hash
stringlengths
40
40
date
stringdate
2020-04-14 18:04:14
2025-03-25 16:48:49
author
stringclasses
154 values
commit_message
stringlengths
15
172
is_merge
bool
1 class
masked_commit_message
stringlengths
11
165
type
stringclasses
7 values
git_diff
stringlengths
32
8.56M
12283892dcf0edf0b8692584650ab24ad35df600
2023-11-20 14:59:48
sharanya-appsmith
test: Cypress - skipping flaky cases in ce (#28959)
false
Cypress - skipping flaky cases in ce (#28959)
test
diff --git a/app/client/cypress/e2e/Regression/ClientSide/Git/GitSync/GitSyncedApps_spec.js b/app/client/cypress/e2e/Regression/ClientSide/Git/GitSync/GitSyncedApps_spec.js index 2451d218f0e3..421dc7640abe 100644 --- a/app/client/cypress/e2e/Regression/ClientSide/Git/GitSync/GitSyncedApps_spec.js +++ b/app/client/cypress/e2e/Regression/ClientSide/Git/GitSync/GitSyncedApps_spec.js @@ -27,7 +27,7 @@ const mainBranch = "master"; let datasourceName; let repoName; -describe("Git sync apps", function () { +describe.skip("Git sync apps", function () { before(() => { // homePage.NavigateToHome(); // cy.createWorkspace(); diff --git a/app/client/cypress/e2e/Regression/ClientSide/Widgets/Modal/Modal_spec.ts b/app/client/cypress/e2e/Regression/ClientSide/Widgets/Modal/Modal_spec.ts index 03c8b6a42b68..f60d2107bdf6 100644 --- a/app/client/cypress/e2e/Regression/ClientSide/Widgets/Modal/Modal_spec.ts +++ b/app/client/cypress/e2e/Regression/ClientSide/Widgets/Modal/Modal_spec.ts @@ -10,7 +10,7 @@ import { table, } from "../../../../../support/Objects/ObjectsCore"; -describe("Modal Widget test cases", function () { +describe.skip("Modal Widget test cases", function () { const image = (src: string) => 'img[src="' + src + '"]'; const jpgImg = "https://jpeg.org/images/jpegsystems-home.jpg"; const gifImg =
2214abc1bf2d93d7df220e91c3179f24b746353a
2023-11-20 09:26:45
Manish Kumar
fix: modified error code for unauthorised trigger and execute calls (#28946)
false
modified error code for unauthorised trigger and execute calls (#28946)
fix
diff --git a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/exceptions/pluginExceptions/AppsmithPluginError.java b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/exceptions/pluginExceptions/AppsmithPluginError.java index 802f01623524..9f5b575b81ef 100644 --- a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/exceptions/pluginExceptions/AppsmithPluginError.java +++ b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/exceptions/pluginExceptions/AppsmithPluginError.java @@ -107,6 +107,15 @@ public enum AppsmithPluginError implements BasePluginError { ErrorType.AUTHENTICATION_ERROR, "{0}", "{1}"), + PLUGIN_DATASOURCE_AUTHENTICATION_ERROR( + 400, + AppsmithPluginErrorCode.PLUGIN_DATASOURCE_AUTHENTICATION_ERROR.getCode(), + "Invalid authentication credentials. Please check datasource configuration.", + AppsmithErrorAction.DEFAULT, + "Datasource authentication error", + ErrorType.DATASOURCE_CONFIGURATION_ERROR, + "{0}", + "{1}"), PLUGIN_DATASOURCE_ERROR( 400, AppsmithPluginErrorCode.PLUGIN_DATASOURCE_ERROR.getCode(), diff --git a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/exceptions/pluginExceptions/AppsmithPluginErrorCode.java b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/exceptions/pluginExceptions/AppsmithPluginErrorCode.java index 7e6465e4ab4a..7e482eefa358 100644 --- a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/exceptions/pluginExceptions/AppsmithPluginErrorCode.java +++ b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/exceptions/pluginExceptions/AppsmithPluginErrorCode.java @@ -17,6 +17,7 @@ public enum AppsmithPluginErrorCode { PLUGIN_DATASOURCE_TIMEOUT_ERROR("PE-DSE-5004", "Timed out when connecting to datasource"), PLUGIN_QUERY_TIMEOUT_ERROR("PE-QRY-5000", "Timed out on query execution"), PLUGIN_AUTHENTICATION_ERROR("PE-ATH-5000", "Datasource authentication error"), + PLUGIN_DATASOURCE_AUTHENTICATION_ERROR("PE-ATH-4000", "Datasource authentication error"), PLUGIN_DATASOURCE_ERROR("PE-DSE-4000", "Datasource error"), PLUGIN_UQI_WHERE_CONDITION_UNKNOWN("PE-UQI-5000", "Where condition could not be parsed"), GENERIC_STALE_CONNECTION("PE-STC-5000", "Secondary stale connection error"), diff --git a/app/server/appsmith-plugins/openAiPlugin/src/main/java/com/external/plugins/OpenAiPlugin.java b/app/server/appsmith-plugins/openAiPlugin/src/main/java/com/external/plugins/OpenAiPlugin.java index 22acc5f477c6..dc181441e41e 100644 --- a/app/server/appsmith-plugins/openAiPlugin/src/main/java/com/external/plugins/OpenAiPlugin.java +++ b/app/server/appsmith-plugins/openAiPlugin/src/main/java/com/external/plugins/OpenAiPlugin.java @@ -111,8 +111,8 @@ public Mono<ActionExecutionResult> executeCommon( if (HttpStatusCode.valueOf(401).isSameCodeAs(statusCode)) { actionExecutionResult.setIsExecutionSuccess(false); - actionExecutionResult.setErrorInfo( - new AppsmithPluginException(AppsmithPluginError.PLUGIN_AUTHENTICATION_ERROR)); + actionExecutionResult.setErrorInfo(new AppsmithPluginException( + AppsmithPluginError.PLUGIN_DATASOURCE_AUTHENTICATION_ERROR)); return Mono.just(actionExecutionResult); } @@ -183,8 +183,8 @@ public Mono<TriggerResultDTO> trigger( return RequestUtils.makeRequest(httpMethod, uri, bearerTokenAuth, BodyInserters.empty()) .flatMap(responseEntity -> { if (responseEntity.getStatusCode().is4xxClientError()) { - return Mono.error( - new AppsmithPluginException(AppsmithPluginError.PLUGIN_AUTHENTICATION_ERROR)); + return Mono.error(new AppsmithPluginException( + AppsmithPluginError.PLUGIN_DATASOURCE_AUTHENTICATION_ERROR)); } if (!responseEntity.getStatusCode().is2xxSuccessful()) { @@ -237,12 +237,13 @@ public Mono<DatasourceTestResult> testDatasource(DatasourceConfiguration datasou } AppsmithPluginException error = - new AppsmithPluginException(AppsmithPluginError.PLUGIN_AUTHENTICATION_ERROR); + new AppsmithPluginException(AppsmithPluginError.PLUGIN_DATASOURCE_AUTHENTICATION_ERROR); return new DatasourceTestResult(error.getMessage()); }) .onErrorResume(error -> { if (!(error instanceof AppsmithPluginException)) { - error = new AppsmithPluginException(AppsmithPluginError.PLUGIN_AUTHENTICATION_ERROR); + error = new AppsmithPluginException( + AppsmithPluginError.PLUGIN_DATASOURCE_AUTHENTICATION_ERROR); } return Mono.just(new DatasourceTestResult(error.getMessage())); });
c8792b1bae39896d10ea50994c783a191b9aa6ae
2023-08-10 19:42:19
NandanAnantharamu
test: cypress - updated tests for Tab (#26210)
false
cypress - updated tests for Tab (#26210)
test
diff --git a/app/client/cypress/e2e/Regression/ClientSide/DynamicHeight/Text_With_Different_Size_spec.ts b/app/client/cypress/e2e/Regression/ClientSide/DynamicHeight/Text_With_Different_Size_spec.ts index c23976e81bd9..93379bb44ecd 100644 --- a/app/client/cypress/e2e/Regression/ClientSide/DynamicHeight/Text_With_Different_Size_spec.ts +++ b/app/client/cypress/e2e/Regression/ClientSide/DynamicHeight/Text_With_Different_Size_spec.ts @@ -8,8 +8,9 @@ import { describe("Dynamic Height Width validation", function () { function validateCssProperties(property) { agHelper.GetNClickByContains("button", "Small", 0, true); - agHelper.Sleep(3000); + agHelper.Sleep(2000); entityExplorer.SelectEntityByName("Text1"); + agHelper.Sleep(2000); agHelper .GetWidgetCSSFrAttribute( locators._widgetInDeployed(draggableWidgets.TEXT), @@ -26,6 +27,7 @@ describe("Dynamic Height Width validation", function () { ) .then((CurrentValueOfSecondText) => { entityExplorer.SelectEntityByName("Text3"); + agHelper.Sleep(2000); agHelper .GetWidgetCSSFrAttribute( locators._widgetInDeployed(draggableWidgets.TEXT), @@ -34,6 +36,7 @@ describe("Dynamic Height Width validation", function () { ) .then((CurrentValueOfThirdText) => { entityExplorer.SelectEntityByName("Text4"); + agHelper.Sleep(2000); agHelper .GetWidgetCSSFrAttribute( locators._widgetInDeployed(draggableWidgets.TEXT), @@ -120,8 +123,9 @@ describe("Dynamic Height Width validation", function () { 0, true, ); - agHelper.Sleep(3000); + agHelper.Sleep(2000); entityExplorer.SelectEntityByName("Text1"); + agHelper.Sleep(2000); agHelper .GetWidgetCSSFrAttribute( locators._widgetInDeployed( @@ -147,6 +151,7 @@ describe("Dynamic Height Width validation", function () { entityExplorer.SelectEntityByName( "Text3", ); + agHelper.Sleep(2000); agHelper .GetWidgetCSSFrAttribute( locators._widgetInDeployed( @@ -162,6 +167,7 @@ describe("Dynamic Height Width validation", function () { entityExplorer.SelectEntityByName( "Text4", ); + agHelper.Sleep(2000); agHelper .GetWidgetCSSFrAttribute( locators._widgetInDeployed( diff --git a/app/client/cypress/e2e/Regression/ClientSide/Widgets/Tab/Tab_spec.js b/app/client/cypress/e2e/Regression/ClientSide/Widgets/Tab/Tab_spec.js index 559dd8538c38..eb2f7a2deaea 100644 --- a/app/client/cypress/e2e/Regression/ClientSide/Widgets/Tab/Tab_spec.js +++ b/app/client/cypress/e2e/Regression/ClientSide/Widgets/Tab/Tab_spec.js @@ -2,11 +2,15 @@ const commonlocators = require("../../../../../locators/commonlocators.json"); const Layoutpage = require("../../../../../locators/Layout.json"); const widgetsPage = require("../../../../../locators/Widgets.json"); const publish = require("../../../../../locators/publishWidgetspage.json"); -import * as _ from "../../../../../support/Objects/ObjectsCore"; +import { + agHelper, + deployMode, + propPane, +} from "../../../../../support/Objects/ObjectsCore"; describe("Tab widget test", function () { before(() => { - _.agHelper.AddDsl("layoutdsl"); + agHelper.AddDsl("layoutdsl"); }); it("1. Tab Widget Functionality Test", function () { cy.openPropertyPane("tabswidget"); @@ -45,7 +49,7 @@ describe("Tab widget test", function () { .scrollIntoView({ easing: "linear" }) .should("be.visible"); cy.assertPageSave(); - _.deployMode.DeployApp(); + deployMode.DeployApp(); }); it("2. Tab Widget Functionality To Select Tabs", function () { @@ -54,23 +58,23 @@ describe("Tab widget test", function () { .last() .click({ force: true }) .should("have.class", "is-selected"); - _.deployMode.NavigateBacktoEditor(); + deployMode.NavigateBacktoEditor(); }); it("3. Tab Widget Functionality To Unchecked Visible Widget", function () { cy.openPropertyPane("tabswidget"); cy.togglebarDisable(commonlocators.visibleCheckbox); - _.deployMode.DeployApp(); + deployMode.DeployApp(); cy.get(publish.tabWidget).should("not.exist"); - _.deployMode.NavigateBacktoEditor(); + deployMode.NavigateBacktoEditor(); }); it("4. Tab Widget Functionality To Check Visible Widget", function () { cy.openPropertyPane("tabswidget"); cy.togglebar(commonlocators.visibleCheckbox); - _.deployMode.DeployApp(); + deployMode.DeployApp(); cy.get(publish.tabWidget).should("be.visible"); - _.deployMode.NavigateBacktoEditor(); + deployMode.NavigateBacktoEditor(); }); it("5. Tab Widget Functionality To Check tab invisiblity", function () { @@ -80,9 +84,9 @@ describe("Tab widget test", function () { }); cy.get(Layoutpage.tabVisibility).first().click({ force: true }); cy.get(Layoutpage.tabWidget).contains("Tab 1").should("not.exist"); - _.deployMode.DeployApp(); + deployMode.DeployApp(); cy.get(publish.tabWidget).contains("Tab 1").should("not.exist"); - _.deployMode.NavigateBacktoEditor(); + deployMode.NavigateBacktoEditor(); }); it("6. Tab Widget Functionality To Check tab visibility", function () { @@ -92,9 +96,9 @@ describe("Tab widget test", function () { }); cy.get(Layoutpage.tabVisibility).first().click({ force: true }); cy.get(Layoutpage.tabWidget).contains("Tab 1").should("be.visible"); - _.deployMode.DeployApp(); + deployMode.DeployApp(); cy.get(publish.tabWidget).contains("Tab 1").should("be.visible"); - _.deployMode.NavigateBacktoEditor(); + deployMode.NavigateBacktoEditor(); }); /* Test to be revisted as the undo action is inconsistent in automation it("7. Tab Widget Functionality To Check undo action after delete", function() { @@ -115,7 +119,7 @@ describe("Tab widget test", function () { cy.get(Layoutpage.tabWidget) .contains("Tab 1") .should("be.visible"); - _.deployMode.DeployApp(); + deployMode.DeployApp(); cy.get(publish.tabWidget) .contains("Tab 1") .should("be.visible"); @@ -129,8 +133,8 @@ describe("Tab widget test", function () { cy.openPropertyPane("tabswidget"); // Add a new tab - cy.get(Layoutpage.tabButton).last().click({ force: true }); - cy.get(Layoutpage.tabButton).last().click({ force: true }); + agHelper.ClickButton("Add tab"); + agHelper.ClickButton("Add tab"); cy.tabVerify(3, "Tab3-for-testing-scroll-navigation-controls"); // Should show off right navigation arrow cy.get(leftNavButtonSelector).should("exist"); @@ -141,7 +145,7 @@ describe("Tab widget test", function () { }); it("8. Tab Widget Functionality To Check Default Tab selected After Selected Tab Delete", function () { - cy.testJsontext("defaulttab", "Tab 2"); + propPane.UpdatePropertyFieldValue("Default tab", "Tab 1"); cy.tabVerify(3, "Tab3-for-testing-scroll-navigation-controls"); cy.get(Layoutpage.tabWidget) .contains("Tab3-for-testing-scroll-navigation-controls") @@ -153,19 +157,20 @@ describe("Tab widget test", function () { ), ).click({ force: true }); cy.get(Layoutpage.tabWidget) - .contains("Tab 2") + .contains("Tab 1") .should("have.class", "is-selected"); }); it("9. Tab Widget Functionality To Check First Tab Selected After Selected Tab(Default one) Delete", function () { - cy.get(Layoutpage.tabDelete).eq(2).click({ force: true }); + cy.get(Layoutpage.tabDelete).eq(1).click({ force: true }); + cy.wait(1000); cy.get(Layoutpage.tabWidget) .contains("Aditya") .should("have.class", "is-selected"); // Validates Total Number Of Tabs Displayed In The Property Pane cy.get(Layoutpage.tabNumber).should("have.text", "2"); // Validates Total Number Of Tabs Displayed In The Property Pane After Adding A Tab - cy.get(Layoutpage.tabButton).last().click({ force: true }); + agHelper.ClickButton("Add tab"); cy.get(Layoutpage.tabNumber).should("have.text", "3"); //Validates Total Number Of Tabs Displayed In The Property Pane After Deleting A Tab cy.get(Layoutpage.tabDelete).eq(1).click({ force: true });
6ea32b1d8d67f2d9db35d6be5f0e3bbdbe02a29e
2023-06-02 18:08:50
tkAppsmith
fix: added gitsyncid assignment to DataSource constructor with dataSourceS… (#23912)
false
added gitsyncid assignment to DataSource constructor with dataSourceS… (#23912)
fix
diff --git a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/ActionDTO.java b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/ActionDTO.java index 7ad24f140a06..a4e824b57452 100644 --- a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/ActionDTO.java +++ b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/ActionDTO.java @@ -192,6 +192,7 @@ public void sanitiseToExportDBObject() { this.setCacheResponse(null); if (this.getDatasource() != null) { this.getDatasource().setCreatedAt(null); + this.getDatasource().setDatasourceStorages(null); } if (this.getUserPermissions() != null) { this.getUserPermissions().clear(); diff --git a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/Datasource.java b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/Datasource.java index 7366e0f4e59a..30a89648a314 100644 --- a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/Datasource.java +++ b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/Datasource.java @@ -124,6 +124,7 @@ public Datasource(DatasourceStorage datasourceStorage) { this.isRecentlyCreated = datasourceStorage.getIsRecentlyCreated(); this.isTemplate = datasourceStorage.getIsTemplate(); this.isMock = datasourceStorage.getIsMock(); + this.gitSyncId = datasourceStorage.getGitSyncId(); HashMap<String, DatasourceStorageDTO> storages = new HashMap<>(); this.datasourceStorages = storages; diff --git a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/DatasourceStorage.java b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/DatasourceStorage.java index deb092e34f04..05f9678bfe3a 100644 --- a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/DatasourceStorage.java +++ b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/DatasourceStorage.java @@ -42,6 +42,12 @@ public class DatasourceStorage extends BaseDomain { @JsonView(Views.Public.class) Set<String> invalids = new HashSet<>(); + @Transient + String name; + + @Transient + String pluginId; + /* * - To return useful hints to the user. * - These messages are generated by the API server based on the other datasource attributes. @@ -51,12 +57,6 @@ public class DatasourceStorage extends BaseDomain { @JsonView(Views.Public.class) Set<String> messages = new HashSet<>(); - @Transient - String name; - - @Transient - String pluginId; - @Transient String pluginName; @@ -162,5 +162,6 @@ public void sanitiseToExportResource(Map<String, String> pluginMap) { this.setId(null); this.setWorkspaceId(null); this.setPluginId(pluginMap.get(this.getPluginId())); + this.setIsRecentlyCreated(null); } }
ce787752777575a22cbebd2cf5fbaf962d6afec5
2023-08-16 18:28:45
Anagh Hegde
chore: Analytics file lock stale time (#26276)
false
Analytics file lock stale time (#26276)
chore
diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/constants/ce/FieldNameCE.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/constants/ce/FieldNameCE.java index 1099acd76bd1..6292e0b310b4 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/constants/ce/FieldNameCE.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/constants/ce/FieldNameCE.java @@ -185,4 +185,6 @@ public class FieldNameCE { public static final String GIT_HOSTING_PROVIDER = "gitHostingProvider"; public static final String IS_MERGEABLE = "isMergeable"; + + public static final String FILE_LOCK_DURATION = "fileLockDuration"; } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/exceptions/GlobalExceptionHandler.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/exceptions/GlobalExceptionHandler.java index 832144592ca1..d0b79fbbafda 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/exceptions/GlobalExceptionHandler.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/exceptions/GlobalExceptionHandler.java @@ -339,6 +339,7 @@ private Mono<Boolean> deleteLockFileAndSendAnalytics(File file, String urlPath) analyticsProps.put(FieldName.APPLICATION_ID, appId); } if (!fileTime.equals(0L)) { + analyticsProps.put(FieldName.FILE_LOCK_DURATION, fileTime); return sessionUserService .getCurrentUser() .flatMap(user -> analyticsService.sendEvent( diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/GitServiceCEImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/GitServiceCEImpl.java index b883fa8c65f3..de5573640f84 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/GitServiceCEImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/GitServiceCEImpl.java @@ -2236,7 +2236,7 @@ public Mono<MergeStatusDTO> isBranchMergeable(String defaultApplicationId, GitMe .getGitApplicationMetadata() .getIsRepoPrivate(), false, - true)) + mergeStatusDTO.isMergeAble())) .then(Mono.just(mergeStatusDTO)))) .onErrorResume(error -> { try {
f7e69f59848adf73fb85bf7634785858c7ba8faf
2022-09-13 13:14:06
Trisha Anand
chore: Added username to error logs when signup is disabled (#16720)
false
Added username to error logs when signup is disabled (#16720)
chore
diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/exceptions/AppsmithError.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/exceptions/AppsmithError.java index 975b9b064d27..78d679ccc07a 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/exceptions/AppsmithError.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/exceptions/AppsmithError.java @@ -111,7 +111,7 @@ public enum AppsmithError { MARKETPLACE_NOT_CONFIGURED(500, 5007, "Marketplace is not configured.", AppsmithErrorAction.DEFAULT, null, ErrorType.CONFIGURATION_ERROR, null), PAYLOAD_TOO_LARGE(413, 4028, "The request payload is too large. Max allowed size for request payload is {0} KB", AppsmithErrorAction.DEFAULT, null, ErrorType.CONNECTIVITY_ERROR, null), - SIGNUP_DISABLED(403, 4033, "Signup is restricted on this instance of Appsmith. Please contact the administrator to get an invite.", + SIGNUP_DISABLED(403, 4033, "Signup is restricted on this instance of Appsmith. Please contact the administrator to get an invite for user {0}.", AppsmithErrorAction.DEFAULT, null, ErrorType.INTERNAL_ERROR, null), FAIL_UPDATE_USER_IN_SESSION(500, 5008, "Unable to update user in session.", AppsmithErrorAction.LOG_EXTERNALLY, null, ErrorType.INTERNAL_ERROR, null), APPLICATION_FORKING_NOT_ALLOWED(403, 4034, "Forking this application is not permitted at this time.", AppsmithErrorAction.DEFAULT, null, ErrorType.INTERNAL_ERROR, null), diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/UserServiceCEImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/UserServiceCEImpl.java index 7aa65d24d906..c8c2cf014ccb 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/UserServiceCEImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/UserServiceCEImpl.java @@ -534,7 +534,7 @@ private Mono<User> signupIfAllowed(User user) { if (commonConfig.isSignupDisabled()) { // Signing up has been globally disabled. Reject. - return Mono.error(new AppsmithException(AppsmithError.SIGNUP_DISABLED)); + return Mono.error(new AppsmithException(AppsmithError.SIGNUP_DISABLED, user.getUsername())); } final List<String> allowedDomains = user.getSource() == LoginSource.FORM @@ -546,7 +546,7 @@ private Mono<User> signupIfAllowed(User user) { && !allowedDomains.contains(user.getEmail().split("@")[1])) { // There is an explicit whitelist of email address domains that should be allowed. If the new email is // of a different domain, reject. - return Mono.error(new AppsmithException(AppsmithError.SIGNUP_DISABLED)); + return Mono.error(new AppsmithException(AppsmithError.SIGNUP_DISABLED, user.getUsername())); } } else { isAdminUser = true;
efc704b94ea818fe603afedc51b7942db8f88785
2023-10-06 15:05:08
NandanAnantharamu
test: fix for tabs2 spec (#27854)
false
fix for tabs2 spec (#27854)
test
diff --git a/app/client/cypress/e2e/Regression/ClientSide/Widgets/Tab/Tabs_2_spec.ts b/app/client/cypress/e2e/Regression/ClientSide/Widgets/Tab/Tabs_2_spec.ts index e6f7360f30aa..eeca97b3f6dd 100644 --- a/app/client/cypress/e2e/Regression/ClientSide/Widgets/Tab/Tabs_2_spec.ts +++ b/app/client/cypress/e2e/Regression/ClientSide/Widgets/Tab/Tabs_2_spec.ts @@ -6,6 +6,7 @@ import { propPane, table, tabs, + assertHelper, } from "../../../../../support/Objects/ObjectsCore"; describe("Tabs widget Tests", function () { @@ -205,6 +206,7 @@ describe("Tabs widget Tests", function () { // Border Color propPane.SelectColorFromColorPicker("bordercolor", 13); + assertHelper.AssertNetworkStatus("@updateLayout"); agHelper.AssertCSS( tabs._tabsWidgetStyle, "border-color", @@ -221,6 +223,7 @@ describe("Tabs widget Tests", function () { // Verify Box Shadow agHelper.GetNClick(`${propPane._segmentedControl("0")}:contains('Large')`); + assertHelper.AssertNetworkStatus("@updateLayout"); agHelper.AssertCSS( tabs._tabsWidgetStyle, "box-shadow",
cc36ae70bbd5104d927f107cd5cd50c4182fc1e3
2022-07-04 14:33:31
Bhavin K
fix: revert checkbox-group widget breaking UI issue (#14933)
false
revert checkbox-group widget breaking UI issue (#14933)
fix
diff --git a/app/client/src/widgets/CheckboxGroupWidget/component/index.tsx b/app/client/src/widgets/CheckboxGroupWidget/component/index.tsx index a3657b984eb3..2830f891b327 100644 --- a/app/client/src/widgets/CheckboxGroupWidget/component/index.tsx +++ b/app/client/src/widgets/CheckboxGroupWidget/component/index.tsx @@ -69,15 +69,6 @@ export interface CheckboxGroupContainerProps { export const CheckboxGroupContainer = styled.div<CheckboxGroupContainerProps>` ${labelLayoutStyles} - justify-content: ${({ compactMode, labelPosition }) => { - if ( - labelPosition && - labelPosition !== LabelPosition.Left && - !compactMode - ) { - return "flex-start"; - } - }}; & .${LABEL_CONTAINER_CLASS} { ${({ labelPosition }) => labelPosition === LabelPosition.Left && "min-height: 30px"}; diff --git a/app/client/src/widgets/CheckboxGroupWidget/widget/index.tsx b/app/client/src/widgets/CheckboxGroupWidget/widget/index.tsx index ae5024495d63..4451cb6b8cad 100644 --- a/app/client/src/widgets/CheckboxGroupWidget/widget/index.tsx +++ b/app/client/src/widgets/CheckboxGroupWidget/widget/index.tsx @@ -165,29 +165,9 @@ class CheckboxGroupWidget extends BaseWidget< isJSConvertible: true, isBindProperty: true, isTriggerProperty: false, - updateHook: ( - props: CheckboxGroupWidgetProps, - propertyPath: string, - propertyValue: string, - ) => { - const propertiesToUpdate = [{ propertyPath, propertyValue }]; - const isOffInline = - typeof propertyValue === "string" - ? !(propertyValue === "true") - : !propertyValue; - - if (isOffInline) { - propertiesToUpdate.push({ - propertyPath: "optionAlignment", - propertyValue: CheckboxGroupAlignmentTypes.NONE, - }); - } - return propertiesToUpdate; - }, validation: { type: ValidationTypes.BOOLEAN, }, - dependencies: ["isInline"], }, { propertyName: "isSelectAll", @@ -335,12 +315,6 @@ class CheckboxGroupWidget extends BaseWidget< ], }, }, - hidden: (props: CheckboxGroupWidgetProps) => { - return typeof props.isInline === "string" - ? !(props.isInline === "true") - : !props.isInline; - }, - dependencies: ["isInline"], }, { propertyName: "labelTextColor",
1688757bc634dbf76eae30bb68300fec09ed382d
2022-03-04 11:56:12
Ankita Kinger
fix: Signup text update & code optimisation (#11606)
false
Signup text update & code optimisation (#11606)
fix
diff --git a/app/client/jest.config.js b/app/client/jest.config.js index bae9af532c91..478bea0b291f 100644 --- a/app/client/jest.config.js +++ b/app/client/jest.config.js @@ -44,6 +44,7 @@ module.exports = { enableGithubOAuth: parseConfig("__APPSMITH_OAUTH2_GITHUB_CLIENT_ID__"), disableLoginForm: parseConfig("__APPSMITH_FORM_LOGIN_DISABLED__"), disableSignup: parseConfig("__APPSMITH_SIGNUP_DISABLED__"), + disableTelemetry: parseConfig("__APPSMITH_DISABLE_TELEMETRY__"), enableRapidAPI: parseConfig("__APPSMITH_MARKETPLACE_ENABLED__"), segment: { apiKey: parseConfig("__APPSMITH_SEGMENT_KEY__"), diff --git a/app/client/public/index.html b/app/client/public/index.html index 3cedce33ae4f..0fd4b0143470 100755 --- a/app/client/public/index.html +++ b/app/client/public/index.html @@ -195,6 +195,7 @@ enableGithubOAuth: parseConfig("__APPSMITH_OAUTH2_GITHUB_CLIENT_ID__"), disableLoginForm: parseConfig("__APPSMITH_FORM_LOGIN_DISABLED__"), disableSignup: parseConfig("__APPSMITH_SIGNUP_DISABLED__"), + disableTelemetry: parseConfig("__APPSMITH_DISABLE_TELEMETRY__"), enableRapidAPI: parseConfig("__APPSMITH_MARKETPLACE_ENABLED__"), segment: { apiKey: parseConfig("__APPSMITH_SEGMENT_KEY__"), diff --git a/app/client/src/ce/configs/index.ts b/app/client/src/ce/configs/index.ts index 5200a0d2699b..8a6750bab9ae 100644 --- a/app/client/src/ce/configs/index.ts +++ b/app/client/src/ce/configs/index.ts @@ -17,6 +17,7 @@ export interface INJECTED_CONFIGS { enableGithubOAuth: boolean; disableLoginForm: boolean; disableSignup: boolean; + disableTelemetry: boolean; enableRapidAPI: boolean; segment: { apiKey: string; @@ -77,6 +78,9 @@ export const getConfigsFromEnvVars = (): INJECTED_CONFIGS => { disableSignup: process.env.APPSMITH_SIGNUP_DISABLED ? process.env.APPSMITH_SIGNUP_DISABLED.length > 0 : false, + disableTelemetry: process.env.APPSMITH_DISABLE_TELEMETRY + ? process.env.APPSMITH_DISABLE_TELEMETRY.length > 0 + : true, segment: { apiKey: process.env.REACT_APP_SEGMENT_KEY || "", ceKey: process.env.REACT_APP_SEGMENT_CE_KEY || "", @@ -246,6 +250,8 @@ export const getAppsmithConfigs = (): AppsmithUIConfigs => { ENV_CONFIG.disableLoginForm || APPSMITH_FEATURE_CONFIGS.disableLoginForm, disableSignup: ENV_CONFIG.disableSignup || APPSMITH_FEATURE_CONFIGS.disableSignup, + disableTelemetry: + ENV_CONFIG.disableTelemetry || APPSMITH_FEATURE_CONFIGS.disableTelemetry, enableGoogleOAuth: ENV_CONFIG.enableGoogleOAuth || APPSMITH_FEATURE_CONFIGS.enableGoogleOAuth, diff --git a/app/client/src/ce/configs/types.ts b/app/client/src/ce/configs/types.ts index 51bf7e7c6a31..7eac1a47da30 100644 --- a/app/client/src/ce/configs/types.ts +++ b/app/client/src/ce/configs/types.ts @@ -46,6 +46,7 @@ export interface AppsmithUIConfigs { enableGithubOAuth: boolean; disableLoginForm: boolean; disableSignup: boolean; + disableTelemetry: boolean; enableMixpanel: boolean; enableTNCPP: boolean; diff --git a/app/client/src/ce/pages/AdminSettings/config/authentication/index.tsx b/app/client/src/ce/pages/AdminSettings/config/authentication/index.tsx index 951d865820a7..19c3d897a11b 100644 --- a/app/client/src/ce/pages/AdminSettings/config/authentication/index.tsx +++ b/app/client/src/ce/pages/AdminSettings/config/authentication/index.tsx @@ -6,6 +6,7 @@ import { } from "constants/ThirdPartyConstants"; import { SettingCategories, + SettingSubCategories, SettingTypes, SettingSubtype, AdminConfigType, @@ -34,7 +35,7 @@ const Form_Auth: AdminConfigType = { { id: "APPSMITH_FORM_LOGIN_DISABLED", category: SettingCategories.FORM_AUTH, - subCategory: "form login", + subCategory: SettingSubCategories.FORMLOGIN, controlType: SettingTypes.TOGGLE, label: "Form Login Option", toggleText: (value: boolean) => { @@ -48,12 +49,12 @@ const Form_Auth: AdminConfigType = { { id: "APPSMITH_SIGNUP_DISABLED", category: SettingCategories.FORM_AUTH, - subCategory: "form signup", + subCategory: SettingSubCategories.FORMLOGIN, controlType: SettingTypes.TOGGLE, label: "Signup", toggleText: (value: boolean) => { if (value) { - return "Allow only invited users to signup"; + return "Restrict Signups"; } else { return " Allow all users to signup"; } @@ -62,7 +63,7 @@ const Form_Auth: AdminConfigType = { { id: "APPSMITH_FORM_CALLOUT_BANNER", category: SettingCategories.FORM_AUTH, - subCategory: "form signup", + subCategory: SettingSubCategories.FORMLOGIN, controlType: SettingTypes.LINK, label: "User emails are not verified. This can lead to a breach in your application.", @@ -83,7 +84,7 @@ const Google_Auth: AdminConfigType = { { id: "APPSMITH_OAUTH2_GOOGLE_READ_MORE", category: SettingCategories.GOOGLE_AUTH, - subCategory: "google signup", + subCategory: SettingSubCategories.GOOGLE, controlType: SettingTypes.LINK, label: "How to configure?", url: GOOGLE_SIGNUP_SETUP_DOC, @@ -91,7 +92,7 @@ const Google_Auth: AdminConfigType = { { id: "APPSMITH_OAUTH2_GOOGLE_CLIENT_ID", category: SettingCategories.GOOGLE_AUTH, - subCategory: "google signup", + subCategory: SettingSubCategories.GOOGLE, controlType: SettingTypes.TEXTINPUT, controlSubType: SettingSubtype.TEXT, label: "Client ID", @@ -99,7 +100,7 @@ const Google_Auth: AdminConfigType = { { id: "APPSMITH_OAUTH2_GOOGLE_CLIENT_SECRET", category: SettingCategories.GOOGLE_AUTH, - subCategory: "google signup", + subCategory: SettingSubCategories.GOOGLE, controlType: SettingTypes.TEXTINPUT, controlSubType: SettingSubtype.TEXT, label: "Client Secret", @@ -107,7 +108,7 @@ const Google_Auth: AdminConfigType = { { id: "APPSMITH_SIGNUP_ALLOWED_DOMAINS", category: SettingCategories.GOOGLE_AUTH, - subCategory: "google signup", + subCategory: SettingSubCategories.GOOGLE, controlType: SettingTypes.TEXTINPUT, controlSubType: SettingSubtype.TEXT, label: "Allowed Domains", @@ -128,7 +129,7 @@ const Github_Auth: AdminConfigType = { { id: "APPSMITH_OAUTH2_GITHUB_READ_MORE", category: SettingCategories.GITHUB_AUTH, - subCategory: "github signup", + subCategory: SettingSubCategories.GITHUB, controlType: SettingTypes.LINK, label: "How to configure?", url: GITHUB_SIGNUP_SETUP_DOC, @@ -136,7 +137,7 @@ const Github_Auth: AdminConfigType = { { id: "APPSMITH_OAUTH2_GITHUB_CLIENT_ID", category: SettingCategories.GITHUB_AUTH, - subCategory: "github signup", + subCategory: SettingSubCategories.GITHUB, controlType: SettingTypes.TEXTINPUT, controlSubType: SettingSubtype.TEXT, label: "Client ID", @@ -144,7 +145,7 @@ const Github_Auth: AdminConfigType = { { id: "APPSMITH_OAUTH2_GITHUB_CLIENT_SECRET", category: SettingCategories.GITHUB_AUTH, - subCategory: "github signup", + subCategory: SettingSubCategories.GITHUB, controlType: SettingTypes.TEXTINPUT, controlSubType: SettingSubtype.TEXT, label: "Client Secret", diff --git a/app/client/src/ce/pages/AdminSettings/config/types.ts b/app/client/src/ce/pages/AdminSettings/config/types.ts index 859a8776ab84..869a5663d3e3 100644 --- a/app/client/src/ce/pages/AdminSettings/config/types.ts +++ b/app/client/src/ce/pages/AdminSettings/config/types.ts @@ -71,6 +71,12 @@ export const SettingCategories = { GITHUB_AUTH: "github-auth", }; +export const SettingSubCategories = { + GOOGLE: "google signup", + GITHUB: "github signup", + FORMLOGIN: "form login", +}; + export type AdminConfigType = { type: string; controlType: SettingTypes; diff --git a/app/client/src/ce/utils/adminSettingsHelpers.ts b/app/client/src/ce/utils/adminSettingsHelpers.ts index 6a83b7000b43..04b97c286270 100644 --- a/app/client/src/ce/utils/adminSettingsHelpers.ts +++ b/app/client/src/ce/utils/adminSettingsHelpers.ts @@ -11,18 +11,21 @@ export const connectedMethods = [ !disableLoginForm, ].filter(Boolean); +/* settings is the updated & unsaved settings on Admin settings page */ export const saveAllowed = (settings: any) => { - if ( - connectedMethods.length >= 2 || - (connectedMethods.length === 1 && - ((!("APPSMITH_FORM_LOGIN_DISABLED" in settings) && !disableLoginForm) || - (settings["APPSMITH_OAUTH2_GOOGLE_CLIENT_ID"] !== "" && - enableGoogleOAuth) || - (settings["APPSMITH_OAUTH2_GITHUB_CLIENT_ID"] !== "" && - enableGithubOAuth))) - ) { - return true; + if (connectedMethods.length === 1) { + const checkFormLogin = !( + "APPSMITH_FORM_LOGIN_DISABLED" in settings || disableLoginForm + ), + checkGoogleAuth = + settings["APPSMITH_OAUTH2_GOOGLE_CLIENT_ID"] !== "" && + enableGoogleOAuth, + checkGithubAuth = + settings["APPSMITH_OAUTH2_GITHUB_CLIENT_ID"] !== "" && + enableGithubOAuth; + + return checkFormLogin || checkGoogleAuth || checkGithubAuth; } else { - return false; + return connectedMethods.length >= 2; } }; diff --git a/app/client/src/pages/Settings/FormGroup/TextInput.tsx b/app/client/src/pages/Settings/FormGroup/TextInput.tsx index ae37172c6cce..4dfce25bc22b 100644 --- a/app/client/src/pages/Settings/FormGroup/TextInput.tsx +++ b/app/client/src/pages/Settings/FormGroup/TextInput.tsx @@ -6,7 +6,8 @@ import { FormGroup, SettingComponentProps } from "./Common"; export default function TextInput({ setting }: SettingComponentProps) { return ( <FormGroup - className={`t--admin-settings-text-input t--admin-settings-${setting.name}`} + className={`t--admin-settings-text-input t--admin-settings-${setting.name || + setting.id}`} setting={setting} > <FormTextField diff --git a/app/client/src/pages/Settings/SettingsForm.tsx b/app/client/src/pages/Settings/SettingsForm.tsx index 1fa91b547ed2..0feca1feaf63 100644 --- a/app/client/src/pages/Settings/SettingsForm.tsx +++ b/app/client/src/pages/Settings/SettingsForm.tsx @@ -193,9 +193,9 @@ export function SettingsForm( const validate = (values: Record<string, any>) => { const errors: any = {}; _.filter(values, (value, name) => { - const message = AdminConfig.validate(name, value); - if (message) { - errors[name] = message; + const err_message = AdminConfig.validate(name, value); + if (err_message) { + errors[name] = err_message; } }); return errors; diff --git a/app/client/src/pages/Settings/config/advanced.ts b/app/client/src/pages/Settings/config/advanced.ts index 323c424785f6..907a1cac0169 100644 --- a/app/client/src/pages/Settings/config/advanced.ts +++ b/app/client/src/pages/Settings/config/advanced.ts @@ -12,7 +12,7 @@ export const config: AdminConfigType = { settings: [ { id: "APPSMITH_MONGODB_URI", - category: "advanced", + category: SettingCategories.ADVANCED, controlType: SettingTypes.TEXTINPUT, controlSubType: SettingSubtype.TEXT, label: "MongoDB URI", @@ -21,7 +21,7 @@ export const config: AdminConfigType = { }, { id: "APPSMITH_REDIS_URL", - category: "advanced", + category: SettingCategories.ADVANCED, controlType: SettingTypes.TEXTINPUT, controlSubType: SettingSubtype.TEXT, label: "Redis URL", @@ -30,7 +30,7 @@ export const config: AdminConfigType = { }, { id: "APPSMITH_CUSTOM_DOMAIN", - category: "advanced", + category: SettingCategories.ADVANCED, controlType: SettingTypes.TEXTINPUT, controlSubType: SettingSubtype.TEXT, label: "Custom Domain", diff --git a/app/client/src/pages/Settings/config/email.ts b/app/client/src/pages/Settings/config/email.ts index ff638f4028e1..aa4b37fb3ecc 100644 --- a/app/client/src/pages/Settings/config/email.ts +++ b/app/client/src/pages/Settings/config/email.ts @@ -21,14 +21,14 @@ export const config: AdminConfigType = { settings: [ { id: "APPSMITH_MAIL_READ_MORE", - category: "email", + category: SettingCategories.EMAIL, controlType: SettingTypes.LINK, label: "How to configure?", url: EMAIL_SETUP_DOC, }, { id: "APPSMITH_MAIL_HOST", - category: "email", + category: SettingCategories.EMAIL, controlType: SettingTypes.TEXTINPUT, controlSubType: SettingSubtype.TEXT, label: "SMTP Host", @@ -36,7 +36,7 @@ export const config: AdminConfigType = { }, { id: "APPSMITH_MAIL_PORT", - category: "email", + category: SettingCategories.EMAIL, controlType: SettingTypes.TEXTINPUT, controlSubType: SettingSubtype.NUMBER, placeholder: "25", @@ -50,7 +50,7 @@ export const config: AdminConfigType = { }, { id: "APPSMITH_MAIL_FROM", - category: "email", + category: SettingCategories.EMAIL, controlType: SettingTypes.TEXTINPUT, controlSubType: SettingSubtype.TEXT, label: "From Address", @@ -65,13 +65,13 @@ export const config: AdminConfigType = { }, { id: "APPSMITH_MAIL_SMTP_TLS_ENABLED", - category: "email", + category: SettingCategories.EMAIL, controlType: SettingTypes.TOGGLE, label: "TLS Protected Connection", }, { id: "APPSMITH_MAIL_USERNAME", - category: "email", + category: SettingCategories.EMAIL, controlType: SettingTypes.TEXTINPUT, controlSubType: SettingSubtype.TEXT, label: "SMTP Username", @@ -81,7 +81,7 @@ export const config: AdminConfigType = { }, { id: "APPSMITH_MAIL_PASSWORD", - category: "email", + category: SettingCategories.EMAIL, controlType: SettingTypes.TEXTINPUT, controlSubType: SettingSubtype.PASSWORD, label: "SMTP Password", @@ -91,7 +91,7 @@ export const config: AdminConfigType = { }, { id: "APPSMITH_MAIL_TEST_EMAIL", - category: "email", + category: SettingCategories.EMAIL, action: (dispatch: Dispatch<ReduxAction<any>>, settings: any = {}) => { dispatch && dispatch({ diff --git a/app/client/src/pages/Settings/config/general.ts b/app/client/src/pages/Settings/config/general.ts index 6138fe1ed1de..15c2053cb85d 100644 --- a/app/client/src/pages/Settings/config/general.ts +++ b/app/client/src/pages/Settings/config/general.ts @@ -16,7 +16,7 @@ export const config: AdminConfigType = { settings: [ { id: "APPSMITH_INSTANCE_NAME", - category: "general", + category: SettingCategories.GENERAL, controlType: SettingTypes.TEXTINPUT, controlSubType: SettingSubtype.TEXT, label: "Instance Name", @@ -24,7 +24,7 @@ export const config: AdminConfigType = { }, { id: "APPSMITH_ADMIN_EMAILS", - category: "general", + category: SettingCategories.GENERAL, controlType: SettingTypes.TEXTINPUT, controlSubType: SettingSubtype.EMAIL, label: "Admin Email", @@ -51,14 +51,14 @@ export const config: AdminConfigType = { "_blank", ); }, - category: "general", + category: SettingCategories.GENERAL, controlType: SettingTypes.BUTTON, label: "Generated Docker Compose File", text: "Download", }, { id: "APPSMITH_DISABLE_TELEMETRY", - category: "general", + category: SettingCategories.GENERAL, controlType: SettingTypes.TOGGLE, label: "Disable Sharing Anonymous Usage Data", subText: "Share anonymous usage data to help improve the product", @@ -66,7 +66,7 @@ export const config: AdminConfigType = { if (value) { return "Don't share any data"; } else { - return "Share data & make appsmith better!"; + return "Share Anonymous Telemetry"; } }, }, diff --git a/app/client/src/pages/Settings/config/googleMaps.ts b/app/client/src/pages/Settings/config/googleMaps.ts index 365bd5b5322a..8601ece8b3ec 100644 --- a/app/client/src/pages/Settings/config/googleMaps.ts +++ b/app/client/src/pages/Settings/config/googleMaps.ts @@ -14,14 +14,14 @@ export const config: AdminConfigType = { settings: [ { id: "APPSMITH_GOOGLE_MAPS_READ_MORE", - category: "google-maps", + category: SettingCategories.GOOGLE_MAPS, controlType: SettingTypes.LINK, label: "How to configure?", url: GOOGLE_MAPS_SETUP_DOC, }, { id: "APPSMITH_GOOGLE_MAPS_API_KEY", - category: "google-maps", + category: SettingCategories.GOOGLE_MAPS, controlType: SettingTypes.TEXTINPUT, controlSubType: SettingSubtype.TEXT, label: "Google Maps API Key", diff --git a/app/client/src/pages/Settings/config/version.ts b/app/client/src/pages/Settings/config/version.ts index 36d84ec6f0cb..6abe20c91cf9 100644 --- a/app/client/src/pages/Settings/config/version.ts +++ b/app/client/src/pages/Settings/config/version.ts @@ -14,7 +14,7 @@ export const config: AdminConfigType = { settings: [ { id: "APPSMITH_CURRENT_VERSION", - category: "version", + category: SettingCategories.VERSION, controlType: SettingTypes.TEXT, label: "Current version", }, @@ -27,7 +27,7 @@ export const config: AdminConfigType = { payload: true, }); }, - category: "version", + category: SettingCategories.VERSION, controlType: SettingTypes.LINK, label: "Release Notes", }, diff --git a/app/client/src/sagas/SuperUserSagas.tsx b/app/client/src/sagas/SuperUserSagas.tsx index 9239a0f89b4f..29a00fb414b6 100644 --- a/app/client/src/sagas/SuperUserSagas.tsx +++ b/app/client/src/sagas/SuperUserSagas.tsx @@ -133,7 +133,7 @@ function* SendTestEmail(action: ReduxAction<SendTestEmailPayload>) { }); } catch (e) { Toaster.show({ - text: createMessage(TEST_EMAIL_FAILURE), + text: e?.message || createMessage(TEST_EMAIL_FAILURE), hideProgressBar: true, variant: Variant.danger, });
396922e260d804f3ba0ae538b7bb94b3198d40ef
2022-07-01 16:53:34
Pawan Kumar
fix: Updates border radius and box shadow labels in widgets (#14948)
false
Updates border radius and box shadow labels in widgets (#14948)
fix
diff --git a/app/client/src/constants/ThemeConstants.tsx b/app/client/src/constants/ThemeConstants.tsx index c02fa4862bb0..3980e6578afe 100644 --- a/app/client/src/constants/ThemeConstants.tsx +++ b/app/client/src/constants/ThemeConstants.tsx @@ -122,8 +122,8 @@ export const borderRadiusPropertyName = "borderRadius"; */ export const borderRadiusOptions: Record<string, string> = { none: "0px", - md: "0.375rem", - lg: "1.5rem", + M: "0.375rem", + L: "1.5rem", }; export const boxShadowPropertyName = "boxShadow"; @@ -133,9 +133,9 @@ export const boxShadowPropertyName = "boxShadow"; */ export const boxShadowOptions: Record<string, string> = { none: "none", - sm: "0 1px 3px 0 rgba(0, 0, 0, 0.1), 0 1px 2px 0 rgba(0, 0, 0, 0.06)", - md: "0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06)", - lg: "0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -2px rgba(0, 0, 0, 0.05)", + S: "0 1px 3px 0 rgba(0, 0, 0, 0.1), 0 1px 2px 0 rgba(0, 0, 0, 0.06)", + M: "0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06)", + L: "0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -2px rgba(0, 0, 0, 0.05)", }; export const colorsPropertyName = "colors";
bb55029f42f548efcda3c1d931ca9aac79199bd8
2020-08-24 16:20:50
Abhinav Jha
fix: Missing form button (#397)
false
Missing form button (#397)
fix
diff --git a/app/client/src/icons/WidgetIcons.tsx b/app/client/src/icons/WidgetIcons.tsx index 41e31c193c30..e4c85b4f7114 100644 --- a/app/client/src/icons/WidgetIcons.tsx +++ b/app/client/src/icons/WidgetIcons.tsx @@ -125,6 +125,11 @@ export const WidgetIcons: { <ModalIcon /> </IconWrapper> ), + FORM_BUTTON_WIDGET: (props: IconProps) => ( + <IconWrapper {...props}> + <ButtonIcon /> + </IconWrapper> + ), }; export type WidgetIcon = typeof WidgetIcons[keyof typeof WidgetIcons];
d06477afafcd53af251ccd1b4c2c8d7ed3e59dbb
2024-08-02 12:22:03
Nidhi
fix: Do not return composed action collections after refactor (#35350)
false
Do not return composed action collections after refactor (#35350)
fix
diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/actioncollections/base/ActionCollectionServiceCE.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/actioncollections/base/ActionCollectionServiceCE.java index b048168c81b3..7f44a12aea7b 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/actioncollections/base/ActionCollectionServiceCE.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/actioncollections/base/ActionCollectionServiceCE.java @@ -40,7 +40,8 @@ Mono<ActionCollectionDTO> populateActionCollectionByViewMode( Mono<ActionCollectionDTO> splitValidActionsByViewMode( ActionCollectionDTO actionCollectionDTO, List<ActionDTO> actionsList, Boolean viewMode); - Flux<ActionCollectionDTO> getActionCollectionsByViewMode(MultiValueMap<String, String> params, Boolean viewMode); + Flux<ActionCollectionDTO> getNonComposedActionCollectionsByViewMode( + MultiValueMap<String, String> params, Boolean viewMode); Mono<ActionCollectionDTO> update(String id, ActionCollectionDTO actionCollectionDTO); diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/actioncollections/base/ActionCollectionServiceCEImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/actioncollections/base/ActionCollectionServiceCEImpl.java index 49635f17a093..b7d369ef7242 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/actioncollections/base/ActionCollectionServiceCEImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/actioncollections/base/ActionCollectionServiceCEImpl.java @@ -130,7 +130,7 @@ public Mono<ActionCollection> findByBaseIdAndBranchName(String id, String branch @Override public Flux<ActionCollectionDTO> getPopulatedActionCollectionsByViewMode( MultiValueMap<String, String> params, Boolean viewMode) { - return this.getActionCollectionsByViewMode(params, viewMode) + return this.getNonComposedActionCollectionsByViewMode(params, viewMode) .flatMap(actionCollectionDTO -> this.populateActionCollectionByViewMode(actionCollectionDTO, viewMode)); } @@ -187,7 +187,7 @@ public Flux<ActionCollectionViewDTO> getActionCollectionsForViewMode(String appl return applicationService .findBranchedApplicationId(branchName, applicationId, applicationPermission.getReadPermission()) .flatMapMany(branchedApplicationId -> repository - .findByApplicationIdAndViewMode( + .findNonComposedByApplicationIdAndViewMode( branchedApplicationId, true, actionPermission.getExecutePermission()) .flatMap(this::generateActionCollectionViewDTO)); } @@ -195,7 +195,8 @@ public Flux<ActionCollectionViewDTO> getActionCollectionsForViewMode(String appl @Override public Flux<ActionCollectionViewDTO> getActionCollectionsForViewMode(String branchedApplicationId) { return repository - .findByApplicationIdAndViewMode(branchedApplicationId, true, actionPermission.getExecutePermission()) + .findNonComposedByApplicationIdAndViewMode( + branchedApplicationId, true, actionPermission.getExecutePermission()) .flatMap(this::generateActionCollectionViewDTO); } @@ -235,16 +236,16 @@ protected Mono<ActionCollectionViewDTO> generateActionCollectionViewDTO( } @Override - public Flux<ActionCollectionDTO> getActionCollectionsByViewMode( + public Flux<ActionCollectionDTO> getNonComposedActionCollectionsByViewMode( MultiValueMap<String, String> params, Boolean viewMode) { if (params == null || viewMode == null) { return Flux.empty(); } - return getActionCollectionsFromRepoByViewMode(params, viewMode) + return getNonComposedActionCollectionsFromRepoByViewMode(params, viewMode) .flatMap(actionCollection -> generateActionCollectionByViewMode(actionCollection, viewMode)); } - protected Flux<ActionCollection> getActionCollectionsFromRepoByViewMode( + protected Flux<ActionCollection> getNonComposedActionCollectionsFromRepoByViewMode( MultiValueMap<String, String> params, Boolean viewMode) { if (params.getFirst(FieldName.APPLICATION_ID) != null) { // Fetch unpublished pages because GET actions is only called during edit mode. For view mode, different @@ -254,7 +255,7 @@ protected Flux<ActionCollection> getActionCollectionsFromRepoByViewMode( params.getFirst(FieldName.BRANCH_NAME), params.getFirst(FieldName.APPLICATION_ID), applicationPermission.getReadPermission()) - .flatMapMany(childApplicationId -> repository.findByApplicationIdAndViewMode( + .flatMapMany(childApplicationId -> repository.findNonComposedByApplicationIdAndViewMode( childApplicationId, viewMode, actionPermission.getReadPermission())); } String pageId = null; @@ -262,7 +263,7 @@ protected Flux<ActionCollection> getActionCollectionsFromRepoByViewMode( if (params.getFirst(FieldName.PAGE_ID) != null) { pageId = params.getFirst(FieldName.PAGE_ID); } - return repository.findByPageIdAndViewMode(pageId, viewMode, actionPermission.getReadPermission()); + return repository.findAllNonComposedByPageIdAndViewMode(pageId, viewMode, actionPermission.getReadPermission()); } @Override diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/CustomActionCollectionRepositoryCE.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/CustomActionCollectionRepositoryCE.java index 444e8472f913..c7103a988fb8 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/CustomActionCollectionRepositoryCE.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/CustomActionCollectionRepositoryCE.java @@ -18,7 +18,7 @@ public interface CustomActionCollectionRepositoryCE extends AppsmithRepository<A Flux<ActionCollection> findByApplicationId( String applicationId, Optional<AclPermission> aclPermission, Optional<Sort> sort); - Flux<ActionCollection> findByApplicationIdAndViewMode( + Flux<ActionCollection> findNonComposedByApplicationIdAndViewMode( String applicationId, boolean viewMode, AclPermission aclPermission); Flux<ActionCollection> findByPageId(String pageId, AclPermission permission); @@ -39,4 +39,7 @@ Flux<ActionCollection> findAllPublishedActionCollectionsByContextIdAndContextTyp String contextId, CreatorContextType contextType, AclPermission permission); Flux<ActionCollection> findByPageIdAndViewMode(String pageId, boolean viewMode, AclPermission permission); + + Flux<ActionCollection> findAllNonComposedByPageIdAndViewMode( + String pageId, boolean viewMode, AclPermission permission); } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/CustomActionCollectionRepositoryCEImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/CustomActionCollectionRepositoryCEImpl.java index cce3cc3ff8e4..b47d6751485a 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/CustomActionCollectionRepositoryCEImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/CustomActionCollectionRepositoryCEImpl.java @@ -60,7 +60,7 @@ protected BridgeQuery<ActionCollection> getBridgeQueryForFindByApplicationIdAndV } @Override - public Flux<ActionCollection> findByApplicationIdAndViewMode( + public Flux<ActionCollection> findNonComposedByApplicationIdAndViewMode( String applicationId, boolean viewMode, AclPermission aclPermission) { BridgeQuery<ActionCollection> bridgeQuery = getBridgeQueryForFindByApplicationIdAndViewMode(applicationId, viewMode); @@ -138,6 +138,13 @@ public Flux<ActionCollection> findAllPublishedActionCollectionsByContextIdAndCon @Override public Flux<ActionCollection> findByPageIdAndViewMode(String pageId, boolean viewMode, AclPermission permission) { + final BridgeQuery<ActionCollection> query = getActionCollectionsByPageIdAndViewModeQuery(pageId, viewMode); + + return queryBuilder().criteria(query).permission(permission).all(); + } + + protected BridgeQuery<ActionCollection> getActionCollectionsByPageIdAndViewModeQuery( + String pageId, boolean viewMode) { final BridgeQuery<ActionCollection> query = Bridge.query(); if (Boolean.TRUE.equals(viewMode)) { @@ -153,7 +160,12 @@ public Flux<ActionCollection> findByPageIdAndViewMode(String pageId, boolean vie // would exist. To handle this, only fetch non-deleted actions query.isNull(ActionCollection.Fields.unpublishedCollection_deletedAt); } + return query; + } - return queryBuilder().criteria(query).permission(permission).all(); + @Override + public Flux<ActionCollection> findAllNonComposedByPageIdAndViewMode( + String pageId, boolean viewMode, AclPermission permission) { + return this.findByPageIdAndViewMode(pageId, viewMode, permission); } } diff --git a/app/server/appsmith-server/src/test/java/com/appsmith/server/refactors/ce/RefactoringServiceTest.java b/app/server/appsmith-server/src/test/java/com/appsmith/server/refactors/ce/RefactoringServiceTest.java index 12a39821c361..28e8b18141de 100644 --- a/app/server/appsmith-server/src/test/java/com/appsmith/server/refactors/ce/RefactoringServiceTest.java +++ b/app/server/appsmith-server/src/test/java/com/appsmith/server/refactors/ce/RefactoringServiceTest.java @@ -281,7 +281,8 @@ public void jsActionWithoutCollectionIdShouldBeIgnoredDuringNameChecking() { mockActionCollectionDTO.setName("testCollection"); mockActionCollectionDTO.setActions(List.of(firstAction, secondAction)); - Mockito.when(actionCollectionService.getActionCollectionsByViewMode(Mockito.any(), Mockito.anyBoolean())) + Mockito.when(actionCollectionService.getNonComposedActionCollectionsByViewMode( + Mockito.any(), Mockito.anyBoolean())) .thenReturn(Flux.just(mockActionCollectionDTO)); Mono<Boolean> nameAllowedMono = refactoringService.isNameAllowed(
3c688e772bdb60d6a86698ce3cd80eace85c7fea
2023-05-24 11:38:06
Sanveer Singh Osahan
feat: Implemented Schema Fetch for MSSQL Plugin (#16014) (#23498)
false
Implemented Schema Fetch for MSSQL Plugin (#16014) (#23498)
feat
diff --git a/app/server/appsmith-plugins/mssqlPlugin/src/main/java/com/external/plugins/MssqlPlugin.java b/app/server/appsmith-plugins/mssqlPlugin/src/main/java/com/external/plugins/MssqlPlugin.java index 230c801a4ba9..21ea029b5ab5 100644 --- a/app/server/appsmith-plugins/mssqlPlugin/src/main/java/com/external/plugins/MssqlPlugin.java +++ b/app/server/appsmith-plugins/mssqlPlugin/src/main/java/com/external/plugins/MssqlPlugin.java @@ -11,8 +11,9 @@ import com.appsmith.external.models.ActionConfiguration; import com.appsmith.external.models.ActionExecutionRequest; import com.appsmith.external.models.ActionExecutionResult; -import com.appsmith.external.models.DBAuth; import com.appsmith.external.models.DatasourceConfiguration; +import com.appsmith.external.models.DatasourceStructure; +import com.appsmith.external.models.DBAuth; import com.appsmith.external.models.Endpoint; import com.appsmith.external.models.MustacheBindingToken; import com.appsmith.external.models.Param; @@ -25,14 +26,14 @@ import com.appsmith.external.plugins.SmartSubstitutionInterface; import com.external.plugins.exceptions.MssqlErrorMessages; import com.external.plugins.exceptions.MssqlPluginError; +import com.external.plugins.utils.MssqlDatasourceUtils; +import com.external.plugins.utils.MssqlExecuteUtils; import com.zaxxer.hikari.HikariConfig; import com.zaxxer.hikari.HikariDataSource; -import com.zaxxer.hikari.HikariPoolMXBean; import com.zaxxer.hikari.pool.HikariPool; import lombok.NonNull; import lombok.extern.slf4j.Slf4j; import org.apache.commons.io.IOUtils; -import org.apache.commons.lang.ObjectUtils; import org.pf4j.Extension; import org.pf4j.PluginWrapper; import org.springframework.util.CollectionUtils; @@ -47,16 +48,13 @@ import java.sql.Date; import java.sql.PreparedStatement; import java.sql.ResultSet; -import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.sql.Statement; import java.sql.Time; import java.sql.Timestamp; import java.sql.Types; +import java.text.MessageFormat; import java.time.Duration; -import java.time.LocalDateTime; -import java.time.OffsetDateTime; -import java.time.format.DateTimeFormatter; import java.util.AbstractMap.SimpleEntry; import java.util.ArrayList; import java.util.HashMap; @@ -68,10 +66,12 @@ import java.util.stream.IntStream; import static com.appsmith.external.constants.ActionConstants.ACTION_CONFIGURATION_BODY; -import static com.appsmith.external.helpers.PluginUtils.getColumnsListForJdbcPlugin; import static com.appsmith.external.helpers.PluginUtils.getIdenticalColumns; import static com.appsmith.external.helpers.PluginUtils.getPSParamLabel; import static com.appsmith.external.helpers.SmartSubstitutionHelper.replaceQuestionMarkWithDollarIndex; +import static com.external.plugins.utils.MssqlDatasourceUtils.getConnectionFromConnectionPool; +import static com.external.plugins.utils.MssqlDatasourceUtils.logHikariCPStatus; +import static com.external.plugins.utils.MssqlExecuteUtils.closeConnectionPostExecution; import static java.lang.Boolean.FALSE; import static java.lang.Boolean.TRUE; @@ -80,8 +80,6 @@ public class MssqlPlugin extends BasePlugin { private static final String JDBC_DRIVER = "com.microsoft.sqlserver.jdbc.SQLServerDriver"; - private static final String DATE_COLUMN_TYPE_NAME = "date"; - private static final int VALIDITY_CHECK_TIMEOUT = 5; private static final int MINIMUM_POOL_SIZE = 5; @@ -102,7 +100,7 @@ public MssqlPlugin(PluginWrapper wrapper) { @Extension public static class MssqlPluginExecutor implements PluginExecutor<HikariDataSource>, SmartSubstitutionInterface { - private final Scheduler scheduler = Schedulers.boundedElastic(); + public static final Scheduler scheduler = Schedulers.boundedElastic(); private static final int PREPARED_STATEMENT_INDEX = 0; @@ -212,14 +210,9 @@ public Mono<ActionExecutionResult> executeCommon(HikariDataSource hikariDSConnec log.error("Error checking validity of MsSQL connection.", error); } - HikariPoolMXBean poolProxy = hikariDSConnection.getHikariPoolMXBean(); - - int idleConnections = poolProxy.getIdleConnections(); - int activeConnections = poolProxy.getActiveConnections(); - int totalConnections = poolProxy.getTotalConnections(); - int threadsAwaitingConnection = poolProxy.getThreadsAwaitingConnection(); - log.debug("Before executing MsSQL query [{}] Hikari Pool stats : active - {} , idle - {} , awaiting - {} , total - {}", - query, activeConnections, idleConnections, threadsAwaitingConnection, totalConnections); + // Log HikariCP status + logHikariCPStatus(MessageFormat.format("Before executing Mssql query [{0}]", query), + hikariDSConnection);; try { if (FALSE.equals(preparedStatement)) { @@ -247,92 +240,18 @@ public Mono<ActionExecutionResult> executeCommon(HikariDataSource hikariDSConnec resultSet = preparedQuery.getResultSet(); } - if (!isResultSet) { - Object updateCount = FALSE.equals(preparedStatement) ? - ObjectUtils.defaultIfNull(statement.getUpdateCount(), 0) : - ObjectUtils.defaultIfNull(preparedQuery.getUpdateCount(), 0); - - rowsList.add(Map.of("affectedRows", updateCount)); - } else { - ResultSetMetaData metaData = resultSet.getMetaData(); - int colCount = metaData.getColumnCount(); - columnsList.addAll(getColumnsListForJdbcPlugin(metaData)); - - while (resultSet.next()) { - // Use `LinkedHashMap` here so that the column ordering is preserved in the response. - Map<String, Object> row = new LinkedHashMap<>(colCount); - - for (int i = 1; i <= colCount; i++) { - Object value; - final String typeName = metaData.getColumnTypeName(i); - - if (resultSet.getObject(i) == null) { - value = null; - - } else if (DATE_COLUMN_TYPE_NAME.equalsIgnoreCase(typeName)) { - value = DateTimeFormatter.ISO_DATE.format(resultSet.getDate(i).toLocalDate()); - - } else if ("timestamp".equalsIgnoreCase(typeName)) { - value = DateTimeFormatter.ISO_DATE_TIME.format( - LocalDateTime.of( - resultSet.getDate(i).toLocalDate(), - resultSet.getTime(i).toLocalTime() - ) - ) + "Z"; - - } else if ("timestamptz".equalsIgnoreCase(typeName)) { - value = DateTimeFormatter.ISO_DATE_TIME.format( - resultSet.getObject(i, OffsetDateTime.class) - ); - - } else if ("time".equalsIgnoreCase(typeName) || "timetz".equalsIgnoreCase(typeName)) { - value = resultSet.getString(i); - - } else if ("interval".equalsIgnoreCase(typeName)) { - value = resultSet.getObject(i).toString(); - - } else { - value = resultSet.getObject(i); - - } - - row.put(metaData.getColumnName(i), value); - } - - rowsList.add(row); - } - - } + MssqlExecuteUtils.populateRowsAndColumns(rowsList, columnsList, resultSet, isResultSet, preparedStatement, + statement, preparedQuery); } catch (SQLException e) { return Mono.error(new AppsmithPluginException(MssqlPluginError.QUERY_EXECUTION_FAILED, MssqlErrorMessages.QUERY_EXECUTION_FAILED_ERROR_MSG, e.getMessage(), "SQLSTATE: "+ e.getSQLState())); } finally { - sqlConnectionFromPool.close(); - if (resultSet != null) { - try { - resultSet.close(); - } catch (SQLException e) { - log.warn("Error closing MsSQL ResultSet", e); - } - } - - if (statement != null) { - try { - statement.close(); - } catch (SQLException e) { - log.warn("Error closing MsSQL Statement", e); - } - } - - if (preparedQuery != null) { - try { - preparedQuery.close(); - } catch (SQLException e) { - log.warn("Error closing MsSQL Statement", e); - } - } + // Log HikariCP status + logHikariCPStatus(MessageFormat.format("After executing Mssql query [{0}]", query), + hikariDSConnection); + closeConnectionPostExecution(resultSet, statement, preparedQuery, sqlConnectionFromPool); } ActionExecutionResult result = new ActionExecutionResult(); @@ -436,6 +355,12 @@ public Mono<ActionExecutionResult> execute(HikariDataSource connection, return Mono.error(new AppsmithPluginException(MssqlPluginError.QUERY_EXECUTION_FAILED, MssqlErrorMessages.QUERY_EXECUTION_FAILED_ERROR_MSG, "Unsupported Operation")); } + @Override + public Mono<DatasourceStructure> getStructure( + HikariDataSource connection, DatasourceConfiguration datasourceConfiguration) { + return MssqlDatasourceUtils.getStructure(connection, datasourceConfiguration); + } + @Override public Object substituteValueInInput(int index, String binding, @@ -631,23 +556,4 @@ private static void addSslOptionsToUrlBuilder(DatasourceConfiguration datasource " Appsmith customer support to resolve this."); } } - - /** - * First checks if the connection pool is still valid. If yes, we fetch a connection from the pool and return - * In case a connection is not available in the pool, SQL Exception is thrown - * - * @param hikariDSConnectionPool - * @return SQL Connection - */ - private static Connection getConnectionFromConnectionPool(HikariDataSource hikariDSConnectionPool) throws SQLException { - - if (hikariDSConnectionPool == null || hikariDSConnectionPool.isClosed() || !hikariDSConnectionPool.isRunning()) { - log.debug("Encountered stale connection pool in SQL Server plugin. Reporting back."); - throw new StaleConnectionException(); - } - - Connection sqlDataSourceConnection = hikariDSConnectionPool.getConnection(); - - return sqlDataSourceConnection; - } } \ No newline at end of file diff --git a/app/server/appsmith-plugins/mssqlPlugin/src/main/java/com/external/plugins/exceptions/MssqlErrorMessages.java b/app/server/appsmith-plugins/mssqlPlugin/src/main/java/com/external/plugins/exceptions/MssqlErrorMessages.java index de61718f6519..2cb5d2f878c0 100644 --- a/app/server/appsmith-plugins/mssqlPlugin/src/main/java/com/external/plugins/exceptions/MssqlErrorMessages.java +++ b/app/server/appsmith-plugins/mssqlPlugin/src/main/java/com/external/plugins/exceptions/MssqlErrorMessages.java @@ -1,6 +1,7 @@ package com.external.plugins.exceptions; public class MssqlErrorMessages { + private MssqlErrorMessages() { //Prevents instantiation } @@ -13,6 +14,8 @@ private MssqlErrorMessages() { public static final String CONNECTION_POOL_CREATION_FAILED_ERROR_MSG = "Exception occurred while creating connection pool. One or more arguments in the datasource configuration may be invalid. Please check your datasource configuration."; + public static final String GET_STRUCTURE_ERROR_MSG = "The Appsmith server has failed to fetch the structure of your schema."; + /* ************************************************************************************************************************************************ Error messages related to validation of datasource. diff --git a/app/server/appsmith-plugins/mssqlPlugin/src/main/java/com/external/plugins/utils/MssqlDatasourceUtils.java b/app/server/appsmith-plugins/mssqlPlugin/src/main/java/com/external/plugins/utils/MssqlDatasourceUtils.java new file mode 100644 index 000000000000..d02e7874ba6c --- /dev/null +++ b/app/server/appsmith-plugins/mssqlPlugin/src/main/java/com/external/plugins/utils/MssqlDatasourceUtils.java @@ -0,0 +1,308 @@ +package com.external.plugins.utils; + +import com.appsmith.external.exceptions.pluginExceptions.AppsmithPluginError; +import com.appsmith.external.exceptions.pluginExceptions.AppsmithPluginException; +import com.appsmith.external.exceptions.pluginExceptions.StaleConnectionException; +import com.appsmith.external.models.DatasourceConfiguration; +import com.appsmith.external.models.DatasourceStructure; +import com.external.plugins.exceptions.MssqlErrorMessages; +import com.zaxxer.hikari.HikariDataSource; +import com.zaxxer.hikari.HikariPoolMXBean; +import lombok.AccessLevel; +import lombok.NoArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import reactor.core.publisher.Mono; + +import java.sql.Connection; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.text.MessageFormat; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +import static com.appsmith.external.helpers.PluginUtils.safelyCloseSingleConnectionFromHikariCP; +import static com.external.plugins.MssqlPlugin.MssqlPluginExecutor.scheduler; + +@Slf4j +@NoArgsConstructor(access = AccessLevel.PRIVATE) +public class MssqlDatasourceUtils { + + public static final String PRIMARY_KEY_INDICATOR = "PRIMARY KEY"; + + /** + * Example output: + * + * <pre> + * +------------+-----------+---------------+-------------+ + * | TABLE_NAME | COLUMN_NAME | COLUMN_TYPE | SCHEMA_NAME | + * +------------+-----------+---------------+-------------+ + * | CLUB | ID | NUMBER | DBO | + * | STUDENTS | NAME | VARCHAR2 | DBO | + * +------------+-----------+--------------+--------------+ + * </pre> + */ + private static final String QUERY_TO_GET_ALL_TABLE_COLUMN_TYPE = "SELECT \n" + + " col.name AS column_name,\n" + + " typ.name AS column_type,\n" + + " tbl.name AS table_name,\n" + + " sch.name AS schema_name\n" + + "FROM sys.columns col\n" + + " INNER JOIN sys.tables tbl ON col.object_id = tbl.object_id\n" + + " INNER JOIN sys.types typ ON col.user_type_id = typ.user_type_id\n" + + " INNER JOIN sys.schemas sch ON tbl.schema_id = sch.schema_id\n" + + "WHERE tbl.is_ms_shipped = 0\n" + + "ORDER BY tbl.name, col.column_id;\n"; + + + /** + * Example output: + * <pre> + * +------------+-----------+-----------------+-----------------+-------------+ + * | TABLE_NAME |COLUMN_NAME| CONSTRAINT_TYPE | CONSTRAINT_NAME | SCHEMA_NAME | + * +------------+-----------+-----------------+-----------------+-------------+ + * | CLUB | ID | R | FK_STUDENTS_ID | DBO | + * | STUDENTS | ID | P | SYS_C006397 | DBO | + * +------------+-----------+-----------------+-----------------+-------------+ + * </pre> + */ + private static final String QUERY_TO_GET_ALL_TABLE_COLUMN_KEY_CONSTRAINTS = "SELECT \n" + + " cols.table_name,\n" + + " cols.column_name,\n" + + " cols.constraint_schema as schema_name,\n" + + " cons.constraint_type,\n" + + " cons.constraint_name\n" + + "FROM \n" + + " INFORMATION_SCHEMA.KEY_COLUMN_USAGE cols\n" + + " JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS cons\n" + + " ON cols.CONSTRAINT_SCHEMA = cons.CONSTRAINT_SCHEMA\n" + + " AND cols.CONSTRAINT_NAME = cons.CONSTRAINT_NAME\n" + + "WHERE \n" + + " cons.constraint_type IN ('PRIMARY KEY', 'FOREIGN KEY')\n" + + " AND cols.CONSTRAINT_SCHEMA = 'dbo'\n" + + "ORDER BY \n" + + " cols.table_name,\n" + + " cols.ordinal_position\n"; + + public static Mono<DatasourceStructure> getStructure(HikariDataSource connection, DatasourceConfiguration datasourceConfiguration) { + final DatasourceStructure structure = new DatasourceStructure(); + final Map<String, DatasourceStructure.Table> tableNameToTableMap = new LinkedHashMap<>(); + + return Mono.fromSupplier(() -> { + Connection connectionFromPool; + try { + connectionFromPool = getConnectionFromConnectionPool(connection); + } catch (SQLException | StaleConnectionException e) { + // The function can throw either StaleConnectionException or SQLException. The + // underlying hikari library throws SQLException in case the pool is closed or there is an issue + // initializing the connection pool which can also be translated in our world to + // StaleConnectionException and should then trigger the destruction and recreation of the pool. + return Mono.error(e instanceof StaleConnectionException ? e : new StaleConnectionException()); + } + + logHikariCPStatus("Before getting Mssql DB schema", connection); + + try (Statement statement = connectionFromPool.createStatement()) { + // Set table names. For each table set its column names and column types. + setTableNamesAndColumnNamesAndColumnTypes(statement, tableNameToTableMap); + + // Set primary key and foreign key constraints. + setPrimaryAndForeignKeyInfoInTables(statement, tableNameToTableMap); + + } catch (SQLException throwable) { + return Mono.error(new AppsmithPluginException( AppsmithPluginError.PLUGIN_GET_STRUCTURE_ERROR, + MssqlErrorMessages.GET_STRUCTURE_ERROR_MSG, throwable.getCause(), + "SQLSTATE: " + throwable.getSQLState())); + } finally { + logHikariCPStatus("After getting Oracle DB schema", connection); + safelyCloseSingleConnectionFromHikariCP(connectionFromPool, "Error returning Oracle connection to pool " + + "during get structure"); + } + + // Set SQL query templates + setSQLQueryTemplates(tableNameToTableMap); + + structure.setTables(new ArrayList<>(tableNameToTableMap.values())); + log.debug("Got the structure of postgres db"); + return structure; + }) + .map(resultStructure -> (DatasourceStructure) resultStructure) + .subscribeOn(scheduler); + } + + /** + * First checks if the connection pool is still valid. If yes, we fetch a connection from the pool and return + * In case a connection is not available in the pool, SQL Exception is thrown + * + * @param hikariDSConnectionPool + * @return SQL Connection + */ + public static Connection getConnectionFromConnectionPool(HikariDataSource hikariDSConnectionPool) throws SQLException { + + if (hikariDSConnectionPool == null || hikariDSConnectionPool.isClosed() || !hikariDSConnectionPool.isRunning()) { + log.debug("Encountered stale connection pool in SQL Server plugin. Reporting back."); + throw new StaleConnectionException(); + } + + Connection sqlDataSourceConnection = hikariDSConnectionPool.getConnection(); + + return sqlDataSourceConnection; + } + + public static void logHikariCPStatus(String logPrefix, HikariDataSource connectionPool) { + HikariPoolMXBean poolProxy = connectionPool.getHikariPoolMXBean(); + int idleConnections = poolProxy.getIdleConnections(); + int activeConnections = poolProxy.getActiveConnections(); + int totalConnections = poolProxy.getTotalConnections(); + int threadsAwaitingConnection = poolProxy.getThreadsAwaitingConnection(); + log.debug(MessageFormat.format("{0}: Hikari Pool stats : active - {1} , idle - {2}, awaiting - {3} , total - {4}", + logPrefix, activeConnections, idleConnections, threadsAwaitingConnection, totalConnections)); + } + + /** + * Run a SQL query to fetch all tables accessible to user along with their columns and data type of each column. + * Then read the response and populate Appsmith's Table object with the same. + * Please check the SQL query macro definition to find a sample response as comment. + */ + private static void setTableNamesAndColumnNamesAndColumnTypes( + Statement statement, Map<String, DatasourceStructure.Table> tableNameToTableMap) throws SQLException { + try (ResultSet columnsResultSet = statement.executeQuery(QUERY_TO_GET_ALL_TABLE_COLUMN_TYPE)) { + while (columnsResultSet.next()) { + final String columnName = columnsResultSet.getString("column_name"); + final String columnType = columnsResultSet.getString("column_type"); + final String tableName = columnsResultSet.getString("table_name"); + final String schemaName = columnsResultSet.getString("schema_name"); + final String fullTableName = schemaName + "." + tableName; + if (!tableNameToTableMap.containsKey(fullTableName)) { + tableNameToTableMap.put(fullTableName, new DatasourceStructure.Table( + DatasourceStructure.TableType.TABLE, + schemaName, + fullTableName, + new ArrayList<>(), + new ArrayList<>(), + new ArrayList<>())); + } + + final DatasourceStructure.Table table = tableNameToTableMap.get(fullTableName); + + table.getColumns().add( + new DatasourceStructure.Column(columnName, columnType, null, false)); + } + } + } + + /** + * Run a SQL query to fetch all user accessible tables along with their column names and if the column is a + * primary or foreign key. + * Please check the SQL query macro definition to find a sample response as comment. + */ + private static void setPrimaryAndForeignKeyInfoInTables ( + Statement statement, Map<String, DatasourceStructure.Table> tableNameToTableMap) throws SQLException { + Map<String, String> primaryKeyConstraintNameToTableNameMap = new HashMap<>(); + Map<String, String> primaryKeyConstraintNameToColumnNameMap = new HashMap<>(); + Map<String, String> foreignKeyConstraintNameToTableNameMap = new HashMap<>(); + Map<String, String> foreignKeyConstraintNameToColumnNameMap = new HashMap<>(); + try (ResultSet constraintsResultSet = statement.executeQuery(QUERY_TO_GET_ALL_TABLE_COLUMN_KEY_CONSTRAINTS)) { + while (constraintsResultSet.next()) { + final String tableName = constraintsResultSet.getString("table_name"); + final String columnName = constraintsResultSet.getString("column_name"); + final String constraintType = constraintsResultSet.getString("constraint_type"); + final String constraintName = constraintsResultSet.getString("constraint_name"); + final String schemaName = constraintsResultSet.getString("schema_name"); + final String fullTableName = schemaName + "." + tableName; + + if (PRIMARY_KEY_INDICATOR.equalsIgnoreCase(constraintType)) { + primaryKeyConstraintNameToTableNameMap.put(constraintName, fullTableName); + primaryKeyConstraintNameToColumnNameMap.put(constraintName, columnName); + } else { + foreignKeyConstraintNameToTableNameMap.put(constraintName, fullTableName); + foreignKeyConstraintNameToColumnNameMap.put(constraintName, columnName); + } + } + } + + primaryKeyConstraintNameToColumnNameMap.keySet().stream() + .filter(constraintName -> { + String tableName = primaryKeyConstraintNameToTableNameMap.get(constraintName); + return tableNameToTableMap.containsKey(tableName); + }) + .forEach(constraintName -> { + String tableName = primaryKeyConstraintNameToTableNameMap.get(constraintName); + DatasourceStructure.Table table = tableNameToTableMap.get(tableName); + String columnName = primaryKeyConstraintNameToColumnNameMap.get(constraintName); + table.getKeys().add(new DatasourceStructure.PrimaryKey(constraintName, + List.of(columnName))); + }); + + foreignKeyConstraintNameToColumnNameMap.keySet().stream() + .filter(constraintName -> { + String tableName = foreignKeyConstraintNameToTableNameMap.get(constraintName); + return tableNameToTableMap.containsKey(tableName); + }) + .forEach(constraintName -> { + String tableName = foreignKeyConstraintNameToTableNameMap.get(constraintName); + DatasourceStructure.Table table = tableNameToTableMap.get(tableName); + String columnName = foreignKeyConstraintNameToColumnNameMap.get(constraintName); + table.getKeys().add(new DatasourceStructure.ForeignKey(constraintName, + List.of(columnName), new ArrayList<>())); + }); + } + + private static void setSQLQueryTemplates(Map<String, DatasourceStructure.Table> tableNameToTableMap) { + tableNameToTableMap.values() + .forEach(table -> { + LinkedHashMap<String, String> columnNameToSampleColumnDataMap = + new LinkedHashMap<>(); + table.getColumns() + .forEach(column -> columnNameToSampleColumnDataMap.put(column.getName(), + getSampleColumnData(column.getType()))); + + String selectQueryTemplate = MessageFormat.format("SELECT TOP 10 * FROM {0}", table.getName()); + String insertQueryTemplate = MessageFormat.format("INSERT INTO {0} ({1}) " + + "VALUES ({2})", table.getName(), + getSampleColumnNamesCSVString(columnNameToSampleColumnDataMap), + getSampleColumnDataCSVString(columnNameToSampleColumnDataMap)); + String updateQueryTemplate = MessageFormat.format("UPDATE {0} SET {1} WHERE " + + "1=0 -- Specify a valid condition here. Removing the condition may " + + "update every row in the table!", table.getName(), + getSampleOneColumnUpdateString(columnNameToSampleColumnDataMap)); + String deleteQueryTemplate = MessageFormat.format("DELETE FROM {0} WHERE 1=0" + + " -- Specify a valid condition here. Removing the condition may " + + "delete everything in the table!", table.getName()); + + table.getTemplates().add(new DatasourceStructure.Template("SELECT", selectQueryTemplate)); + table.getTemplates().add(new DatasourceStructure.Template("INSERT", insertQueryTemplate)); + table.getTemplates().add(new DatasourceStructure.Template("UPDATE", updateQueryTemplate)); + table.getTemplates().add(new DatasourceStructure.Template("DELETE", deleteQueryTemplate)); + }); + } + + private static String getSampleColumnData(String type) { + if (type == null) { + return "NULL"; + } + + return switch (type.toUpperCase()) { + case "NUMBER", "INT" -> "1"; + case "FLOAT", "DOUBLE" -> "1.0"; + case "CHAR", "NCHAR", "VARCHAR", "VARCHAR2", "NVARCHAR", "NVARCHAR2" -> "'text'"; + default -> "NULL"; + }; + } + + private static String getSampleColumnNamesCSVString(LinkedHashMap<String, String> columnNameToSampleColumnDataMap) { + return String.join(", ", columnNameToSampleColumnDataMap.keySet()); + } + + private static String getSampleColumnDataCSVString(LinkedHashMap<String, String> columnNameToSampleColumnDataMap) { + return String.join(", ", columnNameToSampleColumnDataMap.values()); + } + + private static String getSampleOneColumnUpdateString(LinkedHashMap<String, String> columnNameToSampleColumnDataMap) { + return MessageFormat.format("{0}={1}", columnNameToSampleColumnDataMap.keySet().stream().findFirst().orElse( + "id"), columnNameToSampleColumnDataMap.values().stream().findFirst().orElse("'uid'")); + } +} diff --git a/app/server/appsmith-plugins/mssqlPlugin/src/main/java/com/external/plugins/utils/MssqlExecuteUtils.java b/app/server/appsmith-plugins/mssqlPlugin/src/main/java/com/external/plugins/utils/MssqlExecuteUtils.java new file mode 100644 index 000000000000..f26a5d1df21b --- /dev/null +++ b/app/server/appsmith-plugins/mssqlPlugin/src/main/java/com/external/plugins/utils/MssqlExecuteUtils.java @@ -0,0 +1,125 @@ +package com.external.plugins.utils; + +import org.apache.commons.lang.ObjectUtils; + +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSetMetaData; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.text.MessageFormat; +import java.time.LocalDateTime; +import java.time.OffsetDateTime; +import java.time.format.DateTimeFormatter; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +import static com.appsmith.external.helpers.PluginUtils.getColumnsListForJdbcPlugin; +import static com.appsmith.external.helpers.PluginUtils.safelyCloseSingleConnectionFromHikariCP; +import static java.lang.Boolean.FALSE; + +public class MssqlExecuteUtils { + + private static final String DATE_COLUMN_TYPE_NAME = "date"; + private static final String TIMESTAMP_TYPE_NAME = "timestamp"; + private static final String TIMESTAMPTZ_TYPE_NAME = "timestamptz"; + private static final String TIME_TYPE_NAME = "time"; + private static final String TIMETZ_TYPE_NAME = "timetz"; + private static final String INTERVAL_TYPE_NAME = "interval"; + + + public static void closeConnectionPostExecution(ResultSet resultSet, Statement statement, + PreparedStatement preparedQuery, Connection connectionFromPool) { + if (resultSet != null) { + try { + resultSet.close(); + } catch (SQLException e) { + System.out.println(Thread.currentThread().getName() + + ": Execute Error closing Mssql ResultSet" + e.getMessage()); + } + } + + if (statement != null) { + try { + statement.close(); + } catch (SQLException e) { + System.out.println(Thread.currentThread().getName() + + ": Execute Error closing Mssql Statement" + e.getMessage()); + } + } + + if (preparedQuery != null) { + try { + preparedQuery.close(); + } catch (SQLException e) { + System.out.println(Thread.currentThread().getName() + + ": Execute Error closing Mssql Statement" + e.getMessage()); + } + } + + safelyCloseSingleConnectionFromHikariCP(connectionFromPool, MessageFormat.format("{0}: Execute Error returning " + + "Oracle connection to pool", Thread.currentThread().getName())); + } + + public static void populateRowsAndColumns(List<Map<String, Object>> rowsList, List<String> columnsList, ResultSet resultSet, boolean isResultSet, Boolean preparedStatement, Statement statement, PreparedStatement preparedQuery) throws SQLException { + + if (!isResultSet) { + Object updateCount = FALSE.equals(preparedStatement) ? + ObjectUtils.defaultIfNull(statement.getUpdateCount(), 0) : + ObjectUtils.defaultIfNull(preparedQuery.getUpdateCount(), 0); + + rowsList.add(Map.of("affectedRows", updateCount)); + } else { + ResultSetMetaData metaData = resultSet.getMetaData(); + int colCount = metaData.getColumnCount(); + columnsList.addAll(getColumnsListForJdbcPlugin(metaData)); + + while (resultSet.next()) { + // Use `LinkedHashMap` here so that the column ordering is preserved in the response. + Map<String, Object> row = new LinkedHashMap<>(colCount); + + for (int i = 1; i <= colCount; i++) { + Object value; + final String typeName = metaData.getColumnTypeName(i); + + if (resultSet.getObject(i) == null) { + value = null; + + } else if (DATE_COLUMN_TYPE_NAME.equalsIgnoreCase(typeName)) { + value = DateTimeFormatter.ISO_DATE.format(resultSet.getDate(i).toLocalDate()); + + } else if (TIMESTAMP_TYPE_NAME.equalsIgnoreCase(typeName)) { + value = DateTimeFormatter.ISO_DATE_TIME.format( + LocalDateTime.of( + resultSet.getDate(i).toLocalDate(), + resultSet.getTime(i).toLocalTime() + ) + ) + "Z"; + + } else if (TIMESTAMPTZ_TYPE_NAME.equalsIgnoreCase(typeName)) { + value = DateTimeFormatter.ISO_DATE_TIME.format( + resultSet.getObject(i, OffsetDateTime.class) + ); + + } else if (TIME_TYPE_NAME.equalsIgnoreCase(typeName) || TIMETZ_TYPE_NAME.equalsIgnoreCase(typeName)) { + value = resultSet.getString(i); + + } else if (INTERVAL_TYPE_NAME.equalsIgnoreCase(typeName)) { + value = resultSet.getObject(i).toString(); + + } else { + value = resultSet.getObject(i); + + } + + row.put(metaData.getColumnName(i), value); + } + + rowsList.add(row); + } + + } + } +} diff --git a/app/server/appsmith-plugins/mssqlPlugin/src/test/java/com/external/plugins/MssqlGetDBSchemaTest.java b/app/server/appsmith-plugins/mssqlPlugin/src/test/java/com/external/plugins/MssqlGetDBSchemaTest.java new file mode 100644 index 000000000000..369f7d566204 --- /dev/null +++ b/app/server/appsmith-plugins/mssqlPlugin/src/test/java/com/external/plugins/MssqlGetDBSchemaTest.java @@ -0,0 +1,159 @@ +package com.external.plugins; + +import com.appsmith.external.models.DatasourceStructure; +import com.zaxxer.hikari.HikariDataSource; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.testcontainers.containers.MSSQLServerContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; +import reactor.core.publisher.Mono; +import reactor.test.StepVerifier; + +import java.sql.SQLException; +import java.util.Optional; +import java.util.Set; +import java.util.stream.Collectors; + +import static com.external.plugins.MssqlTestDBContainerManager.createDatasourceConfiguration; +import static com.external.plugins.MssqlTestDBContainerManager.mssqlPluginExecutor; +import static com.external.plugins.MssqlTestDBContainerManager.runSQLQueryOnMssqlTestDB; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +@Testcontainers +public class MssqlGetDBSchemaTest { + public static final String SQL_QUERY_TO_CREATE_TABLE_WITH_PRIMARY_KEY = + "CREATE TABLE supplier\n" + + "( supplier_id int not null,\n" + + " supplier_name varchar(50) not null,\n" + + " contact_name varchar(50),\n" + + " CONSTRAINT supplier_pk PRIMARY KEY (supplier_id)\n" + + ")"; + + public static final String SQL_QUERY_TO_CREATE_TABLE_WITH_FOREIGN_KEY = + "CREATE TABLE products\n" + + "( product_id int not null,\n" + + " supplier_id int not null,\n" + + " CONSTRAINT fk_supplier\n" + + " FOREIGN KEY (supplier_id)\n" + + " REFERENCES supplier(supplier_id)\n" + + ")"; + + @SuppressWarnings("rawtypes") // The type parameter for the container type is just itself and is pseudo-optional. + @Container + private static final MSSQLServerContainer container = MssqlTestDBContainerManager.getMssqlDBForTest(); + + private static HikariDataSource sharedConnectionPool = null; + + @BeforeAll + public static void setup() throws SQLException { + sharedConnectionPool = mssqlPluginExecutor.datasourceCreate(createDatasourceConfiguration(container)).block(); + createTablesForTest(); + } + + @Test + public void testDBSchemaShowsAllTables() { + Mono<DatasourceStructure> datasourceStructureMono = + mssqlPluginExecutor.getStructure(sharedConnectionPool, + createDatasourceConfiguration(container)); + + StepVerifier.create(datasourceStructureMono) + .assertNext(datasourceStructure -> { + Set<String> setOfAllTableNames = datasourceStructure.getTables().stream() + .map(DatasourceStructure.Table::getName) + .map(String::toLowerCase) + .collect(Collectors.toSet()); + + assertTrue(setOfAllTableNames.equals(Set.of("dbo.supplier","dbo.products")), setOfAllTableNames.toString()); + }) + .verifyComplete(); + } + + @Test + public void testDBSchemaShowsAllColumnsAndTypesInATable() { + Mono<DatasourceStructure> datasourceStructureMono = + mssqlPluginExecutor.getStructure(sharedConnectionPool, + createDatasourceConfiguration(container)); + + StepVerifier.create(datasourceStructureMono) + .assertNext(datasourceStructure -> { + Optional<DatasourceStructure.Table> supplierTable = datasourceStructure.getTables().stream() + .filter(table -> "dbo.supplier".equalsIgnoreCase(table.getName())) + .findFirst(); + + assertTrue(supplierTable.isPresent(), "supplier table not found in DB schema"); + + Set<String> allColumnNames = supplierTable.get().getColumns().stream() + .map(DatasourceStructure.Column::getName) + .map(String::toLowerCase) + .collect(Collectors.toSet()); + Set<String> expectedColumnNames = Set.of("supplier_id", "supplier_name", "contact_name"); + assertEquals(expectedColumnNames, allColumnNames, allColumnNames.toString()); + + supplierTable.get().getColumns() + .forEach(column -> { + String columnName = column.getName().toLowerCase(); + String columnType = column.getType().toLowerCase(); + String expectedColumnType; + + if ("supplier_id".equals(columnName)) { + expectedColumnType = "int"; + } + else { + expectedColumnType = "varchar"; + } + + assertEquals(expectedColumnType, columnType, columnType); + }); + }) + .verifyComplete(); + } + + @Test + public void testDynamicSqlTemplateQueriesForATable() { + Mono<DatasourceStructure> datasourceStructureMono = + mssqlPluginExecutor.getStructure(sharedConnectionPool, + createDatasourceConfiguration(container)); + + StepVerifier.create(datasourceStructureMono) + .assertNext(datasourceStructure -> { + Optional<DatasourceStructure.Table> supplierTable = datasourceStructure.getTables().stream() + .filter(table -> "dbo.supplier".equalsIgnoreCase(table.getName())) + .findFirst(); + + assertTrue(supplierTable.isPresent(), "supplier table not found in DB schema"); + + supplierTable.get().getTemplates().stream() + .filter(template -> "select".equalsIgnoreCase(template.getTitle()) || "delete".equalsIgnoreCase(template.getTitle())) + .forEach(template -> { + + /* + * Not sure how to test query templates for insert and update queries as these + * queries include column names in an order that is not fixed. Hence, skipping testing + * them for now. + */ + + String expectedQueryTemplate = null; + if ("select".equalsIgnoreCase(template.getTitle())) { + expectedQueryTemplate = "select top 10 * from dbo.supplier"; + } + else if ("delete".equalsIgnoreCase(template.getTitle())) { + expectedQueryTemplate = "delete from dbo.supplier where 1=0 -- specify a valid" + + " condition here. removing the condition may delete everything in the " + + "table!"; + } + + String templateQuery = template.getBody(); + assertEquals(expectedQueryTemplate, templateQuery.toLowerCase(), + templateQuery.toLowerCase()); + }); + }) + .verifyComplete(); + } + + private static void createTablesForTest() throws SQLException { + runSQLQueryOnMssqlTestDB(SQL_QUERY_TO_CREATE_TABLE_WITH_PRIMARY_KEY, sharedConnectionPool); + runSQLQueryOnMssqlTestDB(SQL_QUERY_TO_CREATE_TABLE_WITH_FOREIGN_KEY, sharedConnectionPool); + } +} diff --git a/app/server/appsmith-plugins/mssqlPlugin/src/test/java/com/external/plugins/MssqlPluginTest.java b/app/server/appsmith-plugins/mssqlPlugin/src/test/java/com/external/plugins/MssqlPluginTest.java index 885434cbc749..7735c37c4a1a 100755 --- a/app/server/appsmith-plugins/mssqlPlugin/src/test/java/com/external/plugins/MssqlPluginTest.java +++ b/app/server/appsmith-plugins/mssqlPlugin/src/test/java/com/external/plugins/MssqlPluginTest.java @@ -28,14 +28,11 @@ import org.testcontainers.containers.MSSQLServerContainer; import org.testcontainers.junit.jupiter.Container; import org.testcontainers.junit.jupiter.Testcontainers; -import org.testcontainers.utility.DockerImageName; import reactor.core.publisher.Mono; import reactor.test.StepVerifier; -import java.sql.Connection; -import java.sql.DriverManager; import java.sql.SQLException; -import java.sql.Statement; + import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; @@ -48,120 +45,67 @@ import java.util.stream.Stream; import static com.appsmith.external.constants.ActionConstants.ACTION_CONFIGURATION_BODY; -import static org.junit.jupiter.api.Assertions.assertArrayEquals; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertTrue; +import static com.external.plugins.MssqlTestDBContainerManager.createDatasourceConfiguration; +import static com.external.plugins.MssqlTestDBContainerManager.mssqlPluginExecutor; +import static com.external.plugins.MssqlTestDBContainerManager.runSQLQueryOnMssqlTestDB; +import static org.junit.jupiter.api.Assertions.*; @Testcontainers public class MssqlPluginTest { - MssqlPlugin.MssqlPluginExecutor pluginExecutor = new MssqlPlugin.MssqlPluginExecutor(); - @SuppressWarnings("rawtypes") // The type parameter for the container type is just itself and is pseudo-optional. @Container - public static final MSSQLServerContainer container = - new MSSQLServerContainer<>( - DockerImageName.parse("mcr.microsoft.com/azure-sql-edge:1.0.3").asCompatibleSubstituteFor("mcr.microsoft.com/mssql/server:2017-latest")) - .acceptLicense() - .withExposedPorts(1433) - .withPassword("Mssql123"); - - private static String address; - private static Integer port; - private static String username, password; + public static final MSSQLServerContainer container = MssqlTestDBContainerManager.getMssqlDBForTest(); + + private static HikariDataSource sharedConnectionPool = null; + + private static final String CREATE_USER_TABLE_QUERY = "CREATE TABLE users (\n" + + " id int identity (1, 1) NOT NULL,\n" + + " username VARCHAR (50),\n" + + " password VARCHAR (50),\n" + + " email VARCHAR (355),\n" + + " spouse_dob DATE,\n" + + " dob DATE NOT NULL,\n" + + " time1 TIME NOT NULL,\n" + + " constraint pk_users_id primary key (id)\n" + + ")"; + + private static final String SET_IDENTITY_INSERT_USERS_QUERY = "SET IDENTITY_INSERT users ON;"; + + private static final String INSERT_USER1_QUERY = "INSERT INTO users (id, username, password, email, spouse_dob, dob, time1) VALUES (" + + "1, 'Jack', 'jill', '[email protected]', NULL, '2018-12-31'," + + " '18:32:45'" + + ")"; + + private static final String INSERT_USER2_QUERY = "INSERT INTO users (id, username, password, email, spouse_dob, dob, time1) VALUES (" + + "2, 'Jill', 'jack', '[email protected]', NULL, '2019-12-31'," + + " '15:45:30'" + + ")"; + + private static final String INSERT_USER3_QUERY = "INSERT INTO users (id, username, password, email, spouse_dob, dob, time1) VALUES (" + + "3, 'JackJill', 'jaji', '[email protected]', NULL, '2021-01-31'," + + " '15:45:30'" + + ")"; @BeforeAll public static void setUp() throws SQLException { - address = container.getContainerIpAddress(); - port = container.getMappedPort(1433); - username = container.getUsername(); - password = container.getPassword(); - - try (Connection connection = DriverManager.getConnection( - "jdbc:sqlserver://" + address + ":" + port + ";user=" + username + ";password=" + password + ";trustServerCertificate=true" - )) { - - try (Statement statement = connection.createStatement()) { - statement.execute("CREATE TABLE users (\n" + - " id int identity (1, 1) NOT NULL,\n" + - " username VARCHAR (50),\n" + - " password VARCHAR (50),\n" + - " email VARCHAR (355),\n" + - " spouse_dob DATE,\n" + - " dob DATE NOT NULL,\n" + - " time1 TIME NOT NULL,\n" + - " constraint pk_users_id primary key (id)\n" + - ")"); - - statement.execute("CREATE TABLE possessions (\n" + - " id int identity (1, 1) not null,\n" + - " title VARCHAR (50) NOT NULL,\n" + - " user_id int NOT NULL,\n" + - " constraint pk_possessions_id primary key (id),\n" + - " constraint user_fk foreign key (user_id) references users(id)\n" + - ")"); - } - - try (Statement statement = connection.createStatement()) { - statement.execute("SET identity_insert users ON;"); - } - - try (Statement statement = connection.createStatement()) { - statement.execute( - "INSERT INTO users (id, username, password, email, spouse_dob, dob, time1) VALUES (" + - "1, 'Jack', 'jill', '[email protected]', NULL, '2018-12-31'," + - " '18:32:45'" + - ")"); - } - - try (Statement statement = connection.createStatement()) { - statement.execute( - "INSERT INTO users (id, username, password, email, spouse_dob, dob, time1) VALUES (" + - "2, 'Jill', 'jack', '[email protected]', NULL, '2019-12-31'," + - " '15:45:30'" + - ")"); - } - - try (Statement statement = connection.createStatement()) { - statement.execute( - "INSERT INTO users (id, username, password, email, spouse_dob, dob, time1) VALUES (" + - "3, 'JackJill', 'jaji', '[email protected]', NULL, '2021-01-31'," + - " '15:45:30'" + - ")"); - } - - } + sharedConnectionPool = mssqlPluginExecutor.datasourceCreate(createDatasourceConfiguration(container)).block(); + createTablesForTest(); } - private DatasourceConfiguration createDatasourceConfiguration() { - DBAuth authDTO = new DBAuth(); - authDTO.setAuthType(DBAuth.Type.USERNAME_PASSWORD); - authDTO.setUsername(username); - authDTO.setPassword(password); - - Endpoint endpoint = new Endpoint(); - endpoint.setHost(address); - endpoint.setPort(port.longValue()); - - DatasourceConfiguration dsConfig = new DatasourceConfiguration(); - dsConfig.setAuthentication(authDTO); - dsConfig.setEndpoints(List.of(endpoint)); - - /* set ssl mode */ - dsConfig.setConnection(new com.appsmith.external.models.Connection()); - dsConfig.getConnection().setSsl(new SSLDetails()); - dsConfig.getConnection().getSsl().setAuthType(SSLDetails.AuthType.NO_VERIFY); - - return dsConfig; + private static void createTablesForTest() throws SQLException { + runSQLQueryOnMssqlTestDB(CREATE_USER_TABLE_QUERY, sharedConnectionPool); + runSQLQueryOnMssqlTestDB(SET_IDENTITY_INSERT_USERS_QUERY, sharedConnectionPool); + runSQLQueryOnMssqlTestDB(INSERT_USER1_QUERY, sharedConnectionPool); + runSQLQueryOnMssqlTestDB(INSERT_USER2_QUERY, sharedConnectionPool); + runSQLQueryOnMssqlTestDB(INSERT_USER3_QUERY, sharedConnectionPool); } @Test public void testDefaultPort() { Endpoint endpoint = new Endpoint(); - endpoint.setHost(address); + endpoint.setHost(container.getHost()); long defaultPort = MssqlPlugin.getPort(endpoint); @@ -171,9 +115,9 @@ public void testDefaultPort() { @Test public void testConnectMsSqlContainer() { - DatasourceConfiguration dsConfig = createDatasourceConfiguration(); + DatasourceConfiguration dsConfig = createDatasourceConfiguration(container); - Mono<HikariDataSource> dsConnectionMono = pluginExecutor.datasourceCreate(dsConfig); + Mono<HikariDataSource> dsConnectionMono = mssqlPluginExecutor.datasourceCreate(dsConfig); StepVerifier.create(dsConnectionMono) .assertNext(Assertions::assertNotNull) @@ -182,9 +126,9 @@ public void testConnectMsSqlContainer() { @Test public void testTestDatasource_withCorrectCredentials_returnsWithoutInvalids() { - DatasourceConfiguration dsConfig = createDatasourceConfiguration(); + DatasourceConfiguration dsConfig = createDatasourceConfiguration(container); - final Mono<DatasourceTestResult> testDatasourceMono = pluginExecutor.testDatasource(dsConfig); + final Mono<DatasourceTestResult> testDatasourceMono = mssqlPluginExecutor.testDatasource(dsConfig); StepVerifier.create(testDatasourceMono) .assertNext(datasourceTestResult -> { @@ -198,14 +142,14 @@ public void testTestDatasource_withCorrectCredentials_returnsWithoutInvalids() { @Test public void testAliasColumnNames() { - DatasourceConfiguration dsConfig = createDatasourceConfiguration(); - Mono<HikariDataSource> dsConnectionMono = pluginExecutor.datasourceCreate(dsConfig); + DatasourceConfiguration dsConfig = createDatasourceConfiguration(container); + Mono<HikariDataSource> dsConnectionMono = mssqlPluginExecutor.datasourceCreate(dsConfig); ActionConfiguration actionConfiguration = new ActionConfiguration(); actionConfiguration.setBody("SELECT id as user_id FROM users WHERE id = 1"); Mono<ActionExecutionResult> executeMono = dsConnectionMono - .flatMap(conn -> pluginExecutor.executeParameterized(conn, new ExecuteActionDTO(), dsConfig, actionConfiguration)); + .flatMap(conn -> mssqlPluginExecutor.executeParameterized(conn, new ExecuteActionDTO(), dsConfig, actionConfiguration)); StepVerifier.create(executeMono) .assertNext(result -> { @@ -225,14 +169,14 @@ public void testAliasColumnNames() { @Test public void testExecute() { - DatasourceConfiguration dsConfig = createDatasourceConfiguration(); - Mono<HikariDataSource> dsConnectionMono = pluginExecutor.datasourceCreate(dsConfig); + DatasourceConfiguration dsConfig = createDatasourceConfiguration(container); + Mono<HikariDataSource> dsConnectionMono = mssqlPluginExecutor.datasourceCreate(dsConfig); ActionConfiguration actionConfiguration = new ActionConfiguration(); actionConfiguration.setBody("SELECT * FROM users WHERE id = 1"); Mono<ActionExecutionResult> executeMono = dsConnectionMono - .flatMap(conn -> pluginExecutor.executeParameterized(conn, new ExecuteActionDTO(), dsConfig, actionConfiguration)); + .flatMap(conn -> mssqlPluginExecutor.executeParameterized(conn, new ExecuteActionDTO(), dsConfig, actionConfiguration)); StepVerifier.create(executeMono) .assertNext(result -> { @@ -277,13 +221,13 @@ public void testExecute() { @Test public void invalidTestConnectMsSqlContainer() { - DatasourceConfiguration dsConfig = createDatasourceConfiguration(); + DatasourceConfiguration dsConfig = createDatasourceConfiguration(container); // Set up random username and password and try to connect DBAuth auth = (DBAuth) dsConfig.getAuthentication(); auth.setUsername(new ObjectId().toString()); auth.setPassword(new ObjectId().toString()); - Mono<HikariDataSource> dsConnectionMono = pluginExecutor.datasourceCreate(dsConfig); + Mono<HikariDataSource> dsConnectionMono = mssqlPluginExecutor.datasourceCreate(dsConfig); StepVerifier.create(dsConnectionMono) .expectErrorMatches(throwable -> throwable instanceof AppsmithPluginException) @@ -292,7 +236,7 @@ public void invalidTestConnectMsSqlContainer() { @Test public void testPreparedStatementWithoutQuotes() { - DatasourceConfiguration dsConfig = createDatasourceConfiguration(); + DatasourceConfiguration dsConfig = createDatasourceConfiguration(container); ActionConfiguration actionConfiguration = new ActionConfiguration(); // First test with the binding not surrounded with quotes @@ -311,10 +255,10 @@ public void testPreparedStatementWithoutQuotes() { params.add(param); executeActionDTO.setParams(params); - Mono<HikariDataSource> connectionCreateMono = pluginExecutor.datasourceCreate(dsConfig).cache(); + Mono<HikariDataSource> connectionCreateMono = mssqlPluginExecutor.datasourceCreate(dsConfig).cache(); Mono<ActionExecutionResult> resultMono = connectionCreateMono - .flatMap(pool -> pluginExecutor.executeParameterized(pool, executeActionDTO, dsConfig, actionConfiguration)); + .flatMap(pool -> mssqlPluginExecutor.executeParameterized(pool, executeActionDTO, dsConfig, actionConfiguration)); StepVerifier.create(resultMono) .assertNext(result -> { @@ -358,7 +302,7 @@ public void testPreparedStatementWithoutQuotes() { @Test public void testPreparedStatementWithDoubleQuotes() { - DatasourceConfiguration dsConfig = createDatasourceConfiguration(); + DatasourceConfiguration dsConfig = createDatasourceConfiguration(container); ActionConfiguration actionConfiguration = new ActionConfiguration(); actionConfiguration.setBody("SELECT * FROM users where id = \"{{binding1}}\";"); @@ -376,10 +320,10 @@ public void testPreparedStatementWithDoubleQuotes() { params.add(param); executeActionDTO.setParams(params); - Mono<HikariDataSource> connectionCreateMono = pluginExecutor.datasourceCreate(dsConfig).cache(); + Mono<HikariDataSource> connectionCreateMono = mssqlPluginExecutor.datasourceCreate(dsConfig).cache(); Mono<ActionExecutionResult> resultMono = connectionCreateMono - .flatMap(pool -> pluginExecutor.executeParameterized(pool, executeActionDTO, dsConfig, actionConfiguration)); + .flatMap(pool -> mssqlPluginExecutor.executeParameterized(pool, executeActionDTO, dsConfig, actionConfiguration)); StepVerifier.create(resultMono) .assertNext(result -> { @@ -433,7 +377,7 @@ public void testPreparedStatementWithDoubleQuotes() { @Test public void testPreparedStatementWithSingleQuotes() { - DatasourceConfiguration dsConfig = createDatasourceConfiguration(); + DatasourceConfiguration dsConfig = createDatasourceConfiguration(container); ActionConfiguration actionConfiguration = new ActionConfiguration(); actionConfiguration.setBody("SELECT * FROM users where id = '{{binding1}}';"); @@ -451,10 +395,10 @@ public void testPreparedStatementWithSingleQuotes() { params.add(param); executeActionDTO.setParams(params); - Mono<HikariDataSource> connectionCreateMono = pluginExecutor.datasourceCreate(dsConfig).cache(); + Mono<HikariDataSource> connectionCreateMono = mssqlPluginExecutor.datasourceCreate(dsConfig).cache(); Mono<ActionExecutionResult> resultMono = connectionCreateMono - .flatMap(pool -> pluginExecutor.executeParameterized(pool, executeActionDTO, dsConfig, actionConfiguration)); + .flatMap(pool -> mssqlPluginExecutor.executeParameterized(pool, executeActionDTO, dsConfig, actionConfiguration)); StepVerifier.create(resultMono) .assertNext(result -> { @@ -491,7 +435,7 @@ public void testPreparedStatementWithSingleQuotes() { @Test public void testPreparedStatementWithNullStringValue() { - DatasourceConfiguration dsConfig = createDatasourceConfiguration(); + DatasourceConfiguration dsConfig = createDatasourceConfiguration(container); ActionConfiguration actionConfiguration = new ActionConfiguration(); actionConfiguration.setBody("UPDATE users set " + @@ -513,10 +457,10 @@ public void testPreparedStatementWithNullStringValue() { params.add(param); executeActionDTO.setParams(params); - Mono<HikariDataSource> connectionCreateMono = pluginExecutor.datasourceCreate(dsConfig).cache(); + Mono<HikariDataSource> connectionCreateMono = mssqlPluginExecutor.datasourceCreate(dsConfig).cache(); Mono<ActionExecutionResult> resultMono = connectionCreateMono - .flatMap(pool -> pluginExecutor.executeParameterized(pool, executeActionDTO, dsConfig, actionConfiguration)); + .flatMap(pool -> mssqlPluginExecutor.executeParameterized(pool, executeActionDTO, dsConfig, actionConfiguration)); StepVerifier.create(resultMono) .assertNext(result -> { @@ -526,7 +470,7 @@ public void testPreparedStatementWithNullStringValue() { actionConfiguration.setBody("SELECT * FROM users where id = 2;"); resultMono = connectionCreateMono - .flatMap(pool -> pluginExecutor.executeParameterized(pool, executeActionDTO, dsConfig, actionConfiguration)); + .flatMap(pool -> mssqlPluginExecutor.executeParameterized(pool, executeActionDTO, dsConfig, actionConfiguration)); StepVerifier.create(resultMono) .assertNext(result -> { @@ -542,7 +486,7 @@ public void testPreparedStatementWithNullStringValue() { @Test public void testPreparedStatementWithNullValue() { - DatasourceConfiguration dsConfig = createDatasourceConfiguration(); + DatasourceConfiguration dsConfig = createDatasourceConfiguration(container); ActionConfiguration actionConfiguration = new ActionConfiguration(); @@ -565,10 +509,10 @@ public void testPreparedStatementWithNullValue() { params.add(param); executeActionDTO.setParams(params); - Mono<HikariDataSource> connectionCreateMono = pluginExecutor.datasourceCreate(dsConfig).cache(); + Mono<HikariDataSource> connectionCreateMono = mssqlPluginExecutor.datasourceCreate(dsConfig).cache(); Mono<ActionExecutionResult> resultMono = connectionCreateMono - .flatMap(pool -> pluginExecutor.executeParameterized(pool, executeActionDTO, dsConfig, actionConfiguration)); + .flatMap(pool -> mssqlPluginExecutor.executeParameterized(pool, executeActionDTO, dsConfig, actionConfiguration)); StepVerifier.create(resultMono) .assertNext(result -> { @@ -578,7 +522,7 @@ public void testPreparedStatementWithNullValue() { actionConfiguration.setBody("SELECT * FROM users where id = 3;"); resultMono = connectionCreateMono - .flatMap(pool -> pluginExecutor.executeParameterized(pool, executeActionDTO, dsConfig, actionConfiguration)); + .flatMap(pool -> mssqlPluginExecutor.executeParameterized(pool, executeActionDTO, dsConfig, actionConfiguration)); StepVerifier.create(resultMono) .assertNext(result -> { @@ -594,14 +538,14 @@ public void testPreparedStatementWithNullValue() { @Test public void testDuplicateColumnNames() { - DatasourceConfiguration dsConfig = createDatasourceConfiguration(); - Mono<HikariDataSource> dsConnectionMono = pluginExecutor.datasourceCreate(dsConfig); + DatasourceConfiguration dsConfig = createDatasourceConfiguration(container); + Mono<HikariDataSource> dsConnectionMono = mssqlPluginExecutor.datasourceCreate(dsConfig); ActionConfiguration actionConfiguration = new ActionConfiguration(); actionConfiguration.setBody("SELECT id, username as id, password, email as password FROM users WHERE id = 1"); Mono<ActionExecutionResult> executeMono = dsConnectionMono - .flatMap(conn -> pluginExecutor.executeParameterized(conn, new ExecuteActionDTO(), dsConfig, actionConfiguration)); + .flatMap(conn -> mssqlPluginExecutor.executeParameterized(conn, new ExecuteActionDTO(), dsConfig, actionConfiguration)); StepVerifier.create(executeMono) .assertNext(result -> { @@ -633,7 +577,7 @@ public void testDuplicateColumnNames() { @Test public void testLimitQuery() { - DatasourceConfiguration dsConfig = createDatasourceConfiguration(); + DatasourceConfiguration dsConfig = createDatasourceConfiguration(container); ActionConfiguration actionConfiguration = new ActionConfiguration(); // First test with the binding not surrounded with quotes @@ -647,10 +591,10 @@ public void testLimitQuery() { List<Param> params = new ArrayList<>(); executeActionDTO.setParams(params); - Mono<HikariDataSource> connectionCreateMono = pluginExecutor.datasourceCreate(dsConfig).cache(); + Mono<HikariDataSource> connectionCreateMono = mssqlPluginExecutor.datasourceCreate(dsConfig).cache(); Mono<ActionExecutionResult> resultMono = connectionCreateMono - .flatMap(pool -> pluginExecutor.executeParameterized(pool, executeActionDTO, dsConfig, actionConfiguration)); + .flatMap(pool -> mssqlPluginExecutor.executeParameterized(pool, executeActionDTO, dsConfig, actionConfiguration)); StepVerifier.create(resultMono) .assertNext(result -> { @@ -661,7 +605,7 @@ public void testLimitQuery() { @Test public void testNumericStringHavingLeadingZeroWithPreparedStatement() { - DatasourceConfiguration dsConfig = createDatasourceConfiguration(); + DatasourceConfiguration dsConfig = createDatasourceConfiguration(container); ActionConfiguration actionConfiguration = new ActionConfiguration(); actionConfiguration.setBody("SELECT {{binding1}} as numeric_string;"); @@ -679,10 +623,10 @@ public void testNumericStringHavingLeadingZeroWithPreparedStatement() { params.add(param1); executeActionDTO.setParams(params); - Mono<HikariDataSource> connectionCreateMono = pluginExecutor.datasourceCreate(dsConfig).cache(); + Mono<HikariDataSource> connectionCreateMono = mssqlPluginExecutor.datasourceCreate(dsConfig).cache(); Mono<ActionExecutionResult> resultMono = connectionCreateMono - .flatMap(pool -> pluginExecutor.executeParameterized(pool, executeActionDTO, dsConfig, + .flatMap(pool -> mssqlPluginExecutor.executeParameterized(pool, executeActionDTO, dsConfig, actionConfiguration)); StepVerifier.create(resultMono) @@ -736,12 +680,12 @@ public void testSSLNoVerifyConnectionIsEncrypted() { List<Param> params = new ArrayList<>(); executeActionDTO.setParams(params); - DatasourceConfiguration dsConfig = createDatasourceConfiguration(); + DatasourceConfiguration dsConfig = createDatasourceConfiguration(container); dsConfig.getConnection().getSsl().setAuthType(SSLDetails.AuthType.NO_VERIFY); - Mono<HikariDataSource> connectionCreateMono = pluginExecutor.datasourceCreate(dsConfig); + Mono<HikariDataSource> connectionCreateMono = mssqlPluginExecutor.datasourceCreate(dsConfig); Mono<ActionExecutionResult> resultMono = connectionCreateMono - .flatMap(pool -> pluginExecutor.executeParameterized(pool, executeActionDTO, dsConfig, actionConfiguration)); + .flatMap(pool -> mssqlPluginExecutor.executeParameterized(pool, executeActionDTO, dsConfig, actionConfiguration)); StepVerifier.create(resultMono) .assertNext(result -> { @@ -772,12 +716,12 @@ public void testSSLDisabledConnectionIsNotEncrypted() { List<Param> params = new ArrayList<>(); executeActionDTO.setParams(params); - DatasourceConfiguration dsConfig = createDatasourceConfiguration(); + DatasourceConfiguration dsConfig = createDatasourceConfiguration(container); dsConfig.getConnection().getSsl().setAuthType(SSLDetails.AuthType.DISABLE); - Mono<HikariDataSource> connectionCreateMono = pluginExecutor.datasourceCreate(dsConfig); + Mono<HikariDataSource> connectionCreateMono = mssqlPluginExecutor.datasourceCreate(dsConfig); Mono<ActionExecutionResult> resultMono = connectionCreateMono - .flatMap(pool -> pluginExecutor.executeParameterized(pool, executeActionDTO, dsConfig, actionConfiguration)); + .flatMap(pool -> mssqlPluginExecutor.executeParameterized(pool, executeActionDTO, dsConfig, actionConfiguration)); StepVerifier.create(resultMono) .assertNext(result -> { diff --git a/app/server/appsmith-plugins/mssqlPlugin/src/test/java/com/external/plugins/MssqlTestDBContainerManager.java b/app/server/appsmith-plugins/mssqlPlugin/src/test/java/com/external/plugins/MssqlTestDBContainerManager.java new file mode 100644 index 000000000000..2d6fd3a0ef82 --- /dev/null +++ b/app/server/appsmith-plugins/mssqlPlugin/src/test/java/com/external/plugins/MssqlTestDBContainerManager.java @@ -0,0 +1,64 @@ +package com.external.plugins; + +import com.appsmith.external.models.DBAuth; +import com.appsmith.external.models.DatasourceConfiguration; +import com.appsmith.external.models.Endpoint; +import com.appsmith.external.models.SSLDetails; +import com.zaxxer.hikari.HikariDataSource; +import org.testcontainers.containers.MSSQLServerContainer; +import org.testcontainers.utility.DockerImageName; + +import java.sql.SQLException; +import java.sql.Statement; +import java.util.List; + +import static com.external.plugins.utils.MssqlDatasourceUtils.getConnectionFromConnectionPool; +import static com.external.plugins.utils.MssqlExecuteUtils.closeConnectionPostExecution; + +public class MssqlTestDBContainerManager { + + static MssqlPlugin.MssqlPluginExecutor mssqlPluginExecutor = new MssqlPlugin.MssqlPluginExecutor(); + + @SuppressWarnings("rawtypes") + public static MSSQLServerContainer getMssqlDBForTest() { + return new MSSQLServerContainer<>( + DockerImageName.parse("mcr.microsoft.com/azure-sql-edge:1.0.3").asCompatibleSubstituteFor("mcr.microsoft.com/mssql/server:2017-latest")) + .acceptLicense() + .withExposedPorts(1433) + .withPassword("Mssql123"); + } + + static DatasourceConfiguration createDatasourceConfiguration(MSSQLServerContainer container) { + String address = container.getHost(); + Integer port = container.getMappedPort(1433); + String username = container.getUsername(); + String password = container.getPassword(); + + DBAuth authDTO = new DBAuth(); + authDTO.setAuthType(DBAuth.Type.USERNAME_PASSWORD); + authDTO.setUsername(username); + authDTO.setPassword(password); + + Endpoint endpoint = new Endpoint(); + endpoint.setHost(address); + endpoint.setPort(port.longValue()); + + DatasourceConfiguration dsConfig = new DatasourceConfiguration(); + dsConfig.setAuthentication(authDTO); + dsConfig.setEndpoints(List.of(endpoint)); + + /* set ssl mode */ + dsConfig.setConnection(new com.appsmith.external.models.Connection()); + dsConfig.getConnection().setSsl(new SSLDetails()); + dsConfig.getConnection().getSsl().setAuthType(SSLDetails.AuthType.NO_VERIFY); + + return dsConfig; + } + + static void runSQLQueryOnMssqlTestDB(String sqlQuery, HikariDataSource sharedConnectionPool) throws SQLException { + java.sql.Connection connectionFromPool = getConnectionFromConnectionPool(sharedConnectionPool); + Statement statement = connectionFromPool.createStatement(); + statement.execute(sqlQuery); + closeConnectionPostExecution(null, statement, null, connectionFromPool); + } +}
d5bd30202efa8cd35923789603ab3fc36a3ff48d
2025-02-04 12:13:13
Valera Melnikov
fix: move ee utitls (#38986)
false
move ee utitls (#38986)
fix
diff --git a/app/client/packages/utils/src/file/getFileExtension.ts b/app/client/packages/utils/src/file/getFileExtension.ts new file mode 100644 index 000000000000..0610c2ec5031 --- /dev/null +++ b/app/client/packages/utils/src/file/getFileExtension.ts @@ -0,0 +1,9 @@ +/** + * @example + * getFileExtension("file.txt") => "txt" + * getFileExtension("file") => "" + * getFileExtension("file.txt.txt") => "txt" + */ +export const getFileExtension = (fileName: string): string => { + return fileName.split(".").pop() ?? ""; +}; diff --git a/app/client/packages/utils/src/file/getFileName.ts b/app/client/packages/utils/src/file/getFileName.ts new file mode 100644 index 000000000000..a216ddc7e863 --- /dev/null +++ b/app/client/packages/utils/src/file/getFileName.ts @@ -0,0 +1,9 @@ +/** + * @example + * getFileName("file.txt") => "file" + * getFileName("file") => "file" + * getFileName("file.txt.txt") => "file.txt" + */ +export const getFileName = (fileName: string): string => { + return fileName.split(".").slice(0, 1)?.[0] || ""; +}; diff --git a/app/client/packages/utils/src/file/index.ts b/app/client/packages/utils/src/file/index.ts new file mode 100644 index 000000000000..1539c6253b62 --- /dev/null +++ b/app/client/packages/utils/src/file/index.ts @@ -0,0 +1,2 @@ +export { getFileExtension } from "./getFileExtension"; +export { getFileName } from "./getFileName"; diff --git a/app/client/packages/utils/src/index.ts b/app/client/packages/utils/src/index.ts index 442a65511ef1..bde100269226 100644 --- a/app/client/packages/utils/src/index.ts +++ b/app/client/packages/utils/src/index.ts @@ -1,2 +1,5 @@ -export * from "./object"; export * from "./compose"; +export * from "./file"; +export * from "./object"; +export * from "./url"; +export * from "./validateApiPath"; diff --git a/app/client/packages/utils/src/url/buildUrlTextFragment.test.ts b/app/client/packages/utils/src/url/buildUrlTextFragment.test.ts new file mode 100644 index 000000000000..c35ceba7610f --- /dev/null +++ b/app/client/packages/utils/src/url/buildUrlTextFragment.test.ts @@ -0,0 +1,17 @@ +import { buildUrlTextFragment } from "./buildUrlTextFragment"; + +it("should return an empty array if no fragments are provided", () => { + expect(buildUrlTextFragment([])).toEqual(""); +}); + +it("should encode special characters", () => { + expect(buildUrlTextFragment(["text 1 = 2"])).toEqual( + ":~:text=text%201%20%3D%202", + ); +}); + +it("should join fragments", () => { + expect(buildUrlTextFragment(["text 1", "text 2"])).toEqual( + ":~:text=text%201&text=text%202", + ); +}); diff --git a/app/client/packages/utils/src/url/buildUrlTextFragment.ts b/app/client/packages/utils/src/url/buildUrlTextFragment.ts new file mode 100644 index 000000000000..f8a8a7e8eddf --- /dev/null +++ b/app/client/packages/utils/src/url/buildUrlTextFragment.ts @@ -0,0 +1,17 @@ +/** + * @example + * buildUrlTextFragment(["text1"]) // ":~:text=text1" + * buildUrlTextFragment(["text1", "text2"]) // ":~:text=text1&text=text2" + * buildUrlTextFragment([]) // "" + */ +export const buildUrlTextFragment = (fragments: string[]): string => { + if (fragments.length === 0) { + return ""; + } + + const textFragments = fragments + .map(encodeURIComponent) + .map((line) => `text=${line}`); + + return `:~:${textFragments.join("&")}`; +}; diff --git a/app/client/packages/utils/src/url/index.ts b/app/client/packages/utils/src/url/index.ts new file mode 100644 index 000000000000..73ed15204626 --- /dev/null +++ b/app/client/packages/utils/src/url/index.ts @@ -0,0 +1 @@ +export { buildUrlTextFragment } from "./buildUrlTextFragment"; diff --git a/app/client/packages/utils/src/validateApiPath/index.ts b/app/client/packages/utils/src/validateApiPath/index.ts new file mode 100644 index 000000000000..f0ebcab87f1e --- /dev/null +++ b/app/client/packages/utils/src/validateApiPath/index.ts @@ -0,0 +1 @@ +export { validateApiPath } from "./validateApiPath"; diff --git a/app/client/packages/utils/src/validateApiPath/validateApiPath.test.ts b/app/client/packages/utils/src/validateApiPath/validateApiPath.test.ts new file mode 100644 index 000000000000..67d765cb46f3 --- /dev/null +++ b/app/client/packages/utils/src/validateApiPath/validateApiPath.test.ts @@ -0,0 +1,17 @@ +import { validateApiPath } from "./validateApiPath"; + +describe("validateApiPath", () => { + it("should return the path if it starts with 'https://'", () => { + const validPath = "https://example.com"; + + expect(validateApiPath(validPath)).toBe(validPath); + }); + + it("should throw an error if the path does not start with 'https://'", () => { + const invalidPath = "example.com"; + + expect(() => validateApiPath(invalidPath)).toThrow( + "The example.com path must start with 'https://'.", + ); + }); +}); diff --git a/app/client/packages/utils/src/validateApiPath/validateApiPath.ts b/app/client/packages/utils/src/validateApiPath/validateApiPath.ts new file mode 100644 index 000000000000..d84fb93ae995 --- /dev/null +++ b/app/client/packages/utils/src/validateApiPath/validateApiPath.ts @@ -0,0 +1,15 @@ +/** + * Validates if the given path starts with "https://". + * Throws an error if the path does not start with "https://". + * + * @param path - The path to validate. + * @returns path if the path starts with "https://". + * @throws Error if the path does not start with "https://". + */ +export const validateApiPath = (path: string): string => { + if (path.startsWith("https://")) { + return path; + } else { + throw new Error(`The ${path} path must start with 'https://'.`); + } +};
12d1482a477b0e74be9590f464211504cb36b926
2023-09-25 15:36:24
Ankita Kinger
fix: Removing saas integrations section on datasources page for airgap (#27590)
false
Removing saas integrations section on datasources page for airgap (#27590)
fix
diff --git a/app/client/src/pages/Editor/IntegrationEditor/IntegrationsHomeScreen.tsx b/app/client/src/pages/Editor/IntegrationEditor/IntegrationsHomeScreen.tsx index 1367848ced98..de30120d4085 100644 --- a/app/client/src/pages/Editor/IntegrationEditor/IntegrationsHomeScreen.tsx +++ b/app/client/src/pages/Editor/IntegrationEditor/IntegrationsHomeScreen.tsx @@ -37,6 +37,7 @@ import Debugger, { import { showDebuggerFlag } from "selectors/debuggerSelectors"; import AnalyticsUtil from "utils/AnalyticsUtil"; import { DatasourceCreateEntryPoints } from "constants/Datasource"; +import { isAirgapped } from "@appsmith/utils/airgapHelpers"; const HeaderFlex = styled.div` font-size: 20px; @@ -219,6 +220,7 @@ function CreateNewSaasIntegration({ }: any) { const newSaasAPIRef = useRef<HTMLDivElement>(null); const isMounted = useRef(false); + const isAirgappedInstance = isAirgapped(); useEffect(() => { if (active && newSaasAPIRef.current) { @@ -233,7 +235,7 @@ function CreateNewSaasIntegration({ isMounted.current = true; } }, [active]); - return ( + return !isAirgappedInstance ? ( <div id="new-saas-api" ref={newSaasAPIRef}> <Text type={TextType.H2}>Saas Integrations</Text> <NewApiScreen @@ -245,7 +247,7 @@ function CreateNewSaasIntegration({ showUnsupportedPluginDialog={showUnsupportedPluginDialog} /> </div> - ); + ) : null; } function CreateNewDatasource({
de66a50f6c62736732e57e37a38607fd02ce59a4
2023-07-27 16:13:37
Rajat Agrawal
chore: Add property path to WidgetErrors (#25711)
false
Add property path to WidgetErrors (#25711)
chore
diff --git a/app/client/src/utils/widgetRenderUtils.test.ts b/app/client/src/utils/widgetRenderUtils.test.ts index 28ec42779bfe..0737707fb7db 100644 --- a/app/client/src/utils/widgetRenderUtils.test.ts +++ b/app/client/src/utils/widgetRenderUtils.test.ts @@ -41,7 +41,7 @@ describe("createCanvasWidget functionality", () => { const dataTree = { __evaluation__: { errors: { - text: [ + propertyPath: [ { errorMessage: { name: "Validation Error", @@ -64,6 +64,7 @@ describe("createCanvasWidget functionality", () => { expect(response.errors[0].message).toStrictEqual("Error Message"); expect(response.errors[0].stack).toStrictEqual("Error Message Stack"); expect(response.errors[0].type).toStrictEqual("property"); + expect(response.errors[0].path).toStrictEqual("propertyPath"); }); }); diff --git a/app/client/src/utils/widgetRenderUtils.tsx b/app/client/src/utils/widgetRenderUtils.tsx index e35444485db7..985b979a2783 100644 --- a/app/client/src/utils/widgetRenderUtils.tsx +++ b/app/client/src/utils/widgetRenderUtils.tsx @@ -65,19 +65,24 @@ function widgetErrorsFromStaticProps(props: Record<string, unknown>) { string, DataTreeError[] >; - const evaluationErrors: DataTreeError[] = - Object.values(evaluationErrorMap).flat(); const widgetErrors: WidgetError[] = []; - for (const evalError of evaluationErrors) { - const widgetError: WidgetError = { - name: evalError.errorMessage.name, - message: evalError.errorMessage.message, - stack: evalError.raw, - type: "property", - }; - - widgetErrors.push(widgetError); - } + + Object.keys(evaluationErrorMap).forEach((propertyPath) => { + const propertyErrors = evaluationErrorMap[propertyPath]; + + propertyErrors.forEach((evalError) => { + const widgetError: WidgetError = { + name: evalError.errorMessage.name, + message: evalError.errorMessage.message, + stack: evalError.raw, + type: "property", + path: propertyPath, + }; + + widgetErrors.push(widgetError); + }); + }); + return widgetErrors; } diff --git a/app/client/src/widgets/BaseWidget.tsx b/app/client/src/widgets/BaseWidget.tsx index a7d5b777e1ce..67725e2e86c7 100644 --- a/app/client/src/widgets/BaseWidget.tsx +++ b/app/client/src/widgets/BaseWidget.tsx @@ -871,6 +871,7 @@ export const WIDGET_DISPLAY_PROPS = { }; export interface WidgetError extends Error { type: "property" | "configuration" | "other"; + path?: string; } export interface WidgetErrorProps { errors?: WidgetError[];
912246232d5292cc3cdbdf4ec6d9b32b7a6c938d
2022-12-15 14:53:02
sidhantgoel
chore: Splitted import export service code for V2 (#18927)
false
Splitted import export service code for V2 (#18927)
chore
diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/GitServiceImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/GitServiceImpl.java index 230e6028a45e..6c84da3318d9 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/GitServiceImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/GitServiceImpl.java @@ -16,6 +16,8 @@ import com.appsmith.server.solutions.PagePermission; import io.sentry.protocol.App; import lombok.extern.slf4j.Slf4j; + +import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.context.annotation.Import; import org.springframework.stereotype.Service; @@ -32,7 +34,7 @@ public GitServiceImpl(UserService userService, NewActionService newActionService, ActionCollectionService actionCollectionService, GitFileUtils fileUtils, - ImportExportApplicationService importExportApplicationService, + @Qualifier("importExportServiceCEImplV2") ImportExportApplicationService importExportApplicationService, GitExecutor gitExecutor, ResponseUtils responseUtils, EmailConfig emailConfig, diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ImportExportApplicationServiceImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ImportExportApplicationServiceImpl.java index 15e519925a96..3690b58d3db3 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ImportExportApplicationServiceImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ImportExportApplicationServiceImpl.java @@ -19,10 +19,12 @@ import com.appsmith.server.services.WorkspaceService; import com.appsmith.server.solutions.ce.ImportExportApplicationServiceCEImpl; import lombok.extern.slf4j.Slf4j; +import org.springframework.context.annotation.Primary; import org.springframework.stereotype.Component; @Slf4j @Component +@Primary public class ImportExportApplicationServiceImpl extends ImportExportApplicationServiceCEImpl implements ImportExportApplicationService { public ImportExportApplicationServiceImpl(DatasourceService datasourceService, diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ImportExportApplicationServiceImplV2.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ImportExportApplicationServiceImplV2.java new file mode 100644 index 000000000000..d86b8583e010 --- /dev/null +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ImportExportApplicationServiceImplV2.java @@ -0,0 +1,62 @@ +package com.appsmith.server.solutions; + +import com.appsmith.server.helpers.PolicyUtils; +import com.appsmith.server.repositories.ActionCollectionRepository; +import com.appsmith.server.repositories.DatasourceRepository; +import com.appsmith.server.repositories.NewActionRepository; +import com.appsmith.server.repositories.NewPageRepository; +import com.appsmith.server.repositories.PluginRepository; +import com.appsmith.server.services.ActionCollectionService; +import com.appsmith.server.services.AnalyticsService; +import com.appsmith.server.services.ApplicationPageService; +import com.appsmith.server.services.ApplicationService; +import com.appsmith.server.services.DatasourceService; +import com.appsmith.server.services.NewActionService; +import com.appsmith.server.services.NewPageService; +import com.appsmith.server.services.SequenceService; +import com.appsmith.server.services.SessionUserService; +import com.appsmith.server.services.ThemeService; +import com.appsmith.server.services.WorkspaceService; +import com.appsmith.server.solutions.ce.ImportExportApplicationServiceCEImplV2; + +import lombok.extern.slf4j.Slf4j; + +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.stereotype.Component; + +@Slf4j +@Component +@Qualifier("importExportServiceCEImplV2") +public class ImportExportApplicationServiceImplV2 extends ImportExportApplicationServiceCEImplV2 implements ImportExportApplicationService { + + public ImportExportApplicationServiceImplV2(DatasourceService datasourceService, + SessionUserService sessionUserService, + NewActionRepository newActionRepository, + DatasourceRepository datasourceRepository, + PluginRepository pluginRepository, + WorkspaceService workspaceService, + ApplicationService applicationService, + NewPageService newPageService, + ApplicationPageService applicationPageService, + NewPageRepository newPageRepository, + NewActionService newActionService, + SequenceService sequenceService, + ExamplesWorkspaceCloner examplesWorkspaceCloner, + ActionCollectionRepository actionCollectionRepository, + ActionCollectionService actionCollectionService, + ThemeService themeService, + PolicyUtils policyUtils, + AnalyticsService analyticsService, + DatasourcePermission datasourcePermission, + WorkspacePermission workspacePermission, + ApplicationPermission applicationPermission, + PagePermission pagePermission, + ActionPermission actionPermission) { + + super(datasourceService, sessionUserService, newActionRepository, datasourceRepository, pluginRepository, + workspaceService, applicationService, newPageService, applicationPageService, newPageRepository, + newActionService, sequenceService, examplesWorkspaceCloner, actionCollectionRepository, + actionCollectionService, themeService, policyUtils, analyticsService, datasourcePermission, + workspacePermission, applicationPermission, pagePermission, actionPermission); + } +} diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ce/ImportExportApplicationServiceCEImplV2.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ce/ImportExportApplicationServiceCEImplV2.java new file mode 100644 index 000000000000..0934177453d9 --- /dev/null +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ce/ImportExportApplicationServiceCEImplV2.java @@ -0,0 +1,2174 @@ +package com.appsmith.server.solutions.ce; + +import com.appsmith.external.constants.AnalyticsEvents; +import com.appsmith.external.converters.GsonISOStringToInstantConverter; +import com.appsmith.external.helpers.Stopwatch; +import com.appsmith.external.models.AuthenticationDTO; +import com.appsmith.external.models.AuthenticationResponse; +import com.appsmith.external.models.BaseDomain; +import com.appsmith.external.models.BasicAuth; +import com.appsmith.external.models.DBAuth; +import com.appsmith.external.models.Datasource; +import com.appsmith.external.models.DatasourceConfiguration; +import com.appsmith.external.models.DecryptedSensitiveFields; +import com.appsmith.external.models.DefaultResources; +import com.appsmith.external.models.OAuth2; +import com.appsmith.server.acl.AclPermission; +import com.appsmith.server.constants.FieldName; +import com.appsmith.server.constants.ResourceModes; +import com.appsmith.server.constants.SerialiseApplicationObjective; +import com.appsmith.server.domains.ActionCollection; +import com.appsmith.server.domains.Application; +import com.appsmith.server.domains.ApplicationPage; +import com.appsmith.server.domains.Layout; +import com.appsmith.server.domains.NewAction; +import com.appsmith.server.domains.NewPage; +import com.appsmith.server.domains.Theme; +import com.appsmith.server.domains.User; +import com.appsmith.server.domains.Workspace; +import com.appsmith.server.domains.GitApplicationMetadata; +import com.appsmith.server.dtos.ActionCollectionDTO; +import com.appsmith.external.models.ActionDTO; +import com.appsmith.server.dtos.ApplicationImportDTO; +import com.appsmith.server.dtos.ApplicationJson; +import com.appsmith.server.dtos.ExportFileDTO; +import com.appsmith.server.dtos.PageDTO; +import com.appsmith.server.exceptions.AppsmithError; +import com.appsmith.server.exceptions.AppsmithException; +import com.appsmith.server.helpers.DefaultResourcesUtils; +import com.appsmith.server.helpers.PolicyUtils; +import com.appsmith.server.helpers.TextUtils; +import com.appsmith.server.migrations.ApplicationVersion; +import com.appsmith.server.migrations.JsonSchemaMigration; +import com.appsmith.server.migrations.JsonSchemaVersions; +import com.appsmith.server.repositories.ActionCollectionRepository; +import com.appsmith.server.repositories.DatasourceRepository; +import com.appsmith.server.repositories.NewActionRepository; +import com.appsmith.server.repositories.NewPageRepository; +import com.appsmith.server.repositories.PluginRepository; +import com.appsmith.server.services.ActionCollectionService; +import com.appsmith.server.services.AnalyticsService; +import com.appsmith.server.services.ApplicationPageService; +import com.appsmith.server.services.ApplicationService; +import com.appsmith.server.services.DatasourceService; +import com.appsmith.server.services.NewActionService; +import com.appsmith.server.services.NewPageService; +import com.appsmith.server.services.SequenceService; +import com.appsmith.server.services.SessionUserService; +import com.appsmith.server.services.ThemeService; +import com.appsmith.server.services.WorkspaceService; +import com.appsmith.server.solutions.ActionPermission; +import com.appsmith.server.solutions.ApplicationPermission; +import com.appsmith.server.solutions.DatasourcePermission; +import com.appsmith.server.solutions.ExamplesWorkspaceCloner; +import com.appsmith.server.solutions.PagePermission; +import com.appsmith.server.solutions.WorkspacePermission; +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.reflect.TypeToken; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.apache.commons.collections.CollectionUtils; +import org.apache.commons.lang.StringUtils; +import org.bson.types.ObjectId; +import org.springframework.core.io.buffer.DataBufferUtils; +import org.springframework.dao.DuplicateKeyException; +import org.springframework.http.ContentDisposition; +import org.springframework.http.HttpHeaders; +import org.springframework.http.MediaType; +import org.springframework.http.codec.multipart.Part; +import reactor.core.publisher.Flux; +import reactor.core.publisher.Mono; +import reactor.util.function.Tuple2; + +import java.lang.reflect.Type; +import java.nio.charset.StandardCharsets; +import java.time.Instant; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.stream.Collectors; + +import static com.appsmith.external.helpers.AppsmithBeanUtils.copyNestedNonNullProperties; +import static com.appsmith.server.acl.AclPermission.MANAGE_ACTIONS; +import static com.appsmith.server.acl.AclPermission.MANAGE_PAGES; +import static com.appsmith.server.acl.AclPermission.READ_ACTIONS; +import static com.appsmith.server.acl.AclPermission.READ_PAGES; +import static com.appsmith.server.acl.AclPermission.READ_THEMES; +import static com.appsmith.server.constants.ResourceModes.EDIT; +import static com.appsmith.server.constants.ResourceModes.VIEW; +import static com.appsmith.external.constants.GitConstants.NAME_SEPARATOR; +import static java.lang.Boolean.TRUE; + +@Slf4j +@RequiredArgsConstructor +public class ImportExportApplicationServiceCEImplV2 implements ImportExportApplicationServiceCE { + + private final DatasourceService datasourceService; + private final SessionUserService sessionUserService; + private final NewActionRepository newActionRepository; + private final DatasourceRepository datasourceRepository; + private final PluginRepository pluginRepository; + private final WorkspaceService workspaceService; + private final ApplicationService applicationService; + private final NewPageService newPageService; + private final ApplicationPageService applicationPageService; + private final NewPageRepository newPageRepository; + private final NewActionService newActionService; + private final SequenceService sequenceService; + private final ExamplesWorkspaceCloner examplesWorkspaceCloner; + private final ActionCollectionRepository actionCollectionRepository; + private final ActionCollectionService actionCollectionService; + private final ThemeService themeService; + private final PolicyUtils policyUtils; + private final AnalyticsService analyticsService; + private final DatasourcePermission datasourcePermission; + private final WorkspacePermission workspacePermission; + private final ApplicationPermission applicationPermission; + private final PagePermission pagePermission; + private final ActionPermission actionPermission; + + private static final Set<MediaType> ALLOWED_CONTENT_TYPES = Set.of(MediaType.APPLICATION_JSON); + private static final String INVALID_JSON_FILE = "invalid json file"; + + /** + * This function will give the application resource to rebuild the application in import application flow + * + * @param applicationId which needs to be exported + * @return application reference from which entire application can be rehydrated + */ + public Mono<ApplicationJson> exportApplicationById(String applicationId, SerialiseApplicationObjective serialiseFor) { + + // Start the stopwatch to log the execution time + Stopwatch stopwatch = new Stopwatch(AnalyticsEvents.EXPORT.getEventName()); + /* + 1. Fetch application by id + 2. Fetch pages from the application + 3. Fetch datasources from workspace + 4. Fetch actions from the application + 5. Filter out relevant datasources using actions reference + 6. Fetch action collections from the application + */ + ApplicationJson applicationJson = new ApplicationJson(); + Map<String, String> pluginMap = new HashMap<>(); + Map<String, String> datasourceIdToNameMap = new HashMap<>(); + Map<String, String> pageIdToNameMap = new HashMap<>(); + Map<String, String> actionIdToNameMap = new HashMap<>(); + Map<String, String> collectionIdToNameMap = new HashMap<>(); + + if (applicationId == null || applicationId.isEmpty()) { + return Mono.error(new AppsmithException(AppsmithError.INVALID_PARAMETER, FieldName.APPLICATION_ID)); + } + + // Check permissions depending upon the serialization objective: + // Git-sync => Manage permission + // Share application + // : Normal apps => Export permission + // : Sample apps where datasource config needs to be shared => Read permission + + boolean isGitSync = SerialiseApplicationObjective.VERSION_CONTROL.equals(serialiseFor); + + // If Git-sync, then use MANAGE_APPLICATIONS, else use EXPORT_APPLICATION permission to fetch application + AclPermission permission = isGitSync ? applicationPermission.getEditPermission() : applicationPermission.getExportPermission(); + + Mono<User> currentUserMono = sessionUserService.getCurrentUser().cache(); + + Mono<Application> applicationMono = + // Find the application with appropriate permission + applicationService.findById(applicationId, permission) + // Find the application without permissions if it is a template application + .switchIfEmpty(applicationService.findByIdAndExportWithConfiguration(applicationId, TRUE)) + .switchIfEmpty(Mono.error( + new AppsmithException(AppsmithError.NO_RESOURCE_FOUND, FieldName.APPLICATION_ID, applicationId)) + ) + .map(application -> { + if (!TRUE.equals(application.getExportWithConfiguration())) { + // Explicitly setting the boolean to avoid NPE for future checks + application.setExportWithConfiguration(false); + } + + return application; + }); + + // Set json schema version which will be used to check the compatibility while importing the JSON + applicationJson.setServerSchemaVersion(JsonSchemaVersions.serverVersion); + applicationJson.setClientSchemaVersion(JsonSchemaVersions.clientVersion); + + Mono<Theme> defaultThemeMono = themeService.getSystemTheme(Theme.DEFAULT_THEME_NAME) + .map(theme -> { + log.debug("Default theme found: {}", theme.getName()); + return theme; + }) + .cache(); + + return pluginRepository + .findAll() + .map(plugin -> { + pluginMap.put(plugin.getId(), plugin.getPluginName() == null ? plugin.getPackageName() : plugin.getPluginName()); + return plugin; + }) + .then(applicationMono) + .flatMap(application -> themeService.getThemeById(application.getEditModeThemeId(), READ_THEMES) + .switchIfEmpty(defaultThemeMono) // setting default theme if theme is missing + .zipWith(themeService + .getThemeById(application.getPublishedModeThemeId(), READ_THEMES) + .switchIfEmpty(defaultThemeMono)// setting default theme if theme is missing + ) + .map(themesTuple -> { + Theme editModeTheme = themesTuple.getT1(); + Theme publishedModeTheme = themesTuple.getT2(); + editModeTheme.sanitiseToExportDBObject(); + publishedModeTheme.sanitiseToExportDBObject(); + applicationJson.setEditModeTheme(editModeTheme); + applicationJson.setPublishedTheme(publishedModeTheme); + return themesTuple; + }).thenReturn(application)) + .flatMap(application -> { + + // Refactor application to remove the ids + final String workspaceId = application.getWorkspaceId(); + GitApplicationMetadata gitApplicationMetadata = application.getGitApplicationMetadata(); + Instant applicationLastCommittedAt = gitApplicationMetadata != null ? gitApplicationMetadata.getLastCommittedAt() : null; + boolean isClientSchemaMigrated = !JsonSchemaVersions.clientVersion.equals(application.getClientSchemaVersion()); + boolean isServerSchemaMigrated = !JsonSchemaVersions.serverVersion.equals(application.getServerSchemaVersion()); + examplesWorkspaceCloner.makePristine(application); + application.sanitiseToExportDBObject(); + applicationJson.setExportedApplication(application); + Set<String> dbNamesUsedInActions = new HashSet<>(); + + Flux<NewPage> pageFlux = TRUE.equals(application.getExportWithConfiguration()) + ? newPageRepository.findByApplicationId(applicationId, pagePermission.getReadPermission()) + : newPageRepository.findByApplicationId(applicationId, pagePermission.getEditPermission()); + + return pageFlux + .collectList() + .flatMap(newPageList -> { + // Extract mongoEscapedWidgets from pages and save it to applicationJson object as this + // field is JsonIgnored. Also remove any ids those are present in the page objects + + Set<String> updatedPageSet = new HashSet<String>(); + newPageList.forEach(newPage -> { + if (newPage.getUnpublishedPage() != null) { + pageIdToNameMap.put( + newPage.getId() + EDIT, newPage.getUnpublishedPage().getName() + ); + PageDTO unpublishedPageDTO = newPage.getUnpublishedPage(); + if (!CollectionUtils.isEmpty(unpublishedPageDTO.getLayouts())) { + unpublishedPageDTO.getLayouts().forEach(layout -> { + layout.setId(unpublishedPageDTO.getName()); + }); + } + } + + if (newPage.getPublishedPage() != null) { + pageIdToNameMap.put( + newPage.getId() + VIEW, newPage.getPublishedPage().getName() + ); + PageDTO publishedPageDTO = newPage.getPublishedPage(); + if (!CollectionUtils.isEmpty(publishedPageDTO.getLayouts())) { + publishedPageDTO.getLayouts().forEach(layout -> { + layout.setId(publishedPageDTO.getName()); + }); + } + } + // Including updated pages list for git file storage + Instant newPageUpdatedAt = newPage.getUpdatedAt(); + boolean isNewPageUpdated = isClientSchemaMigrated || isServerSchemaMigrated || applicationLastCommittedAt == null || newPageUpdatedAt == null || applicationLastCommittedAt.isBefore(newPageUpdatedAt); + String newPageName = newPage.getUnpublishedPage() != null ? newPage.getUnpublishedPage().getName() : newPage.getPublishedPage() != null ? newPage.getPublishedPage().getName() : null; + if (isNewPageUpdated && newPageName != null) { + updatedPageSet.add(newPageName); + } + newPage.sanitiseToExportDBObject(); + }); + applicationJson.setPageList(newPageList); + applicationJson.setUpdatedResources(new HashMap<String, Set<String>>() {{ + put(FieldName.PAGE_LIST, updatedPageSet); + }}); + + Flux<Datasource> datasourceFlux = TRUE.equals(application.getExportWithConfiguration()) + ? datasourceRepository.findAllByWorkspaceId(workspaceId, datasourcePermission.getReadPermission()) + : datasourceRepository.findAllByWorkspaceId(workspaceId, datasourcePermission.getEditPermission()); + + return datasourceFlux.collectList(); + }) + .flatMapMany(datasourceList -> { + datasourceList.forEach(datasource -> + datasourceIdToNameMap.put(datasource.getId(), datasource.getName())); + applicationJson.setDatasourceList(datasourceList); + + Flux<ActionCollection> actionCollectionFlux = TRUE.equals(application.getExportWithConfiguration()) + ? actionCollectionRepository.findByApplicationId(applicationId, actionPermission.getReadPermission(), null) + : actionCollectionRepository.findByApplicationId(applicationId, actionPermission.getEditPermission(), null); + return actionCollectionFlux; + }) + .map(actionCollection -> { + // Remove references to ids since the serialized version does not have this information + actionCollection.setWorkspaceId(null); + actionCollection.setPolicies(null); + actionCollection.setApplicationId(null); + // Set unique ids for actionCollection, also populate collectionIdToName map which will + // be used to replace collectionIds in action + if (actionCollection.getUnpublishedCollection() != null) { + ActionCollectionDTO actionCollectionDTO = actionCollection.getUnpublishedCollection(); + actionCollectionDTO.setPageId(pageIdToNameMap.get(actionCollectionDTO.getPageId() + EDIT)); + actionCollectionDTO.setPluginId(pluginMap.get(actionCollectionDTO.getPluginId())); + + final String updatedCollectionId = actionCollectionDTO.getPageId() + "_" + actionCollectionDTO.getName(); + collectionIdToNameMap.put(actionCollection.getId(), updatedCollectionId); + actionCollection.setId(updatedCollectionId); + } + if (actionCollection.getPublishedCollection() != null) { + ActionCollectionDTO actionCollectionDTO = actionCollection.getPublishedCollection(); + actionCollectionDTO.setPageId(pageIdToNameMap.get(actionCollectionDTO.getPageId() + VIEW)); + actionCollectionDTO.setPluginId(pluginMap.get(actionCollectionDTO.getPluginId())); + + if (!collectionIdToNameMap.containsValue(actionCollection.getId())) { + final String updatedCollectionId = actionCollectionDTO.getPageId() + "_" + actionCollectionDTO.getName(); + collectionIdToNameMap.put(actionCollection.getId(), updatedCollectionId); + actionCollection.setId(updatedCollectionId); + } + } + return actionCollection; + }) + .collectList() + .flatMapMany(actionCollections -> { + // This object won't have the list of actions but we don't care about that today + // Because the actions will have a reference to the collection + + Set<String> updatedActionCollectionSet = new HashSet<>(); + actionCollections.forEach(actionCollection -> { + ActionCollectionDTO publishedActionCollectionDTO = actionCollection.getPublishedCollection(); + ActionCollectionDTO unpublishedActionCollectionDTO = actionCollection.getUnpublishedCollection(); + ActionCollectionDTO actionCollectionDTO = unpublishedActionCollectionDTO != null ? unpublishedActionCollectionDTO : publishedActionCollectionDTO; + String actionCollectionName = actionCollectionDTO != null ? actionCollectionDTO.getName() + NAME_SEPARATOR + actionCollectionDTO.getPageId() : null; + Instant actionCollectionUpdatedAt = actionCollection.getUpdatedAt(); + boolean isActionCollectionUpdated = isClientSchemaMigrated || isServerSchemaMigrated || applicationLastCommittedAt == null || actionCollectionUpdatedAt == null || applicationLastCommittedAt.isBefore(actionCollectionUpdatedAt); + if (isActionCollectionUpdated && actionCollectionName != null) { + updatedActionCollectionSet.add(actionCollectionName); + } + actionCollection.sanitiseToExportDBObject(); + }); + + applicationJson.setActionCollectionList(actionCollections); + applicationJson.getUpdatedResources().put(FieldName.ACTION_COLLECTION_LIST, updatedActionCollectionSet); + + Flux<NewAction> actionFlux = TRUE.equals(application.getExportWithConfiguration()) + ? newActionRepository.findByApplicationId(applicationId, actionPermission.getReadPermission(), null) + : newActionRepository.findByApplicationId(applicationId, actionPermission.getEditPermission(), null); + + return actionFlux; + }) + .map(newAction -> { + newAction.setPluginId(pluginMap.get(newAction.getPluginId())); + newAction.setWorkspaceId(null); + newAction.setPolicies(null); + newAction.setApplicationId(null); + dbNamesUsedInActions.add( + sanitizeDatasourceInActionDTO(newAction.getPublishedAction(), datasourceIdToNameMap, pluginMap, null, true) + ); + dbNamesUsedInActions.add( + sanitizeDatasourceInActionDTO(newAction.getUnpublishedAction(), datasourceIdToNameMap, pluginMap, null, true) + ); + + // Set unique id for action + if (newAction.getUnpublishedAction() != null) { + ActionDTO actionDTO = newAction.getUnpublishedAction(); + actionDTO.setPageId(pageIdToNameMap.get(actionDTO.getPageId() + EDIT)); + + if (!StringUtils.isEmpty(actionDTO.getCollectionId()) + && collectionIdToNameMap.containsKey(actionDTO.getCollectionId())) { + actionDTO.setCollectionId(collectionIdToNameMap.get(actionDTO.getCollectionId())); + } + + final String updatedActionId = actionDTO.getPageId() + "_" + actionDTO.getValidName(); + actionIdToNameMap.put(newAction.getId(), updatedActionId); + newAction.setId(updatedActionId); + } + if (newAction.getPublishedAction() != null) { + ActionDTO actionDTO = newAction.getPublishedAction(); + actionDTO.setPageId(pageIdToNameMap.get(actionDTO.getPageId() + VIEW)); + + if (!StringUtils.isEmpty(actionDTO.getCollectionId()) + && collectionIdToNameMap.containsKey(actionDTO.getCollectionId())) { + actionDTO.setCollectionId(collectionIdToNameMap.get(actionDTO.getCollectionId())); + } + + if (!actionIdToNameMap.containsValue(newAction.getId())) { + final String updatedActionId = actionDTO.getPageId() + "_" + actionDTO.getValidName(); + actionIdToNameMap.put(newAction.getId(), updatedActionId); + newAction.setId(updatedActionId); + } + } + return newAction; + }) + .collectList() + .map(actionList -> { + Set<String> updatedActionSet = new HashSet<>(); + actionList.forEach(newAction -> { + ActionDTO unpublishedActionDTO = newAction.getUnpublishedAction(); + ActionDTO publishedActionDTO = newAction.getPublishedAction(); + ActionDTO actionDTO = unpublishedActionDTO != null ? unpublishedActionDTO : publishedActionDTO; + String newActionName = actionDTO != null ? actionDTO.getValidName() + NAME_SEPARATOR + actionDTO.getPageId() : null; + Instant newActionUpdatedAt = newAction.getUpdatedAt(); + boolean isNewActionUpdated = isClientSchemaMigrated || isServerSchemaMigrated || applicationLastCommittedAt == null || newActionUpdatedAt == null || applicationLastCommittedAt.isBefore(newActionUpdatedAt); + if (isNewActionUpdated && newActionName != null) { + updatedActionSet.add(newActionName); + } + newAction.sanitiseToExportDBObject(); + }); + applicationJson.getUpdatedResources().put(FieldName.ACTION_LIST, updatedActionSet); + applicationJson.setActionList(actionList); + // This is where we're removing global datasources that are unused in this application + applicationJson + .getDatasourceList() + .removeIf(datasource -> !dbNamesUsedInActions.contains(datasource.getName())); + + // Save decrypted fields for datasources for internally used sample apps and templates only + // when serialising for file sharing + if (TRUE.equals(application.getExportWithConfiguration()) && SerialiseApplicationObjective.SHARE.equals(serialiseFor)) { + // Save decrypted fields for datasources + Map<String, DecryptedSensitiveFields> decryptedFields = new HashMap<>(); + applicationJson.getDatasourceList().forEach(datasource -> { + decryptedFields.put(datasource.getName(), getDecryptedFields(datasource)); + datasource.sanitiseToExportResource(pluginMap); + }); + applicationJson.setDecryptedFields(decryptedFields); + } else { + applicationJson.getDatasourceList().forEach(datasource -> { + // Remove the datasourceConfiguration object as user will configure it once imported to other instance + datasource.setDatasourceConfiguration(null); + datasource.sanitiseToExportResource(pluginMap); + }); + } + + // Update ids for layoutOnLoadAction + for (NewPage newPage : applicationJson.getPageList()) { + updateIdsForLayoutOnLoadAction(newPage.getUnpublishedPage(), actionIdToNameMap, collectionIdToNameMap); + updateIdsForLayoutOnLoadAction(newPage.getPublishedPage(), actionIdToNameMap, collectionIdToNameMap); + } + + application.exportApplicationPages(pageIdToNameMap); + // Disable exporting the application with datasource config once imported in destination instance + application.setExportWithConfiguration(null); + return applicationJson; + }); + }) + .then(currentUserMono) + .map(user -> { + stopwatch.stopTimer(); + final Map<String, Object> data = Map.of( + FieldName.APPLICATION_ID, applicationId, + "pageCount", applicationJson.getPageList().size(), + "actionCount", applicationJson.getActionList().size(), + "JSObjectCount", applicationJson.getActionCollectionList().size(), + FieldName.FLOW_NAME, stopwatch.getFlow(), + "executionTime", stopwatch.getExecutionTime() + ); + analyticsService.sendEvent(AnalyticsEvents.UNIT_EXECUTION_TIME.getEventName(), user.getUsername(), data); + return applicationJson; + }) + .then(sendImportExportApplicationAnalyticsEvent(applicationId, AnalyticsEvents.EXPORT)) + .thenReturn(applicationJson); + } + + public Mono<ApplicationJson> exportApplicationById(String applicationId, String branchName) { + return applicationService.findBranchedApplicationId(branchName, applicationId, applicationPermission.getExportPermission()) + .flatMap(branchedAppId -> exportApplicationById(branchedAppId, SerialiseApplicationObjective.SHARE)); + } + + private void updateIdsForLayoutOnLoadAction(PageDTO page, + Map<String, String> actionIdToNameMap, + Map<String, String> collectionIdToNameMap) { + + if (page != null && !CollectionUtils.isEmpty(page.getLayouts())) { + for (Layout layout : page.getLayouts()) { + if (!CollectionUtils.isEmpty(layout.getLayoutOnLoadActions())) { + layout.getLayoutOnLoadActions().forEach(onLoadAction -> onLoadAction + .forEach(actionDTO -> { + if (actionIdToNameMap.containsKey(actionDTO.getId())) { + actionDTO.setId(actionIdToNameMap.get(actionDTO.getId())); + } + if (collectionIdToNameMap.containsKey(actionDTO.getCollectionId())) { + actionDTO.setCollectionId(collectionIdToNameMap.get(actionDTO.getCollectionId())); + } + }) + ); + } + } + } + } + + public Mono<ExportFileDTO> getApplicationFile(String applicationId, String branchName) { + return this.exportApplicationById(applicationId, branchName) + .map(applicationJson -> { + Gson gson = new GsonBuilder() + .registerTypeAdapter(Instant.class, new GsonISOStringToInstantConverter()) + .create(); + + String stringifiedFile = gson.toJson(applicationJson); + String applicationName = applicationJson.getExportedApplication().getName(); + Object jsonObject = gson.fromJson(stringifiedFile, Object.class); + HttpHeaders responseHeaders = new HttpHeaders(); + ContentDisposition contentDisposition = ContentDisposition + .builder("attachment") + .filename(applicationName + ".json", StandardCharsets.UTF_8) + .build(); + responseHeaders.setContentDisposition(contentDisposition); + responseHeaders.setContentType(MediaType.APPLICATION_JSON); + + ExportFileDTO exportFileDTO = new ExportFileDTO(); + exportFileDTO.setApplicationResource(jsonObject); + exportFileDTO.setHttpHeaders(responseHeaders); + return exportFileDTO; + }); + } + + /** + * This function will take the Json filepart and saves the application in workspace + * + * @param workspaceId workspace to which the application needs to be hydrated + * @param filePart Json file which contains the entire application object + * @return saved application in DB + */ + public Mono<ApplicationImportDTO> extractFileAndSaveApplication(String workspaceId, Part filePart) { + + /* + 1. Check the validity of file part + 2. Save application to workspace + */ + + final MediaType contentType = filePart.headers().getContentType(); + + if (workspaceId == null || workspaceId.isEmpty()) { + return Mono.error(new AppsmithException(AppsmithError.INVALID_PARAMETER, FieldName.WORKSPACE_ID)); + } + + if (contentType == null || !ALLOWED_CONTENT_TYPES.contains(contentType)) { + return Mono.error(new AppsmithException(AppsmithError.VALIDATION_FAILURE, INVALID_JSON_FILE)); + } + + Mono<String> stringifiedFile = DataBufferUtils.join(filePart.content()) + .map(dataBuffer -> { + byte[] data = new byte[dataBuffer.readableByteCount()]; + dataBuffer.read(data); + DataBufferUtils.release(dataBuffer); + return new String(data); + }); + + Mono<ApplicationImportDTO> importedApplicationMono = stringifiedFile + .flatMap(data -> { + Gson gson = new GsonBuilder() + .registerTypeAdapter(Instant.class, new GsonISOStringToInstantConverter()) + .create(); + /* + // Use JsonObject to migrate when we remove some field from the collection which is being exported + JsonObject json = gson.fromJson(data, JsonObject.class); + JsonObject update = new JsonObject(); + update.addProperty("slug", "update_name"); + update.addProperty("name", "update name"); + ((JsonObject) json.get("exportedApplication")).add("name", update); + json.get("random") == null => true + ((JsonArray) json.get("pageList")) + */ + + Type fileType = new TypeToken<ApplicationJson>() { + }.getType(); + ApplicationJson jsonFile = gson.fromJson(data, fileType); + return importApplicationInWorkspace(workspaceId, jsonFile) + .onErrorResume(error -> { + if (error instanceof AppsmithException) { + return Mono.error(error); + } + return Mono.error(new AppsmithException(AppsmithError.GENERIC_JSON_IMPORT_ERROR, workspaceId, error.getMessage())); + }); + }) + // Add un-configured datasource to the list to response + .flatMap(application -> getApplicationImportDTO(application.getId(), application.getWorkspaceId(), application)); + + return Mono.create(sink -> importedApplicationMono + .subscribe(sink::success, sink::error, null, sink.currentContext()) + ); + } + + /** + * This function will save the application to workspace from the application resource + * + * @param workspaceId workspace to which application is going to be stored + * @param importedDoc application resource which contains necessary information to save the application + * @return saved application in DB + */ + public Mono<Application> importApplicationInWorkspace(String workspaceId, ApplicationJson importedDoc) { + return importApplicationInWorkspace(workspaceId, importedDoc, null, null); + } + + public Mono<Application> importApplicationInWorkspace(String workspaceId, + ApplicationJson applicationJson, + String applicationId, + String branchName) { + return importApplicationInWorkspace(workspaceId, applicationJson, applicationId, branchName, false); + } + + /** + * validates whether a ApplicationJSON contains the required fields or not. + * + * @param importedDoc ApplicationJSON object that needs to be validated + * @return Name of the field that have error. Empty string otherwise + */ + private String validateApplicationJson(ApplicationJson importedDoc) { + String errorField = ""; + if (CollectionUtils.isEmpty(importedDoc.getPageList())) { + errorField = FieldName.PAGES; + } else if (importedDoc.getExportedApplication() == null) { + errorField = FieldName.APPLICATION; + } else if (importedDoc.getActionList() == null) { + errorField = FieldName.ACTIONS; + } else if (importedDoc.getDatasourceList() == null) { + errorField = FieldName.DATASOURCE; + } + + return errorField; + } + + /** + * This function will take the application reference object to hydrate the application in mongoDB + * + * @param workspaceId workspace to which application is going to be stored + * @param applicationJson application resource which contains necessary information to import the application + * @param applicationId application which needs to be saved with the updated resources + * @param branchName name of the branch of application with applicationId + * @param appendToApp whether applicationJson will be appended to the existing app or not + * @return Updated application + */ + private Mono<Application> importApplicationInWorkspace(String workspaceId, + ApplicationJson applicationJson, + String applicationId, + String branchName, + boolean appendToApp) { + /* + 1. Migrate resource to latest schema + 2. Fetch workspace by id + 3. Extract datasources and update plugin information + 4. Create new datasource if same datasource is not present + 5. Extract and save application + 6. Extract and save pages in the application + 7. Extract and save actions in the application + */ + ApplicationJson importedDoc = JsonSchemaMigration.migrateApplicationToLatestSchema(applicationJson); + + // check for validation error and raise exception if error found + String errorField = validateApplicationJson(importedDoc); + if (!errorField.isEmpty()) { + return Mono.error(new AppsmithException(AppsmithError.NO_RESOURCE_FOUND, errorField, INVALID_JSON_FILE)); + } + + Map<String, String> pluginMap = new HashMap<>(); + Map<String, String> datasourceMap = new HashMap<>(); + Map<String, NewPage> pageNameMap = new HashMap<>(); + Map<String, String> actionIdMap = new HashMap<>(); + // Datastructures to create a link between collectionId to embedded action ids + Map<String, Map<String, String>> unpublishedCollectionIdToActionIdsMap = new HashMap<>(); + Map<String, Map<String, String>> publishedCollectionIdToActionIdsMap = new HashMap<>(); + // Datastructures to create a link between actionIds to collectionIds + // <actionId, [collectionId, defaultCollectionId]> + Map<String, List<String>> unpublishedActionIdToCollectionIdMap = new HashMap<>(); + Map<String, List<String>> publishedActionIdToCollectionIdMap = new HashMap<>(); + + Application importedApplication = importedDoc.getExportedApplication(); + + List<Datasource> importedDatasourceList = importedDoc.getDatasourceList(); + List<NewPage> importedNewPageList = importedDoc.getPageList(); + List<NewAction> importedNewActionList = importedDoc.getActionList(); + List<ActionCollection> importedActionCollectionList = importedDoc.getActionCollectionList(); + + Mono<User> currUserMono = sessionUserService.getCurrentUser().cache(); + final Flux<Datasource> existingDatasourceFlux = datasourceRepository + .findAllByWorkspaceId(workspaceId, datasourcePermission.getEditPermission()) + .cache(); + + assert importedApplication != null : "Received invalid application object!"; + if (importedApplication.getApplicationVersion() == null) { + importedApplication.setApplicationVersion(ApplicationVersion.EARLIEST_VERSION); + } + + final List<ApplicationPage> publishedPages = importedApplication.getPublishedPages(); + importedApplication.setViewMode(false); + final List<ApplicationPage> unpublishedPages = importedApplication.getPages(); + + importedApplication.setPages(null); + importedApplication.setPublishedPages(null); + // Start the stopwatch to log the execution time + Stopwatch stopwatch = new Stopwatch(AnalyticsEvents.IMPORT.getEventName()); + Mono<Application> importedApplicationMono = pluginRepository.findAll() + .map(plugin -> { + final String pluginReference = plugin.getPluginName() == null ? plugin.getPackageName() : plugin.getPluginName(); + pluginMap.put(pluginReference, plugin.getId()); + return plugin; + }) + .then(workspaceService.findById(workspaceId, workspacePermission.getApplicationCreatePermission())) + .switchIfEmpty(Mono.error( + new AppsmithException(AppsmithError.ACL_NO_RESOURCE_FOUND, FieldName.WORKSPACE, workspaceId)) + ) + .flatMap(workspace -> { + // Check if the request is to hydrate the application to DB for particular branch + // Application id will be present for GIT sync + if (applicationId != null) { + // No need to hydrate the datasource as we expect user will configure the datasource + return existingDatasourceFlux.collectList(); + } + return Mono.just(new ArrayList<Datasource>()); + }) + .flatMapMany(existingDatasources -> { + if (CollectionUtils.isEmpty(importedDatasourceList)) { + return Mono.empty(); + } + Map<String, Datasource> savedDatasourcesGitIdToDatasourceMap = new HashMap<>(); + + existingDatasources.stream() + .filter(datasource -> datasource.getGitSyncId() != null) + .forEach(datasource -> savedDatasourcesGitIdToDatasourceMap.put(datasource.getGitSyncId(), datasource)); + + // Check if the destination org have all the required plugins installed + for (Datasource datasource : importedDatasourceList) { + if (StringUtils.isEmpty(pluginMap.get(datasource.getPluginId()))) { + log.error("Unable to find the plugin ", datasource.getPluginId()); + return Mono.error(new AppsmithException(AppsmithError.UNKNOWN_PLUGIN_REFERENCE, datasource.getPluginId())); + } + } + return Flux.fromIterable(importedDatasourceList) + // Check for duplicate datasources to avoid duplicates in target workspace + .flatMap(datasource -> { + + final String importedDatasourceName = datasource.getName(); + // Check if the datasource has gitSyncId and if it's already in DB + if (datasource.getGitSyncId() != null + && savedDatasourcesGitIdToDatasourceMap.containsKey(datasource.getGitSyncId())) { + + // Since the resource is already present in DB, just update resource + Datasource existingDatasource = savedDatasourcesGitIdToDatasourceMap.get(datasource.getGitSyncId()); + datasource.setId(null); + // Don't update datasource config as the saved datasource is already configured by user + // for this instance + datasource.setDatasourceConfiguration(null); + datasource.setPluginId(null); + copyNestedNonNullProperties(datasource, existingDatasource); + existingDatasource.setStructure(null); + // Don't update the datasource configuration for already available datasources + existingDatasource.setDatasourceConfiguration(null); + return datasourceService.update(existingDatasource.getId(), existingDatasource) + .map(datasource1 -> { + datasourceMap.put(importedDatasourceName, datasource1.getId()); + return datasource1; + }); + } + + // This is explicitly copied over from the map we created before + datasource.setPluginId(pluginMap.get(datasource.getPluginId())); + datasource.setWorkspaceId(workspaceId); + + // Check if any decrypted fields are present for datasource + if (importedDoc.getDecryptedFields() != null + && importedDoc.getDecryptedFields().get(datasource.getName()) != null) { + + DecryptedSensitiveFields decryptedFields = + importedDoc.getDecryptedFields().get(datasource.getName()); + + updateAuthenticationDTO(datasource, decryptedFields); + } + + return createUniqueDatasourceIfNotPresent(existingDatasourceFlux, datasource, workspaceId) + .map(datasource1 -> { + datasourceMap.put(importedDatasourceName, datasource1.getId()); + return datasource1; + }); + }); + }) + .then( + // 1. Assign the policies for the imported application + // 2. Check for possible duplicate names, + // 3. Save the updated application + + Mono.just(importedApplication) + .zipWith(currUserMono) + .map(objects -> { + Application application = objects.getT1(); + application.setModifiedBy(objects.getT2().getUsername()); + return application; + }) + .flatMap(application -> { + importedApplication.setWorkspaceId(workspaceId); + // Application Id will be present for GIT sync + if (!StringUtils.isEmpty(applicationId)) { + return applicationService.findById(applicationId, applicationPermission.getEditPermission()) + .switchIfEmpty( + Mono.error(new AppsmithException( + AppsmithError.ACL_NO_RESOURCE_FOUND, + FieldName.APPLICATION_ID, + applicationId)) + ) + .flatMap(existingApplication -> { + if (appendToApp) { + // When we are appending the pages to the existing application + // e.g. import template we are only importing this in unpublished + // version. At the same time we want to keep the existing page ref + unpublishedPages.addAll(existingApplication.getPages()); + return Mono.just(existingApplication); + } + importedApplication.setId(existingApplication.getId()); + // For the existing application we don't need to default value of the flag + // The isPublic flag has a default value as false and this would be confusing to user + // when it is reset to false during importing where the application already is present in DB + importedApplication.setIsPublic(null); + copyNestedNonNullProperties(importedApplication, existingApplication); + // We are expecting the changes present in DB are committed to git directory + // so that these won't be lost when we are pulling changes from remote and + // rehydrate the application. We are now rehydrating the application with/without + // the changes from remote + // We are using the save instead of update as we are using @Encrypted + // for GitAuth + return applicationService.findById(existingApplication.getGitApplicationMetadata().getDefaultApplicationId()) + .flatMap(application1 -> { + // Set the policies from the defaultApplication + existingApplication.setPolicies(application1.getPolicies()); + importedApplication.setPolicies(application1.getPolicies()); + return applicationService.save(existingApplication) + .onErrorResume(DuplicateKeyException.class, error -> { + if (error.getMessage() != null) { + return applicationPageService + .createOrUpdateSuffixedApplication( + existingApplication, + existingApplication.getName(), + 0 + ); + } + throw error; + }); + }); + }); + } + return applicationPageService.createOrUpdateSuffixedApplication(application, application.getName(), 0); + }) + ) + .flatMap(savedApp -> importThemes(savedApp, importedDoc, appendToApp)) + .flatMap(savedApp -> { + importedApplication.setId(savedApp.getId()); + if (savedApp.getGitApplicationMetadata() != null) { + importedApplication.setGitApplicationMetadata(savedApp.getGitApplicationMetadata()); + } + + // Import and save pages, also update the pages related fields in saved application + assert importedNewPageList != null : "Unable to find pages in the imported application"; + + if (appendToApp) { + // add existing pages to importedApplication so that they are not lost + // when we update application from importedApplication + importedApplication.setPages(savedApp.getPages()); + } + + // For git-sync this will not be empty + Mono<List<NewPage>> existingPagesMono = newPageService + .findNewPagesByApplicationId(importedApplication.getId(), pagePermission.getEditPermission()) + .collectList() + .cache(); + + Flux<NewPage> importNewPageFlux = importAndSavePages( + importedNewPageList, + savedApp, + branchName, + existingPagesMono + ); + Flux<NewPage> importedNewPagesMono; + + if (appendToApp) { + // we need to rename page if there is a conflict + // also need to remap the renamed page + importedNewPagesMono = updateNewPagesBeforeMerge(existingPagesMono, importedNewPageList) + .flatMapMany(newToOldNameMap -> + importNewPageFlux.map(newPage -> { + // we need to map the newly created page with old name + // because other related resources e.g. actions will refer the page with old name + String newPageName = newPage.getUnpublishedPage().getName(); + String oldPageName = newToOldNameMap.get(newPageName); + if (!newPageName.equals(oldPageName)) { + renamePageInActions(importedNewActionList, oldPageName, newPageName); + renamePageInActionCollections(importedActionCollectionList, oldPageName, newPageName); + unpublishedPages.stream() + .filter(applicationPage -> oldPageName.equals(applicationPage.getId())) + .findAny() + .ifPresent(applicationPage -> applicationPage.setId(newPageName)); + } + return newPage; + }) + ); + } else { + importedNewPagesMono = importNewPageFlux; + } + importedNewPagesMono = importedNewPagesMono + .map(newPage -> { + // Save the map of pageName and NewPage + if (newPage.getUnpublishedPage() != null && newPage.getUnpublishedPage().getName() != null) { + pageNameMap.put(newPage.getUnpublishedPage().getName(), newPage); + } + if (newPage.getPublishedPage() != null && newPage.getPublishedPage().getName() != null) { + pageNameMap.put(newPage.getPublishedPage().getName(), newPage); + } + return newPage; + }); + + return importedNewPagesMono + .collectList() + .map(newPageList -> { + Map<ResourceModes, List<ApplicationPage>> applicationPages = new HashMap<>(); + applicationPages.put(EDIT, unpublishedPages); + applicationPages.put(VIEW, publishedPages); + + Iterator<ApplicationPage> unpublishedPageItr = unpublishedPages.iterator(); + while (unpublishedPageItr.hasNext()) { + ApplicationPage applicationPage = unpublishedPageItr.next(); + NewPage newPage = pageNameMap.get(applicationPage.getId()); + if (newPage == null) { + if (appendToApp) { + // Don't remove the page reference if doing the partial import and appending + // to the existing application + continue; + } + log.debug("Unable to find the page during import for appId {}, with name {}", applicationId, applicationPage.getId()); + unpublishedPageItr.remove(); + } else { + applicationPage.setId(newPage.getId()); + applicationPage.setDefaultPageId(newPage.getDefaultResources().getPageId()); + // Keep the existing page as the default one + if (appendToApp) { + applicationPage.setIsDefault(false); + } + } + } + + Iterator<ApplicationPage> publishedPagesItr; + // Remove the newly added pages from merge app flow. Keep only the existing page from the old app + if(appendToApp) { + List<String> existingPagesId = savedApp.getPublishedPages().stream().map(applicationPage -> applicationPage.getId()).collect(Collectors.toList()); + List<ApplicationPage> publishedApplicationPages = publishedPages.stream().filter(applicationPage -> existingPagesId.contains(applicationPage.getId())).collect(Collectors.toList()); + applicationPages.replace(VIEW, publishedApplicationPages); + publishedPagesItr = publishedApplicationPages.iterator(); + } else { + publishedPagesItr = publishedPages.iterator(); + } + while (publishedPagesItr.hasNext()) { + ApplicationPage applicationPage = publishedPagesItr.next(); + NewPage newPage = pageNameMap.get(applicationPage.getId()); + if (newPage == null) { + log.debug("Unable to find the page during import for appId {}, with name {}", applicationId, applicationPage.getId()); + if (!appendToApp) { + publishedPagesItr.remove(); + } + } else { + applicationPage.setId(newPage.getId()); + applicationPage.setDefaultPageId(newPage.getDefaultResources().getPageId()); + if (appendToApp) { + applicationPage.setIsDefault(false); + } + } + } + + return applicationPages; + }) + .flatMap(applicationPages -> { + // During partial import/appending to the existing application keep the resources + // attached to the application: + // Delete the invalid resources (which are not the part of applicationJsonDTO) in + // the git flow only + if (!StringUtils.isEmpty(applicationId) && !appendToApp) { + Set<String> validPageIds = applicationPages.get(EDIT).stream() + .map(ApplicationPage::getId) + .collect(Collectors.toSet()); + + validPageIds.addAll(applicationPages.get(VIEW) + .stream() + .map(ApplicationPage::getId) + .collect(Collectors.toSet())); + + return existingPagesMono + .flatMap(existingPagesList -> { + Set<String> invalidPageIds = new HashSet<>(); + for (NewPage newPage : existingPagesList) { + if (!validPageIds.contains(newPage.getId())) { + invalidPageIds.add(newPage.getId()); + } + } + + // Delete the pages which were removed during git merge operation + // This does not apply to the traditional import via file approach + return Flux.fromIterable(invalidPageIds) + .flatMap(applicationPageService::deleteUnpublishedPage) + .flatMap(page -> newPageService.archiveById(page.getId()) + .onErrorResume(e -> { + log.debug("Unable to archive page {} with error {}", page.getId(), e.getMessage()); + return Mono.empty(); + }) + ) + .then() + .thenReturn(applicationPages); + }); + } + return Mono.just(applicationPages); + }); + }) + .flatMap(applicationPageMap -> { + + // Set page sequence based on the order for published and unpublished pages + importedApplication.setPages(applicationPageMap.get(EDIT)); + importedApplication.setPublishedPages(applicationPageMap.get(VIEW)); + // This will be non-empty for GIT sync + return newActionRepository.findByApplicationId(importedApplication.getId()) + .collectList(); + }) + .flatMap(existingActions -> + importAndSaveAction( + importedNewActionList, + existingActions, + importedApplication, + branchName, + pageNameMap, + actionIdMap, + pluginMap, + datasourceMap, + unpublishedCollectionIdToActionIdsMap, + publishedCollectionIdToActionIdsMap + ) + .map(NewAction::getId) + .collectList() + .flatMap(savedActionIds -> { + // Updating the existing application for git-sync + // During partial import/appending to the existing application keep the resources + // attached to the application: + // Delete the invalid resources (which are not the part of applicationJsonDTO) in + // the git flow only + if (!StringUtils.isEmpty(applicationId) && !appendToApp) { + // Remove unwanted actions + Set<String> invalidActionIds = new HashSet<>(); + for (NewAction action : existingActions) { + if (!savedActionIds.contains(action.getId())) { + invalidActionIds.add(action.getId()); + } + } + return Flux.fromIterable(invalidActionIds) + .flatMap(actionId -> newActionService.deleteUnpublishedAction(actionId) + // return an empty action so that the filter can remove it from the list + .onErrorResume(throwable -> { + log.debug("Failed to delete action with id {} during import", actionId); + log.error(throwable.getMessage()); + return Mono.empty(); + }) + ) + .then() + .thenReturn(savedActionIds); + } + return Mono.just(savedActionIds); + }) + .thenMany(actionCollectionRepository.findByApplicationId(importedApplication.getId())) + .collectList() + ) + .flatMap(existingActionCollections -> { + if (importedActionCollectionList == null) { + return Mono.just(true); + } + Set<String> savedCollectionIds = new HashSet<>(); + return importAndSaveActionCollection( + importedActionCollectionList, + existingActionCollections, + importedApplication, + branchName, + pageNameMap, + pluginMap, + unpublishedCollectionIdToActionIdsMap, + publishedCollectionIdToActionIdsMap, + appendToApp + ) + .flatMap(tuple -> { + final String importedActionCollectionId = tuple.getT1(); + ActionCollection savedActionCollection = tuple.getT2(); + savedCollectionIds.add(savedActionCollection.getId()); + return updateActionsWithImportedCollectionIds( + importedActionCollectionId, + savedActionCollection, + unpublishedCollectionIdToActionIdsMap, + publishedCollectionIdToActionIdsMap, + unpublishedActionIdToCollectionIdMap, + publishedActionIdToCollectionIdMap + ); + }) + .collectList() + .flatMap(ignore -> { + // Updating the existing application for git-sync + // During partial import/appending to the existing application keep the resources + // attached to the application: + // Delete the invalid resources (which are not the part of applicationJsonDTO) in + // the git flow only + if (!StringUtils.isEmpty(applicationId) && !appendToApp) { + // Remove unwanted action collections + Set<String> invalidCollectionIds = new HashSet<>(); + for (ActionCollection collection : existingActionCollections) { + if (!savedCollectionIds.contains(collection.getId())) { + invalidCollectionIds.add(collection.getId()); + } + } + return Flux.fromIterable(invalidCollectionIds) + .flatMap(collectionId -> actionCollectionService.deleteUnpublishedActionCollection(collectionId) + // return an empty collection so that the filter can remove it from the list + .onErrorResume(throwable -> { + log.debug("Failed to delete collection with id {} during import", collectionId); + log.error(throwable.getMessage()); + return Mono.empty(); + }) + ) + .then() + .thenReturn(savedCollectionIds); + } + return Mono.just(savedCollectionIds); + }) + .thenReturn(true); + }) + .flatMap(ignored -> { + // Don't update gitAuth as we are using @Encrypted for private key + importedApplication.setGitApplicationMetadata(null); + // Map layoutOnLoadActions ids with relevant actions + return newPageService.findNewPagesByApplicationId(importedApplication.getId(), pagePermission.getEditPermission()) + .flatMap(newPage -> { + if (newPage.getDefaultResources() != null) { + newPage.getDefaultResources().setBranchName(branchName); + } + return mapActionAndCollectionIdWithPageLayout( + newPage, actionIdMap, unpublishedActionIdToCollectionIdMap, publishedActionIdToCollectionIdMap + ); + }) + .collectList() + .flatMapMany(newPageService::saveAll) + .then(applicationService.update(importedApplication.getId(), importedApplication)) + .then(sendImportExportApplicationAnalyticsEvent(importedApplication.getId(), AnalyticsEvents.IMPORT)) + .zipWith(currUserMono) + .map(tuple -> { + Application application = tuple.getT1(); + stopwatch.stopTimer(); + stopwatch.stopAndLogTimeInMillis(); + final Map<String, Object> data = Map.of( + FieldName.APPLICATION_ID, application.getId(), + FieldName.ORGANIZATION_ID, application.getWorkspaceId(), + "pageCount", applicationJson.getPageList().size(), + "actionCount", applicationJson.getActionList().size(), + "JSObjectCount", applicationJson.getActionCollectionList().size(), + FieldName.FLOW_NAME, stopwatch.getFlow(), + "executionTime", stopwatch.getExecutionTime() + ); + analyticsService.sendEvent(AnalyticsEvents.UNIT_EXECUTION_TIME.getEventName(), tuple.getT2().getUsername(), data); + return application; + }); + }) + .onErrorResume(throwable -> { + log.error("Error while importing the application ", throwable.getMessage()); + if (importedApplication.getId() != null) { + return applicationPageService.deleteApplication(importedApplication.getId()) + .then(Mono.error(new AppsmithException(AppsmithError.GENERIC_JSON_IMPORT_ERROR, workspaceId, throwable.getMessage()))); + } + return Mono.error(new AppsmithException(AppsmithError.UNKNOWN_PLUGIN_REFERENCE)); + }); + + // Import Application is currently a slow API because it needs to import and create application, pages, actions + // and action collection. This process may take time and the client may cancel the request. This leads to the flow + // getting stopped midway producing corrupted objects in DB. The following ensures that even though the client may have + // cancelled the flow, the importing the application should proceed uninterrupted and whenever the user refreshes + // the page, the imported application is available and is in sane state. + // To achieve this, we use a synchronous sink which does not take subscription cancellations into account. This + // means that even if the subscriber has cancelled its subscription, the create method still generates its event. + return Mono.create(sink -> importedApplicationMono + .subscribe(sink::success, sink::error, null, sink.currentContext()) + ); + } + + private void renamePageInActions(List<NewAction> newActionList, String oldPageName, String newPageName) { + for (NewAction newAction : newActionList) { + if (newAction.getUnpublishedAction().getPageId().equals(oldPageName)) { + newAction.getUnpublishedAction().setPageId(newPageName); + } + } + } + + private void renamePageInActionCollections(List<ActionCollection> actionCollectionList, String oldPageName, String newPageName) { + for (ActionCollection actionCollection : actionCollectionList) { + if (actionCollection.getUnpublishedCollection().getPageId().equals(oldPageName)) { + actionCollection.getUnpublishedCollection().setPageId(newPageName); + } + } + } + + /** + * This function will respond with unique suffixed number for the entity to avoid duplicate names + * + * @param sourceEntity for which the suffixed number is required to avoid duplication + * @param workspaceId workspace in which entity should be searched + * @return next possible number in case of duplication + */ + private Mono<String> getUniqueSuffixForDuplicateNameEntity(BaseDomain sourceEntity, String workspaceId) { + if (sourceEntity != null) { + return sequenceService + .getNextAsSuffix(sourceEntity.getClass(), " for workspace with _id : " + workspaceId) + .map(sequenceNumber -> { + // sequence number will be empty if no duplicate is found + return sequenceNumber.isEmpty() ? " #1" : " #" + sequenceNumber.trim(); + }); + } + return Mono.just(""); + } + + /** + * Method to + * - save imported pages + * - update the mongoEscapedWidgets if present in the page + * - set the policies for the page + * - update default resource ids along with branch-name if the application is connected to git + * + * @param pages pagelist extracted from the imported JSON file + * @param application saved application where pages needs to be added + * @param branchName to which branch pages should be imported if application is connected to git + * @param existingPages existing pages in DB if the application is connected to git + * @return flux of saved pages in DB + */ + private Flux<NewPage> importAndSavePages(List<NewPage> pages, + Application application, + String branchName, + Mono<List<NewPage>> existingPages) { + + Map<String, String> oldToNewLayoutIds = new HashMap<>(); + pages.forEach(newPage -> { + newPage.setApplicationId(application.getId()); + if (newPage.getUnpublishedPage() != null) { + applicationPageService.generateAndSetPagePolicies(application, newPage.getUnpublishedPage()); + newPage.setPolicies(newPage.getUnpublishedPage().getPolicies()); + newPage.getUnpublishedPage().getLayouts().forEach(layout -> { + String layoutId = new ObjectId().toString(); + oldToNewLayoutIds.put(layout.getId(), layoutId); + layout.setId(layoutId); + }); + } + + if (newPage.getPublishedPage() != null) { + applicationPageService.generateAndSetPagePolicies(application, newPage.getPublishedPage()); + newPage.getPublishedPage().getLayouts().forEach(layout -> { + String layoutId = oldToNewLayoutIds.containsKey(layout.getId()) + ? oldToNewLayoutIds.get(layout.getId()) : new ObjectId().toString(); + layout.setId(layoutId); + }); + } + }); + + return existingPages.flatMapMany(existingSavedPages -> { + Map<String, NewPage> savedPagesGitIdToPageMap = new HashMap<>(); + + existingSavedPages.stream() + .filter(newPage -> !StringUtils.isEmpty(newPage.getGitSyncId())) + .forEach(newPage -> savedPagesGitIdToPageMap.put(newPage.getGitSyncId(), newPage)); + + return Flux.fromIterable(pages) + .flatMap(newPage -> { + + // Check if the page has gitSyncId and if it's already in DB + if (newPage.getGitSyncId() != null && savedPagesGitIdToPageMap.containsKey(newPage.getGitSyncId())) { + //Since the resource is already present in DB, just update resource + NewPage existingPage = savedPagesGitIdToPageMap.get(newPage.getGitSyncId()); + copyNestedNonNullProperties(newPage, existingPage); + // Update branchName + existingPage.getDefaultResources().setBranchName(branchName); + // Recover the deleted state present in DB from imported page + existingPage.getUnpublishedPage().setDeletedAt(newPage.getUnpublishedPage().getDeletedAt()); + existingPage.setDeletedAt(newPage.getDeletedAt()); + existingPage.setDeleted(newPage.getDeleted()); + return newPageService.save(existingPage); + } else if (application.getGitApplicationMetadata() != null) { + final String defaultApplicationId = application.getGitApplicationMetadata().getDefaultApplicationId(); + return newPageService.findByGitSyncIdAndDefaultApplicationId(defaultApplicationId, newPage.getGitSyncId(), pagePermission.getEditPermission()) + .switchIfEmpty(Mono.defer(() -> { + // This is the first page we are saving with given gitSyncId in this instance + DefaultResources defaultResources = new DefaultResources(); + defaultResources.setApplicationId(defaultApplicationId); + defaultResources.setBranchName(branchName); + newPage.setDefaultResources(defaultResources); + return saveNewPageAndUpdateDefaultResources(newPage, branchName); + })) + .flatMap(branchedPage -> { + DefaultResources defaultResources = branchedPage.getDefaultResources(); + // Create new page but keep defaultApplicationId and defaultPageId same for both the pages + defaultResources.setBranchName(branchName); + newPage.setDefaultResources(defaultResources); + newPage.getUnpublishedPage().setDeletedAt(branchedPage.getUnpublishedPage().getDeletedAt()); + newPage.setDeletedAt(branchedPage.getDeletedAt()); + newPage.setDeleted(branchedPage.getDeleted()); + // Set policies from existing branch object + newPage.setPolicies(branchedPage.getPolicies()); + return newPageService.save(newPage); + }); + } + return saveNewPageAndUpdateDefaultResources(newPage, branchName); + }); + }); + } + + /** + * Method to + * - save imported actions with updated policies + * - update default resource ids along with branch-name if the application is connected to git + * - update the map of imported collectionIds to the actionIds in saved in DB + * + * @param importedNewActionList action list extracted from the imported JSON file + * @param existingActions actions already present in DB connected to the application + * @param importedApplication imported and saved application in DB + * @param branchName branch to which the actions needs to be saved if the application is connected to git + * @param pageNameMap map of page name to saved page in DB + * @param actionIdMap empty map which will be used to store actionIds from imported file to actual actionIds from DB + * this will eventually be used to update on page load actions + * @param pluginMap map of plugin name to saved plugin id in DB + * @param datasourceMap map of plugin name to saved datasource id in DB + * @param unpublishedCollectionIdToActionIdsMap empty map which will be used to store unpublished collectionId from imported file to + * actual actionIds from DB, format for value will be <defaultActionId, actionId> + * for more details please check defaultToBranchedActionIdsMap {@link ActionCollectionDTO} + * @param publishedCollectionIdToActionIdsMap empty map which will be used to store published collectionId from imported file to + * actual actionIds from DB, format for value will be <defaultActionId, actionId> + * for more details please check defaultToBranchedActionIdsMap{@link ActionCollectionDTO} + * @return saved actions in DB + */ + private Flux<NewAction> importAndSaveAction(List<NewAction> importedNewActionList, + List<NewAction> existingActions, + Application importedApplication, + String branchName, + Map<String, NewPage> pageNameMap, + Map<String, String> actionIdMap, + Map<String, String> pluginMap, + Map<String, String> datasourceMap, + Map<String, Map<String, String>> unpublishedCollectionIdToActionIdsMap, + Map<String, Map<String, String>> publishedCollectionIdToActionIdsMap) { + + Map<String, NewAction> savedActionsGitIdToActionsMap = new HashMap<>(); + final String workspaceId = importedApplication.getWorkspaceId(); + if (CollectionUtils.isEmpty(importedNewActionList)) { + return Flux.fromIterable(new ArrayList<>()); + } + existingActions.stream() + .filter(newAction -> newAction.getGitSyncId() != null) + .forEach(newAction -> savedActionsGitIdToActionsMap.put(newAction.getGitSyncId(), newAction)); + + + return Flux.fromIterable(importedNewActionList) + .filter(action -> action.getUnpublishedAction() != null + && !StringUtils.isEmpty(action.getUnpublishedAction().getPageId())) + .flatMap(newAction -> { + NewPage parentPage = new NewPage(); + ActionDTO unpublishedAction = newAction.getUnpublishedAction(); + ActionDTO publishedAction = newAction.getPublishedAction(); + + // If pageId is missing in the actionDTO create a fallback pageId + final String fallbackParentPageId = unpublishedAction.getPageId(); + + if (unpublishedAction.getValidName() != null) { + unpublishedAction.setId(newAction.getId()); + parentPage = updatePageInAction(unpublishedAction, pageNameMap, actionIdMap); + sanitizeDatasourceInActionDTO(unpublishedAction, datasourceMap, pluginMap, workspaceId, false); + } + + if (publishedAction != null && publishedAction.getValidName() != null) { + publishedAction.setId(newAction.getId()); + if (StringUtils.isEmpty(publishedAction.getPageId())) { + publishedAction.setPageId(fallbackParentPageId); + } + NewPage publishedActionPage = updatePageInAction(publishedAction, pageNameMap, actionIdMap); + parentPage = parentPage == null ? publishedActionPage : parentPage; + sanitizeDatasourceInActionDTO(publishedAction, datasourceMap, pluginMap, workspaceId, false); + } + + examplesWorkspaceCloner.makePristine(newAction); + newAction.setWorkspaceId(workspaceId); + newAction.setApplicationId(importedApplication.getId()); + newAction.setPluginId(pluginMap.get(newAction.getPluginId())); + newActionService.generateAndSetActionPolicies(parentPage, newAction); + + // Check if the action has gitSyncId and if it's already in DB + if (newAction.getGitSyncId() != null + && savedActionsGitIdToActionsMap.containsKey(newAction.getGitSyncId())) { + + //Since the resource is already present in DB, just update resource + NewAction existingAction = savedActionsGitIdToActionsMap.get(newAction.getGitSyncId()); + copyNestedNonNullProperties(newAction, existingAction); + // Update branchName + existingAction.getDefaultResources().setBranchName(branchName); + // Recover the deleted state present in DB from imported action + existingAction.getUnpublishedAction().setDeletedAt(newAction.getUnpublishedAction().getDeletedAt()); + existingAction.setDeletedAt(newAction.getDeletedAt()); + existingAction.setDeleted(newAction.getDeleted()); + return newActionService.save(existingAction); + } else if (importedApplication.getGitApplicationMetadata() != null) { + final String defaultApplicationId = importedApplication.getGitApplicationMetadata().getDefaultApplicationId(); + return newActionRepository.findByGitSyncIdAndDefaultApplicationId(defaultApplicationId, newAction.getGitSyncId(), actionPermission.getEditPermission()) + .switchIfEmpty(Mono.defer(() -> { + // This is the first page we are saving with given gitSyncId in this instance + DefaultResources defaultResources = new DefaultResources(); + defaultResources.setApplicationId(defaultApplicationId); + defaultResources.setBranchName(branchName); + newAction.setDefaultResources(defaultResources); + return saveNewActionAndUpdateDefaultResources(newAction, branchName); + })) + .flatMap(branchedAction -> { + DefaultResources defaultResources = branchedAction.getDefaultResources(); + // Create new action but keep defaultApplicationId and defaultActionId same for both the actions + defaultResources.setBranchName(branchName); + newAction.setDefaultResources(defaultResources); + + String defaultPageId = branchedAction.getUnpublishedAction() != null + ? branchedAction.getUnpublishedAction().getDefaultResources().getPageId() + : branchedAction.getPublishedAction().getDefaultResources().getPageId(); + DefaultResources defaultsDTO = new DefaultResources(); + defaultsDTO.setPageId(defaultPageId); + if (newAction.getUnpublishedAction() != null) { + newAction.getUnpublishedAction().setDefaultResources(defaultsDTO); + } + if (newAction.getPublishedAction() != null) { + newAction.getPublishedAction().setDefaultResources(defaultsDTO); + } + + newAction.getUnpublishedAction().setDeletedAt(branchedAction.getUnpublishedAction().getDeletedAt()); + newAction.setDeletedAt(branchedAction.getDeletedAt()); + newAction.setDeleted(branchedAction.getDeleted()); + // Set policies from existing branch object + newAction.setPolicies(branchedAction.getPolicies()); + return newActionService.save(newAction); + }); + } + + return saveNewActionAndUpdateDefaultResources(newAction, branchName); + }) + .map(newAction -> { + // Populate actionIdsMap to associate the appropriate actions to run on page load + if (newAction.getUnpublishedAction() != null) { + ActionDTO unpublishedAction = newAction.getUnpublishedAction(); + actionIdMap.put( + actionIdMap.get(unpublishedAction.getValidName() + unpublishedAction.getPageId()), + newAction.getId() + ); + + if (unpublishedAction.getCollectionId() != null) { + unpublishedCollectionIdToActionIdsMap.putIfAbsent(unpublishedAction.getCollectionId(), new HashMap<>()); + final Map<String, String> actionIds = unpublishedCollectionIdToActionIdsMap.get(unpublishedAction.getCollectionId()); + actionIds.put(newAction.getDefaultResources().getActionId(), newAction.getId()); + } + } + if (newAction.getPublishedAction() != null) { + ActionDTO publishedAction = newAction.getPublishedAction(); + actionIdMap.put( + actionIdMap.get(publishedAction.getValidName() + publishedAction.getPageId()), + newAction.getId() + ); + + if (publishedAction.getCollectionId() != null) { + publishedCollectionIdToActionIdsMap.putIfAbsent(publishedAction.getCollectionId(), new HashMap<>()); + final Map<String, String> actionIds = publishedCollectionIdToActionIdsMap.get(publishedAction.getCollectionId()); + actionIds.put(newAction.getDefaultResources().getActionId(), newAction.getId()); + } + } + return newAction; + }); + } + + /** + * Method to + * - save imported actionCollections with updated policies + * - update default resource ids along with branch-name if the application is connected to git + * + * @param importedActionCollectionList action list extracted from the imported JSON file + * @param existingActionCollections actions already present in DB connected to the application + * @param importedApplication imported and saved application in DB + * @param branchName branch to which the actions needs to be saved if the application is connected to git + * @param pageNameMap map of page name to saved page in DB + * @param pluginMap map of plugin name to saved plugin id in DB + * @param unpublishedCollectionIdToActionIdsMap + * @param publishedCollectionIdToActionIdsMap map of importedCollectionId to saved actions in DB + * <defaultActionId, actionId> for more details please check + * defaultToBranchedActionIdsMap {@link ActionCollectionDTO} + * @return tuple of imported actionCollectionId and saved actionCollection in DB + */ + private Flux<Tuple2<String, ActionCollection>> importAndSaveActionCollection( + List<ActionCollection> importedActionCollectionList, + List<ActionCollection> existingActionCollections, + Application importedApplication, + String branchName, + Map<String, NewPage> pageNameMap, + Map<String, String> pluginMap, + Map<String, Map<String, String>> unpublishedCollectionIdToActionIdsMap, + Map<String, Map<String, String>> publishedCollectionIdToActionIdsMap, + boolean appendToApp) { + + final String workspaceId = importedApplication.getWorkspaceId(); + return Flux.fromIterable(importedActionCollectionList) + .filter(actionCollection -> actionCollection.getUnpublishedCollection() != null + && !StringUtils.isEmpty(actionCollection.getUnpublishedCollection().getPageId())) + .flatMap(actionCollection -> { + final String importedActionCollectionId = actionCollection.getId(); + NewPage parentPage = new NewPage(); + final ActionCollectionDTO unpublishedCollection = actionCollection.getUnpublishedCollection(); + final ActionCollectionDTO publishedCollection = actionCollection.getPublishedCollection(); + + // If pageId is missing in the actionCollectionDTO create a fallback pageId + final String fallbackParentPageId = unpublishedCollection.getPageId(); + + if (unpublishedCollection.getName() != null) { + unpublishedCollection.setDefaultToBranchedActionIdsMap(unpublishedCollectionIdToActionIdsMap.get(importedActionCollectionId)); + unpublishedCollection.setPluginId(pluginMap.get(unpublishedCollection.getPluginId())); + parentPage = updatePageInActionCollection(unpublishedCollection, pageNameMap); + } + + if (publishedCollection != null && publishedCollection.getName() != null) { + publishedCollection.setDefaultToBranchedActionIdsMap(publishedCollectionIdToActionIdsMap.get(importedActionCollectionId)); + publishedCollection.setPluginId(pluginMap.get(publishedCollection.getPluginId())); + if (StringUtils.isEmpty(publishedCollection.getPageId())) { + publishedCollection.setPageId(fallbackParentPageId); + } + NewPage publishedCollectionPage = updatePageInActionCollection(publishedCollection, pageNameMap); + parentPage = parentPage == null ? publishedCollectionPage : parentPage; + } + + examplesWorkspaceCloner.makePristine(actionCollection); + actionCollection.setWorkspaceId(workspaceId); + actionCollection.setApplicationId(importedApplication.getId()); + actionCollectionService.generateAndSetPolicies(parentPage, actionCollection); + + Map<String, ActionCollection> savedActionCollectionGitIdToCollectionsMap = new HashMap<>(); + + existingActionCollections.stream() + .filter(collection -> collection.getGitSyncId() != null) + .forEach(collection -> savedActionCollectionGitIdToCollectionsMap.put(collection.getGitSyncId(), collection)); + // Check if the action has gitSyncId and if it's already in DB + if (actionCollection.getGitSyncId() != null + && savedActionCollectionGitIdToCollectionsMap.containsKey(actionCollection.getGitSyncId())) { + + //Since the resource is already present in DB, just update resource + ActionCollection existingActionCollection = savedActionCollectionGitIdToCollectionsMap.get(actionCollection.getGitSyncId()); + copyNestedNonNullProperties(actionCollection, existingActionCollection); + // Update branchName + existingActionCollection.getDefaultResources().setBranchName(branchName); + // Recover the deleted state present in DB from imported actionCollection + existingActionCollection.getUnpublishedCollection().setDeletedAt(actionCollection.getUnpublishedCollection().getDeletedAt()); + existingActionCollection.setDeletedAt(actionCollection.getDeletedAt()); + existingActionCollection.setDeleted(actionCollection.getDeleted()); + return Mono.zip( + Mono.just(importedActionCollectionId), + actionCollectionService.save(existingActionCollection) + ); + } else if (importedApplication.getGitApplicationMetadata() != null) { + final String defaultApplicationId = importedApplication.getGitApplicationMetadata().getDefaultApplicationId(); + return actionCollectionRepository.findByGitSyncIdAndDefaultApplicationId(defaultApplicationId, actionCollection.getGitSyncId(), actionPermission.getEditPermission()) + .switchIfEmpty(Mono.defer(() -> { + // This is the first page we are saving with given gitSyncId in this instance + DefaultResources defaultResources = new DefaultResources(); + defaultResources.setApplicationId(defaultApplicationId); + defaultResources.setBranchName(branchName); + actionCollection.setDefaultResources(defaultResources); + return saveNewCollectionAndUpdateDefaultResources(actionCollection, branchName); + })) + .flatMap(branchedActionCollection -> { + DefaultResources defaultResources = branchedActionCollection.getDefaultResources(); + // Create new action but keep defaultApplicationId and defaultActionId same for both the actions + defaultResources.setBranchName(branchName); + actionCollection.setDefaultResources(defaultResources); + + String defaultPageId = branchedActionCollection.getUnpublishedCollection() != null + ? branchedActionCollection.getUnpublishedCollection().getDefaultResources().getPageId() + : branchedActionCollection.getPublishedCollection().getDefaultResources().getPageId(); + DefaultResources defaultsDTO = new DefaultResources(); + defaultsDTO.setPageId(defaultPageId); + if (actionCollection.getUnpublishedCollection() != null) { + actionCollection.getUnpublishedCollection().setDefaultResources(defaultsDTO); + } + if (actionCollection.getPublishedCollection() != null) { + actionCollection.getPublishedCollection().setDefaultResources(defaultsDTO); + } + actionCollection.getUnpublishedCollection() + .setDeletedAt(branchedActionCollection.getUnpublishedCollection().getDeletedAt()); + actionCollection.setDeletedAt(branchedActionCollection.getDeletedAt()); + actionCollection.setDeleted(branchedActionCollection.getDeleted()); + // Set policies from existing branch object + actionCollection.setPolicies(branchedActionCollection.getPolicies()); + return Mono.zip( + Mono.just(importedActionCollectionId), + actionCollectionService.save(actionCollection) + ); + }); + } + + return Mono.zip( + Mono.just(importedActionCollectionId), + saveNewCollectionAndUpdateDefaultResources(actionCollection, branchName) + ); + }); + } + + private Flux<NewAction> updateActionsWithImportedCollectionIds( + String importedActionCollectionId, + ActionCollection savedActionCollection, + Map<String, Map<String, String>> unpublishedCollectionIdToActionIdsMap, + Map<String, Map<String, String>> publishedCollectionIdToActionIdsMap, + Map<String, List<String>> unpublishedActionIdToCollectionIdMap, + Map<String, List<String>> publishedActionIdToCollectionIdMap) { + + final String savedActionCollectionId = savedActionCollection.getId(); + final String defaultCollectionId = savedActionCollection.getDefaultResources().getCollectionId(); + List<String> collectionIds = List.of(savedActionCollectionId, defaultCollectionId); + unpublishedCollectionIdToActionIdsMap + .getOrDefault(importedActionCollectionId, Map.of()) + .forEach((defaultActionId, actionId) -> { + unpublishedActionIdToCollectionIdMap.putIfAbsent(actionId, collectionIds); + }); + publishedCollectionIdToActionIdsMap + .getOrDefault(importedActionCollectionId, Map.of()) + .forEach((defaultActionId, actionId) -> { + publishedActionIdToCollectionIdMap.putIfAbsent(actionId, collectionIds); + }); + final HashSet<String> actionIds = new HashSet<>(); + actionIds.addAll(unpublishedActionIdToCollectionIdMap.keySet()); + actionIds.addAll(publishedActionIdToCollectionIdMap.keySet()); + return Flux.fromIterable(actionIds) + .flatMap(actionId -> newActionRepository.findById(actionId, actionPermission.getEditPermission())) + .map(newAction -> { + // Update collectionId and defaultCollectionIds in actionDTOs + ActionDTO unpublishedAction = newAction.getUnpublishedAction(); + ActionDTO publishedAction = newAction.getPublishedAction(); + if (!CollectionUtils.sizeIsEmpty(unpublishedActionIdToCollectionIdMap) + && !CollectionUtils.isEmpty(unpublishedActionIdToCollectionIdMap.get(newAction.getId()))) { + + unpublishedAction.setCollectionId( + unpublishedActionIdToCollectionIdMap.get(newAction.getId()).get(0) + ); + if (unpublishedAction.getDefaultResources() != null + && StringUtils.isEmpty(unpublishedAction.getDefaultResources().getCollectionId())) { + + unpublishedAction.getDefaultResources().setCollectionId( + unpublishedActionIdToCollectionIdMap.get(newAction.getId()).get(1) + ); + } + } + if (!CollectionUtils.sizeIsEmpty(publishedActionIdToCollectionIdMap) + && !CollectionUtils.isEmpty(publishedActionIdToCollectionIdMap.get(newAction.getId()))) { + + publishedAction.setCollectionId( + publishedActionIdToCollectionIdMap.get(newAction.getId()).get(0) + ); + + if (publishedAction.getDefaultResources() != null + && StringUtils.isEmpty(publishedAction.getDefaultResources().getCollectionId())) { + + publishedAction.getDefaultResources().setCollectionId( + publishedActionIdToCollectionIdMap.get(newAction.getId()).get(1) + ); + } + } + return newAction; + }) + .collectList() + .flatMapMany(newActionService::saveAll); + } + + private Mono<NewPage> saveNewPageAndUpdateDefaultResources(NewPage newPage, String branchName) { + NewPage update = new NewPage(); + return newPageService.save(newPage) + .flatMap(page -> { + update.setDefaultResources(DefaultResourcesUtils.createDefaultIdsOrUpdateWithGivenResourceIds(page, branchName).getDefaultResources()); + return newPageService.update(page.getId(), update); + }); + } + + private Mono<NewAction> saveNewActionAndUpdateDefaultResources(NewAction newAction, String branchName) { + return newActionService.save(newAction) + .flatMap(action -> { + NewAction update = new NewAction(); + update.setDefaultResources( + DefaultResourcesUtils + .createDefaultIdsOrUpdateWithGivenResourceIds(action, branchName).getDefaultResources() + ); + return newActionService.update(action.getId(), update); + }); + } + + private Mono<ActionCollection> saveNewCollectionAndUpdateDefaultResources(ActionCollection actionCollection, String branchName) { + return actionCollectionService.create(actionCollection) + .flatMap(actionCollection1 -> { + ActionCollection update = new ActionCollection(); + update.setDefaultResources( + DefaultResourcesUtils + .createDefaultIdsOrUpdateWithGivenResourceIds(actionCollection1, branchName) + .getDefaultResources() + ); + return actionCollectionService.update(actionCollection1.getId(), update); + }); + } + + private NewPage updatePageInAction(ActionDTO action, + Map<String, NewPage> pageNameMap, + Map<String, String> actionIdMap) { + NewPage parentPage = pageNameMap.get(action.getPageId()); + if (parentPage == null) { + return null; + } + actionIdMap.put(action.getValidName() + parentPage.getId(), action.getId()); + action.setPageId(parentPage.getId()); + + // Update defaultResources in actionDTO + DefaultResources defaultResources = new DefaultResources(); + defaultResources.setPageId(parentPage.getDefaultResources().getPageId()); + action.setDefaultResources(defaultResources); + + return parentPage; + } + + private NewPage updatePageInActionCollection(ActionCollectionDTO collectionDTO, + Map<String, NewPage> pageNameMap) { + NewPage parentPage = pageNameMap.get(collectionDTO.getPageId()); + if (parentPage == null) { + return null; + } + collectionDTO.setPageId(parentPage.getId()); + + // Update defaultResources in actionCollectionDTO + DefaultResources defaultResources = new DefaultResources(); + defaultResources.setPageId(parentPage.getDefaultResources().getPageId()); + collectionDTO.setDefaultResources(defaultResources); + + return parentPage; + } + + /** + * This function will be used to sanitise datasource within the actionDTO + * + * @param actionDTO for which the datasource needs to be sanitised as per import format expected + * @param datasourceMap datasource id to name map + * @param pluginMap plugin id to name map + * @param workspaceId workspace in which the application supposed to be imported + * @return + */ + private String sanitizeDatasourceInActionDTO(ActionDTO actionDTO, + Map<String, String> datasourceMap, + Map<String, String> pluginMap, + String workspaceId, + boolean isExporting) { + + if (actionDTO != null && actionDTO.getDatasource() != null) { + + Datasource ds = actionDTO.getDatasource(); + if (isExporting) { + ds.setUpdatedAt(null); + } + if (ds.getId() != null) { + //Mapping ds name in id field + ds.setId(datasourceMap.get(ds.getId())); + ds.setWorkspaceId(null); + if (ds.getPluginId() != null) { + ds.setPluginId(pluginMap.get(ds.getPluginId())); + } + return ds.getId(); + } else { + // This means we don't have regular datasource it can be simple REST_API and will also be used when + // importing the action to populate the data + ds.setWorkspaceId(workspaceId); + ds.setPluginId(pluginMap.get(ds.getPluginId())); + return ""; + } + } + + return ""; + } + + // This method will update the action id in saved page for layoutOnLoadAction + private Mono<NewPage> mapActionAndCollectionIdWithPageLayout(NewPage page, + Map<String, String> actionIdMap, + Map<String, List<String>> unpublishedActionIdToCollectionIdsMap, + Map<String, List<String>> publishedActionIdToCollectionIdsMap) { + + Set<String> layoutOnLoadActions = new HashSet<>(); + if (page.getUnpublishedPage().getLayouts() != null) { + + page.getUnpublishedPage().getLayouts().forEach(layout -> { + if (layout.getLayoutOnLoadActions() != null) { + layout.getLayoutOnLoadActions().forEach(onLoadAction -> onLoadAction + .forEach(actionDTO -> { + actionDTO.setId(actionIdMap.get(actionDTO.getId())); + if (!CollectionUtils.sizeIsEmpty(unpublishedActionIdToCollectionIdsMap) + && !CollectionUtils.isEmpty(unpublishedActionIdToCollectionIdsMap.get(actionDTO.getId()))) { + actionDTO.setCollectionId(unpublishedActionIdToCollectionIdsMap.get(actionDTO.getId()).get(0)); + } + layoutOnLoadActions.add(actionDTO.getId()); + })); + } + }); + } + + if (page.getPublishedPage() != null && page.getPublishedPage().getLayouts() != null) { + + page.getPublishedPage().getLayouts().forEach(layout -> { + if (layout.getLayoutOnLoadActions() != null) { + layout.getLayoutOnLoadActions().forEach(onLoadAction -> onLoadAction + .forEach(actionDTO -> { + actionDTO.setId(actionIdMap.get(actionDTO.getId())); + if (!CollectionUtils.sizeIsEmpty(publishedActionIdToCollectionIdsMap) + && !CollectionUtils.isEmpty(publishedActionIdToCollectionIdsMap.get(actionDTO.getId()))) { + actionDTO.setCollectionId(publishedActionIdToCollectionIdsMap.get(actionDTO.getId()).get(0)); + } + layoutOnLoadActions.add(actionDTO.getId()); + })); + } + }); + } + + layoutOnLoadActions.remove(null); + return Flux.fromIterable(layoutOnLoadActions) + .flatMap(newActionService::findById) + .map(newAction -> { + final String defaultActionId = newAction.getDefaultResources().getActionId(); + if (page.getUnpublishedPage().getLayouts() != null) { + final String defaultCollectionId = newAction.getUnpublishedAction().getDefaultResources().getCollectionId(); + page.getUnpublishedPage().getLayouts().forEach(layout -> { + if (layout.getLayoutOnLoadActions() != null) { + layout.getLayoutOnLoadActions() + .forEach(onLoadAction -> onLoadAction + .stream() + .filter(actionDTO -> StringUtils.equals(actionDTO.getId(), newAction.getId())) + .forEach(actionDTO -> { + actionDTO.setDefaultActionId(defaultActionId); + actionDTO.setDefaultCollectionId(defaultCollectionId); + }) + ); + } + }); + } + + if (page.getPublishedPage() != null && page.getPublishedPage().getLayouts() != null) { + page.getPublishedPage().getLayouts().forEach(layout -> { + if (layout.getLayoutOnLoadActions() != null) { + layout.getLayoutOnLoadActions().forEach(onLoadAction -> onLoadAction + .stream() + .filter(actionDTO -> StringUtils.equals(actionDTO.getId(), newAction.getId())) + .forEach(actionDTO -> { + actionDTO.setDefaultActionId(defaultActionId); + if (newAction.getPublishedAction() != null + && newAction.getPublishedAction().getDefaultResources() != null) { + actionDTO.setDefaultCollectionId( + newAction.getPublishedAction().getDefaultResources().getCollectionId() + ); + } + }) + ); + } + }); + } + return newAction; + }) + .then(Mono.just(page)); + } + + /** + * This will check if the datasource is already present in the workspace and create a new one if unable to find one + * + * @param existingDatasourceFlux already present datasource in the workspace + * @param datasource which will be checked against existing datasources + * @param workspaceId workspace where duplicate datasource should be checked + * @return already present or brand new datasource depending upon the equality check + */ + private Mono<Datasource> createUniqueDatasourceIfNotPresent(Flux<Datasource> existingDatasourceFlux, + Datasource datasource, + String workspaceId) { + /* + 1. If same datasource is present return + 2. If unable to find the datasource create a new datasource with unique name and return + */ + final DatasourceConfiguration datasourceConfig = datasource.getDatasourceConfiguration(); + AuthenticationResponse authResponse = new AuthenticationResponse(); + if (datasourceConfig != null && datasourceConfig.getAuthentication() != null) { + copyNestedNonNullProperties( + datasourceConfig.getAuthentication().getAuthenticationResponse(), authResponse); + datasourceConfig.getAuthentication().setAuthenticationResponse(null); + datasourceConfig.getAuthentication().setAuthenticationType(null); + } + + return existingDatasourceFlux + // For git import exclude datasource configuration + .filter(ds -> ds.getName().equals(datasource.getName()) && datasource.getPluginId().equals(ds.getPluginId())) + .next() // Get the first matching datasource, we don't need more than one here. + .switchIfEmpty(Mono.defer(() -> { + if (datasourceConfig != null && datasourceConfig.getAuthentication() != null) { + datasourceConfig.getAuthentication().setAuthenticationResponse(authResponse); + } + // No matching existing datasource found, so create a new one. + datasource.setIsConfigured(datasourceConfig != null && datasourceConfig.getAuthentication() != null); + return datasourceService + .findByNameAndWorkspaceId(datasource.getName(), workspaceId, datasourcePermission.getEditPermission()) + .flatMap(duplicateNameDatasource -> + getUniqueSuffixForDuplicateNameEntity(duplicateNameDatasource, workspaceId) + ) + .map(suffix -> { + datasource.setName(datasource.getName() + suffix); + return datasource; + }) + .then(datasourceService.create(datasource)); + })); + } + + /** + * Here we will be rehydrating the sensitive fields like password, secrets etc. in datasource while importing the application + * + * @param datasource for which sensitive fields should be rehydrated + * @param decryptedFields sensitive fields + * @return updated datasource with rehydrated sensitive fields + */ + private Datasource updateAuthenticationDTO(Datasource datasource, DecryptedSensitiveFields decryptedFields) { + + final DatasourceConfiguration dsConfig = datasource.getDatasourceConfiguration(); + String authType = decryptedFields.getAuthType(); + if (dsConfig == null || authType == null) { + return datasource; + } + + if (StringUtils.equals(authType, DBAuth.class.getName())) { + final DBAuth dbAuth = decryptedFields.getDbAuth(); + dbAuth.setPassword(decryptedFields.getPassword()); + datasource.getDatasourceConfiguration().setAuthentication(dbAuth); + } else if (StringUtils.equals(authType, BasicAuth.class.getName())) { + final BasicAuth basicAuth = decryptedFields.getBasicAuth(); + basicAuth.setPassword(decryptedFields.getPassword()); + datasource.getDatasourceConfiguration().setAuthentication(basicAuth); + } else if (StringUtils.equals(authType, OAuth2.class.getName())) { + OAuth2 auth2 = decryptedFields.getOpenAuth2(); + AuthenticationResponse authResponse = new AuthenticationResponse(); + auth2.setClientSecret(decryptedFields.getPassword()); + authResponse.setToken(decryptedFields.getToken()); + authResponse.setRefreshToken(decryptedFields.getRefreshToken()); + authResponse.setTokenResponse(decryptedFields.getTokenResponse()); + authResponse.setExpiresAt(Instant.now()); + auth2.setAuthenticationResponse(authResponse); + datasource.getDatasourceConfiguration().setAuthentication(auth2); + } + return datasource; + } + + private Mono<Application> importThemes(Application application, ApplicationJson importedApplicationJson, boolean appendToApp) { + if (appendToApp) { + // appending to existing app, theme should not change + return Mono.just(application); + } + return themeService.importThemesToApplication(application, importedApplicationJson); + } + + /** + * This will be used to dehydrate sensitive fields from the datasource while exporting the application + * + * @param datasource entity from which sensitive fields need to be dehydrated + * @return sensitive fields which then will be deserialized and exported in JSON file + */ + private DecryptedSensitiveFields getDecryptedFields(Datasource datasource) { + final AuthenticationDTO authentication = datasource.getDatasourceConfiguration() == null + ? null : datasource.getDatasourceConfiguration().getAuthentication(); + + if (authentication != null) { + DecryptedSensitiveFields dsDecryptedFields = + authentication.getAuthenticationResponse() == null + ? new DecryptedSensitiveFields() + : new DecryptedSensitiveFields(authentication.getAuthenticationResponse()); + + if (authentication instanceof DBAuth) { + DBAuth auth = (DBAuth) authentication; + dsDecryptedFields.setPassword(auth.getPassword()); + dsDecryptedFields.setDbAuth(auth); + } else if (authentication instanceof OAuth2) { + OAuth2 auth = (OAuth2) authentication; + dsDecryptedFields.setPassword(auth.getClientSecret()); + dsDecryptedFields.setOpenAuth2(auth); + } else if (authentication instanceof BasicAuth) { + BasicAuth auth = (BasicAuth) authentication; + dsDecryptedFields.setPassword(auth.getPassword()); + dsDecryptedFields.setBasicAuth(auth); + } + dsDecryptedFields.setAuthType(authentication.getClass().getName()); + return dsDecryptedFields; + } + return null; + } + + public Mono<List<Datasource>> findDatasourceByApplicationId(String applicationId, String workspaceId) { + // TODO: Investigate further why datasourcePermission.getReadPermission() is not being used. + Mono<List<Datasource>> listMono = datasourceService.findAllByWorkspaceId(workspaceId, datasourcePermission.getEditPermission()).collectList(); + return newActionService.findAllByApplicationIdAndViewMode(applicationId, false, actionPermission.getReadPermission(), null) + .collectList() + .zipWith(listMono) + .flatMap(objects -> { + List<Datasource> datasourceList = objects.getT2(); + List<NewAction> actionList = objects.getT1(); + List<String> usedDatasource = actionList.stream() + .map(newAction -> newAction.getUnpublishedAction().getDatasource().getId()) + .collect(Collectors.toList()); + + datasourceList.removeIf(datasource -> !usedDatasource.contains(datasource.getId())); + + return Mono.just(datasourceList); + }); + } + + @Override + public Mono<ApplicationImportDTO> getApplicationImportDTO(String applicationId, String workspaceId, Application application) { + return findDatasourceByApplicationId(applicationId, workspaceId) + .map(datasources -> { + ApplicationImportDTO applicationImportDTO = new ApplicationImportDTO(); + applicationImportDTO.setApplication(application); + Boolean isUnConfiguredDatasource = datasources.stream().anyMatch(datasource -> Boolean.FALSE.equals(datasource.getIsConfigured())); + if (Boolean.TRUE.equals(isUnConfiguredDatasource)) { + applicationImportDTO.setIsPartialImport(true); + applicationImportDTO.setUnConfiguredDatasourceList(datasources); + } else { + applicationImportDTO.setIsPartialImport(false); + } + return applicationImportDTO; + }); + } + + /** + * @param applicationId default ID of the application where this ApplicationJSON is going to get merged with + * @param branchName name of the branch of the application where this ApplicationJSON is going to get merged with + * @param applicationJson ApplicationJSON of the application that will be merged to + * @param pagesToImport Name of the pages that should be merged from the ApplicationJSON. + * If null or empty, all pages will be merged. + * @return Merged Application + */ + @Override + public Mono<Application> mergeApplicationJsonWithApplication(String workspaceId, + String applicationId, + String branchName, + ApplicationJson applicationJson, + List<String> pagesToImport) { + // Update the application JSON to prepare it for merging inside an existing application + if (applicationJson.getExportedApplication() != null) { + // setting some properties to null so that target application is not updated by these properties + applicationJson.getExportedApplication().setName(null); + applicationJson.getExportedApplication().setSlug(null); + applicationJson.getExportedApplication().setForkingEnabled(null); + applicationJson.getExportedApplication().setClonedFromApplicationId(null); + } + + // need to remove git sync id. Also filter pages if pageToImport is not empty + if (applicationJson.getPageList() != null) { + List<ApplicationPage> applicationPageList = new ArrayList<>(applicationJson.getPageList().size()); + List<String> pageNames = new ArrayList<>(applicationJson.getPageList().size()); + List<NewPage> importedNewPageList = applicationJson.getPageList().stream() + .filter(newPage -> newPage.getUnpublishedPage() != null && + (CollectionUtils.isEmpty(pagesToImport) || + pagesToImport.contains(newPage.getUnpublishedPage().getName())) + ) + .peek(newPage -> { + ApplicationPage applicationPage = new ApplicationPage(); + applicationPage.setId(newPage.getUnpublishedPage().getName()); + applicationPage.setIsDefault(false); + applicationPageList.add(applicationPage); + pageNames.add(applicationPage.getId()); + }) + .peek(newPage -> newPage.setGitSyncId(null)) + .collect(Collectors.toList()); + applicationJson.setPageList(importedNewPageList); + // Remove the pages from the exported Application inside the json based on the pagesToImport + applicationJson.getExportedApplication().setPages(applicationPageList); + applicationJson.getExportedApplication().setPublishedPages(applicationPageList); +// if (!CollectionUtils.isEmpty(applicationJson.getExportedApplication().getPages())) { +// applicationJson.getExportedApplication().getPages().addAll(applicationPageList); +// } else { +// // If the pages are not emebedded inside the application object we have to add these to pageOrder as +// // JSONSchema migration only works with pageOrder +// applicationJson.getPageOrder().addAll(pageNames); +// } + } + if (applicationJson.getActionList() != null) { + List<NewAction> importedNewActionList = applicationJson.getActionList().stream() + .filter(newAction -> + newAction.getUnpublishedAction() != null && + (CollectionUtils.isEmpty(pagesToImport) || + pagesToImport.contains(newAction.getUnpublishedAction().getPageId())) + ).peek(newAction -> newAction.setGitSyncId(null)) // setting this null so that this action can be imported again + .collect(Collectors.toList()); + applicationJson.setActionList(importedNewActionList); + } + if (applicationJson.getActionCollectionList() != null) { + List<ActionCollection> importedActionCollectionList = applicationJson.getActionCollectionList().stream() + .filter(actionCollection -> + (CollectionUtils.isEmpty(pagesToImport) || + pagesToImport.contains(actionCollection.getUnpublishedCollection().getPageId())) + ).peek(actionCollection -> actionCollection.setGitSyncId(null)) // setting this null so that this action collection can be imported again + .collect(Collectors.toList()); + applicationJson.setActionCollectionList(importedActionCollectionList); + } + + return importApplicationInWorkspace(workspaceId, applicationJson, applicationId, branchName, true); + } + + private Mono<Map<String, String>> updateNewPagesBeforeMerge(Mono<List<NewPage>> existingPagesMono, List<NewPage> newPagesList) { + return existingPagesMono.map(newPages -> { + Map<String, String> newToOldToPageNameMap = new HashMap<>(); // maps new names with old names + + // get a list of unpublished page names that already exists + List<String> unpublishedPageNames = newPages.stream() + .filter(newPage -> newPage.getUnpublishedPage() != null) + .map(newPage -> newPage.getUnpublishedPage().getName()) + .collect(Collectors.toList()); + + // modify each new page + for (NewPage newPage : newPagesList) { + newPage.setPublishedPage(null); // we'll not merge published pages so removing this + + // let's check if page name conflicts, rename in that case + String oldPageName = newPage.getUnpublishedPage().getName(), + newPageName = newPage.getUnpublishedPage().getName(); + + int i = 1; + while (unpublishedPageNames.contains(newPageName)) { + i++; + newPageName = oldPageName + i; + } + newPage.getUnpublishedPage().setName(newPageName); // set new name. may be same as before or not + newPage.getUnpublishedPage().setSlug(TextUtils.makeSlug(newPageName)); // set the slug also + newToOldToPageNameMap.put(newPageName, oldPageName); // map: new name -> old name + } + return newToOldToPageNameMap; + }); + } + + /** + * To send analytics event for import and export of application + * + * @param applicationId Id of application being imported or exported + * @param event AnalyticsEvents event + * @return The application which is imported or exported + */ + private Mono<Application> sendImportExportApplicationAnalyticsEvent(String applicationId, AnalyticsEvents event) { + + return applicationService.findById(applicationId, applicationPermission.getReadPermission()) + .flatMap(application -> { + return Mono.zip(Mono.just(application), workspaceService.getById(application.getWorkspaceId())); + }) + .flatMap(tuple -> { + Application application = tuple.getT1(); + Workspace workspace = tuple.getT2(); + final Map<String, Object> eventData = Map.of( + FieldName.APPLICATION, application, + FieldName.WORKSPACE, workspace + ); + + final Map<String, Object> data = Map.of( + FieldName.APPLICATION_ID, application.getId(), + FieldName.WORKSPACE_ID, workspace.getId(), + FieldName.EVENT_DATA, eventData + ); + + return analyticsService.sendObjectEvent(event, application, data); + }); + } +} diff --git a/app/server/appsmith-server/src/test/java/com/appsmith/server/solutions/ImportExportApplicationServiceV2Tests.java b/app/server/appsmith-server/src/test/java/com/appsmith/server/solutions/ImportExportApplicationServiceV2Tests.java new file mode 100644 index 000000000000..fe82381d6c13 --- /dev/null +++ b/app/server/appsmith-server/src/test/java/com/appsmith/server/solutions/ImportExportApplicationServiceV2Tests.java @@ -0,0 +1,3513 @@ +package com.appsmith.server.solutions; + +import com.appsmith.external.helpers.AppsmithBeanUtils; +import com.appsmith.external.models.ActionConfiguration; +import com.appsmith.external.models.DBAuth; +import com.appsmith.external.models.Datasource; +import com.appsmith.external.models.DatasourceConfiguration; +import com.appsmith.external.models.InvisibleActionFields; +import com.appsmith.external.models.Policy; +import com.appsmith.external.models.Property; +import com.appsmith.server.constants.FieldName; +import com.appsmith.server.constants.SerialiseApplicationObjective; +import com.appsmith.server.domains.ActionCollection; +import com.appsmith.server.domains.Application; +import com.appsmith.server.domains.ApplicationMode; +import com.appsmith.server.domains.ApplicationPage; +import com.appsmith.server.domains.GitApplicationMetadata; +import com.appsmith.server.domains.Layout; +import com.appsmith.server.domains.NewAction; +import com.appsmith.server.domains.NewPage; +import com.appsmith.server.domains.PermissionGroup; +import com.appsmith.server.domains.Plugin; +import com.appsmith.external.models.PluginType; +import com.appsmith.server.domains.Theme; +import com.appsmith.server.domains.Workspace; +import com.appsmith.server.dtos.ActionCollectionDTO; +import com.appsmith.external.models.ActionDTO; +import com.appsmith.server.dtos.ApplicationAccessDTO; +import com.appsmith.server.dtos.ApplicationImportDTO; +import com.appsmith.server.dtos.ApplicationJson; +import com.appsmith.server.dtos.ApplicationPagesDTO; +import com.appsmith.server.dtos.PageDTO; +import com.appsmith.server.dtos.PageNameIdDTO; +import com.appsmith.server.exceptions.AppsmithError; +import com.appsmith.server.exceptions.AppsmithException; +import com.appsmith.server.helpers.MockPluginExecutor; +import com.appsmith.server.helpers.PluginExecutorHelper; +import com.appsmith.server.migrations.ApplicationVersion; +import com.appsmith.server.migrations.JsonSchemaMigration; +import com.appsmith.server.migrations.JsonSchemaVersions; +import com.appsmith.server.repositories.ApplicationRepository; +import com.appsmith.server.repositories.PermissionGroupRepository; +import com.appsmith.server.repositories.PluginRepository; +import com.appsmith.server.repositories.ThemeRepository; +import com.appsmith.server.services.ActionCollectionService; +import com.appsmith.server.services.ApplicationPageService; +import com.appsmith.server.services.ApplicationService; +import com.appsmith.server.services.DatasourceService; +import com.appsmith.server.services.LayoutActionService; +import com.appsmith.server.services.LayoutCollectionService; +import com.appsmith.server.services.NewActionService; +import com.appsmith.server.services.NewPageService; +import com.appsmith.server.services.PermissionGroupService; +import com.appsmith.server.services.WorkspaceService; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.google.gson.Gson; +import lombok.extern.slf4j.Slf4j; +import net.minidev.json.JSONArray; +import net.minidev.json.JSONObject; +import org.apache.commons.lang.StringUtils; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.MethodOrderer; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.Mockito; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.mock.mockito.MockBean; +import org.springframework.core.io.ClassPathResource; +import org.springframework.core.io.buffer.DataBuffer; +import org.springframework.core.io.buffer.DataBufferUtils; +import org.springframework.core.io.buffer.DefaultDataBufferFactory; +import org.springframework.http.HttpMethod; +import org.springframework.http.MediaType; +import org.springframework.http.codec.multipart.FilePart; +import org.springframework.security.test.context.support.WithUserDetails; +import org.springframework.test.annotation.DirtiesContext; +import org.springframework.test.context.junit.jupiter.SpringExtension; +import org.springframework.util.LinkedMultiValueMap; +import reactor.core.publisher.Flux; +import reactor.core.publisher.Mono; +import reactor.test.StepVerifier; +import reactor.util.function.Tuple3; +import reactor.util.function.Tuple4; + +import java.time.Duration; +import java.time.Instant; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.Set; +import java.util.UUID; +import java.util.stream.Collectors; + +import static com.appsmith.server.acl.AclPermission.MANAGE_ACTIONS; +import static com.appsmith.server.acl.AclPermission.MANAGE_APPLICATIONS; +import static com.appsmith.server.acl.AclPermission.MANAGE_DATASOURCES; +import static com.appsmith.server.acl.AclPermission.MANAGE_PAGES; +import static com.appsmith.server.acl.AclPermission.READ_ACTIONS; +import static com.appsmith.server.acl.AclPermission.READ_APPLICATIONS; +import static com.appsmith.server.acl.AclPermission.READ_PAGES; +import static com.appsmith.server.acl.AclPermission.READ_WORKSPACES; +import static com.appsmith.server.constants.FieldName.DEFAULT_PAGE_LAYOUT; +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.assertEquals; + +@Slf4j +@ExtendWith(SpringExtension.class) +@SpringBootTest +@DirtiesContext +@TestMethodOrder(MethodOrderer.MethodName.class) +public class ImportExportApplicationServiceV2Tests { + + @Autowired + @Qualifier("importExportServiceCEImplV2") + ImportExportApplicationService importExportApplicationService; + + @Autowired + ApplicationPageService applicationPageService; + + @Autowired + PluginRepository pluginRepository; + + @Autowired + ApplicationRepository applicationRepository; + + @Autowired + DatasourceService datasourceService; + + @Autowired + NewPageService newPageService; + + @Autowired + NewActionService newActionService; + + @Autowired + WorkspaceService workspaceService; + + @Autowired + LayoutActionService layoutActionService; + + @Autowired + LayoutCollectionService layoutCollectionService; + + @Autowired + ActionCollectionService actionCollectionService; + + @MockBean + PluginExecutorHelper pluginExecutorHelper; + + @Autowired + ThemeRepository themeRepository; + + @Autowired + ApplicationService applicationService; + + @Autowired + PermissionGroupRepository permissionGroupRepository; + + @Autowired + PermissionGroupService permissionGroupService; + + private static final String INVALID_JSON_FILE = "invalid json file"; + private static Plugin installedPlugin; + private static String workspaceId; + private static String testAppId; + private static Datasource jsDatasource; + private static final Map<String, Datasource> datasourceMap = new HashMap<>(); + private static Plugin installedJsPlugin; + private static Boolean isSetupDone = false; + private static String exportWithConfigurationAppId; + + @BeforeEach + public void setup() { + Mockito + .when(pluginExecutorHelper.getPluginExecutor(Mockito.any())) + .thenReturn(Mono.just(new MockPluginExecutor())); + + if (Boolean.TRUE.equals(isSetupDone)) { + return; + } + installedPlugin = pluginRepository.findByPackageName("installed-plugin").block(); + Workspace workspace = new Workspace(); + workspace.setName("Import-Export-Test-Workspace"); + Workspace savedWorkspace = workspaceService.create(workspace).block(); + workspaceId = savedWorkspace.getId(); + + Application testApplication = new Application(); + testApplication.setName("Export-Application-Test-Application"); + testApplication.setWorkspaceId(workspaceId); + testApplication.setUpdatedAt(Instant.now()); + testApplication.setLastDeployedAt(Instant.now()); + testApplication.setModifiedBy("some-user"); + testApplication.setGitApplicationMetadata(new GitApplicationMetadata()); + + Application savedApplication = applicationPageService.createApplication(testApplication, workspaceId).block(); + testAppId = savedApplication.getId(); + + Datasource ds1 = new Datasource(); + ds1.setName("DS1"); + ds1.setWorkspaceId(workspaceId); + ds1.setPluginId(installedPlugin.getId()); + final DatasourceConfiguration datasourceConfiguration = new DatasourceConfiguration(); + datasourceConfiguration.setUrl("http://httpbin.org/get"); + datasourceConfiguration.setHeaders(List.of( + new Property("X-Answer", "42") + )); + ds1.setDatasourceConfiguration(datasourceConfiguration); + + Datasource ds2 = new Datasource(); + ds2.setName("DS2"); + ds2.setPluginId(installedPlugin.getId()); + ds2.setDatasourceConfiguration(new DatasourceConfiguration()); + ds2.setWorkspaceId(workspaceId); + DBAuth auth = new DBAuth(); + auth.setPassword("awesome-password"); + ds2.getDatasourceConfiguration().setAuthentication(auth); + + jsDatasource = new Datasource(); + jsDatasource.setName("Default JS datasource"); + jsDatasource.setWorkspaceId(workspaceId); + installedJsPlugin = pluginRepository.findByPackageName("installed-js-plugin").block(); + assert installedJsPlugin != null; + jsDatasource.setPluginId(installedJsPlugin.getId()); + + ds1 = datasourceService.create(ds1).block(); + ds2 = datasourceService.create(ds2).block(); + datasourceMap.put("DS1", ds1); + datasourceMap.put("DS2", ds2); + isSetupDone = true; + } + + private Flux<ActionDTO> getActionsInApplication(Application application) { + return newPageService + // fetch the unpublished pages + .findByApplicationId(application.getId(), READ_PAGES, false) + .flatMap(page -> newActionService.getUnpublishedActions(new LinkedMultiValueMap<>( + Map.of(FieldName.PAGE_ID, Collections.singletonList(page.getId()))), "")); + } + + private FilePart createFilePart(String filePath) { + FilePart filepart = Mockito.mock(FilePart.class, Mockito.RETURNS_DEEP_STUBS); + Flux<DataBuffer> dataBufferFlux = DataBufferUtils + .read( + new ClassPathResource(filePath), + new DefaultDataBufferFactory(), + 4096) + .cache(); + + Mockito.when(filepart.content()).thenReturn(dataBufferFlux); + Mockito.when(filepart.headers().getContentType()).thenReturn(MediaType.APPLICATION_JSON); + + return filepart; + + } + + private Mono<ApplicationJson> createAppJson(String filePath) { + FilePart filePart = createFilePart(filePath); + + Mono<String> stringifiedFile = DataBufferUtils.join(filePart.content()) + .map(dataBuffer -> { + byte[] data = new byte[dataBuffer.readableByteCount()]; + dataBuffer.read(data); + DataBufferUtils.release(dataBuffer); + return new String(data); + }); + + return stringifiedFile + .map(data -> { + Gson gson = new Gson(); + return gson.fromJson(data, ApplicationJson.class); + }) + .map(JsonSchemaMigration::migrateApplicationToLatestSchema); + } + + private Workspace createTemplateWorkspace() { + Workspace newWorkspace = new Workspace(); + newWorkspace.setName("Template Workspace"); + return workspaceService.create(newWorkspace).block(); + } + + @Test + @WithUserDetails(value = "api_user") + public void exportApplicationWithNullApplicationIdTest() { + Mono<ApplicationJson> resultMono = importExportApplicationService.exportApplicationById(null, ""); + + StepVerifier + .create(resultMono) + .expectErrorMatches(throwable -> throwable instanceof AppsmithException && + throwable.getMessage().equals(AppsmithError.INVALID_PARAMETER.getMessage(FieldName.APPLICATION_ID))) + .verify(); + } + + @Test + @WithUserDetails(value = "api_user") + public void exportPublicApplicationTest() { + + Application application = new Application(); + application.setName("exportPublicApplicationTest-Test"); + + Application createdApplication = applicationPageService.createApplication(application, workspaceId).block(); + + Mono<Workspace> workspaceResponse = workspaceService.findById(workspaceId, READ_WORKSPACES); + + ApplicationAccessDTO applicationAccessDTO = new ApplicationAccessDTO(); + applicationAccessDTO.setPublicAccess(true); + + // Make the application public + applicationService.changeViewAccess(createdApplication.getId(), applicationAccessDTO).block(); + + Mono<ApplicationJson> resultMono = + importExportApplicationService.exportApplicationById(createdApplication.getId(), ""); + + StepVerifier + .create(resultMono) + .assertNext(applicationJson -> { + Application exportedApplication = applicationJson.getExportedApplication(); + assertThat(exportedApplication).isNotNull(); + // Assert that the exported application is NOT public + assertThat(exportedApplication.getDefaultPermissionGroup()).isNull(); + assertThat(exportedApplication.getPolicies()).isNullOrEmpty(); + }) + .verifyComplete(); + } + + @Test + @WithUserDetails(value = "api_user") + public void exportApplication_withInvalidApplicationId_throwNoResourceFoundException() { + Mono<ApplicationJson> resultMono = importExportApplicationService.exportApplicationById("invalidAppId", ""); + + StepVerifier + .create(resultMono) + .expectErrorMatches(throwable -> throwable instanceof AppsmithException && + throwable.getMessage().equals(AppsmithError.NO_RESOURCE_FOUND.getMessage(FieldName.APPLICATION_ID, "invalidAppId"))) + .verify(); + } + + @Test + @WithUserDetails(value = "api_user") + public void exportApplicationById_WhenContainsInternalFields_InternalFieldsNotExported() { + Mono<ApplicationJson> resultMono = importExportApplicationService.exportApplicationById(testAppId, ""); + + StepVerifier + .create(resultMono) + .assertNext(applicationJson -> { + Application exportedApplication = applicationJson.getExportedApplication(); + assertThat(exportedApplication.getModifiedBy()).isNull(); + assertThat(exportedApplication.getLastUpdateTime()).isNull(); + assertThat(exportedApplication.getLastEditedAt()).isNull(); + assertThat(exportedApplication.getLastDeployedAt()).isNull(); + assertThat(exportedApplication.getGitApplicationMetadata()).isNull(); + assertThat(exportedApplication.getEditModeThemeId()).isNull(); + assertThat(exportedApplication.getPublishedModeThemeId()).isNull(); + }) + .verifyComplete(); + } + + @Test + @WithUserDetails(value = "api_user") + public void createExportAppJsonWithDatasourceButWithoutActionsTest() { + + Application testApplication = new Application(); + testApplication.setName("Another Export Application"); + + final Mono<ApplicationJson> resultMono = workspaceService.getById(workspaceId) + .flatMap(workspace -> { + + final Datasource ds1 = datasourceMap.get("DS1"); + ds1.setWorkspaceId(workspace.getId()); + + final Datasource ds2 = datasourceMap.get("DS2"); + ds2.setWorkspaceId(workspace.getId()); + + return applicationPageService.createApplication(testApplication, workspaceId); + }) + .flatMap(application -> importExportApplicationService.exportApplicationById(application.getId(), "")); + + StepVerifier.create(resultMono) + .assertNext(applicationJson -> { + + assertThat(applicationJson.getPageList()).hasSize(1); + assertThat(applicationJson.getActionList()).isEmpty(); + assertThat(applicationJson.getDatasourceList()).isEmpty(); + }) + .verifyComplete(); + } + + @Test + @WithUserDetails(value = "api_user") + public void createExportAppJsonWithActionAndActionCollectionTest() { + + Workspace newWorkspace = new Workspace(); + newWorkspace.setName("template-org-with-ds"); + + Application testApplication = new Application(); + testApplication.setName("ApplicationWithActionCollectionAndDatasource"); + testApplication = applicationPageService.createApplication(testApplication, workspaceId).block(); + + assert testApplication != null; + final String appName = testApplication.getName(); + final Mono<ApplicationJson> resultMono = Mono.zip( + Mono.just(testApplication), + newPageService.findPageById(testApplication.getPages().get(0).getId(), READ_PAGES, false) + ) + .flatMap(tuple -> { + Application testApp = tuple.getT1(); + PageDTO testPage = tuple.getT2(); + + Layout layout = testPage.getLayouts().get(0); + ObjectMapper objectMapper = new ObjectMapper(); + JSONObject dsl = new JSONObject(); + try { + dsl = new JSONObject(objectMapper.readValue(DEFAULT_PAGE_LAYOUT, new TypeReference<HashMap<String, Object>>() { + })); + } catch (JsonProcessingException e) { + e.printStackTrace(); + } + + ArrayList children = (ArrayList) dsl.get("children"); + JSONObject testWidget = new JSONObject(); + testWidget.put("widgetName", "firstWidget"); + JSONArray temp = new JSONArray(); + temp.addAll(List.of(new JSONObject(Map.of("key", "testField")))); + testWidget.put("dynamicBindingPathList", temp); + testWidget.put("testField", "{{ validAction.data }}"); + children.add(testWidget); + + JSONObject tableWidget = new JSONObject(); + tableWidget.put("widgetName", "Table1"); + tableWidget.put("type", "TABLE_WIDGET"); + Map<String, Object> primaryColumns = new HashMap<>(); + JSONObject jsonObject = new JSONObject(Map.of("key", "value")); + primaryColumns.put("_id", "{{ PageAction.data }}"); + primaryColumns.put("_class", jsonObject); + tableWidget.put("primaryColumns", primaryColumns); + final ArrayList<Object> objects = new ArrayList<>(); + JSONArray temp2 = new JSONArray(); + temp2.addAll(List.of(new JSONObject(Map.of("key", "primaryColumns._id")))); + tableWidget.put("dynamicBindingPathList", temp2); + children.add(tableWidget); + + layout.setDsl(dsl); + layout.setPublishedDsl(dsl); + + ActionDTO action = new ActionDTO(); + action.setName("validAction"); + action.setPageId(testPage.getId()); + action.setExecuteOnLoad(true); + ActionConfiguration actionConfiguration = new ActionConfiguration(); + actionConfiguration.setHttpMethod(HttpMethod.GET); + action.setActionConfiguration(actionConfiguration); + action.setDatasource(datasourceMap.get("DS2")); + + ActionDTO action2 = new ActionDTO(); + action2.setName("validAction2"); + action2.setPageId(testPage.getId()); + action2.setExecuteOnLoad(true); + action2.setUserSetOnLoad(true); + ActionConfiguration actionConfiguration2 = new ActionConfiguration(); + actionConfiguration2.setHttpMethod(HttpMethod.GET); + action2.setActionConfiguration(actionConfiguration2); + action2.setDatasource(datasourceMap.get("DS2")); + + ActionCollectionDTO actionCollectionDTO1 = new ActionCollectionDTO(); + actionCollectionDTO1.setName("testCollection1"); + actionCollectionDTO1.setPageId(testPage.getId()); + actionCollectionDTO1.setApplicationId(testApp.getId()); + actionCollectionDTO1.setWorkspaceId(testApp.getWorkspaceId()); + actionCollectionDTO1.setPluginId(jsDatasource.getPluginId()); + ActionDTO action1 = new ActionDTO(); + action1.setName("testAction1"); + action1.setActionConfiguration(new ActionConfiguration()); + action1.getActionConfiguration().setBody("mockBody"); + actionCollectionDTO1.setActions(List.of(action1)); + actionCollectionDTO1.setPluginType(PluginType.JS); + + return layoutCollectionService.createCollection(actionCollectionDTO1) + .then(layoutActionService.createSingleAction(action)) + .then(layoutActionService.createSingleAction(action2)) + .then(layoutActionService.updateLayout(testPage.getId(), testPage.getApplicationId(), layout.getId(), layout)) + .then(importExportApplicationService.exportApplicationById(testApp.getId(), "")); + }) + .cache(); + + Mono<List<NewAction>> actionListMono = resultMono + .then(newActionService + .findAllByApplicationIdAndViewMode(testApplication.getId(), false, READ_ACTIONS, null).collectList()); + + Mono<List<ActionCollection>> collectionListMono = resultMono.then( + actionCollectionService + .findAllByApplicationIdAndViewMode(testApplication.getId(), false, READ_ACTIONS, null).collectList()); + + Mono<List<NewPage>> pageListMono = resultMono.then( + newPageService + .findNewPagesByApplicationId(testApplication.getId(), READ_PAGES).collectList()); + + StepVerifier + .create(Mono.zip(resultMono, actionListMono, collectionListMono, pageListMono)) + .assertNext(tuple -> { + + ApplicationJson applicationJson = tuple.getT1(); + List<NewAction> DBActions = tuple.getT2(); + List<ActionCollection> DBCollections = tuple.getT3(); + List<NewPage> DBPages = tuple.getT4(); + + Application exportedApp = applicationJson.getExportedApplication(); + List<NewPage> pageList = applicationJson.getPageList(); + List<NewAction> actionList = applicationJson.getActionList(); + List<ActionCollection> actionCollectionList = applicationJson.getActionCollectionList(); + List<Datasource> datasourceList = applicationJson.getDatasourceList(); + + List<String> exportedCollectionIds = actionCollectionList.stream().map(ActionCollection::getId).collect(Collectors.toList()); + List<String> exportedActionIds = actionList.stream().map(NewAction::getId).collect(Collectors.toList()); + List<String> DBCollectionIds = DBCollections.stream().map(ActionCollection::getId).collect(Collectors.toList()); + List<String> DBActionIds = DBActions.stream().map(NewAction::getId).collect(Collectors.toList()); + List<String> DBOnLayoutLoadActionIds = new ArrayList<>(); + List<String> exportedOnLayoutLoadActionIds = new ArrayList<>(); + + assertThat(DBPages).hasSize(1); + DBPages.forEach(newPage -> + newPage.getUnpublishedPage().getLayouts().forEach(layout -> { + if (layout.getLayoutOnLoadActions() != null) { + layout.getLayoutOnLoadActions().forEach(dslActionDTOSet -> { + dslActionDTOSet.forEach(actionDTO -> DBOnLayoutLoadActionIds.add(actionDTO.getId())); + }); + } + }) + ); + pageList.forEach(newPage -> + newPage.getUnpublishedPage().getLayouts().forEach(layout -> { + if (layout.getLayoutOnLoadActions() != null) { + layout.getLayoutOnLoadActions().forEach(dslActionDTOSet -> { + dslActionDTOSet.forEach(actionDTO -> exportedOnLayoutLoadActionIds.add(actionDTO.getId())); + }); + } + }) + ); + + NewPage defaultPage = pageList.get(0); + + // Check if the mongo escaped widget names are carried to exported file from DB + Layout pageLayout = DBPages.get(0).getUnpublishedPage().getLayouts().get(0); + Set<String> mongoEscapedWidgets = pageLayout.getMongoEscapedWidgetNames(); + Set<String> expectedMongoEscapedWidgets = Set.of("Table1"); + assertThat(mongoEscapedWidgets).isEqualTo(expectedMongoEscapedWidgets); + + pageLayout = pageList.get(0).getUnpublishedPage().getLayouts().get(0); + Set<String> exportedMongoEscapedWidgets = pageLayout.getMongoEscapedWidgetNames(); + assertThat(exportedMongoEscapedWidgets).isEqualTo(expectedMongoEscapedWidgets); + + + assertThat(exportedApp.getName()).isEqualTo(appName); + assertThat(exportedApp.getWorkspaceId()).isNull(); + assertThat(exportedApp.getPages()).hasSize(1); + assertThat(exportedApp.getPages().get(0).getId()).isEqualTo(defaultPage.getUnpublishedPage().getName()); + + assertThat(exportedApp.getPolicies()).isNull(); + + assertThat(pageList).hasSize(1); + assertThat(defaultPage.getApplicationId()).isNull(); + assertThat(defaultPage.getUnpublishedPage().getLayouts().get(0).getDsl()).isNotNull(); + assertThat(defaultPage.getId()).isNull(); + assertThat(defaultPage.getPolicies()).isNull(); + + assertThat(actionList.isEmpty()).isFalse(); + assertThat(actionList).hasSize(3); + NewAction validAction = actionList.stream().filter(action -> action.getId().equals("Page1_validAction")).findFirst().get(); + assertThat(validAction.getApplicationId()).isNull(); + assertThat(validAction.getPluginId()).isEqualTo(installedPlugin.getPackageName()); + assertThat(validAction.getPluginType()).isEqualTo(PluginType.API); + assertThat(validAction.getWorkspaceId()).isNull(); + assertThat(validAction.getPolicies()).isNull(); + assertThat(validAction.getId()).isNotNull(); + ActionDTO unpublishedAction = validAction.getUnpublishedAction(); + assertThat(unpublishedAction.getPageId()).isEqualTo(defaultPage.getUnpublishedPage().getName()); + assertThat(unpublishedAction.getDatasource().getPluginId()).isEqualTo(installedPlugin.getPackageName()); + + NewAction testAction1 = actionList.stream().filter(action -> action.getUnpublishedAction().getName().equals("testAction1")).findFirst().get(); + assertThat(testAction1.getId()).isEqualTo("Page1_testCollection1.testAction1"); + + assertThat(actionCollectionList.isEmpty()).isFalse(); + assertThat(actionCollectionList).hasSize(1); + final ActionCollection actionCollection = actionCollectionList.get(0); + assertThat(actionCollection.getApplicationId()).isNull(); + assertThat(actionCollection.getWorkspaceId()).isNull(); + assertThat(actionCollection.getPolicies()).isNull(); + assertThat(actionCollection.getId()).isNotNull(); + assertThat(actionCollection.getUnpublishedCollection().getPluginType()).isEqualTo(PluginType.JS); + assertThat(actionCollection.getUnpublishedCollection().getPageId()) + .isEqualTo(defaultPage.getUnpublishedPage().getName()); + assertThat(actionCollection.getUnpublishedCollection().getPluginId()).isEqualTo(installedJsPlugin.getPackageName()); + + assertThat(datasourceList).hasSize(1); + Datasource datasource = datasourceList.get(0); + assertThat(datasource.getWorkspaceId()).isNull(); + assertThat(datasource.getId()).isNull(); + assertThat(datasource.getPluginId()).isEqualTo(installedPlugin.getPackageName()); + assertThat(datasource.getDatasourceConfiguration()).isNull(); + + assertThat(applicationJson.getInvisibleActionFields()).isNull(); + NewAction validAction2 = actionList.stream().filter(action -> action.getId().equals("Page1_validAction2")).findFirst().get(); + assertEquals(true, validAction2.getUnpublishedAction().getUserSetOnLoad()); + + assertThat(applicationJson.getUnpublishedLayoutmongoEscapedWidgets()).isNull(); + assertThat(applicationJson.getPublishedLayoutmongoEscapedWidgets()).isNull(); + assertThat(applicationJson.getEditModeTheme()).isNotNull(); + assertThat(applicationJson.getEditModeTheme().isSystemTheme()).isTrue(); + assertThat(applicationJson.getEditModeTheme().getName()).isEqualToIgnoringCase(Theme.DEFAULT_THEME_NAME); + + assertThat(applicationJson.getPublishedTheme()).isNotNull(); + assertThat(applicationJson.getPublishedTheme().isSystemTheme()).isTrue(); + assertThat(applicationJson.getPublishedTheme().getName()).isEqualToIgnoringCase(Theme.DEFAULT_THEME_NAME); + + assertThat(exportedCollectionIds).isNotEmpty(); + assertThat(exportedCollectionIds).doesNotContain(String.valueOf(DBCollectionIds)); + + assertThat(exportedActionIds).isNotEmpty(); + assertThat(exportedActionIds).doesNotContain(String.valueOf(DBActionIds)); + + assertThat(exportedOnLayoutLoadActionIds).isNotEmpty(); + assertThat(exportedOnLayoutLoadActionIds).doesNotContain(String.valueOf(DBOnLayoutLoadActionIds)); + }) + .verifyComplete(); + } + + @Test + @WithUserDetails(value = "api_user") + public void createExportAppJsonForGitTest() { + + StringBuilder pageName = new StringBuilder(); + final Mono<ApplicationJson> resultMono = applicationRepository.findById(testAppId) + .flatMap(testApp -> { + final String pageId = testApp.getPages().get(0).getId(); + return Mono.zip( + Mono.just(testApp), + newPageService.findPageById(pageId, READ_PAGES, false) + ); + }) + .flatMap(tuple -> { + Datasource ds1 = datasourceMap.get("DS1"); + Application testApp = tuple.getT1(); + PageDTO testPage = tuple.getT2(); + pageName.append(testPage.getName()); + + Layout layout = testPage.getLayouts().get(0); + JSONObject dsl = new JSONObject(Map.of("text", "{{ query1.data }}")); + + layout.setDsl(dsl); + layout.setPublishedDsl(dsl); + + ActionDTO action = new ActionDTO(); + action.setName("validAction"); + action.setPageId(testPage.getId()); + action.setExecuteOnLoad(true); + ActionConfiguration actionConfiguration = new ActionConfiguration(); + actionConfiguration.setHttpMethod(HttpMethod.GET); + action.setActionConfiguration(actionConfiguration); + action.setDatasource(ds1); + + return layoutActionService.createAction(action) + .then(importExportApplicationService.exportApplicationById(testApp.getId(), SerialiseApplicationObjective.VERSION_CONTROL)); + }); + + StepVerifier + .create(resultMono) + .assertNext(applicationJson -> { + + Application exportedApp = applicationJson.getExportedApplication(); + List<NewPage> pageList = applicationJson.getPageList(); + List<NewAction> actionList = applicationJson.getActionList(); + List<Datasource> datasourceList = applicationJson.getDatasourceList(); + + NewPage newPage = pageList.get(0); + + assertThat(applicationJson.getServerSchemaVersion()).isEqualTo(JsonSchemaVersions.serverVersion); + assertThat(applicationJson.getClientSchemaVersion()).isEqualTo(JsonSchemaVersions.clientVersion); + + assertThat(exportedApp.getName()).isNotNull(); + assertThat(exportedApp.getWorkspaceId()).isNull(); + assertThat(exportedApp.getPages()).hasSize(1); + assertThat(exportedApp.getPages().get(0).getId()).isEqualTo(pageName.toString()); + assertThat(exportedApp.getGitApplicationMetadata()).isNull(); + + assertThat(exportedApp.getPolicies()).isNull(); + assertThat(exportedApp.getUserPermissions()).isNull(); + + assertThat(pageList).hasSize(1); + assertThat(newPage.getApplicationId()).isNull(); + assertThat(newPage.getUnpublishedPage().getLayouts().get(0).getDsl()).isNotNull(); + assertThat(newPage.getId()).isNull(); + assertThat(newPage.getPolicies()).isNull(); + + assertThat(actionList.isEmpty()).isFalse(); + NewAction validAction = actionList.get(0); + assertThat(validAction.getApplicationId()).isNull(); + assertThat(validAction.getPluginId()).isEqualTo(installedPlugin.getPackageName()); + assertThat(validAction.getPluginType()).isEqualTo(PluginType.API); + assertThat(validAction.getWorkspaceId()).isNull(); + assertThat(validAction.getPolicies()).isNull(); + assertThat(validAction.getId()).isNotNull(); + assertThat(validAction.getUnpublishedAction().getPageId()) + .isEqualTo(newPage.getUnpublishedPage().getName()); + + assertThat(datasourceList).hasSize(1); + Datasource datasource = datasourceList.get(0); + assertThat(datasource.getWorkspaceId()).isNull(); + assertThat(datasource.getId()).isNull(); + assertThat(datasource.getPluginId()).isEqualTo(installedPlugin.getPackageName()); + assertThat(datasource.getDatasourceConfiguration()).isNull(); + + assertThat(applicationJson.getUnpublishedLayoutmongoEscapedWidgets()).isNull(); + assertThat(applicationJson.getPublishedLayoutmongoEscapedWidgets()).isNull(); + }) + .verifyComplete(); + } + + @Test + @WithUserDetails(value = "api_user") + public void importApplicationFromInvalidFileTest() { + FilePart filepart = Mockito.mock(FilePart.class, Mockito.RETURNS_DEEP_STUBS); + Flux<DataBuffer> dataBufferFlux = DataBufferUtils + .read(new ClassPathResource("test_assets/WorkspaceServiceTest/my_workspace_logo.png"), new DefaultDataBufferFactory(), 4096) + .cache(); + + Mockito.when(filepart.content()).thenReturn(dataBufferFlux); + Mockito.when(filepart.headers().getContentType()).thenReturn(MediaType.IMAGE_PNG); + + Mono<ApplicationImportDTO> resultMono = importExportApplicationService.extractFileAndSaveApplication(workspaceId, filepart); + + StepVerifier + .create(resultMono) + .expectErrorMatches(error -> error instanceof AppsmithException) + .verify(); + } + + @Test + @WithUserDetails(value = "api_user") + public void importApplicationWithNullWorkspaceIdTest() { + FilePart filepart = Mockito.mock(FilePart.class, Mockito.RETURNS_DEEP_STUBS); + + Mono<ApplicationImportDTO> resultMono = importExportApplicationService + .extractFileAndSaveApplication(null, filepart); + + StepVerifier + .create(resultMono) + .expectErrorMatches(throwable -> throwable instanceof AppsmithException && + throwable.getMessage().equals(AppsmithError.INVALID_PARAMETER.getMessage(FieldName.WORKSPACE_ID))) + .verify(); + } + + @Test + @WithUserDetails(value = "api_user") + public void importApplicationFromInvalidJsonFileWithoutPagesTest() { + + FilePart filePart = createFilePart("test_assets/ImportExportServiceTest/invalid-json-without-pages.json"); + Mono<ApplicationImportDTO> resultMono = importExportApplicationService.extractFileAndSaveApplication(workspaceId, filePart); + + StepVerifier + .create(resultMono) + .expectErrorMatches(throwable -> throwable instanceof AppsmithException && + throwable.getMessage().equals(AppsmithError.NO_RESOURCE_FOUND.getMessage(FieldName.PAGES, INVALID_JSON_FILE))) + .verify(); + } + + @Test + @WithUserDetails(value = "api_user") + public void importApplicationFromInvalidJsonFileWithoutApplicationTest() { + + FilePart filePart = createFilePart("test_assets/ImportExportServiceTest/invalid-json-without-app.json"); + Mono<ApplicationImportDTO> resultMono = importExportApplicationService.extractFileAndSaveApplication(workspaceId, filePart); + + StepVerifier + .create(resultMono) + .expectErrorMatches(throwable -> throwable instanceof AppsmithException && + throwable.getMessage().equals(AppsmithError.NO_RESOURCE_FOUND.getMessage(FieldName.APPLICATION, INVALID_JSON_FILE))) + .verify(); + } + + @Test + @WithUserDetails(value = "api_user") + public void importApplicationFromValidJsonFileTest() { + + FilePart filePart = createFilePart("test_assets/ImportExportServiceTest/valid-application.json"); + + Workspace newWorkspace = new Workspace(); + newWorkspace.setName("Template Workspace"); + + Mono<Workspace> workspaceMono = workspaceService + .create(newWorkspace).cache(); + + final Mono<ApplicationImportDTO> resultMono = workspaceMono + .flatMap(workspace -> importExportApplicationService + .extractFileAndSaveApplication(workspace.getId(), filePart) + ); + + List<PermissionGroup> permissionGroups = workspaceMono + .flatMapMany(savedWorkspace -> { + Set<String> defaultPermissionGroups = savedWorkspace.getDefaultPermissionGroups(); + return permissionGroupRepository.findAllById(defaultPermissionGroups); + }) + .collectList() + .block(); + + PermissionGroup adminPermissionGroup = permissionGroups.stream() + .filter(permissionGroup -> permissionGroup.getName().startsWith(FieldName.ADMINISTRATOR)) + .findFirst().get(); + + PermissionGroup developerPermissionGroup = permissionGroups.stream() + .filter(permissionGroup -> permissionGroup.getName().startsWith(FieldName.DEVELOPER)) + .findFirst().get(); + + PermissionGroup viewerPermissionGroup = permissionGroups.stream() + .filter(permissionGroup -> permissionGroup.getName().startsWith(FieldName.VIEWER)) + .findFirst().get(); + + Policy manageAppPolicy = Policy.builder().permission(MANAGE_APPLICATIONS.getValue()) + .permissionGroups(Set.of(adminPermissionGroup.getId(), developerPermissionGroup.getId())) + .build(); + Policy readAppPolicy = Policy.builder().permission(READ_APPLICATIONS.getValue()) + .permissionGroups(Set.of(adminPermissionGroup.getId(), developerPermissionGroup.getId(), + viewerPermissionGroup.getId())) + .build(); + + StepVerifier + .create(resultMono + .flatMap(applicationImportDTO -> { + Application application = applicationImportDTO.getApplication(); + return Mono.zip( + Mono.just(applicationImportDTO), + datasourceService.findAllByWorkspaceId(application.getWorkspaceId(), MANAGE_DATASOURCES).collectList(), + newActionService.findAllByApplicationIdAndViewMode(application.getId(), false, READ_ACTIONS, null).collectList(), + newPageService.findByApplicationId(application.getId(), MANAGE_PAGES, false).collectList(), + actionCollectionService.findAllByApplicationIdAndViewMode(application.getId(), false, MANAGE_ACTIONS, null).collectList() + ); + })) + .assertNext(tuple -> { + final Application application = tuple.getT1().getApplication(); + final List<Datasource> unConfiguredDatasourceList = tuple.getT1().getUnConfiguredDatasourceList(); + final boolean isPartialImport = tuple.getT1().getIsPartialImport(); + final List<Datasource> datasourceList = tuple.getT2(); + final List<NewAction> actionList = tuple.getT3(); + final List<PageDTO> pageList = tuple.getT4(); + final List<ActionCollection> actionCollectionList = tuple.getT5(); + + assertThat(application.getName()).isEqualTo("valid_application"); + assertThat(application.getWorkspaceId()).isNotNull(); + assertThat(application.getPages()).hasSize(2); + assertThat(application.getPolicies()).containsAll(Set.of(manageAppPolicy, readAppPolicy)); + assertThat(application.getPublishedPages()).hasSize(1); + assertThat(application.getModifiedBy()).isEqualTo("api_user"); + assertThat(application.getUpdatedAt()).isNotNull(); + assertThat(application.getEditModeThemeId()).isNotNull(); + assertThat(application.getPublishedModeThemeId()).isNotNull(); + assertThat(isPartialImport).isEqualTo(Boolean.TRUE); + assertThat(unConfiguredDatasourceList).isNotNull(); + + assertThat(datasourceList).isNotEmpty(); + datasourceList.forEach(datasource -> { + assertThat(datasource.getWorkspaceId()).isEqualTo(application.getWorkspaceId()); + assertThat(datasource.getDatasourceConfiguration()).isNotNull(); + }); + + List<String> collectionIdInAction = new ArrayList<>(); + assertThat(actionList).isNotEmpty(); + actionList.forEach(newAction -> { + ActionDTO actionDTO = newAction.getUnpublishedAction(); + assertThat(actionDTO.getPageId()).isNotEqualTo(pageList.get(0).getName()); + if (StringUtils.equals(actionDTO.getName(), "api_wo_auth")) { + ActionDTO publishedAction = newAction.getPublishedAction(); + assertThat(publishedAction).isNotNull(); + assertThat(publishedAction.getActionConfiguration()).isNotNull(); + // Test the fallback page ID from the unpublishedAction is copied to published version when + // published version does not have pageId + assertThat(actionDTO.getPageId()).isEqualTo(publishedAction.getPageId()); + } + if (!StringUtils.isEmpty(actionDTO.getCollectionId())) { + collectionIdInAction.add(actionDTO.getCollectionId()); + } + }); + + assertThat(actionCollectionList).isNotEmpty(); + actionCollectionList.forEach(actionCollection -> { + assertThat(actionCollection.getUnpublishedCollection().getPageId()).isNotEqualTo(pageList.get(0).getName()); + if (StringUtils.equals(actionCollection.getUnpublishedCollection().getName(), "JSObject2")) { + // Check if this action collection is not attached to any action + assertThat(collectionIdInAction).doesNotContain(actionCollection.getId()); + } else { + assertThat(collectionIdInAction).contains(actionCollection.getId()); + } + }); + + assertThat(pageList).hasSize(2); + + ApplicationPage defaultAppPage = application.getPages() + .stream() + .filter(ApplicationPage::getIsDefault) + .findFirst() + .orElse(null); + assertThat(defaultAppPage).isNotNull(); + + PageDTO defaultPageDTO = pageList.stream() + .filter(pageDTO -> pageDTO.getId().equals(defaultAppPage.getId())).findFirst().orElse(null); + + assertThat(defaultPageDTO).isNotNull(); + assertThat(defaultPageDTO.getLayouts().get(0).getLayoutOnLoadActions()).isNotEmpty(); + }) + .verifyComplete(); + } + + @Test + @WithUserDetails(value = "api_user") + public void importFromValidJson_cancelledMidway_importSuccess() { + + FilePart filePart = createFilePart("test_assets/ImportExportServiceTest/valid-application.json"); + + Workspace newWorkspace = new Workspace(); + newWorkspace.setName("Midway cancel import app workspace"); + newWorkspace = workspaceService.create(newWorkspace).block(); + + importExportApplicationService + .extractFileAndSaveApplication(newWorkspace.getId(), filePart) + .timeout(Duration.ofMillis(10)) + .subscribe(); + + // Wait for import to complete + Mono<Application> importedAppFromDbMono = Mono.just(newWorkspace) + .flatMap(workspace -> { + try { + // Before fetching the imported application, sleep for 5 seconds to ensure that the import completes + Thread.sleep(5000); + } catch (InterruptedException e) { + e.printStackTrace(); + } + return applicationRepository.findByWorkspaceId(workspace.getId(), READ_APPLICATIONS) + .next(); + }); + + StepVerifier.create(importedAppFromDbMono) + .assertNext(application -> { + assertThat(application.getId()).isNotEmpty(); + }) + .verifyComplete(); + } + + @Test + @WithUserDetails(value = "api_user") + public void importApplicationInWorkspace_WhenCustomizedThemes_ThemesCreated() { + FilePart filePart = createFilePart( + "test_assets/ImportExportServiceTest/valid-application-with-custom-themes.json" + ); + + Workspace newWorkspace = new Workspace(); + newWorkspace.setName("Import theme test org"); + + final Mono<ApplicationImportDTO> resultMono = workspaceService + .create(newWorkspace) + .flatMap(workspace -> importExportApplicationService + .extractFileAndSaveApplication(workspace.getId(), filePart) + ); + + StepVerifier + .create(resultMono + .flatMap(applicationImportDTO -> Mono.zip( + Mono.just(applicationImportDTO), + themeRepository.findById(applicationImportDTO.getApplication().getEditModeThemeId()), + themeRepository.findById(applicationImportDTO.getApplication().getPublishedModeThemeId()) + ))) + .assertNext(tuple -> { + final Application application = tuple.getT1().getApplication(); + Theme editTheme = tuple.getT2(); + Theme publishedTheme = tuple.getT3(); + + assertThat(editTheme.isSystemTheme()).isFalse(); + assertThat(editTheme.getDisplayName()).isEqualTo("Custom edit theme"); + assertThat(editTheme.getWorkspaceId()).isNull(); + assertThat(editTheme.getApplicationId()).isNull(); + + assertThat(publishedTheme.isSystemTheme()).isFalse(); + assertThat(publishedTheme.getDisplayName()).isEqualTo("Custom published theme"); + assertThat(publishedTheme.getWorkspaceId()).isNullOrEmpty(); + assertThat(publishedTheme.getApplicationId()).isNullOrEmpty(); + }) + .verifyComplete(); + } + + @Test + @WithUserDetails(value = "api_user") + public void importApplication_withoutActionCollection_succeedsWithoutError() { + + FilePart filePart = createFilePart("test_assets/ImportExportServiceTest/valid-application-without-action-collection.json"); + + Workspace newWorkspace = new Workspace(); + newWorkspace.setName("Template Workspace"); + + Mono<Workspace> workspaceMono = workspaceService + .create(newWorkspace).cache(); + + final Mono<ApplicationImportDTO> resultMono = workspaceMono + .flatMap(workspace -> importExportApplicationService + .extractFileAndSaveApplication(workspace.getId(), filePart) + ); + + List<PermissionGroup> permissionGroups = workspaceMono + .flatMapMany(savedWorkspace -> { + Set<String> defaultPermissionGroups = savedWorkspace.getDefaultPermissionGroups(); + return permissionGroupRepository.findAllById(defaultPermissionGroups); + }) + .collectList() + .block(); + + PermissionGroup adminPermissionGroup = permissionGroups.stream() + .filter(permissionGroup -> permissionGroup.getName().startsWith(FieldName.ADMINISTRATOR)) + .findFirst().get(); + + PermissionGroup developerPermissionGroup = permissionGroups.stream() + .filter(permissionGroup -> permissionGroup.getName().startsWith(FieldName.DEVELOPER)) + .findFirst().get(); + + PermissionGroup viewerPermissionGroup = permissionGroups.stream() + .filter(permissionGroup -> permissionGroup.getName().startsWith(FieldName.VIEWER)) + .findFirst().get(); + + Policy manageAppPolicy = Policy.builder().permission(MANAGE_APPLICATIONS.getValue()) + .permissionGroups(Set.of(adminPermissionGroup.getId(), developerPermissionGroup.getId())) + .build(); + Policy readAppPolicy = Policy.builder().permission(READ_APPLICATIONS.getValue()) + .permissionGroups(Set.of(adminPermissionGroup.getId(), developerPermissionGroup.getId(), + viewerPermissionGroup.getId())) + .build(); + + StepVerifier + .create(resultMono + .flatMap(applicationImportDTO -> Mono.zip( + Mono.just(applicationImportDTO), + datasourceService.findAllByWorkspaceId(applicationImportDTO.getApplication().getWorkspaceId(), MANAGE_DATASOURCES).collectList(), + getActionsInApplication(applicationImportDTO.getApplication()).collectList(), + newPageService.findByApplicationId(applicationImportDTO.getApplication().getId(), MANAGE_PAGES, false).collectList(), + actionCollectionService.findAllByApplicationIdAndViewMode(applicationImportDTO.getApplication().getId(), false + , MANAGE_ACTIONS, null).collectList() + ))) + .assertNext(tuple -> { + final Application application = tuple.getT1().getApplication(); + final List<Datasource> datasourceList = tuple.getT2(); + final List<ActionDTO> actionDTOS = tuple.getT3(); + final List<PageDTO> pageList = tuple.getT4(); + final List<ActionCollection> actionCollectionList = tuple.getT5(); + + assertThat(application.getName()).isEqualTo("valid_application"); + assertThat(application.getWorkspaceId()).isNotNull(); + assertThat(application.getPages()).hasSize(2); + assertThat(application.getPolicies()).containsAll(Set.of(manageAppPolicy, readAppPolicy)); + assertThat(application.getPublishedPages()).hasSize(1); + assertThat(application.getModifiedBy()).isEqualTo("api_user"); + assertThat(application.getUpdatedAt()).isNotNull(); + + assertThat(datasourceList).isNotEmpty(); + datasourceList.forEach(datasource -> { + assertThat(datasource.getWorkspaceId()).isEqualTo(application.getWorkspaceId()); + assertThat(datasource.getDatasourceConfiguration()).isNotNull(); + }); + + assertThat(actionDTOS).isNotEmpty(); + actionDTOS.forEach(actionDTO -> { + assertThat(actionDTO.getPageId()).isNotEqualTo(pageList.get(0).getName()); + + }); + + assertThat(actionCollectionList).isEmpty(); + + assertThat(pageList).hasSize(2); + + ApplicationPage defaultAppPage = application.getPages() + .stream() + .filter(ApplicationPage::getIsDefault) + .findFirst() + .orElse(null); + assertThat(defaultAppPage).isNotNull(); + + PageDTO defaultPageDTO = pageList.stream() + .filter(pageDTO -> pageDTO.getId().equals(defaultAppPage.getId())).findFirst().orElse(null); + + assertThat(defaultPageDTO).isNotNull(); + assertThat(defaultPageDTO.getLayouts().get(0).getLayoutOnLoadActions()).isNotEmpty(); + }) + .verifyComplete(); + } + + @Test + @WithUserDetails(value = "api_user") + public void importApplication_WithoutThemes_LegacyThemesAssigned() { + FilePart filePart = createFilePart("test_assets/ImportExportServiceTest/valid-application-without-theme.json"); + + Workspace newWorkspace = new Workspace(); + newWorkspace.setName("Template Workspace"); + + final Mono<ApplicationImportDTO> resultMono = workspaceService.create(newWorkspace) + .flatMap(workspace -> importExportApplicationService + .extractFileAndSaveApplication(workspace.getId(), filePart) + ); + + StepVerifier + .create(resultMono) + .assertNext(applicationImportDTO -> { + assertThat(applicationImportDTO.getApplication().getEditModeThemeId()).isNotEmpty(); + assertThat(applicationImportDTO.getApplication().getPublishedModeThemeId()).isNotEmpty(); + }) + .verifyComplete(); + } + + @Test + @WithUserDetails(value = "api_user") + public void importApplication_withoutPageIdInActionCollection_succeeds() { + + FilePart filePart = createFilePart("test_assets/ImportExportServiceTest/invalid-application-without-pageId-action-collection.json"); + + Workspace newWorkspace = new Workspace(); + newWorkspace.setName("Template Workspace"); + + final Mono<ApplicationImportDTO> resultMono = workspaceService + .create(newWorkspace) + .flatMap(workspace -> importExportApplicationService + .extractFileAndSaveApplication(workspace.getId(), filePart) + ); + + StepVerifier + .create(resultMono + .flatMap(applicationImportDTO -> Mono.zip( + Mono.just(applicationImportDTO), + datasourceService.findAllByWorkspaceId(applicationImportDTO.getApplication().getWorkspaceId(), MANAGE_DATASOURCES).collectList(), + getActionsInApplication(applicationImportDTO.getApplication()).collectList(), + newPageService.findByApplicationId(applicationImportDTO.getApplication().getId(), MANAGE_PAGES, false).collectList(), + actionCollectionService + .findAllByApplicationIdAndViewMode(applicationImportDTO.getApplication().getId(), false, MANAGE_ACTIONS, null).collectList() + ))) + .assertNext(tuple -> { + final Application application = tuple.getT1().getApplication(); + final List<Datasource> datasourceList = tuple.getT2(); + final List<ActionDTO> actionDTOS = tuple.getT3(); + final List<PageDTO> pageList = tuple.getT4(); + final List<ActionCollection> actionCollectionList = tuple.getT5(); + + + assertThat(datasourceList).isNotEmpty(); + + assertThat(actionDTOS).hasSize(1); + actionDTOS.forEach(actionDTO -> { + assertThat(actionDTO.getPageId()).isNotEqualTo(pageList.get(0).getName()); + + }); + + assertThat(actionCollectionList).isEmpty(); + }) + .verifyComplete(); + } + + @Test + @WithUserDetails(value = "api_user") + public void exportImportApplication_importWithBranchName_updateApplicationResourcesWithBranch() { + Application testApplication = new Application(); + testApplication.setName("Export-Import-Update-Branch_Test-App"); + testApplication.setWorkspaceId(workspaceId); + testApplication.setUpdatedAt(Instant.now()); + testApplication.setLastDeployedAt(Instant.now()); + testApplication.setModifiedBy("some-user"); + testApplication.setGitApplicationMetadata(new GitApplicationMetadata()); + GitApplicationMetadata gitData = new GitApplicationMetadata(); + gitData.setBranchName("testBranch"); + testApplication.setGitApplicationMetadata(gitData); + + Application savedApplication = applicationPageService.createApplication(testApplication, workspaceId) + .flatMap(application1 -> { + application1.getGitApplicationMetadata().setDefaultApplicationId(application1.getId()); + return applicationService.save(application1); + }).block(); + + Mono<Application> result = newPageService.findNewPagesByApplicationId(savedApplication.getId(), READ_PAGES).collectList() + .flatMap(newPages -> { + NewPage newPage = newPages.get(0); + + ActionDTO action = new ActionDTO(); + action.setName("validAction"); + action.setPageId(newPage.getId()); + action.setExecuteOnLoad(true); + ActionConfiguration actionConfiguration = new ActionConfiguration(); + actionConfiguration.setHttpMethod(HttpMethod.GET); + action.setActionConfiguration(actionConfiguration); + action.setDatasource(datasourceMap.get("DS1")); + return layoutActionService.createAction(action) + .flatMap(createdAction -> newActionService.findById(createdAction.getId(), READ_ACTIONS)); + }) + .then(importExportApplicationService.exportApplicationById(savedApplication.getId(), SerialiseApplicationObjective.VERSION_CONTROL) + .flatMap(applicationJson -> importExportApplicationService.importApplicationInWorkspace(workspaceId, applicationJson, savedApplication.getId(), gitData.getBranchName()))) + .cache(); + + Mono<List<NewPage>> updatedPagesMono = result.then(newPageService.findNewPagesByApplicationId(savedApplication.getId(), READ_PAGES).collectList()); + + Mono<List<NewAction>> updatedActionsMono = result.then(newActionService.findAllByApplicationIdAndViewMode(savedApplication.getId(), false, READ_PAGES, null).collectList()); + + StepVerifier + .create(Mono.zip(result, updatedPagesMono, updatedActionsMono)) + .assertNext(tuple -> { + Application application = tuple.getT1(); + List<NewPage> pageList = tuple.getT2(); + List<NewAction> actionList = tuple.getT3(); + + final String branchName = application.getGitApplicationMetadata().getBranchName(); + pageList.forEach(page -> { + assertThat(page.getDefaultResources()).isNotNull(); + assertThat(page.getDefaultResources().getBranchName()).isEqualTo(branchName); + }); + + actionList.forEach(action -> { + assertThat(action.getDefaultResources()).isNotNull(); + assertThat(action.getDefaultResources().getBranchName()).isEqualTo(branchName); + }); + }) + .verifyComplete(); + } + + @Test + @WithUserDetails(value = "api_user") + public void importApplication_incompatibleJsonFile_throwException() { + FilePart filePart = createFilePart("test_assets/ImportExportServiceTest/incompatible_version.json"); + Mono<ApplicationImportDTO> resultMono = importExportApplicationService.extractFileAndSaveApplication(workspaceId, filePart); + + StepVerifier + .create(resultMono) + .expectErrorMatches(throwable -> throwable instanceof AppsmithException && + throwable.getMessage().equals(AppsmithError.INCOMPATIBLE_IMPORTED_JSON.getMessage())) + .verify(); + } + + @Test + @WithUserDetails(value = "api_user") + public void importApplication_withUnConfiguredDatasources_Success() { + FilePart filePart = createFilePart("test_assets/ImportExportServiceTest/valid-application-with-un-configured-datasource.json"); + + Workspace newWorkspace = new Workspace(); + newWorkspace.setName("Template Workspace"); + + Mono<Workspace> workspaceMono = workspaceService + .create(newWorkspace).cache(); + + final Mono<ApplicationImportDTO> resultMono = workspaceMono + .flatMap(workspace -> importExportApplicationService + .extractFileAndSaveApplication(workspace.getId(), filePart) + ); + + List<PermissionGroup> permissionGroups = workspaceMono + .flatMapMany(savedWorkspace -> { + Set<String> defaultPermissionGroups = savedWorkspace.getDefaultPermissionGroups(); + return permissionGroupRepository.findAllById(defaultPermissionGroups); + }) + .collectList() + .block(); + + PermissionGroup adminPermissionGroup = permissionGroups.stream() + .filter(permissionGroup -> permissionGroup.getName().startsWith(FieldName.ADMINISTRATOR)) + .findFirst().get(); + + PermissionGroup developerPermissionGroup = permissionGroups.stream() + .filter(permissionGroup -> permissionGroup.getName().startsWith(FieldName.DEVELOPER)) + .findFirst().get(); + + PermissionGroup viewerPermissionGroup = permissionGroups.stream() + .filter(permissionGroup -> permissionGroup.getName().startsWith(FieldName.VIEWER)) + .findFirst().get(); + + Policy manageAppPolicy = Policy.builder().permission(MANAGE_APPLICATIONS.getValue()) + .permissionGroups(Set.of(adminPermissionGroup.getId(), developerPermissionGroup.getId())) + .build(); + Policy readAppPolicy = Policy.builder().permission(READ_APPLICATIONS.getValue()) + .permissionGroups(Set.of(adminPermissionGroup.getId(), developerPermissionGroup.getId(), + viewerPermissionGroup.getId())) + .build(); + + StepVerifier + .create(resultMono + .flatMap(applicationImportDTO -> { + Application application = applicationImportDTO.getApplication(); + return Mono.zip( + Mono.just(applicationImportDTO), + datasourceService.findAllByWorkspaceId(application.getWorkspaceId(), MANAGE_DATASOURCES).collectList(), + newActionService.findAllByApplicationIdAndViewMode(application.getId(), false, READ_ACTIONS, null).collectList(), + newPageService.findByApplicationId(application.getId(), MANAGE_PAGES, false).collectList(), + actionCollectionService.findAllByApplicationIdAndViewMode(application.getId(), false, MANAGE_ACTIONS, null).collectList() + ); + })) + .assertNext(tuple -> { + final Application application = tuple.getT1().getApplication(); + final List<Datasource> unConfiguredDatasourceList = tuple.getT1().getUnConfiguredDatasourceList(); + final boolean isPartialImport = tuple.getT1().getIsPartialImport(); + final List<Datasource> datasourceList = tuple.getT2(); + final List<NewAction> actionList = tuple.getT3(); + final List<PageDTO> pageList = tuple.getT4(); + final List<ActionCollection> actionCollectionList = tuple.getT5(); + + assertThat(application.getName()).isEqualTo("importExportTest"); + assertThat(application.getWorkspaceId()).isNotNull(); + assertThat(application.getPages()).hasSize(1); + assertThat(application.getPolicies()).containsAll(Set.of(manageAppPolicy, readAppPolicy)); + assertThat(application.getPublishedPages()).hasSize(1); + assertThat(application.getModifiedBy()).isEqualTo("api_user"); + assertThat(application.getUpdatedAt()).isNotNull(); + assertThat(application.getEditModeThemeId()).isNotNull(); + assertThat(application.getPublishedModeThemeId()).isNotNull(); + assertThat(isPartialImport).isEqualTo(Boolean.TRUE); + assertThat(unConfiguredDatasourceList.size()).isNotEqualTo(0); + + assertThat(datasourceList).isNotEmpty(); + List<String> datasourceNames = unConfiguredDatasourceList.stream().map(Datasource::getName).collect(Collectors.toList()); + assertThat(datasourceNames).contains("mongoDatasource", "postgresTest"); + + List<String> collectionIdInAction = new ArrayList<>(); + assertThat(actionList).isNotEmpty(); + actionList.forEach(newAction -> { + ActionDTO actionDTO = newAction.getUnpublishedAction(); + assertThat(actionDTO.getPageId()).isNotEqualTo(pageList.get(0).getName()); + if (!StringUtils.isEmpty(actionDTO.getCollectionId())) { + collectionIdInAction.add(actionDTO.getCollectionId()); + } + }); + + assertThat(actionCollectionList).isEmpty(); + + assertThat(pageList).hasSize(1); + + ApplicationPage defaultAppPage = application.getPages() + .stream() + .filter(ApplicationPage::getIsDefault) + .findFirst() + .orElse(null); + assertThat(defaultAppPage).isNotNull(); + + PageDTO defaultPageDTO = pageList.stream() + .filter(pageDTO -> pageDTO.getId().equals(defaultAppPage.getId())).findFirst().orElse(null); + + assertThat(defaultPageDTO).isNotNull(); + }) + .verifyComplete(); + } + + public void importApplicationIntoWorkspace_pageRemovedAndUpdatedDefaultPageNameInBranchApplication_Success() { + Application testApplication = new Application(); + testApplication.setName("importApplicationIntoWorkspace_pageRemovedInBranchApplication_Success"); + testApplication.setWorkspaceId(workspaceId); + testApplication.setUpdatedAt(Instant.now()); + testApplication.setLastDeployedAt(Instant.now()); + testApplication.setModifiedBy("some-user"); + testApplication.setGitApplicationMetadata(new GitApplicationMetadata()); + GitApplicationMetadata gitData = new GitApplicationMetadata(); + gitData.setBranchName("master"); + testApplication.setGitApplicationMetadata(gitData); + + Application application = applicationPageService.createApplication(testApplication, workspaceId) + .flatMap(application1 -> { + application1.getGitApplicationMetadata().setDefaultApplicationId(application1.getId()); + return applicationService.save(application1); + }).block(); + String gitSyncIdBeforeImport = newPageService.findById(application.getPages().get(0).getId(), MANAGE_PAGES).block().getGitSyncId(); + + PageDTO page = new PageDTO(); + page.setName("Page 2"); + page.setApplicationId(application.getId()); + PageDTO savedPage = applicationPageService.createPage(page).block(); + + assert application.getId() != null; + Set<String> applicationPageIdsBeforeImport = Objects.requireNonNull(applicationRepository.findById(application.getId()).block()) + .getPages() + .stream() + .map(ApplicationPage::getId) + .collect(Collectors.toSet()); + + ApplicationJson applicationJson = createAppJson("test_assets/ImportExportServiceTest/valid-application-with-page-removed.json").block(); + applicationJson.getPageList().get(0).setGitSyncId(gitSyncIdBeforeImport); + + Application importedApplication = importExportApplicationService.importApplicationInWorkspace(workspaceId, applicationJson, application.getId(), "master").block(); + + assert importedApplication != null; + Mono<List<NewPage>> pageList = Flux.fromIterable( + importedApplication + .getPages() + .stream() + .map(ApplicationPage::getId) + .collect(Collectors.toList()) + ).flatMap(s -> newPageService.findById(s, MANAGE_PAGES)).collectList(); + + StepVerifier + .create(pageList) + .assertNext(newPages -> { + // Check before import we had both the pages + assertThat(applicationPageIdsBeforeImport).hasSize(2); + assertThat(applicationPageIdsBeforeImport).contains(savedPage.getId()); + + assertThat(newPages.size()).isEqualTo(1); + assertThat(importedApplication.getPages().size()).isEqualTo(1); + assertThat(importedApplication.getPages().get(0).getId()).isEqualTo(newPages.get(0).getId()); + assertThat(newPages.get(0).getPublishedPage().getName()).isEqualTo("importedPage"); + assertThat(newPages.get(0).getGitSyncId()).isEqualTo(gitSyncIdBeforeImport); + + }) + .verifyComplete(); + } + + @Test + @WithUserDetails(value = "api_user") + public void importApplicationIntoWorkspace_pageAddedInBranchApplication_Success() { + Application testApplication = new Application(); + testApplication.setName("importApplicationIntoWorkspace_pageAddedInBranchApplication_Success"); + testApplication.setWorkspaceId(workspaceId); + testApplication.setUpdatedAt(Instant.now()); + testApplication.setLastDeployedAt(Instant.now()); + testApplication.setModifiedBy("some-user"); + testApplication.setGitApplicationMetadata(new GitApplicationMetadata()); + GitApplicationMetadata gitData = new GitApplicationMetadata(); + gitData.setBranchName("master"); + testApplication.setGitApplicationMetadata(gitData); + + Application application = applicationPageService.createApplication(testApplication, workspaceId) + .flatMap(application1 -> { + application1.getGitApplicationMetadata().setDefaultApplicationId(application1.getId()); + return applicationService.save(application1); + }).block(); + + String gitSyncIdBeforeImport = newPageService.findById(application.getPages().get(0).getId(), MANAGE_PAGES).block().getGitSyncId(); + + assert application.getId() != null; + Set<String> applicationPageIdsBeforeImport = Objects.requireNonNull(applicationRepository.findById(application.getId()).block()) + .getPages() + .stream() + .map(ApplicationPage::getId) + .collect(Collectors.toSet()); + + ApplicationJson applicationJson = createAppJson("test_assets/ImportExportServiceTest/valid-application-with-page-added.json").block(); + applicationJson.getPageList().get(0).setGitSyncId(gitSyncIdBeforeImport); + + Application applicationMono = importExportApplicationService.importApplicationInWorkspace(workspaceId, applicationJson, application.getId(), "master").block(); + + Mono<List<NewPage>> pageList = Flux.fromIterable( + applicationMono.getPages() + .stream() + .map(ApplicationPage::getId) + .collect(Collectors.toList()) + ).flatMap(s -> newPageService.findById(s, MANAGE_PAGES)).collectList(); + + StepVerifier + .create(pageList) + .assertNext(newPages -> { + // Check before import we had both the pages + assertThat(applicationPageIdsBeforeImport).hasSize(1); + assertThat(newPages.size()).isEqualTo(3); + List<String> pageNames = newPages.stream().map(newPage -> newPage.getUnpublishedPage().getName()).collect(Collectors.toList()); + assertThat(pageNames).contains("Page1"); + assertThat(pageNames).contains("Page2"); + assertThat(pageNames).contains("Page3"); + }) + .verifyComplete(); + + } + + @Test + @WithUserDetails(value = "api_user") + public void importUpdatedApplicationIntoWorkspaceFromFile_publicApplication_visibilityFlagNotReset() { + // Create a application and make it public + // Now add a page and export the same import it to the app + // Check if the policies and visibility flag are not reset + + Mono<Workspace> workspaceResponse = workspaceService.findById(workspaceId, READ_WORKSPACES); + + List<PermissionGroup> permissionGroups = workspaceResponse + .flatMapMany(savedWorkspace -> { + Set<String> defaultPermissionGroups = savedWorkspace.getDefaultPermissionGroups(); + return permissionGroupRepository.findAllById(defaultPermissionGroups); + }) + .collectList() + .block(); + + PermissionGroup adminPermissionGroup = permissionGroups.stream() + .filter(permissionGroup -> permissionGroup.getName().startsWith(FieldName.ADMINISTRATOR)) + .findFirst().get(); + + PermissionGroup developerPermissionGroup = permissionGroups.stream() + .filter(permissionGroup -> permissionGroup.getName().startsWith(FieldName.DEVELOPER)) + .findFirst().get(); + + PermissionGroup viewerPermissionGroup = permissionGroups.stream() + .filter(permissionGroup -> permissionGroup.getName().startsWith(FieldName.VIEWER)) + .findFirst().get(); + + Application testApplication = new Application(); + testApplication.setName("importUpdatedApplicationIntoWorkspaceFromFile_publicApplication_visibilityFlagNotReset"); + testApplication.setWorkspaceId(workspaceId); + testApplication.setUpdatedAt(Instant.now()); + testApplication.setLastDeployedAt(Instant.now()); + testApplication.setModifiedBy("some-user"); + testApplication.setGitApplicationMetadata(new GitApplicationMetadata()); + GitApplicationMetadata gitData = new GitApplicationMetadata(); + gitData.setBranchName("master"); + testApplication.setGitApplicationMetadata(gitData); + + Application application = applicationPageService.createApplication(testApplication, workspaceId) + .flatMap(application1 -> { + application1.getGitApplicationMetadata().setDefaultApplicationId(application1.getId()); + return applicationService.save(application1); + }).block(); + ApplicationAccessDTO applicationAccessDTO = new ApplicationAccessDTO(); + applicationAccessDTO.setPublicAccess(true); + Application newApplication = applicationService.changeViewAccess(application.getId(), "master", applicationAccessDTO).block(); + + PermissionGroup anonymousPermissionGroup = permissionGroupService.getPublicPermissionGroup().block(); + + Policy manageAppPolicy = Policy.builder().permission(MANAGE_APPLICATIONS.getValue()) + .permissionGroups(Set.of(adminPermissionGroup.getId(), developerPermissionGroup.getId())) + .build(); + Policy readAppPolicy = Policy.builder().permission(READ_APPLICATIONS.getValue()) + .permissionGroups(Set.of(adminPermissionGroup.getId(), developerPermissionGroup.getId(), + viewerPermissionGroup.getId(), anonymousPermissionGroup.getId())) + .build(); + + Mono<Application> applicationMono = importExportApplicationService.exportApplicationById(application.getId(), "master") + .flatMap(applicationJson -> importExportApplicationService.importApplicationInWorkspace(workspaceId, applicationJson, application.getId(), "master")); + + StepVerifier + .create(applicationMono) + .assertNext(application1 -> { + assertThat(application1.getIsPublic()).isEqualTo(Boolean.TRUE); + assertThat(application1.getPolicies()).containsAll(Set.of(manageAppPolicy, readAppPolicy)); + }) + .verifyComplete(); + } + + /** + * Testcase for checking the discard changes flow for following events: + * 1. Import application in org + * 2. Add new page to the imported application + * 3. User tries to import application from same application json file + * 4. Added page will be removed + */ + @Test + @WithUserDetails(value = "api_user") + public void discardChange_addNewPageAfterImport_addedPageRemoved() { + + /* + 1. Import application + 2. Add single page to imported app + 3. Import the application from same JSON with applicationId + 4. Added page should be deleted from DB + */ + Mono<ApplicationJson> applicationJsonMono = createAppJson("test_assets/ImportExportServiceTest/valid-application.json"); + String workspaceId = createTemplateWorkspace().getId(); + final Mono<Application> resultMonoWithoutDiscardOperation = applicationJsonMono + .flatMap(applicationJson -> { + applicationJson.getExportedApplication().setName("discard-change-page-added"); + return importExportApplicationService.importApplicationInWorkspace(workspaceId, applicationJson); + }) + .flatMap(application -> { + PageDTO page = new PageDTO(); + page.setName("discard-page-test"); + page.setApplicationId(application.getId()); + return applicationPageService.createPage(page); + }) + .flatMap(page -> applicationRepository.findById(page.getApplicationId())) + .cache(); + + StepVerifier + .create(resultMonoWithoutDiscardOperation + .flatMap(application -> Mono.zip( + Mono.just(application), + newPageService.findByApplicationId(application.getId(), MANAGE_PAGES, false).collectList() + ))) + .assertNext(tuple -> { + final Application application = tuple.getT1(); + final List<PageDTO> pageList = tuple.getT2(); + + assertThat(application.getName()).isEqualTo("discard-change-page-added"); + assertThat(application.getWorkspaceId()).isNotNull(); + assertThat(application.getPages()).hasSize(3); + assertThat(application.getPublishedPages()).hasSize(1); + assertThat(application.getModifiedBy()).isEqualTo("api_user"); + assertThat(application.getUpdatedAt()).isNotNull(); + assertThat(application.getEditModeThemeId()).isNotNull(); + assertThat(application.getPublishedModeThemeId()).isNotNull(); + + assertThat(pageList).hasSize(3); + + ApplicationPage defaultAppPage = application.getPages() + .stream() + .filter(ApplicationPage::getIsDefault) + .findFirst() + .orElse(null); + assertThat(defaultAppPage).isNotNull(); + + PageDTO defaultPageDTO = pageList.stream() + .filter(pageDTO -> pageDTO.getId().equals(defaultAppPage.getId())).findFirst().orElse(null); + + assertThat(defaultPageDTO).isNotNull(); + assertThat(defaultPageDTO.getLayouts().get(0).getLayoutOnLoadActions()).isNotEmpty(); + + List<String> pageNames = new ArrayList<>(); + pageList.forEach(page -> pageNames.add(page.getName())); + assertThat(pageNames).contains("discard-page-test"); + }) + .verifyComplete(); + + // Import the same application again to find if the added page is deleted + final Mono<Application> resultMonoWithDiscardOperation = resultMonoWithoutDiscardOperation + .flatMap(importedApplication -> + applicationJsonMono + .flatMap(applicationJson -> + { + importedApplication.setGitApplicationMetadata(new GitApplicationMetadata()); + importedApplication.getGitApplicationMetadata().setDefaultApplicationId(importedApplication.getId()); + return applicationService.save(importedApplication) + .then(importExportApplicationService.importApplicationInWorkspace( + importedApplication.getWorkspaceId(), + applicationJson, + importedApplication.getId(), + "main") + ); + } + ) + ); + + StepVerifier + .create(resultMonoWithDiscardOperation + .flatMap(application -> Mono.zip( + Mono.just(application), + newPageService.findByApplicationId(application.getId(), MANAGE_PAGES, false).collectList() + ))) + .assertNext(tuple -> { + final Application application = tuple.getT1(); + final List<PageDTO> pageList = tuple.getT2(); + + assertThat(application.getPages()).hasSize(2); + assertThat(application.getPublishedPages()).hasSize(1); + + assertThat(pageList).hasSize(2); + + List<String> pageNames = new ArrayList<>(); + pageList.forEach(page -> pageNames.add(page.getName())); + assertThat(pageNames).doesNotContain("discard-page-test"); + }) + .verifyComplete(); + } + + /** + * Testcase for checking the discard changes flow for following events: + * 1. Import application in org + * 2. Add new action to the imported application + * 3. User tries to import application from same application json file + * 4. Added action will be removed + */ + @Test + @WithUserDetails(value = "api_user") + public void discardChange_addNewActionAfterImport_addedActionRemoved() { + + Mono<ApplicationJson> applicationJsonMono = createAppJson("test_assets/ImportExportServiceTest/valid-application.json"); + String workspaceId = createTemplateWorkspace().getId(); + + final Mono<Application> resultMonoWithoutDiscardOperation = applicationJsonMono + .flatMap(applicationJson -> { + applicationJson.getExportedApplication().setName("discard-change-action-added"); + return importExportApplicationService.importApplicationInWorkspace(workspaceId, applicationJson); + }) + .flatMap(application -> { + ActionDTO action = new ActionDTO(); + ActionConfiguration actionConfiguration = new ActionConfiguration(); + actionConfiguration.setHttpMethod(HttpMethod.GET); + action.setActionConfiguration(actionConfiguration); + action.setDatasource(datasourceMap.get("DS1")); + action.setName("discard-action-test"); + action.setPageId(application.getPages().get(0).getId()); + return layoutActionService.createAction(action); + }) + .flatMap(actionDTO -> newActionService.getById(actionDTO.getId())) + .flatMap(newAction -> applicationRepository.findById(newAction.getApplicationId())) + .cache(); + + StepVerifier + .create(resultMonoWithoutDiscardOperation + .flatMap(application -> Mono.zip( + Mono.just(application), + getActionsInApplication(application).collectList() + ))) + .assertNext(tuple -> { + final Application application = tuple.getT1(); + final List<ActionDTO> actionList = tuple.getT2(); + + assertThat(application.getName()).isEqualTo("discard-change-action-added"); + assertThat(application.getWorkspaceId()).isNotNull(); + + + List<String> actionNames = new ArrayList<>(); + actionList.forEach(actionDTO -> actionNames.add(actionDTO.getName())); + assertThat(actionNames).contains("discard-action-test"); + }) + .verifyComplete(); + + // Import the same application again + final Mono<Application> resultMonoWithDiscardOperation = resultMonoWithoutDiscardOperation + .flatMap(importedApplication -> + applicationJsonMono + .flatMap(applicationJson -> { + importedApplication.setGitApplicationMetadata(new GitApplicationMetadata()); + importedApplication.getGitApplicationMetadata().setDefaultApplicationId(importedApplication.getId()); + return applicationService.save(importedApplication) + .then(importExportApplicationService.importApplicationInWorkspace( + importedApplication.getWorkspaceId(), + applicationJson, + importedApplication.getId(), + "main") + ); + } + ) + ); + + StepVerifier + .create(resultMonoWithDiscardOperation + .flatMap(application -> Mono.zip( + Mono.just(application), + getActionsInApplication(application).collectList() + ))) + .assertNext(tuple -> { + final Application application = tuple.getT1(); + final List<ActionDTO> actionList = tuple.getT2(); + + assertThat(application.getWorkspaceId()).isNotNull(); + + List<String> actionNames = new ArrayList<>(); + actionList.forEach(actionDTO -> actionNames.add(actionDTO.getName())); + assertThat(actionNames).doesNotContain("discard-action-test"); + }) + .verifyComplete(); + } + + /** + * Testcase for checking the discard changes flow for following events: + * 1. Import application in org + * 2. Add actionCollection to the imported application + * 3. User tries to import application from same application json file + * 4. Added actionCollection will be removed + */ + @Test + @WithUserDetails(value = "api_user") + public void discardChange_addNewActionCollectionAfterImport_addedActionCollectionRemoved() { + + Mono<ApplicationJson> applicationJsonMono = createAppJson("test_assets/ImportExportServiceTest/valid-application-without-action-collection.json"); + String workspaceId = createTemplateWorkspace().getId(); + final Mono<Application> resultMonoWithoutDiscardOperation = applicationJsonMono + .flatMap(applicationJson -> { + applicationJson.getExportedApplication().setName("discard-change-collection-added"); + return importExportApplicationService.importApplicationInWorkspace(workspaceId, applicationJson); + }) + .flatMap(application -> { + ActionCollectionDTO actionCollectionDTO1 = new ActionCollectionDTO(); + actionCollectionDTO1.setName("discard-action-collection-test"); + actionCollectionDTO1.setPageId(application.getPages().get(0).getId()); + actionCollectionDTO1.setApplicationId(application.getId()); + actionCollectionDTO1.setWorkspaceId(application.getWorkspaceId()); + actionCollectionDTO1.setPluginId(jsDatasource.getPluginId()); + ActionDTO action1 = new ActionDTO(); + action1.setName("discard-action-collection-test-action"); + action1.setActionConfiguration(new ActionConfiguration()); + action1.getActionConfiguration().setBody("mockBody"); + actionCollectionDTO1.setActions(List.of(action1)); + actionCollectionDTO1.setPluginType(PluginType.JS); + + return layoutCollectionService.createCollection(actionCollectionDTO1); + }) + .flatMap(actionCollectionDTO -> actionCollectionService.getById(actionCollectionDTO.getId())) + .flatMap(actionCollection -> applicationRepository.findById(actionCollection.getApplicationId())) + .cache(); + + StepVerifier + .create(resultMonoWithoutDiscardOperation + .flatMap(application -> Mono.zip( + Mono.just(application), + actionCollectionService.findAllByApplicationIdAndViewMode(application.getId(), false, READ_ACTIONS, null).collectList(), + getActionsInApplication(application).collectList() + ))) + .assertNext(tuple -> { + final Application application = tuple.getT1(); + final List<ActionCollection> actionCollectionList = tuple.getT2(); + final List<ActionDTO> actionList = tuple.getT3(); + + assertThat(application.getName()).isEqualTo("discard-change-collection-added"); + assertThat(application.getWorkspaceId()).isNotNull(); + + List<String> actionCollectionNames = new ArrayList<>(); + actionCollectionList.forEach(actionCollection -> actionCollectionNames.add(actionCollection.getUnpublishedCollection().getName())); + assertThat(actionCollectionNames).contains("discard-action-collection-test"); + + List<String> actionNames = new ArrayList<>(); + actionList.forEach(actionDTO -> actionNames.add(actionDTO.getName())); + assertThat(actionNames).contains("discard-action-collection-test-action"); + }) + .verifyComplete(); + + // Import the same application again + final Mono<Application> resultMonoWithDiscardOperation = resultMonoWithoutDiscardOperation + .flatMap(importedApplication -> + applicationJsonMono + .flatMap(applicationJson -> + { + importedApplication.setGitApplicationMetadata(new GitApplicationMetadata()); + importedApplication.getGitApplicationMetadata().setDefaultApplicationId(importedApplication.getId()); + return applicationService.save(importedApplication) + .then(importExportApplicationService.importApplicationInWorkspace( + importedApplication.getWorkspaceId(), + applicationJson, + importedApplication.getId(), + "main") + ); + } + ) + ); + + StepVerifier + .create(resultMonoWithDiscardOperation + .flatMap(application -> Mono.zip( + Mono.just(application), + actionCollectionService.findAllByApplicationIdAndViewMode(application.getId(), false, READ_ACTIONS, null).collectList(), + getActionsInApplication(application).collectList() + ))) + .assertNext(tuple -> { + final Application application = tuple.getT1(); + final List<ActionCollection> actionCollectionList = tuple.getT2(); + final List<ActionDTO> actionList = tuple.getT3(); + + assertThat(application.getWorkspaceId()).isNotNull(); + + List<String> actionCollectionNames = new ArrayList<>(); + actionCollectionList.forEach(actionCollection -> actionCollectionNames.add(actionCollection.getUnpublishedCollection().getName())); + assertThat(actionCollectionNames).doesNotContain("discard-action-collection-test"); + + List<String> actionNames = new ArrayList<>(); + actionList.forEach(actionDTO -> actionNames.add(actionDTO.getName())); + assertThat(actionNames).doesNotContain("discard-action-collection-test-action"); + }) + .verifyComplete(); + } + + /** + * Testcase for checking the discard changes flow for following events: + * 1. Import application in org + * 2. Remove existing page from imported application + * 3. Import application from same application json file + * 4. Removed page will be restored + */ + @Test + @WithUserDetails(value = "api_user") + public void discardChange_removeNewPageAfterImport_removedPageRestored() { + + Mono<ApplicationJson> applicationJsonMono = createAppJson("test_assets/ImportExportServiceTest/valid-application.json"); + String workspaceId = createTemplateWorkspace().getId(); + final Mono<Application> resultMonoWithoutDiscardOperation = applicationJsonMono + .flatMap(applicationJson -> { + applicationJson.getExportedApplication().setName("discard-change-page-removed"); + return importExportApplicationService.importApplicationInWorkspace(workspaceId, applicationJson); + }) + .flatMap(application -> { + Optional<ApplicationPage> applicationPage = application + .getPages() + .stream() + .filter(page -> !page.isDefault()) + .findFirst(); + return applicationPageService.deleteUnpublishedPage(applicationPage.get().getId()); + }) + .flatMap(page -> applicationRepository.findById(page.getApplicationId())) + .cache(); + + StepVerifier + .create(resultMonoWithoutDiscardOperation + .flatMap(application -> Mono.zip( + Mono.just(application), + newPageService.findByApplicationId(application.getId(), MANAGE_PAGES, false).collectList() + ))) + .assertNext(tuple -> { + final Application application = tuple.getT1(); + final List<PageDTO> pageList = tuple.getT2(); + + assertThat(application.getName()).isEqualTo("discard-change-page-removed"); + assertThat(application.getWorkspaceId()).isNotNull(); + assertThat(application.getPages()).hasSize(1); + + assertThat(pageList).hasSize(1); + }) + .verifyComplete(); + + // Import the same application again + final Mono<Application> resultMonoWithDiscardOperation = resultMonoWithoutDiscardOperation + .flatMap(importedApplication -> + applicationJsonMono + .flatMap(applicationJson -> + { + importedApplication.setGitApplicationMetadata(new GitApplicationMetadata()); + importedApplication.getGitApplicationMetadata().setDefaultApplicationId(importedApplication.getId()); + return applicationService.save(importedApplication) + .then(importExportApplicationService.importApplicationInWorkspace( + importedApplication.getWorkspaceId(), + applicationJson, + importedApplication.getId(), + "main") + ); + } + ) + ); + + StepVerifier + .create(resultMonoWithDiscardOperation + .flatMap(application -> Mono.zip( + Mono.just(application), + newPageService.findByApplicationId(application.getId(), MANAGE_PAGES, false).collectList() + ))) + .assertNext(tuple -> { + final Application application = tuple.getT1(); + final List<PageDTO> pageList = tuple.getT2(); + + assertThat(application.getPages()).hasSize(2); + assertThat(application.getPublishedPages()).hasSize(1); + + assertThat(pageList).hasSize(2); + }) + .verifyComplete(); + } + + /** + * Testcase for checking the discard changes flow for following events: + * 1. Import application in org + * 2. Remove existing action from imported application + * 3. Import application from same application json file + * 4. Removed action will be restored + */ + @Test + @WithUserDetails(value = "api_user") + public void discardChange_removeNewActionAfterImport_removedActionRestored() { + + Mono<ApplicationJson> applicationJsonMono = createAppJson("test_assets/ImportExportServiceTest/valid-application.json"); + String workspaceId = createTemplateWorkspace().getId(); + final String[] deletedActionName = new String[1]; + final Mono<Application> resultMonoWithoutDiscardOperation = applicationJsonMono + .flatMap(applicationJson -> { + applicationJson.getExportedApplication().setName("discard-change-action-removed"); + return importExportApplicationService.importApplicationInWorkspace(workspaceId, applicationJson); + }) + .flatMap(application -> { + return getActionsInApplication(application) + .next() + .flatMap(actionDTO -> { + deletedActionName[0] = actionDTO.getName(); + return newActionService.deleteUnpublishedAction(actionDTO.getId()); + }) + .then(applicationPageService.publish(application.getId(), true)); + }) + .cache(); + + StepVerifier + .create(resultMonoWithoutDiscardOperation + .flatMap(application -> Mono.zip( + Mono.just(application), + getActionsInApplication(application).collectList() + ))) + .assertNext(tuple -> { + final Application application = tuple.getT1(); + final List<ActionDTO> actionList = tuple.getT2(); + + assertThat(application.getName()).isEqualTo("discard-change-action-removed"); + assertThat(application.getWorkspaceId()).isNotNull(); + + List<String> actionNames = new ArrayList<>(); + actionList.forEach(actionDTO -> actionNames.add(actionDTO.getName())); + assertThat(actionNames).doesNotContain(deletedActionName[0]); + }) + .verifyComplete(); + + // Import the same application again + final Mono<Application> resultMonoWithDiscardOperation = resultMonoWithoutDiscardOperation + .flatMap(importedApplication -> + applicationJsonMono + .flatMap(applicationJson -> + { + importedApplication.setGitApplicationMetadata(new GitApplicationMetadata()); + importedApplication.getGitApplicationMetadata().setDefaultApplicationId(importedApplication.getId()); + return applicationService.save(importedApplication) + .then(importExportApplicationService.importApplicationInWorkspace( + importedApplication.getWorkspaceId(), + applicationJson, + importedApplication.getId(), + "main") + ); + } + ) + ); + + StepVerifier + .create(resultMonoWithDiscardOperation + .flatMap(application -> Mono.zip( + Mono.just(application), + getActionsInApplication(application).collectList() + ))) + .assertNext(tuple -> { + final Application application = tuple.getT1(); + final List<ActionDTO> actionList = tuple.getT2(); + + assertThat(application.getWorkspaceId()).isNotNull(); + + List<String> actionNames = new ArrayList<>(); + actionList.forEach(actionDTO -> actionNames.add(actionDTO.getName())); + assertThat(actionNames).contains(deletedActionName[0]); + }) + .verifyComplete(); + } + + /** + * Testcase for checking the discard changes flow for following events: + * 1. Import application in org + * 2. Remove existing actionCollection from imported application + * 3. Import application from same application json file + * 4. Removed actionCollection along-with actions will be restored + */ + @Test + @WithUserDetails(value = "api_user") + public void discardChange_removeNewActionCollection_removedActionCollectionRestored() { + + Mono<ApplicationJson> applicationJsonMono = createAppJson("test_assets/ImportExportServiceTest/valid-application.json"); + String workspaceId = createTemplateWorkspace().getId(); + final String[] deletedActionCollectionNames = new String[1]; + final Mono<Application> resultMonoWithoutDiscardOperation = applicationJsonMono + .flatMap(applicationJson -> { + applicationJson.getExportedApplication().setName("discard-change-collection-removed"); + return importExportApplicationService.importApplicationInWorkspace(workspaceId, applicationJson); + }) + .flatMap(application -> { + return actionCollectionService.findAllByApplicationIdAndViewMode(application.getId(), false, READ_ACTIONS, null) + .next() + .flatMap(actionCollection -> { + deletedActionCollectionNames[0] = actionCollection.getUnpublishedCollection().getName(); + return actionCollectionService.deleteUnpublishedActionCollection(actionCollection.getId()); + }) + .then(applicationPageService.publish(application.getId(), true)); + }) + .cache(); + + StepVerifier + .create(resultMonoWithoutDiscardOperation + .flatMap(application -> Mono.zip( + Mono.just(application), + actionCollectionService.findAllByApplicationIdAndViewMode(application.getId(), false, READ_ACTIONS, null).collectList() + ))) + .assertNext(tuple -> { + final Application application = tuple.getT1(); + final List<ActionCollection> actionCollectionList = tuple.getT2(); + + assertThat(application.getName()).isEqualTo("discard-change-collection-removed"); + assertThat(application.getWorkspaceId()).isNotNull(); + + List<String> actionCollectionNames = new ArrayList<>(); + actionCollectionList.forEach(actionCollection -> actionCollectionNames.add(actionCollection.getUnpublishedCollection().getName())); + assertThat(actionCollectionNames).doesNotContain(deletedActionCollectionNames); + }) + .verifyComplete(); + + // Import the same application again + final Mono<Application> resultMonoWithDiscardOperation = resultMonoWithoutDiscardOperation + .flatMap(importedApplication -> + applicationJsonMono + .flatMap(applicationJson -> + { + importedApplication.setGitApplicationMetadata(new GitApplicationMetadata()); + importedApplication.getGitApplicationMetadata().setDefaultApplicationId(importedApplication.getId()); + return applicationService.save(importedApplication) + .then(importExportApplicationService.importApplicationInWorkspace( + importedApplication.getWorkspaceId(), + applicationJson, + importedApplication.getId(), + "main") + ); + } + ) + ); + + StepVerifier + .create(resultMonoWithDiscardOperation + .flatMap(application -> Mono.zip( + Mono.just(application), + actionCollectionService.findAllByApplicationIdAndViewMode(application.getId(), false, READ_ACTIONS, null).collectList() + ))) + .assertNext(tuple -> { + final Application application = tuple.getT1(); + final List<ActionCollection> actionCollectionList = tuple.getT2(); + + assertThat(application.getWorkspaceId()).isNotNull(); + + List<String> actionCollectionNames = new ArrayList<>(); + actionCollectionList.forEach(actionCollection -> actionCollectionNames.add(actionCollection.getUnpublishedCollection().getName())); + assertThat(actionCollectionNames).contains(deletedActionCollectionNames); + }) + .verifyComplete(); + } + + @Test + @WithUserDetails(value = "api_user") + public void applySchemaMigration_jsonFileWithFirstVersion_migratedToLatestVersionSuccess() { + FilePart filePart = createFilePart("test_assets/ImportExportServiceTest/file-with-v1.json"); + + Mono<String> stringifiedFile = DataBufferUtils.join(filePart.content()) + .map(dataBuffer -> { + byte[] data = new byte[dataBuffer.readableByteCount()]; + dataBuffer.read(data); + DataBufferUtils.release(dataBuffer); + return new String(data); + }); + Mono<ApplicationJson> v1ApplicationMono = stringifiedFile + .map(data -> { + Gson gson = new Gson(); + return gson.fromJson(data, ApplicationJson.class); + }).cache(); + + Mono<ApplicationJson> migratedApplicationMono = v1ApplicationMono + .map(applicationJson -> { + ApplicationJson applicationJson1 = new ApplicationJson(); + AppsmithBeanUtils.copyNestedNonNullProperties(applicationJson, applicationJson1); + return JsonSchemaMigration.migrateApplicationToLatestSchema(applicationJson1); + }); + + StepVerifier + .create(Mono.zip(v1ApplicationMono, migratedApplicationMono)) + .assertNext(tuple -> { + ApplicationJson v1ApplicationJson = tuple.getT1(); + ApplicationJson latestApplicationJson = tuple.getT2(); + + assertThat(v1ApplicationJson.getServerSchemaVersion()).isEqualTo(1); + assertThat(v1ApplicationJson.getClientSchemaVersion()).isEqualTo(1); + + assertThat(latestApplicationJson.getServerSchemaVersion()).isEqualTo(JsonSchemaVersions.serverVersion); + assertThat(latestApplicationJson.getClientSchemaVersion()).isEqualTo(JsonSchemaVersions.clientVersion); + }) + .verifyComplete(); + } + + /** + * Testcase to check if the application is exported with the datasource configuration object if this setting is + * enabled from application object + * This can be enabled with exportWithConfiguration: true + */ + @Test + @WithUserDetails(value = "api_user") + public void exportApplication_withDatasourceConfig_exportedWithDecryptedFields() { + Workspace newWorkspace = new Workspace(); + newWorkspace.setName("template-org-with-ds"); + + Application testApplication = new Application(); + testApplication.setName("exportApplication_withCredentialsForSampleApps_SuccessWithDecryptFields"); + testApplication.setExportWithConfiguration(true); + testApplication = applicationPageService.createApplication(testApplication, workspaceId).block(); + assert testApplication != null; + exportWithConfigurationAppId = testApplication.getId(); + ApplicationAccessDTO accessDTO = new ApplicationAccessDTO(); + accessDTO.setPublicAccess(true); + applicationService.changeViewAccess(exportWithConfigurationAppId, accessDTO).block(); + final String appName = testApplication.getName(); + final Mono<ApplicationJson> resultMono = Mono.zip( + Mono.just(testApplication), + newPageService.findPageById(testApplication.getPages().get(0).getId(), READ_PAGES, false) + ) + .flatMap(tuple -> { + Application testApp = tuple.getT1(); + PageDTO testPage = tuple.getT2(); + + Layout layout = testPage.getLayouts().get(0); + ObjectMapper objectMapper = new ObjectMapper(); + JSONObject dsl = new JSONObject(); + try { + dsl = new JSONObject(objectMapper.readValue(DEFAULT_PAGE_LAYOUT, new TypeReference<HashMap<String, Object>>() { + })); + } catch (JsonProcessingException e) { + e.printStackTrace(); + } + + ArrayList children = (ArrayList) dsl.get("children"); + JSONObject testWidget = new JSONObject(); + testWidget.put("widgetName", "firstWidget"); + JSONArray temp = new JSONArray(); + temp.addAll(List.of(new JSONObject(Map.of("key", "testField")))); + testWidget.put("dynamicBindingPathList", temp); + testWidget.put("testField", "{{ validAction.data }}"); + children.add(testWidget); + + layout.setDsl(dsl); + layout.setPublishedDsl(dsl); + + ActionDTO action = new ActionDTO(); + action.setName("validAction"); + action.setPageId(testPage.getId()); + action.setExecuteOnLoad(true); + ActionConfiguration actionConfiguration = new ActionConfiguration(); + actionConfiguration.setHttpMethod(HttpMethod.GET); + action.setActionConfiguration(actionConfiguration); + action.setDatasource(datasourceMap.get("DS2")); + + ActionDTO action2 = new ActionDTO(); + action2.setName("validAction2"); + action2.setPageId(testPage.getId()); + action2.setExecuteOnLoad(true); + action2.setUserSetOnLoad(true); + ActionConfiguration actionConfiguration2 = new ActionConfiguration(); + actionConfiguration2.setHttpMethod(HttpMethod.GET); + action2.setActionConfiguration(actionConfiguration2); + action2.setDatasource(datasourceMap.get("DS2")); + + ActionCollectionDTO actionCollectionDTO1 = new ActionCollectionDTO(); + actionCollectionDTO1.setName("testCollection1"); + actionCollectionDTO1.setPageId(testPage.getId()); + actionCollectionDTO1.setApplicationId(testApp.getId()); + actionCollectionDTO1.setWorkspaceId(testApp.getWorkspaceId()); + actionCollectionDTO1.setPluginId(jsDatasource.getPluginId()); + ActionDTO action1 = new ActionDTO(); + action1.setName("testAction1"); + action1.setActionConfiguration(new ActionConfiguration()); + action1.getActionConfiguration().setBody("mockBody"); + actionCollectionDTO1.setActions(List.of(action1)); + actionCollectionDTO1.setPluginType(PluginType.JS); + + return layoutCollectionService.createCollection(actionCollectionDTO1) + .then(layoutActionService.createSingleAction(action)) + .then(layoutActionService.createSingleAction(action2)) + .then(layoutActionService.updateLayout(testPage.getId(), testPage.getApplicationId(), layout.getId(), layout)) + .then(importExportApplicationService.exportApplicationById(testApp.getId(), "")); + }) + .cache(); + + Mono<List<NewAction>> actionListMono = resultMono + .then(newActionService + .findAllByApplicationIdAndViewMode(testApplication.getId(), false, READ_ACTIONS, null).collectList()); + + Mono<List<ActionCollection>> collectionListMono = resultMono.then( + actionCollectionService + .findAllByApplicationIdAndViewMode(testApplication.getId(), false, READ_ACTIONS, null).collectList()); + + Mono<List<NewPage>> pageListMono = resultMono.then( + newPageService + .findNewPagesByApplicationId(testApplication.getId(), READ_PAGES).collectList()); + + StepVerifier + .create(Mono.zip(resultMono, actionListMono, collectionListMono, pageListMono)) + .assertNext(tuple -> { + + ApplicationJson applicationJson = tuple.getT1(); + List<NewAction> DBActions = tuple.getT2(); + List<ActionCollection> DBCollections = tuple.getT3(); + List<NewPage> DBPages = tuple.getT4(); + + Application exportedApp = applicationJson.getExportedApplication(); + List<NewPage> pageList = applicationJson.getPageList(); + List<NewAction> actionList = applicationJson.getActionList(); + List<ActionCollection> actionCollectionList = applicationJson.getActionCollectionList(); + List<Datasource> datasourceList = applicationJson.getDatasourceList(); + + List<String> exportedCollectionIds = actionCollectionList.stream().map(ActionCollection::getId).collect(Collectors.toList()); + List<String> exportedActionIds = actionList.stream().map(NewAction::getId).collect(Collectors.toList()); + List<String> DBCollectionIds = DBCollections.stream().map(ActionCollection::getId).collect(Collectors.toList()); + List<String> DBActionIds = DBActions.stream().map(NewAction::getId).collect(Collectors.toList()); + List<String> DBOnLayoutLoadActionIds = new ArrayList<>(); + List<String> exportedOnLayoutLoadActionIds = new ArrayList<>(); + + DBPages.forEach(newPage -> + newPage.getUnpublishedPage().getLayouts().forEach(layout -> { + if (layout.getLayoutOnLoadActions() != null) { + layout.getLayoutOnLoadActions().forEach(dslActionDTOSet -> { + dslActionDTOSet.forEach(actionDTO -> DBOnLayoutLoadActionIds.add(actionDTO.getId())); + }); + } + }) + ); + + pageList.forEach(newPage -> + newPage.getUnpublishedPage().getLayouts().forEach(layout -> { + if (layout.getLayoutOnLoadActions() != null) { + layout.getLayoutOnLoadActions().forEach(dslActionDTOSet -> { + dslActionDTOSet.forEach(actionDTO -> exportedOnLayoutLoadActionIds.add(actionDTO.getId())); + }); + } + }) + ); + + NewPage defaultPage = pageList.get(0); + + assertThat(exportedApp.getName()).isEqualTo(appName); + assertThat(exportedApp.getWorkspaceId()).isNull(); + assertThat(exportedApp.getPages()).hasSize(1); + ApplicationPage page = exportedApp.getPages().get(0); + + assertThat(page.getId()).isEqualTo(defaultPage.getUnpublishedPage().getName()); + assertThat(page.getIsDefault()).isTrue(); + assertThat(page.getDefaultPageId()).isNull(); + + assertThat(exportedApp.getPolicies()).isNull(); + + assertThat(pageList).hasSize(1); + assertThat(defaultPage.getApplicationId()).isNull(); + assertThat(defaultPage.getUnpublishedPage().getLayouts().get(0).getDsl()).isNotNull(); + assertThat(defaultPage.getId()).isNull(); + assertThat(defaultPage.getPolicies()).isNull(); + + assertThat(actionList.isEmpty()).isFalse(); + assertThat(actionList).hasSize(3); + NewAction validAction = actionList.stream().filter(action -> action.getId().equals("Page1_validAction")).findFirst().get(); + assertThat(validAction.getApplicationId()).isNull(); + assertThat(validAction.getPluginId()).isEqualTo(installedPlugin.getPackageName()); + assertThat(validAction.getPluginType()).isEqualTo(PluginType.API); + assertThat(validAction.getWorkspaceId()).isNull(); + assertThat(validAction.getPolicies()).isNull(); + assertThat(validAction.getId()).isNotNull(); + ActionDTO unpublishedAction = validAction.getUnpublishedAction(); + assertThat(unpublishedAction.getPageId()).isEqualTo(defaultPage.getUnpublishedPage().getName()); + assertThat(unpublishedAction.getDatasource().getPluginId()).isEqualTo(installedPlugin.getPackageName()); + + NewAction testAction1 = actionList.stream().filter(action -> action.getUnpublishedAction().getName().equals("testAction1")).findFirst().get(); + assertThat(testAction1.getId()).isEqualTo("Page1_testCollection1.testAction1"); + + assertThat(actionCollectionList.isEmpty()).isFalse(); + assertThat(actionCollectionList).hasSize(1); + final ActionCollection actionCollection = actionCollectionList.get(0); + assertThat(actionCollection.getApplicationId()).isNull(); + assertThat(actionCollection.getWorkspaceId()).isNull(); + assertThat(actionCollection.getPolicies()).isNull(); + assertThat(actionCollection.getId()).isNotNull(); + assertThat(actionCollection.getUnpublishedCollection().getPluginType()).isEqualTo(PluginType.JS); + assertThat(actionCollection.getUnpublishedCollection().getPageId()) + .isEqualTo(defaultPage.getUnpublishedPage().getName()); + assertThat(actionCollection.getUnpublishedCollection().getPluginId()).isEqualTo(installedJsPlugin.getPackageName()); + + assertThat(datasourceList).hasSize(1); + Datasource datasource = datasourceList.get(0); + assertThat(datasource.getWorkspaceId()).isNull(); + assertThat(datasource.getId()).isNull(); + assertThat(datasource.getPluginId()).isEqualTo(installedPlugin.getPackageName()); + assertThat(datasource.getDatasourceConfiguration()).isNotNull(); + + final Map<String, InvisibleActionFields> invisibleActionFields = applicationJson.getInvisibleActionFields(); + + assertThat(invisibleActionFields).isNull(); + for (NewAction newAction : actionList) { + if (newAction.getId().equals("Page1_validAction2")) { + assertEquals(true, newAction.getUnpublishedAction().getUserSetOnLoad()); + } else { + assertEquals(false, newAction.getUnpublishedAction().getUserSetOnLoad()); + } + } + + assertThat(applicationJson.getUnpublishedLayoutmongoEscapedWidgets()).isNull(); + assertThat(applicationJson.getPublishedLayoutmongoEscapedWidgets()).isNull(); + assertThat(applicationJson.getEditModeTheme()).isNotNull(); + assertThat(applicationJson.getEditModeTheme().isSystemTheme()).isTrue(); + assertThat(applicationJson.getEditModeTheme().getName()).isEqualToIgnoringCase(Theme.DEFAULT_THEME_NAME); + + assertThat(applicationJson.getPublishedTheme()).isNotNull(); + assertThat(applicationJson.getPublishedTheme().isSystemTheme()).isTrue(); + assertThat(applicationJson.getPublishedTheme().getName()).isEqualToIgnoringCase(Theme.DEFAULT_THEME_NAME); + + assertThat(exportedCollectionIds).isNotEmpty(); + assertThat(exportedCollectionIds).doesNotContain(String.valueOf(DBCollectionIds)); + + assertThat(exportedActionIds).isNotEmpty(); + assertThat(exportedActionIds).doesNotContain(String.valueOf(DBActionIds)); + + assertThat(exportedOnLayoutLoadActionIds).isNotEmpty(); + assertThat(exportedOnLayoutLoadActionIds).doesNotContain(String.valueOf(DBOnLayoutLoadActionIds)); + + assertThat(applicationJson.getDecryptedFields()).isNotNull(); + }) + .verifyComplete(); + } + + /** + * Test to check if the application can be exported with read only access if this is sample application + */ + @Test + @WithUserDetails(value = "[email protected]") + public void exportApplication_withReadOnlyAccess_exportedWithDecryptedFields() { + Mono<ApplicationJson> exportApplicationMono = importExportApplicationService + .exportApplicationById(exportWithConfigurationAppId, SerialiseApplicationObjective.SHARE); + + StepVerifier + .create(exportApplicationMono) + .assertNext(applicationJson -> { + assertThat(applicationJson.getExportedApplication()).isNotNull(); + assertThat(applicationJson.getDecryptedFields()).isNotNull(); + }) + .verifyComplete(); + } + + @Test + @WithUserDetails(value = "api_user") + public void importApplication_datasourceWithSameNameAndDifferentPlugin_importedWithValidActionsAndSuffixedDatasource() { + + ApplicationJson applicationJson = createAppJson("test_assets/ImportExportServiceTest/valid-application.json").block(); + + Workspace testWorkspace = new Workspace(); + testWorkspace.setName("Duplicate datasource with different plugin org"); + testWorkspace = workspaceService.create(testWorkspace).block(); + + Datasource testDatasource = new Datasource(); + // Chose any plugin except for mongo, as json static file has mongo plugin for datasource + Plugin postgreSQLPlugin = pluginRepository.findByName("PostgreSQL").block(); + testDatasource.setPluginId(postgreSQLPlugin.getId()); + testDatasource.setWorkspaceId(testWorkspace.getId()); + final String datasourceName = applicationJson.getDatasourceList().get(0).getName(); + testDatasource.setName(datasourceName); + datasourceService.create(testDatasource).block(); + + final Mono<Application> resultMono = importExportApplicationService.importApplicationInWorkspace(testWorkspace.getId(), applicationJson); + + StepVerifier + .create(resultMono + .flatMap(application -> Mono.zip( + Mono.just(application), + datasourceService.findAllByWorkspaceId(application.getWorkspaceId(), MANAGE_DATASOURCES).collectList(), + newActionService.findAllByApplicationIdAndViewMode(application.getId(), false, READ_ACTIONS, null).collectList() + ))) + .assertNext(tuple -> { + final Application application = tuple.getT1(); + final List<Datasource> datasourceList = tuple.getT2(); + final List<NewAction> actionList = tuple.getT3(); + + assertThat(application.getName()).isEqualTo("valid_application"); + + List<String> datasourceNameList = new ArrayList<>(); + assertThat(datasourceList).isNotEmpty(); + datasourceList.forEach(datasource -> { + assertThat(datasource.getWorkspaceId()).isEqualTo(application.getWorkspaceId()); + datasourceNameList.add(datasource.getName()); + }); + // Check if both suffixed and newly imported datasource are present + assertThat(datasourceNameList).contains(datasourceName, datasourceName + " #1"); + + assertThat(actionList).isNotEmpty(); + actionList.forEach(newAction -> { + ActionDTO actionDTO = newAction.getUnpublishedAction(); + assertThat(actionDTO.getDatasource()).isNotNull(); + }); + }) + .verifyComplete(); + } + + @Test + @WithUserDetails(value = "api_user") + public void importApplication_datasourceWithSameNameAndPlugin_importedWithValidActionsWithoutSuffixedDatasource() { + + ApplicationJson applicationJson = createAppJson("test_assets/ImportExportServiceTest/valid-application.json").block(); + + Workspace testWorkspace = new Workspace(); + testWorkspace.setName("Duplicate datasource with same plugin org"); + testWorkspace = workspaceService.create(testWorkspace).block(); + + Datasource testDatasource = new Datasource(); + // Chose plugin same as mongo, as json static file has mongo plugin for datasource + Plugin postgreSQLPlugin = pluginRepository.findByName("MongoDB").block(); + testDatasource.setPluginId(postgreSQLPlugin.getId()); + testDatasource.setWorkspaceId(testWorkspace.getId()); + final String datasourceName = applicationJson.getDatasourceList().get(0).getName(); + testDatasource.setName(datasourceName); + datasourceService.create(testDatasource).block(); + + final Mono<Application> resultMono = importExportApplicationService.importApplicationInWorkspace(testWorkspace.getId(), applicationJson); + + StepVerifier + .create(resultMono + .flatMap(application -> Mono.zip( + Mono.just(application), + datasourceService.findAllByWorkspaceId(application.getWorkspaceId(), MANAGE_DATASOURCES).collectList(), + newActionService.findAllByApplicationIdAndViewMode(application.getId(), false, READ_ACTIONS, null).collectList() + ))) + .assertNext(tuple -> { + final Application application = tuple.getT1(); + final List<Datasource> datasourceList = tuple.getT2(); + final List<NewAction> actionList = tuple.getT3(); + + assertThat(application.getName()).isEqualTo("valid_application"); + + List<String> datasourceNameList = new ArrayList<>(); + assertThat(datasourceList).isNotEmpty(); + datasourceList.forEach(datasource -> { + assertThat(datasource.getWorkspaceId()).isEqualTo(application.getWorkspaceId()); + datasourceNameList.add(datasource.getName()); + }); + // Check that there are no datasources are created with suffix names as datasource's are of same plugin + assertThat(datasourceNameList).contains(datasourceName); + + assertThat(actionList).isNotEmpty(); + actionList.forEach(newAction -> { + ActionDTO actionDTO = newAction.getUnpublishedAction(); + assertThat(actionDTO.getDatasource()).isNotNull(); + }); + }) + .verifyComplete(); + } + + @Test + @WithUserDetails(value = "api_user") + public void exportAndImportApplication_withMultiplePagesOrderSameInDeployAndEditMode_PagesOrderIsMaintainedInEditAndViewMode() { + Workspace newWorkspace = new Workspace(); + newWorkspace.setName("template-org-with-ds"); + + Application testApplication = new Application(); + testApplication.setName("exportAndImportApplication_withMultiplePagesOrderSameInDeployAndEditMode_PagesOrderIsMaintainedInEditAndViewMode"); + testApplication.setExportWithConfiguration(true); + testApplication = applicationPageService.createApplication(testApplication, workspaceId).block(); + assert testApplication != null; + + PageDTO testPage1 = new PageDTO(); + testPage1.setName("testPage1"); + testPage1.setApplicationId(testApplication.getId()); + testPage1 = applicationPageService.createPage(testPage1).block(); + + PageDTO testPage2 = new PageDTO(); + testPage2.setName("testPage2"); + testPage2.setApplicationId(testApplication.getId()); + testPage2 = applicationPageService.createPage(testPage2).block(); + + // Set order for the newly created pages + applicationPageService.reorderPage(testApplication.getId(), testPage1.getId(), 0, null).block(); + applicationPageService.reorderPage(testApplication.getId(), testPage2.getId(), 1, null).block(); + // Deploy the current application + applicationPageService.publish(testApplication.getId(), true).block(); + + Mono<ApplicationJson> applicationJsonMono = importExportApplicationService.exportApplicationById(testApplication.getId(), "").cache(); + + StepVerifier + .create(applicationJsonMono) + .assertNext(applicationJson -> { + assertThat(applicationJson.getPageOrder()).isNull(); + assertThat(applicationJson.getPublishedPageOrder()).isNull(); + List<String> pageList = applicationJson.getExportedApplication().getPages() + .stream() + .map(ApplicationPage::getId) + .collect(Collectors.toList()); + + assertThat(pageList.get(0)).isEqualTo("testPage1"); + assertThat(pageList.get(1)).isEqualTo("testPage2"); + assertThat(pageList.get(2)).isEqualTo("Page1"); + + List<String> publishedPageList = applicationJson.getExportedApplication().getPublishedPages() + .stream() + .map(ApplicationPage::getId) + .collect(Collectors.toList()); + + assertThat(publishedPageList.get(0)).isEqualTo("testPage1"); + assertThat(publishedPageList.get(1)).isEqualTo("testPage2"); + assertThat(publishedPageList.get(2)).isEqualTo("Page1"); + }) + .verifyComplete(); + + ApplicationJson applicationJson = applicationJsonMono.block(); + Application application = importExportApplicationService.importApplicationInWorkspace(workspaceId, applicationJson).block(); + + // Get the unpublished pages and verify the order + List<ApplicationPage> pageDTOS = application.getPages(); + Mono<NewPage> newPageMono1 = newPageService.findById(pageDTOS.get(0).getId(), MANAGE_PAGES); + Mono<NewPage> newPageMono2 = newPageService.findById(pageDTOS.get(1).getId(), MANAGE_PAGES); + Mono<NewPage> newPageMono3 = newPageService.findById(pageDTOS.get(2).getId(), MANAGE_PAGES); + + StepVerifier + .create(Mono.zip(newPageMono1, newPageMono2, newPageMono3)) + .assertNext(objects -> { + NewPage newPage1 = objects.getT1(); + NewPage newPage2 = objects.getT2(); + NewPage newPage3 = objects.getT3(); + assertThat(newPage1.getUnpublishedPage().getName()).isEqualTo("testPage1"); + assertThat(newPage2.getUnpublishedPage().getName()).isEqualTo("testPage2"); + assertThat(newPage3.getUnpublishedPage().getName()).isEqualTo("Page1"); + + assertThat(newPage1.getId()).isEqualTo(pageDTOS.get(0).getId()); + assertThat(newPage2.getId()).isEqualTo(pageDTOS.get(1).getId()); + assertThat(newPage3.getId()).isEqualTo(pageDTOS.get(2).getId()); + }) + .verifyComplete(); + + // Get the published pages + List<ApplicationPage> publishedPageDTOs = application.getPublishedPages(); + Mono<NewPage> newPublishedPageMono1 = newPageService.findById(publishedPageDTOs.get(0).getId(), MANAGE_PAGES); + Mono<NewPage> newPublishedPageMono2 = newPageService.findById(publishedPageDTOs.get(1).getId(), MANAGE_PAGES); + Mono<NewPage> newPublishedPageMono3 = newPageService.findById(publishedPageDTOs.get(2).getId(), MANAGE_PAGES); + + StepVerifier + .create(Mono.zip(newPublishedPageMono1, newPublishedPageMono2, newPublishedPageMono3)) + .assertNext(objects -> { + NewPage newPage1 = objects.getT1(); + NewPage newPage2 = objects.getT2(); + NewPage newPage3 = objects.getT3(); + assertThat(newPage1.getPublishedPage().getName()).isEqualTo("testPage1"); + assertThat(newPage2.getPublishedPage().getName()).isEqualTo("testPage2"); + assertThat(newPage3.getPublishedPage().getName()).isEqualTo("Page1"); + + assertThat(newPage1.getId()).isEqualTo(publishedPageDTOs.get(0).getId()); + assertThat(newPage2.getId()).isEqualTo(publishedPageDTOs.get(1).getId()); + assertThat(newPage3.getId()).isEqualTo(publishedPageDTOs.get(2).getId()); + }) + .verifyComplete(); + + } + + + @Test + @WithUserDetails(value = "api_user") + public void exportAndImportApplication_withMultiplePagesOrderDifferentInDeployAndEditMode_PagesOrderIsMaintainedInEditAndViewMode() { + Workspace newWorkspace = new Workspace(); + newWorkspace.setName("template-org-with-ds"); + + Application testApplication = new Application(); + testApplication.setName("exportAndImportApplication_withMultiplePagesOrderDifferentInDeployAndEditMode_PagesOrderIsMaintainedInEditAndViewMode"); + testApplication.setExportWithConfiguration(true); + testApplication = applicationPageService.createApplication(testApplication, workspaceId).block(); + assert testApplication != null; + + PageDTO testPage1 = new PageDTO(); + testPage1.setName("testPage1"); + testPage1.setApplicationId(testApplication.getId()); + testPage1 = applicationPageService.createPage(testPage1).block(); + + PageDTO testPage2 = new PageDTO(); + testPage2.setName("testPage2"); + testPage2.setApplicationId(testApplication.getId()); + testPage2 = applicationPageService.createPage(testPage2).block(); + + // Deploy the current application so that edit and view mode will have different page order + applicationPageService.publish(testApplication.getId(), true).block(); + + // Set order for the newly created pages + applicationPageService.reorderPage(testApplication.getId(), testPage1.getId(), 0, null).block(); + applicationPageService.reorderPage(testApplication.getId(), testPage2.getId(), 1, null).block(); + + Mono<ApplicationJson> applicationJsonMono = importExportApplicationService.exportApplicationById(testApplication.getId(), "").cache(); + + StepVerifier + .create(applicationJsonMono) + .assertNext(applicationJson -> { + Application exportedApplication = applicationJson.getExportedApplication(); + exportedApplication.setViewMode(false); + List<String> pageOrder = exportedApplication.getPages() + .stream() + .map(ApplicationPage::getId) + .collect(Collectors.toList()); + assertThat(pageOrder.get(0)).isEqualTo("testPage1"); + assertThat(pageOrder.get(1)).isEqualTo("testPage2"); + assertThat(pageOrder.get(2)).isEqualTo("Page1"); + + pageOrder.clear(); + pageOrder = exportedApplication.getPublishedPages() + .stream() + .map(ApplicationPage::getId) + .collect(Collectors.toList()); + assertThat(pageOrder.get(0)).isEqualTo("Page1"); + assertThat(pageOrder.get(1)).isEqualTo("testPage1"); + assertThat(pageOrder.get(2)).isEqualTo("testPage2"); + }) + .verifyComplete(); + + ApplicationJson applicationJson = applicationJsonMono.block(); + Application application = importExportApplicationService.importApplicationInWorkspace(workspaceId, applicationJson).block(); + + // Get the unpublished pages and verify the order + application.setViewMode(false); + List<ApplicationPage> pageDTOS = application.getPages(); + Mono<NewPage> newPageMono1 = newPageService.findById(pageDTOS.get(0).getId(), MANAGE_PAGES); + Mono<NewPage> newPageMono2 = newPageService.findById(pageDTOS.get(1).getId(), MANAGE_PAGES); + Mono<NewPage> newPageMono3 = newPageService.findById(pageDTOS.get(2).getId(), MANAGE_PAGES); + + StepVerifier + .create(Mono.zip(newPageMono1, newPageMono2, newPageMono3)) + .assertNext(objects -> { + NewPage newPage1 = objects.getT1(); + NewPage newPage2 = objects.getT2(); + NewPage newPage3 = objects.getT3(); + assertThat(newPage1.getUnpublishedPage().getName()).isEqualTo("testPage1"); + assertThat(newPage2.getUnpublishedPage().getName()).isEqualTo("testPage2"); + assertThat(newPage3.getUnpublishedPage().getName()).isEqualTo("Page1"); + + assertThat(newPage1.getId()).isEqualTo(pageDTOS.get(0).getId()); + assertThat(newPage2.getId()).isEqualTo(pageDTOS.get(1).getId()); + assertThat(newPage3.getId()).isEqualTo(pageDTOS.get(2).getId()); + }) + .verifyComplete(); + + // Get the published pages + List<ApplicationPage> publishedPageDTOs = application.getPublishedPages(); + Mono<NewPage> newPublishedPageMono1 = newPageService.findById(publishedPageDTOs.get(0).getId(), MANAGE_PAGES); + Mono<NewPage> newPublishedPageMono2 = newPageService.findById(publishedPageDTOs.get(1).getId(), MANAGE_PAGES); + Mono<NewPage> newPublishedPageMono3 = newPageService.findById(publishedPageDTOs.get(2).getId(), MANAGE_PAGES); + + StepVerifier + .create(Mono.zip(newPublishedPageMono1, newPublishedPageMono2, newPublishedPageMono3)) + .assertNext(objects -> { + NewPage newPage1 = objects.getT1(); + NewPage newPage2 = objects.getT2(); + NewPage newPage3 = objects.getT3(); + assertThat(newPage1.getPublishedPage().getName()).isEqualTo("Page1"); + assertThat(newPage2.getPublishedPage().getName()).isEqualTo("testPage1"); + assertThat(newPage3.getPublishedPage().getName()).isEqualTo("testPage2"); + + assertThat(newPage1.getId()).isEqualTo(publishedPageDTOs.get(0).getId()); + assertThat(newPage2.getId()).isEqualTo(publishedPageDTOs.get(1).getId()); + assertThat(newPage3.getId()).isEqualTo(publishedPageDTOs.get(2).getId()); + }) + .verifyComplete(); + + } + + private ApplicationJson createApplicationJSON(List<String> pageNames) { + ApplicationJson applicationJson = new ApplicationJson(); + + // set the application data + Application application = new Application(); + application.setName("Template Application"); + application.setSlug("template-application"); + application.setForkingEnabled(true); + application.setIsPublic(true); + application.setApplicationVersion(ApplicationVersion.LATEST_VERSION); + applicationJson.setExportedApplication(application); + + Datasource sampleDatasource = new Datasource(); + sampleDatasource.setName("SampleDS"); + sampleDatasource.setPluginId("restapi-plugin"); + + applicationJson.setDatasourceList(List.of(sampleDatasource)); + + // add pages and actions + List<NewPage> newPageList = new ArrayList<>(pageNames.size()); + List<NewAction> actionList = new ArrayList<>(); + List<ActionCollection> actionCollectionList = new ArrayList<>(); + + for (String pageName : pageNames) { + NewPage newPage = new NewPage(); + newPage.setUnpublishedPage(new PageDTO()); + newPage.getUnpublishedPage().setName(pageName); + newPage.getUnpublishedPage().setLayouts(List.of()); + newPageList.add(newPage); + + NewAction action = new NewAction(); + action.setId(pageName + "_SampleQuery"); + action.setPluginType(PluginType.API); + action.setPluginId("restapi-plugin"); + action.setUnpublishedAction(new ActionDTO()); + action.getUnpublishedAction().setName("SampleQuery"); + action.getUnpublishedAction().setPageId(pageName); + action.getUnpublishedAction().setDatasource(new Datasource()); + action.getUnpublishedAction().getDatasource().setId("SampleDS"); + action.getUnpublishedAction().getDatasource().setPluginId("restapi-plugin"); + actionList.add(action); + + ActionCollection actionCollection = new ActionCollection(); + actionCollection.setId(pageName + "_SampleJS"); + actionCollection.setUnpublishedCollection(new ActionCollectionDTO()); + actionCollection.getUnpublishedCollection().setName("SampleJS"); + actionCollection.getUnpublishedCollection().setPageId(pageName); + actionCollection.getUnpublishedCollection().setPluginId("js-plugin"); + actionCollection.getUnpublishedCollection().setPluginType(PluginType.JS); + actionCollection.getUnpublishedCollection().setBody("export default {\\n\\t\\n}"); + actionCollectionList.add(actionCollection); + } + + applicationJson.setPageList(newPageList); + applicationJson.setActionList(actionList); + applicationJson.setActionCollectionList(actionCollectionList); + return applicationJson; + } + + @Test + @WithUserDetails("api_user") + public void mergeApplicationJsonWithApplication_WhenPageNameConflicts_PageNamesRenamed() { + String uniqueString = UUID.randomUUID().toString(); + + Application destApplication = new Application(); + destApplication.setName("App_" + uniqueString); + destApplication.setSlug("my-slug"); + destApplication.setIsPublic(false); + destApplication.setForkingEnabled(false); + Mono<Application> createAppAndPageMono = applicationPageService.createApplication(destApplication, workspaceId) + .flatMap(application -> { + PageDTO pageDTO = new PageDTO(); + pageDTO.setName("Home"); + pageDTO.setApplicationId(application.getId()); + return applicationPageService.createPage(pageDTO).thenReturn(application); + }); + + // let's create an ApplicationJSON which we'll merge with application created by createAppAndPageMono + ApplicationJson applicationJson = createApplicationJSON(List.of("Home", "About")); + + Mono<Tuple3<ApplicationPagesDTO, List<NewAction>, List<ActionCollection>>> tuple2Mono = createAppAndPageMono.flatMap(application -> + // merge the application json with the application we've created + importExportApplicationService.mergeApplicationJsonWithApplication(application.getWorkspaceId(), application.getId(), null, applicationJson, null) + .thenReturn(application) + ).flatMap(application -> + // fetch the application pages, this should contain pages from application json + Mono.zip( + newPageService.findApplicationPages(application.getId(), null, null, ApplicationMode.EDIT), + newActionService.findAllByApplicationIdAndViewMode(application.getId(), false, MANAGE_ACTIONS, null).collectList(), + actionCollectionService.findAllByApplicationIdAndViewMode(application.getId(), false, MANAGE_ACTIONS, null).collectList() + ) + ); + + StepVerifier.create(tuple2Mono).assertNext(objects -> { + ApplicationPagesDTO applicationPagesDTO = objects.getT1(); + List<NewAction> newActionList = objects.getT2(); + List<ActionCollection> actionCollectionList = objects.getT3(); + + assertThat(applicationPagesDTO.getApplication().getName()).isEqualTo(destApplication.getName()); + assertThat(applicationPagesDTO.getApplication().getSlug()).isEqualTo(destApplication.getSlug()); + assertThat(applicationPagesDTO.getApplication().getIsPublic()).isFalse(); + assertThat(applicationPagesDTO.getApplication().getForkingEnabled()).isFalse(); + assertThat(applicationPagesDTO.getPages().size()).isEqualTo(4); + List<String> pageNames = applicationPagesDTO.getPages().stream() + .map(PageNameIdDTO::getName) + .collect(Collectors.toList()); + assertThat(pageNames).contains("Home", "Home2", "About"); + assertThat(newActionList.size()).isEqualTo(2); // we imported two pages and each page has one action + assertThat(actionCollectionList.size()).isEqualTo(2); // we imported two pages and each page has one Collection + }).verifyComplete(); + } + + @Test + @WithUserDetails("api_user") + public void mergeApplicationJsonWithApplication_WhenPageListIProvided_OnlyListedPagesAreMerged() { + String uniqueString = UUID.randomUUID().toString(); + + Application destApplication = new Application(); + destApplication.setName("App_" + uniqueString); + Mono<Application> createAppAndPageMono = applicationPageService.createApplication(destApplication, workspaceId) + .flatMap(application -> { + PageDTO pageDTO = new PageDTO(); + pageDTO.setName("Home"); + pageDTO.setApplicationId(application.getId()); + return applicationPageService.createPage(pageDTO).thenReturn(application); + }); + + // let's create an ApplicationJSON which we'll merge with application created by createAppAndPageMono + ApplicationJson applicationJson = createApplicationJSON(List.of("Profile", "About", "Contact US")); + + Mono<ApplicationPagesDTO> applicationPagesDTOMono = createAppAndPageMono.flatMap(application -> + // merge the application json with the application we've created + importExportApplicationService.mergeApplicationJsonWithApplication(application.getWorkspaceId(), application.getId(), null, applicationJson, List.of("About", "Contact US")) + .thenReturn(application) + ).flatMap(application -> + // fetch the application pages, this should contain pages from application json + newPageService.findApplicationPages(application.getId(), null, null, ApplicationMode.EDIT) + ); + + StepVerifier.create(applicationPagesDTOMono).assertNext(applicationPagesDTO -> { + assertThat(applicationPagesDTO.getPages().size()).isEqualTo(4); + List<String> pageNames = applicationPagesDTO.getPages().stream() + .map(PageNameIdDTO::getName) + .collect(Collectors.toList()); + assertThat(pageNames).contains("Home", "About", "Contact US"); + assertThat(pageNames).doesNotContain("Profile"); + }).verifyComplete(); + } + + @Test + @WithUserDetails(value = "api_user") + public void exportApplicationById_WhenThemeDoesNotExist_ExportedWithDefaultTheme() { + Theme customTheme = new Theme(); + customTheme.setName("my-custom-theme"); + + String randomId = UUID.randomUUID().toString(); + Application testApplication = new Application(); + testApplication.setName("Application_" + randomId); + Mono<ApplicationJson> exportedAppJson = applicationPageService.createApplication(testApplication, workspaceId) + .flatMap(application -> { + application.setEditModeThemeId("invalid-theme-id"); + application.setPublishedModeThemeId("invalid-theme-id"); + String branchName = null; + return applicationService.save(application) + .then(importExportApplicationService.exportApplicationById(application.getId(), branchName)); + }); + + StepVerifier.create(exportedAppJson).assertNext(applicationJson -> { + assertThat(applicationJson.getEditModeTheme().getName()).isEqualToIgnoringCase(Theme.DEFAULT_THEME_NAME); + assertThat(applicationJson.getPublishedTheme().getName()).isEqualToIgnoringCase(Theme.DEFAULT_THEME_NAME); + }).verifyComplete(); + } + + @Test + @WithUserDetails(value = "api_user") + public void importApplication_invalidPluginReferenceForDatasource_throwException() { + + Workspace newWorkspace = new Workspace(); + newWorkspace.setName("Template Workspace"); + + ApplicationJson appJson = createAppJson("test_assets/ImportExportServiceTest/valid-application.json").block(); + assert appJson != null; + final String randomId = UUID.randomUUID().toString(); + appJson.getDatasourceList().get(0).setPluginId(randomId); + final Mono<Application> resultMono = workspaceService + .create(newWorkspace) + .flatMap(workspace -> importExportApplicationService.importApplicationInWorkspace(workspace.getId(), appJson)); + + StepVerifier + .create(resultMono) + .expectErrorMatches(throwable -> throwable instanceof AppsmithException && + throwable.getMessage().equals(AppsmithError.UNKNOWN_PLUGIN_REFERENCE.getMessage(randomId))) + .verify(); + } + + @Test + @WithUserDetails(value = "api_user") + public void importApplication_importSameApplicationTwice_applicationImportedLaterWithSuffixCount() { + + Mono<ApplicationJson> applicationJsonMono = createAppJson("test_assets/ImportExportServiceTest/valid-application-without-action-collection.json"); + + Workspace newWorkspace = new Workspace(); + newWorkspace.setName("Template Workspace"); + + Mono<Workspace> createWorkspaceMono = workspaceService.create(newWorkspace).cache(); + final Mono<Application> importApplicationMono = createWorkspaceMono + .zipWith(applicationJsonMono) + .flatMap(tuple -> { + Workspace workspace = tuple.getT1(); + ApplicationJson applicationJson = tuple.getT2(); + return importExportApplicationService + .importApplicationInWorkspace(workspace.getId(), applicationJson); + }); + + StepVerifier + .create(importApplicationMono.zipWhen(application -> importApplicationMono)) + .assertNext(tuple -> { + Application firstImportedApplication = tuple.getT1(); + Application secondImportedApplication = tuple.getT2(); + assertThat(firstImportedApplication.getName()).isEqualTo("valid_application"); + assertThat(secondImportedApplication.getName()).isEqualTo("valid_application (1)"); + assertThat(firstImportedApplication.getWorkspaceId()).isEqualTo(secondImportedApplication.getWorkspaceId()); + assertThat(firstImportedApplication.getWorkspaceId()).isNotNull(); + }) + .verifyComplete(); + } + + @Test + @WithUserDetails(value = "api_user") + public void mergeApplication_existingApplication_pageAddedSuccessfully() { + + //Create application + Application application = new Application(); + application.setName("mergeApplication_existingApplication_pageAddedSuccessfully"); + application.setWorkspaceId(workspaceId); + application = applicationPageService.createApplication(application).block(); + + Mono<ApplicationJson> applicationJson = createAppJson("test_assets/ImportExportServiceTest/valid-application.json"); + + Application finalApplication = application; + Mono<Tuple4<Application, List<NewPage>, List<NewAction>, List<ActionCollection>>> importedApplication = applicationJson + .flatMap(applicationJson1 -> importExportApplicationService.mergeApplicationJsonWithApplication( + workspaceId, + finalApplication.getId(), + null, + applicationJson1, + new ArrayList<>()) + ) + .flatMap(application1 -> { + Mono<List<NewPage>> pageList = newPageService.findNewPagesByApplicationId(application1.getId(), MANAGE_PAGES).collectList(); + Mono<List<NewAction>> actionList = newActionService.findAllByApplicationIdAndViewMode(application1.getId(), false, MANAGE_ACTIONS, null).collectList(); + Mono<List<ActionCollection>> actionCollectionList = actionCollectionService.findAllByApplicationIdAndViewMode(application1.getId(), false, MANAGE_ACTIONS, null).collectList(); + return Mono.zip(Mono.just(application1), pageList, actionList, actionCollectionList); + }); + + + StepVerifier + .create(importedApplication) + .assertNext(tuple -> { + Application application1 = tuple.getT1(); + List<NewPage> pageList = tuple.getT2(); + List<NewAction> actionList = tuple.getT3(); + List<ActionCollection> actionCollectionList = tuple.getT4(); + + assertThat(application1.getId()).isEqualTo(finalApplication.getId()); + assertThat(finalApplication.getPages().size()).isLessThan(application1.getPages().size()); + assertThat(finalApplication.getPages().size()).isEqualTo(application1.getPublishedPages().size()); + + // Verify the pages after merging the template + pageList.forEach(newPage -> { + assertThat(newPage.getUnpublishedPage().getName()).containsAnyOf("Page1", "Page12", "Page2"); + assertThat(newPage.getGitSyncId()).isNotNull(); + }); + + NewPage page = pageList.stream().filter(newPage -> newPage.getUnpublishedPage().getName().equals("Page12")).collect(Collectors.toList()).get(0); + // Verify the actions after merging the template + actionList.forEach(newAction -> { + assertThat(newAction.getUnpublishedAction().getName()).containsAnyOf("api_wo_auth", "get_users", "run"); + assertThat(newAction.getUnpublishedAction().getPageId()).isEqualTo(page.getId()); + }); + + // Verify the actionCollections after merging the template + actionCollectionList.forEach(newAction -> { + assertThat(newAction.getUnpublishedCollection().getName()).containsAnyOf("JSObject1", "JSObject2"); + assertThat(newAction.getUnpublishedCollection().getPageId()).isEqualTo(page.getId()); + }); + }) + .verifyComplete(); + + } + + @Test + @WithUserDetails(value = "api_user") + public void mergeApplication_gitConnectedApplication_pageAddedSuccessfully() { + + //Create application connected to git + Application testApplication = new Application(); + testApplication.setName("mergeApplication_gitConnectedApplication_pageAddedSuccessfully"); + testApplication.setWorkspaceId(workspaceId); + testApplication.setUpdatedAt(Instant.now()); + testApplication.setLastDeployedAt(Instant.now()); + testApplication.setModifiedBy("some-user"); + testApplication.setGitApplicationMetadata(new GitApplicationMetadata()); + GitApplicationMetadata gitData = new GitApplicationMetadata(); + gitData.setBranchName("master"); + gitData.setDefaultBranchName("master"); + testApplication.setGitApplicationMetadata(gitData); + + Application application = applicationPageService.createApplication(testApplication, workspaceId) + .flatMap(application1 -> { + application1.getGitApplicationMetadata().setDefaultApplicationId(application1.getId()); + return applicationService.save(application1); + }).block(); + + Mono<ApplicationJson> applicationJson = createAppJson("test_assets/ImportExportServiceTest/valid-application.json"); + + Application finalApplication = application; + Mono<Tuple4<Application, List<NewPage>, List<NewAction>, List<ActionCollection>>> importedApplication = applicationJson + .flatMap(applicationJson1 -> importExportApplicationService.mergeApplicationJsonWithApplication( + workspaceId, + finalApplication.getId(), + "master", + applicationJson1, + new ArrayList<>()) + ) + .flatMap(application1 -> { + Mono<List<NewPage>> pageList = newPageService.findNewPagesByApplicationId(application1.getId(), MANAGE_PAGES).collectList(); + Mono<List<NewAction>> actionList = newActionService.findAllByApplicationIdAndViewMode(application1.getId(), false, MANAGE_ACTIONS, null).collectList(); + Mono<List<ActionCollection>> actionCollectionList = actionCollectionService.findAllByApplicationIdAndViewMode(application1.getId(), false, MANAGE_ACTIONS, null).collectList(); + return Mono.zip(Mono.just(application1), pageList, actionList, actionCollectionList); + }); + + StepVerifier + .create(importedApplication) + .assertNext(tuple -> { + Application application1 = tuple.getT1(); + List<NewPage> pageList = tuple.getT2(); + List<NewAction> actionList = tuple.getT3(); + List<ActionCollection> actionCollectionList = tuple.getT4(); + + assertThat(application1.getId()).isEqualTo(finalApplication.getId()); + assertThat(finalApplication.getPages().size()).isLessThan(application1.getPages().size()); + assertThat(finalApplication.getPages().size()).isEqualTo(application1.getPublishedPages().size()); + + // Verify the pages after merging the template + pageList.forEach(newPage -> { + assertThat(newPage.getUnpublishedPage().getName()).containsAnyOf("Page1", "Page12", "Page2"); + assertThat(newPage.getGitSyncId()).isNotNull(); + }); + + NewPage page = pageList.stream().filter(newPage -> newPage.getUnpublishedPage().getName().equals("Page12")).collect(Collectors.toList()).get(0); + // Verify the actions after merging the template + actionList.forEach(newAction -> { + assertThat(newAction.getUnpublishedAction().getName()).containsAnyOf("api_wo_auth", "get_users", "run"); + assertThat(newAction.getUnpublishedAction().getPageId()).isEqualTo(page.getId()); + }); + + // Verify the actionCollections after merging the template + actionCollectionList.forEach(newAction -> { + assertThat(newAction.getUnpublishedCollection().getName()).containsAnyOf("JSObject1", "JSObject2"); + assertThat(newAction.getUnpublishedCollection().getPageId()).isEqualTo(page.getId()); + }); + }) + .verifyComplete(); + + } + + @Test + @WithUserDetails(value = "api_user") + public void mergeApplication_gitConnectedApplicationChildBranch_pageAddedSuccessfully() { + + //Create application connected to git + Application testApplication = new Application(); + testApplication.setName("mergeApplication_gitConnectedApplicationChildBranch_pageAddedSuccessfully"); + testApplication.setWorkspaceId(workspaceId); + testApplication.setUpdatedAt(Instant.now()); + testApplication.setLastDeployedAt(Instant.now()); + testApplication.setModifiedBy("some-user"); + testApplication.setGitApplicationMetadata(new GitApplicationMetadata()); + GitApplicationMetadata gitData = new GitApplicationMetadata(); + gitData.setBranchName("master"); + gitData.setDefaultBranchName("master"); + testApplication.setGitApplicationMetadata(gitData); + + Application application = applicationPageService.createApplication(testApplication, workspaceId) + .flatMap(application1 -> { + application1.getGitApplicationMetadata().setDefaultApplicationId(application1.getId()); + return applicationService.save(application1); + }).block(); + + // Create branch for the application + testApplication = new Application(); + testApplication.setName("mergeApplication_gitConnectedApplicationChildBranch_pageAddedSuccessfully1"); + testApplication.setWorkspaceId(workspaceId); + testApplication.setUpdatedAt(Instant.now()); + testApplication.setLastDeployedAt(Instant.now()); + testApplication.setModifiedBy("some-user"); + testApplication.setGitApplicationMetadata(new GitApplicationMetadata()); + GitApplicationMetadata gitData1 = new GitApplicationMetadata(); + gitData1.setBranchName("feature"); + gitData1.setDefaultBranchName("master"); + testApplication.setGitApplicationMetadata(gitData1); + + Application branchApp = applicationPageService.createApplication(testApplication, workspaceId) + .flatMap(application2 -> { + application2.getGitApplicationMetadata().setDefaultApplicationId(application.getId()); + return applicationService.save(application2); + }).block(); + + Mono<ApplicationJson> applicationJson = createAppJson("test_assets/ImportExportServiceTest/valid-application.json"); + + Application finalApplication = application; + Mono<Tuple4<Application, List<NewPage>, List<NewAction>, List<ActionCollection>>> importedApplication = applicationJson + .flatMap(applicationJson1 -> importExportApplicationService.mergeApplicationJsonWithApplication( + workspaceId, + branchApp.getId(), + "feature", + applicationJson1, + new ArrayList<>()) + ) + .flatMap(application2 -> { + Mono<List<NewPage>> pageList = newPageService.findNewPagesByApplicationId(branchApp.getId(), MANAGE_PAGES).collectList(); + Mono<List<NewAction>> actionList = newActionService.findAllByApplicationIdAndViewMode(branchApp.getId(), false, MANAGE_ACTIONS, null).collectList(); + Mono<List<ActionCollection>> actionCollectionList = actionCollectionService.findAllByApplicationIdAndViewMode(branchApp.getId(), false, MANAGE_ACTIONS, null).collectList(); + return Mono.zip(Mono.just(application2), pageList, actionList, actionCollectionList); + }); + + StepVerifier + .create(importedApplication) + .assertNext(tuple -> { + Application application3 = tuple.getT1(); + List<NewPage> pageList = tuple.getT2(); + List<NewAction> actionList = tuple.getT3(); + List<ActionCollection> actionCollectionList = tuple.getT4(); + + assertThat(application3.getId()).isNotEqualTo(finalApplication.getId()); + assertThat(finalApplication.getPages().size()).isLessThan(application3.getPages().size()); + assertThat(finalApplication.getPages().size()).isEqualTo(application3.getPublishedPages().size()); + + // Verify the pages after merging the template + pageList.forEach(newPage -> { + assertThat(newPage.getUnpublishedPage().getName()).containsAnyOf("Page1", "Page12", "Page2"); + assertThat(newPage.getGitSyncId()).isNotNull(); + }); + + NewPage page = pageList.stream().filter(newPage -> newPage.getUnpublishedPage().getName().equals("Page12")).collect(Collectors.toList()).get(0); + // Verify the actions after merging the template + actionList.forEach(newAction -> { + assertThat(newAction.getUnpublishedAction().getName()).containsAnyOf("api_wo_auth", "get_users", "run"); + assertThat(newAction.getUnpublishedAction().getPageId()).isEqualTo(page.getId()); + }); + + // Verify the actionCollections after merging the template + actionCollectionList.forEach(newAction -> { + assertThat(newAction.getUnpublishedCollection().getName()).containsAnyOf("JSObject1", "JSObject2"); + assertThat(newAction.getUnpublishedCollection().getPageId()).isEqualTo(page.getId()); + }); + }) + .verifyComplete(); + + } + + @Test + @WithUserDetails(value = "api_user") + public void mergeApplication_gitConnectedApplicationSelectedSpecificPages_selectedPageAddedSuccessfully() { + //Create application connected to git + Application testApplication = new Application(); + testApplication.setName("mergeApplication_gitConnectedApplicationSelectedSpecificPages_selectedPageAddedSuccessfully"); + testApplication.setWorkspaceId(workspaceId); + testApplication.setUpdatedAt(Instant.now()); + testApplication.setLastDeployedAt(Instant.now()); + testApplication.setModifiedBy("some-user"); + testApplication.setGitApplicationMetadata(new GitApplicationMetadata()); + GitApplicationMetadata gitData = new GitApplicationMetadata(); + gitData.setBranchName("master"); + gitData.setDefaultBranchName("master"); + testApplication.setGitApplicationMetadata(gitData); + + Application application = applicationPageService.createApplication(testApplication, workspaceId) + .flatMap(application1 -> { + application1.getGitApplicationMetadata().setDefaultApplicationId(application1.getId()); + return applicationService.save(application1); + }).block(); + + // Create branch for the application + testApplication = new Application(); + testApplication.setName("mergeApplication_gitConnectedApplicationSelectedSpecificPages_selectedPageAddedSuccessfully1"); + testApplication.setWorkspaceId(workspaceId); + testApplication.setUpdatedAt(Instant.now()); + testApplication.setLastDeployedAt(Instant.now()); + testApplication.setModifiedBy("some-user"); + testApplication.setGitApplicationMetadata(new GitApplicationMetadata()); + GitApplicationMetadata gitData1 = new GitApplicationMetadata(); + gitData1.setBranchName("feature"); + gitData1.setDefaultBranchName("master"); + testApplication.setGitApplicationMetadata(gitData1); + + Application branchApp = applicationPageService.createApplication(testApplication, workspaceId) + .flatMap(application2 -> { + application2.getGitApplicationMetadata().setDefaultApplicationId(application.getId()); + return applicationService.save(application2); + }).block(); + + Mono<ApplicationJson> applicationJson = createAppJson("test_assets/ImportExportServiceTest/valid-application.json"); + + Application finalApplication = application; + Mono<Tuple4<Application, List<NewPage>, List<NewAction>, List<ActionCollection>>> importedApplication = applicationJson + .flatMap(applicationJson1 -> importExportApplicationService.mergeApplicationJsonWithApplication( + workspaceId, + branchApp.getId(), + "feature", + applicationJson1, + List.of("Page1")) + ) + .flatMap(application2 -> { + Mono<List<NewPage>> pageList = newPageService.findNewPagesByApplicationId(branchApp.getId(), MANAGE_PAGES).collectList(); + Mono<List<NewAction>> actionList = newActionService.findAllByApplicationIdAndViewMode(branchApp.getId(), false, MANAGE_ACTIONS, null).collectList(); + Mono<List<ActionCollection>> actionCollectionList = actionCollectionService.findAllByApplicationIdAndViewMode(branchApp.getId(), false, MANAGE_ACTIONS, null).collectList(); + return Mono.zip(Mono.just(application2), pageList, actionList, actionCollectionList); + }); + + StepVerifier + .create(importedApplication) + .assertNext(tuple -> { + Application application3 = tuple.getT1(); + List<NewPage> pageList = tuple.getT2(); + List<NewAction> actionList = tuple.getT3(); + List<ActionCollection> actionCollectionList = tuple.getT4(); + + assertThat(application3.getId()).isNotEqualTo(finalApplication.getId()); + assertThat(finalApplication.getPages().size()).isLessThan(application3.getPages().size()); + assertThat(finalApplication.getPages().size()).isEqualTo(application3.getPublishedPages().size()); + + // Verify the pages after merging the template + pageList.forEach(newPage -> { + assertThat(newPage.getUnpublishedPage().getName()).containsAnyOf("Page1", "Page12"); + assertThat(newPage.getGitSyncId()).isNotNull(); + }); + + NewPage page = pageList.stream().filter(newPage -> newPage.getUnpublishedPage().getName().equals("Page12")).collect(Collectors.toList()).get(0); + // Verify the actions after merging the template + actionList.forEach(newAction -> { + assertThat(newAction.getUnpublishedAction().getName()).containsAnyOf("api_wo_auth", "get_users", "run"); + assertThat(newAction.getUnpublishedAction().getPageId()).isEqualTo(page.getId()); + }); + + // Verify the actionCollections after merging the template + actionCollectionList.forEach(newAction -> { + assertThat(newAction.getUnpublishedCollection().getName()).containsAnyOf("JSObject1", "JSObject2"); + assertThat(newAction.getUnpublishedCollection().getPageId()).isEqualTo(page.getId()); + }); + }) + .verifyComplete(); + } + + @Test + @WithUserDetails(value = "api_user") + public void mergeApplication_gitConnectedApplicationSelectedAllPages_selectedPageAddedSuccessfully() { + //Create application connected to git + Application testApplication = new Application(); + testApplication.setName("mergeApplication_gitConnectedApplicationSelectedAllPages_selectedPageAddedSuccessfully"); + testApplication.setWorkspaceId(workspaceId); + testApplication.setUpdatedAt(Instant.now()); + testApplication.setLastDeployedAt(Instant.now()); + testApplication.setModifiedBy("some-user"); + testApplication.setGitApplicationMetadata(new GitApplicationMetadata()); + GitApplicationMetadata gitData = new GitApplicationMetadata(); + gitData.setBranchName("master"); + gitData.setDefaultBranchName("master"); + testApplication.setGitApplicationMetadata(gitData); + + Application application = applicationPageService.createApplication(testApplication, workspaceId) + .flatMap(application1 -> { + application1.getGitApplicationMetadata().setDefaultApplicationId(application1.getId()); + return applicationService.save(application1); + }).block(); + + // Create branch for the application + testApplication = new Application(); + testApplication.setName("mergeApplication_gitConnectedApplicationSelectedAllPages_selectedPageAddedSuccessfully1"); + testApplication.setWorkspaceId(workspaceId); + testApplication.setUpdatedAt(Instant.now()); + testApplication.setLastDeployedAt(Instant.now()); + testApplication.setModifiedBy("some-user"); + testApplication.setGitApplicationMetadata(new GitApplicationMetadata()); + GitApplicationMetadata gitData1 = new GitApplicationMetadata(); + gitData1.setBranchName("feature"); + gitData1.setDefaultBranchName("master"); + testApplication.setGitApplicationMetadata(gitData1); + + Application branchApp = applicationPageService.createApplication(testApplication, workspaceId) + .flatMap(application2 -> { + application2.getGitApplicationMetadata().setDefaultApplicationId(application.getId()); + return applicationService.save(application2); + }).block(); + + Mono<ApplicationJson> applicationJson = createAppJson("test_assets/ImportExportServiceTest/valid-application.json"); + + Application finalApplication = application; + Mono<Tuple4<Application, List<NewPage>, List<NewAction>, List<ActionCollection>>> importedApplication = applicationJson + .flatMap(applicationJson1 -> importExportApplicationService.mergeApplicationJsonWithApplication( + workspaceId, + branchApp.getId(), + "feature", + applicationJson1, + List.of("Page1", "Page2")) + ) + .flatMap(application2 -> { + Mono<List<NewPage>> pageList = newPageService.findNewPagesByApplicationId(branchApp.getId(), MANAGE_PAGES).collectList(); + Mono<List<NewAction>> actionList = newActionService.findAllByApplicationIdAndViewMode(branchApp.getId(), false, MANAGE_ACTIONS, null).collectList(); + Mono<List<ActionCollection>> actionCollectionList = actionCollectionService.findAllByApplicationIdAndViewMode(branchApp.getId(), false, MANAGE_ACTIONS, null).collectList(); + return Mono.zip(Mono.just(application2), pageList, actionList, actionCollectionList); + }); + + StepVerifier + .create(importedApplication) + .assertNext(tuple -> { + Application application3 = tuple.getT1(); + List<NewPage> pageList = tuple.getT2(); + List<NewAction> actionList = tuple.getT3(); + List<ActionCollection> actionCollectionList = tuple.getT4(); + + assertThat(application3.getId()).isNotEqualTo(finalApplication.getId()); + assertThat(finalApplication.getPages().size()).isLessThan(application3.getPages().size()); + assertThat(finalApplication.getPages().size()).isEqualTo(application3.getPublishedPages().size()); + + // Verify the pages after merging the template + pageList.forEach(newPage -> { + assertThat(newPage.getUnpublishedPage().getName()).containsAnyOf("Page1", "Page12", "Page2"); + assertThat(newPage.getGitSyncId()).isNotNull(); + }); + + NewPage page = pageList.stream().filter(newPage -> newPage.getUnpublishedPage().getName().equals("Page12")).collect(Collectors.toList()).get(0); + // Verify the actions after merging the template + actionList.forEach(newAction -> { + assertThat(newAction.getUnpublishedAction().getName()).containsAnyOf("api_wo_auth", "get_users", "run"); + assertThat(newAction.getUnpublishedAction().getPageId()).isEqualTo(page.getId()); + }); + + // Verify the actionCollections after merging the template + actionCollectionList.forEach(newAction -> { + assertThat(newAction.getUnpublishedCollection().getName()).containsAnyOf("JSObject1", "JSObject2"); + assertThat(newAction.getUnpublishedCollection().getPageId()).isEqualTo(page.getId()); + }); + }) + .verifyComplete(); + } + + @Test + @WithUserDetails(value = "api_user") + public void mergeApplication_nonGitConnectedApplicationSelectedSpecificPages_selectedPageAddedSuccessfully() { + //Create application + Application application = new Application(); + application.setName("mergeApplication_nonGitConnectedApplicationSelectedSpecificPages_selectedPageAddedSuccessfully"); + application.setWorkspaceId(workspaceId); + application = applicationPageService.createApplication(application).block(); + + Mono<ApplicationJson> applicationJson = createAppJson("test_assets/ImportExportServiceTest/valid-application.json"); + + Application finalApplication = application; + Mono<Tuple4<Application, List<NewPage>, List<NewAction>, List<ActionCollection>>> importedApplication = applicationJson + .flatMap(applicationJson1 -> importExportApplicationService.mergeApplicationJsonWithApplication( + workspaceId, + finalApplication.getId(), + null, + applicationJson1, + List.of("Page1")) + ) + .flatMap(application1 -> { + Mono<List<NewPage>> pageList = newPageService.findNewPagesByApplicationId(application1.getId(), MANAGE_PAGES).collectList(); + Mono<List<NewAction>> actionList = newActionService.findAllByApplicationIdAndViewMode(application1.getId(), false, MANAGE_ACTIONS, null).collectList(); + Mono<List<ActionCollection>> actionCollectionList = actionCollectionService.findAllByApplicationIdAndViewMode(application1.getId(), false, MANAGE_ACTIONS, null).collectList(); + return Mono.zip(Mono.just(application1), pageList, actionList, actionCollectionList); + }); + + + StepVerifier + .create(importedApplication) + .assertNext(tuple -> { + Application application1 = tuple.getT1(); + List<NewPage> pageList = tuple.getT2(); + List<NewAction> actionList = tuple.getT3(); + List<ActionCollection> actionCollectionList = tuple.getT4(); + + assertThat(application1.getId()).isEqualTo(finalApplication.getId()); + assertThat(finalApplication.getPages().size()).isLessThan(application1.getPages().size()); + assertThat(finalApplication.getPages().size()).isEqualTo(application1.getPublishedPages().size()); + + // Verify the pages after merging the template + pageList.forEach(newPage -> { + assertThat(newPage.getUnpublishedPage().getName()).containsAnyOf("Page1", "Page12"); + assertThat(newPage.getGitSyncId()).isNotNull(); + }); + + NewPage page = pageList.stream().filter(newPage -> newPage.getUnpublishedPage().getName().equals("Page12")).collect(Collectors.toList()).get(0); + // Verify the actions after merging the template + actionList.forEach(newAction -> { + assertThat(newAction.getUnpublishedAction().getName()).containsAnyOf("api_wo_auth", "get_users", "run"); + assertThat(newAction.getUnpublishedAction().getPageId()).isEqualTo(page.getId()); + }); + + // Verify the actionCollections after merging the template + actionCollectionList.forEach(newAction -> { + assertThat(newAction.getUnpublishedCollection().getName()).containsAnyOf("JSObject1", "JSObject2"); + assertThat(newAction.getUnpublishedCollection().getPageId()).isEqualTo(page.getId()); + }); + }) + .verifyComplete(); + } + + @Test + @WithUserDetails(value = "api_user") + public void mergeApplication_nonGitConnectedApplicationSelectedAllPages_selectedPageAddedSuccessfully() { + //Create application + Application application = new Application(); + application.setName("mergeApplication_nonGitConnectedApplicationSelectedAllPages_selectedPageAddedSuccessfully"); + application.setWorkspaceId(workspaceId); + application = applicationPageService.createApplication(application).block(); + + Mono<ApplicationJson> applicationJson = createAppJson("test_assets/ImportExportServiceTest/valid-application.json"); + + Application finalApplication = application; + Mono<Tuple4<Application, List<NewPage>, List<NewAction>, List<ActionCollection>>> importedApplication = applicationJson + .flatMap(applicationJson1 -> importExportApplicationService.mergeApplicationJsonWithApplication( + workspaceId, + finalApplication.getId(), + null, + applicationJson1, + List.of("Page1", "Page2")) + ) + .flatMap(application1 -> { + Mono<List<NewPage>> pageList = newPageService.findNewPagesByApplicationId(application1.getId(), MANAGE_PAGES).collectList(); + Mono<List<NewAction>> actionList = newActionService.findAllByApplicationIdAndViewMode(application1.getId(), false, MANAGE_ACTIONS, null).collectList(); + Mono<List<ActionCollection>> actionCollectionList = actionCollectionService.findAllByApplicationIdAndViewMode(application1.getId(), false, MANAGE_ACTIONS, null).collectList(); + return Mono.zip(Mono.just(application1), pageList, actionList, actionCollectionList); + }); + + + StepVerifier + .create(importedApplication) + .assertNext(tuple -> { + Application application1 = tuple.getT1(); + List<NewPage> pageList = tuple.getT2(); + List<NewAction> actionList = tuple.getT3(); + List<ActionCollection> actionCollectionList = tuple.getT4(); + + assertThat(application1.getId()).isEqualTo(finalApplication.getId()); + assertThat(finalApplication.getPages().size()).isLessThan(application1.getPages().size()); + assertThat(finalApplication.getPages().size()).isEqualTo(application1.getPublishedPages().size()); + + // Verify the pages after merging the template + pageList.forEach(newPage -> { + assertThat(newPage.getUnpublishedPage().getName()).containsAnyOf("Page1", "Page12", "Page2"); + assertThat(newPage.getGitSyncId()).isNotNull(); + }); + + NewPage page = pageList.stream().filter(newPage -> newPage.getUnpublishedPage().getName().equals("Page12")).collect(Collectors.toList()).get(0); + // Verify the actions after merging the template + actionList.forEach(newAction -> { + assertThat(newAction.getUnpublishedAction().getName()).containsAnyOf("api_wo_auth", "get_users", "run"); + assertThat(newAction.getUnpublishedAction().getPageId()).isEqualTo(page.getId()); + }); + + // Verify the actionCollections after merging the template + actionCollectionList.forEach(newAction -> { + assertThat(newAction.getUnpublishedCollection().getName()).containsAnyOf("JSObject1", "JSObject2"); + assertThat(newAction.getUnpublishedCollection().getPageId()).isEqualTo(page.getId()); + }); + }) + .verifyComplete(); + } + + @Test + @WithUserDetails(value = "api_user") + public void importApplication_invalidJson_createdAppIsDeleted() { + FilePart filePart = createFilePart("test_assets/ImportExportServiceTest/invalid-json-without-pages.json"); + + List<Application> applicationList = applicationService.findAllApplicationsByWorkspaceId(workspaceId).collectList().block(); + + Mono<ApplicationImportDTO> resultMono = importExportApplicationService.extractFileAndSaveApplication(workspaceId, filePart); + + StepVerifier + .create(resultMono) + .expectErrorMatches(throwable -> throwable instanceof AppsmithException && + throwable.getMessage().equals(AppsmithError.NO_RESOURCE_FOUND.getMessage(FieldName.PAGES, INVALID_JSON_FILE))) + .verify(); + + // Verify that the app card is not created + StepVerifier + .create(applicationService.findAllApplicationsByWorkspaceId(workspaceId).collectList()) + .assertNext(applications -> { + assertThat(applicationList.size()).isEqualTo(applications.size()); + }) + .verifyComplete(); + + } +}
0b4d6645585344bdd507248659f4ecaf87e71795
2024-07-03 19:11:41
Shrikant Sharat Kandula
chore: Remove strict payload parsing (#34680)
false
Remove strict payload parsing (#34680)
chore
diff --git a/app/client/src/api/DatasourcesApi.ts b/app/client/src/api/DatasourcesApi.ts index 3a1b1ef7f6c3..1ba5810ba2a9 100644 --- a/app/client/src/api/DatasourcesApi.ts +++ b/app/client/src/api/DatasourcesApi.ts @@ -50,9 +50,6 @@ class DatasourcesApi extends API { datasourceConfiguration: { ...storage.datasourceConfiguration, isValid: undefined, - authentication: DatasourcesApi.cleanAuthenticationObject( - storage.datasourceConfiguration.authentication, - ), connection: storage.datasourceConfiguration.connection && { ...storage.datasourceConfiguration.connection, ssl: { @@ -70,6 +67,7 @@ class DatasourcesApi extends API { return API.post(DatasourcesApi.url, datasourceConfig); } + // Need for when we add strict type checking back on server static cleanAuthenticationObject(authentication: any): any { if (!authentication) { return undefined; @@ -144,9 +142,6 @@ class DatasourcesApi extends API { toastMessage: undefined, datasourceConfiguration: datasourceConfig.datasourceConfiguration && { ...datasourceConfig.datasourceConfiguration, - authentication: DatasourcesApi.cleanAuthenticationObject( - datasourceConfig.datasourceConfiguration.authentication, - ), connection: datasourceConfig.datasourceConfiguration.connection && { ...datasourceConfig.datasourceConfiguration.connection, ssl: { @@ -179,9 +174,6 @@ class DatasourcesApi extends API { toastMessage: undefined, datasourceConfiguration: datasourceStorage.datasourceConfiguration && { ...datasourceStorage.datasourceConfiguration, - authentication: DatasourcesApi.cleanAuthenticationObject( - datasourceStorage.datasourceConfiguration.authentication, - ), connection: datasourceStorage.datasourceConfiguration.connection && { ...datasourceStorage.datasourceConfiguration.connection, ssl: { diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/configurations/CommonConfig.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/configurations/CommonConfig.java index 1767baaf12e3..72545773fb46 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/configurations/CommonConfig.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/configurations/CommonConfig.java @@ -3,7 +3,6 @@ import com.appsmith.util.JSONPrettyPrinter; import com.appsmith.util.SerializationUtils; import com.fasterxml.jackson.core.PrettyPrinter; -import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.gson.Gson; import com.google.gson.GsonBuilder; @@ -18,7 +17,6 @@ import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; -import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter; import org.springframework.util.StringUtils; import reactor.core.scheduler.Scheduler; import reactor.core.scheduler.Schedulers; @@ -103,16 +101,6 @@ public ObjectMapper objectMapper() { return SerializationUtils.getDefaultObjectMapper(null); } - @Bean - public MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter() { - final MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter(); - - converter.setObjectMapper(objectMapper() - .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, "CE".equals(ProjectProperties.EDITION))); - - return converter; - } - @Bean public Gson gsonInstance() { GsonBuilder gsonBuilder = new GsonBuilder();
3a3d51231c1feeeeed1d82e4b3d33d9c76a99238
2023-01-13 10:47:45
Ankita Kinger
fix: Updating logic to push blank key value params based on manage access for APIs (#19722)
false
Updating logic to push blank key value params based on manage access for APIs (#19722)
fix
diff --git a/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/Workspace/MemberRoles_Spec.ts b/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/Workspace/MemberRoles_Spec.ts index 9d19c3332dd3..f052547f91b6 100644 --- a/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/Workspace/MemberRoles_Spec.ts +++ b/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/Workspace/MemberRoles_Spec.ts @@ -66,7 +66,6 @@ describe("Create new workspace and invite user & validate all roles", () => { cy.wait(2000); cy.xpath(HomePage.selectRole).click(); cy.get(".t--dropdown-option") - // .should("have.length", Cypress.env("Edition") === 1 ? 1 : 2) .should("have.length", 1) .and("contain.text", `App Viewer`); cy.get(HomePage.closeBtn).click(); @@ -105,7 +104,6 @@ describe("Create new workspace and invite user & validate all roles", () => { cy.wait(2000); cy.xpath(HomePage.selectRole).click(); cy.get(".t--dropdown-option") - // .should("have.length", Cypress.env("Edition") === 0 ? 2 : 3) .should("have.length", 2) .and("contain.text", `App Viewer`, `Developer`); cy.get(HomePage.editModeInviteModalCloseBtn).click(); @@ -150,7 +148,6 @@ describe("Create new workspace and invite user & validate all roles", () => { cy.wait(2000); cy.xpath(HomePage.selectRole).click(); cy.get(".t--dropdown-option") - // .should("have.length", Cypress.env("Edition") === 0 ? 3 : 4) .should("have.length", 3) .should("contain.text", `App Viewer`, `Developer`); cy.get(".t--dropdown-option").should("contain.text", `Administrator`); diff --git a/app/client/src/pages/Editor/APIEditor/CommonEditorForm.tsx b/app/client/src/pages/Editor/APIEditor/CommonEditorForm.tsx index c733a41ccfcc..1a68fcfbf771 100644 --- a/app/client/src/pages/Editor/APIEditor/CommonEditorForm.tsx +++ b/app/client/src/pages/Editor/APIEditor/CommonEditorForm.tsx @@ -719,7 +719,7 @@ function CommonEditorForm(props: CommonFormPropsWithExtraParams) { label="Headers" name="actionConfiguration.headers" placeholder="Value" - pushFields + pushFields={isChangePermitted} theme={theme} /> </TabSection> @@ -743,7 +743,7 @@ function CommonEditorForm(props: CommonFormPropsWithExtraParams) { hideHeader={!!props.datasourceParams.length} label="Params" name="actionConfiguration.queryParameters" - pushFields + pushFields={isChangePermitted} theme={theme} /> </TabSection> diff --git a/app/client/src/sagas/ActionExecution/PluginActionSaga.ts b/app/client/src/sagas/ActionExecution/PluginActionSaga.ts index 6bdc62255a16..f99ee91cbb10 100644 --- a/app/client/src/sagas/ActionExecution/PluginActionSaga.ts +++ b/app/client/src/sagas/ActionExecution/PluginActionSaga.ts @@ -530,8 +530,8 @@ function* runActionSaga( if (isSaving || isDirty || isSavingEntity) { if (isDirty && !isSaving) { yield put(updateAction({ id: actionId })); + yield take(ReduxActionTypes.UPDATE_ACTION_SUCCESS); } - yield take(ReduxActionTypes.UPDATE_ACTION_SUCCESS); } const actionObject = shouldBeDefined<Action>( yield select(getAction, actionId),
cfcc00ef6727abdf7a357dbc3e73f7f9e30e26d8
2024-05-22 18:10:22
Abhijeet
fix: Remove the strict check for mongo url (#33652)
false
Remove the strict check for mongo url (#33652)
fix
diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/configurations/CommonDBConfig.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/configurations/CommonDBConfig.java index b7bd7a52f11d..662777fb30cd 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/configurations/CommonDBConfig.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/configurations/CommonDBConfig.java @@ -30,7 +30,8 @@ public class CommonDBConfig { @Primary @Profile("!test") public MongoProperties configureMongoDB() { - if (!appsmithDbUrl.startsWith("mongodb")) { + log.debug("Configuring MongoDB with url: {}", appsmithDbUrl); + if (!appsmithDbUrl.contains("mongodb")) { return null; } log.info("Found MongoDB uri configuring now"); diff --git a/deploy/docker/fs/opt/appsmith/entrypoint.sh b/deploy/docker/fs/opt/appsmith/entrypoint.sh index 2bf6be004ed4..76ce9d2c639a 100644 --- a/deploy/docker/fs/opt/appsmith/entrypoint.sh +++ b/deploy/docker/fs/opt/appsmith/entrypoint.sh @@ -183,6 +183,7 @@ configure_database_connection_url() { elif [[ "${APPSMITH_DB_URL}" == "mongodb"* ]]; then isMongoUrl=1 fi + echo "Configured database connection URL is $APPSMITH_DB_URL" } check_db_uri() {
f87ba6a6714dd1ee44a72b36a38c44498dc8d310
2023-04-27 19:22:41
Ayangade Adeoluwa
feat: Feat/add google sheets metdata (#22577)
false
Feat/add google sheets metdata (#22577)
feat
diff --git a/app/client/src/ce/constants/messages.ts b/app/client/src/ce/constants/messages.ts index c66f5498dfb4..f39ad4d368fb 100644 --- a/app/client/src/ce/constants/messages.ts +++ b/app/client/src/ce/constants/messages.ts @@ -1571,8 +1571,7 @@ export const RECONNECT_BUTTON_TEXT = () => "RECONNECT"; export const SAVE_BUTTON_TEXT = () => "SAVE"; export const SAVE_AND_AUTHORIZE_BUTTON_TEXT = () => "SAVE AND AUTHORIZE"; export const DISCARD_POPUP_DONT_SAVE_BUTTON_TEXT = () => "DON'T SAVE"; -export const GSHEET_AUTHORISED_FILE_IDS_KEY = () => - "Google sheets authorised file ids key"; +export const GSHEET_AUTHORISED_FILE_IDS_KEY = () => "userAuthorizedSheetIds"; export const GOOGLE_SHEETS_INFO_BANNER_MESSAGE = () => "Appsmith will require access to your google drive to access google sheets."; export const GOOGLE_SHEETS_AUTHORIZE_DATASOURCE = () => "Authorize Datasource"; diff --git a/app/client/src/components/formControls/BaseControl.tsx b/app/client/src/components/formControls/BaseControl.tsx index b312ace0c535..84c97f6a6f73 100644 --- a/app/client/src/components/formControls/BaseControl.tsx +++ b/app/client/src/components/formControls/BaseControl.tsx @@ -20,7 +20,12 @@ export type ComparisonOperations = | "GREATER" | "IN" | "NOT_IN" - | "FEATURE_FLAG"; + | "FEATURE_FLAG" + | "VIEW_MODE"; + +export enum ComparisonOperationsEnum { + VIEW_MODE = "VIEW_MODE", +} export type HiddenType = boolean | Condition | ConditionObject; diff --git a/app/client/src/components/formControls/utils.ts b/app/client/src/components/formControls/utils.ts index 3be307ffdad1..3f53d3d7b793 100644 --- a/app/client/src/components/formControls/utils.ts +++ b/app/client/src/components/formControls/utils.ts @@ -65,6 +65,7 @@ export const caculateIsHidden = ( values: any, hiddenConfig?: HiddenType, featureFlags?: FeatureFlags, + viewMode?: boolean, ) => { if (!!hiddenConfig && !isBoolean(hiddenConfig)) { let valueAtPath; @@ -102,6 +103,9 @@ export const caculateIsHidden = ( // and show new configs if feature flag is enabled, if disabled/ not present, // previous config would be shown as is return !!featureFlags && featureFlags[flagValue] === value; + case "VIEW_MODE": + // This can be used to decide which form controls to show in view mode or edit mode depending on the value. + return viewMode === value; default: return true; } @@ -112,13 +116,14 @@ export const isHidden = ( values: any, hiddenConfig?: HiddenType, featureFlags?: FeatureFlags, + viewMode?: boolean, ) => { if (!!hiddenConfig && !isBoolean(hiddenConfig)) { if ("conditionType" in hiddenConfig) { //check if nested conditions exist return isHiddenConditionsEvaluation(values, hiddenConfig); } else { - return caculateIsHidden(values, hiddenConfig, featureFlags); + return caculateIsHidden(values, hiddenConfig, featureFlags, viewMode); } } return !!hiddenConfig; diff --git a/app/client/src/pages/Editor/DataSourceEditor/Connected.tsx b/app/client/src/pages/Editor/DataSourceEditor/Connected.tsx index 0ca2aad3f3a8..afea32499155 100644 --- a/app/client/src/pages/Editor/DataSourceEditor/Connected.tsx +++ b/app/client/src/pages/Editor/DataSourceEditor/Connected.tsx @@ -2,12 +2,10 @@ import React from "react"; import { useSelector } from "react-redux"; import { useParams } from "react-router"; import type { AppState } from "@appsmith/reducers"; -import { isNil } from "lodash"; import { getDatasource, getPlugin } from "selectors/entitiesSelector"; import { Colors } from "constants/Colors"; import { HeaderIcons } from "icons/HeaderIcons"; import styled from "styled-components"; -import RenderDatasourceInformation from "./DatasourceSection"; import NewActionButton from "./NewActionButton"; import { hasCreateDatasourceActionPermission } from "@appsmith/utils/permissionHelpers"; @@ -28,16 +26,8 @@ const Header = styled.div` justify-content: space-between; `; -const Wrapper = styled.div` - display: flex; - flex-direction: column; - border-bottom: 1px solid #d0d7dd; - padding: 24px 20px; -`; - function Connected({ errorComponent, - hideDatasourceRenderSection = false, showDatasourceSavedText = true, }: { errorComponent?: JSX.Element | null; @@ -50,10 +40,6 @@ function Connected({ getDatasource(state, params.datasourceId), ); - const datasourceFormConfigs = useSelector( - (state: AppState) => state.entities.plugins.formConfigs, - ); - const plugin = useSelector((state: AppState) => getPlugin(state, datasource?.pluginId ?? ""), ); @@ -67,11 +53,8 @@ function Connected({ ...pagePermissions, ]); - const currentFormConfig: Array<any> = - datasourceFormConfigs[datasource?.pluginId ?? ""]; - return ( - <Wrapper> + <> {showDatasourceSavedText && ( <Header> <ConnectedText> @@ -91,17 +74,7 @@ function Connected({ </Header> )} {errorComponent} - <div style={{ marginTop: showDatasourceSavedText ? "30px" : "" }}> - {!isNil(currentFormConfig) && - !isNil(datasource) && - !hideDatasourceRenderSection ? ( - <RenderDatasourceInformation - config={currentFormConfig[0]} - datasource={datasource} - /> - ) : undefined} - </div> - </Wrapper> + </> ); } diff --git a/app/client/src/pages/Editor/DataSourceEditor/DBForm.tsx b/app/client/src/pages/Editor/DataSourceEditor/DBForm.tsx index 659cfe756bcc..8e18a7a19140 100644 --- a/app/client/src/pages/Editor/DataSourceEditor/DBForm.tsx +++ b/app/client/src/pages/Editor/DataSourceEditor/DBForm.tsx @@ -34,6 +34,7 @@ import Debugger, { } from "./Debugger"; import { getAssetUrl } from "@appsmith/utils/airgapHelpers"; import { showDebuggerFlag } from "selectors/debuggerSelectors"; +import DatasourceInformation from "./DatasourceSection"; import { DocsLink, openDoc } from "../../../constants/DocumentationLinks"; const { cloudHosting } = getAppsmithConfigs(); @@ -86,6 +87,13 @@ export const Form = styled.form` flex: 1; `; +const ViewModeWrapper = styled.div` + display: flex; + flex-direction: column; + border-bottom: 1px solid #d0d7dd; + padding: 24px 20px; +`; + class DatasourceDBEditor extends JSONtoForm<Props> { componentDidUpdate(prevProps: Props) { if (prevProps.datasourceId !== this.props.datasourceId) { @@ -125,6 +133,7 @@ class DatasourceDBEditor extends JSONtoForm<Props> { datasourceButtonConfiguration, datasourceDeleteTrigger, datasourceId, + formConfig, formData, messages, pluginType, @@ -200,7 +209,20 @@ class DatasourceDBEditor extends JSONtoForm<Props> { {""} </> )} - {viewMode && <Connected />} + {viewMode && ( + <ViewModeWrapper> + <Connected /> + <div style={{ marginTop: "30px" }}> + {!_.isNil(formConfig) && !_.isNil(datasource) ? ( + <DatasourceInformation + config={formConfig[0]} + datasource={datasource} + viewMode={viewMode} + /> + ) : undefined} + </div> + </ViewModeWrapper> + )} {/* Render datasource form call-to-actions */} {datasource && ( <DatasourceAuth diff --git a/app/client/src/pages/Editor/DataSourceEditor/DatasourceSection.tsx b/app/client/src/pages/Editor/DataSourceEditor/DatasourceSection.tsx index 0d462350fbba..38a34bae7533 100644 --- a/app/client/src/pages/Editor/DataSourceEditor/DatasourceSection.tsx +++ b/app/client/src/pages/Editor/DataSourceEditor/DatasourceSection.tsx @@ -5,6 +5,7 @@ import { Colors } from "constants/Colors"; import styled from "styled-components"; import { isHidden, isKVArray } from "components/formControls/utils"; import log from "loglevel"; +import { ComparisonOperationsEnum } from "components/formControls/BaseControl"; const Key = styled.div` color: ${Colors.DOVE_GRAY}; @@ -35,6 +36,7 @@ const FieldWrapper = styled.div` export default class RenderDatasourceInformation extends React.Component<{ config: any; datasource: Datasource; + viewMode?: boolean; }> { renderKVArray = (children: Array<any>) => { try { @@ -85,11 +87,12 @@ export default class RenderDatasourceInformation extends React.Component<{ }; renderDatasourceSection(section: any) { - const { datasource } = this.props; + const { datasource, viewMode } = this.props; return ( <React.Fragment key={datasource.id}> {map(section.children, (section) => { - if (isHidden(datasource, section.hidden)) return null; + if (isHidden(datasource, section.hidden, undefined, viewMode)) + return null; if ("children" in section) { if (isKVArray(section.children)) { return this.renderKVArray(section.children); @@ -123,6 +126,15 @@ export default class RenderDatasourceInformation extends React.Component<{ } } + if ( + !value && + !!viewMode && + "comparison" in section.hidden && + section.hidden.comparison === ComparisonOperationsEnum.VIEW_MODE + ) { + value = section.initialValue; + } + if (!value || (isArray(value) && value.length < 1)) { return; } diff --git a/app/client/src/pages/Editor/DataSourceEditor/JSONtoForm.tsx b/app/client/src/pages/Editor/DataSourceEditor/JSONtoForm.tsx index 60124d7d74ac..fd4e35d3749f 100644 --- a/app/client/src/pages/Editor/DataSourceEditor/JSONtoForm.tsx +++ b/app/client/src/pages/Editor/DataSourceEditor/JSONtoForm.tsx @@ -246,7 +246,14 @@ export class JSONtoForm< // hides features/configs that are hidden behind feature flag // TODO: remove hidden config property as well as this param, // when feature flag is removed - if (isHidden(this.props.formData, section.hidden, this.props?.featureFlags)) + if ( + isHidden( + this.props.formData, + section.hidden, + this.props?.featureFlags, + false, // viewMode is false here. + ) + ) return null; return ( <Collapsible @@ -314,8 +321,9 @@ export class JSONtoForm< if ( isHidden( this.props.formData, - section.hidden, + propertyControlOrSection.hidden, this.props?.featureFlags, + false, ) ) return null; diff --git a/app/client/src/pages/Editor/QueryEditor/EditorJSONtoForm.tsx b/app/client/src/pages/Editor/QueryEditor/EditorJSONtoForm.tsx index 6ccc4c5c0b32..255b4000237b 100644 --- a/app/client/src/pages/Editor/QueryEditor/EditorJSONtoForm.tsx +++ b/app/client/src/pages/Editor/QueryEditor/EditorJSONtoForm.tsx @@ -738,7 +738,8 @@ export function EditorJSONtoForm(props: Props) { (section: any): any => { return section.children.map( (formControlOrSection: ControlProps, idx: number) => { - if (isHidden(props.formData, section.hidden)) return null; + if (isHidden(props.formData, section.hidden, undefined, false)) + return null; if (formControlOrSection.hasOwnProperty("children")) { return renderEachConfig(formName)(formControlOrSection); } else { diff --git a/app/client/src/pages/Editor/SaaSEditor/DatasourceForm.tsx b/app/client/src/pages/Editor/SaaSEditor/DatasourceForm.tsx index 12b6a35a85fc..bc8d8b10f361 100644 --- a/app/client/src/pages/Editor/SaaSEditor/DatasourceForm.tsx +++ b/app/client/src/pages/Editor/SaaSEditor/DatasourceForm.tsx @@ -29,7 +29,6 @@ import { } from "../DataSourceEditor/JSONtoForm"; import { getConfigInitialValues } from "components/formControls/utils"; import Connected from "../DataSourceEditor/Connected"; - import { getCurrentApplicationId, getGsheetProjectID, @@ -71,6 +70,8 @@ import { getDatasourceErrorMessage } from "./errorUtils"; import { getAssetUrl } from "@appsmith/utils/airgapHelpers"; import { DocumentationLink } from "../QueryEditor/EditorJSONtoForm"; import GoogleSheetFilePicker from "./GoogleSheetFilePicker"; +import DatasourceInformation from "./../DataSourceEditor/DatasourceSection"; +import styled from "styled-components"; interface StateProps extends JSONtoFormProps { applicationId: string; @@ -133,6 +134,13 @@ type State = { navigation(): void; }; +const ViewModeWrapper = styled.div` + display: flex; + flex-direction: column; + border-bottom: 1px solid #d0d7dd; + padding: 24px 20px; +`; + class DatasourceSaaSEditor extends JSONtoForm<Props, State> { constructor(props: Props) { super(props); @@ -272,6 +280,7 @@ class DatasourceSaaSEditor extends JSONtoForm<Props, State> { datasourceId, documentationLink, featureFlags, + formConfig, formData, gsheetProjectID, gsheetToken, @@ -410,20 +419,32 @@ class DatasourceSaaSEditor extends JSONtoForm<Props, State> { </> )} {viewMode && ( - <Connected - errorComponent={ - datasource && isGoogleSheetPlugin && !isPluginAuthorized ? ( - <AuthMessage - actionType={ActionType.AUTHORIZE} + <ViewModeWrapper> + <Connected + errorComponent={ + datasource && isGoogleSheetPlugin && !isPluginAuthorized ? ( + <AuthMessage + actionType="authorize" + datasource={datasource} + description={authErrorMessage} + pageId={pageId} + /> + ) : null + } + showDatasourceSavedText={!isGoogleSheetPlugin} + /> + <div style={{ marginTop: "30px" }}> + {!_.isNil(formConfig) && + !_.isNil(datasource) && + !hideDatasourceSection ? ( + <DatasourceInformation + config={formConfig[0]} datasource={datasource} - description={authErrorMessage} - pageId={pageId} + viewMode={!!viewMode} /> - ) : null - } - hideDatasourceRenderSection={hideDatasourceSection} - showDatasourceSavedText={!isGoogleSheetPlugin} - /> + ) : undefined} + </div> + </ViewModeWrapper> )} {/* Render datasource form call-to-actions */} {datasource && ( diff --git a/app/client/src/sagas/DatasourcesSagas.ts b/app/client/src/sagas/DatasourcesSagas.ts index 40726d386b14..99a4e177a5b5 100644 --- a/app/client/src/sagas/DatasourcesSagas.ts +++ b/app/client/src/sagas/DatasourcesSagas.ts @@ -1213,7 +1213,8 @@ function* filePickerActionCallbackSaga( // Once users selects/cancels the file selection, // Sending sheet ids selected as part of datasource // config properties in order to save it in database - set(datasource, "datasourceConfiguration.properties[0]", { + // using the second index specifically for file ids. + set(datasource, "datasourceConfiguration.properties[1]", { key: createMessage(GSHEET_AUTHORISED_FILE_IDS_KEY), value: fileIds, }); diff --git a/app/server/appsmith-plugins/googleSheetsPlugin/src/main/java/com/external/utils/SheetsUtil.java b/app/server/appsmith-plugins/googleSheetsPlugin/src/main/java/com/external/utils/SheetsUtil.java index 30ca8d94f83e..cae59d4c7fb2 100644 --- a/app/server/appsmith-plugins/googleSheetsPlugin/src/main/java/com/external/utils/SheetsUtil.java +++ b/app/server/appsmith-plugins/googleSheetsPlugin/src/main/java/com/external/utils/SheetsUtil.java @@ -15,6 +15,7 @@ public class SheetsUtil { private static final String FILE_SPECIFIC_DRIVE_SCOPE = "https://www.googleapis.com/auth/drive.file"; + private static final int USER_AUTHORIZED_SHEET_IDS_INDEX = 1; static Pattern COLUMN_NAME_PATTERN = Pattern.compile("[a-zA-Z]+"); public static int getColumnNumber(String columnName) { @@ -33,11 +34,11 @@ public static int getColumnNumber(String columnName) { public static Set<String> getUserAuthorizedSheetIds(DatasourceConfiguration datasourceConfiguration) { OAuth2 oAuth2 = (OAuth2) datasourceConfiguration.getAuthentication(); if (!isEmpty(datasourceConfiguration.getProperties()) - && datasourceConfiguration.getProperties().get(0) != null - && datasourceConfiguration.getProperties().get(0).getValue() != null + && datasourceConfiguration.getProperties().get(USER_AUTHORIZED_SHEET_IDS_INDEX) != null + && datasourceConfiguration.getProperties().get(USER_AUTHORIZED_SHEET_IDS_INDEX).getValue() != null && oAuth2.getScope() != null && oAuth2.getScope().contains(FILE_SPECIFIC_DRIVE_SCOPE)) { - ArrayList<String> temp = (ArrayList) datasourceConfiguration.getProperties().get(0).getValue(); + ArrayList<String> temp = (ArrayList) datasourceConfiguration.getProperties().get(USER_AUTHORIZED_SHEET_IDS_INDEX).getValue(); return new HashSet<String>(temp); } return null; diff --git a/app/server/appsmith-plugins/googleSheetsPlugin/src/main/resources/form.json b/app/server/appsmith-plugins/googleSheetsPlugin/src/main/resources/form.json index 96e279ace112..5fe2a428cb87 100644 --- a/app/server/appsmith-plugins/googleSheetsPlugin/src/main/resources/form.json +++ b/app/server/appsmith-plugins/googleSheetsPlugin/src/main/resources/form.json @@ -72,6 +72,17 @@ "hidden": true, "initialValue": "authorization_code" }, + { + "label": "Account", + "configProperty": "datasourceConfiguration.properties[0].value", + "controlType": "INPUT_TEXT", + "isRequired": false, + "hidden": { + "comparison": "VIEW_MODE", + "value": false + }, + "initialValue": "Authorize datasource to fetch account name" + }, { "label": "Permissions | Scope", "configProperty": "datasourceConfiguration.authentication.scopeString",
74217484d740f47afd73342107acefd0c22882d4
2024-09-17 08:14:11
Abhijeet
chore: Add null check for PolicyUtils (#36341)
false
Add null check for PolicyUtils (#36341)
chore
diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/helpers/ce/PolicyUtil.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/helpers/ce/PolicyUtil.java index bc0a32dcb886..bd1314a29929 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/helpers/ce/PolicyUtil.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/helpers/ce/PolicyUtil.java @@ -15,6 +15,9 @@ public class PolicyUtil { public static boolean isPermissionPresentInPolicies( String permission, Set<Policy> policies, Set<String> userPermissionGroupIds) { + if (policies == null) { + return FALSE; + } Optional<Policy> interestingPolicyOptional = policies.stream() .filter(policy -> policy.getPermission().equals(permission)) .findFirst();
60503bb9a6764298a7555618dc6a80022db95a24
2022-04-22 15:14:22
Abhinav Jha
feat: Dynamic Height widget config (#13143)
false
Dynamic Height widget config (#13143)
feat
diff --git a/app/client/src/constants/PropertyControlConstants.tsx b/app/client/src/constants/PropertyControlConstants.tsx index 27857158faae..9911273ab84f 100644 --- a/app/client/src/constants/PropertyControlConstants.tsx +++ b/app/client/src/constants/PropertyControlConstants.tsx @@ -65,6 +65,9 @@ export type PropertyPaneControlConfig = { dependencies?: string[]; evaluatedDependencies?: string[]; // dependencies to be picked from the __evaluated__ object expected?: CodeEditorExpected; + // TODO(abhinav): To fix this, rename the options property of the controls which use this + // Alternatively, create a new structure + options?: any; }; type ValidationConfigParams = { diff --git a/app/client/src/pages/Editor/PropertyPane/Generator.tsx b/app/client/src/pages/Editor/PropertyPane/Generator.tsx index 37a82993f827..c2bd615f914c 100644 --- a/app/client/src/pages/Editor/PropertyPane/Generator.tsx +++ b/app/client/src/pages/Editor/PropertyPane/Generator.tsx @@ -52,6 +52,7 @@ export const generatePropertyControl = ( } else if ((config as PropertyPaneControlConfig).controlType) { return ( <Boxed + key={config.id + props.id} show={ (config as PropertyPaneControlConfig).propertyName !== "tableData" && props.type === "TABLE_WIDGET" diff --git a/app/client/src/utils/WidgetFactory.tsx b/app/client/src/utils/WidgetFactory.tsx index 52bf48649d1a..71f4441f0ee8 100644 --- a/app/client/src/utils/WidgetFactory.tsx +++ b/app/client/src/utils/WidgetFactory.tsx @@ -5,99 +5,22 @@ import { WidgetState, } from "widgets/BaseWidget"; import React from "react"; -import { - PropertyPaneConfig, - PropertyPaneControlConfig, - ValidationConfig, -} from "constants/PropertyControlConstants"; -import { generateReactKey } from "./generators"; +import { PropertyPaneConfig } from "constants/PropertyControlConstants"; + import { WidgetConfigProps } from "reducers/entityReducers/widgetConfigReducer"; -import { ValidationTypes } from "constants/WidgetValidation"; import { RenderMode } from "constants/WidgetConstants"; import * as log from "loglevel"; +import { WidgetFeatures } from "./WidgetFeatures"; +import { + addPropertyConfigIds, + convertFunctionsToString, + enhancePropertyPaneConfig, +} from "./WidgetFactoryHelpers"; type WidgetDerivedPropertyType = any; export type DerivedPropertiesMap = Record<string, string>; - -// TODO (abhinav): To enforce the property pane config structure in this function -// Throw an error if the config is not of the desired format. -const addPropertyConfigIds = (config: PropertyPaneConfig[]) => { - return config.map((sectionOrControlConfig: PropertyPaneConfig) => { - sectionOrControlConfig.id = generateReactKey(); - if (sectionOrControlConfig.children) { - sectionOrControlConfig.children = addPropertyConfigIds( - sectionOrControlConfig.children, - ); - } - const config = sectionOrControlConfig as PropertyPaneControlConfig; - if ( - config.panelConfig && - config.panelConfig.children && - Array.isArray(config.panelConfig.children) - ) { - config.panelConfig.children = addPropertyConfigIds( - config.panelConfig.children, - ); - - (sectionOrControlConfig as PropertyPaneControlConfig) = config; - } - return sectionOrControlConfig; - }); -}; - export type WidgetType = typeof WidgetFactory.widgetTypes[number]; -function validatePropertyPaneConfig(config: PropertyPaneConfig[]) { - return config.map((sectionOrControlConfig: PropertyPaneConfig) => { - if (sectionOrControlConfig.children) { - sectionOrControlConfig.children = sectionOrControlConfig.children.map( - validatePropertyControl, - ); - } - return sectionOrControlConfig; - }); -} - -function validatePropertyControl( - config: PropertyPaneConfig, -): PropertyPaneConfig { - const _config = config as PropertyPaneControlConfig; - if (_config.validation !== undefined) { - _config.validation = validateValidationStructure(_config.validation); - } - - if (_config.children) { - _config.children = _config.children.map(validatePropertyControl); - } - - if (_config.panelConfig) { - _config.panelConfig.children = _config.panelConfig.children.map( - validatePropertyControl, - ); - } - return _config; -} - -function validateValidationStructure( - config: ValidationConfig, -): ValidationConfig { - // Todo(abhinav): This only checks for top level params. Throwing nothing here. - if ( - config.type === ValidationTypes.FUNCTION && - config.params && - config.params.fn - ) { - config.params.fnString = config.params.fn.toString(); - if (!config.params.expected) - log.error( - `Error in configuration ${JSON.stringify(config)}: For a ${ - ValidationTypes.FUNCTION - } type validation, expected type and example are mandatory`, - ); - delete config.params.fn; - } - return config; -} class WidgetFactory { static widgetTypes: Record<string, string> = {}; static widgetMap: Map< @@ -134,6 +57,7 @@ class WidgetFactory { defaultPropertiesMap: Record<string, string>, metaPropertiesMap: Record<string, any>, propertyPaneConfig?: PropertyPaneConfig[], + features?: WidgetFeatures, ) { if (!this.widgetTypes[widgetType]) { this.widgetTypes[widgetType] = widgetType; @@ -143,13 +67,22 @@ class WidgetFactory { this.metaPropertiesMap.set(widgetType, metaPropertiesMap); if (propertyPaneConfig) { - const validatedPropertyPaneConfig = validatePropertyPaneConfig( + const enhancedPropertyPaneConfig = enhancePropertyPaneConfig( propertyPaneConfig, + features, + ); + + const serializablePropertyPaneConfig = convertFunctionsToString( + enhancedPropertyPaneConfig, + ); + + const finalPropertyPaneConfig = addPropertyConfigIds( + serializablePropertyPaneConfig, ); this.propertyPaneConfigsMap.set( widgetType, - Object.freeze(addPropertyConfigIds(validatedPropertyPaneConfig)), + Object.freeze(finalPropertyPaneConfig), ); } } diff --git a/app/client/src/utils/WidgetFactoryHelpers.test.ts b/app/client/src/utils/WidgetFactoryHelpers.test.ts new file mode 100644 index 000000000000..055b4e5dc994 --- /dev/null +++ b/app/client/src/utils/WidgetFactoryHelpers.test.ts @@ -0,0 +1,255 @@ +import { ValidationTypes } from "constants/WidgetValidation"; +import { WidgetProps } from "widgets/BaseWidget"; +import { AutocompleteDataType } from "./autocomplete/TernServer"; +import { + convertFunctionsToString, + enhancePropertyPaneConfig, +} from "./WidgetFactoryHelpers"; +import { DynamicHeight } from "./WidgetFeatures"; + +const ORIGINAL_PROPERTY_CONFIG = [ + { + sectionName: "General", + children: [ + { + propertyName: "url", + label: "URL", + controlType: "INPUT_TEXT", + placeholderText: "Enter URL", + inputType: "TEXT", + isBindProperty: true, + isTriggerProperty: false, + }, + ], + }, + { + sectionName: "Events", + children: [ + { + helpText: "Triggers an action when the video is played", + propertyName: "onPlay", + label: "onPlay", + controlType: "ACTION_SELECTOR", + isJSConvertible: true, + isBindProperty: true, + isTriggerProperty: true, + }, + { + helpText: "Triggers an action when the video is paused", + propertyName: "onPause", + label: "onPause", + controlType: "ACTION_SELECTOR", + isJSConvertible: true, + isBindProperty: true, + isTriggerProperty: true, + }, + { + helpText: "Triggers an action when the video ends", + propertyName: "onEnd", + label: "onEnd", + controlType: "ACTION_SELECTOR", + isJSConvertible: true, + isBindProperty: true, + isTriggerProperty: true, + }, + ], + }, +]; + +const EXPECTED_PROPERTY_CONFIG = [ + { + sectionName: "General", + children: [ + { + propertyName: "url", + label: "URL", + controlType: "INPUT_TEXT", + placeholderText: "Enter URL", + inputType: "TEXT", + isBindProperty: true, + isTriggerProperty: false, + }, + ], + }, + { + sectionName: "Layout Features", + children: [ + { + helpText: + "Dynamic Height: Configure the way the widget height react to content changes.", + propertyName: "dynamicHeight", + label: "Height", + controlType: "DROP_DOWN", + isBindProperty: false, + isTriggerProperty: false, + options: [ + { + label: "Hug Contents", + value: DynamicHeight.HUG_CONTENTS, + }, + { + label: "Fixed", + value: DynamicHeight.FIXED, + }, + ], + }, + { + propertyName: "minDynamicHeight", + label: "Min Height (in rows)", + helpText: "Minimum number of rows to occupy irrespective of contents", + controlType: "INPUT_TEXT", + hidden: (props: WidgetProps) => { + return props.dynamicHeight !== DynamicHeight.HUG_CONTENTS; + }, + dependencies: ["dynamicHeight"], + isJSConvertible: false, + isBindProperty: false, + isTriggerProperty: false, + }, + { + propertyName: "maxDynamicHeight", + label: "Max Height (in rows)", + helpText: "Maximum Height, after which contents will scroll", + controlType: "INPUT_TEXT", + dependencies: ["dynamicHeight"], + hidden: (props: WidgetProps) => { + return props.dynamicHeight !== DynamicHeight.HUG_CONTENTS; + }, + isJSConvertible: false, + isBindProperty: false, + isTriggerProperty: false, + }, + ], + }, + { + sectionName: "Events", + children: [ + { + helpText: "Triggers an action when the video is played", + propertyName: "onPlay", + label: "onPlay", + controlType: "ACTION_SELECTOR", + isJSConvertible: true, + isBindProperty: true, + isTriggerProperty: true, + }, + { + helpText: "Triggers an action when the video is paused", + propertyName: "onPause", + label: "onPause", + controlType: "ACTION_SELECTOR", + isJSConvertible: true, + isBindProperty: true, + isTriggerProperty: true, + }, + { + helpText: "Triggers an action when the video ends", + propertyName: "onEnd", + label: "onEnd", + controlType: "ACTION_SELECTOR", + isJSConvertible: true, + isBindProperty: true, + isTriggerProperty: true, + }, + ], + }, +]; + +describe("Widget Factory Helper tests", () => { + it("Make sure dynamicHeight property configs are added when enabled in widget", () => { + const features = { + dynamicHeight: true, + }; + const result = enhancePropertyPaneConfig( + ORIGINAL_PROPERTY_CONFIG, + features, + ); + expect(JSON.stringify(result)).toEqual( + JSON.stringify(EXPECTED_PROPERTY_CONFIG), + ); + }); + it("Make sure dynamicHeight property configs are NOT added when disabled in widget", () => { + const features = { + dynamicHeight: false, + }; + + const result_with_false = enhancePropertyPaneConfig( + ORIGINAL_PROPERTY_CONFIG, + features, + ); + const result_with_undefined = enhancePropertyPaneConfig( + ORIGINAL_PROPERTY_CONFIG, + undefined, + ); + + expect(result_with_false).toStrictEqual(ORIGINAL_PROPERTY_CONFIG); + expect(result_with_undefined).toStrictEqual(ORIGINAL_PROPERTY_CONFIG); + }); + + it("Makes sure that fn function validation params are converted to fnString", () => { + const add = (value: unknown) => { + return { + parsed: (value as string) + "__suffix", + message: [], + isValid: true, + }; + }; + const config = [ + { + sectionName: "General", + children: [ + { + propertyName: "url", + label: "URL", + controlType: "INPUT_TEXT", + placeholderText: "Enter URL", + inputType: "TEXT", + isBindProperty: true, + isTriggerProperty: false, + validation: { + type: ValidationTypes.FUNCTION, + params: { + fn: add, + expected: { + type: "number", + example: `100`, + autocompleteDataType: AutocompleteDataType.STRING, + }, + }, + }, + }, + ], + }, + ]; + + const expected = [ + { + sectionName: "General", + children: [ + { + propertyName: "url", + label: "URL", + controlType: "INPUT_TEXT", + placeholderText: "Enter URL", + inputType: "TEXT", + isBindProperty: true, + isTriggerProperty: false, + validation: { + type: ValidationTypes.FUNCTION, + params: { + fnString: add.toString(), + expected: { + type: "number", + example: `100`, + autocompleteDataType: AutocompleteDataType.STRING, + }, + }, + }, + }, + ], + }, + ]; + const result = convertFunctionsToString(config); + expect(result).toStrictEqual(expected); + }); +}); diff --git a/app/client/src/utils/WidgetFactoryHelpers.ts b/app/client/src/utils/WidgetFactoryHelpers.ts new file mode 100644 index 000000000000..5e08d4b9caae --- /dev/null +++ b/app/client/src/utils/WidgetFactoryHelpers.ts @@ -0,0 +1,102 @@ +import { + PropertyPaneConfig, + PropertyPaneControlConfig, +} from "constants/PropertyControlConstants"; +import { ValidationTypes } from "constants/WidgetValidation"; +import { generateReactKey } from "./generators"; +import { PropertyPaneConfigTemplates, WidgetFeatures } from "./WidgetFeatures"; + +/* This function recursively parses the property pane configuration and + adds random hash values as `id`. + + These are generated once when the Appsmith editor is loaded, + the resulting config is frozen and re-used during the lifecycle + of the current browser session. See WidgetFactory +*/ +export const addPropertyConfigIds = (config: PropertyPaneConfig[]) => { + return config.map((sectionOrControlConfig: PropertyPaneConfig) => { + sectionOrControlConfig.id = generateReactKey(); + if (sectionOrControlConfig.children) { + sectionOrControlConfig.children = addPropertyConfigIds( + sectionOrControlConfig.children, + ); + } + const config = sectionOrControlConfig as PropertyPaneControlConfig; + if ( + config.panelConfig && + config.panelConfig.children && + Array.isArray(config.panelConfig.children) + ) { + config.panelConfig.children = addPropertyConfigIds( + config.panelConfig.children, + ); + + (sectionOrControlConfig as PropertyPaneControlConfig) = config; + } + return sectionOrControlConfig; + }); +}; + +/* General function which enhances the property pane configuration + + We can use this to insert or add property configs based on widget + features passed as the second argument. +*/ +export function enhancePropertyPaneConfig( + config: PropertyPaneConfig[], + features?: WidgetFeatures, +) { + // Enhance property pane for dynamic height feature + if (features && features.dynamicHeight) { + config.splice(1, 0, PropertyPaneConfigTemplates.DYNAMIC_HEIGHT); + } + return config; +} + +/* + ValidationTypes.FUNCTION, allow us to configure functions within them, + However, these are not serializable, which results in them not being able to + be sent to the workers. + We convert these functions to strings and delete the original function properties + in this function + + property added `fnString` + property deleted `fn` +*/ + +export function convertFunctionsToString(config: PropertyPaneConfig[]) { + return config.map((sectionOrControlConfig: PropertyPaneConfig) => { + const controlConfig = sectionOrControlConfig as PropertyPaneControlConfig; + if ( + controlConfig.validation && + controlConfig.validation?.type === ValidationTypes.FUNCTION && + controlConfig.validation?.params && + controlConfig.validation?.params.fn + ) { + controlConfig.validation.params.fnString = controlConfig.validation.params.fn.toString(); + delete controlConfig.validation.params.fn; + return sectionOrControlConfig; + } + + if (sectionOrControlConfig.children) { + sectionOrControlConfig.children = convertFunctionsToString( + sectionOrControlConfig.children, + ); + } + + const config = sectionOrControlConfig as PropertyPaneControlConfig; + + if ( + config.panelConfig && + config.panelConfig.children && + Array.isArray(config.panelConfig.children) + ) { + config.panelConfig.children = convertFunctionsToString( + config.panelConfig.children, + ); + + (sectionOrControlConfig as PropertyPaneControlConfig) = config; + } + return sectionOrControlConfig; + }); +} diff --git a/app/client/src/utils/WidgetFeatures.test.ts b/app/client/src/utils/WidgetFeatures.test.ts new file mode 100644 index 000000000000..6b1f6440f635 --- /dev/null +++ b/app/client/src/utils/WidgetFeatures.test.ts @@ -0,0 +1,53 @@ +import { RenderModes } from "constants/WidgetConstants"; +import { WidgetProps } from "widgets/BaseWidget"; +import { + DynamicHeight, + hideDynamicHeightPropertyControl, +} from "./WidgetFeatures"; + +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("Widget Features tests", () => { + it("Make sure hidden hook for dynamic Height disables if dynamic height is disabled", () => { + const inputs = [ + DynamicHeight.FIXED, + "Some other value", + undefined, + null, + "hugcontents", + "hug_contents", + ]; + + inputs.forEach((dynamicHeight) => { + const result = hideDynamicHeightPropertyControl({ + ...DUMMY_WIDGET, + dynamicHeight, + }); + expect(result).toBe(true); + }); + }); + it("Make sure hidden hook for dynamic Height enabled if dynamic height is enabled", () => { + const inputs = [DynamicHeight.HUG_CONTENTS, "HUG_CONTENTS"]; + + inputs.forEach((dynamicHeight) => { + const result = hideDynamicHeightPropertyControl({ + ...DUMMY_WIDGET, + dynamicHeight, + }); + expect(result).toBe(false); + }); + }); +}); diff --git a/app/client/src/utils/WidgetFeatures.ts b/app/client/src/utils/WidgetFeatures.ts new file mode 100644 index 000000000000..2cc061b539ea --- /dev/null +++ b/app/client/src/utils/WidgetFeatures.ts @@ -0,0 +1,85 @@ +import { PropertyPaneConfig } from "constants/PropertyControlConstants"; +import { WidgetProps } from "widgets/BaseWidget"; + +export interface WidgetFeatures { + dynamicHeight: boolean; +} + +export enum DynamicHeight { + HUG_CONTENTS = "HUG_CONTENTS", + FIXED = "FIXED", +} + +/* This contains all properties which will be added + to a widget, automatically, by the Appsmith platform + Each feature, is a unique key, whose value is an object + with the list of properties to be added to a widget along + with their default values + + Note: These are added to the widget configs during registration +*/ +export const WidgetFeatureProps = { + DYNAMIC_HEIGHT: { + minDynamicHeight: 0, + maxDynamicHeight: 0, + dynamicHeight: DynamicHeight.FIXED, + }, +}; + +/* Hide the min height and max height properties using this function + as the `hidden` hook in the property pane configuration + This function checks if the `dynamicHeight` property is enabled + and returns true if disabled, and false if enabled. +*/ +export function hideDynamicHeightPropertyControl(props: WidgetProps) { + return props.dynamicHeight !== DynamicHeight.HUG_CONTENTS; +} + +export const PropertyPaneConfigTemplates: Record<string, PropertyPaneConfig> = { + DYNAMIC_HEIGHT: { + sectionName: "Layout Features", + children: [ + { + helpText: + "Dynamic Height: Configure the way the widget height react to content changes.", + propertyName: "dynamicHeight", + label: "Height", + controlType: "DROP_DOWN", + isBindProperty: false, + isTriggerProperty: false, + options: [ + { + label: "Hug Contents", + value: DynamicHeight.HUG_CONTENTS, + }, + { + label: "Fixed", + value: DynamicHeight.FIXED, + }, + ], + }, + { + propertyName: "minDynamicHeight", + label: "Min Height (in rows)", + helpText: "Minimum number of rows to occupy irrespective of contents", + controlType: "INPUT_TEXT", + hidden: hideDynamicHeightPropertyControl, + dependencies: ["dynamicHeight"], + isJSConvertible: false, + isBindProperty: false, + isTriggerProperty: false, + }, + { + propertyName: "maxDynamicHeight", + label: "Max Height (in rows)", + helpText: "Maximum Height, after which contents will scroll", + controlType: "INPUT_TEXT", + dependencies: ["dynamicHeight"], + hidden: hideDynamicHeightPropertyControl, + isJSConvertible: false, + isBindProperty: false, + isTriggerProperty: false, + }, + ], + }, +}; diff --git a/app/client/src/utils/WidgetRegisterHelpers.tsx b/app/client/src/utils/WidgetRegisterHelpers.tsx index af9ffc984373..e08d05cfeeca 100644 --- a/app/client/src/utils/WidgetRegisterHelpers.tsx +++ b/app/client/src/utils/WidgetRegisterHelpers.tsx @@ -3,31 +3,15 @@ import React from "react"; import * as Sentry from "@sentry/react"; import store from "store"; -import BaseWidget, { WidgetProps } from "widgets/BaseWidget"; -import { WidgetConfigProps } from "reducers/entityReducers/widgetConfigReducer"; -import { PropertyPaneConfig } from "constants/PropertyControlConstants"; -import WidgetFactory, { DerivedPropertiesMap } from "./WidgetFactory"; +import BaseWidget from "widgets/BaseWidget"; +import WidgetFactory from "./WidgetFactory"; import { ReduxActionTypes } from "@appsmith/constants/ReduxActionConstants"; import withMeta from "widgets/MetaHOC"; import { generateReactKey } from "./generators"; import { memoize } from "lodash"; - -export interface WidgetConfiguration { - type: string; - name: string; - iconSVG?: string; - defaults: Partial<WidgetProps> & WidgetConfigProps; - hideCard?: boolean; - isCanvas?: boolean; - needsMeta?: boolean; - properties: { - config: PropertyPaneConfig[]; - default: Record<string, string>; - meta: Record<string, any>; - derived: DerivedPropertiesMap; - }; -} +import { WidgetFeatureProps } from "./WidgetFeatures"; +import { WidgetConfiguration } from "widgets/constants"; const generateWidget = memoize(function getWidgetComponent( Widget: typeof BaseWidget, @@ -55,12 +39,18 @@ export const registerWidget = (Widget: any, config: WidgetConfiguration) => { config.properties.default, config.properties.meta, config.properties.config, + config.features, ); configureWidget(config); }; export const configureWidget = (config: WidgetConfiguration) => { + let features = {}; + if (config.features && config.features.dynamicHeight) { + features = Object.assign({}, WidgetFeatureProps.DYNAMIC_HEIGHT); + } const _config = { + ...features, ...config.defaults, type: config.type, hideCard: !!config.hideCard || !config.iconSVG, diff --git a/app/client/src/utils/WidgetRegistry.tsx b/app/client/src/utils/WidgetRegistry.tsx index d24e9f7ebd7d..fa98b80c43fc 100644 --- a/app/client/src/utils/WidgetRegistry.tsx +++ b/app/client/src/utils/WidgetRegistry.tsx @@ -144,7 +144,8 @@ import VideoWidget, { import ProgressWidget, { CONFIG as PROGRESS_WIDGET_CONFIG, } from "widgets/ProgressWidget"; -import { registerWidget, WidgetConfiguration } from "./WidgetRegisterHelpers"; +import { registerWidget } from "./WidgetRegisterHelpers"; +import { WidgetConfiguration } from "widgets/constants"; export const ALL_WIDGETS_AND_CONFIG = [ [CanvasWidget, CANVAS_WIDGET_CONFIG], diff --git a/app/client/src/widgets/constants.ts b/app/client/src/widgets/constants.ts index 69ae01b2f002..765e96a147cc 100644 --- a/app/client/src/widgets/constants.ts +++ b/app/client/src/widgets/constants.ts @@ -1,5 +1,26 @@ +import { PropertyPaneConfig } from "constants/PropertyControlConstants"; +import { WidgetConfigProps } from "reducers/entityReducers/widgetConfigReducer"; +import { DerivedPropertiesMap } from "utils/WidgetFactory"; +import { WidgetFeatures } from "utils/WidgetFeatures"; import { WidgetProps } from "./BaseWidget"; +export interface WidgetConfiguration { + type: string; + name: string; + iconSVG?: string; + defaults: Partial<WidgetProps> & WidgetConfigProps; + hideCard?: boolean; + isCanvas?: boolean; + needsMeta?: boolean; + features?: WidgetFeatures; + properties: { + config: PropertyPaneConfig[]; + default: Record<string, string>; + meta: Record<string, any>; + derived: DerivedPropertiesMap; + }; +} + export const GRID_DENSITY_MIGRATION_V1 = 4; export enum BlueprintOperationTypes {
02785b90b2829a5e912bec6ed49198d8f49e61d1
2022-01-18 13:22:24
balajisoundar
feat: Input, Phone no., Currency input widget (#10259)
false
Input, Phone no., Currency input widget (#10259)
feat
diff --git a/app/client/cypress/fixtures/CMSdsl.json b/app/client/cypress/fixtures/CMSdsl.json index 6479481a4f3c..996e0dc1f35e 100644 --- a/app/client/cypress/fixtures/CMSdsl.json +++ b/app/client/cypress/fixtures/CMSdsl.json @@ -286,7 +286,7 @@ "bottomRow": 20, "parentRowSpace": 10, "autoFocus": false, - "type": "INPUT_WIDGET", + "type": "INPUT_WIDGET_V2", "hideCard": false, "parentColumnSpace": 5.645751953125, "dynamicTriggerPathList": [], @@ -318,7 +318,7 @@ "bottomRow": 26, "parentRowSpace": 10, "autoFocus": false, - "type": "INPUT_WIDGET", + "type": "INPUT_WIDGET_V2", "hideCard": false, "parentColumnSpace": 5.645751953125, "dynamicTriggerPathList": [], @@ -350,7 +350,7 @@ "bottomRow": 32, "parentRowSpace": 10, "autoFocus": false, - "type": "INPUT_WIDGET", + "type": "INPUT_WIDGET_V2", "hideCard": false, "parentColumnSpace": 5.645751953125, "dynamicTriggerPathList": [], @@ -382,7 +382,7 @@ "bottomRow": 38, "parentRowSpace": 10, "autoFocus": false, - "type": "INPUT_WIDGET", + "type": "INPUT_WIDGET_V2", "hideCard": false, "parentColumnSpace": 5.645751953125, "dynamicTriggerPathList": [], @@ -414,7 +414,7 @@ "bottomRow": 6, "parentRowSpace": 10, "autoFocus": false, - "type": "INPUT_WIDGET", + "type": "INPUT_WIDGET_V2", "hideCard": false, "parentColumnSpace": 6.887054443359375, "dynamicTriggerPathList": [], @@ -1008,7 +1008,7 @@ "bottomRow": 13, "parentRowSpace": 10, "autoFocus": false, - "type": "INPUT_WIDGET", + "type": "INPUT_WIDGET_V2", "hideCard": false, "parentColumnSpace": 6.34375, "dynamicTriggerPathList": [], @@ -1040,7 +1040,7 @@ "bottomRow": 19, "parentRowSpace": 10, "autoFocus": false, - "type": "INPUT_WIDGET", + "type": "INPUT_WIDGET_V2", "hideCard": false, "parentColumnSpace": 6.34375, "dynamicTriggerPathList": [], @@ -1072,7 +1072,7 @@ "bottomRow": 36, "parentRowSpace": 10, "autoFocus": false, - "type": "INPUT_WIDGET", + "type": "INPUT_WIDGET_V2", "hideCard": false, "parentColumnSpace": 6.34375, "dynamicTriggerPathList": [], @@ -1187,7 +1187,7 @@ "bottomRow": 24, "parentRowSpace": 10, "autoFocus": false, - "type": "INPUT_WIDGET", + "type": "INPUT_WIDGET_V2", "hideCard": false, "parentColumnSpace": 6.0625, "dynamicTriggerPathList": [], @@ -1272,7 +1272,7 @@ "bottomRow": 12, "parentRowSpace": 10, "autoFocus": false, - "type": "INPUT_WIDGET", + "type": "INPUT_WIDGET_V2", "hideCard": false, "parentColumnSpace": 6.0625, "dynamicTriggerPathList": [], @@ -1304,7 +1304,7 @@ "bottomRow": 18, "parentRowSpace": 10, "autoFocus": false, - "type": "INPUT_WIDGET", + "type": "INPUT_WIDGET_V2", "hideCard": false, "parentColumnSpace": 6.0625, "dynamicTriggerPathList": [], diff --git a/app/client/cypress/fixtures/ChartDsl.json b/app/client/cypress/fixtures/ChartDsl.json index 18c85349c8bc..ef878a21595c 100644 --- a/app/client/cypress/fixtures/ChartDsl.json +++ b/app/client/cypress/fixtures/ChartDsl.json @@ -53,7 +53,7 @@ "widgetName": "Input1", "version": 1, "resetOnSubmit": true, - "type": "INPUT_WIDGET", + "type": "INPUT_WIDGET_V2", "isLoading": false, "parentColumnSpace": 74, "parentRowSpace": 40, @@ -71,7 +71,7 @@ "widgetName": "Input2", "version": 1, "resetOnSubmit": true, - "type": "INPUT_WIDGET", + "type": "INPUT_WIDGET_V2", "isLoading": false, "parentColumnSpace": 74, "parentRowSpace": 40, diff --git a/app/client/cypress/fixtures/Js_toggle_dsl.json b/app/client/cypress/fixtures/Js_toggle_dsl.json index a36552e5a4e1..864e137c8f8b 100644 --- a/app/client/cypress/fixtures/Js_toggle_dsl.json +++ b/app/client/cypress/fixtures/Js_toggle_dsl.json @@ -43,7 +43,7 @@ "inputType": "TEXT", "label": "", "widgetName": "Input1", - "type": "INPUT_WIDGET", + "type": "INPUT_WIDGET_V2", "isLoading": false, "parentColumnSpace": 74, "parentRowSpace": 40, diff --git a/app/client/cypress/fixtures/MultipleInput.json b/app/client/cypress/fixtures/MultipleInput.json index 8fcdaaf8aaf4..befcf22b16de 100644 --- a/app/client/cypress/fixtures/MultipleInput.json +++ b/app/client/cypress/fixtures/MultipleInput.json @@ -24,7 +24,7 @@ "inputType": "TEXT", "label": "", "widgetName": "Input1", - "type": "INPUT_WIDGET", + "type": "INPUT_WIDGET_V2", "isLoading": false, "parentColumnSpace": 74, "parentRowSpace": 40, @@ -40,7 +40,7 @@ "inputType": "TEXT", "label": "", "widgetName": "Input2", - "type": "INPUT_WIDGET", + "type": "INPUT_WIDGET_V2", "isLoading": false, "parentColumnSpace": 74, "parentRowSpace": 40, @@ -56,7 +56,7 @@ "inputType": "TEXT", "label": "", "widgetName": "Input3", - "type": "INPUT_WIDGET", + "type": "INPUT_WIDGET_V2", "isLoading": false, "parentColumnSpace": 74, "parentRowSpace": 40, diff --git a/app/client/cypress/fixtures/MultipleWidgetDsl.json b/app/client/cypress/fixtures/MultipleWidgetDsl.json index 03ad53df5ce7..23832e5cb0dd 100644 --- a/app/client/cypress/fixtures/MultipleWidgetDsl.json +++ b/app/client/cypress/fixtures/MultipleWidgetDsl.json @@ -24,7 +24,7 @@ "inputType": "TEXT", "label": "", "widgetName": "Input1", - "type": "INPUT_WIDGET", + "type": "INPUT_WIDGET_V2", "isLoading": false, "parentColumnSpace": 74, "parentRowSpace": 40, diff --git a/app/client/cypress/fixtures/PgAdmindsl.json b/app/client/cypress/fixtures/PgAdmindsl.json index 7d195001b83b..052cb6347060 100644 --- a/app/client/cypress/fixtures/PgAdmindsl.json +++ b/app/client/cypress/fixtures/PgAdmindsl.json @@ -1893,7 +1893,7 @@ "bottomRow": 18, "parentRowSpace": 10, "autoFocus": false, - "type": "INPUT_WIDGET", + "type": "INPUT_WIDGET_V2", "hideCard": false, "parentColumnSpace": 5.40625, "dynamicTriggerPathList": [], @@ -2299,7 +2299,7 @@ "bottomRow": 5, "parentRowSpace": 10, "autoFocus": false, - "type": "INPUT_WIDGET", + "type": "INPUT_WIDGET_V2", "hideCard": false, "parentColumnSpace": 6.015625, "resetOnSubmit": true, @@ -2688,7 +2688,7 @@ "isRequired": false, "isDisabled": false, "allowCurrencyChange": false, - "type": "INPUT_WIDGET", + "type": "INPUT_WIDGET_V2", "hideCard": false, "displayName": "Input", "key": "mqy3hiv1cd", @@ -2877,7 +2877,7 @@ "bottomRow": 4, "parentRowSpace": 10, "autoFocus": false, - "type": "INPUT_WIDGET", + "type": "INPUT_WIDGET_V2", "hideCard": false, "parentColumnSpace": 4.883636474609375, "resetOnSubmit": true, diff --git a/app/client/cypress/fixtures/autocomp.json b/app/client/cypress/fixtures/autocomp.json index a3983c06848d..39244e7bac37 100644 --- a/app/client/cypress/fixtures/autocomp.json +++ b/app/client/cypress/fixtures/autocomp.json @@ -71,7 +71,7 @@ "parentRowSpace": 38, "isVisible": true, "label": "Test Input Label", - "type": "INPUT_WIDGET", + "type": "INPUT_WIDGET_V2", "parentId": "iw4o07jvik", "isLoading": false, "parentColumnSpace": 34.6875, diff --git a/app/client/cypress/fixtures/basicDsl.json b/app/client/cypress/fixtures/basicDsl.json index a3932623ec56..86e217e5b627 100644 --- a/app/client/cypress/fixtures/basicDsl.json +++ b/app/client/cypress/fixtures/basicDsl.json @@ -1 +1 @@ -{"dsl":{"widgetName":"MainContainer","backgroundColor":"none","rightColumn":966,"snapColumns":64,"detachFromLayout":true,"widgetId":"0","topRow":0,"bottomRow":320,"containerStyle":"none","snapRows":125,"parentRowSpace":1,"type":"CANVAS_WIDGET","canExtend":true,"version":23,"minHeight":1292,"parentColumnSpace":1,"dynamicBindingPathList":[],"leftColumn":0,"children":[{"isVisible":true,"inputType":"TEXT","label":"","widgetName":"Input1","version":1,"resetOnSubmit":true,"isRequired":false,"isDisabled":false,"type":"INPUT_WIDGET","isLoading":false,"parentColumnSpace":14.84375,"parentRowSpace":10,"leftColumn":23,"rightColumn":43,"topRow":8,"bottomRow":12,"parentId":"0","widgetId":"ihviqc47ev"}],"dynamicTriggerPathList":[]}} \ No newline at end of file +{"dsl":{"widgetName":"MainContainer","backgroundColor":"none","rightColumn":966,"snapColumns":64,"detachFromLayout":true,"widgetId":"0","topRow":0,"bottomRow":320,"containerStyle":"none","snapRows":125,"parentRowSpace":1,"type":"CANVAS_WIDGET","canExtend":true,"version":23,"minHeight":1292,"parentColumnSpace":1,"dynamicBindingPathList":[],"leftColumn":0,"children":[{"isVisible":true,"inputType":"TEXT","label":"","widgetName":"Input1","version":1,"resetOnSubmit":true,"isRequired":false,"isDisabled":false,"type":"INPUT_WIDGET_V2","isLoading":false,"parentColumnSpace":14.84375,"parentRowSpace":10,"leftColumn":23,"rightColumn":43,"topRow":8,"bottomRow":12,"parentId":"0","widgetId":"ihviqc47ev"}],"dynamicTriggerPathList":[]}} \ No newline at end of file diff --git a/app/client/cypress/fixtures/commondsl.json b/app/client/cypress/fixtures/commondsl.json index 143fdacf79c1..b780924fa39a 100644 --- a/app/client/cypress/fixtures/commondsl.json +++ b/app/client/cypress/fixtures/commondsl.json @@ -68,7 +68,7 @@ "parentRowSpace": 38, "isVisible": true, "label": "Test Input Label", - "type": "INPUT_WIDGET", + "type": "INPUT_WIDGET_V2", "dynamicBindingPathList": [], "parentId": "iw4o07jvik", "isLoading": false, diff --git a/app/client/cypress/fixtures/debuggerDependencyDsl.json b/app/client/cypress/fixtures/debuggerDependencyDsl.json index d023180e2488..fc2eb22395b4 100644 --- a/app/client/cypress/fixtures/debuggerDependencyDsl.json +++ b/app/client/cypress/fixtures/debuggerDependencyDsl.json @@ -42,7 +42,7 @@ "inputType": "TEXT", "label": "", "widgetName": "Input1", - "type": "INPUT_WIDGET", + "type": "INPUT_WIDGET_V2", "isLoading": false, "parentColumnSpace": 74, "parentRowSpace": 40, diff --git a/app/client/cypress/fixtures/executionParamsDsl.json b/app/client/cypress/fixtures/executionParamsDsl.json index dbcd0e9ff268..970e1d73cc41 100644 --- a/app/client/cypress/fixtures/executionParamsDsl.json +++ b/app/client/cypress/fixtures/executionParamsDsl.json @@ -115,7 +115,7 @@ "label": "Endpoint", "widgetName": "EndpointInput", "defaultText": "users", - "type": "INPUT_WIDGET", + "type": "INPUT_WIDGET_V2", "isLoading": false, "parentColumnSpace": 71.75, "parentRowSpace": 38, diff --git a/app/client/cypress/fixtures/forkedApp.json b/app/client/cypress/fixtures/forkedApp.json index 8d92e622ac41..04354d79072d 100644 --- a/app/client/cypress/fixtures/forkedApp.json +++ b/app/client/cypress/fixtures/forkedApp.json @@ -297,7 +297,7 @@ "bottomRow": 47, "parentRowSpace": 10, "autoFocus": false, - "type": "INPUT_WIDGET", + "type": "INPUT_WIDGET_V2", "hideCard": false, "animateLoading": true, "parentColumnSpace": 12.5625, diff --git a/app/client/cypress/fixtures/formInputTableDsl.json b/app/client/cypress/fixtures/formInputTableDsl.json index a64c5144658c..8d76774acc43 100644 --- a/app/client/cypress/fixtures/formInputTableDsl.json +++ b/app/client/cypress/fixtures/formInputTableDsl.json @@ -85,7 +85,7 @@ "inputType": "TEXT", "label": "", "widgetName": "Input1", - "type": "INPUT_WIDGET", + "type": "INPUT_WIDGET_V2", "isLoading": false, "parentColumnSpace": 29.875, "parentRowSpace": 40, @@ -103,7 +103,7 @@ "inputType": "TEXT", "label": "", "widgetName": "Input2", - "type": "INPUT_WIDGET", + "type": "INPUT_WIDGET_V2", "isLoading": false, "parentColumnSpace": 29.875, "parentRowSpace": 40, diff --git a/app/client/cypress/fixtures/formResetDsl.json b/app/client/cypress/fixtures/formResetDsl.json index 9a0514262001..b89374b7448d 100644 --- a/app/client/cypress/fixtures/formResetDsl.json +++ b/app/client/cypress/fixtures/formResetDsl.json @@ -103,7 +103,7 @@ "inputType": "TEXT", "label": "", "widgetName": "Input1", - "type": "INPUT_WIDGET", + "type": "INPUT_WIDGET_V2", "isLoading": false, "parentColumnSpace": 71.5, "parentRowSpace": 40, diff --git a/app/client/cypress/fixtures/formWidgetWithInputValCheckDsl.json b/app/client/cypress/fixtures/formWidgetWithInputValCheckDsl.json index 4526b2e882fc..e9b9af77d70c 100644 --- a/app/client/cypress/fixtures/formWidgetWithInputValCheckDsl.json +++ b/app/client/cypress/fixtures/formWidgetWithInputValCheckDsl.json @@ -149,7 +149,7 @@ "bottomRow": 19, "parentRowSpace": 10, "autoFocus": false, - "type": "INPUT_WIDGET", + "type": "INPUT_WIDGET_V2", "hideCard": false, "parentColumnSpace": 9.3203125, "dynamicTriggerPathList": [], diff --git a/app/client/cypress/fixtures/formWithInputdsl.json b/app/client/cypress/fixtures/formWithInputdsl.json index 5a33e795b1fb..1adf89837bb7 100644 --- a/app/client/cypress/fixtures/formWithInputdsl.json +++ b/app/client/cypress/fixtures/formWithInputdsl.json @@ -166,7 +166,7 @@ "isRequired": false, "isDisabled": false, "allowCurrencyChange": false, - "type": "INPUT_WIDGET", + "type": "INPUT_WIDGET_V2", "isLoading": false, "parentColumnSpace": 14.90625, "parentRowSpace": 10, diff --git a/app/client/cypress/fixtures/inputBindingdsl.json b/app/client/cypress/fixtures/inputBindingdsl.json index 0970b08a6f58..474bceb5dda9 100644 --- a/app/client/cypress/fixtures/inputBindingdsl.json +++ b/app/client/cypress/fixtures/inputBindingdsl.json @@ -24,7 +24,7 @@ "inputType": "TEXT", "label": "", "widgetName": "Input1", - "type": "INPUT_WIDGET", + "type": "INPUT_WIDGET_V2", "isLoading": false, "parentColumnSpace": 74, "parentRowSpace": 40, @@ -40,7 +40,7 @@ "inputType": "TEXT", "label": "", "widgetName": "Input2", - "type": "INPUT_WIDGET", + "type": "INPUT_WIDGET_V2", "isLoading": false, "parentColumnSpace": 74, "parentRowSpace": 40, diff --git a/app/client/cypress/fixtures/inputMaxCharDsl.json b/app/client/cypress/fixtures/inputMaxCharDsl.json index 214392b1f804..545ff5279a5b 100644 --- a/app/client/cypress/fixtures/inputMaxCharDsl.json +++ b/app/client/cypress/fixtures/inputMaxCharDsl.json @@ -26,7 +26,7 @@ "defaultText": "1234567", "maxChars": 5, "widgetName": "Input1", - "type": "INPUT_WIDGET", + "type": "INPUT_WIDGET_V2", "isLoading": false, "parentColumnSpace": 74, "parentRowSpace": 40, diff --git a/app/client/cypress/fixtures/inputdsl.json b/app/client/cypress/fixtures/inputdsl.json index 4bfa22a4426a..f2c89d25d97a 100644 --- a/app/client/cypress/fixtures/inputdsl.json +++ b/app/client/cypress/fixtures/inputdsl.json @@ -24,7 +24,7 @@ "inputType": "TEXT", "label": "", "widgetName": "Input1", - "type": "INPUT_WIDGET", + "type": "INPUT_WIDGET_V2", "isLoading": false, "parentColumnSpace": 74, "parentRowSpace": 40, diff --git a/app/client/cypress/fixtures/mongo_PUT_replaceLayoutWithCRUD.json b/app/client/cypress/fixtures/mongo_PUT_replaceLayoutWithCRUD.json index 90f24a3477c6..5ac7cee6a85d 100644 --- a/app/client/cypress/fixtures/mongo_PUT_replaceLayoutWithCRUD.json +++ b/app/client/cypress/fixtures/mongo_PUT_replaceLayoutWithCRUD.json @@ -839,7 +839,7 @@ "parentRowSpace": 10.0, "isVisible": "true", "label": "", - "type": "INPUT_WIDGET", + "type": "INPUT_WIDGET_V2", "version": 1.0, "parentId": "tp9pui0e6y", "isLoading": false, @@ -894,7 +894,7 @@ "parentRowSpace": 10.0, "isVisible": "true", "label": "", - "type": "INPUT_WIDGET", + "type": "INPUT_WIDGET_V2", "version": 1.0, "parentId": "tp9pui0e6y", "isLoading": false, @@ -949,7 +949,7 @@ "parentRowSpace": 10.0, "isVisible": "true", "label": "", - "type": "INPUT_WIDGET", + "type": "INPUT_WIDGET_V2", "version": 1.0, "parentId": "tp9pui0e6y", "isLoading": false, @@ -1004,7 +1004,7 @@ "parentRowSpace": 10.0, "isVisible": "true", "label": "", - "type": "INPUT_WIDGET", + "type": "INPUT_WIDGET_V2", "version": 1.0, "parentId": "tp9pui0e6y", "isLoading": false, @@ -1184,7 +1184,7 @@ "parentRowSpace": 10.0, "isVisible": "true", "label": "", - "type": "INPUT_WIDGET", + "type": "INPUT_WIDGET_V2", "version": 1.0, "parentId": "cicukwhp5j", "isLoading": false, @@ -1214,7 +1214,7 @@ "parentRowSpace": 10.0, "isVisible": "true", "label": "", - "type": "INPUT_WIDGET", + "type": "INPUT_WIDGET_V2", "version": 1.0, "parentId": "cicukwhp5j", "isLoading": false, @@ -1244,7 +1244,7 @@ "parentRowSpace": 10.0, "isVisible": "true", "label": "", - "type": "INPUT_WIDGET", + "type": "INPUT_WIDGET_V2", "version": 1.0, "parentId": "cicukwhp5j", "isLoading": false, @@ -1274,7 +1274,7 @@ "parentRowSpace": 10.0, "isVisible": "true", "label": "", - "type": "INPUT_WIDGET", + "type": "INPUT_WIDGET_V2", "version": 1.0, "parentId": "cicukwhp5j", "isLoading": false, diff --git a/app/client/cypress/fixtures/multiSelectDsl.json b/app/client/cypress/fixtures/multiSelectDsl.json index de475e44ef6e..8126c7aa6884 100644 --- a/app/client/cypress/fixtures/multiSelectDsl.json +++ b/app/client/cypress/fixtures/multiSelectDsl.json @@ -71,7 +71,7 @@ "parentRowSpace": 38, "isVisible": true, "label": "", - "type": "INPUT_WIDGET", + "type": "INPUT_WIDGET_V2", "version": 1, "parentId": "e3tq9qwta6", "isLoading": false, diff --git a/app/client/cypress/fixtures/mySQL_PUT_replaceLayoutWithCRUD.json b/app/client/cypress/fixtures/mySQL_PUT_replaceLayoutWithCRUD.json index 77a375ffb40a..31314925a25a 100644 --- a/app/client/cypress/fixtures/mySQL_PUT_replaceLayoutWithCRUD.json +++ b/app/client/cypress/fixtures/mySQL_PUT_replaceLayoutWithCRUD.json @@ -841,7 +841,7 @@ "parentRowSpace": 10.0, "isVisible": "true", "label": "", - "type": "INPUT_WIDGET", + "type": "INPUT_WIDGET_V2", "version": 1.0, "parentId": "tp9pui0e6y", "isLoading": false, @@ -895,7 +895,7 @@ "parentRowSpace": 10.0, "isVisible": "true", "label": "", - "type": "INPUT_WIDGET", + "type": "INPUT_WIDGET_V2", "version": 1.0, "parentId": "tp9pui0e6y", "isLoading": false, @@ -950,7 +950,7 @@ "parentRowSpace": 10.0, "isVisible": "true", "label": "", - "type": "INPUT_WIDGET", + "type": "INPUT_WIDGET_V2", "version": 1.0, "parentId": "tp9pui0e6y", "isLoading": false, @@ -1005,7 +1005,7 @@ "parentRowSpace": 10.0, "isVisible": "true", "label": "", - "type": "INPUT_WIDGET", + "type": "INPUT_WIDGET_V2", "version": 1.0, "parentId": "tp9pui0e6y", "isLoading": false, @@ -1185,7 +1185,7 @@ "parentRowSpace": 10.0, "isVisible": "true", "label": "", - "type": "INPUT_WIDGET", + "type": "INPUT_WIDGET_V2", "version": 1.0, "parentId": "cicukwhp5j", "isLoading": false, @@ -1215,7 +1215,7 @@ "parentRowSpace": 10.0, "isVisible": "true", "label": "", - "type": "INPUT_WIDGET", + "type": "INPUT_WIDGET_V2", "version": 1.0, "parentId": "cicukwhp5j", "isLoading": false, @@ -1245,7 +1245,7 @@ "parentRowSpace": 10.0, "isVisible": "true", "label": "", - "type": "INPUT_WIDGET", + "type": "INPUT_WIDGET_V2", "version": 1.0, "parentId": "cicukwhp5j", "isLoading": false, diff --git a/app/client/cypress/fixtures/navigateToInputDsl.json b/app/client/cypress/fixtures/navigateToInputDsl.json index ba6da67bd881..e4fc275a9e45 100644 --- a/app/client/cypress/fixtures/navigateToInputDsl.json +++ b/app/client/cypress/fixtures/navigateToInputDsl.json @@ -29,7 +29,7 @@ "isRequired": false, "isDisabled": false, "allowCurrencyChange": false, - "type": "INPUT_WIDGET", + "type": "INPUT_WIDGET_V2", "isLoading": false, "parentColumnSpace": 14.90625, "parentRowSpace": 10, diff --git a/app/client/cypress/fixtures/newFormDsl.json b/app/client/cypress/fixtures/newFormDsl.json index fde4b7029727..df7a25a2f3d6 100644 --- a/app/client/cypress/fixtures/newFormDsl.json +++ b/app/client/cypress/fixtures/newFormDsl.json @@ -58,7 +58,7 @@ "label": "", "iconAlign": "left", "widgetName": "Input1", - "type": "INPUT_WIDGET", + "type": "INPUT_WIDGET_V2", "isLoading": false, "parentColumnSpace": 71.75, "parentRowSpace": 38, diff --git a/app/client/cypress/fixtures/previewMode.json b/app/client/cypress/fixtures/previewMode.json index 4076beeed221..e789905f0396 100644 --- a/app/client/cypress/fixtures/previewMode.json +++ b/app/client/cypress/fixtures/previewMode.json @@ -42,7 +42,7 @@ "inputType": "TEXT", "label": "", "widgetName": "Input1", - "type": "INPUT_WIDGET", + "type": "INPUT_WIDGET_V2", "isLoading": false, "parentColumnSpace": 74, "parentRowSpace": 40, diff --git a/app/client/cypress/fixtures/rundsl.json b/app/client/cypress/fixtures/rundsl.json index eeba23ca9c92..4535635c5b82 100644 --- a/app/client/cypress/fixtures/rundsl.json +++ b/app/client/cypress/fixtures/rundsl.json @@ -42,7 +42,7 @@ "inputType": "TEXT", "label": "", "widgetName": "Input1", - "type": "INPUT_WIDGET", + "type": "INPUT_WIDGET_V2", "isLoading": false, "parentColumnSpace": 74, "parentRowSpace": 40, diff --git a/app/client/cypress/fixtures/tabInputDsl.json b/app/client/cypress/fixtures/tabInputDsl.json index 6fb8d652e8f9..479627cf450c 100644 --- a/app/client/cypress/fixtures/tabInputDsl.json +++ b/app/client/cypress/fixtures/tabInputDsl.json @@ -24,7 +24,7 @@ "inputType": "TEXT", "label": "", "widgetName": "Input1", - "type": "INPUT_WIDGET", + "type": "INPUT_WIDGET_V2", "isLoading": false, "parentColumnSpace": 74, "parentRowSpace": 40, diff --git a/app/client/cypress/fixtures/tableInputDsl.json b/app/client/cypress/fixtures/tableInputDsl.json index c5b747ff4058..f25955fa2ff8 100644 --- a/app/client/cypress/fixtures/tableInputDsl.json +++ b/app/client/cypress/fixtures/tableInputDsl.json @@ -24,7 +24,7 @@ "inputType": "TEXT", "label": "", "widgetName": "Input1", - "type": "INPUT_WIDGET", + "type": "INPUT_WIDGET_V2", "isLoading": false, "parentColumnSpace": 74, "parentRowSpace": 40, diff --git a/app/client/cypress/fixtures/xmlParser.json b/app/client/cypress/fixtures/xmlParser.json index e499363a073f..ed63586a5c86 100644 --- a/app/client/cypress/fixtures/xmlParser.json +++ b/app/client/cypress/fixtures/xmlParser.json @@ -46,7 +46,7 @@ "inputType": "TEXT", "label": "", "widgetName": "Input1", - "type": "INPUT_WIDGET", + "type": "INPUT_WIDGET_V2", "isLoading": false, "parentColumnSpace": 74, "parentRowSpace": 40, diff --git a/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/Binding/InputWidgets_NavigateTo_validation_spec.js b/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/Binding/InputWidgets_NavigateTo_validation_spec.js index e8bb7f9d68ac..02c24e0c1f98 100644 --- a/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/Binding/InputWidgets_NavigateTo_validation_spec.js +++ b/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/Binding/InputWidgets_NavigateTo_validation_spec.js @@ -12,7 +12,7 @@ describe("Binding the multiple Widgets and validating NavigateTo Page", function }); it("Input widget test with default value from table widget", function() { - cy.openPropertyPane("inputwidget"); + cy.openPropertyPane("inputwidgetv2"); cy.get(widgetsPage.defaultInput).type(testdata.defaultInputWidget); cy.get(widgetsPage.inputOnTextChange) .first() diff --git a/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/Binding/No_Binding_Prompt_spec.js b/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/Binding/No_Binding_Prompt_spec.js index c30c12a45df2..c56e7568dae7 100644 --- a/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/Binding/No_Binding_Prompt_spec.js +++ b/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/Binding/No_Binding_Prompt_spec.js @@ -8,7 +8,7 @@ describe("Binding prompt", function() { }); it("Show binding prompt when there are no bindings in the editor", () => { - cy.openPropertyPane("inputwidget"); + cy.openPropertyPane("inputwidgetv2"); cy.testJsontext("defaulttext", " "); cy.get(dynamicInput.bindingPrompt).should("be.visible"); cy.get(widgetsPage.defaultInput).type("{{"); diff --git a/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/Binding/Widgets_Default_data_validation_spec.js b/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/Binding/Widgets_Default_data_validation_spec.js index 5742d7037173..a6210bbffb54 100644 --- a/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/Binding/Widgets_Default_data_validation_spec.js +++ b/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/Binding/Widgets_Default_data_validation_spec.js @@ -12,7 +12,7 @@ describe("Binding the multiple widgets and validating default data", function() }); it("Input widget test with default value from table widget", function() { - cy.openPropertyPane("inputwidget"); + cy.openPropertyPane("inputwidgetv2"); cy.testJsontext("defaulttext", testdata.defaultInputWidget + "}}"); cy.wait("@updateLayout").should( diff --git a/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/Binding/Widgets_Dependancy_validation_spec.js b/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/Binding/Widgets_Dependancy_validation_spec.js index ad14432e9a85..cb8decf02fe7 100644 --- a/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/Binding/Widgets_Dependancy_validation_spec.js +++ b/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/Binding/Widgets_Dependancy_validation_spec.js @@ -18,7 +18,7 @@ describe("Binding the multiple input Widget", function() { }); it("Cyclic depedancy error message validation", function() { - cy.openPropertyPane("inputwidget"); + cy.openPropertyPane("inputwidgetv2"); cy.testJsontext("defaulttext", testdata.defaultMoustacheData + "}}"); cy.wait("@updateLayout").should( @@ -30,7 +30,7 @@ describe("Binding the multiple input Widget", function() { }); it("Binding input widget1 and validating", function() { - cy.openPropertyPane("inputwidget"); + cy.openPropertyPane("inputwidgetv2"); cy.testJsontext("defaulttext", testdata.defaultdata); cy.wait("@updateLayout").should( diff --git a/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/Debugger/Inspect_Element_spec.js b/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/Debugger/Inspect_Element_spec.js index d188cbe79022..7bdf7c6f6da0 100644 --- a/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/Debugger/Inspect_Element_spec.js +++ b/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/Debugger/Inspect_Element_spec.js @@ -5,7 +5,7 @@ describe("Inspect Entity", function() { cy.addDsl(dsl); }); it("Check whether depedencies and references are shown correctly", function() { - cy.openPropertyPane("inputwidget"); + cy.openPropertyPane("inputwidgetv2"); cy.testJsontext("defaulttext", "{{Button1.text}}"); cy.get(".t--debugger").click(); diff --git a/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/FormWidgets/FormWidget_spec.js b/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/FormWidgets/FormWidget_spec.js index b309e8e0d786..43c81e588000 100644 --- a/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/FormWidgets/FormWidget_spec.js +++ b/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/FormWidgets/FormWidget_spec.js @@ -28,7 +28,7 @@ describe("Form Widget Functionality", function() { x: 100, y: 100, }); - cy.dragAndDropToWidget("inputwidget", "formwidget", { x: 50, y: 200 }); + cy.dragAndDropToWidget("inputwidgetv2", "formwidget", { x: 50, y: 200 }); cy.get(formWidgetsPage.multiselectWidget).should("be.visible"); cy.get(widgetsPage.inputWidget).should("be.visible"); cy.PublishtheApp(); diff --git a/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/FormWidgets/Input_MaxChar_spec.js b/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/FormWidgets/Input_MaxChar_spec.js index a5e87682c659..b2d531ab2a84 100644 --- a/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/FormWidgets/Input_MaxChar_spec.js +++ b/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/FormWidgets/Input_MaxChar_spec.js @@ -17,7 +17,7 @@ describe("Input Widget Max Char Functionality", function() { }); it("Number Input will not show error for maxChar validation", () => { - cy.openPropertyPane("inputwidget"); + cy.openPropertyPane("inputwidgetv2"); cy.selectDropdownValue(commonlocators.dataType, "Number"); cy.get(".bp3-popover-content").should("not.exist"); }); diff --git a/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/FormWidgets/Input_spec.js b/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/FormWidgets/Input_spec.js index 590723a8d596..a8ae82250f5b 100644 --- a/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/FormWidgets/Input_spec.js +++ b/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/FormWidgets/Input_spec.js @@ -10,7 +10,7 @@ describe("Input Widget Functionality", function() { // Note: commenting it out because Drag/Drop feature is not stable on cypress. // it("Checks if default values are not persisted in cache after delete", function() { - // cy.openPropertyPane("inputwidget"); + // cy.openPropertyPane("inputwidgetv2"); // cy.get(widgetsPage.defaultInput) // .type(this.data.command) // .type(this.data.defaultdata); @@ -19,7 +19,7 @@ describe("Input Widget Functionality", function() { // .should("contain", this.data.defaultdata); // cy.get(commonlocators.deleteWidget).click(); // cy.get(explorer.addWidget).click(); - // cy.dragAndDropToCanvas("inputwidget"); + // cy.dragAndDropToCanvas("inputwidgetv2"); // cy.get(widgetsPage.inputWidget + " " + "input") // .invoke("attr", "value") // .should("not.contain", this.data.defaultdata); @@ -29,7 +29,7 @@ describe("Input Widget Functionality", function() { // }); it("Input Widget Functionality", function() { - cy.openPropertyPane("inputwidget"); + cy.openPropertyPane("inputwidgetv2"); /** * @param{Text} Random Text * @param{InputWidget}Mouseover @@ -48,7 +48,7 @@ describe("Input Widget Functionality", function() { cy.get(widgetsPage.inputWidget + " " + "input") .invoke("attr", "value") .should("contain", this.data.para); - //cy.openPropertyPane("inputwidget"); + //cy.openPropertyPane("inputwidgetv2"); cy.testJsontext("defaulttext", this.data.defaultdata); cy.get(widgetsPage.inputWidget + " " + "input") .invoke("attr", "value") @@ -81,7 +81,7 @@ describe("Input Widget Functionality", function() { }); it("isSpellCheck: true", function() { - cy.openPropertyPane("inputwidget"); + cy.openPropertyPane("inputwidgetv2"); cy.togglebar(commonlocators.spellCheck + " " + "input"); cy.PublishtheApp(); cy.get(publish.inputWidget + " " + "input") @@ -91,7 +91,7 @@ describe("Input Widget Functionality", function() { }); it("isSpellCheck: false", function() { - cy.openPropertyPane("inputwidget"); + cy.openPropertyPane("inputwidgetv2"); cy.togglebarDisable(commonlocators.spellCheck + " " + "input"); cy.PublishtheApp(); cy.get(publish.inputWidget + " " + "input") @@ -101,28 +101,28 @@ describe("Input Widget Functionality", function() { }); it("Input Widget Functionality To Check Disabled Widget", function() { - cy.openPropertyPane("inputwidget"); + cy.openPropertyPane("inputwidgetv2"); cy.togglebar(commonlocators.Disablejs + " " + "input"); cy.PublishtheApp(); cy.get(publish.inputWidget + " " + "input").should("be.disabled"); cy.get(publish.backToEditor).click({ force: true }); }); it("Input Widget Functionality To Check Enabled Widget", function() { - cy.openPropertyPane("inputwidget"); + cy.openPropertyPane("inputwidgetv2"); cy.togglebarDisable(commonlocators.Disablejs + " " + "input"); cy.PublishtheApp(); cy.get(publish.inputWidget + " " + "input").should("be.enabled"); cy.get(publish.backToEditor).click({ force: true }); }); it("Input Functionality To Unchecked Visible Widget", function() { - cy.openPropertyPane("inputwidget"); + cy.openPropertyPane("inputwidgetv2"); cy.togglebarDisable(commonlocators.visibleCheckbox); cy.PublishtheApp(); cy.get(publish.inputWidget + " " + "input").should("not.exist"); cy.get(publish.backToEditor).click({ force: true }); }); it("Input Functionality To Check Visible Widget", function() { - cy.openPropertyPane("inputwidget"); + cy.openPropertyPane("inputwidgetv2"); cy.togglebar(commonlocators.visibleCheckbox); cy.PublishtheApp(); cy.get(publish.inputWidget + " " + "input").should("be.visible"); @@ -130,7 +130,7 @@ describe("Input Widget Functionality", function() { }); it("Input Functionality To check number input type with custom regex", function() { - cy.openPropertyPane("inputwidget"); + cy.openPropertyPane("inputwidgetv2"); cy.get(commonlocators.dataType) .last() .click({ force: true }); @@ -152,50 +152,7 @@ describe("Input Widget Functionality", function() { cy.get(widgetsPage.innertext) .click({ force: true }) .clear(); - cy.closePropertyPane("inputwidget"); - }); - - it("Input Functionality To check currency input type", function() { - cy.openPropertyPane("inputwidget"); - cy.testJsontext("regex", ""); - cy.get(widgetsPage.innertext) - .click() - .clear() - .type("13242.2"); - cy.selectDropdownValue(commonlocators.dataType, "Currency"); - cy.selectDropdownValue(commonlocators.decimalType, "1"); - cy.togglebar(commonlocators.allowCurrencyChange); - cy.selectDropdownValue(commonlocators.currencyType, "EUR - Euro"); - cy.get(widgetsPage.innertext) - .click() - .focus({ force: true }) - .blur(); - cy.wait(1000); - cy.get(commonlocators.inputCurrencyChangeType) - .invoke("text") - .then((text) => { - expect(text).to.equal("€"); - }); - cy.closePropertyPane("inputwidget"); - cy.get(widgetsPage.innertext) - .invoke("attr", "value") - .then((text) => { - expect(text).to.equal("13,242.2"); - }); - }); - - it("Input Functionality To check phone number input type", function() { - cy.get(widgetsPage.innertext) - .click() - .clear(); - cy.openPropertyPane("inputwidget"); - cy.wait(1000); - cy.selectDropdownValue(commonlocators.dataType, "Phone Number"); - cy.get(commonlocators.inputCountryCodeChangeType) - .invoke("text") - .then((text) => { - expect(text).to.equal("🇺🇸+1"); - }); + cy.closePropertyPane("inputwidgetv2"); }); it("Input label wrapper do not show if lable and tooltip is empty", () => { @@ -203,6 +160,7 @@ describe("Input Widget Functionality", function() { }); it("Input label renders if label prop is not empty", () => { + cy.openPropertyPane("inputwidgetv2"); // enter label in property pan cy.get(widgetsPage.inputLabelControl).type("Label1"); // test if label shows up with correct text @@ -210,6 +168,7 @@ describe("Input Widget Functionality", function() { }); it("Input tooltip renders if tooltip prop is not empty", () => { + cy.openPropertyPane("inputwidgetv2"); // enter tooltip in property pan cy.get(widgetsPage.inputTooltipControl).type("Helpfull text for input"); // tooltip help icon shows @@ -233,7 +192,7 @@ describe("Input Widget Functionality", function() { .click({ force: true }) .type("0");*/ cy.testJsontext("defaulttext", "0"); - cy.closePropertyPane("inputwidget"); + cy.closePropertyPane("inputwidgetv2"); cy.get(widgetsPage.innertext) .invoke("val") .then((text) => { diff --git a/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/FormWidgets/Phone_input_spec.js b/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/FormWidgets/Phone_input_spec.js new file mode 100644 index 000000000000..dd3c781c7bc5 --- /dev/null +++ b/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/FormWidgets/Phone_input_spec.js @@ -0,0 +1,57 @@ +const dsl = require("../../../../fixtures/emptyDSL.json"); +const explorer = require("../../../../locators/explorerlocators.json"); + +const widgetName = "phoneinputwidget"; + +describe("Phone input widget - ", () => { + before(() => { + cy.addDsl(dsl); + }); + + it("Add new dropdown widget", () => { + cy.get(explorer.addWidget).click(); + cy.dragAndDropToCanvas(widgetName, { x: 300, y: 300 }); + cy.get(`.t--widget-${widgetName}`).should("exist"); + cy.dragAndDropToCanvas("textwidget", { x: 300, y: 500 }); + cy.openPropertyPane("textwidget"); + cy.updateCodeInput( + ".t--property-control-text", + `{{PhoneInput1.text}}:{{PhoneInput1.countryCode}}:{{PhoneInput1.dialCode}}`, + ); + }); + + it("should check for the format and dialCode", () => { + cy.get(`.t--widget-${widgetName} input`).clear(); + cy.wait(300); + cy.get(`.t--widget-${widgetName} input`).type("9999999999"); + cy.get(".t--widget-textwidget").should("contain", "(999) 999-9999:US:+1"); + + cy.openPropertyPane(widgetName); + cy.selectDropdownValue( + ".t--property-control-defaultcountrycode", + "Afghanistan (+93)", + ); + cy.get(`.t--widget-${widgetName} input`).clear(); + cy.wait(300); + cy.get(`.t--widget-${widgetName} input`).type("1111111111"); + cy.get(".t--widget-textwidget").should("contain", "1111111111:AF:+93"); + cy.get(".t--input-country-code-change").should("contain", "🇦🇫+93"); + + cy.get(".t--property-control-allowcountrycodechange label") + .last() + .click({ force: true }); + cy.get(".t--input-country-code-change") + .first() + .click(); + cy.get(".t--search-input input").type("+91"); + cy.wait(500); + cy.get(".t--dropdown-option") + .last() + .click(); + cy.get(`.t--widget-${widgetName} input`).clear(); + cy.wait(300); + cy.get(`.t--widget-${widgetName} input`).type("9999999999"); + cy.get(".t--widget-textwidget").should("contain", "99999 99999:IN:+91"); + cy.get(".t--input-country-code-change").should("contain", "🇮🇳+91"); + }); +}); diff --git a/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/FormWidgets/currency_widget_spec.js b/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/FormWidgets/currency_widget_spec.js new file mode 100644 index 000000000000..adfcba3f8237 --- /dev/null +++ b/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/FormWidgets/currency_widget_spec.js @@ -0,0 +1,90 @@ +const dsl = require("../../../../fixtures/emptyDSL.json"); +const explorer = require("../../../../locators/explorerlocators.json"); + +const widgetName = "currencyinputwidget"; + +describe("Currency widget - ", () => { + before(() => { + cy.addDsl(dsl); + }); + + it("Add new dropdown widget", () => { + cy.get(explorer.addWidget).click(); + cy.dragAndDropToCanvas(widgetName, { x: 300, y: 300 }); + cy.get(`.t--widget-${widgetName}`).should("exist"); + cy.dragAndDropToCanvas("textwidget", { x: 300, y: 500 }); + cy.openPropertyPane("textwidget"); + cy.updateCodeInput( + ".t--property-control-text", + `{{CurrencyInput1.text}}:{{CurrencyInput1.value}}:{{CurrencyInput1.isValid}}:{{typeof CurrencyInput1.text}}:{{typeof CurrencyInput1.value}}:{{CurrencyInput1.countryCode}}:{{CurrencyInput1.currencyCode}}`, + ); + }); + + it("should check for type of value and widget", () => { + function enterAndTest(text, expected) { + cy.get(`.t--widget-${widgetName} input`).clear(); + cy.wait(300); + if (text) { + cy.get(`.t--widget-${widgetName} input`).type(text); + } + cy.openPropertyPane("textwidget"); + cy.get(".t--widget-textwidget").should("contain", expected); + } + [ + ["100", "100:100:true:string:number:AS:USD"], + ["1000", "1,000:1000:true:string:number:AS:USD"], + ["100.22", "10,022:10022:true:string:number:AS:USD"], + ["1000.22", "100,022:100022:true:string:number:AS:USD"], + ].forEach((d) => { + enterAndTest(d[0], d[1]); + }); + + cy.openPropertyPane(widgetName); + cy.selectDropdownValue(".t--property-control-decimals", "1"); + + [ + ["100", "100:100:true:string:number:AS:USD"], + ["1000", "1,000:1000:true:string:number:AS:USD"], + ["100.22", "100.2:100.2:true:string:number:AS:USD"], + ["1000.22", "1,000.2:1000.2:true:string:number:AS:USD"], + ].forEach((d) => { + enterAndTest(d[0], d[1]); + }); + + cy.openPropertyPane(widgetName); + cy.selectDropdownValue(".t--property-control-decimals", "2"); + + [ + ["100", "100:100:true:string:number:AS:USD"], + ["1000", "1,000:1000:true:string:number:AS:USD"], + ["100.22", "100.22:100.22:true:string:number:AS:USD"], + ["1000.22", "1,000.22:1000.22:true:string:number:AS:USD"], + ].forEach((d) => { + enterAndTest(d[0], d[1]); + }); + cy.get(".currency-type-trigger").should("contain", "$"); + + cy.openPropertyPane(widgetName); + cy.selectDropdownValue( + ".t--property-control-currency", + "INR - Indian Rupee", + ); + enterAndTest("100.22", "100.22:100.22:true:string:number:IN:INR"); + cy.get(".currency-type-trigger").should("contain", "₹"); + + cy.openPropertyPane(widgetName); + cy.get(".t--property-control-allowcurrencychange label") + .last() + .click({ force: true }); + cy.get(".t--input-currency-change") + .first() + .click(); + cy.get(".t--search-input input").type("gbp"); + cy.wait(500); + cy.get(".t--dropdown-option") + .last() + .click(); + enterAndTest("100.22", "100.22:100.22:true:string:number:GB:GBP"); + cy.get(".t--input-currency-change").should("contain", "£"); + }); +}); diff --git a/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/FormWidgets/input_v2_spec.js b/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/FormWidgets/input_v2_spec.js new file mode 100644 index 000000000000..bacb94eddbe0 --- /dev/null +++ b/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/FormWidgets/input_v2_spec.js @@ -0,0 +1,137 @@ +const dsl = require("../../../../fixtures/emptyDSL.json"); +const explorer = require("../../../../locators/explorerlocators.json"); + +const widgetName = "inputwidgetv2"; + +describe("Input widget V2 - ", () => { + before(() => { + cy.addDsl(dsl); + }); + + it("Add new dropdown widget", () => { + cy.get(explorer.addWidget).click(); + cy.dragAndDropToCanvas(widgetName, { x: 300, y: 300 }); + cy.get(`.t--widget-${widgetName}`).should("exist"); + cy.dragAndDropToCanvas("textwidget", { x: 300, y: 500 }); + cy.openPropertyPane("textwidget"); + cy.updateCodeInput( + ".t--property-control-text", + `{{Input1.text}}:{{Input1.value}}:{{Input1.isValid}}`, + ); + }); + + describe("TEXT type -", () => { + it("should test text can be entered into widget", () => { + function enterAndTest(text, expected) { + cy.get(`.t--widget-${widgetName} input`).clear(); + cy.wait(300); + if (text) { + cy.get(`.t--widget-${widgetName} input`).type(text); + } + cy.get(".t--widget-textwidget").should("contain", expected); + } + + [ + "test:test:true", + "test123:test123:true", + "123:123:true", + "::true", + "$100.22:$100.22:true", + "[email protected]:[email protected]:true", + ].forEach((text) => enterAndTest(text.split(":")[0], text)); + + cy.openPropertyPane(widgetName); + + cy.get(".t--property-control-required label") + .last() + .click({ force: true }); + + [ + "test:test:true", + "test123:test123:true", + "123:123:true", + "-:-:true", + "::false", + "$100.22:$100.22:true", + "[email protected]:[email protected]:true", + ].forEach((text) => enterAndTest(text.split(":")[0], text)); + }); + }); + + describe("Number type -", () => { + it("should test text can be entered into widge", () => { + cy.openPropertyPane(widgetName); + cy.selectDropdownValue(".t--property-control-datatype", "Number"); + function enterAndTest(text, expected) { + cy.get(`.t--widget-${widgetName} input`).clear(); + cy.wait(300); + if (text) { + cy.get(`.t--widget-${widgetName} input`).type(text); + } + cy.get(".t--widget-textwidget").should("contain", expected); + } + + [ + "test:", + "test123:123", + "123:123", + "-:-", + ":", + "$100.22:100.22", + "[email protected]:", + ].forEach((text) => { + enterAndTest(text.split(":")[0], text.split(":")[1]); + }); + }); + }); + + describe("Password type -", () => { + it("should test text can be entered into widget", () => { + cy.openPropertyPane(widgetName); + cy.selectDropdownValue(".t--property-control-datatype", "Password"); + function enterAndTest(text) { + cy.get(`.t--widget-${widgetName} input`).clear(); + cy.wait(300); + if (text) { + cy.get(`.t--widget-${widgetName} input`).type(text); + } + cy.get(".t--widget-textwidget").should("contain", text); + } + + [ + "test", + "test123", + "123", + "-", + "", + "$100.22", + "[email protected]", + ].forEach(enterAndTest); + }); + }); + + describe("Email type -", () => { + it("should test text can be entered into widget", () => { + cy.openPropertyPane(widgetName); + cy.selectDropdownValue(".t--property-control-datatype", "Email"); + function enterAndTest(text) { + cy.get(`.t--widget-${widgetName} input`).clear(); + cy.wait(300); + if (text) { + cy.get(`.t--widget-${widgetName} input`).type(text); + } + cy.get(".t--widget-textwidget").should("contain", text); + } + + [ + "test", + "test123", + "123", + "-", + "", + "$100.22", + "[email protected]", + ].forEach(enterAndTest); + }); + }); +}); diff --git a/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/Onboarding/Onboarding_spec.js b/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/Onboarding/Onboarding_spec.js index eb4847656e3e..5ae6792c9ae3 100644 --- a/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/Onboarding/Onboarding_spec.js +++ b/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/Onboarding/Onboarding_spec.js @@ -75,7 +75,7 @@ describe("Onboarding", function() { // eslint-disable-next-line cypress/no-unnecessary-waiting cy.wait(1000); cy.contains(".t--onboarding-helper-title", "Capture Hero Updates"); - cy.dragAndDropToCanvas("inputwidget", { x: 360, y: 40 }); + cy.dragAndDropToCanvas("inputwidgetv2", { x: 360, y: 40 }); cy.get(".t--property-control-onsubmit .t--open-dropdown-Select-Action") .click({ force: true }) .selectOnClickOption("Execute a query") diff --git a/app/client/cypress/locators/Widgets.json b/app/client/cypress/locators/Widgets.json index 9ed8630bd681..45582fa6db8e 100644 --- a/app/client/cypress/locators/Widgets.json +++ b/app/client/cypress/locators/Widgets.json @@ -1,7 +1,7 @@ { "NavHomePage": "[data-icon='home']", "containerWidget": ".t--draggable-containerwidget", - "inputWidget": ".t--draggable-inputwidget", + "inputWidget": ".t--draggable-inputwidgetv2", "togglebutton": "input[type='checkbox']", "inputPropsDataType": ".t--property-control-datatype", "inputdatatypeplaceholder": ".t--property-control-placeholder", @@ -22,13 +22,13 @@ "buttonOnClick": ".t--property-control-onclick .bp3-popover-target", "buttonCreateApi": "a.t--create-api-btn", "Scrollbutton": ".t--property-control-scrollcontents input", - "label": ".t--draggable-inputwidget label", + "label": ".t--draggable-inputwidgetv2 label", "labelColor": ".t--property-control-labelcolor input", - "inputval": ".t--draggable-inputwidget span.t--widget-name", + "inputval": ".t--draggable-inputwidgetv2 span.t--widget-name", "dataclass": "'.bp3-input", "datatype": ".t--property-control-datatype .bp3-popover-target", "rowHeight": ".t--property-control-defaultrowheight .bp3-popover-target", - "innertext": ".t--draggable-inputwidget input", + "innertext": ".t--draggable-inputwidgetv2 input", "defaultinput": ".t--property-control-defaultinput", "requiredjs": ".t--property-control-required input", "visible": ".t--property-control-visible input", @@ -49,7 +49,7 @@ "inputLabelControl": ".t--property-control-label .CodeMirror-code", "inputTextControl": ".t--property-control-text .CodeMirror-code", "inputTooltipControl": ".t--property-control-tooltip .CodeMirror-code", - "inputButtonPos": ".t--draggable-inputwidget button", + "inputButtonPos": ".t--draggable-inputwidgetv2 button", "deleteWidget": ".t--modal-widget>div .t--widget-delete-control", "textbuttonWidget": ".t--draggable-buttonwidget button.bp3-button[type='button']", "textInputval": ".t--draggable-textwidget span.t--widget-name", diff --git a/app/client/cypress/locators/publishWidgetspage.json b/app/client/cypress/locators/publishWidgetspage.json index 34c5fb661d8c..307431df81b2 100644 --- a/app/client/cypress/locators/publishWidgetspage.json +++ b/app/client/cypress/locators/publishWidgetspage.json @@ -4,7 +4,7 @@ "richTextEditorWidget": ".t--widget-richtexteditorwidget", "datepickerWidget": ".t--widget-datepickerwidget", "backToEditor": ".t--back-to-editor", - "inputWidget": ".t--widget-inputwidget", + "inputWidget": ".t--widget-inputwidgetv2", "checkboxWidget": ".t--widget-checkboxwidget", "switchwidget": ".t--widget-switchwidget", "radioWidget": ".t--widget-radiogroupwidget", diff --git a/app/client/cypress/support/Objects/CommonLocators.ts b/app/client/cypress/support/Objects/CommonLocators.ts index 5848d4fa2bee..d5ece3f0bd9b 100644 --- a/app/client/cypress/support/Objects/CommonLocators.ts +++ b/app/client/cypress/support/Objects/CommonLocators.ts @@ -15,7 +15,7 @@ export class CommonLocators { _entityExplorersearch = "#entity-explorer-search" _propertyControl = ".t--property-control-" _textWidget = ".t--draggable-textwidget span" - _inputWidget = ".t--draggable-inputwidget span" + _inputWidget = ".t--draggable-inputwidgetv2 span" _publishButton = ".t--application-publish-btn" _textWidgetInDeployed = ".t--widget-textwidget span" _backToEditor = ".t--back-to-editor" diff --git a/app/client/package.json b/app/client/package.json index 4adf9de5854a..bd19dbb8df46 100644 --- a/app/client/package.json +++ b/app/client/package.json @@ -71,6 +71,7 @@ "js-sha256": "^0.9.0", "jshint": "^2.13.1", "json-fn": "^1.1.1", + "libphonenumber-js": "^1.9.44", "lint-staged": "^9.2.5", "localforage": "^1.7.3", "lodash": "^4.17.21", diff --git a/app/client/src/assets/icons/widget/currencyInput.svg b/app/client/src/assets/icons/widget/currencyInput.svg new file mode 100644 index 000000000000..7da986a9337b --- /dev/null +++ b/app/client/src/assets/icons/widget/currencyInput.svg @@ -0,0 +1,4 @@ +<svg width="20" height="12" viewBox="0 0 20 12" fill="none" xmlns="http://www.w3.org/2000/svg"> +<path fill-rule="evenodd" clip-rule="evenodd" d="M0 0H20V12H0V0ZM2 10V2H18V10H2Z" fill="#4B4848"/> +<path d="M4.5915 5.6705C4.82608 6.08262 5.16738 6.42392 5.5795 6.6585L5.8005 6.349C5.83604 6.29923 5.88859 6.26422 5.9482 6.25058C6.00781 6.23695 6.07036 6.24563 6.124 6.275C6.47758 6.46823 6.86805 6.58444 7.26975 6.616C7.33244 6.62097 7.39096 6.64938 7.43364 6.69558C7.47631 6.74178 7.50001 6.80236 7.5 6.86525V7.98075C7.50001 8.04265 7.47706 8.10235 7.43559 8.1483C7.39412 8.19425 7.33708 8.22319 7.2755 8.2295C7.143 8.24325 7.0095 8.25 6.875 8.25C4.735 8.25 3 6.515 3 4.375C3 4.2405 3.00675 4.107 3.0205 3.9745C3.02681 3.91292 3.05575 3.85588 3.1017 3.81441C3.14765 3.77294 3.20735 3.74999 3.26925 3.75H4.38475C4.44764 3.74999 4.50822 3.77369 4.55442 3.81636C4.60062 3.85904 4.62903 3.91756 4.634 3.98025C4.66556 4.38195 4.78177 4.77242 4.975 5.126C5.00437 5.17964 5.01305 5.24219 4.99942 5.3018C4.98578 5.36141 4.95077 5.41396 4.901 5.4495L4.5915 5.6705ZM3.961 5.50625L4.436 5.167C4.3012 4.87602 4.20884 4.56721 4.16175 4.25H3.5025C3.501 4.2915 3.50025 4.33325 3.50025 4.375C3.5 6.239 5.011 7.75 6.875 7.75C6.91675 7.75 6.9585 7.74925 7 7.7475V7.08825C6.68279 7.04116 6.37398 6.9488 6.083 6.814L5.74375 7.289C5.60717 7.23593 5.4745 7.17327 5.34675 7.1015L5.33225 7.09325C4.84189 6.81418 4.43582 6.40811 4.15675 5.91775L4.1485 5.90325C4.07673 5.7755 4.01407 5.64283 3.961 5.50625Z" fill="#4B4848"/> +</svg> diff --git a/app/client/src/assets/icons/widget/phoneInput.svg b/app/client/src/assets/icons/widget/phoneInput.svg new file mode 100644 index 000000000000..189182612aac --- /dev/null +++ b/app/client/src/assets/icons/widget/phoneInput.svg @@ -0,0 +1,4 @@ +<svg width="20" height="12" viewBox="0 0 20 12" fill="none" xmlns="http://www.w3.org/2000/svg"> +<path fill-rule="evenodd" clip-rule="evenodd" d="M0 0H20V12H0V0ZM2 10V2H18V10H2Z" fill="#4B4848"/> +<path d="M4.81348 8.41895H5.15625V7.93262C5.93555 7.87695 6.52441 7.46094 6.52441 6.74023V6.73438C6.52441 6.10156 6.10254 5.78516 5.32031 5.60352L5.15625 5.56543V4.42871C5.50781 4.47852 5.75098 4.68652 5.78906 5.0293L5.79199 5.03516L6.47168 5.03223V5.0293C6.44531 4.3584 5.91797 3.90137 5.15625 3.83984V3.34766H4.81348V3.83984C4.04883 3.89258 3.50098 4.3291 3.50098 5V5.00586C3.50098 5.61523 3.91113 5.95508 4.66406 6.12793L4.81348 6.16309V7.34668C4.37402 7.2998 4.15723 7.07129 4.10742 6.75195L4.10449 6.74609L3.4248 6.74902L3.42188 6.75195C3.44531 7.46094 4.03711 7.88281 4.81348 7.93262V8.41895ZM4.20703 4.95312V4.94727C4.20703 4.69531 4.41504 4.47559 4.81348 4.42871V5.48633C4.37988 5.37207 4.20703 5.19922 4.20703 4.95312ZM5.81836 6.80469V6.81055C5.81836 7.10059 5.61328 7.30859 5.15625 7.34668V6.24219C5.65723 6.36816 5.81836 6.52637 5.81836 6.80469Z" fill="#4B4848"/> +</svg> diff --git a/app/client/src/components/editorComponents/ActionRightPane/SuggestedWidgets.tsx b/app/client/src/components/editorComponents/ActionRightPane/SuggestedWidgets.tsx index 4def57cfd7b2..9e0eaf7fe0a8 100644 --- a/app/client/src/components/editorComponents/ActionRightPane/SuggestedWidgets.tsx +++ b/app/client/src/components/editorComponents/ActionRightPane/SuggestedWidgets.tsx @@ -98,7 +98,7 @@ export const WIDGET_DATA_FIELD_MAP: Record<string, WidgetBindingInfo> = { image: "https://s3.us-east-2.amazonaws.com/assets.appsmith.com/widgetSuggestion/text.svg", }, - INPUT_WIDGET: { + INPUT_WIDGET_V2: { label: "text", propertyName: "defaultText", widgetName: "Input", diff --git a/app/client/src/constants/HelpConstants.ts b/app/client/src/constants/HelpConstants.ts index 74527dadb607..62288c0b8927 100644 --- a/app/client/src/constants/HelpConstants.ts +++ b/app/client/src/constants/HelpConstants.ts @@ -27,6 +27,10 @@ export const HelpMap: Record<string, { path: string; searchKey: string }> = { path: "/widget-reference/input", searchKey: "Input", }, + INPUT_WIDGET_V2: { + path: "/widget-reference/input", + searchKey: "Input", + }, DATE_PICKER_WIDGET: { path: "/widget-reference/datepicker", searchKey: "DatePicker", diff --git a/app/client/src/constants/ISDCodes_v2.tsx b/app/client/src/constants/ISDCodes_v2.tsx new file mode 100644 index 000000000000..aa17e8313bd6 --- /dev/null +++ b/app/client/src/constants/ISDCodes_v2.tsx @@ -0,0 +1,1213 @@ +export interface ISDCodeProps { + code: string; + name: string; + dial_code: string; +} + +export const ISDCodeOptions: Array<ISDCodeProps> = [ + { + name: "Afghanistan", + dial_code: "+93", + code: "AF", + }, + { + name: "Aland Islands", + dial_code: "+358", + code: "AX", + }, + { + name: "Albania", + dial_code: "+355", + code: "AL", + }, + { + name: "Algeria", + dial_code: "+213", + code: "DZ", + }, + { + name: "AmericanSamoa", + dial_code: "+1684", + code: "AS", + }, + { + name: "Andorra", + dial_code: "+376", + code: "AD", + }, + { + name: "Angola", + dial_code: "+244", + code: "AO", + }, + { + name: "Anguilla", + dial_code: "+1264", + code: "AI", + }, + { + name: "Antarctica", + dial_code: "+672", + code: "AQ", + }, + { + name: "Antigua and Barbuda", + dial_code: "+1268", + code: "AG", + }, + { + name: "Argentina", + dial_code: "+54", + code: "AR", + }, + { + name: "Armenia", + dial_code: "+374", + code: "AM", + }, + { + name: "Aruba", + dial_code: "+297", + code: "AW", + }, + { + name: "Australia", + dial_code: "+61", + code: "AU", + }, + { + name: "Austria", + dial_code: "+43", + code: "AT", + }, + { + name: "Azerbaijan", + dial_code: "+994", + code: "AZ", + }, + { + name: "Bahamas", + dial_code: "+1242", + code: "BS", + }, + { + name: "Bahrain", + dial_code: "+973", + code: "BH", + }, + { + name: "Bangladesh", + dial_code: "+880", + code: "BD", + }, + { + name: "Barbados", + dial_code: "+1246", + code: "BB", + }, + { + name: "Belarus", + dial_code: "+375", + code: "BY", + }, + { + name: "Belgium", + dial_code: "+32", + code: "BE", + }, + { + name: "Belize", + dial_code: "+501", + code: "BZ", + }, + { + name: "Benin", + dial_code: "+229", + code: "BJ", + }, + { + name: "Bermuda", + dial_code: "+1441", + code: "BM", + }, + { + name: "Bhutan", + dial_code: "+975", + code: "BT", + }, + { + name: "Bolivia, Plurinational State of", + dial_code: "+591", + code: "BO", + }, + { + name: "Bosnia and Herzegovina", + dial_code: "+387", + code: "BA", + }, + { + name: "Botswana", + dial_code: "+267", + code: "BW", + }, + { + name: "Brazil", + dial_code: "+55", + code: "BR", + }, + { + name: "British Indian Ocean Territory", + dial_code: "+246", + code: "IO", + }, + { + name: "Brunei Darussalam", + dial_code: "+673", + code: "BN", + }, + { + name: "Bulgaria", + dial_code: "+359", + code: "BG", + }, + { + name: "Burkina Faso", + dial_code: "+226", + code: "BF", + }, + { + name: "Burundi", + dial_code: "+257", + code: "BI", + }, + { + name: "Cambodia", + dial_code: "+855", + code: "KH", + }, + { + name: "Cameroon", + dial_code: "+237", + code: "CM", + }, + { + name: "Cape Verde", + dial_code: "+238", + code: "CV", + }, + { + name: "Cayman Islands", + dial_code: "+ 345", + code: "KY", + }, + { + name: "Central African Republic", + dial_code: "+236", + code: "CF", + }, + { + name: "Chad", + dial_code: "+235", + code: "TD", + }, + { + name: "Chile", + dial_code: "+56", + code: "CL", + }, + { + name: "China", + dial_code: "+86", + code: "CN", + }, + { + name: "Christmas Island", + dial_code: "+61", + code: "CX", + }, + { + name: "Cocos (Keeling) Islands", + dial_code: "+61", + code: "CC", + }, + { + name: "Colombia", + dial_code: "+57", + code: "CO", + }, + { + name: "Comoros", + dial_code: "+269", + code: "KM", + }, + { + name: "Congo", + dial_code: "+242", + code: "CG", + }, + { + name: "Congo, The Democratic Republic of the Congo", + dial_code: "+243", + code: "CD", + }, + { + name: "Cook Islands", + dial_code: "+682", + code: "CK", + }, + { + name: "Costa Rica", + dial_code: "+506", + code: "CR", + }, + { + name: "Cote d'Ivoire", + dial_code: "+225", + code: "CI", + }, + { + name: "Croatia", + dial_code: "+385", + code: "HR", + }, + { + name: "Cuba", + dial_code: "+53", + code: "CU", + }, + { + name: "Cyprus", + dial_code: "+357", + code: "CY", + }, + { + name: "Czech Republic", + dial_code: "+420", + code: "CZ", + }, + { + name: "Denmark", + dial_code: "+45", + code: "DK", + }, + { + name: "Djibouti", + dial_code: "+253", + code: "DJ", + }, + { + name: "Dominica", + dial_code: "+1767", + code: "DM", + }, + { + name: "Dominican Republic", + dial_code: "+1849", + code: "DO", + }, + { + name: "Ecuador", + dial_code: "+593", + code: "EC", + }, + { + name: "Egypt", + dial_code: "+20", + code: "EG", + }, + { + name: "El Salvador", + dial_code: "+503", + code: "SV", + }, + { + name: "Equatorial Guinea", + dial_code: "+240", + code: "GQ", + }, + { + name: "Eritrea", + dial_code: "+291", + code: "ER", + }, + { + name: "Estonia", + dial_code: "+372", + code: "EE", + }, + { + name: "Ethiopia", + dial_code: "+251", + code: "ET", + }, + { + name: "Falkland Islands (Malvinas)", + dial_code: "+500", + code: "FK", + }, + { + name: "Faroe Islands", + dial_code: "+298", + code: "FO", + }, + { + name: "Fiji", + dial_code: "+679", + code: "FJ", + }, + { + name: "Finland", + dial_code: "+358", + code: "FI", + }, + { + name: "France", + dial_code: "+33", + code: "FR", + }, + { + name: "French Guiana", + dial_code: "+594", + code: "GF", + }, + { + name: "French Polynesia", + dial_code: "+689", + code: "PF", + }, + { + name: "Gabon", + dial_code: "+241", + code: "GA", + }, + { + name: "Gambia", + dial_code: "+220", + code: "GM", + }, + { + name: "Georgia", + dial_code: "+995", + code: "GE", + }, + { + name: "Germany", + dial_code: "+49", + code: "DE", + }, + { + name: "Ghana", + dial_code: "+233", + code: "GH", + }, + { + name: "Gibraltar", + dial_code: "+350", + code: "GI", + }, + { + name: "Greece", + dial_code: "+30", + code: "GR", + }, + { + name: "Greenland", + dial_code: "+299", + code: "GL", + }, + { + name: "Grenada", + dial_code: "+1473", + code: "GD", + }, + { + name: "Guadeloupe", + dial_code: "+590", + code: "GP", + }, + { + name: "Guam", + dial_code: "+1671", + code: "GU", + }, + { + name: "Guatemala", + dial_code: "+502", + code: "GT", + }, + { + name: "Guernsey", + dial_code: "+44", + code: "GG", + }, + { + name: "Guinea", + dial_code: "+224", + code: "GN", + }, + { + name: "Guinea-Bissau", + dial_code: "+245", + code: "GW", + }, + { + name: "Guyana", + dial_code: "+595", + code: "GY", + }, + { + name: "Haiti", + dial_code: "+509", + code: "HT", + }, + { + name: "Holy See (Vatican City State)", + dial_code: "+379", + code: "VA", + }, + { + name: "Honduras", + dial_code: "+504", + code: "HN", + }, + { + name: "Hong Kong", + dial_code: "+852", + code: "HK", + }, + { + name: "Hungary", + dial_code: "+36", + code: "HU", + }, + { + name: "Iceland", + dial_code: "+354", + code: "IS", + }, + { + name: "India", + dial_code: "+91", + code: "IN", + }, + { + name: "Indonesia", + dial_code: "+62", + code: "ID", + }, + { + name: "Iran, Islamic Republic of Persian Gulf", + dial_code: "+98", + code: "IR", + }, + { + name: "Iraq", + dial_code: "+964", + code: "IQ", + }, + { + name: "Ireland", + dial_code: "+353", + code: "IE", + }, + { + name: "Isle of Man", + dial_code: "+44", + code: "IM", + }, + { + name: "Israel", + dial_code: "+972", + code: "IL", + }, + { + name: "Italy", + dial_code: "+39", + code: "IT", + }, + { + name: "Jamaica", + dial_code: "+1876", + code: "JM", + }, + { + name: "Japan", + dial_code: "+81", + code: "JP", + }, + { + name: "Jersey", + dial_code: "+44", + code: "JE", + }, + { + name: "Jordan", + dial_code: "+962", + code: "JO", + }, + { + name: "Kazakhstan", + dial_code: "+77", + code: "KZ", + }, + { + name: "Kenya", + dial_code: "+254", + code: "KE", + }, + { + name: "Kiribati", + dial_code: "+686", + code: "KI", + }, + { + name: "Korea, Democratic People's Republic of Korea", + dial_code: "+850", + code: "KP", + }, + { + name: "Korea, Republic of South Korea", + dial_code: "+82", + code: "KR", + }, + { + name: "Kuwait", + dial_code: "+965", + code: "KW", + }, + { + name: "Kyrgyzstan", + dial_code: "+996", + code: "KG", + }, + { + name: "Laos", + dial_code: "+856", + code: "LA", + }, + { + name: "Latvia", + dial_code: "+371", + code: "LV", + }, + { + name: "Lebanon", + dial_code: "+961", + code: "LB", + }, + { + name: "Lesotho", + dial_code: "+266", + code: "LS", + }, + { + name: "Liberia", + dial_code: "+231", + code: "LR", + }, + { + name: "Libyan Arab Jamahiriya", + dial_code: "+218", + code: "LY", + }, + { + name: "Liechtenstein", + dial_code: "+423", + code: "LI", + }, + { + name: "Lithuania", + dial_code: "+370", + code: "LT", + }, + { + name: "Luxembourg", + dial_code: "+352", + code: "LU", + }, + { + name: "Macao", + dial_code: "+853", + code: "MO", + }, + { + name: "Macedonia", + dial_code: "+389", + code: "MK", + }, + { + name: "Madagascar", + dial_code: "+261", + code: "MG", + }, + { + name: "Malawi", + dial_code: "+265", + code: "MW", + }, + { + name: "Malaysia", + dial_code: "+60", + code: "MY", + }, + { + name: "Maldives", + dial_code: "+960", + code: "MV", + }, + { + name: "Mali", + dial_code: "+223", + code: "ML", + }, + { + name: "Malta", + dial_code: "+356", + code: "MT", + }, + { + name: "Marshall Islands", + dial_code: "+692", + code: "MH", + }, + { + name: "Martinique", + dial_code: "+596", + code: "MQ", + }, + { + name: "Mauritania", + dial_code: "+222", + code: "MR", + }, + { + name: "Mauritius", + dial_code: "+230", + code: "MU", + }, + { + name: "Mayotte", + dial_code: "+262", + code: "YT", + }, + { + name: "Mexico", + dial_code: "+52", + code: "MX", + }, + { + name: "Micronesia, Federated States of Micronesia", + dial_code: "+691", + code: "FM", + }, + { + name: "Moldova", + dial_code: "+373", + code: "MD", + }, + { + name: "Monaco", + dial_code: "+377", + code: "MC", + }, + { + name: "Mongolia", + dial_code: "+976", + code: "MN", + }, + { + name: "Montenegro", + dial_code: "+382", + code: "ME", + }, + { + name: "Montserrat", + dial_code: "+1664", + code: "MS", + }, + { + name: "Morocco", + dial_code: "+212", + code: "MA", + }, + { + name: "Mozambique", + dial_code: "+258", + code: "MZ", + }, + { + name: "Myanmar", + dial_code: "+95", + code: "MM", + }, + { + name: "Namibia", + dial_code: "+264", + code: "NA", + }, + { + name: "Nauru", + dial_code: "+674", + code: "NR", + }, + { + name: "Nepal", + dial_code: "+977", + code: "NP", + }, + { + name: "Netherlands", + dial_code: "+31", + code: "NL", + }, + { + name: "Netherlands Antilles", + dial_code: "+599", + code: "AN", + }, + { + name: "New Caledonia", + dial_code: "+687", + code: "NC", + }, + { + name: "New Zealand", + dial_code: "+64", + code: "NZ", + }, + { + name: "Nicaragua", + dial_code: "+505", + code: "NI", + }, + { + name: "Niger", + dial_code: "+227", + code: "NE", + }, + { + name: "Nigeria", + dial_code: "+234", + code: "NG", + }, + { + name: "Niue", + dial_code: "+683", + code: "NU", + }, + { + name: "Norfolk Island", + dial_code: "+672", + code: "NF", + }, + { + name: "Northern Mariana Islands", + dial_code: "+1670", + code: "MP", + }, + { + name: "Norway", + dial_code: "+47", + code: "NO", + }, + { + name: "Oman", + dial_code: "+968", + code: "OM", + }, + { + name: "Pakistan", + dial_code: "+92", + code: "PK", + }, + { + name: "Palau", + dial_code: "+680", + code: "PW", + }, + { + name: "Palestinian Territory, Occupied", + dial_code: "+970", + code: "PS", + }, + { + name: "Panama", + dial_code: "+507", + code: "PA", + }, + { + name: "Papua New Guinea", + dial_code: "+675", + code: "PG", + }, + { + name: "Paraguay", + dial_code: "+595", + code: "PY", + }, + { + name: "Peru", + dial_code: "+51", + code: "PE", + }, + { + name: "Philippines", + dial_code: "+63", + code: "PH", + }, + { + name: "Pitcairn", + dial_code: "+872", + code: "PN", + }, + { + name: "Poland", + dial_code: "+48", + code: "PL", + }, + { + name: "Portugal", + dial_code: "+351", + code: "PT", + }, + { + name: "Puerto Rico", + dial_code: "+1939", + code: "PR", + }, + { + name: "Qatar", + dial_code: "+974", + code: "QA", + }, + { + name: "Romania", + dial_code: "+40", + code: "RO", + }, + { + name: "Russia", + dial_code: "+7", + code: "RU", + }, + { + name: "Rwanda", + dial_code: "+250", + code: "RW", + }, + { + name: "Reunion", + dial_code: "+262", + code: "RE", + }, + { + name: "Saint Barthelemy", + dial_code: "+590", + code: "BL", + }, + { + name: "Saint Helena, Ascension and Tristan Da Cunha", + dial_code: "+290", + code: "SH", + }, + { + name: "Saint Kitts and Nevis", + dial_code: "+1869", + code: "KN", + }, + { + name: "Saint Lucia", + dial_code: "+1758", + code: "LC", + }, + { + name: "Saint Martin", + dial_code: "+590", + code: "MF", + }, + { + name: "Saint Pierre and Miquelon", + dial_code: "+508", + code: "PM", + }, + { + name: "Saint Vincent and the Grenadines", + dial_code: "+1784", + code: "VC", + }, + { + name: "Samoa", + dial_code: "+685", + code: "WS", + }, + { + name: "San Marino", + dial_code: "+378", + code: "SM", + }, + { + name: "Sao Tome and Principe", + dial_code: "+239", + code: "ST", + }, + { + name: "Saudi Arabia", + dial_code: "+966", + code: "SA", + }, + { + name: "Senegal", + dial_code: "+221", + code: "SN", + }, + { + name: "Serbia", + dial_code: "+381", + code: "RS", + }, + { + name: "Seychelles", + dial_code: "+248", + code: "SC", + }, + { + name: "Sierra Leone", + dial_code: "+232", + code: "SL", + }, + { + name: "Singapore", + dial_code: "+65", + code: "SG", + }, + { + name: "Slovakia", + dial_code: "+421", + code: "SK", + }, + { + name: "Slovenia", + dial_code: "+386", + code: "SI", + }, + { + name: "Solomon Islands", + dial_code: "+677", + code: "SB", + }, + { + name: "Somalia", + dial_code: "+252", + code: "SO", + }, + { + name: "South Africa", + dial_code: "+27", + code: "ZA", + }, + { + name: "South Sudan", + dial_code: "+211", + code: "SS", + }, + { + name: "South Georgia and the South Sandwich Islands", + dial_code: "+500", + code: "GS", + }, + { + name: "Spain", + dial_code: "+34", + code: "ES", + }, + { + name: "Sri Lanka", + dial_code: "+94", + code: "LK", + }, + { + name: "Sudan", + dial_code: "+249", + code: "SD", + }, + { + name: "Suriname", + dial_code: "+597", + code: "SR", + }, + { + name: "Svalbard and Jan Mayen", + dial_code: "+47", + code: "SJ", + }, + { + name: "Swaziland", + dial_code: "+268", + code: "SZ", + }, + { + name: "Sweden", + dial_code: "+46", + code: "SE", + }, + { + name: "Switzerland", + dial_code: "+41", + code: "CH", + }, + { + name: "Syrian Arab Republic", + dial_code: "+963", + code: "SY", + }, + { + name: "Taiwan", + dial_code: "+886", + code: "TW", + }, + { + name: "Tajikistan", + dial_code: "+992", + code: "TJ", + }, + { + name: "Tanzania, United Republic of Tanzania", + dial_code: "+255", + code: "TZ", + }, + { + name: "Thailand", + dial_code: "+66", + code: "TH", + }, + { + name: "Timor-Leste", + dial_code: "+670", + code: "TL", + }, + { + name: "Togo", + dial_code: "+228", + code: "TG", + }, + { + name: "Tokelau", + dial_code: "+690", + code: "TK", + }, + { + name: "Tonga", + dial_code: "+676", + code: "TO", + }, + { + name: "Trinidad and Tobago", + dial_code: "+1868", + code: "TT", + }, + { + name: "Tunisia", + dial_code: "+216", + code: "TN", + }, + { + name: "Turkey", + dial_code: "+90", + code: "TR", + }, + { + name: "Turkmenistan", + dial_code: "+993", + code: "TM", + }, + { + name: "Turks and Caicos Islands", + dial_code: "+1649", + code: "TC", + }, + { + name: "Tuvalu", + dial_code: "+688", + code: "TV", + }, + { + name: "Uganda", + dial_code: "+256", + code: "UG", + }, + { + name: "Ukraine", + dial_code: "+380", + code: "UA", + }, + { + name: "United Arab Emirates", + dial_code: "+971", + code: "AE", + }, + { + name: "United Kingdom", + dial_code: "+44", + code: "GB", + }, + { + name: "United States / Canada", + dial_code: "+1", + code: "US", + }, + { + name: "Uruguay", + dial_code: "+598", + code: "UY", + }, + { + name: "Uzbekistan", + dial_code: "+998", + code: "UZ", + }, + { + name: "Vanuatu", + dial_code: "+678", + code: "VU", + }, + { + name: "Venezuela, Bolivarian Republic of Venezuela", + dial_code: "+58", + code: "VE", + }, + { + name: "Vietnam", + dial_code: "+84", + code: "VN", + }, + { + name: "Virgin Islands, British", + dial_code: "+1284", + code: "VG", + }, + { + name: "Virgin Islands, U.S.", + dial_code: "+1340", + code: "VI", + }, + { + name: "Wallis and Futuna", + dial_code: "+681", + code: "WF", + }, + { + name: "Yemen", + dial_code: "+967", + code: "YE", + }, + { + name: "Zambia", + dial_code: "+260", + code: "ZM", + }, + { + name: "Zimbabwe", + dial_code: "+263", + code: "ZW", + }, +]; diff --git a/app/client/src/entities/DataTree/dataTreeWidget.test.ts b/app/client/src/entities/DataTree/dataTreeWidget.test.ts index 325383b543de..48ccaf1d76b6 100644 --- a/app/client/src/entities/DataTree/dataTreeWidget.test.ts +++ b/app/client/src/entities/DataTree/dataTreeWidget.test.ts @@ -164,7 +164,7 @@ describe("generateDataTreeWidget", () => { renderMode: RenderModes.CANVAS, rightColumn: 0, topRow: 0, - type: "INPUT_WIDGET", + type: "INPUT_WIDGET_V2", version: 0, widgetId: "123", widgetName: "Input1", @@ -241,7 +241,7 @@ describe("generateDataTreeWidget", () => { renderMode: RenderModes.CANVAS, rightColumn: 0, topRow: 0, - type: "INPUT_WIDGET", + type: "INPUT_WIDGET_V2", version: 0, widgetId: "123", widgetName: "Input1", diff --git a/app/client/src/icons/WidgetIcons.tsx b/app/client/src/icons/WidgetIcons.tsx index 2ddce3b51d00..f98d34fc81a2 100644 --- a/app/client/src/icons/WidgetIcons.tsx +++ b/app/client/src/icons/WidgetIcons.tsx @@ -41,6 +41,8 @@ import { ReactComponent as ProgressBarIcon } from "assets/icons/widget/progressb import { ReactComponent as SwitchGroupIcon } from "assets/icons/widget/switch-group.svg"; import { ReactComponent as CameraIcon } from "assets/icons/widget/camera.svg"; import { ReactComponent as MapChartIcon } from "assets/icons/widget/map-chart.svg"; +import { ReactComponent as PhoneInput } from "assets/icons/widget/phoneInput.svg"; +import { ReactComponent as CurrencyInput } from "assets/icons/widget/currencyInput.svg"; /* eslint-disable react/display-name */ @@ -115,6 +117,11 @@ export const WidgetIcons: { <InputIcon /> </StyledIconWrapper> ), + INPUT_WIDGET_V2: (props: IconProps) => ( + <StyledIconWrapper {...props}> + <InputIcon /> + </StyledIconWrapper> + ), RICH_TEXT_EDITOR_WIDGET: (props: IconProps) => ( <StyledIconWrapper {...props}> <RichTextEditorIcon /> @@ -250,6 +257,16 @@ export const WidgetIcons: { <MapChartIcon /> </StyledIconWrapper> ), + PHONE_INPUT_WIDGET: (props: IconProps) => ( + <StyledIconWrapper {...props}> + <PhoneInput /> + </StyledIconWrapper> + ), + CURRENCY_INPUT_WIDGET: (props: IconProps) => ( + <StyledIconWrapper {...props}> + <CurrencyInput /> + </StyledIconWrapper> + ), }; export type WidgetIcon = typeof WidgetIcons[keyof typeof WidgetIcons]; diff --git a/app/client/src/pages/Editor/MainContainer.test.tsx b/app/client/src/pages/Editor/MainContainer.test.tsx index 54e6c15b4595..0d9d1f4e75a2 100644 --- a/app/client/src/pages/Editor/MainContainer.test.tsx +++ b/app/client/src/pages/Editor/MainContainer.test.tsx @@ -28,7 +28,7 @@ const renderNestedComponent = () => { const children: any = buildChildren([ { - type: "INPUT_WIDGET", + type: "INPUT_WIDGET_V2", dragDisabled: true, leftColumn: 0, topRow: 1, @@ -908,10 +908,10 @@ describe("Drag in a nested container", () => { const component = renderNestedComponent(); const inputWidget: any = component.container.querySelector( - ".t--widget-inputwidget", + ".t--widget-inputwidgetv2", ); const draggableInputWidget: any = component.container.querySelector( - ".t--draggable-inputwidget", + ".t--draggable-inputwidgetv2", ); const draggableContainerWidget: any = component.container.querySelector( ".t--draggable-containerwidget", @@ -975,7 +975,7 @@ describe("Drag in a nested container", () => { } const movedInputWidget: any = component.container.querySelector( - ".t--widget-inputwidget", + ".t--widget-inputwidgetv2", ); const finalInputWidgetPositions = { left: movedInputWidget.style.left, diff --git a/app/client/src/pages/Editor/WidgetSidebar.tsx b/app/client/src/pages/Editor/WidgetSidebar.tsx index 43ca26411980..4e1518512ef6 100644 --- a/app/client/src/pages/Editor/WidgetSidebar.tsx +++ b/app/client/src/pages/Editor/WidgetSidebar.tsx @@ -99,7 +99,7 @@ function WidgetSidebar(props: IPanelProps) { key={card.key} show={ (card.type === "TABLE_WIDGET" && showTableWidget) || - (card.type === "INPUT_WIDGET" && showInputWidget) + (card.type === "INPUT_WIDGET_V2" && showInputWidget) } step={OnboardingStep.DEPLOY} > @@ -109,7 +109,7 @@ function WidgetSidebar(props: IPanelProps) { show={ (card.type === "TABLE_WIDGET" && currentStep === OnboardingStep.RUN_QUERY_SUCCESS) || - (card.type === "INPUT_WIDGET" && + (card.type === "INPUT_WIDGET_V2" && currentSubStep === 0 && currentStep === OnboardingStep.ADD_INPUT_WIDGET) } diff --git a/app/client/src/reducers/uiReducers/pageWidgetsReducer.test.ts b/app/client/src/reducers/uiReducers/pageWidgetsReducer.test.ts index fdbcd4fc8bc0..ca13d8ac6f99 100644 --- a/app/client/src/reducers/uiReducers/pageWidgetsReducer.test.ts +++ b/app/client/src/reducers/uiReducers/pageWidgetsReducer.test.ts @@ -141,7 +141,7 @@ const pageWidgetUIInitialState = { version: 1, resetOnSubmit: true, placeholderText: "Type your update and hit enter!", - type: "INPUT_WIDGET", + type: "INPUT_WIDGET_V2", isLoading: false, leftColumn: 5, rightColumn: 11, diff --git a/app/client/src/sagas/OnboardingSagas.ts b/app/client/src/sagas/OnboardingSagas.ts index 760dfe1363a9..90f284fd0a5d 100644 --- a/app/client/src/sagas/OnboardingSagas.ts +++ b/app/client/src/sagas/OnboardingSagas.ts @@ -216,7 +216,7 @@ function* listenForAddInputWidget() { const widgets = yield select(getWidgets); const inputWidget: any = Object.values(widgets).find( - (widget: any) => widget.type === "INPUT_WIDGET", + (widget: any) => widget.type === "INPUT_WIDGET_V2", ); const isOnBuilder = matchBuilderPath(window.location.pathname); @@ -230,7 +230,7 @@ function* listenForAddInputWidget() { if ( inputWidget && - inputWidget.type === "INPUT_WIDGET" && + inputWidget.type === "INPUT_WIDGET_V2" && canvasWidgets[inputWidget.widgetId] ) { if (!isOnBuilder) { @@ -777,7 +777,7 @@ function* addTableWidget() { function* addInputWidget() { yield call(addWidget, { - type: WidgetTypes.INPUT_WIDGET, + type: WidgetTypes.INPUT_WIDGET_V2, widgetName: "Standup_Input", ...getStandupInputDimensions(), props: getStandupInputProps(), @@ -815,7 +815,7 @@ function* addOnSubmitHandler() { const widgets = yield select(getWidgets); const inputWidget: any = Object.values(widgets).find( - (widget: any) => widget.type === "INPUT_WIDGET", + (widget: any) => widget.type === "INPUT_WIDGET_V2", ); if (inputWidget) { diff --git a/app/client/src/sagas/SnipingModeSagas.ts b/app/client/src/sagas/SnipingModeSagas.ts index b3a575ac7b76..1fb9bb51854e 100644 --- a/app/client/src/sagas/SnipingModeSagas.ts +++ b/app/client/src/sagas/SnipingModeSagas.ts @@ -82,6 +82,10 @@ export function* bindDataToWidgetSaga( propertyPath = "defaultText"; propertyValue = `{{${currentAction.config.name}.data}}`; break; + case WidgetTypes.INPUT_WIDGET_V2: + propertyPath = "defaultText"; + propertyValue = `{{${currentAction.config.name}.data}}`; + break; case WidgetTypes.LIST_WIDGET: propertyPath = "items"; propertyValue = `{{${currentAction.config.name}.data}}`; diff --git a/app/client/src/utils/WidgetRegistry.tsx b/app/client/src/utils/WidgetRegistry.tsx index 60e3d2467d5e..3bfdb9e6246c 100644 --- a/app/client/src/utils/WidgetRegistry.tsx +++ b/app/client/src/utils/WidgetRegistry.tsx @@ -114,6 +114,16 @@ import ProgressBarWidget, { import SwitchGroupWidget, { CONFIG as SWITCH_GROUP_WIDGET_CONFIG, } from "widgets/SwitchGroupWidget"; +import InputWidgetV2, { + CONFIG as INPUT_WIDGET_V2_CONFIG, +} from "widgets/InputWidgetV2"; +import PhoneInputWidget, { + CONFIG as PHONE_INPUT_WIDGET_V2_CONFIG, +} from "widgets/PhoneInputWidget"; +import CurrencyInputWidget, { + CONFIG as CURRENCY_INPUT_WIDGET_V2_CONFIG, +} from "widgets/CurrencyInputWidget"; + import CameraWidget, { CONFIG as CAMERA_WIDGET_CONFIG, } from "widgets/CameraWidget"; @@ -169,6 +179,9 @@ export const ALL_WDIGETS_AND_CONFIG = [ [ProgressBarWidget, PROGRESSBAR_WIDGET_CONFIG], [CameraWidget, CAMERA_WIDGET_CONFIG], [MapChartWidget, MAP_CHART_WIDGET_CONFIG], + [InputWidgetV2, INPUT_WIDGET_V2_CONFIG], + [PhoneInputWidget, PHONE_INPUT_WIDGET_V2_CONFIG], + [CurrencyInputWidget, CURRENCY_INPUT_WIDGET_V2_CONFIG], ]; export const registerWidgets = () => { diff --git a/app/client/src/utils/autocomplete/EntityDefinitions.test.ts b/app/client/src/utils/autocomplete/EntityDefinitions.test.ts index 67b2ebf802cb..1870ee4d5e68 100644 --- a/app/client/src/utils/autocomplete/EntityDefinitions.test.ts +++ b/app/client/src/utils/autocomplete/EntityDefinitions.test.ts @@ -8,7 +8,7 @@ describe("EntityDefinitions", () => { parentId: "123", renderMode: "CANVAS", text: "yo", - type: "INPUT_WIDGET", + type: "INPUT_WIDGET_V2", parentColumnSpace: 1, parentRowSpace: 2, leftColumn: 2, diff --git a/app/client/src/utils/autocomplete/EntityDefinitions.ts b/app/client/src/utils/autocomplete/EntityDefinitions.ts index 6d2229939c6f..720f018dc1ac 100644 --- a/app/client/src/utils/autocomplete/EntityDefinitions.ts +++ b/app/client/src/utils/autocomplete/EntityDefinitions.ts @@ -456,6 +456,66 @@ export const entityDefinitions: Record<string, unknown> = { isVisible: isVisible, selectedDataPoint: "mapChartDataPoint", }, + INPUT_WIDGET_V2: { + "!doc": + "An input text field is used to capture a users textual input such as their names, numbers, emails etc. Inputs are used in forms and can have custom validations.", + "!url": "https://docs.appsmith.com/widget-reference/input", + text: { + "!type": "string", + "!doc": "The text value of the input", + "!url": "https://docs.appsmith.com/widget-reference/input", + }, + isValid: "bool", + isVisible: isVisible, + isDisabled: "bool", + }, + CURRENCY_INPUT_WIDGET: { + "!doc": + "An input text field is used to capture a currency value. Inputs are used in forms and can have custom validations.", + "!url": "https://docs.appsmith.com/widget-reference/input", + text: { + "!type": "string", + "!doc": "The formatted text value of the input", + "!url": "https://docs.appsmith.com/widget-reference/input", + }, + value: { + "!type": "number", + "!doc": "The value of the input", + "!url": "https://docs.appsmith.com/widget-reference/input", + }, + isValid: "bool", + isVisible: isVisible, + isDisabled: "bool", + countryCode: { + "!type": "string", + "!doc": "Selected country code for Currency", + }, + currencyCode: { + "!type": "string", + "!doc": "Selected Currency code", + }, + }, + PHONE_INPUT_WIDGET: { + "!doc": + "An input text field is used to capture a phone number. Inputs are used in forms and can have custom validations.", + "!url": "https://docs.appsmith.com/widget-reference/input", + text: { + "!type": "string", + "!doc": "The text value of the input", + "!url": "https://docs.appsmith.com/widget-reference/input", + }, + isValid: "bool", + isVisible: isVisible, + isDisabled: "bool", + countryCode: { + "!type": "string", + "!doc": "Selected country code for Phone Number", + }, + dialCode: { + "!type": "string", + "!doc": "Selected dialing code for Phone Number", + }, + }, }; export const GLOBAL_DEFS = { diff --git a/app/client/src/utils/autocomplete/dataTreeTypeDefCreator.test.ts b/app/client/src/utils/autocomplete/dataTreeTypeDefCreator.test.ts index 449d4f679797..ba648195bdea 100644 --- a/app/client/src/utils/autocomplete/dataTreeTypeDefCreator.test.ts +++ b/app/client/src/utils/autocomplete/dataTreeTypeDefCreator.test.ts @@ -18,7 +18,7 @@ describe("dataTreeTypeDefCreator", () => { parentId: "123", renderMode: "CANVAS", text: "yo", - type: "INPUT_WIDGET", + type: "INPUT_WIDGET_V2", ENTITY_TYPE: ENTITY_TYPE.WIDGET, parentColumnSpace: 1, parentRowSpace: 2, @@ -43,11 +43,11 @@ describe("dataTreeTypeDefCreator", () => { // 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).toBe(entityDefinitions.INPUT_WIDGET); + expect(def.Input1).toBe(entityDefinitions.INPUT_WIDGET_V2); expect(def).toHaveProperty("Input1.isDisabled"); expect(entityInfo.get("Input1")).toStrictEqual({ type: ENTITY_TYPE.WIDGET, - subType: "INPUT_WIDGET", + subType: "INPUT_WIDGET_V2", }); }); diff --git a/app/client/src/utils/autocomplete/dataTypeSortRules.ts b/app/client/src/utils/autocomplete/dataTypeSortRules.ts index 9573f10af9d8..2d0d4cfbe771 100644 --- a/app/client/src/utils/autocomplete/dataTypeSortRules.ts +++ b/app/client/src/utils/autocomplete/dataTypeSortRules.ts @@ -2,7 +2,13 @@ import { AutocompleteDataType } from "utils/autocomplete/TernServer"; const RULES: Record<AutocompleteDataType, Array<string>> = { STRING: [ - "INPUT_WIDGET.text", + "INPUT_WIDGET_V2.text", + "PHONE_INPUT_WIDGET.text", + "PHONE_INPUT_WIDGET.countryCode", + "PHONE_INPUT_WIDGET.currencyCode", + "CURRENCY_INPUT_WIDGET.text", + "CURRENCY_INPUT_WIDGET.countryCode", + "CURRENCY_INPUT_WIDGET.dialCode", "RICH_TEXT_EDITOR_WIDGET.text", "DROP_DOWN_WIDGET.selectedOptionValue", "DATE_PICKER_WIDGET_2.selectedDate", @@ -28,7 +34,8 @@ const RULES: Record<AutocompleteDataType, Array<string>> = { NUMBER: [ "TABLE_WIDGET.pageNo", "TABLE_WIDGET.pageSize", - "INPUT_WIDGET.text", + "INPUT_WIDGET_V2.text", + "CURRENCY_INPUT_WIDGET.value", "TABLE_WIDGET.selectedRowIndex", "RICH_TEXT_EDITOR_WIDGET.text", "DROP_DOWN_WIDGET.selectedOptionValue", @@ -54,7 +61,9 @@ const RULES: Record<AutocompleteDataType, Array<string>> = { "CHECKBOX_WIDGET.isChecked", "SWITCH_WIDGET.isSwitchedOn", "CONTAINER_WIDGET.isVisible", - "INPUT_WIDGET.isVisible", + "INPUT_WIDGET_V2.isVisible", + "PHONE_INPUT_WIDGET.isVisible", + "CURRENCY_INPUT_WIDGET.isVisible", "TABLE_WIDGET.isVisible", "DROP_DOWN_WIDGET.isVisible", "IMAGE_WIDGET.isVisible", @@ -74,8 +83,12 @@ const RULES: Record<AutocompleteDataType, Array<string>> = { "RATE_WIDGET.isVisible", "IFRAME_WIDGET.isVisible", "DIVIDER_WIDGET.isVisible", - "INPUT_WIDGET.isValid", - "INPUT_WIDGET.isDisabled", + "INPUT_WIDGET_V2.isValid", + "INPUT_WIDGET_V2.isDisabled", + "PHONE_INPUT_WIDGET.isValid", + "PHONE_INPUT_WIDGET.isDisabled", + "CURRENCY_INPUT_WIDGET.isValid", + "CURRENCY_INPUT_WIDGET.isDisabled", "DROP_DOWN_WIDGET.isDisabled", "BUTTON_WIDGET.isDisabled", "DATE_PICKER_WIDGET2.isDisabled", diff --git a/app/client/src/utils/helpers.test.ts b/app/client/src/utils/helpers.test.ts index 4620924d4ee3..4887d1f7b6f6 100644 --- a/app/client/src/utils/helpers.test.ts +++ b/app/client/src/utils/helpers.test.ts @@ -1,4 +1,9 @@ -import { flattenObject, getSubstringBetweenTwoWords } from "./helpers"; +import { + flattenObject, + getLocale, + getSubstringBetweenTwoWords, + mergeWidgetConfig, +} from "./helpers"; describe("flattenObject test", () => { it("Check if non nested object is returned correctly", () => { @@ -104,3 +109,81 @@ describe("#getSubstringBetweenTwoWords", () => { }); }); }); + +describe("#mergeWidgetConfig", () => { + it("should merge the widget configs", () => { + const base = [ + { + sectionName: "General", + children: [ + { + propertyName: "someWidgetConfig", + }, + ], + }, + { + sectionName: "icon", + children: [ + { + propertyName: "someWidgetIconConfig", + }, + ], + }, + ]; + const extended = [ + { + sectionName: "General", + children: [ + { + propertyName: "someOtherWidgetConfig", + }, + ], + }, + { + sectionName: "style", + children: [ + { + propertyName: "someWidgetStyleConfig", + }, + ], + }, + ]; + const expected = [ + { + sectionName: "General", + children: [ + { + propertyName: "someOtherWidgetConfig", + }, + { + propertyName: "someWidgetConfig", + }, + ], + }, + { + sectionName: "style", + children: [ + { + propertyName: "someWidgetStyleConfig", + }, + ], + }, + { + sectionName: "icon", + children: [ + { + propertyName: "someWidgetIconConfig", + }, + ], + }, + ]; + + expect(mergeWidgetConfig(extended, base)).toEqual(expected); + }); +}); + +describe("#getLocale", () => { + it("should test that getLocale is returning navigator.languages[0]", () => { + expect(getLocale()).toBe(navigator.languages[0]); + }); +}); diff --git a/app/client/src/utils/helpers.tsx b/app/client/src/utils/helpers.tsx index eb665939ec2c..f7e7a63c7128 100644 --- a/app/client/src/utils/helpers.tsx +++ b/app/client/src/utils/helpers.tsx @@ -634,3 +634,31 @@ export function unFocus(document: Document, window: Window) { export function getLogToSentryFromResponse(response?: ApiResponse) { return response && response?.responseMeta?.status >= 500; } + +/* + * Function to merge property pane config of a widget + * + */ +export const mergeWidgetConfig = (target: any, source: any) => { + const sectionMap: Record<string, any> = {}; + + target.forEach((section: { sectionName: string }) => { + sectionMap[section.sectionName] = section; + }); + + source.forEach((section: { sectionName: string; children: any[] }) => { + const targetSection = sectionMap[section.sectionName]; + + if (targetSection) { + Array.prototype.push.apply(targetSection.children, section.children); + } else { + target.push(section); + } + }); + + return target; +}; + +export const getLocale = () => { + return navigator.languages?.[0] || "en-US"; +}; diff --git a/app/client/src/widgets/BaseInputWidget/component/index.tsx b/app/client/src/widgets/BaseInputWidget/component/index.tsx new file mode 100644 index 000000000000..d478c8f583ee --- /dev/null +++ b/app/client/src/widgets/BaseInputWidget/component/index.tsx @@ -0,0 +1,647 @@ +import React from "react"; +import styled from "styled-components"; +import { labelStyle } from "constants/DefaultTheme"; +import { ComponentProps } from "widgets/BaseComponent"; +import { + FontStyleTypes, + TextSize, + TEXT_SIZES, +} from "constants/WidgetConstants"; +import { + Alignment, + Intent, + NumericInput, + IconName, + InputGroup, + Label, + Classes, + ControlGroup, + TextArea, + Tag, + Position, +} from "@blueprintjs/core"; +import Tooltip from "components/ads/Tooltip"; +import { ReactComponent as HelpIcon } from "assets/icons/control/help.svg"; +import { IconWrapper } from "constants/IconConstants"; + +import { Colors } from "constants/Colors"; +import _, { isNil } from "lodash"; +import { + createMessage, + INPUT_WIDGET_DEFAULT_VALIDATION_ERROR, +} from "constants/messages"; +import { InputTypes } from "../constants"; + +// TODO(abhinav): All of the following imports should not be in widgets. +import ErrorTooltip from "components/editorComponents/ErrorTooltip"; +import Icon from "components/ads/Icon"; +import { InputType } from "widgets/InputWidget/constants"; + +/** + * All design system component specific logic goes here. + * Ex. Blueprint has a separate numeric input and text input so switching between them goes here + * Ex. To set the icon as currency, blue print takes in a set of defined types + * All generic logic like max characters for phone numbers should be 10, should go in the widget + */ + +const InputComponentWrapper = styled((props) => ( + <ControlGroup + {..._.omit(props, [ + "hasError", + "numeric", + "labelTextColor", + "allowCurrencyChange", + "compactMode", + "labelStyle", + "labelTextSize", + "multiline", + "numeric", + "inputType", + ])} + /> +))<{ + numeric: boolean; + multiline: string; + hasError: boolean; + allowCurrencyChange?: boolean; + disabled?: boolean; + inputType: InputType; +}>` + flex-direction: ${(props) => (props.compactMode ? "row" : "column")}; + &&&& { + .currency-type-filter, + .country-type-filter { + width: fit-content; + height: 36px; + display: inline-block; + left: 0; + z-index: 16; + &:hover { + border: 1px solid ${Colors.GREY_5} !important; + } + } + .${Classes.INPUT} { + min-height: 36px; + ${(props) => + props.inputType === InputTypes.CURRENCY && + props.allowCurrencyChange && + ` + padding-left: 45px;`}; + ${(props) => + props.inputType === InputTypes.CURRENCY && + !props.allowCurrencyChange && + ` + padding-left: 35px;`}; + ${(props) => + props.inputType === InputTypes.PHONE_NUMBER && + `padding-left: 85px; + `}; + box-shadow: none; + border: 1px solid; + border-color: ${({ hasError }) => + hasError ? `${Colors.DANGER_SOLID} !important;` : `${Colors.GREY_3};`} + border-radius: 0; + height: ${(props) => (props.multiline === "true" ? "100%" : "inherit")}; + width: 100%; + ${(props) => + props.numeric && + ` + border-top-right-radius: 0px; + border-bottom-right-radius: 0px; + ${props.hasError ? "" : "border-right-width: 0px;"} + `} + ${(props) => + props.inputType === "PASSWORD" && + ` + & + .bp3-input-action { + height: 36px; + width: 36px; + cursor: pointer; + padding: 1px; + .password-input { + color: ${Colors.GREY_6}; + justify-content: center; + height: 100%; + svg { + width: 20px; + height: 20px; + } + &:hover { + background-color: ${Colors.GREY_2}; + color: ${Colors.GREY_10}; + } + } + } + `} + transition: border-color .15s ease-in-out,box-shadow .15s ease-in-out; + &:active { + border-color: ${({ hasError }) => + hasError ? Colors.DANGER_SOLID : Colors.HIT_GRAY}; + } + &:hover { + border-left: 1px solid ${Colors.GREY_5}; + border-right: 1px solid ${Colors.GREY_5}; + border-color: ${Colors.GREY_5}; + } + &:focus { + border-color: ${({ hasError }) => + hasError ? Colors.DANGER_SOLID : Colors.MYSTIC}; + + &:focus { + outline: 0; + border: 1px solid ${Colors.GREEN_1}; + box-shadow: 0px 0px 0px 2px ${Colors.GREEN_2} !important; + } + } + &:disabled { + background-color: ${Colors.GREY_1}; + border: 1.2px solid ${Colors.GREY_3}; + & + .bp3-input-action { + pointer-events: none; + } + } + } + .${Classes.INPUT_GROUP} { + display: block; + margin: 0; + .bp3-tag { + background-color: transparent; + color: #5c7080; + margin-top: 8px; + } + &.${Classes.DISABLED} + .bp3-button-group.bp3-vertical { + pointer-events: none; + button { + background: ${Colors.GREY_1}; + } + } + } + .${Classes.CONTROL_GROUP} { + justify-content: flex-start; + } + height: 100%; + align-items: center; + label { + ${labelStyle} + margin-right: 5px; + text-align: right; + align-self: flex-start; + color: ${(props) => props.labelTextColor || "inherit"}; + font-size: ${(props) => props.labelTextSize}; + font-weight: ${(props) => + props?.labelStyle?.includes(FontStyleTypes.BOLD) ? "bold" : "normal"}; + font-style: ${(props) => + props?.labelStyle?.includes(FontStyleTypes.ITALIC) ? "italic" : ""}; + text-decoration: ${(props) => + props?.labelStyle?.includes(FontStyleTypes.UNDERLINE) + ? "underline" + : ""}; + } + } + &&&& .bp3-input-group { + display: flex; + > { + &.bp3-icon:first-child { + top: 3px; + } + input:not(:first-child) { + border-left: 1px solid transparent; + line-height: 16px; + + &:hover:not(:focus) { + border-left: 1px solid ${Colors.GREY_5}; + } + } + } + + ${(props) => { + if (props.inputType === InputTypes.PHONE_NUMBER) { + return ` + > { + input:not(:first-child) { + padding-left: 10px; + } + .currency-type-filter, + .currency-type-trigger, + .country-type-filter, + .country-type-trigger { + position: static; + background: rgb(255, 255, 255); + border-width: 1.2px 0px 1.2px 1.2px; + border-top-style: solid; + border-bottom-style: solid; + border-left-style: solid; + border-top-color: rgb(235, 235, 235); + border-bottom-color: rgb(235, 235, 235); + border-left-color: rgb(235, 235, 235); + border-image: initial; + color: rgb(9, 7, 7); + border-right-style: initial; + border-right-color: initial; + } + } + `; + } + }} + } +`; + +const StyledNumericInput = styled(NumericInput)` + &&&& .bp3-button-group.bp3-vertical { + border: 1.2px solid ${Colors.GREY_3}; + border-left: none; + button { + background: ${Colors.WHITE}; + box-shadow: none; + min-width: 24px; + width: 24px; + border-radius: 0; + &:hover { + background: ${Colors.GREY_2}; + span { + color: ${Colors.GREY_10}; + } + } + &:focus { + border: 1px solid ${Colors.GREEN_1}; + box-shadow: 0px 0px 0px 2px ${Colors.GREEN_2}; + } + span { + color: ${Colors.GREY_6}; + svg { + width: 14px; + } + } + } + } +`; + +const ToolTipIcon = styled(IconWrapper)` + cursor: help; + margin-top: 1.5px; + &&&:hover { + svg { + path { + fill: #716e6e; + } + } + } +`; + +const TextLableWrapper = styled.div<{ + compactMode: boolean; +}>` + ${(props) => + props.compactMode ? "&&& {margin-right: 5px;}" : "width: 100%;"} + display: flex; + max-height: 20px; +`; + +const TextInputWrapper = styled.div` + width: 100%; + display: flex; + flex: 1; +`; + +type InputHTMLType = "TEXT" | "NUMBER" | "PASSWORD" | "EMAIL" | "TEL"; + +export const isNumberInputType = (inputHTMLType: InputHTMLType = "TEXT") => { + return inputHTMLType === "NUMBER"; +}; + +class BaseInputComponent extends React.Component< + BaseInputComponentProps, + InputComponentState +> { + constructor(props: BaseInputComponentProps) { + super(props); + this.state = { showPassword: false }; + } + + setFocusState = (isFocused: boolean) => { + this.props.onFocusChange(isFocused); + }; + + onTextChange = ( + event: + | React.ChangeEvent<HTMLInputElement> + | React.ChangeEvent<HTMLTextAreaElement>, + ) => { + this.props.onValueChange(event.target.value); + }; + + onNumberChange = (valueAsNum: number, valueAsString: string) => { + this.props.onValueChange(valueAsString); + }; + + getLeftIcon = () => { + if (this.props.iconName && this.props.iconAlign === "left") { + return this.props.iconName; + } + return this.props.leftIcon; + }; + + getType(inputType: InputHTMLType = "TEXT") { + switch (inputType) { + case "PASSWORD": + return this.state.showPassword ? "text" : "password"; + case "TEL": + return "tel"; + case "EMAIL": + return "email"; + default: + return "text"; + } + } + + onKeyDownTextArea = (e: React.KeyboardEvent<HTMLTextAreaElement>) => { + const isEnterKey = e.key === "Enter" || e.keyCode === 13; + const { disableNewLineOnPressEnterKey } = this.props; + if (isEnterKey && disableNewLineOnPressEnterKey && !e.shiftKey) { + e.preventDefault(); + } + if (typeof this.props.onKeyDown === "function") { + this.props.onKeyDown(e); + } + }; + + onKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => { + if (typeof this.props.onKeyDown === "function") { + this.props.onKeyDown(e); + } + }; + + private numericInputComponent = () => { + const leftIcon = this.getLeftIcon(); + const conditionalProps: Record<string, number> = {}; + + if (!isNil(this.props.maxNum)) { + conditionalProps.max = this.props.maxNum; + } + + if (!isNil(this.props.minNum)) { + conditionalProps.min = this.props.minNum; + } + + return ( + <StyledNumericInput + allowNumericCharactersOnly + autoFocus={this.props.autoFocus} + className={this.props.isLoading ? "bp3-skeleton" : Classes.FILL} + disabled={this.props.disabled} + intent={this.props.intent} + leftIcon={leftIcon} + majorStepSize={null} + minorStepSize={null} + onBlur={() => this.setFocusState(false)} + onFocus={() => this.setFocusState(true)} + onKeyDown={this.onKeyDown} + onValueChange={this.onNumberChange} + placeholder={this.props.placeholder} + stepSize={this.props.stepSize} + value={this.props.value} + {...conditionalProps} + /> + ); + }; + + private textAreaInputComponent = () => ( + <TextArea + autoFocus={this.props.autoFocus} + className={this.props.isLoading ? "bp3-skeleton" : ""} + disabled={this.props.disabled} + growVertically={false} + intent={this.props.intent} + maxLength={this.props.maxChars} + onBlur={() => this.setFocusState(false)} + onChange={this.onTextChange} + onFocus={() => this.setFocusState(true)} + onKeyDown={this.onKeyDownTextArea} + placeholder={this.props.placeholder} + style={{ resize: "none" }} + value={this.props.value} + /> + ); + + private textInputComponent = (isTextArea: boolean) => + isTextArea ? ( + this.textAreaInputComponent() + ) : ( + <InputGroup + autoFocus={this.props.autoFocus} + className={this.props.isLoading ? "bp3-skeleton" : ""} + disabled={this.props.disabled} + intent={this.props.intent} + leftIcon={ + this.props.iconName && this.props.iconAlign === "left" + ? this.props.iconName + : this.props.leftIcon + } + maxLength={this.props.maxChars} + onBlur={() => this.setFocusState(false)} + onChange={this.onTextChange} + onFocus={() => this.setFocusState(true)} + onKeyDown={this.onKeyDown} + placeholder={this.props.placeholder} + rightElement={ + this.props.inputType === "PASSWORD" ? ( + <Icon + className="password-input" + name={this.state.showPassword ? "eye-off" : "eye-on"} + onClick={() => { + this.setState({ showPassword: !this.state.showPassword }); + }} + /> + ) : this.props.iconName && this.props.iconAlign === "right" ? ( + <Tag icon={this.props.iconName} /> + ) : ( + undefined + ) + } + spellCheck={this.props.spellCheck} + type={this.getType(this.props.inputHTMLType)} + value={this.props.value} + /> + ); + private renderInputComponent = ( + inputHTMLType: InputHTMLType = "TEXT", + isTextArea: boolean, + ) => + isNumberInputType(inputHTMLType) + ? this.numericInputComponent() + : this.textInputComponent(isTextArea); + + onStepIncrement = (e: React.KeyboardEvent<HTMLInputElement>) => { + e.preventDefault(); + e.stopPropagation(); + this.props.onStep && this.props.onStep(1); + }; + + onStepDecrement = (e: React.KeyboardEvent<HTMLInputElement>) => { + e.preventDefault(); + e.stopPropagation(); + this.props.onStep && this.props.onStep(-1); + }; + + componentDidMount() { + if (isNumberInputType(this.props.inputHTMLType) && this.props.onStep) { + const element: any = document.querySelector( + `.appsmith_widget_${this.props.widgetId} .bp3-button-group`, + ); + + if (element !== null && element.childNodes) { + element.childNodes[0].addEventListener( + "mousedown", + this.onStepIncrement, + ); + element.childNodes[1].addEventListener( + "mousedown", + this.onStepDecrement, + ); + } + } + } + + componentWillUnmount() { + if (isNumberInputType(this.props.inputHTMLType) && this.props.onStep) { + const element: any = document.querySelectorAll( + `.appsmith_widget_${this.props.widgetId} .bp3-button`, + ); + + if (element !== null && element.childNodes) { + element.childNodes[0].removeEventListener( + "click", + this.onStepIncrement, + ); + element.childNodes[1].removeEventListener( + "click", + this.onStepDecrement, + ); + } + } + } + + render() { + const { + label, + labelStyle, + labelTextColor, + labelTextSize, + tooltip, + } = this.props; + const showLabelHeader = label || tooltip; + + return ( + <InputComponentWrapper + compactMode={this.props.compactMode} + disabled={this.props.disabled} + fill + hasError={this.props.isInvalid} + inputType={this.props.inputType} + labelStyle={labelStyle} + labelTextColor={labelTextColor} + labelTextSize={labelTextSize ? TEXT_SIZES[labelTextSize] : "inherit"} + multiline={(!!this.props.multiline).toString()} + numeric={isNumberInputType(this.props.inputHTMLType)} + > + {showLabelHeader && ( + <TextLableWrapper + className="t--input-label-wrapper" + compactMode={this.props.compactMode} + > + {this.props.label && ( + <Label + className={` + t--input-widget-label ${ + this.props.isLoading + ? Classes.SKELETON + : Classes.TEXT_OVERFLOW_ELLIPSIS + } + `} + > + {this.props.label} + </Label> + )} + {this.props.tooltip && ( + <Tooltip + content={this.props.tooltip} + hoverOpenDelay={200} + position={Position.TOP} + > + <ToolTipIcon + color={Colors.SILVER_CHALICE} + height={14} + width={14} + > + <HelpIcon className="t--input-widget-tooltip" /> + </ToolTipIcon> + </Tooltip> + )} + </TextLableWrapper> + )} + <TextInputWrapper> + <ErrorTooltip + isOpen={this.props.isInvalid && this.props.showError} + message={ + this.props.errorMessage || + createMessage(INPUT_WIDGET_DEFAULT_VALIDATION_ERROR) + } + > + {this.renderInputComponent( + this.props.inputHTMLType, + !!this.props.multiline, + )} + </ErrorTooltip> + </TextInputWrapper> + </InputComponentWrapper> + ); + } +} + +export interface InputComponentState { + showPassword?: boolean; +} + +export interface BaseInputComponentProps extends ComponentProps { + value: string; + inputType: InputType; + inputHTMLType?: InputHTMLType; + disabled?: boolean; + intent?: Intent; + defaultValue?: string | number; + label: string; + labelTextColor?: string; + labelTextSize?: TextSize; + labelStyle?: string; + tooltip?: string; + leftIcon?: IconName | JSX.Element; + allowNumericCharactersOnly?: boolean; + fill?: boolean; + errorMessage?: string; + onValueChange: (valueAsString: string) => void; + stepSize?: number; + placeholder?: string; + isLoading: boolean; + multiline?: boolean; + compactMode: boolean; + isInvalid: boolean; + autoFocus?: boolean; + iconName?: IconName; + iconAlign?: Omit<Alignment, "center">; + showError: boolean; + onFocusChange: (state: boolean) => void; + disableNewLineOnPressEnterKey?: boolean; + onKeyDown?: ( + e: + | React.KeyboardEvent<HTMLTextAreaElement> + | React.KeyboardEvent<HTMLInputElement>, + ) => void; + maxChars?: number; + widgetId: string; + onStep?: (direction: number) => void; + spellCheck?: boolean; + maxNum?: number; + minNum?: number; +} + +export default BaseInputComponent; diff --git a/app/client/src/widgets/BaseInputWidget/constants.ts b/app/client/src/widgets/BaseInputWidget/constants.ts new file mode 100644 index 000000000000..3997261dad6c --- /dev/null +++ b/app/client/src/widgets/BaseInputWidget/constants.ts @@ -0,0 +1,8 @@ +export enum InputTypes { + TEXT = "TEXT", + NUMBER = "NUMBER", + PHONE_NUMBER = "PHONE_NUMBER", + EMAIL = "EMAIL", + PASSWORD = "PASSWORD", + CURRENCY = "CURRENCY", +} diff --git a/app/client/src/widgets/BaseInputWidget/icon.svg b/app/client/src/widgets/BaseInputWidget/icon.svg new file mode 100644 index 000000000000..889009e70e2d --- /dev/null +++ b/app/client/src/widgets/BaseInputWidget/icon.svg @@ -0,0 +1 @@ +<svg fill="none" height="32" viewBox="0 0 32 32" width="32" xmlns="http://www.w3.org/2000/svg"><g fill="#4b4848"><path clip-rule="evenodd" d="m2.66675 8h26.66665v16h-26.66665zm2.66666 13.3333v-10.6666h21.33329v10.6666z" fill-rule="evenodd"/><path d="m6.66675 20v-8h1.33333v8z"/></g></svg> \ No newline at end of file diff --git a/app/client/src/widgets/BaseInputWidget/index.ts b/app/client/src/widgets/BaseInputWidget/index.ts new file mode 100644 index 000000000000..933544934180 --- /dev/null +++ b/app/client/src/widgets/BaseInputWidget/index.ts @@ -0,0 +1,33 @@ +import Widget from "./widget"; +import IconSVG from "./icon.svg"; + +export const CONFIG = { + type: Widget.getWidgetType(), + name: "Input", + hideCard: true, + iconSVG: IconSVG, + needsMeta: true, + defaults: { + rows: 4, + label: "", + columns: 20, + widgetName: "Input", + version: 1, + defaultText: "", + iconAlign: "left", + autoFocus: false, + labelStyle: "", + resetOnSubmit: true, + isRequired: false, + isDisabled: false, + animateLoading: true, + }, + properties: { + derived: Widget.getDerivedPropertiesMap(), + default: Widget.getDefaultPropertiesMap(), + meta: Widget.getMetaPropertiesMap(), + config: Widget.getPropertyPaneConfig(), + }, +}; + +export default Widget; diff --git a/app/client/src/widgets/BaseInputWidget/widget/index.tsx b/app/client/src/widgets/BaseInputWidget/widget/index.tsx new file mode 100644 index 000000000000..d8a76d598cdb --- /dev/null +++ b/app/client/src/widgets/BaseInputWidget/widget/index.tsx @@ -0,0 +1,410 @@ +import React from "react"; +import BaseWidget, { WidgetProps, WidgetState } from "widgets/BaseWidget"; +import { Alignment } from "@blueprintjs/core"; +import { IconName } from "@blueprintjs/icons"; +import { WidgetType, TextSize } from "constants/WidgetConstants"; +import { + EventType, + ExecutionResult, +} from "constants/AppsmithActionConstants/ActionConstants"; +import { ValidationTypes } from "constants/WidgetValidation"; +import { DerivedPropertiesMap } from "utils/WidgetFactory"; +import BaseInputComponent from "../component"; +import { InputTypes } from "../constants"; + +class BaseInputWidget< + T extends BaseInputWidgetProps, + K extends WidgetState +> extends BaseWidget<T, K> { + constructor(props: T) { + super(props); + } + + static getPropertyPaneConfig() { + return [ + { + sectionName: "General", + children: [ + { + helpText: + "Adds a validation to the input which displays an error on failure", + propertyName: "regex", + label: "Regex", + controlType: "INPUT_TEXT", + placeholderText: "^\\w+@[a-zA-Z_]+?\\.[a-zA-Z]{2,3}$", + isBindProperty: true, + isTriggerProperty: false, + validation: { type: ValidationTypes.REGEX }, + }, + { + helpText: "Sets the input validity based on a JS expression", + propertyName: "validation", + label: "Valid", + controlType: "INPUT_TEXT", + placeholderText: "{{ Input1.text.length > 0 }}", + isBindProperty: true, + isTriggerProperty: false, + validation: { type: ValidationTypes.BOOLEAN }, + }, + { + helpText: + "The error message to display if the regex or valid property check fails", + propertyName: "errorMessage", + label: "Error Message", + controlType: "INPUT_TEXT", + placeholderText: "Not a valid value!", + isBindProperty: true, + isTriggerProperty: false, + validation: { type: ValidationTypes.TEXT }, + }, + { + helpText: "Sets a placeholder text for the input", + propertyName: "placeholderText", + label: "Placeholder", + controlType: "INPUT_TEXT", + placeholderText: "Placeholder", + isBindProperty: true, + isTriggerProperty: false, + validation: { type: ValidationTypes.TEXT }, + }, + { + helpText: "Sets the label text of the widget", + propertyName: "label", + label: "Label", + controlType: "INPUT_TEXT", + placeholderText: "Name:", + isBindProperty: true, + isTriggerProperty: false, + validation: { type: ValidationTypes.TEXT }, + }, + { + helpText: "Show help text or details about current input", + propertyName: "tooltip", + label: "Tooltip", + controlType: "INPUT_TEXT", + placeholderText: "Value must be atleast 6 chars", + isBindProperty: true, + isTriggerProperty: false, + validation: { type: ValidationTypes.TEXT }, + }, + { + propertyName: "isRequired", + label: "Required", + helpText: "Makes input to the widget mandatory", + controlType: "SWITCH", + isJSConvertible: true, + isBindProperty: true, + isTriggerProperty: false, + validation: { type: ValidationTypes.BOOLEAN }, + }, + { + helpText: "Controls the visibility of the widget", + propertyName: "isVisible", + label: "Visible", + controlType: "SWITCH", + isJSConvertible: true, + isBindProperty: true, + isTriggerProperty: false, + validation: { type: ValidationTypes.BOOLEAN }, + }, + { + helpText: "Disables input to this widget", + propertyName: "isDisabled", + label: "Disabled", + controlType: "SWITCH", + isJSConvertible: true, + isBindProperty: true, + isTriggerProperty: false, + validation: { type: ValidationTypes.BOOLEAN }, + }, + { + helpText: "Clears the input value after submit", + propertyName: "resetOnSubmit", + label: "Reset on submit", + controlType: "SWITCH", + isJSConvertible: true, + isBindProperty: true, + isTriggerProperty: false, + validation: { type: ValidationTypes.BOOLEAN }, + }, + { + helpText: "Focus input automatically on load", + propertyName: "autoFocus", + label: "Auto Focus", + controlType: "SWITCH", + isJSConvertible: true, + isBindProperty: true, + isTriggerProperty: false, + validation: { type: ValidationTypes.BOOLEAN }, + }, + { + propertyName: "animateLoading", + label: "Animate Loading", + controlType: "SWITCH", + helpText: "Controls the loading of the widget", + defaultValue: true, + isJSConvertible: true, + isBindProperty: true, + isTriggerProperty: false, + validation: { type: ValidationTypes.BOOLEAN }, + }, + { + propertyName: "isSpellCheck", + label: "Spellcheck", + helpText: + "Defines whether the text input may be checked for spelling errors", + controlType: "SWITCH", + isJSConvertible: false, + isBindProperty: true, + isTriggerProperty: false, + validation: { type: ValidationTypes.BOOLEAN }, + hidden: (props: BaseInputWidgetProps) => { + return props.inputType !== InputTypes.TEXT; + }, + dependencies: ["inputType"], + }, + ], + }, + { + sectionName: "Actions", + children: [ + { + helpText: "Triggers an action when the text is changed", + propertyName: "onTextChanged", + label: "onTextChanged", + controlType: "ACTION_SELECTOR", + isJSConvertible: true, + isBindProperty: true, + isTriggerProperty: true, + }, + { + helpText: + "Triggers an action on submit (when the enter key is pressed)", + propertyName: "onSubmit", + label: "onSubmit", + controlType: "ACTION_SELECTOR", + isJSConvertible: true, + isBindProperty: true, + isTriggerProperty: true, + }, + ], + }, + { + sectionName: "Label Styles", + children: [ + { + propertyName: "labelTextColor", + label: "Text Color", + controlType: "COLOR_PICKER", + isJSConvertible: true, + isBindProperty: true, + isTriggerProperty: false, + validation: { + type: ValidationTypes.TEXT, + params: { + regex: /^(?![<|{{]).+/, + }, + }, + }, + { + propertyName: "labelTextSize", + label: "Text Size", + controlType: "DROP_DOWN", + options: [ + { + label: "Heading 1", + value: "HEADING1", + subText: "24px", + icon: "HEADING_ONE", + }, + { + label: "Heading 2", + value: "HEADING2", + subText: "18px", + icon: "HEADING_TWO", + }, + { + label: "Heading 3", + value: "HEADING3", + subText: "16px", + icon: "HEADING_THREE", + }, + { + label: "Paragraph", + value: "PARAGRAPH", + subText: "14px", + icon: "PARAGRAPH", + }, + { + label: "Paragraph 2", + value: "PARAGRAPH2", + subText: "12px", + icon: "PARAGRAPH_TWO", + }, + ], + isBindProperty: false, + isTriggerProperty: false, + }, + { + propertyName: "labelStyle", + label: "Label Font Style", + controlType: "BUTTON_TABS", + options: [ + { + icon: "BOLD_FONT", + value: "BOLD", + }, + { + icon: "ITALICS_FONT", + value: "ITALIC", + }, + ], + isBindProperty: false, + isTriggerProperty: false, + validation: { type: ValidationTypes.TEXT }, + }, + ], + }, + ]; + } + + static getDerivedPropertiesMap(): DerivedPropertiesMap { + return { + value: `{{this.text}}`, + }; + } + + static getDefaultPropertiesMap(): Record<string, string> { + return { + text: "defaultText", + }; + } + + static getMetaPropertiesMap(): Record<string, any> { + return { + text: undefined, + isFocused: false, + isDirty: false, + }; + } + + handleFocusChange(focusState: boolean) { + /** + * Reason for disabling drag on focusState: true: + * 1. In Firefox, draggable="true" property on the parent element + * or <input /> itself, interferes with some <input /> element's events + * Bug Ref - https://bugzilla.mozilla.org/show_bug.cgi?id=800050 + * https://bugzilla.mozilla.org/show_bug.cgi?id=1189486 + * + * Eg - input with draggable="true", double clicking the text; won't highlight the text + * + * 2. Dragging across the text (for text selection) in input won't cause the widget to drag. + */ + this.props.updateWidgetMetaProperty("dragDisabled", focusState); + this.props.updateWidgetMetaProperty("isFocused", focusState); + } + + onSubmitSuccess(result: ExecutionResult) { + if (result.success && this.props.resetOnSubmit) { + this.props.updateWidgetMetaProperty("text", "", { + triggerPropertyName: "onSubmit", + dynamicString: this.props.onTextChanged, + event: { + type: EventType.ON_TEXT_CHANGE, + }, + }); + } + } + + handleKeyDown( + e: + | React.KeyboardEvent<HTMLTextAreaElement> + | React.KeyboardEvent<HTMLInputElement>, + ) { + const { isValid, onSubmit } = this.props; + const isEnterKey = e.key === "Enter" || e.keyCode === 13; + if (isEnterKey && typeof onSubmit == "string" && isValid) { + super.executeAction({ + triggerPropertyName: "onSubmit", + dynamicString: onSubmit, + event: { + type: EventType.ON_SUBMIT, + callback: this.onSubmitSuccess, + }, + }); + } + } + + getPageView() { + return ( + <BaseInputComponent + allowNumericCharactersOnly={this.props.allowNumericCharactersOnly} + autoFocus={this.props.autoFocus} + compactMode={this.props.compactMode} + defaultValue={this.props.defaultValue} + disableNewLineOnPressEnterKey={this.props.disableNewLineOnPressEnterKey} + disabled={this.props.isDisabled} + errorMessage={this.props.errorMessage} + fill={this.props.fill} + iconAlign={this.props.iconAlign} + iconName={this.props.iconName} + inputHTMLType="TEXT" + inputType={this.props.inputType} + intent={this.props.intent} + isInvalid={this.props.isInvalid} + isLoading={this.props.isLoading} + label={this.props.label} + labelStyle={this.props.labelStyle} + labelTextColor={this.props.labelTextColor} + labelTextSize={this.props.labelTextSize} + maxChars={this.props.maxChars} + multiline={this.props.multiline} + onFocusChange={this.props.onFocusChange} + onKeyDown={this.handleKeyDown} + onValueChange={this.props.onValueChange} + placeholder={this.props.placeholder} + showError={this.props.showError} + stepSize={1} + tooltip={this.props.tooltip} + value={this.props.value} + widgetId={this.props.widgetId} + /> + ); + } + + static getWidgetType(): WidgetType { + return "BASE_INPUT_WIDGET"; + } +} + +export interface BaseInputValidator { + validationRegex: string; + errorMessage: string; +} +export interface BaseInputWidgetProps extends WidgetProps { + inputType: InputTypes; + tooltip?: string; + isDisabled?: boolean; + validation: boolean; + text: string; + regex?: string; + errorMessage?: string; + placeholderText?: string; + label: string; + labelTextColor?: string; + labelTextSize?: TextSize; + labelStyle?: string; + inputValidators: BaseInputValidator[]; + isValid: boolean; + focusIndex?: number; + isAutoFocusEnabled?: boolean; + isRequired?: boolean; + isFocused?: boolean; + isDirty?: boolean; + autoFocus?: boolean; + iconName?: IconName; + iconAlign?: Omit<Alignment, "center">; + onSubmit?: string; +} + +export default BaseInputWidget; diff --git a/app/client/src/widgets/CurrencyInputWidget/component/CurrencyCodeDropdown.tsx b/app/client/src/widgets/CurrencyInputWidget/component/CurrencyCodeDropdown.tsx new file mode 100644 index 000000000000..a7b369ff47ed --- /dev/null +++ b/app/client/src/widgets/CurrencyInputWidget/component/CurrencyCodeDropdown.tsx @@ -0,0 +1,173 @@ +import React from "react"; +import styled from "styled-components"; +import Dropdown, { DropdownOption } from "components/ads/Dropdown"; +import { CurrencyTypeOptions, CurrencyOptionProps } from "constants/Currency"; +import Icon, { IconSize } from "components/ads/Icon"; +import { countryToFlag } from "./utilities"; +import { Colors } from "constants/Colors"; + +const DropdownContainer = styled.div` + .currency-type-filter, + .currency-type-trigger { + position: static; + background: rgb(255, 255, 255); + border-width: 1.2px 0px 1.2px 1.2px; + border-top-style: solid; + border-bottom-style: solid; + border-left-style: solid; + border-top-color: rgb(235, 235, 235); + border-bottom-color: rgb(235, 235, 235); + border-left-color: rgb(235, 235, 235); + border-image: initial; + color: rgb(9, 7, 7); + border-right-style: initial; + border-right-color: initial; + } + + &&&&& + input { + padding-left: 10px; + } +`; + +const DropdownTriggerIconWrapper = styled.div` + height: 19px; + padding: 9px 5px 9px 12px; + display: flex; + align-items: center; + justify-content: space-between; + font-size: 14px; + line-height: 18px; + letter-spacing: -0.24px; + color: #090707; + > * { + margin-left: 5px; + } + + &&& .dropdown { + svg { + width: 14px; + height: 14px; + + path { + fill: ${Colors.GREY_10}; + } + } + } +`; + +const CurrencyIconWrapper = styled.span` + position: static; + background: rgb(255, 255, 255); + border-width: 1.2px 0px 1.2px 1.2px; + border-top-style: solid; + border-bottom-style: solid; + border-left-style: solid; + border-top-color: rgb(235, 235, 235); + border-bottom-color: rgb(235, 235, 235); + border-left-color: rgb(235, 235, 235); + border-image: initial; + color: rgb(9, 7, 7); + border-right-style: initial; + border-right-color: initial; + padding: 6px 12px 0px 12px; + + &&&&& + input { + padding-left: 10px; + } +`; + +const getCurrencyOptions = (): Array<DropdownOption> => { + return CurrencyTypeOptions.map((item: CurrencyOptionProps) => { + return { + leftElement: countryToFlag(item.code), + searchText: item.label, + label: `${item.currency} - ${item.currency_name}`, + value: item.currency, + id: item.symbol_native, + }; + }); +}; + +export const CurrencyDropdownOptions = getCurrencyOptions(); + +export const getDefaultCurrency = () => { + return { + code: "US", + currency: "USD", + currency_name: "US Dollar", + label: "United States", + phone: "1", + symbol_native: "$", + }; +}; + +export const getSelectedCurrency = (currencyCode?: string): DropdownOption => { + let selectedCurrency: CurrencyOptionProps | undefined = currencyCode + ? CurrencyTypeOptions.find((item: CurrencyOptionProps) => { + return item.currency === currencyCode; + }) + : undefined; + if (!selectedCurrency) { + selectedCurrency = getDefaultCurrency(); + } + return { + label: `${selectedCurrency.currency} - ${selectedCurrency.currency_name}`, + searchText: selectedCurrency.label, + value: selectedCurrency.currency, + id: selectedCurrency.symbol_native, + }; +}; + +export const getCountryCodeFromCurrencyCode = (currencyCode?: string) => { + const option = CurrencyTypeOptions.find( + (option) => option.currency === currencyCode, + ); + + if (option) { + return option.code; + } else { + return ""; + } +}; + +interface CurrencyDropdownProps { + onCurrencyTypeChange: (currencyCountryCode?: string) => void; + options: Array<DropdownOption>; + selected?: string; + allowCurrencyChange?: boolean; +} + +export default function CurrencyTypeDropdown(props: CurrencyDropdownProps) { + const selectedOption = getSelectedCurrency(props.selected); + const selectedCurrency = selectedOption.id; + if (!props.allowCurrencyChange) { + return ( + <CurrencyIconWrapper className="currency-type-trigger"> + {selectedCurrency} + </CurrencyIconWrapper> + ); + } + const dropdownTriggerIcon = ( + <DropdownTriggerIconWrapper className="t--input-currency-change"> + {selectedCurrency} + <Icon className="dropdown" name="downArrow" size={IconSize.XXS} /> + </DropdownTriggerIconWrapper> + ); + return ( + <DropdownContainer> + <Dropdown + containerClassName="currency-type-filter" + dropdownHeight="139px" + dropdownTriggerIcon={dropdownTriggerIcon} + enableSearch + height="36px" + onSelect={props.onCurrencyTypeChange} + optionWidth="340px" + options={props.options} + searchPlaceholder="Search by currency or country" + selected={selectedOption} + showLabelOnly + /> + </DropdownContainer> + ); +} diff --git a/app/client/src/widgets/CurrencyInputWidget/component/index.tsx b/app/client/src/widgets/CurrencyInputWidget/component/index.tsx new file mode 100644 index 000000000000..afdc357b806e --- /dev/null +++ b/app/client/src/widgets/CurrencyInputWidget/component/index.tsx @@ -0,0 +1,96 @@ +import React from "react"; +import CurrencyTypeDropdown, { + CurrencyDropdownOptions, +} from "./CurrencyCodeDropdown"; +import BaseInputComponent, { + BaseInputComponentProps, +} from "widgets/BaseInputWidget/component"; +import { RenderModes } from "constants/WidgetConstants"; +import { InputTypes } from "widgets/BaseInputWidget/constants"; + +class CurrencyInputComponent extends React.Component< + CurrencyInputComponentProps +> { + onKeyDown = ( + e: + | React.KeyboardEvent<HTMLTextAreaElement> + | React.KeyboardEvent<HTMLInputElement>, + ) => { + if (typeof this.props.onKeyDown === "function") { + this.props.onKeyDown(e); + } + }; + + componentDidMount() { + if (this.props.currencyCode) { + this.props.onCurrencyTypeChange(this.props.currencyCode); + } + } + + componentDidUpdate(prevProps: CurrencyInputComponentProps) { + if ( + this.props.renderMode === RenderModes.CANVAS && + prevProps.currencyCode !== this.props.currencyCode + ) { + this.props.onCurrencyTypeChange(this.props.currencyCode); + } + } + + render() { + return ( + <BaseInputComponent + autoFocus={this.props.autoFocus} + compactMode={this.props.compactMode} + defaultValue={this.props.defaultValue} + disableNewLineOnPressEnterKey={this.props.disableNewLineOnPressEnterKey} + disabled={this.props.disabled} + errorMessage={this.props.errorMessage} + fill={this.props.fill} + iconAlign={this.props.iconAlign} + iconName={this.props.iconName} + inputHTMLType="NUMBER" + inputType={InputTypes.CURRENCY} + intent={this.props.intent} + isInvalid={this.props.isInvalid} + isLoading={this.props.isLoading} + label={this.props.label} + labelStyle={this.props.labelStyle} + labelTextColor={this.props.labelTextColor} + labelTextSize={this.props.labelTextSize} + leftIcon={ + <CurrencyTypeDropdown + allowCurrencyChange={ + this.props.allowCurrencyChange && !this.props.disabled + } + onCurrencyTypeChange={this.props.onCurrencyTypeChange} + options={CurrencyDropdownOptions} + selected={this.props.currencyCode} + /> + } + multiline={false} + onFocusChange={this.props.onFocusChange} + onKeyDown={this.onKeyDown} + onStep={this.props.onStep} + onValueChange={this.props.onValueChange} + placeholder={this.props.placeholder} + showError={this.props.showError} + stepSize={1} + tooltip={this.props.tooltip} + value={this.props.value} + widgetId={this.props.widgetId} + /> + ); + } +} + +export interface CurrencyInputComponentProps extends BaseInputComponentProps { + currencyCode?: string; + noOfDecimals?: number; + allowCurrencyChange?: boolean; + decimals?: number; + onCurrencyTypeChange: (code?: string) => void; + onStep: (direction: number) => void; + renderMode: string; +} + +export default CurrencyInputComponent; diff --git a/app/client/src/widgets/CurrencyInputWidget/component/utilities.test.ts b/app/client/src/widgets/CurrencyInputWidget/component/utilities.test.ts new file mode 100644 index 000000000000..d35605e6f0c0 --- /dev/null +++ b/app/client/src/widgets/CurrencyInputWidget/component/utilities.test.ts @@ -0,0 +1,127 @@ +import { + countryToFlag, + formatCurrencyNumber, + getLocaleThousandSeparator, + getLocaleDecimalSeperator, + 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", () => { + [ + [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"], + ].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]); + }); + }); +}); diff --git a/app/client/src/widgets/CurrencyInputWidget/component/utilities.ts b/app/client/src/widgets/CurrencyInputWidget/component/utilities.ts new file mode 100644 index 000000000000..90d66f664e20 --- /dev/null +++ b/app/client/src/widgets/CurrencyInputWidget/component/utilities.ts @@ -0,0 +1,82 @@ +import { getLocale } from "utils/helpers"; + +export const countryToFlag = (isoCode: string) => { + return typeof String.fromCodePoint !== "undefined" + ? isoCode + .toUpperCase() + .replace(/./g, (char) => + String.fromCodePoint(char.charCodeAt(0) + 127397), + ) + : isoCode; +}; + +/* + Returns formatted value with maximum number of decimals based on decimalsInCurrency value + and add commas based on user's locale + for eg: + a) (2, 1235.456) will return 1,235.45 + b) (1, 1234.456) will return 1,234.4 +*/ +export const formatCurrencyNumber = (decimalsInCurrency = 0, value: string) => { + const fractionDigits = decimalsInCurrency || 0; + const currentIndexOfDecimal = value.indexOf(getLocaleDecimalSeperator()); + const indexOfDecimal = value.length - fractionDigits - 1; + const isDecimal = + value.includes(getLocaleDecimalSeperator()) && + currentIndexOfDecimal <= indexOfDecimal; + const locale = getLocale(); + const formatter = new Intl.NumberFormat(locale, { + style: "decimal", + maximumFractionDigits: isDecimal ? fractionDigits : 0, + }); + const parsedValue = parseLocaleFormattedStringToNumber(value); + return formatter.format(isNaN(parsedValue) ? 0 : parsedValue); +}; + +/* + Returns value in string format with maximum number of decimals based on decimalsInCurrency value + for eg: + a) (2, 1235.456) will return 1235.45 + b) (1, 1234.456) will return 1234.4 +*/ +export const limitDecimalValue = (decimals = 0, value = "") => { + const decimalSeperator = getLocaleDecimalSeperator(); + value = value.split(getLocaleThousandSeparator()).join(""); + switch (decimals) { + case 0: + return value.split(decimalSeperator).shift() || ""; + case 1: + case 2: + const decimalValueArray = value.split(decimalSeperator); + return ( + decimalValueArray[0] + + decimalSeperator + + decimalValueArray[1].substr(0, decimals) + ); + default: + return value; + } +}; + +/* + * Parses the locale formatted currency string to number + */ +export function parseLocaleFormattedStringToNumber(currencyString = "") { + return parseFloat( + currencyString + .replace(new RegExp("\\" + getLocaleThousandSeparator(), "g"), "") + .replace(new RegExp("\\" + getLocaleDecimalSeperator()), "."), + ); +} + +export function getLocaleDecimalSeperator() { + return Intl.NumberFormat(getLocale()) + .format(1.1) + .replace(/\p{Number}/gu, ""); +} + +export function getLocaleThousandSeparator() { + return Intl.NumberFormat(getLocale()) + .format(11111) + .replace(/\p{Number}/gu, ""); +} diff --git a/app/client/src/widgets/CurrencyInputWidget/icon.svg b/app/client/src/widgets/CurrencyInputWidget/icon.svg new file mode 100644 index 000000000000..e6bcd986521e --- /dev/null +++ b/app/client/src/widgets/CurrencyInputWidget/icon.svg @@ -0,0 +1,4 @@ +<svg width="20" height="12" viewBox="0 0 20 12" fill="none" xmlns="http://www.w3.org/2000/svg"> +<path fill-rule="evenodd" clip-rule="evenodd" d="M0 0H20V12H0V0ZM2 10V2H18V10H2Z" fill="#4B4848"/> +<path d="M4.81348 8.41895H5.15625V7.93262C5.93555 7.87695 6.52441 7.46094 6.52441 6.74023V6.73438C6.52441 6.10156 6.10254 5.78516 5.32031 5.60352L5.15625 5.56543V4.42871C5.50781 4.47852 5.75098 4.68652 5.78906 5.0293L5.79199 5.03516L6.47168 5.03223V5.0293C6.44531 4.3584 5.91797 3.90137 5.15625 3.83984V3.34766H4.81348V3.83984C4.04883 3.89258 3.50098 4.3291 3.50098 5V5.00586C3.50098 5.61523 3.91113 5.95508 4.66406 6.12793L4.81348 6.16309V7.34668C4.37402 7.2998 4.15723 7.07129 4.10742 6.75195L4.10449 6.74609L3.4248 6.74902L3.42188 6.75195C3.44531 7.46094 4.03711 7.88281 4.81348 7.93262V8.41895ZM4.20703 4.95312V4.94727C4.20703 4.69531 4.41504 4.47559 4.81348 4.42871V5.48633C4.37988 5.37207 4.20703 5.19922 4.20703 4.95312ZM5.81836 6.80469V6.81055C5.81836 7.10059 5.61328 7.30859 5.15625 7.34668V6.24219C5.65723 6.36816 5.81836 6.52637 5.81836 6.80469Z" fill="#4B4848"/> +</svg> \ No newline at end of file diff --git a/app/client/src/widgets/CurrencyInputWidget/index.ts b/app/client/src/widgets/CurrencyInputWidget/index.ts new file mode 100644 index 000000000000..64809ce4df55 --- /dev/null +++ b/app/client/src/widgets/CurrencyInputWidget/index.ts @@ -0,0 +1,27 @@ +import Widget from "./widget"; +import IconSVG from "./icon.svg"; +import { CONFIG as BaseConfig } from "widgets/BaseInputWidget"; +import { getDefaultCurrency } from "./component/CurrencyCodeDropdown"; + +export const CONFIG = { + type: Widget.getWidgetType(), + name: "Currency Input", + iconSVG: IconSVG, + needsMeta: true, + defaults: { + ...BaseConfig.defaults, + widgetName: "CurrencyInput", + version: 1, + allowCurrencyChange: false, + currencyCode: getDefaultCurrency().currency, + decimals: 0, + }, + properties: { + derived: Widget.getDerivedPropertiesMap(), + default: Widget.getDefaultPropertiesMap(), + meta: Widget.getMetaPropertiesMap(), + config: Widget.getPropertyPaneConfig(), + }, +}; + +export default Widget; diff --git a/app/client/src/widgets/CurrencyInputWidget/widget/derived.js b/app/client/src/widgets/CurrencyInputWidget/widget/derived.js new file mode 100644 index 000000000000..31ee8ec1ec91 --- /dev/null +++ b/app/client/src/widgets/CurrencyInputWidget/widget/derived.js @@ -0,0 +1,90 @@ +/* eslint-disable @typescript-eslint/no-unused-vars*/ +export default { + isValid: (props, moment, _) => { + let hasValidValue, value; + try { + value = Number(props.value); + hasValidValue = Number.isFinite(value); + } catch (e) { + return false; + } + + if (!props.isRequired && (props.text === "" || props.text === undefined)) { + return true; + } + if (props.isRequired && !hasValidValue) { + return false; + } + + if (typeof props.validation === "boolean" && !props.validation) { + return false; + } + + let parsedRegex = null; + if (props.regex) { + /* + * break up the regexp pattern into 4 parts: given regex, regex prefix , regex pattern, regex flags + * Example /test/i will be split into ["/test/gi", "/", "test", "gi"] + */ + const regexParts = props.regex.match(/(\/?)(.+)\\1([a-z]*)/i); + + if (!regexParts) { + parsedRegex = new RegExp(props.regex); + } else { + if ( + regexParts[3] && + !/^(?!.*?(.).*?\\1)[gmisuy]+$/.test(regexParts[3]) + ) { + parsedRegex = RegExp(props.regex); + } else { + /* + * if we have a regex flags, use it to form regexp + */ + parsedRegex = new RegExp(regexParts[2], regexParts[3]); + } + } + } + if (parsedRegex) { + return parsedRegex.test(props.text); + } else { + return hasValidValue; + } + }, + // + value: (props, moment, _) => { + const text = props.text; + + function getLocale() { + return navigator.languages?.[0] || "en-US"; + } + + function getLocaleDecimalSeperator() { + return Intl.NumberFormat(getLocale()) + .format(1.1) + .replace(/\p{Number}/gu, ""); + } + + function getLocaleThousandSeparator() { + return Intl.NumberFormat(getLocale()) + .format(11111) + .replace(/\p{Number}/gu, ""); + } + + if (text) { + const parsed = parseFloat( + text + .replace(new RegExp("\\" + getLocaleThousandSeparator(), "g"), "") + .replace(new RegExp("\\" + getLocaleDecimalSeperator()), "."), + ); + + if (_.isNaN(parsed)) { + parsed = undefined; + } + + return parsed; + } else { + return undefined; + } + }, + // +}; diff --git a/app/client/src/widgets/CurrencyInputWidget/widget/derived.test.ts b/app/client/src/widgets/CurrencyInputWidget/widget/derived.test.ts new file mode 100644 index 000000000000..4014c07987c7 --- /dev/null +++ b/app/client/src/widgets/CurrencyInputWidget/widget/derived.test.ts @@ -0,0 +1,65 @@ +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(); + }); + }); +}); diff --git a/app/client/src/widgets/CurrencyInputWidget/widget/index.test.tsx b/app/client/src/widgets/CurrencyInputWidget/widget/index.test.tsx new file mode 100644 index 000000000000..383b6dd311d8 --- /dev/null +++ b/app/client/src/widgets/CurrencyInputWidget/widget/index.test.tsx @@ -0,0 +1,43 @@ +import { defaultValueValidation, CurrencyInputWidgetProps } 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: [""], + }); + + result = defaultValueValidation("test", {} as CurrencyInputWidgetProps, _); + + expect(result).toEqual({ + isValid: false, + parsed: undefined, + messages: ["This value must be number"], + }); + + result = defaultValueValidation("", {} as CurrencyInputWidgetProps, _); + + expect(result).toEqual({ + isValid: true, + parsed: undefined, + messages: [""], + }); + }); + + 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: ["This value must be number"], + }); + }); +}); diff --git a/app/client/src/widgets/CurrencyInputWidget/widget/index.tsx b/app/client/src/widgets/CurrencyInputWidget/widget/index.tsx new file mode 100644 index 000000000000..5441dc33b47c --- /dev/null +++ b/app/client/src/widgets/CurrencyInputWidget/widget/index.tsx @@ -0,0 +1,399 @@ +import React from "react"; +import { WidgetState } from "widgets/BaseWidget"; +import { RenderModes, WidgetType } from "constants/WidgetConstants"; +import CurrencyInputComponent, { + CurrencyInputComponentProps, +} from "../component"; +import { + EventType, + ExecutionResult, +} from "constants/AppsmithActionConstants/ActionConstants"; +import { + ValidationTypes, + ValidationResponse, +} from "constants/WidgetValidation"; +import { createMessage, FIELD_REQUIRED_ERROR } from "constants/messages"; +import { DerivedPropertiesMap } from "utils/WidgetFactory"; +import { + CurrencyDropdownOptions, + getCountryCodeFromCurrencyCode, +} from "../component/CurrencyCodeDropdown"; +import { AutocompleteDataType } from "utils/autocomplete/TernServer"; +import _ from "lodash"; +import derivedProperties from "./parsedDerivedProperties"; +import BaseInputWidget from "widgets/BaseInputWidget"; +import { BaseInputWidgetProps } from "widgets/BaseInputWidget/widget"; +import * as Sentry from "@sentry/react"; +import log from "loglevel"; +import { + formatCurrencyNumber, + getLocaleDecimalSeperator, + limitDecimalValue, + parseLocaleFormattedStringToNumber, +} from "../component/utilities"; +import { mergeWidgetConfig } from "utils/helpers"; + +export function defaultValueValidation( + value: any, + props: CurrencyInputWidgetProps, + _?: any, +): ValidationResponse { + const NUMBER_ERROR_MESSAGE = "This value must be number"; + const EMPTY_ERROR_MESSAGE = ""; + if (_.isObject(value)) { + return { + isValid: false, + parsed: JSON.stringify(value, null, 2), + messages: [NUMBER_ERROR_MESSAGE], + }; + } + + let parsed: any = Number(value); + let isValid, messages; + + if (_.isString(value) && value.trim() === "") { + /* + * When value is emtpy string + */ + isValid = true; + messages = [EMPTY_ERROR_MESSAGE]; + parsed = undefined; + } else if (!Number.isFinite(parsed)) { + /* + * When parsed value is not a finite numer + */ + isValid = false; + messages = [NUMBER_ERROR_MESSAGE]; + parsed = undefined; + } else { + /* + * When parsed value is a Number + */ + + // Check whether value is honoring the decimals property + if (parsed !== Number(parsed.toFixed(props.decimals))) { + isValid = false; + messages = [ + "No. of decimals are higher than the decimals field set. Please update the default or the decimals field", + ]; + } else { + isValid = true; + messages = [EMPTY_ERROR_MESSAGE]; + } + + parsed = String(parsed); + } + + return { + isValid, + parsed, + messages, + }; +} + +class CurrencyInputWidget extends BaseInputWidget< + CurrencyInputWidgetProps, + WidgetState +> { + static getPropertyPaneConfig() { + return mergeWidgetConfig( + [ + { + sectionName: "General", + children: [ + { + propertyName: "allowCurrencyChange", + label: "Allow currency change", + helpText: "Search by currency or country", + controlType: "SWITCH", + isJSConvertible: false, + isBindProperty: true, + isTriggerProperty: false, + validation: { type: ValidationTypes.BOOLEAN }, + }, + { + helpText: "Changes the type of currency", + propertyName: "currencyCode", + label: "Currency", + enableSearch: true, + dropdownHeight: "195px", + controlType: "DROP_DOWN", + placeholderText: "Search by code or name", + options: CurrencyDropdownOptions, + isJSConvertible: true, + isBindProperty: true, + isTriggerProperty: false, + validation: { + type: ValidationTypes.TEXT, + }, + }, + { + helpText: "No. of decimals in currency input", + propertyName: "decimals", + label: "Decimals", + controlType: "DROP_DOWN", + options: [ + { + label: "0", + value: 0, + }, + { + label: "1", + value: 1, + }, + { + label: "2", + value: 2, + }, + ], + isBindProperty: false, + isTriggerProperty: false, + }, + { + helpText: + "Sets the default text of the widget. The text is updated if the default text changes", + propertyName: "defaultText", + label: "Default Text", + controlType: "INPUT_TEXT", + placeholderText: "100", + isBindProperty: true, + isTriggerProperty: false, + validation: { + type: ValidationTypes.FUNCTION, + params: { + fn: defaultValueValidation, + expected: { + type: "number", + example: `100`, + autocompleteDataType: AutocompleteDataType.STRING, + }, + }, + }, + dependencies: ["decimals"], + }, + ], + }, + ], + super.getPropertyPaneConfig(), + ); + } + + static getDerivedPropertiesMap(): DerivedPropertiesMap { + return { + isValid: `{{(()=>{${derivedProperties.isValid}})()}}`, + value: `{{(()=>{${derivedProperties.value}})()}}`, + }; + } + + static getMetaPropertiesMap(): Record<string, any> { + return _.merge(super.getMetaPropertiesMap(), { + text: undefined, + }); + } + + componentDidMount() { + //format the defaultText and store it in text + this.formatText(); + } + + componentDidUpdate(prevProps: CurrencyInputWidgetProps) { + if ( + prevProps.text !== this.props.text && + !this.props.isFocused && + this.props.text === String(this.props.defaultText) + ) { + this.formatText(); + } + } + + formatText() { + if (!!this.props.text) { + try { + const formattedValue = formatCurrencyNumber( + this.props.decimals, + String(this.props.value), + ); + this.props.updateWidgetMetaProperty("text", formattedValue); + } catch (e) { + log.error(e); + Sentry.captureException(e); + } + } + } + + onValueChange = (value: string) => { + let formattedValue = ""; + const decimalSeperator = getLocaleDecimalSeperator(); + try { + if (value && value.includes(decimalSeperator)) { + formattedValue = limitDecimalValue(this.props.decimals, value); + } else { + formattedValue = value; + } + } catch (e) { + formattedValue = value; + log.error(e); + Sentry.captureException(e); + } + + // text is stored as what user has typed + this.props.updateWidgetMetaProperty("text", String(formattedValue), { + triggerPropertyName: "onTextChanged", + dynamicString: this.props.onTextChanged, + event: { + type: EventType.ON_TEXT_CHANGE, + }, + }); + + if (!this.props.isDirty) { + this.props.updateWidgetMetaProperty("isDirty", true); + } + }; + + handleFocusChange = (isFocused?: boolean) => { + try { + if (isFocused) { + const deFormattedValue = parseLocaleFormattedStringToNumber( + this.props.text, + ); + this.props.updateWidgetMetaProperty( + "text", + isNaN(deFormattedValue) ? "" : String(deFormattedValue), + ); + } else { + if (this.props.text) { + const formattedValue = formatCurrencyNumber( + this.props.decimals, + String(this.props.value), + ); + this.props.updateWidgetMetaProperty("text", formattedValue); + } + } + } catch (e) { + log.error(e); + Sentry.captureException(e); + this.props.updateWidgetMetaProperty("text", this.props.text); + } + + super.handleFocusChange(!!isFocused); + }; + + onCurrencyTypeChange = (currencyCode?: string) => { + const countryCode = getCountryCodeFromCurrencyCode(currencyCode); + + this.props.updateWidgetMetaProperty("countryCode", countryCode); + + if (this.props.renderMode === RenderModes.CANVAS) { + super.updateWidgetProperty("currencyCode", currencyCode); + } else { + this.props.updateWidgetMetaProperty("currencyCode", currencyCode); + } + }; + + onSubmitSuccess = (result: ExecutionResult) => { + if (result.success && this.props.resetOnSubmit) { + this.props.updateWidgetMetaProperty("text", "", { + triggerPropertyName: "onSubmit", + dynamicString: this.props.onTextChanged, + event: { + type: EventType.ON_TEXT_CHANGE, + }, + }); + } + }; + + handleKeyDown = ( + e: + | React.KeyboardEvent<HTMLTextAreaElement> + | React.KeyboardEvent<HTMLInputElement>, + ) => { + const { isValid, onSubmit } = this.props; + const isEnterKey = e.key === "Enter" || e.keyCode === 13; + if (isEnterKey && onSubmit && isValid) { + super.executeAction({ + triggerPropertyName: "onSubmit", + dynamicString: onSubmit, + event: { + type: EventType.ON_SUBMIT, + callback: this.onSubmitSuccess, + }, + }); + } + }; + + onStep = (direction: number) => { + const value = Number(this.props.value) + direction; + const formattedValue = formatCurrencyNumber( + this.props.decimals, + String(value), + ); + this.props.updateWidgetMetaProperty("text", String(formattedValue), { + triggerPropertyName: "onTextChanged", + dynamicString: this.props.onTextChanged, + event: { + type: EventType.ON_TEXT_CHANGE, + }, + }); + }; + + getPageView() { + const value = this.props.text ?? ""; + const isInvalid = + "isValid" in this.props && !this.props.isValid && !!this.props.isDirty; + const currencyCode = this.props.currencyCode; + const conditionalProps: Partial<CurrencyInputComponentProps> = {}; + conditionalProps.errorMessage = this.props.errorMessage; + if (this.props.isRequired && value.length === 0) { + conditionalProps.errorMessage = createMessage(FIELD_REQUIRED_ERROR); + } + + return ( + <CurrencyInputComponent + allowCurrencyChange={this.props.allowCurrencyChange} + autoFocus={this.props.autoFocus} + compactMode + currencyCode={currencyCode} + decimals={this.props.decimals} + defaultValue={this.props.defaultText} + disableNewLineOnPressEnterKey={!!this.props.onSubmit} + disabled={this.props.isDisabled} + iconAlign={this.props.iconAlign} + iconName={this.props.iconName} + inputType={this.props.inputType} + isInvalid={isInvalid} + isLoading={this.props.isLoading} + label={this.props.label} + labelStyle={this.props.labelStyle} + labelTextColor={this.props.labelTextColor} + labelTextSize={this.props.labelTextSize} + onCurrencyTypeChange={this.onCurrencyTypeChange} + onFocusChange={this.handleFocusChange} + onKeyDown={this.handleKeyDown} + onStep={this.onStep} + onValueChange={this.onValueChange} + placeholder={this.props.placeholderText} + renderMode={this.props.renderMode} + showError={!!this.props.isFocused} + tooltip={this.props.tooltip} + value={value} + widgetId={this.props.widgetId} + {...conditionalProps} + /> + ); + } + + static getWidgetType(): WidgetType { + return "CURRENCY_INPUT_WIDGET"; + } +} + +export interface CurrencyInputWidgetProps extends BaseInputWidgetProps { + countryCode?: string; + currencyCode?: string; + noOfDecimals?: number; + allowCurrencyChange?: boolean; + decimals?: number; + defaultText?: number; +} + +export default CurrencyInputWidget; diff --git a/app/client/src/widgets/CurrencyInputWidget/widget/parsedDerivedProperties.ts b/app/client/src/widgets/CurrencyInputWidget/widget/parsedDerivedProperties.ts new file mode 100644 index 000000000000..8c9e69aae510 --- /dev/null +++ b/app/client/src/widgets/CurrencyInputWidget/widget/parsedDerivedProperties.ts @@ -0,0 +1,34 @@ +// eslint-disable-next-line @typescript-eslint/ban-ts-comment +//@ts-ignore +import widgetPropertyFns from "!!raw-loader!./derived.js"; + +// TODO(abhinav): +// Add unit test cases +// Handle edge cases +// Error out on wrong values +const derivedProperties: any = {}; +// const regex = /(\w+):\s?\(props\)\s?=>\s?{([\w\W]*?)},/gim; +const regex = /(\w+):\s?\(props, moment, _\)\s?=>\s?{([\w\W\n]*?)},\n?\s+?\/\//gim; + +let m; +while ((m = regex.exec(widgetPropertyFns)) !== null) { + // This is necessary to avoid infinite loops with zero-width matches + if (m.index === regex.lastIndex) { + regex.lastIndex++; + } + let key = ""; + // The result can be accessed through the `m`-variable. + m.forEach((match, groupIndex) => { + if (groupIndex === 1) { + key = match; + } + if (groupIndex === 2) { + derivedProperties[key] = match + .trim() + .replace(/\n/g, "") + .replace(/props\./g, "this."); + } + }); +} + +export default derivedProperties; diff --git a/app/client/src/widgets/FormWidget/widget/index.tsx b/app/client/src/widgets/FormWidget/widget/index.tsx index 158cbcd6ed0a..996fa71c73b4 100644 --- a/app/client/src/widgets/FormWidget/widget/index.tsx +++ b/app/client/src/widgets/FormWidget/widget/index.tsx @@ -1,5 +1,5 @@ import React from "react"; -import { get, some, isEqual, isNil } from "lodash"; +import _, { get, some, isEqual } from "lodash"; import { WidgetProps } from "../../BaseWidget"; import { WidgetType } from "constants/WidgetConstants"; import ContainerWidget, { @@ -48,7 +48,7 @@ class FormWidget extends ContainerWidget { const formData: any = {}; if (formWidget.children) formWidget.children.forEach((widgetData) => { - if (!isNil(widgetData.value)) { + if (!_.isNil(widgetData.value)) { formData[widgetData.widgetName] = widgetData.value; } }); diff --git a/app/client/src/widgets/InputWidget/index.ts b/app/client/src/widgets/InputWidget/index.ts index 0f8680fc2029..2bca9c6cebeb 100644 --- a/app/client/src/widgets/InputWidget/index.ts +++ b/app/client/src/widgets/InputWidget/index.ts @@ -7,6 +7,7 @@ export const CONFIG = { name: "Input", iconSVG: IconSVG, needsMeta: true, + hideCard: true, defaults: { inputType: "TEXT", rows: GRID_DENSITY_MIGRATION_V1, diff --git a/app/client/src/widgets/InputWidgetV2/component/index.tsx b/app/client/src/widgets/InputWidgetV2/component/index.tsx new file mode 100644 index 000000000000..2078d11589f3 --- /dev/null +++ b/app/client/src/widgets/InputWidgetV2/component/index.tsx @@ -0,0 +1,88 @@ +import React from "react"; +import BaseInputComponent, { + BaseInputComponentProps, +} from "widgets/BaseInputWidget/component"; +import { InputTypes } from "widgets/BaseInputWidget/constants"; + +const getInputHTMLType = (inputType: InputTypes) => { + switch (inputType) { + case "NUMBER": + return "NUMBER"; + case "TEXT": + return "TEXT"; + case "EMAIL": + return "EMAIL"; + case "PASSWORD": + return "PASSWORD"; + default: + return "TEXT"; + } +}; + +class InputComponent extends React.Component<InputComponentProps> { + onTextChange = ( + event: + | React.ChangeEvent<HTMLInputElement> + | React.ChangeEvent<HTMLTextAreaElement>, + ) => { + this.props.onValueChange(event.target.value); + }; + + getIcon(inputType: InputTypes) { + switch (inputType) { + case "EMAIL": + return "envelope"; + default: + return undefined; + } + } + + render() { + return ( + <BaseInputComponent + allowNumericCharactersOnly={this.props.allowNumericCharactersOnly} + autoFocus={this.props.autoFocus} + compactMode={this.props.compactMode} + defaultValue={this.props.defaultValue} + disableNewLineOnPressEnterKey={this.props.disableNewLineOnPressEnterKey} + disabled={this.props.disabled} + errorMessage={this.props.errorMessage} + fill={this.props.fill} + iconAlign={this.props.iconAlign} + iconName={this.props.iconName} + inputHTMLType={getInputHTMLType(this.props.inputType)} + inputType={this.props.inputType} + intent={this.props.intent} + isInvalid={this.props.isInvalid} + isLoading={this.props.isLoading} + label={this.props.label} + labelStyle={this.props.labelStyle} + labelTextColor={this.props.labelTextColor} + labelTextSize={this.props.labelTextSize} + maxChars={this.props.maxChars} + maxNum={this.props.maxNum} + minNum={this.props.minNum} + multiline={this.props.multiline} + onFocusChange={this.props.onFocusChange} + onKeyDown={this.props.onKeyDown} + onValueChange={this.props.onValueChange} + placeholder={this.props.placeholder} + showError={this.props.showError} + spellCheck={this.props.spellCheck} + stepSize={1} + tooltip={this.props.tooltip} + value={this.props.value} + widgetId={this.props.widgetId} + /> + ); + } +} +export interface InputComponentProps extends BaseInputComponentProps { + inputType: InputTypes; + maxChars?: number; + spellCheck?: boolean; + maxNum?: number; + minNum?: number; +} + +export default InputComponent; diff --git a/app/client/src/widgets/InputWidgetV2/icon.svg b/app/client/src/widgets/InputWidgetV2/icon.svg new file mode 100644 index 000000000000..889009e70e2d --- /dev/null +++ b/app/client/src/widgets/InputWidgetV2/icon.svg @@ -0,0 +1 @@ +<svg fill="none" height="32" viewBox="0 0 32 32" width="32" xmlns="http://www.w3.org/2000/svg"><g fill="#4b4848"><path clip-rule="evenodd" d="m2.66675 8h26.66665v16h-26.66665zm2.66666 13.3333v-10.6666h21.33329v10.6666z" fill-rule="evenodd"/><path d="m6.66675 20v-8h1.33333v8z"/></g></svg> \ No newline at end of file diff --git a/app/client/src/widgets/InputWidgetV2/index.ts b/app/client/src/widgets/InputWidgetV2/index.ts new file mode 100644 index 000000000000..8b0c99c80c05 --- /dev/null +++ b/app/client/src/widgets/InputWidgetV2/index.ts @@ -0,0 +1,24 @@ +import Widget from "./widget"; +import IconSVG from "./icon.svg"; +import { CONFIG as BaseConfig } from "widgets/BaseInputWidget"; + +export const CONFIG = { + type: Widget.getWidgetType(), + name: "Input", + iconSVG: IconSVG, + needsMeta: true, + defaults: { + ...BaseConfig.defaults, + inputType: "TEXT", + widgetName: "Input", + version: 2, + }, + properties: { + derived: Widget.getDerivedPropertiesMap(), + default: Widget.getDefaultPropertiesMap(), + meta: Widget.getMetaPropertiesMap(), + config: Widget.getPropertyPaneConfig(), + }, +}; + +export default Widget; diff --git a/app/client/src/widgets/InputWidgetV2/widget/derived.js b/app/client/src/widgets/InputWidgetV2/widget/derived.js new file mode 100644 index 000000000000..ac4b29418d4a --- /dev/null +++ b/app/client/src/widgets/InputWidgetV2/widget/derived.js @@ -0,0 +1,109 @@ +/* eslint-disable @typescript-eslint/no-unused-vars*/ +export default { + isValid: (props, moment, _) => { + let hasValidValue, value, isEmpty; + switch (props.inputType) { + case "NUMBER": + try { + isEmpty = _.isNil(props.text); + value = Number(props.text); + hasValidValue = Number.isFinite(value); + break; + } catch (e) { + return false; + } + case "TEXT": + case "EMAIL": + case "PASSWORD": + value = props.text; + isEmpty = !value; + hasValidValue = !!value; + break; + default: + value = props.text; + isEmpty = !value; + hasValidValue = !!value; + break; + } + + if (!props.isRequired && isEmpty) { + return true; + } + if (props.isRequired && !hasValidValue) { + return false; + } + + if (typeof props.validation === "boolean" && !props.validation) { + return false; + } + + let parsedRegex = null; + if (props.regex) { + /* + * break up the regexp pattern into 4 parts: given regex, regex prefix , regex pattern, regex flags + * Example /test/i will be split into ["/test/gi", "/", "test", "gi"] + */ + const regexParts = props.regex.match(/(\/?)(.+)\\1([a-z]*)/i); + + if (!regexParts) { + parsedRegex = new RegExp(props.regex); + } else { + /* + * if we don't have a regex flags (gmisuy), convert provided string into regexp directly + */ + if ( + regexParts[3] && + !/^(?!.*?(.).*?\\1)[gmisuy]+$/.test(regexParts[3]) + ) { + parsedRegex = RegExp(props.regex); + } else { + /* + * if we have a regex flags, use it to form regexp + */ + parsedRegex = new RegExp(regexParts[2], regexParts[3]); + } + } + } + switch (props.inputType) { + case "EMAIL": + const emailRegex = new RegExp( + /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/, + ); + if (!emailRegex.test(value)) { + /* email should conform to generic email regex */ + return false; + } else if (parsedRegex) { + /* email should conform to user specified regex */ + return parsedRegex.test(props.text); + } else { + return true; + } + case "TEXT": + case "PASSWORD": + if (parsedRegex) { + return parsedRegex.test(props.text); + } else { + return hasValidValue; + } + case "NUMBER": + if ( + !_.isNil(props.maxNum) && + Number.isFinite(props.maxNum) && + props.maxNum < value + ) { + return false; + } else if ( + !_.isNil(props.minNum) && + Number.isFinite(props.minNum) && + props.minNum > value + ) { + return false; + } else if (parsedRegex) { + return parsedRegex.test(props.text); + } else { + return hasValidValue; + } + } + }, + // +}; diff --git a/app/client/src/widgets/InputWidgetV2/widget/derived.test.ts b/app/client/src/widgets/InputWidgetV2/widget/derived.test.ts new file mode 100644 index 000000000000..661cc67c2456 --- /dev/null +++ b/app/client/src/widgets/InputWidgetV2/widget/derived.test.ts @@ -0,0 +1,403 @@ +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, + text: undefined, + isRequired: false, + }, + null, + _, + ); + + expect(isValid).toBeTruthy(); + + //Number input with required true and invalid value + isValid = derivedProperty.isValid( + { + inputType: InputTypes.NUMBER, + text: "test", + isRequired: true, + }, + null, + _, + ); + + expect(isValid).toBeFalsy(); + + //Number input with required true and valid value + isValid = derivedProperty.isValid( + { + inputType: InputTypes.NUMBER, + text: 1, + isRequired: true, + }, + null, + _, + ); + + expect(isValid).toBeTruthy(); + + //Text input with required false and empty value + isValid = derivedProperty.isValid( + { + inputType: InputTypes.TEXT, + text: "", + isRequired: false, + }, + null, + _, + ); + + expect(isValid).toBeTruthy(); + + //Text input with required true and invalid value + isValid = derivedProperty.isValid( + { + inputType: InputTypes.TEXT, + text: "", + isRequired: true, + }, + null, + _, + ); + + expect(isValid).toBeFalsy(); + + //Text input with required true and valid value + isValid = derivedProperty.isValid( + { + inputType: InputTypes.TEXT, + text: "test", + isRequired: true, + }, + null, + _, + ); + + expect(isValid).toBeTruthy(); + + //Email input with required false and empty value + isValid = derivedProperty.isValid( + { + inputType: InputTypes.EMAIL, + text: "", + isRequired: false, + }, + null, + _, + ); + + expect(isValid).toBeTruthy(); + + //Email input with required true and invalid value + isValid = derivedProperty.isValid( + { + inputType: InputTypes.EMAIL, + text: "", + isRequired: true, + }, + null, + _, + ); + + expect(isValid).toBeFalsy(); + + //Email input with required true and valid value + isValid = derivedProperty.isValid( + { + inputType: InputTypes.EMAIL, + text: "[email protected]", + isRequired: true, + }, + null, + _, + ); + + expect(isValid).toBeTruthy(); + + //Password input with required false and empty value + isValid = derivedProperty.isValid( + { + inputType: InputTypes.PASSWORD, + text: "", + isRequired: false, + }, + null, + _, + ); + + expect(isValid).toBeTruthy(); + + //Password input with required true and invalid value + isValid = derivedProperty.isValid( + { + inputType: InputTypes.PASSWORD, + text: "", + isRequired: true, + }, + null, + _, + ); + + expect(isValid).toBeFalsy(); + + //Password input with required true and valid value + isValid = derivedProperty.isValid( + { + inputType: InputTypes.PASSWORD, + text: "admin", + isRequired: true, + }, + null, + _, + ); + + expect(isValid).toBeTruthy(); + }); + + it("should test validation", () => { + let isValid = derivedProperty.isValid( + { + inputType: InputTypes.TEXT, + text: "test", + isRequired: true, + validation: false, + }, + null, + _, + ); + + expect(isValid).toBeFalsy(); + + isValid = derivedProperty.isValid( + { + inputType: InputTypes.TEXT, + text: "test", + isRequired: true, + validation: true, + }, + null, + _, + ); + + expect(isValid).toBeTruthy(); + + isValid = derivedProperty.isValid( + { + inputType: InputTypes.NUMBER, + text: 1, + isRequired: true, + validation: false, + }, + null, + _, + ); + + expect(isValid).toBeFalsy(); + + isValid = derivedProperty.isValid( + { + inputType: InputTypes.NUMBER, + text: 1, + isRequired: true, + validation: true, + }, + null, + _, + ); + + expect(isValid).toBeTruthy(); + + isValid = derivedProperty.isValid( + { + inputType: InputTypes.EMAIL, + text: "[email protected]", + isRequired: true, + validation: false, + }, + null, + _, + ); + + expect(isValid).toBeFalsy(); + + isValid = derivedProperty.isValid( + { + inputType: InputTypes.EMAIL, + text: "[email protected]", + isRequired: true, + validation: true, + }, + null, + _, + ); + + expect(isValid).toBeTruthy(); + + isValid = derivedProperty.isValid( + { + inputType: InputTypes.PASSWORD, + text: "admin123", + isRequired: true, + validation: false, + }, + null, + _, + ); + + expect(isValid).toBeFalsy(); + + isValid = derivedProperty.isValid( + { + inputType: InputTypes.PASSWORD, + text: "admin123", + isRequired: true, + validation: true, + }, + null, + _, + ); + + expect(isValid).toBeTruthy(); + }); + + it("should test regex validation", () => { + let isValid = derivedProperty.isValid( + { + inputType: InputTypes.TEXT, + text: "test", + isRequired: true, + regex: "^test$", + }, + null, + _, + ); + + expect(isValid).toBeTruthy(); + + isValid = derivedProperty.isValid( + { + inputType: InputTypes.TEXT, + text: "test123", + isRequired: true, + regex: "^test$", + }, + null, + _, + ); + + expect(isValid).toBeFalsy(); + + isValid = derivedProperty.isValid( + { + inputType: InputTypes.NUMBER, + text: 1, + isRequired: true, + regex: "^1$", + }, + null, + _, + ); + + expect(isValid).toBeTruthy(); + + isValid = derivedProperty.isValid( + { + inputType: InputTypes.NUMBER, + text: 2, + isRequired: true, + regex: "^1$", + }, + null, + _, + ); + + expect(isValid).toBeFalsy(); + + isValid = derivedProperty.isValid( + { + inputType: InputTypes.EMAIL, + text: "[email protected]", + isRequired: true, + regex: "^[email protected]$", + }, + null, + _, + ); + + expect(isValid).toBeTruthy(); + + isValid = derivedProperty.isValid( + { + inputType: InputTypes.EMAIL, + text: "[email protected]", + isRequired: true, + regex: "^[email protected]$", + }, + null, + _, + ); + + expect(isValid).toBeFalsy(); + + isValid = derivedProperty.isValid( + { + inputType: InputTypes.PASSWORD, + text: "admin123", + isRequired: true, + regex: "^admin123$", + }, + null, + _, + ); + + expect(isValid).toBeTruthy(); + + isValid = derivedProperty.isValid( + { + inputType: InputTypes.PASSWORD, + text: "admin1234", + isRequired: true, + regex: "^admin123$", + }, + null, + _, + ); + + expect(isValid).toBeFalsy(); + }); + + it("should test email type built in validation", () => { + let isValid = derivedProperty.isValid( + { + inputType: InputTypes.EMAIL, + text: "[email protected]", + isRequired: true, + }, + null, + _, + ); + + expect(isValid).toBeTruthy(); + + isValid = derivedProperty.isValid( + { + inputType: InputTypes.EMAIL, + text: "test", + isRequired: true, + }, + null, + _, + ); + + expect(isValid).toBeFalsy(); + }); + }); +}); diff --git a/app/client/src/widgets/InputWidgetV2/widget/index.test.tsx b/app/client/src/widgets/InputWidgetV2/widget/index.test.tsx new file mode 100644 index 000000000000..6782664c673b --- /dev/null +++ b/app/client/src/widgets/InputWidgetV2/widget/index.test.tsx @@ -0,0 +1,214 @@ +import { + defaultValueValidation, + InputWidgetProps, + 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: [""], + }); + + result = defaultValueValidation( + 1, + { inputType: "TEXT" } as InputWidgetProps, + _, + ); + + expect(result).toEqual({ + isValid: true, + parsed: "1", + messages: [""], + }); + }); + + it("should validate defaulttext of Number type", () => { + result = defaultValueValidation( + 1, + { inputType: "NUMBER" } as InputWidgetProps, + _, + ); + + expect(result).toEqual({ + isValid: true, + parsed: 1, + messages: [""], + }); + + result = defaultValueValidation( + "test", + { inputType: "NUMBER" } as InputWidgetProps, + _, + ); + + expect(result).toEqual({ + isValid: false, + parsed: undefined, + messages: ["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: [""], + }); + + result = defaultValueValidation( + 1, + { inputType: "EMAIL" } as InputWidgetProps, + _, + ); + + expect(result).toEqual({ + isValid: true, + parsed: "1", + messages: [""], + }); + }); + + it("should validate defaulttext of Password type", () => { + result = defaultValueValidation( + "admin123", + { inputType: "PASSWORD" } as InputWidgetProps, + _, + ); + + expect(result).toEqual({ + isValid: true, + parsed: "admin123", + messages: [""], + }); + + result = defaultValueValidation( + 1, + { inputType: "PASSWORD" } as InputWidgetProps, + _, + ); + + expect(result).toEqual({ + isValid: true, + parsed: "1", + messages: [""], + }); + }); + + it("should validate defaulttext with type missing", () => { + result = defaultValueValidation( + "admin123", + ({ inputType: "" } as any) as InputWidgetProps, + _, + ); + + expect(result).toEqual({ + isValid: false, + parsed: "", + messages: ["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: ["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(); + }); +}); diff --git a/app/client/src/widgets/InputWidgetV2/widget/index.tsx b/app/client/src/widgets/InputWidgetV2/widget/index.tsx new file mode 100644 index 000000000000..912e8a319cc6 --- /dev/null +++ b/app/client/src/widgets/InputWidgetV2/widget/index.tsx @@ -0,0 +1,478 @@ +import React from "react"; +import { WidgetState } from "widgets/BaseWidget"; +import { WidgetType } from "constants/WidgetConstants"; +import InputComponent, { InputComponentProps } from "../component"; +import { EventType } from "constants/AppsmithActionConstants/ActionConstants"; +import { + ValidationTypes, + ValidationResponse, +} from "constants/WidgetValidation"; +import { + createMessage, + FIELD_REQUIRED_ERROR, + INPUT_DEFAULT_TEXT_MAX_CHAR_ERROR, +} from "constants/messages"; +import { DerivedPropertiesMap } from "utils/WidgetFactory"; +import { GRID_DENSITY_MIGRATION_V1 } from "widgets/constants"; +import { AutocompleteDataType } from "utils/autocomplete/TernServer"; +import BaseInputWidget from "widgets/BaseInputWidget"; +import _, { isNil } from "lodash"; +import derivedProperties from "./parsedDerivedProperties"; +import { BaseInputWidgetProps } from "widgets/BaseInputWidget/widget"; +import { mergeWidgetConfig } from "utils/helpers"; +import { InputTypes } from "widgets/BaseInputWidget/constants"; + +export function defaultValueValidation( + value: any, + props: InputWidgetProps, + _?: any, +): ValidationResponse { + const STRING_ERROR_MESSAGE = "This value must be string"; + const NUMBER_ERROR_MESSAGE = "This value must be number"; + const EMPTY_ERROR_MESSAGE = ""; + if (_.isObject(value)) { + return { + isValid: false, + parsed: JSON.stringify(value, null, 2), + messages: [STRING_ERROR_MESSAGE], + }; + } + + const { inputType } = props; + let parsed; + switch (inputType) { + case "NUMBER": + parsed = Number(value); + let isValid, messages; + + if (_.isString(value) && value.trim() === "") { + /* + * When value is emtpy string + */ + isValid = true; + messages = [EMPTY_ERROR_MESSAGE]; + parsed = undefined; + } else if (!Number.isFinite(parsed)) { + /* + * When parsed value is not a finite numer + */ + isValid = false; + messages = [NUMBER_ERROR_MESSAGE]; + parsed = undefined; + } else { + /* + * When parsed value is a Number + */ + isValid = true; + messages = [EMPTY_ERROR_MESSAGE]; + } + + return { + isValid, + parsed, + messages, + }; + case "TEXT": + case "PASSWORD": + case "EMAIL": + parsed = value; + if (!_.isString(parsed)) { + try { + parsed = _.toString(parsed); + } catch (e) { + return { + isValid: false, + parsed: "", + messages: [STRING_ERROR_MESSAGE], + }; + } + } + return { + isValid: _.isString(parsed), + parsed: parsed, + messages: [EMPTY_ERROR_MESSAGE], + }; + default: + return { + isValid: false, + parsed: "", + messages: [STRING_ERROR_MESSAGE], + }; + } +} + +export function minValueValidation(min: any, props: InputWidgetProps, _?: any) { + const max = props.maxNum; + const value = min; + min = Number(min); + + if (_?.isNil(value) || value === "") { + return { + isValid: true, + parsed: undefined, + messages: [""], + }; + } else if (!Number.isFinite(min)) { + return { + isValid: false, + parsed: undefined, + messages: ["This value must be number"], + }; + } else if (max !== undefined && min >= max) { + return { + isValid: false, + parsed: undefined, + messages: ["This value must be lesser than max value"], + }; + } else { + return { + isValid: true, + parsed: Number(min), + messages: [""], + }; + } +} + +export function maxValueValidation(max: any, props: InputWidgetProps, _?: any) { + const min = props.minNum; + const value = max; + max = Number(max); + + if (_?.isNil(value) || value === "") { + return { + isValid: true, + parsed: undefined, + messages: [""], + }; + } else if (!Number.isFinite(max)) { + return { + isValid: false, + parsed: undefined, + messages: ["This value must be number"], + }; + } else if (min !== undefined && max <= min) { + return { + isValid: false, + parsed: undefined, + messages: ["This value must be greater than min value"], + }; + } else { + return { + isValid: true, + parsed: Number(max), + messages: [""], + }; + } +} +class InputWidget extends BaseInputWidget<InputWidgetProps, WidgetState> { + static getPropertyPaneConfig() { + return mergeWidgetConfig( + [ + { + sectionName: "General", + children: [ + { + helpText: "Changes the type of data captured in the input", + propertyName: "inputType", + label: "Data Type", + controlType: "DROP_DOWN", + options: [ + { + label: "Text", + value: "TEXT", + }, + { + label: "Number", + value: "NUMBER", + }, + { + label: "Password", + value: "PASSWORD", + }, + { + label: "Email", + value: "EMAIL", + }, + ], + isBindProperty: false, + isTriggerProperty: false, + }, + { + helpText: "Sets maximum allowed text length", + propertyName: "maxChars", + label: "Max Chars", + controlType: "INPUT_TEXT", + placeholderText: "255", + isBindProperty: true, + isTriggerProperty: false, + validation: { + type: ValidationTypes.NUMBER, + params: { + min: 1, + }, + }, + hidden: (props: InputWidgetProps) => { + return props.inputType !== InputTypes.TEXT; + }, + dependencies: ["inputType"], + }, + { + helpText: + "Sets the default text of the widget. The text is updated if the default text changes", + propertyName: "defaultText", + label: "Default Text", + controlType: "INPUT_TEXT", + placeholderText: "John Doe", + isBindProperty: true, + isTriggerProperty: false, + validation: { + type: ValidationTypes.FUNCTION, + params: { + fn: defaultValueValidation, + expected: { + type: "string or number", + example: `John | 123`, + autocompleteDataType: AutocompleteDataType.STRING, + }, + }, + }, + dependencies: ["inputType"], + }, + { + helpText: "Sets the minimum allowed value", + propertyName: "minNum", + label: "Min", + controlType: "INPUT_TEXT", + placeholderText: "1", + isBindProperty: true, + isTriggerProperty: false, + validation: { + type: ValidationTypes.FUNCTION, + params: { + fn: minValueValidation, + expected: { + type: "number", + example: `1`, + autocompleteDataType: AutocompleteDataType.NUMBER, + }, + }, + }, + hidden: (props: InputWidgetProps) => { + return props.inputType !== InputTypes.NUMBER; + }, + dependencies: ["inputType"], + }, + { + helpText: "Sets the maximum allowed value", + propertyName: "maxNum", + label: "Max", + controlType: "INPUT_TEXT", + placeholderText: "100", + isBindProperty: true, + isTriggerProperty: false, + validation: { + type: ValidationTypes.FUNCTION, + params: { + fn: maxValueValidation, + expected: { + type: "number", + example: `100`, + autocompleteDataType: AutocompleteDataType.NUMBER, + }, + }, + }, + hidden: (props: InputWidgetProps) => { + return props.inputType !== InputTypes.NUMBER; + }, + dependencies: ["inputType"], + }, + ], + }, + { + sectionName: "Icon Options", + children: [ + { + propertyName: "iconName", + label: "Icon", + helpText: "Sets the icon to be used in input field", + controlType: "ICON_SELECT", + isBindProperty: false, + isTriggerProperty: false, + validation: { type: ValidationTypes.TEXT }, + }, + { + propertyName: "iconAlign", + label: "Icon alignment", + helpText: "Sets the icon alignment of input field", + controlType: "ICON_ALIGN", + isBindProperty: false, + isTriggerProperty: false, + validation: { type: ValidationTypes.TEXT }, + hidden: (props: InputWidgetProps) => !props.iconName, + dependencies: ["iconName"], + }, + ], + }, + ], + super.getPropertyPaneConfig(), + ); + } + + static getDerivedPropertiesMap(): DerivedPropertiesMap { + return _.merge(super.getDerivedPropertiesMap(), { + isValid: `{{(() => {${derivedProperties.isValid}})()}}`, + }); + } + + static getMetaPropertiesMap(): Record<string, any> { + return super.getMetaPropertiesMap(); + } + + handleFocusChange = (focusState: boolean) => { + super.handleFocusChange(focusState); + }; + + handleKeyDown = ( + e: + | React.KeyboardEvent<HTMLTextAreaElement> + | React.KeyboardEvent<HTMLInputElement>, + ) => { + super.handleKeyDown(e); + }; + + onValueChange = (value: string) => { + let parsedValue; + switch (this.props.inputType) { + case "NUMBER": + try { + if (value === "") { + parsedValue = null; + } else if (value === "-") { + parsedValue = "-"; + } else if (/\.$/.test(value)) { + parsedValue = value; + } else { + parsedValue = Number(value); + + if (isNaN(parsedValue)) { + parsedValue = undefined; + } + } + break; + } catch (e) { + parsedValue = value; + } + break; + case "TEXT": + case "EMAIL": + case "PASSWORD": + parsedValue = value; + break; + } + this.props.updateWidgetMetaProperty("text", parsedValue, { + triggerPropertyName: "onTextChanged", + dynamicString: this.props.onTextChanged, + event: { + type: EventType.ON_TEXT_CHANGE, + }, + }); + if (!this.props.isDirty) { + this.props.updateWidgetMetaProperty("isDirty", true); + } + }; + + getPageView() { + const value = this.props.text ?? ""; + let isInvalid = + "isValid" in this.props && !this.props.isValid && !!this.props.isDirty; + const conditionalProps: Partial<InputComponentProps> = {}; + conditionalProps.errorMessage = this.props.errorMessage; + if (this.props.isRequired && value.length === 0) { + conditionalProps.errorMessage = createMessage(FIELD_REQUIRED_ERROR); + } + + if (!isNil(this.props.maxNum)) { + conditionalProps.maxNum = this.props.maxNum; + } + + if (!isNil(this.props.minNum)) { + conditionalProps.minNum = this.props.minNum; + } + + if (this.props.inputType === "TEXT" && this.props.maxChars) { + // pass maxChars only for Text type inputs, undefined for other types + conditionalProps.maxChars = this.props.maxChars; + if ( + this.props.defaultText && + this.props.defaultText.toString().length > this.props.maxChars + ) { + isInvalid = true; + conditionalProps.errorMessage = createMessage( + INPUT_DEFAULT_TEXT_MAX_CHAR_ERROR, + ); + } + } + const minInputSingleLineHeight = + this.props.label || this.props.tooltip + ? // adjust height for label | tooltip extra div + GRID_DENSITY_MIGRATION_V1 + 4 + : // GRID_DENSITY_MIGRATION_V1 used to adjust code as per new scaled canvas. + GRID_DENSITY_MIGRATION_V1; + + return ( + <InputComponent + autoFocus={this.props.autoFocus} + // show label and Input side by side if true + compactMode={ + !( + (this.props.bottomRow - this.props.topRow) / + GRID_DENSITY_MIGRATION_V1 > + 1 && this.props.inputType === "TEXT" + ) + } + defaultValue={this.props.defaultText} + disableNewLineOnPressEnterKey={!!this.props.onSubmit} + disabled={this.props.isDisabled} + iconAlign={this.props.iconAlign} + iconName={this.props.iconName} + inputType={this.props.inputType} + isInvalid={isInvalid} + isLoading={this.props.isLoading} + label={this.props.label} + labelStyle={this.props.labelStyle} + labelTextColor={this.props.labelTextColor} + labelTextSize={this.props.labelTextSize} + multiline={ + (this.props.bottomRow - this.props.topRow) / + minInputSingleLineHeight > + 1 && this.props.inputType === "TEXT" + } + onFocusChange={this.handleFocusChange} + onKeyDown={this.handleKeyDown} + onValueChange={this.onValueChange} + placeholder={this.props.placeholderText} + showError={!!this.props.isFocused} + spellCheck={!!this.props.isSpellCheck} + stepSize={1} + tooltip={this.props.tooltip} + value={value} + widgetId={this.props.widgetId} + {...conditionalProps} + /> + ); + } + + static getWidgetType(): WidgetType { + return "INPUT_WIDGET_V2"; + } +} + +export interface InputWidgetProps extends BaseInputWidgetProps { + defaultText?: string | number; + maxChars?: number; + isSpellCheck?: boolean; + maxNum?: number; + minNum?: number; +} + +export default InputWidget; diff --git a/app/client/src/widgets/InputWidgetV2/widget/parsedDerivedProperties.ts b/app/client/src/widgets/InputWidgetV2/widget/parsedDerivedProperties.ts new file mode 100644 index 000000000000..8c9e69aae510 --- /dev/null +++ b/app/client/src/widgets/InputWidgetV2/widget/parsedDerivedProperties.ts @@ -0,0 +1,34 @@ +// eslint-disable-next-line @typescript-eslint/ban-ts-comment +//@ts-ignore +import widgetPropertyFns from "!!raw-loader!./derived.js"; + +// TODO(abhinav): +// Add unit test cases +// Handle edge cases +// Error out on wrong values +const derivedProperties: any = {}; +// const regex = /(\w+):\s?\(props\)\s?=>\s?{([\w\W]*?)},/gim; +const regex = /(\w+):\s?\(props, moment, _\)\s?=>\s?{([\w\W\n]*?)},\n?\s+?\/\//gim; + +let m; +while ((m = regex.exec(widgetPropertyFns)) !== null) { + // This is necessary to avoid infinite loops with zero-width matches + if (m.index === regex.lastIndex) { + regex.lastIndex++; + } + let key = ""; + // The result can be accessed through the `m`-variable. + m.forEach((match, groupIndex) => { + if (groupIndex === 1) { + key = match; + } + if (groupIndex === 2) { + derivedProperties[key] = match + .trim() + .replace(/\n/g, "") + .replace(/props\./g, "this."); + } + }); +} + +export default derivedProperties; diff --git a/app/client/src/widgets/PhoneInputWidget/component/ISDCodeDropdown.tsx b/app/client/src/widgets/PhoneInputWidget/component/ISDCodeDropdown.tsx new file mode 100644 index 000000000000..41a628d44ed8 --- /dev/null +++ b/app/client/src/widgets/PhoneInputWidget/component/ISDCodeDropdown.tsx @@ -0,0 +1,163 @@ +import React from "react"; +import styled from "styled-components"; +import Dropdown, { DropdownOption } from "components/ads/Dropdown"; +import Icon, { IconSize } from "components/ads/Icon"; +import { countryToFlag } from "./utilities"; +import { ISDCodeOptions, ISDCodeProps } from "constants/ISDCodes_v2"; +import { Colors } from "constants/Colors"; + +type DropdownTriggerIconWrapperProp = { + allowDialCodeChange: boolean; + disabled?: boolean; +}; + +const DropdownTriggerIconWrapper = styled.div<DropdownTriggerIconWrapperProp>` + padding: 7px; + ${(props) => { + if (props.allowDialCodeChange) { + return ` + width: 92px; + min-width: 92px; + `; + } else { + return ` + width: 84px; + width: 84px; + `; + } + }} + display: flex; + align-items: center; + font-size: 14px; + height: 36px; + line-height: ${(props) => (props.disabled ? 36 : 18)}px; + letter-spacing: -0.24px; + color: #090707; + position: ${(props) => props.disabled && "absolute"}; + z-index: 2; + pointer-events: ${(props) => !props.allowDialCodeChange && "none"}; + + &&& .dropdown { + svg { + width: 14px; + height: 14px; + + path { + fill: ${Colors.GREY_10}; + } + } + } +`; + +const FlagWrapper = styled.span` + font-size: 20px; + line-height: 19px; +`; + +const Code = styled.span` + margin-left: 5px; + width: calc(100% - 40px); +`; + +const StyledIcon = styled(Icon)` + margin-left: 2px; +`; + +const getISDCodeOptions = (): Array<DropdownOption> => { + return ISDCodeOptions.map((item: ISDCodeProps) => { + return { + leftElement: countryToFlag(item.dial_code), + searchText: item.name, + label: `${item.name} (${item.dial_code})`, + value: item.dial_code, + id: item.dial_code, + }; + }); +}; + +export const ISDCodeDropdownOptions = getISDCodeOptions(); + +export const getDefaultISDCode = () => ({ + name: "United States", + dial_code: "+1", + code: "US", +}); + +export const getSelectedISDCode = (dialCode?: string): DropdownOption => { + let selectedCountry: ISDCodeProps | undefined = ISDCodeOptions.find( + (item: ISDCodeProps) => item.dial_code === dialCode, + ); + if (!selectedCountry) { + selectedCountry = getDefaultISDCode(); + } + return { + label: `${selectedCountry.name} (${selectedCountry.dial_code})`, + searchText: selectedCountry.name, + value: selectedCountry.dial_code, + id: selectedCountry.dial_code, + }; +}; + +export const getCountryCode = (dialCode?: string) => { + const option = ISDCodeOptions.find((item: ISDCodeProps) => { + return item.dial_code === dialCode; + }); + + if (option) { + return option.code; + } else { + return ""; + } +}; + +interface ISDCodeDropdownProps { + onISDCodeChange: (code?: string) => void; + options: Array<DropdownOption>; + selected: DropdownOption; + allowCountryCodeChange?: boolean; + disabled: boolean; + allowDialCodeChange: boolean; +} + +export default function ISDCodeDropdown(props: ISDCodeDropdownProps) { + const selectedCountry = getSelectedISDCode(props.selected.value); + const dropdownTrigger = ( + <DropdownTriggerIconWrapper + allowDialCodeChange={props.allowDialCodeChange} + className={`t--input-country-code-change ${ + !props.allowDialCodeChange ? "country-type-trigger" : "" + }`} + disabled={props.disabled} + > + <FlagWrapper> + {selectedCountry.value && countryToFlag(selectedCountry.value)} + </FlagWrapper> + <Code>{selectedCountry.id && selectedCountry.id}</Code> + {props.allowDialCodeChange && ( + <StyledIcon + className="dropdown" + name="down-arrow" + size={IconSize.XXS} + /> + )} + </DropdownTriggerIconWrapper> + ); + if (props.disabled || !props.allowDialCodeChange) { + return dropdownTrigger; + } + return ( + <Dropdown + containerClassName="country-type-filter" + dropdownHeight="139px" + dropdownTriggerIcon={dropdownTrigger} + enableSearch + height="36px" + onSelect={props.onISDCodeChange} + optionWidth="340px" + options={props.options} + searchPlaceholder="Search by ISD code or country" + selected={props.selected} + showLabelOnly + /> + ); +} diff --git a/app/client/src/widgets/PhoneInputWidget/component/index.tsx b/app/client/src/widgets/PhoneInputWidget/component/index.tsx new file mode 100644 index 000000000000..cc20b23b32f0 --- /dev/null +++ b/app/client/src/widgets/PhoneInputWidget/component/index.tsx @@ -0,0 +1,93 @@ +import React from "react"; +import ISDCodeDropdown, { + ISDCodeDropdownOptions, + getSelectedISDCode, +} from "./ISDCodeDropdown"; +import BaseInputComponent, { + BaseInputComponentProps, +} from "widgets/BaseInputWidget/component"; +import { CountryCode } from "libphonenumber-js"; +import { InputTypes } from "widgets/BaseInputWidget/constants"; + +class PhoneInputComponent extends React.Component<PhoneInputComponentProps> { + onTextChange = ( + event: + | React.ChangeEvent<HTMLInputElement> + | React.ChangeEvent<HTMLTextAreaElement>, + ) => { + this.props.onValueChange(event.target.value); + }; + + getLeftIcon = () => { + const selectedISDCode = getSelectedISDCode(this.props.dialCode); + return ( + <ISDCodeDropdown + allowDialCodeChange={this.props.allowDialCodeChange} + disabled={!!this.props.disabled} + onISDCodeChange={this.props.onISDCodeChange} + options={ISDCodeDropdownOptions} + selected={selectedISDCode} + /> + ); + }; + + onKeyDown = ( + e: + | React.KeyboardEvent<HTMLTextAreaElement> + | React.KeyboardEvent<HTMLInputElement>, + ) => { + if (typeof this.props.onKeyDown === "function") { + this.props.onKeyDown(e); + } + }; + + componentDidMount() { + if (this.props.dialCode) { + this.props.onISDCodeChange(this.props.dialCode); + } + } + + render() { + return ( + <BaseInputComponent + autoFocus={this.props.autoFocus} + compactMode={this.props.compactMode} + defaultValue={this.props.defaultValue} + disableNewLineOnPressEnterKey={this.props.disableNewLineOnPressEnterKey} + disabled={this.props.disabled} + errorMessage={this.props.errorMessage} + fill={this.props.fill} + iconAlign={this.props.iconAlign} + iconName={this.props.iconName} + inputHTMLType="TEL" + inputType={InputTypes.PHONE_NUMBER} + intent={this.props.intent} + isInvalid={this.props.isInvalid} + isLoading={this.props.isLoading} + label={this.props.label} + labelStyle={this.props.labelStyle} + labelTextColor={this.props.labelTextColor} + labelTextSize={this.props.labelTextSize} + leftIcon={this.getLeftIcon()} + multiline={false} + onFocusChange={this.props.onFocusChange} + onKeyDown={this.onKeyDown} + onValueChange={this.props.onValueChange} + placeholder={this.props.placeholder} + showError={this.props.showError} + tooltip={this.props.tooltip} + value={this.props.value} + widgetId={this.props.widgetId} + /> + ); + } +} + +export interface PhoneInputComponentProps extends BaseInputComponentProps { + dialCode?: string; + countryCode?: CountryCode; + onISDCodeChange: (code?: string) => void; + allowDialCodeChange: boolean; +} + +export default PhoneInputComponent; diff --git a/app/client/src/widgets/PhoneInputWidget/component/utilities.test.ts b/app/client/src/widgets/PhoneInputWidget/component/utilities.test.ts new file mode 100644 index 000000000000..c06874ef0841 --- /dev/null +++ b/app/client/src/widgets/PhoneInputWidget/component/utilities.test.ts @@ -0,0 +1,13 @@ +import { countryToFlag } from "./utilities"; + +describe("Utilities - ", () => { + it("should test countryToFlag", () => { + [ + ["+91", "🇮🇳"], + ["+1", "🇺🇸"], + ["", ""], + ].forEach((d) => { + expect(countryToFlag(d[0])).toBe(d[1]); + }); + }); +}); diff --git a/app/client/src/widgets/PhoneInputWidget/component/utilities.ts b/app/client/src/widgets/PhoneInputWidget/component/utilities.ts new file mode 100644 index 000000000000..dd5ec9113d78 --- /dev/null +++ b/app/client/src/widgets/PhoneInputWidget/component/utilities.ts @@ -0,0 +1,13 @@ +import { ISDCodeOptions } from "constants/ISDCodes_v2"; + +export const countryToFlag = (dialCode: string) => { + const country = ISDCodeOptions.find((item) => item.dial_code === dialCode); + const isoCode = country ? country.code : ""; + return typeof String.fromCodePoint !== "undefined" + ? isoCode + .toUpperCase() + .replace(/./g, (char) => + String.fromCodePoint(char.charCodeAt(0) + 127397), + ) + : isoCode; +}; diff --git a/app/client/src/widgets/PhoneInputWidget/icon.svg b/app/client/src/widgets/PhoneInputWidget/icon.svg new file mode 100644 index 000000000000..a3e9f68b0c7c --- /dev/null +++ b/app/client/src/widgets/PhoneInputWidget/icon.svg @@ -0,0 +1,4 @@ +<svg width="20" height="12" viewBox="0 0 20 12" fill="none" xmlns="http://www.w3.org/2000/svg"> +<path fill-rule="evenodd" clip-rule="evenodd" d="M0 0H20V12H0V0ZM2 10V2H18V10H2Z" fill="#4B4848"/> +<path d="M4.5915 5.6705C4.82608 6.08262 5.16738 6.42392 5.5795 6.6585L5.8005 6.349C5.83604 6.29923 5.88859 6.26422 5.9482 6.25058C6.00781 6.23695 6.07036 6.24563 6.124 6.275C6.47758 6.46823 6.86805 6.58444 7.26975 6.616C7.33244 6.62097 7.39096 6.64938 7.43364 6.69558C7.47631 6.74178 7.50001 6.80236 7.5 6.86525V7.98075C7.50001 8.04265 7.47706 8.10235 7.43559 8.1483C7.39412 8.19425 7.33708 8.22319 7.2755 8.2295C7.143 8.24325 7.0095 8.25 6.875 8.25C4.735 8.25 3 6.515 3 4.375C3 4.2405 3.00675 4.107 3.0205 3.9745C3.02681 3.91292 3.05575 3.85588 3.1017 3.81441C3.14765 3.77294 3.20735 3.74999 3.26925 3.75H4.38475C4.44764 3.74999 4.50822 3.77369 4.55442 3.81636C4.60062 3.85904 4.62903 3.91756 4.634 3.98025C4.66556 4.38195 4.78177 4.77242 4.975 5.126C5.00437 5.17964 5.01305 5.24219 4.99942 5.3018C4.98578 5.36141 4.95077 5.41396 4.901 5.4495L4.5915 5.6705ZM3.961 5.50625L4.436 5.167C4.3012 4.87602 4.20884 4.56721 4.16175 4.25H3.5025C3.501 4.2915 3.50025 4.33325 3.50025 4.375C3.5 6.239 5.011 7.75 6.875 7.75C6.91675 7.75 6.9585 7.74925 7 7.7475V7.08825C6.68279 7.04116 6.37398 6.9488 6.083 6.814L5.74375 7.289C5.60717 7.23593 5.4745 7.17327 5.34675 7.1015L5.33225 7.09325C4.84189 6.81418 4.43582 6.40811 4.15675 5.91775L4.1485 5.90325C4.07673 5.7755 4.01407 5.64283 3.961 5.50625Z" fill="#4B4848"/> +</svg> \ No newline at end of file diff --git a/app/client/src/widgets/PhoneInputWidget/index.ts b/app/client/src/widgets/PhoneInputWidget/index.ts new file mode 100644 index 000000000000..c9971be076fd --- /dev/null +++ b/app/client/src/widgets/PhoneInputWidget/index.ts @@ -0,0 +1,26 @@ +import Widget from "./widget"; +import IconSVG from "./icon.svg"; +import { CONFIG as BaseConfig } from "widgets/BaseInputWidget"; +import { getDefaultISDCode } from "./component/ISDCodeDropdown"; + +export const CONFIG = { + type: Widget.getWidgetType(), + name: "Phone Input", + iconSVG: IconSVG, + needsMeta: true, + defaults: { + ...BaseConfig.defaults, + widgetName: "PhoneInput", + version: 1, + dialCode: getDefaultISDCode().dial_code, + allowDialCodeChange: false, + }, + properties: { + derived: Widget.getDerivedPropertiesMap(), + default: Widget.getDefaultPropertiesMap(), + meta: Widget.getMetaPropertiesMap(), + config: Widget.getPropertyPaneConfig(), + }, +}; + +export default Widget; diff --git a/app/client/src/widgets/PhoneInputWidget/widget/derived.js b/app/client/src/widgets/PhoneInputWidget/widget/derived.js new file mode 100644 index 000000000000..d133704d8a43 --- /dev/null +++ b/app/client/src/widgets/PhoneInputWidget/widget/derived.js @@ -0,0 +1,51 @@ +/* eslint-disable @typescript-eslint/no-unused-vars*/ +export default { + isValid: (props, moment, _) => { + let hasValidValue, value; + value = props.text; + hasValidValue = !!value; + + if (!props.isRequired && (props.text === "" || props.text === undefined)) { + return true; + } + if (props.isRequired && !hasValidValue) { + return false; + } + + if (typeof props.validation === "boolean" && !props.validation) { + return false; + } + + let parsedRegex = null; + if (props.regex) { + /* + * break up the regexp pattern into 4 parts: given regex, regex prefix , regex pattern, regex flags + * Example /test/i will be split into ["/test/gi", "/", "test", "gi"] + */ + const regexParts = props.regex.match(/(\/?)(.+)\\1([a-z]*)/i); + + if (!regexParts) { + parsedRegex = new RegExp(props.regex); + } else { + if ( + regexParts[3] && + !/^(?!.*?(.).*?\\1)[gmisuy]+$/.test(regexParts[3]) + ) { + parsedRegex = RegExp(props.regex); + } else { + /* + * if we have a regex flags, use it to form regexp + */ + parsedRegex = new RegExp(regexParts[2], regexParts[3]); + } + } + } + + if (parsedRegex) { + return parsedRegex.test(props.text); + } else { + return hasValidValue; + } + }, + // +}; diff --git a/app/client/src/widgets/PhoneInputWidget/widget/derived.test.ts b/app/client/src/widgets/PhoneInputWidget/widget/derived.test.ts new file mode 100644 index 000000000000..ece653913f0b --- /dev/null +++ b/app/client/src/widgets/PhoneInputWidget/widget/derived.test.ts @@ -0,0 +1,65 @@ +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(); + }); + }); +}); diff --git a/app/client/src/widgets/PhoneInputWidget/widget/index.test.tsx b/app/client/src/widgets/PhoneInputWidget/widget/index.test.tsx new file mode 100644 index 000000000000..c146ca966f78 --- /dev/null +++ b/app/client/src/widgets/PhoneInputWidget/widget/index.test.tsx @@ -0,0 +1,31 @@ +import { defaultValueValidation, PhoneInputWidgetProps } 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: [""], + }); + }); + + 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: ["This value must be string"], + }); + }); +}); diff --git a/app/client/src/widgets/PhoneInputWidget/widget/index.tsx b/app/client/src/widgets/PhoneInputWidget/widget/index.tsx new file mode 100644 index 000000000000..c2068422915b --- /dev/null +++ b/app/client/src/widgets/PhoneInputWidget/widget/index.tsx @@ -0,0 +1,270 @@ +import React from "react"; +import { WidgetState } from "widgets/BaseWidget"; +import { RenderModes, WidgetType } from "constants/WidgetConstants"; +import PhoneInputComponent, { PhoneInputComponentProps } from "../component"; +import { EventType } from "constants/AppsmithActionConstants/ActionConstants"; +import { + ValidationTypes, + ValidationResponse, +} from "constants/WidgetValidation"; +import { createMessage, FIELD_REQUIRED_ERROR } from "constants/messages"; +import { DerivedPropertiesMap } from "utils/WidgetFactory"; +import { + getCountryCode, + ISDCodeDropdownOptions, +} from "../component/ISDCodeDropdown"; +import { AutocompleteDataType } from "utils/autocomplete/TernServer"; +import _ from "lodash"; +import BaseInputWidget from "widgets/BaseInputWidget"; +import derivedProperties from "./parsedDerivedProperties"; +import { BaseInputWidgetProps } from "widgets/BaseInputWidget/widget"; +import { mergeWidgetConfig } from "utils/helpers"; +import { AsYouType, CountryCode } from "libphonenumber-js"; +import * as Sentry from "@sentry/react"; +import log from "loglevel"; + +export function defaultValueValidation( + value: any, + props: PhoneInputWidgetProps, + _?: any, +): ValidationResponse { + const STRING_ERROR_MESSAGE = "This value must be string"; + const EMPTY_ERROR_MESSAGE = ""; + if (_.isObject(value)) { + return { + isValid: false, + parsed: JSON.stringify(value, null, 2), + messages: [STRING_ERROR_MESSAGE], + }; + } + let parsed = value; + if (!_.isString(value)) { + try { + parsed = _.toString(value); + } catch (e) { + return { + isValid: false, + parsed: "", + messages: [STRING_ERROR_MESSAGE], + }; + } + } + return { + isValid: _.isString(parsed), + parsed: parsed, + messages: [EMPTY_ERROR_MESSAGE], + }; +} + +class PhoneInputWidget extends BaseInputWidget< + PhoneInputWidgetProps, + WidgetState +> { + static getPropertyPaneConfig() { + return mergeWidgetConfig( + [ + { + sectionName: "General", + children: [ + { + propertyName: "allowDialCodeChange", + label: "Allow country code change", + helpText: "Search by country", + controlType: "SWITCH", + isJSConvertible: false, + isBindProperty: true, + isTriggerProperty: false, + validation: { type: ValidationTypes.BOOLEAN }, + }, + { + helpText: "Changes the country code", + propertyName: "dialCode", + label: "Default Country Code", + enableSearch: true, + dropdownHeight: "195px", + controlType: "DROP_DOWN", + placeholderText: "Search by code or country name", + options: ISDCodeDropdownOptions, + isJSConvertible: true, + isBindProperty: true, + isTriggerProperty: false, + validation: { + type: ValidationTypes.TEXT, + }, + }, + { + helpText: + "Sets the default text of the widget. The text is updated if the default text changes", + propertyName: "defaultText", + label: "Default Text", + controlType: "INPUT_TEXT", + placeholderText: "John Doe", + isBindProperty: true, + isTriggerProperty: false, + validation: { + type: ValidationTypes.FUNCTION, + params: { + fn: defaultValueValidation, + expected: { + type: "string", + example: `000 0000`, + autocompleteDataType: AutocompleteDataType.STRING, + }, + }, + }, + }, + ], + }, + ], + super.getPropertyPaneConfig(), + ); + } + + static getDerivedPropertiesMap(): DerivedPropertiesMap { + return _.merge(super.getDerivedPropertiesMap(), { + isValid: `{{(() => {${derivedProperties.isValid}})()}}`, + }); + } + + static getMetaPropertiesMap(): Record<string, any> { + return _.merge(super.getMetaPropertiesMap()); + } + + componentDidMount() { + //format the defaultText and store it in text + if (!!this.props.text) { + try { + const dialCode = this.props.dialCode || "+1"; + const countryCode = getCountryCode(dialCode); + const value = this.props.text; + const parsedValue: string = new AsYouType( + countryCode as CountryCode, + ).input(value); + this.props.updateWidgetMetaProperty("text", parsedValue); + } catch (e) { + log.error(e); + Sentry.captureException(e); + } + } + } + + componentDidUpdate(prevProps: PhoneInputWidgetProps) { + if ( + this.props.renderMode === RenderModes.CANVAS && + prevProps.dialCode !== this.props.dialCode + ) { + this.onISDCodeChange(this.props.dialCode); + } + } + + onISDCodeChange = (dialCode?: string) => { + const countryCode = getCountryCode(dialCode); + + if (this.props.renderMode === RenderModes.CANVAS) { + super.updateWidgetProperty("dialCode", dialCode); + super.updateWidgetProperty("countryCode", countryCode); + } else { + this.props.updateWidgetMetaProperty("dialCode", dialCode); + this.props.updateWidgetMetaProperty("countryCode", countryCode); + } + + if (this.props.text) { + const parsedValue: string = new AsYouType( + countryCode as CountryCode, + ).input(this.props.text); + this.props.updateWidgetMetaProperty("text", parsedValue); + } + }; + + onValueChange = (value: string) => { + const countryCode = this.props.countryCode || "US"; + let parsedValue: string; + + // Don't format as value is typed when user is deleting + if (value.length > this.props.text.length) { + parsedValue = new AsYouType(countryCode).input(value); + } else { + parsedValue = value; + } + + this.props.updateWidgetMetaProperty("text", parsedValue, { + triggerPropertyName: "onTextChanged", + dynamicString: this.props.onTextChanged, + event: { + type: EventType.ON_TEXT_CHANGE, + }, + }); + if (!this.props.isDirty) { + this.props.updateWidgetMetaProperty("isDirty", true); + } + }; + + handleFocusChange = (focusState: boolean) => { + super.handleFocusChange(focusState); + }; + + handleKeyDown = ( + e: + | React.KeyboardEvent<HTMLTextAreaElement> + | React.KeyboardEvent<HTMLInputElement>, + ) => { + super.handleKeyDown(e); + }; + + getPageView() { + const value = this.props.text ?? ""; + const isInvalid = + "isValid" in this.props && !this.props.isValid && !!this.props.isDirty; + const countryCode = this.props.countryCode; + const conditionalProps: Partial<PhoneInputComponentProps> = {}; + conditionalProps.errorMessage = this.props.errorMessage; + if (this.props.isRequired && value.length === 0) { + conditionalProps.errorMessage = createMessage(FIELD_REQUIRED_ERROR); + } + + return ( + <PhoneInputComponent + allowDialCodeChange={this.props.allowDialCodeChange} + autoFocus={this.props.autoFocus} + compactMode + countryCode={countryCode} + defaultValue={this.props.defaultText} + dialCode={this.props.dialCode} + disableNewLineOnPressEnterKey={!!this.props.onSubmit} + disabled={this.props.isDisabled} + iconAlign={this.props.iconAlign} + iconName={this.props.iconName} + inputType={this.props.inputType} + isInvalid={isInvalid} + isLoading={this.props.isLoading} + label={this.props.label} + labelStyle={this.props.labelStyle} + labelTextColor={this.props.labelTextColor} + labelTextSize={this.props.labelTextSize} + onFocusChange={this.handleFocusChange} + onISDCodeChange={this.onISDCodeChange} + onKeyDown={this.handleKeyDown} + onValueChange={this.onValueChange} + placeholder={this.props.placeholderText} + showError={!!this.props.isFocused} + tooltip={this.props.tooltip} + value={value} + widgetId={this.props.widgetId} + {...conditionalProps} + /> + ); + } + + static getWidgetType(): WidgetType { + return "PHONE_INPUT_WIDGET"; + } +} + +export interface PhoneInputWidgetProps extends BaseInputWidgetProps { + dialCode?: string; + countryCode?: CountryCode; + defaultText?: string; + allowDialCodeChange: boolean; +} + +export default PhoneInputWidget; diff --git a/app/client/src/widgets/PhoneInputWidget/widget/parsedDerivedProperties.ts b/app/client/src/widgets/PhoneInputWidget/widget/parsedDerivedProperties.ts new file mode 100644 index 000000000000..8c9e69aae510 --- /dev/null +++ b/app/client/src/widgets/PhoneInputWidget/widget/parsedDerivedProperties.ts @@ -0,0 +1,34 @@ +// eslint-disable-next-line @typescript-eslint/ban-ts-comment +//@ts-ignore +import widgetPropertyFns from "!!raw-loader!./derived.js"; + +// TODO(abhinav): +// Add unit test cases +// Handle edge cases +// Error out on wrong values +const derivedProperties: any = {}; +// const regex = /(\w+):\s?\(props\)\s?=>\s?{([\w\W]*?)},/gim; +const regex = /(\w+):\s?\(props, moment, _\)\s?=>\s?{([\w\W\n]*?)},\n?\s+?\/\//gim; + +let m; +while ((m = regex.exec(widgetPropertyFns)) !== null) { + // This is necessary to avoid infinite loops with zero-width matches + if (m.index === regex.lastIndex) { + regex.lastIndex++; + } + let key = ""; + // The result can be accessed through the `m`-variable. + m.forEach((match, groupIndex) => { + if (groupIndex === 1) { + key = match; + } + if (groupIndex === 2) { + derivedProperties[key] = match + .trim() + .replace(/\n/g, "") + .replace(/props\./g, "this."); + } + }); +} + +export default derivedProperties; diff --git a/app/client/src/widgets/TabsWidget/widget/index.test.tsx b/app/client/src/widgets/TabsWidget/widget/index.test.tsx index fff9f140c45d..646b6b1a23a5 100644 --- a/app/client/src/widgets/TabsWidget/widget/index.test.tsx +++ b/app/client/src/widgets/TabsWidget/widget/index.test.tsx @@ -30,7 +30,7 @@ describe("Tabs widget functional cases", () => { { type: "CHECKBOX_WIDGET", label: "Tab1 Checkbox" }, ]); const tab2Children = buildChildren([ - { type: "INPUT_WIDGET", text: "Tab2 Text" }, + { type: "INPUT_WIDGET_V2", text: "Tab2 Text" }, { type: "BUTTON_WIDGET", label: "Tab2 Button" }, ]); const children: any = buildChildren([{ type: "TABS_WIDGET" }]); diff --git a/app/client/src/workers/evaluate.test.ts b/app/client/src/workers/evaluate.test.ts index 79fb7a14cfd5..a34cbcf116bc 100644 --- a/app/client/src/workers/evaluate.test.ts +++ b/app/client/src/workers/evaluate.test.ts @@ -20,7 +20,7 @@ describe("evaluateSync", () => { renderMode: RenderModes.CANVAS, rightColumn: 0, topRow: 0, - type: "INPUT_WIDGET", + type: "INPUT_WIDGET_V2", version: 0, widgetId: "", widgetName: "", diff --git a/app/client/src/workers/evaluation.test.ts b/app/client/src/workers/evaluation.test.ts index fcc31201e0fb..36f1821a097e 100644 --- a/app/client/src/workers/evaluation.test.ts +++ b/app/client/src/workers/evaluation.test.ts @@ -28,7 +28,7 @@ const WIDGET_CONFIG_MAP: WidgetTypeConfigMap = { derivedProperties: {}, metaProperties: {}, }, - INPUT_WIDGET: { + INPUT_WIDGET_V2: { defaultProperties: { text: "defaultText", }, @@ -440,7 +440,7 @@ describe("DataTreeEvaluator", () => { text: undefined, defaultText: "Default value", widgetName: "Input1", - type: "INPUT_WIDGET", + type: "INPUT_WIDGET_V2", bindingPaths: { defaultText: EvaluationSubstitutionType.TEMPLATE, isValid: EvaluationSubstitutionType.TEMPLATE, diff --git a/app/client/test/factories/Widgets/InputFactory.ts b/app/client/test/factories/Widgets/InputFactory.ts index ddf4ffd251cd..75626b582f23 100644 --- a/app/client/test/factories/Widgets/InputFactory.ts +++ b/app/client/test/factories/Widgets/InputFactory.ts @@ -13,7 +13,7 @@ export const InputFactory = Factory.Sync.makeFactory<WidgetProps>({ parentRowSpace: 38, isVisible: true, label: "Test Input Label", - type: "INPUT_WIDGET", + type: "INPUT_WIDGET_V2", dynamicBindingPathList: [], parentId: "iw4o07jvik", isLoading: false, diff --git a/app/client/test/factories/Widgets/WidgetTypeFactories.ts b/app/client/test/factories/Widgets/WidgetTypeFactories.ts index 96217a72520f..1bf4b72f5de3 100644 --- a/app/client/test/factories/Widgets/WidgetTypeFactories.ts +++ b/app/client/test/factories/Widgets/WidgetTypeFactories.ts @@ -29,7 +29,7 @@ export const WidgetTypeFactories: Record<string, any> = { BUTTON_WIDGET: ButtonFactory, TEXT_WIDGET: TextFactory, IMAGE_WIDGET: ImageFactory, - INPUT_WIDGET: InputFactory, + INPUT_WIDGET_V2: InputFactory, CONTAINER_WIDGET: ContainerFactory, DATE_PICKER_WIDGET: OldDatepickerFactory, DATE_PICKER_WIDGET2: DatepickerFactory, diff --git a/app/client/yarn.lock b/app/client/yarn.lock index 1aa33f230d5d..22ac97a8a1db 100644 --- a/app/client/yarn.lock +++ b/app/client/yarn.lock @@ -10527,6 +10527,11 @@ lib0@^0.2.41: dependencies: isomorphic.js "^0.2.4" +libphonenumber-js@^1.9.44: + version "1.9.44" + resolved "https://registry.yarnpkg.com/libphonenumber-js/-/libphonenumber-js-1.9.44.tgz#d036364fe4c1e27205d1d283c7bf8fc25625200b" + integrity sha512-zhw8nUMJuQf7jG1dZfEOKKOS6M3QYIv3HnvB/vGohNd0QfxIQcObH3a6Y6s350H+9xgBeOXClOJkS0hJ0yvS3g== + [email protected]: version "3.1.1" resolved "https://registry.npmjs.org/lie/-/lie-3.1.1.tgz"
f473da619717d73d51e9f21d38912b2109e4e11d
2024-05-30 10:09:04
NandanAnantharamu
test: remove startRoutesForDatasource from commands (#33688)
false
remove startRoutesForDatasource from commands (#33688)
test
diff --git a/app/client/cypress/e2e/Regression/ClientSide/Binding/JSObject_Postgress_Table_spec.js b/app/client/cypress/e2e/Regression/ClientSide/Binding/JSObject_Postgress_Table_spec.js index 5322bdf4401b..16fe89c8c6e5 100644 --- a/app/client/cypress/e2e/Regression/ClientSide/Binding/JSObject_Postgress_Table_spec.js +++ b/app/client/cypress/e2e/Regression/ClientSide/Binding/JSObject_Postgress_Table_spec.js @@ -13,7 +13,7 @@ describe( { tags: ["@tag.Binding"] }, function () { beforeEach(() => { - cy.startRoutesForDatasource(); + _.dataSources.StartDataSourceRoutes(); }); it("1. Create a query and populate response by choosing addWidget and validate in Table Widget & Bug 7413", () => { diff --git a/app/client/cypress/e2e/Regression/ClientSide/ExplorerTests/CopyQuery_RenameDatasource_spec.js b/app/client/cypress/e2e/Regression/ClientSide/ExplorerTests/CopyQuery_RenameDatasource_spec.js index 40727f264d94..e38696d62478 100644 --- a/app/client/cypress/e2e/Regression/ClientSide/ExplorerTests/CopyQuery_RenameDatasource_spec.js +++ b/app/client/cypress/e2e/Regression/ClientSide/ExplorerTests/CopyQuery_RenameDatasource_spec.js @@ -19,15 +19,9 @@ describe( { tags: ["@tag.IDE"] }, function () { beforeEach(() => { - cy.startRoutesForDatasource(); + dataSources.StartDataSourceRoutes(); }); - // afterEach(function() { - // if (this.currentTest.state === "failed") { - // Cypress.runner.stop(); - // } - // }); - it("1. Create a query with dataSource in explorer, Create new Page", function () { cy.Createpage(pageid); EditorNavigation.SelectEntityByName("Page1", EntityType.Page); diff --git a/app/client/cypress/e2e/Regression/ClientSide/ExplorerTests/Query_Datasource_spec.js b/app/client/cypress/e2e/Regression/ClientSide/ExplorerTests/Query_Datasource_spec.js index 1968885bfa0f..4b12f336818c 100644 --- a/app/client/cypress/e2e/Regression/ClientSide/ExplorerTests/Query_Datasource_spec.js +++ b/app/client/cypress/e2e/Regression/ClientSide/ExplorerTests/Query_Datasource_spec.js @@ -26,7 +26,7 @@ describe( }); beforeEach(() => { - cy.startRoutesForDatasource(); + dataSources.StartDataSourceRoutes(); }); it("1. Create a page/moveQuery/rename/delete in explorer", function () { diff --git a/app/client/cypress/e2e/Regression/ClientSide/OtherUIFeatures/GlobalSearch_spec.js b/app/client/cypress/e2e/Regression/ClientSide/OtherUIFeatures/GlobalSearch_spec.js index 183127369762..80ed386debd9 100644 --- a/app/client/cypress/e2e/Regression/ClientSide/OtherUIFeatures/GlobalSearch_spec.js +++ b/app/client/cypress/e2e/Regression/ClientSide/OtherUIFeatures/GlobalSearch_spec.js @@ -19,7 +19,7 @@ describe("GlobalSearch", function () { }); beforeEach(() => { - cy.startRoutesForDatasource(); + _.dataSources.StartDataSourceRoutes(); }); it("1. Shows And Hides Using Keyboard Shortcuts", () => { diff --git a/app/client/cypress/e2e/Regression/ServerSide/GenerateCRUD/S3_Spec.js b/app/client/cypress/e2e/Regression/ServerSide/GenerateCRUD/S3_Spec.js index 7023f81a57d2..ab6851b32491 100644 --- a/app/client/cypress/e2e/Regression/ServerSide/GenerateCRUD/S3_Spec.js +++ b/app/client/cypress/e2e/Regression/ServerSide/GenerateCRUD/S3_Spec.js @@ -21,7 +21,7 @@ describe( let datasourceName; beforeEach(() => { - cy.startRoutesForDatasource(); + dataSources.StartDataSourceRoutes(); cy.startInterceptRoutesForS3(); }); diff --git a/app/client/cypress/e2e/Regression/ServerSide/Params/ExecutionParams_spec.js b/app/client/cypress/e2e/Regression/ServerSide/Params/ExecutionParams_spec.js index f526610daeb8..25326fee045f 100644 --- a/app/client/cypress/e2e/Regression/ServerSide/Params/ExecutionParams_spec.js +++ b/app/client/cypress/e2e/Regression/ServerSide/Params/ExecutionParams_spec.js @@ -20,7 +20,7 @@ describe( agHelper.AddDsl("executionParamsDsl"); }); beforeEach(() => { - cy.startRoutesForDatasource(); + dataSources.StartDataSourceRoutes(); }); it("1. Create a postgres datasource", function () { cy.NavigateToDatasourceEditor(); diff --git a/app/client/cypress/e2e/Regression/ServerSide/QueryPane/AddWidgetTableAndBind_spec.js b/app/client/cypress/e2e/Regression/ServerSide/QueryPane/AddWidgetTableAndBind_spec.js index 70eb8d0330a9..db112e9af8c0 100644 --- a/app/client/cypress/e2e/Regression/ServerSide/QueryPane/AddWidgetTableAndBind_spec.js +++ b/app/client/cypress/e2e/Regression/ServerSide/QueryPane/AddWidgetTableAndBind_spec.js @@ -22,7 +22,7 @@ describe( }); beforeEach(() => { - cy.startRoutesForDatasource(); + dataSources.StartDataSourceRoutes(); }); it("1. Create a PostgresDataSource", () => { diff --git a/app/client/cypress/e2e/Regression/ServerSide/QueryPane/AddWidget_spec.js b/app/client/cypress/e2e/Regression/ServerSide/QueryPane/AddWidget_spec.js index bed7890c6dcf..bd9f2a07afcb 100644 --- a/app/client/cypress/e2e/Regression/ServerSide/QueryPane/AddWidget_spec.js +++ b/app/client/cypress/e2e/Regression/ServerSide/QueryPane/AddWidget_spec.js @@ -11,7 +11,7 @@ describe( { tags: ["@tag.Datasource"] }, function () { beforeEach(() => { - cy.startRoutesForDatasource(); + dataSources.StartDataSourceRoutes(); cy.createPostgresDatasource(); cy.get("@saveDatasource").then((httpResponse) => { datasourceName = httpResponse.response.body.data.name; diff --git a/app/client/cypress/e2e/Regression/ServerSide/QueryPane/EmptyDataSource_spec.js b/app/client/cypress/e2e/Regression/ServerSide/QueryPane/EmptyDataSource_spec.js index 89a387b62a9e..8a3eb744ef75 100644 --- a/app/client/cypress/e2e/Regression/ServerSide/QueryPane/EmptyDataSource_spec.js +++ b/app/client/cypress/e2e/Regression/ServerSide/QueryPane/EmptyDataSource_spec.js @@ -9,7 +9,7 @@ describe( { tags: ["@tag.Datasource"] }, function () { beforeEach(() => { - cy.startRoutesForDatasource(); + dataSources.StartDataSourceRoutes(); }); it("1. Create a empty datasource", function () { diff --git a/app/client/cypress/e2e/Regression/ServerSide/QueryPane/S3_1_spec.js b/app/client/cypress/e2e/Regression/ServerSide/QueryPane/S3_1_spec.js index e3eb0f80d849..f3a4aa0f1949 100644 --- a/app/client/cypress/e2e/Regression/ServerSide/QueryPane/S3_1_spec.js +++ b/app/client/cypress/e2e/Regression/ServerSide/QueryPane/S3_1_spec.js @@ -28,20 +28,9 @@ describe( }); beforeEach(() => { - cy.startRoutesForDatasource(); + dataSources.StartDataSourceRoutes(); }); - // afterEach(function() { - // if (this.currentTest.state === "failed") { - // Cypress.runner.stop(); - // } - // }); - - // afterEach(() => { - // if (queryName) - // cy.actionContextMenuByEntityName(queryName); - // }); - before("Creates a new Amazon S3 datasource", function () { dataSources.CreateDataSource("S3"); cy.get("@dsName").then((dsName) => { diff --git a/app/client/cypress/e2e/Regression/ServerSide/QueryPane/SwitchDatasource_spec.js b/app/client/cypress/e2e/Regression/ServerSide/QueryPane/SwitchDatasource_spec.js index 500f162d26de..1165a9b6f9a3 100644 --- a/app/client/cypress/e2e/Regression/ServerSide/QueryPane/SwitchDatasource_spec.js +++ b/app/client/cypress/e2e/Regression/ServerSide/QueryPane/SwitchDatasource_spec.js @@ -2,7 +2,7 @@ import { dataSources, agHelper } from "../../../../support/Objects/ObjectsCore"; describe("Switch datasource", { tags: ["@tag.Datasource"] }, function () { let dsName_1, dsName_2, MongoDB; beforeEach(() => { - cy.startRoutesForDatasource(); + dataSources.StartDataSourceRoutes(); }); it("1. Create postgres datasource", function () { diff --git a/app/client/cypress/e2e/Sanity/Datasources/ElasticSearchDatasource_spec.js b/app/client/cypress/e2e/Sanity/Datasources/ElasticSearchDatasource_spec.js index 7a95ee2f3989..151311f95952 100644 --- a/app/client/cypress/e2e/Sanity/Datasources/ElasticSearchDatasource_spec.js +++ b/app/client/cypress/e2e/Sanity/Datasources/ElasticSearchDatasource_spec.js @@ -9,7 +9,7 @@ describe( { tags: ["@tag.Datasource", "@tag.Sanity"] }, function () { beforeEach(() => { - cy.startRoutesForDatasource(); + dataSources.StartDataSourceRoutes(); }); it("1. Create elastic search datasource", function () { diff --git a/app/client/cypress/e2e/Sanity/Datasources/MySQLNoiseTest_spec.js b/app/client/cypress/e2e/Sanity/Datasources/MySQLNoiseTest_spec.js index 85e103863f50..f1a4d43fb661 100644 --- a/app/client/cypress/e2e/Sanity/Datasources/MySQLNoiseTest_spec.js +++ b/app/client/cypress/e2e/Sanity/Datasources/MySQLNoiseTest_spec.js @@ -16,7 +16,7 @@ describe( beforeEach(() => { agHelper.AddDsl("noiseDsl"); - cy.startRoutesForDatasource(); + dataSources.StartDataSourceRoutes(); }); it("1. Verify after killing MySQL session, app should not crash", function () { diff --git a/app/client/cypress/e2e/Sanity/Datasources/MySQL_spec.js b/app/client/cypress/e2e/Sanity/Datasources/MySQL_spec.js index aae11a813a57..97e59863018c 100644 --- a/app/client/cypress/e2e/Sanity/Datasources/MySQL_spec.js +++ b/app/client/cypress/e2e/Sanity/Datasources/MySQL_spec.js @@ -8,7 +8,7 @@ describe( { tags: ["@tag.Datasource", "@tag.Sanity"] }, function () { beforeEach(() => { - cy.startRoutesForDatasource(); + dataSources.StartDataSourceRoutes(); }); it("1. Create, test, save then delete a MySQL datasource", function () { diff --git a/app/client/cypress/e2e/Sanity/Datasources/PostgresDatasource_spec.js b/app/client/cypress/e2e/Sanity/Datasources/PostgresDatasource_spec.js index d9140f5ad0be..e127ee675f97 100644 --- a/app/client/cypress/e2e/Sanity/Datasources/PostgresDatasource_spec.js +++ b/app/client/cypress/e2e/Sanity/Datasources/PostgresDatasource_spec.js @@ -7,7 +7,7 @@ describe( { tags: ["@tag.Datasource", "@tag.Sanity"] }, function () { beforeEach(() => { - cy.startRoutesForDatasource(); + dataSources.StartDataSourceRoutes(); }); it("1. Create, test, save then delete a postgres datasource", function () { diff --git a/app/client/cypress/e2e/Sanity/Datasources/RedshiftDataSourceStub_spec.js b/app/client/cypress/e2e/Sanity/Datasources/RedshiftDataSourceStub_spec.js index 1a757cbb02dc..2febce52d1f2 100644 --- a/app/client/cypress/e2e/Sanity/Datasources/RedshiftDataSourceStub_spec.js +++ b/app/client/cypress/e2e/Sanity/Datasources/RedshiftDataSourceStub_spec.js @@ -8,7 +8,7 @@ describe( { tags: ["@tag.Datasource", "@tag.Sanity"] }, function () { beforeEach(() => { - cy.startRoutesForDatasource(); + dataSources.StartDataSourceRoutes(); }); it("1. Create, test, save then delete a Redshift datasource", function () { diff --git a/app/client/cypress/e2e/Sanity/Datasources/SMTPDatasource_spec.js b/app/client/cypress/e2e/Sanity/Datasources/SMTPDatasource_spec.js index 190def6fe021..e6da42b6a93f 100644 --- a/app/client/cypress/e2e/Sanity/Datasources/SMTPDatasource_spec.js +++ b/app/client/cypress/e2e/Sanity/Datasources/SMTPDatasource_spec.js @@ -10,7 +10,7 @@ describe( function () { let SMTPDatasourceName; beforeEach(() => { - cy.startRoutesForDatasource(); + dataSources.StartDataSourceRoutes(); }); before(() => { agHelper.AddDsl("SMTPTestdsl");
a9a0d714c02baecf87fb4fcbfa6ac3d4e9cd5512
2025-01-07 17:34:15
Pawan Kumar
chore: fix form widgets bugs (#38492)
false
fix form widgets bugs (#38492)
chore
diff --git a/app/client/cypress/e2e/Regression/ClientSide/Anvil/Widgets/AnvilButtonWidgetSnapshot_spec.ts b/app/client/cypress/e2e/Regression/ClientSide/Anvil/Widgets/AnvilButtonWidgetSnapshot_spec.ts index 74e3c855ae41..a78e7ef5d47e 100644 --- a/app/client/cypress/e2e/Regression/ClientSide/Anvil/Widgets/AnvilButtonWidgetSnapshot_spec.ts +++ b/app/client/cypress/e2e/Regression/ClientSide/Anvil/Widgets/AnvilButtonWidgetSnapshot_spec.ts @@ -5,7 +5,7 @@ import { } from "../../../../../support/Objects/ObjectsCore"; // TODO: Enable when issue(github.com/appsmithorg/appsmith/issues/36419) is solved. -describe( +describe.skip( `${ANVIL_EDITOR_TEST}: Anvil tests for Button Widget`, { tags: ["@tag.Anvil", "@tag.Visual"] }, () => { diff --git a/app/client/cypress/e2e/Regression/ClientSide/Anvil/Widgets/AnvilCheckboxGroupWidgetSnapshot_spec.ts b/app/client/cypress/e2e/Regression/ClientSide/Anvil/Widgets/AnvilCheckboxGroupWidgetSnapshot_spec.ts index d2113759c835..66b66d583e7f 100644 --- a/app/client/cypress/e2e/Regression/ClientSide/Anvil/Widgets/AnvilCheckboxGroupWidgetSnapshot_spec.ts +++ b/app/client/cypress/e2e/Regression/ClientSide/Anvil/Widgets/AnvilCheckboxGroupWidgetSnapshot_spec.ts @@ -5,7 +5,7 @@ import { } from "../../../../../support/Objects/ObjectsCore"; // TODO: Enable when issue(github.com/appsmithorg/appsmith/issues/36419) is solved. -describe( +describe.skip( `${ANVIL_EDITOR_TEST}: Anvil tests for Checkbox Group Widget`, { tags: ["@tag.Anvil", "@tag.Visual"] }, () => { diff --git a/app/client/cypress/e2e/Regression/ClientSide/Anvil/Widgets/AnvilCheckboxWidgetSnapshot_spec.ts b/app/client/cypress/e2e/Regression/ClientSide/Anvil/Widgets/AnvilCheckboxWidgetSnapshot_spec.ts index fe143dcab129..5ad568bf5a20 100644 --- a/app/client/cypress/e2e/Regression/ClientSide/Anvil/Widgets/AnvilCheckboxWidgetSnapshot_spec.ts +++ b/app/client/cypress/e2e/Regression/ClientSide/Anvil/Widgets/AnvilCheckboxWidgetSnapshot_spec.ts @@ -5,7 +5,7 @@ import { } from "../../../../../support/Objects/ObjectsCore"; // TODO: Enable when issue(github.com/appsmithorg/appsmith/issues/36419) is solved. -describe( +describe.skip( `${ANVIL_EDITOR_TEST}: Anvil tests for Checkbox Widget`, { tags: ["@tag.Anvil", "@tag.Visual"] }, () => { diff --git a/app/client/cypress/e2e/Regression/ClientSide/Anvil/Widgets/AnvilHeadingWidgetSnapshot_spec.ts b/app/client/cypress/e2e/Regression/ClientSide/Anvil/Widgets/AnvilHeadingWidgetSnapshot_spec.ts index c58a6eff6cd3..82ae69d9a07b 100644 --- a/app/client/cypress/e2e/Regression/ClientSide/Anvil/Widgets/AnvilHeadingWidgetSnapshot_spec.ts +++ b/app/client/cypress/e2e/Regression/ClientSide/Anvil/Widgets/AnvilHeadingWidgetSnapshot_spec.ts @@ -5,7 +5,7 @@ import { } from "../../../../../support/Objects/ObjectsCore"; // TODO: Enable when issue(github.com/appsmithorg/appsmith/issues/36419) is solved. -describe( +describe.skip( `${ANVIL_EDITOR_TEST}: Anvil tests for Heading Widget`, { tags: ["@tag.Anvil", "@tag.Visual"] }, () => { diff --git a/app/client/cypress/e2e/Regression/ClientSide/Anvil/Widgets/AnvilIconButtonWidgetSnapshot_spec.ts b/app/client/cypress/e2e/Regression/ClientSide/Anvil/Widgets/AnvilIconButtonWidgetSnapshot_spec.ts index 9c0b7ec75524..5adb9bde9366 100644 --- a/app/client/cypress/e2e/Regression/ClientSide/Anvil/Widgets/AnvilIconButtonWidgetSnapshot_spec.ts +++ b/app/client/cypress/e2e/Regression/ClientSide/Anvil/Widgets/AnvilIconButtonWidgetSnapshot_spec.ts @@ -5,7 +5,7 @@ import { } from "../../../../../support/Objects/ObjectsCore"; // TODO: Enable when issue(github.com/appsmithorg/appsmith/issues/36419) is solved. -describe( +describe.skip( `${ANVIL_EDITOR_TEST}: Anvil tests for Icon Button Widget`, { tags: ["@tag.Anvil", "@tag.Visual"] }, () => { diff --git a/app/client/cypress/e2e/Regression/ClientSide/Anvil/Widgets/AnvilInlineButtonWidgetSnapshot_spec.ts b/app/client/cypress/e2e/Regression/ClientSide/Anvil/Widgets/AnvilInlineButtonWidgetSnapshot_spec.ts index 67015f2c3e28..9899b8ce2f79 100644 --- a/app/client/cypress/e2e/Regression/ClientSide/Anvil/Widgets/AnvilInlineButtonWidgetSnapshot_spec.ts +++ b/app/client/cypress/e2e/Regression/ClientSide/Anvil/Widgets/AnvilInlineButtonWidgetSnapshot_spec.ts @@ -5,7 +5,7 @@ import { } from "../../../../../support/Objects/ObjectsCore"; // TODO: Enable when issue(github.com/appsmithorg/appsmith/issues/36419) is solved. -describe( +describe.skip( `${ANVIL_EDITOR_TEST}: Anvil tests for Inline Button Widget`, { tags: ["@tag.Anvil", "@tag.Visual"] }, () => { diff --git a/app/client/cypress/e2e/Regression/ClientSide/Anvil/Widgets/AnvilParagraphWidgetSnapshot_spec.ts b/app/client/cypress/e2e/Regression/ClientSide/Anvil/Widgets/AnvilParagraphWidgetSnapshot_spec.ts index 81cbbbac8790..eac9c2178efb 100644 --- a/app/client/cypress/e2e/Regression/ClientSide/Anvil/Widgets/AnvilParagraphWidgetSnapshot_spec.ts +++ b/app/client/cypress/e2e/Regression/ClientSide/Anvil/Widgets/AnvilParagraphWidgetSnapshot_spec.ts @@ -5,7 +5,7 @@ import { } from "../../../../../support/Objects/ObjectsCore"; // TODO: Enable when issue(github.com/appsmithorg/appsmith/issues/36419) is solved. -describe( +describe.skip( `${ANVIL_EDITOR_TEST}: Anvil tests for Paragraph Widget`, { tags: ["@tag.Anvil", "@tag.Visual"] }, () => { diff --git a/app/client/cypress/e2e/Regression/ClientSide/Anvil/Widgets/AnvilRadioGroupWidgetSnapshot_spec.ts b/app/client/cypress/e2e/Regression/ClientSide/Anvil/Widgets/AnvilRadioGroupWidgetSnapshot_spec.ts index 1634c2ae7e80..7b90dbce28ab 100644 --- a/app/client/cypress/e2e/Regression/ClientSide/Anvil/Widgets/AnvilRadioGroupWidgetSnapshot_spec.ts +++ b/app/client/cypress/e2e/Regression/ClientSide/Anvil/Widgets/AnvilRadioGroupWidgetSnapshot_spec.ts @@ -5,7 +5,7 @@ import { } from "../../../../../support/Objects/ObjectsCore"; // TODO: Enable when issue(github.com/appsmithorg/appsmith/issues/36419) is solved. -describe( +describe.skip( `${ANVIL_EDITOR_TEST}: Anvil tests for Radio Group Widget`, { tags: ["@tag.Anvil", "@tag.Visual"] }, () => { diff --git a/app/client/cypress/e2e/Regression/ClientSide/Anvil/Widgets/AnvilStatsWidgetSnapshot_spec.ts b/app/client/cypress/e2e/Regression/ClientSide/Anvil/Widgets/AnvilStatsWidgetSnapshot_spec.ts index 0449dc62d6f5..51da8ac23959 100644 --- a/app/client/cypress/e2e/Regression/ClientSide/Anvil/Widgets/AnvilStatsWidgetSnapshot_spec.ts +++ b/app/client/cypress/e2e/Regression/ClientSide/Anvil/Widgets/AnvilStatsWidgetSnapshot_spec.ts @@ -5,7 +5,7 @@ import { } from "../../../../../support/Objects/ObjectsCore"; // TODO: Enable when issue(github.com/appsmithorg/appsmith/issues/36419) is solved. -describe( +describe.skip( `${ANVIL_EDITOR_TEST}: Anvil tests for Stats Widget`, { tags: ["@tag.Anvil", "@tag.Visual"] }, () => { diff --git a/app/client/cypress/e2e/Regression/ClientSide/Anvil/Widgets/AnvilSwitchGroupWidgetSnapshot_spec.ts b/app/client/cypress/e2e/Regression/ClientSide/Anvil/Widgets/AnvilSwitchGroupWidgetSnapshot_spec.ts index a36b4d2c0b12..2ffed43ba435 100644 --- a/app/client/cypress/e2e/Regression/ClientSide/Anvil/Widgets/AnvilSwitchGroupWidgetSnapshot_spec.ts +++ b/app/client/cypress/e2e/Regression/ClientSide/Anvil/Widgets/AnvilSwitchGroupWidgetSnapshot_spec.ts @@ -5,7 +5,7 @@ import { } from "../../../../../support/Objects/ObjectsCore"; // TODO: Enable when issue(github.com/appsmithorg/appsmith/issues/36419) is solved. -describe( +describe.skip( `${ANVIL_EDITOR_TEST}: Anvil tests for Switch Group Widget`, { tags: ["@tag.Anvil", "@tag.Visual"] }, () => { diff --git a/app/client/cypress/e2e/Regression/ClientSide/Anvil/Widgets/AnvilSwitchWidgetSnapshot_spec.ts b/app/client/cypress/e2e/Regression/ClientSide/Anvil/Widgets/AnvilSwitchWidgetSnapshot_spec.ts index a6eb434fe48a..aec145739a22 100644 --- a/app/client/cypress/e2e/Regression/ClientSide/Anvil/Widgets/AnvilSwitchWidgetSnapshot_spec.ts +++ b/app/client/cypress/e2e/Regression/ClientSide/Anvil/Widgets/AnvilSwitchWidgetSnapshot_spec.ts @@ -5,7 +5,7 @@ import { } from "../../../../../support/Objects/ObjectsCore"; // TODO: Enable when issue(github.com/appsmithorg/appsmith/issues/36419) is solved. -describe( +describe.skip( `${ANVIL_EDITOR_TEST}: Anvil tests for Switch Widget`, { tags: ["@tag.Anvil", "@tag.Visual"] }, () => { diff --git a/app/client/cypress/e2e/Regression/ClientSide/Anvil/Widgets/AnvilToolbarButtonWidgetSnapshot_spec.ts b/app/client/cypress/e2e/Regression/ClientSide/Anvil/Widgets/AnvilToolbarButtonWidgetSnapshot_spec.ts index 1ed021c81277..ef99aeab2938 100644 --- a/app/client/cypress/e2e/Regression/ClientSide/Anvil/Widgets/AnvilToolbarButtonWidgetSnapshot_spec.ts +++ b/app/client/cypress/e2e/Regression/ClientSide/Anvil/Widgets/AnvilToolbarButtonWidgetSnapshot_spec.ts @@ -5,7 +5,7 @@ import { } from "../../../../../support/Objects/ObjectsCore"; // TODO: Enable when issue(github.com/appsmithorg/appsmith/issues/36419) is solved. -describe( +describe.skip( `${ANVIL_EDITOR_TEST}: Anvil tests for Toolbar Button Widget`, { tags: ["@tag.Anvil", "@tag.Visual"] }, () => { diff --git a/app/client/cypress/limited-tests.txt b/app/client/cypress/limited-tests.txt index 3a997515912b..00e32a4629d0 100644 --- a/app/client/cypress/limited-tests.txt +++ b/app/client/cypress/limited-tests.txt @@ -1,6 +1,7 @@ # To run only limited tests - give the spec names in below format: -cypress/e2e/Regression/ClientSide/VisualTests/JSEditorIndent_spec.js +#cypress/e2e/Regression/ClientSide/VisualTests/JSEditorIndent_spec.js # For running all specs - uncomment below: #cypress/e2e/**/**/* +cypress/e2e/Regression/ClientSide/Anvil/Widgets/* #ci-test-limit uses this file to run minimum of specs. Do not run entire suite with this command. diff --git a/app/client/cypress/support/Pages/Anvil/AnvilSnapshot.ts b/app/client/cypress/support/Pages/Anvil/AnvilSnapshot.ts index 356e16994c36..a7da8faebe2a 100644 --- a/app/client/cypress/support/Pages/Anvil/AnvilSnapshot.ts +++ b/app/client/cypress/support/Pages/Anvil/AnvilSnapshot.ts @@ -173,8 +173,8 @@ export class AnvilSnapshot { public triggerInputInvalidState = () => { this.enterPreviewMode(); - cy.get("input[aria-required=true]").first().type("123"); - cy.get("input[aria-required=true]").first().clear(); + cy.get("input[required]").first().type("123"); + cy.get("input[required]").first().clear(); this.exitPreviewMode(); this.agHelper.GetNClick(this.locators.propertyPaneSidebar); }; diff --git a/app/client/packages/design-system/widgets/src/components/Calendar/src/CalendarHeading.tsx b/app/client/packages/design-system/widgets/src/components/Calendar/src/CalendarHeading.tsx index ed931b848db9..160265802dff 100644 --- a/app/client/packages/design-system/widgets/src/components/Calendar/src/CalendarHeading.tsx +++ b/app/client/packages/design-system/widgets/src/components/Calendar/src/CalendarHeading.tsx @@ -1,18 +1,27 @@ -import { Text, type TextProps } from "@appsmith/wds"; -import React, { forwardRef, type ForwardedRef } from "react"; -import { HeadingContext, useContextProps } from "react-aria-components"; +import { type TextProps } from "@appsmith/wds"; +import { + CalendarStateContext, + HeadingContext, + useContextProps, +} from "react-aria-components"; +import React, { forwardRef, useContext, type ForwardedRef } from "react"; + +import styles from "./styles.module.css"; +import { CalendarMonthDropdown } from "./CalendarMonthDropdown"; +import { CalendarYearDropdown } from "./CalendarYearDropdown"; function CalendarHeading( props: TextProps, ref: ForwardedRef<HTMLHeadingElement>, ) { [props, ref] = useContextProps(props, ref, HeadingContext); - const { children, ...domProps } = props; + const state = useContext(CalendarStateContext); return ( - <Text {...domProps} color="neutral" ref={ref}> - {children} - </Text> + <div className={styles.monthYearDropdown}> + <CalendarMonthDropdown state={state} /> + <CalendarYearDropdown state={state} /> + </div> ); } diff --git a/app/client/packages/design-system/widgets/src/components/Calendar/src/CalendarMonthDropdown.tsx b/app/client/packages/design-system/widgets/src/components/Calendar/src/CalendarMonthDropdown.tsx new file mode 100644 index 000000000000..3f37d5647f8d --- /dev/null +++ b/app/client/packages/design-system/widgets/src/components/Calendar/src/CalendarMonthDropdown.tsx @@ -0,0 +1,40 @@ +import React from "react"; +import type { Key } from "react"; +import { useDateFormatter } from "@react-aria/i18n"; +import { ListBoxItem, Select } from "@appsmith/wds"; +import type { CalendarState } from "@react-stately/calendar"; + +import styles from "./styles.module.css"; +import { useValidMonths } from "../utils/calendar"; + +export function CalendarMonthDropdown({ state }: { state: CalendarState }) { + const formatter = useDateFormatter({ + month: "long", + timeZone: state.timeZone, + }); + + const months = useValidMonths(state, formatter); + + const onChange = (value: Key | null) => { + const date = state.focusedDate.set({ month: Number(value) }); + + state.setFocusedDate(date); + }; + + return ( + <Select + aria-label="Month" + className={styles.monthDropdown} + defaultSelectedKey={state.focusedDate.month} + onSelectionChange={onChange} + placeholder="Select Month" + size="small" + > + {months.map((month, i) => ( + <ListBoxItem id={i} key={i} textValue={month}> + {month} + </ListBoxItem> + ))} + </Select> + ); +} diff --git a/app/client/packages/design-system/widgets/src/components/Calendar/src/CalendarYearDropdown.tsx b/app/client/packages/design-system/widgets/src/components/Calendar/src/CalendarYearDropdown.tsx new file mode 100644 index 000000000000..289f974099d6 --- /dev/null +++ b/app/client/packages/design-system/widgets/src/components/Calendar/src/CalendarYearDropdown.tsx @@ -0,0 +1,33 @@ +import React from "react"; +import type { Key } from "react"; +import { ListBoxItem, Select } from "@appsmith/wds"; +import type { CalendarState } from "@react-stately/calendar"; + +import { useYearOptions } from "../utils/calendar"; + +export function CalendarYearDropdown({ state }: { state: CalendarState }) { + const years = useYearOptions(state); + + const onChange = (value: Key | null) => { + const index = Number(value); + const date = years[index].value; + + state.setFocusedDate(date); + }; + + return ( + <Select + aria-label="Year" + onSelectionChange={onChange} + placeholder="Select Year" + selectedKey={20} + size="small" + > + {years.map((year, i) => ( + <ListBoxItem id={i} key={i} textValue={year.formatted}> + {year.formatted} + </ListBoxItem> + ))} + </Select> + ); +} diff --git a/app/client/packages/design-system/widgets/src/components/Calendar/src/styles.module.css b/app/client/packages/design-system/widgets/src/components/Calendar/src/styles.module.css index 216afe61510f..950964ce3e46 100644 --- a/app/client/packages/design-system/widgets/src/components/Calendar/src/styles.module.css +++ b/app/client/packages/design-system/widgets/src/components/Calendar/src/styles.module.css @@ -68,3 +68,12 @@ 0 0 0 calc(var(--box-shadow-offset) + var(--border-width-2)) var(--color-bd-focus); } + +.monthYearDropdown { + display: flex; + gap: var(--inner-spacing-1); +} + +.monthDropdown button { + width: 14ch; +} diff --git a/app/client/packages/design-system/widgets/src/components/Calendar/utils/calendar.ts b/app/client/packages/design-system/widgets/src/components/Calendar/utils/calendar.ts new file mode 100644 index 000000000000..cf1b356de043 --- /dev/null +++ b/app/client/packages/design-system/widgets/src/components/Calendar/utils/calendar.ts @@ -0,0 +1,52 @@ +import { useDateFormatter } from "@react-aria/i18n"; +import type { CalendarState } from "@react-stately/calendar"; + +export function useYearOptions(state: CalendarState) { + const formatter = useDateFormatter({ + year: "numeric", + timeZone: state.timeZone, + }); + + const years: { value: CalendarState["focusedDate"]; formatted: string }[] = + []; + + const YEAR_RANGE = 20; + + for (let i = -YEAR_RANGE; i <= YEAR_RANGE; i++) { + const date = state.focusedDate.add({ years: i }); + + years.push({ + value: date, + formatted: formatter.format(date.toDate(state.timeZone)), + }); + } + + return years; +} + +export function useValidMonths( + state: CalendarState, + formatter: Intl.DateTimeFormat, +) { + const months = []; + const numMonths = state.focusedDate.calendar.getMonthsInYear( + state.focusedDate, + ); + + for (let i = 1; i <= numMonths; i++) { + const date = state.focusedDate.set({ month: i }); + + // Skip months outside valid range + if (state.minValue && date.compare(state.minValue) < 0) { + continue; + } + + if (state.maxValue && date.compare(state.maxValue) > 0) { + continue; + } + + months.push(formatter.format(date.toDate(state.timeZone))); + } + + return months; +} diff --git a/app/client/packages/design-system/widgets/src/components/Datepicker/src/Datepicker.tsx b/app/client/packages/design-system/widgets/src/components/Datepicker/src/Datepicker.tsx index f62f5dd69fb7..f57803332474 100644 --- a/app/client/packages/design-system/widgets/src/components/Datepicker/src/Datepicker.tsx +++ b/app/client/packages/design-system/widgets/src/components/Datepicker/src/Datepicker.tsx @@ -79,7 +79,6 @@ export const DatePicker = <T extends DateValue>(props: DatePickerProps<T>) => { isLoading={isLoading} size={size} /> - <FieldError>{errorMessage}</FieldError> <Popover UNSTABLE_portalContainer={root} className={clsx(datePickerStyles.popover, popoverClassName)} @@ -103,6 +102,7 @@ export const DatePicker = <T extends DateValue>(props: DatePickerProps<T>) => { )} </Dialog> </Popover> + <FieldError>{errorMessage}</FieldError> </> ); }} diff --git a/app/client/packages/design-system/widgets/src/components/FieldLabel/src/FieldLabel.tsx b/app/client/packages/design-system/widgets/src/components/FieldLabel/src/FieldLabel.tsx index 85126a123b94..6287bcc5c88e 100644 --- a/app/client/packages/design-system/widgets/src/components/FieldLabel/src/FieldLabel.tsx +++ b/app/client/packages/design-system/widgets/src/components/FieldLabel/src/FieldLabel.tsx @@ -22,7 +22,12 @@ export function FieldLabel(props: LabelProps) { className={clsx(styles.label)} elementType="label" > - <Text fontWeight={600} size="caption"> + <Text + fontWeight={600} + lineClamp={1} + size="caption" + title={children?.toString()} + > {children} </Text> {Boolean(isRequired) && ( diff --git a/app/client/packages/design-system/widgets/src/components/Input/src/Input.tsx b/app/client/packages/design-system/widgets/src/components/Input/src/Input.tsx index 64e03bc95d66..f52a38a27093 100644 --- a/app/client/packages/design-system/widgets/src/components/Input/src/Input.tsx +++ b/app/client/packages/design-system/widgets/src/components/Input/src/Input.tsx @@ -3,7 +3,7 @@ import { mergeRefs } from "@react-aria/utils"; import React, { forwardRef, useRef, useState } from "react"; import { getTypographyClassName } from "@appsmith/wds-theming"; import { IconButton, Spinner, type IconProps } from "@appsmith/wds"; -import { Group, Input as HeadlessInput } from "react-aria-components"; +import { Input as HeadlessInput } from "react-aria-components"; import styles from "./styles.module.css"; import type { InputProps } from "./types"; @@ -49,7 +49,7 @@ function _Input(props: InputProps, ref: React.Ref<HTMLInputElement>) { })(); return ( - <Group className={styles.inputGroup}> + <div className={styles.inputGroup}> {Boolean(prefix) && ( <span data-input-prefix onClick={() => localRef.current?.focus()}> {prefix} @@ -74,7 +74,7 @@ function _Input(props: InputProps, ref: React.Ref<HTMLInputElement>) { {suffix} </span> )} - </Group> + </div> ); } diff --git a/app/client/packages/design-system/widgets/src/components/Input/src/styles.module.css b/app/client/packages/design-system/widgets/src/components/Input/src/styles.module.css index 63a0d04a895c..821e337af7bf 100644 --- a/app/client/packages/design-system/widgets/src/components/Input/src/styles.module.css +++ b/app/client/packages/design-system/widgets/src/components/Input/src/styles.module.css @@ -27,6 +27,7 @@ padding-block: var(--inner-spacing-1); padding-inline: var(--inner-spacing-2); box-sizing: content-box; + cursor: inherit; } .inputGroup:has([data-input-prefix]) .input { @@ -63,10 +64,18 @@ margin-inline-start: var(--inner-spacing-2); } +.inputGroup:has(.input[data-size="small"]) [data-input-prefix] { + margin-inline-start: 0; +} + .inputGroup [data-input-suffix] { margin-inline-end: var(--inner-spacing-2); } +.inputGroup:has(.input[data-size="small"]) [data-input-suffix] { + margin-inline-end: 0; +} + .inputGroup :is([data-input-suffix], [data-input-prefix]) button { border-radius: calc( var(--border-radius-elevation-3) - var(--inner-spacing-1) @@ -84,7 +93,7 @@ * HOVERED * ---------------------------------------------------------------------------- */ -.inputGroup[data-hovered]:has( +.inputGroup:is([data-hovered], :has([data-hovered])):has( > .input:not( :is( [data-focused], @@ -111,6 +120,9 @@ .inputGroup input[data-readonly] { padding-inline: 0; + text-overflow: ellipsis; + white-space: nowrap; + cursor: text; } /** Reason for doing this is because for readonly inputs, we want focus state to be wider than the component width */ @@ -143,8 +155,9 @@ * DISABLED * ---------------------------------------------------------------------------- */ -.inputGroup:has(> .input[data-disabled]), -.inputGroup:has(> .input:has(~ input[data-disabled])) { +.inputGroup:has( + :is(.input[data-disabled], .input:has(~ input[data-disabled])) + ) { cursor: not-allowed; box-shadow: none; } diff --git a/app/client/packages/design-system/widgets/src/components/Select/src/SelectTrigger.tsx b/app/client/packages/design-system/widgets/src/components/Select/src/SelectTrigger.tsx index 0458df47bacd..91fe6f1c1567 100644 --- a/app/client/packages/design-system/widgets/src/components/Select/src/SelectTrigger.tsx +++ b/app/client/packages/design-system/widgets/src/components/Select/src/SelectTrigger.tsx @@ -2,7 +2,7 @@ import clsx from "clsx"; import React from "react"; import { Icon, Spinner, textInputStyles } from "@appsmith/wds"; import { getTypographyClassName } from "@appsmith/wds-theming"; -import { Button, Group, SelectValue } from "react-aria-components"; +import { Button, SelectValue } from "react-aria-components"; import styles from "./styles.module.css"; import type { SelectProps } from "./types"; @@ -19,9 +19,7 @@ export const SelectTrigger: React.FC<SelectTriggerProps> = (props) => { const { isDisabled, isInvalid, isLoading, placeholder, size } = props; return ( - <Group - className={clsx(textInputStyles.inputGroup, styles.selectInputGroup)} - > + <div className={clsx(textInputStyles.inputGroup, styles.selectInputGroup)}> <Button className={clsx(textInputStyles.input, styles.selectTriggerButton)} data-invalid={Boolean(isInvalid) ? "" : undefined} @@ -44,6 +42,6 @@ export const SelectTrigger: React.FC<SelectTriggerProps> = (props) => { )} </span> </Button> - </Group> + </div> ); }; diff --git a/app/client/packages/design-system/widgets/src/components/Text/src/Text.tsx b/app/client/packages/design-system/widgets/src/components/Text/src/Text.tsx index b3366bf915bc..63a72cf5d329 100644 --- a/app/client/packages/design-system/widgets/src/components/Text/src/Text.tsx +++ b/app/client/packages/design-system/widgets/src/components/Text/src/Text.tsx @@ -45,6 +45,7 @@ const _Text = (props: TextProps, ref: Ref<HTMLDivElement>) => { fontStyle: isItalic ? "italic" : "normal", wordBreak, textAlign, + whiteSpace: "pre-wrap", ...style, }} {...rest} diff --git a/app/client/src/modules/ui-builder/ui/wds/WDSBaseInputWidget/widget/index.tsx b/app/client/src/modules/ui-builder/ui/wds/WDSBaseInputWidget/widget/index.tsx index bc8b78063693..0a2e6fa0bc1a 100644 --- a/app/client/src/modules/ui-builder/ui/wds/WDSBaseInputWidget/widget/index.tsx +++ b/app/client/src/modules/ui-builder/ui/wds/WDSBaseInputWidget/widget/index.tsx @@ -56,7 +56,7 @@ class WDSBaseInputWidget< static getMetaPropertiesMap(): Record<string, any> { return { rawText: undefined, - parsedText: undefined, + text: undefined, isFocused: false, isDirty: false, }; diff --git a/app/client/src/modules/ui-builder/ui/wds/WDSCurrencyInputWidget/config/autocompleteConfig.ts b/app/client/src/modules/ui-builder/ui/wds/WDSCurrencyInputWidget/config/autocompleteConfig.ts index 8796f4c1dc14..15174f781cdb 100644 --- a/app/client/src/modules/ui-builder/ui/wds/WDSCurrencyInputWidget/config/autocompleteConfig.ts +++ b/app/client/src/modules/ui-builder/ui/wds/WDSCurrencyInputWidget/config/autocompleteConfig.ts @@ -4,14 +4,14 @@ export const autocompleteConfig = { "!doc": "An input text field is used to capture a currency value. Inputs are used in forms and can have custom validations.", "!url": "https://docs.appsmith.com/widget-reference/currency-input", - parsedText: { + text: { "!type": "string", "!doc": "The formatted text value of the input", "!url": "https://docs.appsmith.com/widget-reference/currency-input", }, rawText: { "!type": "number", - "!doc": "The value of the input", + "!doc": "The raw text value of the input", "!url": "https://docs.appsmith.com/widget-reference/currency-input", }, isValid: "bool", diff --git a/app/client/src/modules/ui-builder/ui/wds/WDSCurrencyInputWidget/widget/index.tsx b/app/client/src/modules/ui-builder/ui/wds/WDSCurrencyInputWidget/widget/index.tsx index f9087571fc14..fa71e227f114 100644 --- a/app/client/src/modules/ui-builder/ui/wds/WDSCurrencyInputWidget/widget/index.tsx +++ b/app/client/src/modules/ui-builder/ui/wds/WDSCurrencyInputWidget/widget/index.tsx @@ -130,7 +130,7 @@ class WDSCurrencyInputWidget extends WDSBaseInputWidget< static getMetaPropertiesMap(): Record<string, any> { return _.merge(super.getMetaPropertiesMap(), { rawText: "", - parsedText: "", + text: "", currencyCode: undefined, }); } @@ -139,7 +139,7 @@ class WDSCurrencyInputWidget extends WDSBaseInputWidget< return _.merge(super.getDefaultPropertiesMap(), { currencyCode: "defaultCurrencyCode", rawText: "defaultText", - parsedText: "defaultText", + text: "defaultText", }); } @@ -153,9 +153,9 @@ class WDSCurrencyInputWidget extends WDSBaseInputWidget< componentDidUpdate(prevProps: CurrencyInputWidgetProps) { if ( - prevProps.text !== this.props.parsedText && + prevProps.text !== this.props.text && !this.props.isFocused && - this.props.parsedText === String(this.props.defaultText) + this.props.text === String(this.props.defaultText) ) { this.formatText(); } @@ -192,7 +192,7 @@ class WDSCurrencyInputWidget extends WDSBaseInputWidget< Sentry.captureException(e); } - this.props.updateWidgetMetaProperty("parsedText", String(formattedValue)); + this.props.updateWidgetMetaProperty("text", String(formattedValue)); this.props.updateWidgetMetaProperty("rawText", value, { triggerPropertyName: "onTextChanged", @@ -214,13 +214,13 @@ class WDSCurrencyInputWidget extends WDSBaseInputWidget< try { if (isFocused) { - const text = this.props.parsedText || ""; + const text = this.props.text || ""; const deFormattedValue = text.replace( new RegExp("\\" + getLocaleThousandSeparator(), "g"), "", ); - this.props.updateWidgetMetaProperty("parsedText", deFormattedValue); + this.props.updateWidgetMetaProperty("text", deFormattedValue); this.props.updateWidgetMetaProperty("isFocused", isFocused, { triggerPropertyName: "onFocus", dynamicString: this.props.onFocus, @@ -229,13 +229,13 @@ class WDSCurrencyInputWidget extends WDSBaseInputWidget< }, }); } else { - if (this.props.parsedText) { + if (this.props.text) { const formattedValue = formatCurrencyNumber( this.props.decimals, - this.props.parsedText, + this.props.text, ); - this.props.updateWidgetMetaProperty("parsedText", formattedValue); + this.props.updateWidgetMetaProperty("text", formattedValue); } this.props.updateWidgetMetaProperty("isFocused", isFocused, { @@ -249,7 +249,7 @@ class WDSCurrencyInputWidget extends WDSBaseInputWidget< } catch (e) { log.error(e); Sentry.captureException(e); - this.props.updateWidgetMetaProperty("parsedText", this.props.parsedText); + this.props.updateWidgetMetaProperty("text", this.props.text); } super.onFocusChange(!!isFocused); @@ -294,13 +294,13 @@ class WDSCurrencyInputWidget extends WDSBaseInputWidget< }; isTextFormatted = () => { - return this.props.parsedText.includes(getLocaleThousandSeparator()); + return this.props.text.includes(getLocaleThousandSeparator()); }; formatText() { - if (!!this.props.parsedText && !this.isTextFormatted()) { + if (!!this.props.text && !this.isTextFormatted()) { try { - const floatVal = parseFloat(this.props.parsedText); + const floatVal = parseFloat(this.props.text); const formattedValue = Intl.NumberFormat(getLocale(), { style: "decimal", @@ -308,7 +308,7 @@ class WDSCurrencyInputWidget extends WDSBaseInputWidget< maximumFractionDigits: this.props.decimals, }).format(floatVal); - this.props.updateWidgetMetaProperty("parsedText", formattedValue); + this.props.updateWidgetMetaProperty("text", formattedValue); } catch (e) { log.error(e); Sentry.captureException(e); diff --git a/app/client/src/modules/ui-builder/ui/wds/WDSInputWidget/config/autocompleteConfig.ts b/app/client/src/modules/ui-builder/ui/wds/WDSInputWidget/config/autocompleteConfig.ts index 95fa1b3db712..0bebc6f411a4 100644 --- a/app/client/src/modules/ui-builder/ui/wds/WDSInputWidget/config/autocompleteConfig.ts +++ b/app/client/src/modules/ui-builder/ui/wds/WDSInputWidget/config/autocompleteConfig.ts @@ -4,9 +4,14 @@ export const autocompleteConfig = { "!doc": "An input text field is used to capture a users textual input such as their names, numbers, emails etc. Inputs are used in forms and can have custom validations.", "!url": "https://docs.appsmith.com/widget-reference/input", - parsedText: { + text: { "!type": "string", - "!doc": "The text value of the input", + "!doc": "The parsed text value of the input", + "!url": "https://docs.appsmith.com/widget-reference/input", + }, + rawText: { + "!type": "string", + "!doc": "The raw text value of the input", "!url": "https://docs.appsmith.com/widget-reference/input", }, isValid: "bool", diff --git a/app/client/src/modules/ui-builder/ui/wds/WDSInputWidget/config/settersConfig.ts b/app/client/src/modules/ui-builder/ui/wds/WDSInputWidget/config/settersConfig.ts index 42ad0ccb6ad5..ed0afd5a385b 100644 --- a/app/client/src/modules/ui-builder/ui/wds/WDSInputWidget/config/settersConfig.ts +++ b/app/client/src/modules/ui-builder/ui/wds/WDSInputWidget/config/settersConfig.ts @@ -19,7 +19,7 @@ export const settersConfig = { setValue: { path: "defaultText", type: "string", - accessor: "parsedText", + accessor: "text", }, }, }; diff --git a/app/client/src/modules/ui-builder/ui/wds/WDSInputWidget/widget/helper.ts b/app/client/src/modules/ui-builder/ui/wds/WDSInputWidget/widget/helper.ts index 6d4e6cd3b3a3..2d56ecbf943a 100644 --- a/app/client/src/modules/ui-builder/ui/wds/WDSInputWidget/widget/helper.ts +++ b/app/client/src/modules/ui-builder/ui/wds/WDSInputWidget/widget/helper.ts @@ -69,11 +69,11 @@ export const validateInput = (props: InputWidgetProps): Validation => { maxChars, maxNum, minNum, - parsedText, rawText, + text, } = props; - if (isDirty && isRequired && !isNil(parsedText) && parsedText.length === 0) { + if (isDirty && isRequired && !isNil(text) && text.length === 0) { return { validationStatus: "invalid", errorMessage: createMessage(FIELD_REQUIRED_ERROR), @@ -81,7 +81,7 @@ export const validateInput = (props: InputWidgetProps): Validation => { } if (isInputTypeSingleLineOrMultiLine(inputType) && maxChars) { - if (parsedText && parsedText.toString().length > maxChars) { + if (text && text.toString().length > maxChars) { return { validationStatus: "invalid", errorMessage: createMessage(INPUT_TEXT_MAX_CHAR_ERROR, maxChars), @@ -97,16 +97,16 @@ export const validateInput = (props: InputWidgetProps): Validation => { }; } - if (rawText !== "" && isNumber(parsedText)) { + if (rawText !== "" && isNumber(text)) { // check the default text is neither greater than max nor less than min value. - if (!isNil(minNum) && minNum > parsedText) { + if (!isNil(minNum) && minNum > text) { return { validationStatus: "invalid", errorMessage: createMessage(INPUT_DEFAULT_TEXT_MIN_NUM_ERROR), }; } - if (!isNil(maxNum) && maxNum < parsedText) { + if (!isNil(maxNum) && maxNum < text) { return { validationStatus: "invalid", errorMessage: createMessage(INPUT_DEFAULT_TEXT_MAX_NUM_ERROR), diff --git a/app/client/src/modules/ui-builder/ui/wds/WDSInputWidget/widget/index.tsx b/app/client/src/modules/ui-builder/ui/wds/WDSInputWidget/widget/index.tsx index 5eec9a47efe9..216fe6299996 100644 --- a/app/client/src/modules/ui-builder/ui/wds/WDSInputWidget/widget/index.tsx +++ b/app/client/src/modules/ui-builder/ui/wds/WDSInputWidget/widget/index.tsx @@ -62,14 +62,14 @@ class WDSInputWidget extends WDSBaseInputWidget<InputWidgetProps, WidgetState> { static getMetaPropertiesMap(): Record<string, any> { return merge(super.getMetaPropertiesMap(), { rawText: "", - parsedText: "", + text: "", }); } static getDefaultPropertiesMap(): Record<string, string> { return { rawText: "defaultText", - parsedText: "defaultText", + text: "defaultText", }; } @@ -157,17 +157,17 @@ class WDSInputWidget extends WDSBaseInputWidget<InputWidgetProps, WidgetState> { if ( prevProps.rawText !== this.props.rawText && - this.props.rawText !== toString(this.props.parsedText) + this.props.rawText !== toString(this.props.text) ) { pushBatchMetaUpdates( - "parsedText", + "text", parseText(this.props.rawText, this.props.inputType), ); } if (prevProps.inputType !== this.props.inputType) { pushBatchMetaUpdates( - "parsedText", + "text", parseText(this.props.rawText, this.props.inputType), ); } @@ -190,7 +190,7 @@ class WDSInputWidget extends WDSBaseInputWidget<InputWidgetProps, WidgetState> { // derived properties won't work as expected inside a List widget. // TODO(Balaji): Once we refactor the List widget, need to conver // text to a derived property. - pushBatchMetaUpdates("parsedText", parseText(value, this.props.inputType)); + pushBatchMetaUpdates("text", parseText(value, this.props.inputType)); pushBatchMetaUpdates("rawText", value, { triggerPropertyName: "onTextChanged", @@ -211,7 +211,7 @@ class WDSInputWidget extends WDSBaseInputWidget<InputWidgetProps, WidgetState> { const { commitBatchMetaUpdates, pushBatchMetaUpdates } = this.props; pushBatchMetaUpdates("rawText", ""); - pushBatchMetaUpdates("parsedText", parseText("", this.props.inputType)); + pushBatchMetaUpdates("text", parseText("", this.props.inputType)); commitBatchMetaUpdates(); }; diff --git a/app/client/src/modules/ui-builder/ui/wds/WDSPhoneInputWidget/config/autocompleteConfig.ts b/app/client/src/modules/ui-builder/ui/wds/WDSPhoneInputWidget/config/autocompleteConfig.ts index b7fb65a6fcff..6882f5daff98 100644 --- a/app/client/src/modules/ui-builder/ui/wds/WDSPhoneInputWidget/config/autocompleteConfig.ts +++ b/app/client/src/modules/ui-builder/ui/wds/WDSPhoneInputWidget/config/autocompleteConfig.ts @@ -4,7 +4,7 @@ export const autocompleteConfig = { "!doc": "An input text field is used to capture a phone number. Inputs are used in forms and can have custom validations.", "!url": "https://docs.appsmith.com/widget-reference/phone-input", - parsedText: { + text: { "!type": "string", "!doc": "The formatted text value of the input", "!url": "https://docs.appsmith.com/widget-reference/phone-input", diff --git a/app/client/src/modules/ui-builder/ui/wds/WDSPhoneInputWidget/widget/helpers.ts b/app/client/src/modules/ui-builder/ui/wds/WDSPhoneInputWidget/widget/helpers.ts index bb68dac08912..63d2a51dfc9f 100644 --- a/app/client/src/modules/ui-builder/ui/wds/WDSPhoneInputWidget/widget/helpers.ts +++ b/app/client/src/modules/ui-builder/ui/wds/WDSPhoneInputWidget/widget/helpers.ts @@ -5,7 +5,7 @@ import { ISDCodeOptions } from "constants/ISDCodes_v2"; // TODO: Fix this the next time the file is edited // eslint-disable-next-line @typescript-eslint/no-explicit-any export function validateInput(props: any) { - const value = props.parsedText ?? ""; + const value = props.text ?? ""; const isInvalid = "isValid" in props && !props.isValid && !!props.isDirty; // TODO: Fix this the next time the file is edited diff --git a/app/client/src/modules/ui-builder/ui/wds/WDSPhoneInputWidget/widget/index.tsx b/app/client/src/modules/ui-builder/ui/wds/WDSPhoneInputWidget/widget/index.tsx index dc39829aee09..b6d73f339e1e 100644 --- a/app/client/src/modules/ui-builder/ui/wds/WDSPhoneInputWidget/widget/index.tsx +++ b/app/client/src/modules/ui-builder/ui/wds/WDSPhoneInputWidget/widget/index.tsx @@ -117,7 +117,7 @@ class WDSPhoneInputWidget extends WDSBaseInputWidget< static getMetaPropertiesMap(): Record<string, any> { return merge(super.getMetaPropertiesMap(), { rawText: "", - parsedText: "", + text: "", dialCode: undefined, }); } @@ -126,7 +126,7 @@ class WDSPhoneInputWidget extends WDSBaseInputWidget< return merge(super.getDefaultPropertiesMap(), { dialCode: "defaultDialCode", rawText: "defaultText", - parsedText: "defaultText", + text: "defaultText", }); } @@ -160,7 +160,7 @@ class WDSPhoneInputWidget extends WDSBaseInputWidget< const formattedValue = this.getFormattedPhoneNumber(this.props.rawText); this.props.updateWidgetMetaProperty("rawText", this.props.rawText); - this.props.updateWidgetMetaProperty("parsedText", formattedValue); + this.props.updateWidgetMetaProperty("text", formattedValue); } catch (e) { log.error(e); Sentry.captureException(e); @@ -176,24 +176,22 @@ class WDSPhoneInputWidget extends WDSBaseInputWidget< if (prevProps.allowFormatting !== this.props.allowFormatting) { const formattedValue = this.getFormattedPhoneNumber(this.props.rawText); - this.props.updateWidgetMetaProperty("parsedText", formattedValue); + this.props.updateWidgetMetaProperty("text", formattedValue); } // When the default text changes if ( - prevProps.parsedText !== this.props.parsedText && - this.props.parsedText === this.props.defaultText + prevProps.text !== this.props.text && + this.props.text === this.props.defaultText ) { - const formattedValue = this.getFormattedPhoneNumber( - this.props.parsedText, - ); + const formattedValue = this.getFormattedPhoneNumber(this.props.text); if (formattedValue) { this.props.updateWidgetMetaProperty( "rawText", parseIncompletePhoneNumber(formattedValue), ); - this.props.updateWidgetMetaProperty("parsedText", formattedValue); + this.props.updateWidgetMetaProperty("text", formattedValue); } } @@ -214,7 +212,7 @@ class WDSPhoneInputWidget extends WDSBaseInputWidget< if (this.props.rawText && this.props.allowFormatting) { const formattedValue = this.getFormattedPhoneNumber(this.props.rawText); - this.props.updateWidgetMetaProperty("parsedText", formattedValue); + this.props.updateWidgetMetaProperty("text", formattedValue); } }; @@ -222,7 +220,7 @@ class WDSPhoneInputWidget extends WDSBaseInputWidget< let formattedValue; // Don't format, as value is typed, when user is deleting - if (value && value.length > this.props.parsedText?.length) { + if (value && value.length > this.props.text?.length) { formattedValue = this.getFormattedPhoneNumber(value); } else { formattedValue = value; @@ -232,7 +230,7 @@ class WDSPhoneInputWidget extends WDSBaseInputWidget< "rawText", parseIncompletePhoneNumber(formattedValue), ); - this.props.updateWidgetMetaProperty("parsedText", formattedValue, { + this.props.updateWidgetMetaProperty("text", formattedValue, { triggerPropertyName: "onTextChanged", dynamicString: this.props.onTextChanged, event: { @@ -300,7 +298,7 @@ class WDSPhoneInputWidget extends WDSBaseInputWidget< }; getWidgetView() { - const rawText = this.props.parsedText ?? ""; + const rawText = this.props.text ?? ""; const validation = validateInput(this.props);
7c77d3fb7c38fb69eed5082ca5dafbbd8eb006be
2022-07-11 15:40:43
f0c1s
chore: update messaging for Deploy tab (#14911)
false
update messaging for Deploy tab (#14911)
chore
diff --git a/app/client/src/ce/constants/messages.ts b/app/client/src/ce/constants/messages.ts index 55b37a48cebc..05b96af8a88a 100644 --- a/app/client/src/ce/constants/messages.ts +++ b/app/client/src/ce/constants/messages.ts @@ -770,6 +770,8 @@ export const DISCARD_CHANGES = () => "Discard changes"; // GIT DEPLOY begin export const DEPLOY = () => "Deploy"; export const DEPLOY_YOUR_APPLICATION = () => "Deploy your application"; +export const CHANGES_SINCE_LAST_DEPLOYMENT = () => + "Changes since last deployment"; export const CHANGES_ONLY_USER = () => "Changes since last commit"; export const CHANGES_MADE_SINCE_LAST_COMMIT = () => "Changes made since last commit"; @@ -777,8 +779,19 @@ export const CHANGES_ONLY_MIGRATION = () => "Appsmith update changes since last commit"; export const CHANGES_USER_AND_MIGRATION = () => "Appsmith update and user changes since last commit"; +export const CURRENT_PAGE_DISCARD_WARNING = (page: string) => + `Current page (${page}) is in the discard list.`; // GIT DEPLOY end +// GIT CHANGE LIST begin +export const CHANGES_FROM_APPSMITH = () => + "Some changes are platform upgrades from Appsmith."; +export const TRY_TO_PULL = () => + "We will try to pull before pushing your changes."; +export const NOT_PUSHED_YET = () => + "These are the commits that haven't been pushed to remote yet."; +// GIT CHANGE LIST end + // GIT DELETE BRANCH begin export const DELETE = () => "Delete"; export const LOCAL_BRANCHES = () => "Local branches"; diff --git a/app/client/src/pages/Editor/gitSync/Tabs/Deploy.tsx b/app/client/src/pages/Editor/gitSync/Tabs/Deploy.tsx index 1cd7d435e27a..19856e67ef97 100644 --- a/app/client/src/pages/Editor/gitSync/Tabs/Deploy.tsx +++ b/app/client/src/pages/Editor/gitSync/Tabs/Deploy.tsx @@ -69,9 +69,10 @@ import { Space, Title } from "../components/StyledComponents"; import { Variant } from "components/ads"; import DiscardChangesWarning from "../components/DiscardChangesWarning"; import { changeInfoSinceLastCommit } from "../utils"; +import ScrollIndicator from "../../../../components/ads/ScrollIndicator"; const Section = styled.div` - margin-top: ${(props) => props.theme.spaces[11]}px; + margin-top: 0; margin-bottom: ${(props) => props.theme.spaces[11]}px; `; @@ -95,7 +96,20 @@ const SectionTitle = styled.div` `; const Container = styled.div` - width: 100%; + display: flex; + flex-direction: column; + height: 100%; + overflow-y: auto; + overflow-x: hidden; + scrollbar-width: none; + + &::-webkit-scrollbar-thumb { + background-color: transparent; + } + + &::-webkit-scrollbar { + width: 0; + } && ${LabelContainer} span { color: ${Colors.CHARCOAL}; @@ -106,7 +120,7 @@ const Container = styled.div` } `; -const INITIAL_COMMIT = "Initial Commit"; +const FIRST_COMMIT = "First Commit"; const NO_CHANGES_TO_COMMIT = "No changes to commit"; function SubmitWrapper(props: { @@ -149,7 +163,7 @@ function Deploy() { const upstreamErrorDocumentUrl = useSelector(getUpstreamErrorDocUrl); const discardDocUrl = useSelector(getDiscardDocUrl); const [commitMessage, setCommitMessage] = useState( - gitMetaData?.remoteUrl && lastDeployedAt ? "" : INITIAL_COMMIT, + gitMetaData?.remoteUrl && lastDeployedAt ? "" : FIRST_COMMIT, ); const [shouldDiscard, setShouldDiscard] = useState(false); const [isDiscarding, setIsDiscarding] = useState(isDiscardInProgress); @@ -272,8 +286,21 @@ function Deploy() { setShowDiscardWarning(false); setShouldDiscard(false); }; + + const scrollWrapperRef = React.createRef<HTMLDivElement>(); + useEffect(() => { + if (scrollWrapperRef.current) { + setTimeout(() => { + const top = scrollWrapperRef.current?.scrollHeight || 0; + scrollWrapperRef.current?.scrollTo({ + top: top, + }); + }, 100); + } + }, [scrollWrapperRef]); + return ( - <Container data-testid={"t--deploy-tab-container"}> + <Container data-testid={"t--deploy-tab-container"} ref={scrollWrapperRef}> <Title>{createMessage(DEPLOY_YOUR_APPLICATION)}</Title> <Section> {hasChangesToCommit && ( @@ -284,7 +311,7 @@ function Deploy() { {changeReasonText} </Text> )} - <GitChangesList /> + <GitChangesList isAutoUpdate={isAutoUpdate} /> <Row> <SectionTitle> <span>{createMessage(COMMIT_TO)}</span> @@ -435,6 +462,7 @@ function Deploy() { {!pullRequired && !isConflicting && ( <DeployPreview showSuccess={isCommitAndPushSuccessful} /> )} + <ScrollIndicator containerRef={scrollWrapperRef} mode="DARK" top="37px" /> </Container> ); } diff --git a/app/client/src/pages/Editor/gitSync/Tabs/GitConnection.tsx b/app/client/src/pages/Editor/gitSync/Tabs/GitConnection.tsx index 4cf6075ba5ae..2068b0754f17 100644 --- a/app/client/src/pages/Editor/gitSync/Tabs/GitConnection.tsx +++ b/app/client/src/pages/Editor/gitSync/Tabs/GitConnection.tsx @@ -112,7 +112,7 @@ const Container = styled.div` } &::-webkit-scrollbar { - width: 0px; + width: 0; } `; diff --git a/app/client/src/pages/Editor/gitSync/components/DeployPreview.tsx b/app/client/src/pages/Editor/gitSync/components/DeployPreview.tsx index 9e7fd81c27aa..5443bcd6c8db 100644 --- a/app/client/src/pages/Editor/gitSync/components/DeployPreview.tsx +++ b/app/client/src/pages/Editor/gitSync/components/DeployPreview.tsx @@ -24,7 +24,7 @@ const Container = styled.div` display: flex; flex: 1; flex-direction: row; - width: calc(100% - 30px); + gap: ${(props) => props.theme.spaces[6]}px; `; const ButtonWrapper = styled.div` @@ -51,16 +51,6 @@ const IconWrapper = styled.div` } `; -const ContentWrapper = styled.div` - margin-left: ${(props) => props.theme.spaces[6]}px; -`; - -const CloudIconWrapper = styled.div` - display: flex; - justify-content: center; - align-items: center; -`; - export default function DeployPreview(props: { showSuccess: boolean }) { const pageId = useSelector(getCurrentPageId) as string; const lastDeployedAt = useSelector(getApplicationLastDeployedAt); @@ -85,14 +75,14 @@ export default function DeployPreview(props: { showSuccess: boolean }) { : ""; return lastDeployedAt ? ( <Container className="t--git-deploy-preview"> - <CloudIconWrapper> + <div> {props.showSuccess ? ( <SuccessTick height="30px" width="30px" /> ) : ( <CloudyIcon /> )} - </CloudIconWrapper> - <ContentWrapper> + </div> + <div> <ButtonWrapper onClick={showDeployPreview}> <Text case={Case.UPPERCASE} @@ -109,7 +99,7 @@ export default function DeployPreview(props: { showSuccess: boolean }) { <Text color={Colors.GREY_6} type={TextType.P3}> {lastDeployedAtMsg} </Text> - </ContentWrapper> + </div> </Container> ) : null; } diff --git a/app/client/src/pages/Editor/gitSync/components/DiscardChangesWarning.tsx b/app/client/src/pages/Editor/gitSync/components/DiscardChangesWarning.tsx index 1fcb4c559e7d..6ee047cdd79a 100644 --- a/app/client/src/pages/Editor/gitSync/components/DiscardChangesWarning.tsx +++ b/app/client/src/pages/Editor/gitSync/components/DiscardChangesWarning.tsx @@ -6,11 +6,15 @@ import { import React from "react"; import { createMessage, + CURRENT_PAGE_DISCARD_WARNING, DISCARD_CHANGES_WARNING, } from "@appsmith/constants/messages"; import styled from "styled-components"; import { Colors } from "constants/Colors"; import { Text, TextType } from "design-system"; +import { useSelector } from "react-redux"; +import { getCurrentPageName } from "selectors/editorSelectors"; +import { getGitStatus } from "selectors/gitSyncSelectors"; function DiscardWarningMessage() { return ( @@ -20,6 +24,22 @@ function DiscardWarningMessage() { ); } +function CurrentPageDiscardWarningMessage({ + isCurrentPageDiscardable, + pageName, +}: { + isCurrentPageDiscardable: boolean; + pageName: string; +}) { + const out = isCurrentPageDiscardable ? ( + <Text color={Colors.ERROR_600} type={TextType.P3}> + {createMessage(CURRENT_PAGE_DISCARD_WARNING, pageName)} + </Text> + ) : null; + + return out; +} + const Container = styled.div` margin: 8px 0 16px; `; @@ -28,6 +48,15 @@ export default function DiscardChangesWarning({ discardDocUrl, onCloseDiscardChangesWarning, }: any) { + const currentPageName = useSelector(getCurrentPageName) || ""; + const modifiedPageList = useSelector( + getGitStatus, + )?.modified.map((page: string) => page.toLocaleLowerCase()); + const isCurrentPageDiscardable = + modifiedPageList?.some((page: string) => + page.includes(currentPageName.toLocaleLowerCase()), + ) || false; + const notificationBannerOptions: NotificationBannerProps = { canClose: true, className: "error", @@ -39,7 +68,14 @@ export default function DiscardChangesWarning({ return ( <Container> <NotificationBanner {...notificationBannerOptions}> - <DiscardWarningMessage /> + <> + <DiscardWarningMessage /> + <br /> + <CurrentPageDiscardWarningMessage + isCurrentPageDiscardable={isCurrentPageDiscardable} + pageName={currentPageName} + /> + </> </NotificationBanner> </Container> ); diff --git a/app/client/src/pages/Editor/gitSync/components/GitChangesList.test.tsx b/app/client/src/pages/Editor/gitSync/components/GitChangesList.test.tsx index 1d7025000f75..61e76e66c459 100644 --- a/app/client/src/pages/Editor/gitSync/components/GitChangesList.test.tsx +++ b/app/client/src/pages/Editor/gitSync/components/GitChangesList.test.tsx @@ -21,64 +21,8 @@ describe("GitChangesList", () => { expect(Array.isArray(actual)).toBeTruthy(); const actualJSON = JSON.stringify(actual); expect(actualJSON.length).toBeGreaterThan(0); - const expected = [ - { - key: "change-status-widget", - ref: null, - props: { - message: "1 page modified", - iconName: "widget", - hasValue: true, - }, - _owner: null, - _store: {}, - }, - { - key: "change-status-query", - ref: null, - props: { - message: "1 query modified", - iconName: "query", - hasValue: true, - }, - _owner: null, - _store: {}, - }, - { - key: "change-status-git-commit", - ref: null, - props: { - message: "1 commit ahead and 1 commit behind", - iconName: "git-commit", - hasValue: true, - }, - _owner: null, - _store: {}, - }, - { - key: "change-status-js", - ref: null, - props: { - message: "1 JS Object modified", - iconName: "js", - hasValue: true, - }, - _owner: null, - _store: {}, - }, - { - key: "change-status-database-2-line", - ref: null, - props: { - message: "1 datasource modified", - iconName: "database-2-line", - hasValue: true, - }, - _owner: null, - _store: {}, - }, - ]; - const expectedJSON = JSON.stringify(expected); + const expectedJSON = + '[{"key":"change-status-widget","ref":null,"props":{"message":"1 page modified","iconName":"widget","hasValue":true},"_owner":null,"_store":{}},{"key":"change-status-query","ref":null,"props":{"message":"1 query modified","iconName":"query","hasValue":true},"_owner":null,"_store":{}},{"key":"change-status-js","ref":null,"props":{"message":"1 JS Object modified","iconName":"js","hasValue":true},"_owner":null,"_store":{}},{"key":"change-status-database-2-line","ref":null,"props":{"message":"1 datasource modified","iconName":"database-2-line","hasValue":true},"_owner":null,"_store":{}},{"key":"change-status-git-commit","ref":null,"props":{"message":"1 commit ahead. These are the commits that haven\'t been pushed to remote yet.","iconName":"git-commit","hasValue":true},"_owner":null,"_store":{}},{"key":"change-status-git-commit","ref":null,"props":{"message":"1 commit behind. We will try to pull before pushing your changes.","iconName":"git-commit","hasValue":true},"_owner":null,"_store":{}}]'; expect(actualJSON).toEqual(expectedJSON); }); it("returns empty array", () => { diff --git a/app/client/src/pages/Editor/gitSync/components/GitChangesList.tsx b/app/client/src/pages/Editor/gitSync/components/GitChangesList.tsx index 88147b8c1d87..1a13cdc08495 100644 --- a/app/client/src/pages/Editor/gitSync/components/GitChangesList.tsx +++ b/app/client/src/pages/Editor/gitSync/components/GitChangesList.tsx @@ -1,15 +1,21 @@ import React from "react"; import styled from "constants/DefaultTheme"; import { Classes } from "components/ads/common"; +import Icon, { IconSize } from "components/ads/Icon"; import { Text, TextType } from "design-system"; import { Colors } from "constants/Colors"; -import Icon, { IconSize } from "components/ads/Icon"; import { useSelector } from "react-redux"; import { getGitStatus, getIsFetchingGitStatus, } from "selectors/gitSyncSelectors"; import { GitStatusData } from "reducers/uiReducers/gitSyncReducer"; +import { + CHANGES_FROM_APPSMITH, + createMessage, + NOT_PUSHED_YET, + TRY_TO_PULL, +} from "@appsmith/constants/messages"; const DummyChange = styled.div` width: 50%; @@ -43,7 +49,8 @@ const Changes = styled.div` `; export enum Kind { - COMMIT = "COMMIT", + AHEAD_COMMIT = "AHEAD_COMMIT", + BEHIND_COMMIT = "BEHIND_COMMIT", DATA_SOURCE = "DATA_SOURCE", JS_OBJECT = "JS_OBJECT", PAGE = "PAGE", @@ -61,10 +68,15 @@ type GitStatusMap = { }; const STATUS_MAP: GitStatusMap = { - [Kind.COMMIT]: (status: GitStatusData) => ({ - message: commitMessage(status), + [Kind.AHEAD_COMMIT]: (status: GitStatusData) => ({ + message: aheadCommitMessage(status), + iconName: "git-commit", + hasValue: (status?.aheadCount || 0) > 0, + }), + [Kind.BEHIND_COMMIT]: (status: GitStatusData) => ({ + message: behindCommitMessage(status), iconName: "git-commit", - hasValue: (status?.aheadCount || 0) > 0 || (status?.behindCount || 0) > 0, + hasValue: (status?.behindCount || 0) > 0, }), [Kind.DATA_SOURCE]: (status: GitStatusData) => ({ message: `${status?.modifiedDatasources || 0} ${ @@ -96,22 +108,24 @@ const STATUS_MAP: GitStatusMap = { }), }; -function commitMessage(status: GitStatusData) { - const aheadCount = status?.aheadCount || 0; +function behindCommitMessage(status: GitStatusData) { const behindCount = status?.behindCount || 0; - const aheadMessage = - aheadCount > 0 - ? (aheadCount || 0) === 1 - ? `${aheadCount || 0} commit ahead` - : `${aheadCount || 0} commits ahead` - : null; - const behindMessage = - behindCount > 0 - ? (behindCount || 0) === 1 - ? `${behindCount || 0} commit behind` - : `${behindCount || 0} commits behind ` - : null; - return [aheadMessage, behindMessage].filter((i) => i !== null).join(" and "); + let behindMessage = + (behindCount || 0) === 1 + ? `${behindCount || 0} commit` + : `${behindCount || 0} commits`; + behindMessage += ` behind. ${createMessage(TRY_TO_PULL)}`; + return behindMessage; +} + +function aheadCommitMessage(status: GitStatusData) { + const aheadCount = status?.aheadCount || 0; + let aheadMessage = + (aheadCount || 0) === 1 + ? `${aheadCount || 0} commit` + : `${aheadCount || 0} commits`; + aheadMessage += ` ahead. ${createMessage(NOT_PUSHED_YET)}`; + return aheadMessage; } export function Change(props: Partial<GitStatusProps>) { @@ -150,9 +164,10 @@ export function gitChangeListData( const changeKind = [ Kind.PAGE, Kind.QUERY, - Kind.COMMIT, Kind.JS_OBJECT, Kind.DATA_SOURCE, + Kind.AHEAD_COMMIT, + Kind.BEHIND_COMMIT, ]; return changeKind .map((type: Kind) => STATUS_MAP[type](status)) @@ -161,10 +176,24 @@ export function gitChangeListData( .filter((s) => !!s); } -export default function GitChangesList() { +export default function GitChangesList({ + isAutoUpdate, +}: { + isAutoUpdate: boolean; +}) { const status: GitStatusData = useSelector(getGitStatus) as GitStatusData; const loading = useSelector(getIsFetchingGitStatus); const changes = gitChangeListData(status); + if (isAutoUpdate) { + changes.push( + <Change + hasValue={isAutoUpdate} + iconName="info" + key="change-status-auto-update" + message={createMessage(CHANGES_FROM_APPSMITH)} + />, + ); + } return loading ? ( <DummyChange data-testid={"t--git-change-loading-dummy"} /> ) : ( diff --git a/app/client/src/pages/Editor/gitSync/utils.test.ts b/app/client/src/pages/Editor/gitSync/utils.test.ts index 172ffa587079..9c661536c109 100644 --- a/app/client/src/pages/Editor/gitSync/utils.test.ts +++ b/app/client/src/pages/Editor/gitSync/utils.test.ts @@ -224,7 +224,7 @@ describe("gitSync utils", () => { }; const actual = changeInfoSinceLastCommit(applicationData); const expected = { - changeReasonText: "Changes since last commit", + changeReasonText: "Changes since last deployment", isAutoUpdate: false, isManualUpdate: false, }; @@ -245,7 +245,7 @@ describe("gitSync utils", () => { }; const actual = changeInfoSinceLastCommit(applicationData); const expected = { - changeReasonText: "Appsmith update changes since last commit", + changeReasonText: "Changes since last deployment", isAutoUpdate: true, isManualUpdate: false, }; @@ -266,7 +266,7 @@ describe("gitSync utils", () => { }; const actual = changeInfoSinceLastCommit(applicationData); const expected = { - changeReasonText: "Appsmith update and user changes since last commit", + changeReasonText: "Changes since last deployment", isAutoUpdate: true, isManualUpdate: true, }; @@ -287,7 +287,7 @@ describe("gitSync utils", () => { }; const actual = changeInfoSinceLastCommit(applicationData); const expected = { - changeReasonText: "Changes since last commit", + changeReasonText: "Changes since last deployment", isAutoUpdate: false, isManualUpdate: true, }; diff --git a/app/client/src/pages/Editor/gitSync/utils.ts b/app/client/src/pages/Editor/gitSync/utils.ts index 7d56d8a03509..6bee7cc8ca9a 100644 --- a/app/client/src/pages/Editor/gitSync/utils.ts +++ b/app/client/src/pages/Editor/gitSync/utils.ts @@ -1,8 +1,6 @@ import { ApplicationPayload } from "@appsmith/constants/ReduxActionConstants"; import { - CHANGES_ONLY_MIGRATION, - CHANGES_ONLY_USER, - CHANGES_USER_AND_MIGRATION, + CHANGES_SINCE_LAST_DEPLOYMENT, createMessage, } from "@appsmith/constants/messages"; @@ -75,11 +73,6 @@ export function changeInfoSinceLastCommit( ) { const isAutoUpdate = !!currentApplication?.isAutoUpdate; const isManualUpdate = !!currentApplication?.isManualUpdate; - const changeReason = isAutoUpdate - ? isManualUpdate - ? CHANGES_USER_AND_MIGRATION - : CHANGES_ONLY_MIGRATION - : CHANGES_ONLY_USER; - const changeReasonText = createMessage(changeReason); + const changeReasonText = createMessage(CHANGES_SINCE_LAST_DEPLOYMENT); return { isAutoUpdate, isManualUpdate, changeReasonText }; }
8b32fb6e594aff320925cdaba31a5866d8671834
2023-02-20 18:32:46
Sumit Kumar
fix: allow MsSQL plugin to connect with ssl encryption (#20568)
false
allow MsSQL plugin to connect with ssl encryption (#20568)
fix
diff --git a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/SSLDetails.java b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/SSLDetails.java index efb05715f39a..397ac397c11e 100644 --- a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/SSLDetails.java +++ b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/SSLDetails.java @@ -31,7 +31,10 @@ public enum AuthType { PREFERRED, REQUIRED, DISABLED, // Following for MongoDB Connections. - CA_CERTIFICATE, SELF_SIGNED_CERTIFICATE + CA_CERTIFICATE, SELF_SIGNED_CERTIFICATE, + + // For MsSQL connections + NO_VERIFY } public enum CACertificateType { diff --git a/app/server/appsmith-plugins/mssqlPlugin/src/main/java/com/external/plugins/MssqlPlugin.java b/app/server/appsmith-plugins/mssqlPlugin/src/main/java/com/external/plugins/MssqlPlugin.java index 19d89c73c007..230c801a4ba9 100644 --- a/app/server/appsmith-plugins/mssqlPlugin/src/main/java/com/external/plugins/MssqlPlugin.java +++ b/app/server/appsmith-plugins/mssqlPlugin/src/main/java/com/external/plugins/MssqlPlugin.java @@ -19,6 +19,7 @@ import com.appsmith.external.models.Property; import com.appsmith.external.models.PsParameterDTO; import com.appsmith.external.models.RequestParamDTO; +import com.appsmith.external.models.SSLDetails; import com.appsmith.external.plugins.BasePlugin; import com.appsmith.external.plugins.PluginExecutor; import com.appsmith.external.plugins.SmartSubstitutionInterface; @@ -582,7 +583,7 @@ private static HikariDataSource createConnectionPool(DatasourceConfiguration dat .append(";"); } - urlBuilder.append("encrypt=false"); + addSslOptionsToUrlBuilder(datasourceConfiguration, urlBuilder); hikariConfig.setJdbcUrl(urlBuilder.toString()); @@ -595,6 +596,42 @@ private static HikariDataSource createConnectionPool(DatasourceConfiguration dat return hikariDatasource; } + private static void addSslOptionsToUrlBuilder(DatasourceConfiguration datasourceConfiguration, + StringBuilder urlBuilder) throws AppsmithPluginException { + /* + * - Ideally, it is never expected to be null because the SSL dropdown is set to a initial value. + */ + if (datasourceConfiguration.getConnection() == null + || datasourceConfiguration.getConnection().getSsl() == null + || datasourceConfiguration.getConnection().getSsl().getAuthType() == null) { + throw new AppsmithPluginException( + AppsmithPluginError.PLUGIN_ERROR, + "Appsmith server has failed to fetch SSL configuration from datasource configuration form. " + + "Please reach out to Appsmith customer support to resolve this."); + } + + /* + * - By default, the driver configures SSL in the no verify mode. + */ + SSLDetails.AuthType sslAuthType = datasourceConfiguration.getConnection().getSsl().getAuthType(); + switch (sslAuthType) { + case DISABLE: + urlBuilder.append("encrypt=false;"); + + break; + case NO_VERIFY: + urlBuilder.append("encrypt=true;"); + urlBuilder.append("trustServerCertificate=true;"); + + break; + default: + throw new AppsmithPluginException( + AppsmithPluginError.PLUGIN_ERROR, + "Appsmith server has found an unexpected SSL option: " + sslAuthType + ". Please reach out to" + + " Appsmith customer support to resolve this."); + } + } + /** * First checks if the connection pool is still valid. If yes, we fetch a connection from the pool and return * In case a connection is not available in the pool, SQL Exception is thrown diff --git a/app/server/appsmith-plugins/mssqlPlugin/src/main/resources/form.json b/app/server/appsmith-plugins/mssqlPlugin/src/main/resources/form.json index 17572791ee54..f7896f4b22c4 100644 --- a/app/server/appsmith-plugins/mssqlPlugin/src/main/resources/form.json +++ b/app/server/appsmith-plugins/mssqlPlugin/src/main/resources/form.json @@ -71,6 +71,28 @@ ] } ] + }, + { + "id": 3, + "sectionName": "SSL", + "children": [ + { + "label": "SSL Mode", + "configProperty": "datasourceConfiguration.connection.ssl.authType", + "controlType": "DROP_DOWN", + "initialValue": "NO_VERIFY", + "options": [ + { + "label": "Disable", + "value": "DISABLE" + }, + { + "label": "Enabled with no verify", + "value": "NO_VERIFY" + } + ] + } + ] } ] } diff --git a/app/server/appsmith-plugins/mssqlPlugin/src/test/java/com/external/plugins/MssqlPluginTest.java b/app/server/appsmith-plugins/mssqlPlugin/src/test/java/com/external/plugins/MssqlPluginTest.java index 518fd03df5fc..323253dea4d1 100755 --- a/app/server/appsmith-plugins/mssqlPlugin/src/test/java/com/external/plugins/MssqlPluginTest.java +++ b/app/server/appsmith-plugins/mssqlPlugin/src/test/java/com/external/plugins/MssqlPluginTest.java @@ -14,6 +14,7 @@ import com.appsmith.external.models.Property; import com.appsmith.external.models.PsParameterDTO; import com.appsmith.external.models.RequestParamDTO; +import com.appsmith.external.models.SSLDetails; import com.external.plugins.exceptions.MssqlPluginError; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; @@ -147,6 +148,12 @@ private DatasourceConfiguration createDatasourceConfiguration() { DatasourceConfiguration dsConfig = new DatasourceConfiguration(); dsConfig.setAuthentication(authDTO); dsConfig.setEndpoints(List.of(endpoint)); + + /* set ssl mode */ + dsConfig.setConnection(new com.appsmith.external.models.Connection()); + dsConfig.getConnection().setSsl(new SSLDetails()); + dsConfig.getConnection().getSsl().setAuthType(SSLDetails.AuthType.NO_VERIFY); + return dsConfig; } @@ -675,7 +682,8 @@ public void testNumericStringHavingLeadingZeroWithPreparedStatement() { Mono<HikariDataSource> connectionCreateMono = pluginExecutor.datasourceCreate(dsConfig).cache(); Mono<ActionExecutionResult> resultMono = connectionCreateMono - .flatMap(pool -> pluginExecutor.executeParameterized(pool, executeActionDTO, dsConfig, actionConfiguration)); + .flatMap(pool -> pluginExecutor.executeParameterized(pool, executeActionDTO, dsConfig, + actionConfiguration)); StepVerifier.create(resultMono) .assertNext(result -> { diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/migrations/DatabaseChangelog2.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/migrations/DatabaseChangelog2.java index 786daa8aad3f..58cddbbd07ab 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/migrations/DatabaseChangelog2.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/migrations/DatabaseChangelog2.java @@ -2791,4 +2791,20 @@ public void removeUsagePulsesForAppsmithCloud(MongoTemplate mongoTemplate, @NonL } } + /** + * We are introducing SSL settings config for MSSQL, hence this migration configures older existing datasources + * with a setting that matches their current configuration (i.e. set to `disabled` since they have been running + * with encryption disabled post the Spring 6 upgrade). + * + */ + @ChangeSet(order = "041", id = "add-ssl-mode-settings-for-existing-mssql-datasources", author = "") + public void addSslModeSettingsForExistingMssqlDatasource(MongoTemplate mongoTemplate) { + Plugin mssqlPlugin = mongoTemplate.findOne(query(where("packageName").is("mssql-plugin")), + Plugin.class); + Query queryToGetDatasources = getQueryToFetchAllDomainObjectsWhichAreNotDeletedUsingPluginId(mssqlPlugin); + + Update update = new Update(); + update.set("datasourceConfiguration.connection.ssl.authType", "DISABLE"); + mongoTemplate.updateMulti(queryToGetDatasources, update, Datasource.class); + } }
8bfc3ee87eca618ed9a00ad6e5a5b11f3075f06b
2022-06-29 17:47:14
Rishabh Rathod
fix: store value spec as JsObject bug is resolved (#14788)
false
store value spec as JsObject bug is resolved (#14788)
fix
diff --git a/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/ActionExecution/StoreValue_spec.ts b/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/ActionExecution/StoreValue_spec.ts index 5fe0903a70d4..d5eefb330263 100644 --- a/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/ActionExecution/StoreValue_spec.ts +++ b/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/ActionExecution/StoreValue_spec.ts @@ -33,28 +33,15 @@ describe("storeValue Action test", () => { toRun: false, shouldCreateNewJSObj: true, }); - - //Bug 14503 - // jsEditor.EditJSObj(jsObjectBody); - // agHelper.AssertAutoSave(); - - // running twice due to bug - Cypress._.times(2, () => { - cy.get(jsEditor._runButton) - .first() - .click() - .wait(3000); - }); - + agHelper.WaitUntilToastDisappear('created successfully') + agHelper.GetNClick(jsEditor._runButton); agHelper.ValidateToastMessage( JSON.stringify({ val1: "number 1", val2: "number 2", val3: "number 3", val4: "number 4", - }), - 2, + }), 2 ); }); - }); diff --git a/app/client/cypress/support/Pages/AggregateHelper.ts b/app/client/cypress/support/Pages/AggregateHelper.ts index b8fe4a543dd9..785cf5717743 100644 --- a/app/client/cypress/support/Pages/AggregateHelper.ts +++ b/app/client/cypress/support/Pages/AggregateHelper.ts @@ -381,14 +381,19 @@ export class AggregateHelper { }); } - public GetNClick(selector: string, index = 0, force = false) { + public GetNClick( + selector: string, + index = 0, + force = false, + waitTimeInterval = 500, + ) { const locator = selector.startsWith("//") ? cy.xpath(selector) : cy.get(selector); return locator .eq(index) .click({ force: force }) - .wait(500); + .wait(waitTimeInterval); } public GetNClickByContains( @@ -438,8 +443,8 @@ export class AggregateHelper { switchName: string, toggle: "check" | "uncheck" = "check", ) { - let locator = cy.xpath(this.locator._switchToggle(switchName)); - let parentLoc = locator.parent("label"); + const locator = cy.xpath(this.locator._switchToggle(switchName)); + const parentLoc = locator.parent("label"); if (toggle == "check") parentLoc.then(($parent) => { if (!$parent.hasClass("t--switch-widget-active")) {
08e0cc0431e1326d929d4337a1d3594aa61eabf2
2023-10-30 14:46:13
Anagh Hegde
feat: Add API to support partial import (#28357)
false
Add API to support partial import (#28357)
feat
diff --git a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/constants/AnalyticsEvents.java b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/constants/AnalyticsEvents.java index 07e64f3a670e..744496623c1a 100644 --- a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/constants/AnalyticsEvents.java +++ b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/constants/AnalyticsEvents.java @@ -84,7 +84,9 @@ public enum AnalyticsEvents { DS_TEST_EVENT_FAILED("Test_Datasource_Failed"), GIT_STALE_FILE_LOCK_DELETED, - SERVER_SETUP_COMPLETE("server_setup_complete"); + SERVER_SETUP_COMPLETE("server_setup_complete"), + + PARTIAL_IMPORT; private final String eventName; diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/controllers/ApplicationController.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/controllers/ApplicationController.java index dea331d246f8..869f43d058dd 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/controllers/ApplicationController.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/controllers/ApplicationController.java @@ -6,6 +6,7 @@ import com.appsmith.server.exports.internal.PartialExportService; import com.appsmith.server.fork.internal.ApplicationForkingService; import com.appsmith.server.imports.internal.ImportApplicationService; +import com.appsmith.server.imports.internal.PartialImportService; import com.appsmith.server.services.ApplicationPageService; import com.appsmith.server.services.ApplicationService; import com.appsmith.server.services.ApplicationSnapshotService; @@ -27,7 +28,8 @@ public ApplicationController( ExportApplicationService exportApplicationService, ThemeService themeService, ApplicationSnapshotService applicationSnapshotService, - PartialExportService partialExportService) { + PartialExportService partialExportService, + PartialImportService partialImportService) { super( service, applicationPageService, @@ -37,6 +39,7 @@ public ApplicationController( exportApplicationService, themeService, applicationSnapshotService, - partialExportService); + partialExportService, + partialImportService); } } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/controllers/ce/ApplicationControllerCE.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/controllers/ce/ApplicationControllerCE.java index 9d737b49c274..40706829c7aa 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/controllers/ce/ApplicationControllerCE.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/controllers/ce/ApplicationControllerCE.java @@ -12,6 +12,7 @@ import com.appsmith.server.dtos.ApplicationImportDTO; import com.appsmith.server.dtos.ApplicationPagesDTO; import com.appsmith.server.dtos.GitAuthDTO; +import com.appsmith.server.dtos.PartialExportFileDTO; import com.appsmith.server.dtos.ReleaseItemsDTO; import com.appsmith.server.dtos.ResponseDTO; import com.appsmith.server.dtos.UserHomepageDTO; @@ -21,6 +22,7 @@ import com.appsmith.server.exports.internal.PartialExportService; import com.appsmith.server.fork.internal.ApplicationForkingService; import com.appsmith.server.imports.internal.ImportApplicationService; +import com.appsmith.server.imports.internal.PartialImportService; import com.appsmith.server.services.ApplicationPageService; import com.appsmith.server.services.ApplicationService; import com.appsmith.server.services.ApplicationSnapshotService; @@ -64,8 +66,8 @@ public class ApplicationControllerCE extends BaseController<ApplicationService, private final ExportApplicationService exportApplicationService; private final ThemeService themeService; private final ApplicationSnapshotService applicationSnapshotService; - private final PartialExportService partialExportService; + private final PartialImportService partialImportService; @Autowired public ApplicationControllerCE( @@ -77,7 +79,8 @@ public ApplicationControllerCE( ExportApplicationService exportApplicationService, ThemeService themeService, ApplicationSnapshotService applicationSnapshotService, - PartialExportService partialExportService) { + PartialExportService partialExportService, + PartialImportService partialImportService) { super(service); this.applicationPageService = applicationPageService; this.applicationFetcher = applicationFetcher; @@ -87,6 +90,7 @@ public ApplicationControllerCE( this.themeService = themeService; this.applicationSnapshotService = applicationSnapshotService; this.partialExportService = partialExportService; + this.partialImportService = partialImportService; } @JsonView(Views.Public.class) @@ -368,20 +372,34 @@ public Mono<ResponseDTO<List<Application>>> getAll( } @JsonView(Views.Public.class) - @PostMapping("/export/partial/{applicationId}/{pageId}") + @PostMapping(value = "/export/partial/{applicationId}/{pageId}", consumes = MediaType.APPLICATION_JSON_VALUE) public Mono<ResponseEntity<Object>> exportApplicationPartially( @PathVariable String applicationId, @PathVariable String pageId, @RequestHeader(name = FieldName.BRANCH_NAME, required = false) String branchName, - @RequestBody MultiValueMap<String, String> params, - @RequestBody String widgets) { + @Valid @RequestBody PartialExportFileDTO fileDTO) { // params - contains ids of jsLib, actions and datasourceIds to be exported return partialExportService - .getPartialExportResources(applicationId, pageId, branchName, params, widgets) + .getPartialExportResources(applicationId, pageId, branchName, fileDTO) .map(fetchedResource -> { HttpHeaders responseHeaders = fetchedResource.getHttpHeaders(); Object applicationResource = fetchedResource.getApplicationResource(); return new ResponseEntity<>(applicationResource, responseHeaders, HttpStatus.OK); }); } + + @JsonView(Views.Public.class) + @PostMapping( + value = "/import/partial/{workspaceId}/{applicationId}", + consumes = MediaType.MULTIPART_FORM_DATA_VALUE) + public Mono<ResponseDTO<Application>> importApplicationPartially( + @RequestPart("file") Mono<Part> fileMono, + @PathVariable String workspaceId, + @PathVariable String applicationId, + @RequestParam String pageId, + @RequestHeader(name = FieldName.BRANCH_NAME, required = false) String branchName) { + return fileMono.flatMap(fileData -> partialImportService.importResourceInPage( + workspaceId, applicationId, pageId, branchName, fileData)) + .map(fetchedResource -> new ResponseDTO<>(HttpStatus.OK.value(), fetchedResource, null)); + } } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/dtos/PartialExportFileDTO.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/dtos/PartialExportFileDTO.java new file mode 100644 index 000000000000..c5f8997298da --- /dev/null +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/dtos/PartialExportFileDTO.java @@ -0,0 +1,20 @@ +package com.appsmith.server.dtos; + +import lombok.Data; + +import java.util.ArrayList; +import java.util.List; + +@Data +public class PartialExportFileDTO { + + List<String> actionList = new ArrayList<>(); + + List<String> actionCollectionList = new ArrayList<>(); + + List<String> customJsLib = new ArrayList<>(); + + List<String> datasourceList = new ArrayList<>(); + + String widget = ""; +} diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/exports/internal/PartialExportServiceCE.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/exports/internal/PartialExportServiceCE.java index 44c109f23136..8e521d7fdc67 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/exports/internal/PartialExportServiceCE.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/exports/internal/PartialExportServiceCE.java @@ -1,14 +1,10 @@ package com.appsmith.server.exports.internal; import com.appsmith.server.dtos.ExportFileDTO; -import org.springframework.util.MultiValueMap; +import com.appsmith.server.dtos.PartialExportFileDTO; import reactor.core.publisher.Mono; public interface PartialExportServiceCE { Mono<ExportFileDTO> getPartialExportResources( - String applicationId, - String pageId, - String branchName, - MultiValueMap<String, String> params, - String widgets); + String applicationId, String pageId, String branchName, PartialExportFileDTO partialExportFileDTO); } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/exports/internal/PartialExportServiceCEImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/exports/internal/PartialExportServiceCEImpl.java index 640dba8e3661..4db03216084f 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/exports/internal/PartialExportServiceCEImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/exports/internal/PartialExportServiceCEImpl.java @@ -15,6 +15,7 @@ import com.appsmith.server.dtos.ExportFileDTO; import com.appsmith.server.dtos.ExportingMetaDTO; import com.appsmith.server.dtos.MappedExportableResourcesDTO; +import com.appsmith.server.dtos.PartialExportFileDTO; import com.appsmith.server.exceptions.AppsmithError; import com.appsmith.server.exceptions.AppsmithException; import com.appsmith.server.exports.exportable.ExportableService; @@ -31,12 +32,10 @@ import org.springframework.http.ContentDisposition; import org.springframework.http.HttpHeaders; import org.springframework.http.MediaType; -import org.springframework.util.MultiValueMap; import reactor.core.publisher.Mono; import java.nio.charset.StandardCharsets; import java.util.List; -import java.util.Set; import java.util.stream.Collectors; import static com.appsmith.server.constants.ResourceModes.EDIT; @@ -60,11 +59,7 @@ public class PartialExportServiceCEImpl implements PartialExportServiceCE { @Override public Mono<ExportFileDTO> getPartialExportResources( - String applicationId, - String pageId, - String branchName, - MultiValueMap<String, String> params, - String widgets) { + String applicationId, String pageId, String branchName, PartialExportFileDTO partialExportFileDTO) { /* * Params has ids for actions, customJsLibs and datasource * Export the resources based on the value of these entities @@ -96,21 +91,25 @@ public Mono<ExportFileDTO> getPartialExportResources( return applicationMono .flatMap(application -> { applicationJson.setExportedApplication(application); - return pluginExportableService.getExportableEntities( - exportingMetaDTO, mappedResourcesDTO, applicationMono, applicationJson); + return pluginExportableService + .getExportableEntities( + exportingMetaDTO, mappedResourcesDTO, applicationMono, applicationJson) + .thenReturn(applicationJson); }) .flatMap(pluginList -> { - if (params.containsKey(FieldName.DATASOURCE_LIST)) { - return datasourceExportableService.getExportableEntities( - exportingMetaDTO, mappedResourcesDTO, applicationMono, applicationJson); + if (partialExportFileDTO.getDatasourceList().size() > 0) { + return datasourceExportableService + .getExportableEntities( + exportingMetaDTO, mappedResourcesDTO, applicationMono, applicationJson) + .thenReturn(applicationJson); } return Mono.just(applicationJson); }) .flatMap(appJson -> { - if (params.containsKey(FieldName.CUSTOM_JS_LIB_LIST)) { + if (partialExportFileDTO.getCustomJsLib().size() > 0) { return exportFilteredCustomJSLib( applicationId, - Set.copyOf(params.get(FieldName.CUSTOM_JS_LIB_LIST)), + partialExportFileDTO.getCustomJsLib(), applicationJson, branchName) .flatMap(jsLibList -> { @@ -129,33 +128,34 @@ public Mono<ExportFileDTO> getPartialExportResources( // update page name in meta and exportable DTO for resource to name mapping .flatMap(branchedPageId -> updatePageNameInResourceMapDTO(branchedPageId, mappedResourcesDTO)) // export actions + // export js objects .flatMap(branchedPageId -> { - if (params.containsKey(FieldName.ACTION_LIST) - || params.containsKey(FieldName.ACTION_COLLECTION_LIST)) { - return exportActions( + if (partialExportFileDTO.getActionCollectionList().size() > 0) { + return exportActionCollections( branchedPageId, - Set.copyOf(params.get(FieldName.ACTION_LIST)), + partialExportFileDTO.getActionCollectionList(), applicationJson, mappedResourcesDTO) .then(Mono.just(branchedPageId)); } return Mono.just(branchedPageId); }) - // export js objects .flatMap(branchedPageId -> { - if (params.containsKey(FieldName.ACTION_COLLECTION_LIST)) { - return exportActionCollections( - branchedPageId, - Set.copyOf(params.get(FieldName.ACTION_COLLECTION_LIST)), - applicationJson, - mappedResourcesDTO); + if (partialExportFileDTO.getActionCollectionList().size() > 0 + || partialExportFileDTO.getActionList().size() > 0) { + return exportActions( + branchedPageId, + partialExportFileDTO.getActionList(), + applicationJson, + mappedResourcesDTO) + .then(Mono.just(branchedPageId)); } - return Mono.just(applicationJson); + return Mono.just(branchedPageId); }) .flatMap(appJson -> { // Remove the datasources not in use - if (params.containsKey(FieldName.DATASOURCE_LIST)) { - exportDatasource(Set.copyOf(params.get(FieldName.DATASOURCE_LIST)), applicationJson); + if (partialExportFileDTO.getDatasourceList().size() > 0) { + exportDatasource(partialExportFileDTO.getDatasourceList(), applicationJson); // Sanitise the datasource datasourceExportableService.sanitizeEntities( exportingMetaDTO, @@ -168,7 +168,7 @@ public Mono<ExportFileDTO> getPartialExportResources( .map(exportedJson -> { String applicationName = applicationJson.getExportedApplication().getName(); - applicationJson.setWidgets(widgets); + applicationJson.setWidgets(partialExportFileDTO.getWidget()); applicationJson.setExportedApplication(null); String stringifiedFile = gson.toJson(exportedJson); Object jsonObject = gson.fromJson(stringifiedFile, Object.class); @@ -186,7 +186,7 @@ public Mono<ExportFileDTO> getPartialExportResources( }); } - private void exportDatasource(Set<String> validDatasource, ApplicationJson applicationJson) { + private void exportDatasource(List<String> validDatasource, ApplicationJson applicationJson) { List<DatasourceStorage> datasourceList = applicationJson.getDatasourceList().stream() .filter(datasourceStorage -> validDatasource.contains(datasourceStorage.getDatasourceId())) .toList(); @@ -194,7 +194,7 @@ private void exportDatasource(Set<String> validDatasource, ApplicationJson appli } private Mono<ApplicationJson> exportFilteredCustomJSLib( - String applicationId, Set<String> customJSLibSet, ApplicationJson applicationJson, String branchName) { + String applicationId, List<String> customJSLibSet, ApplicationJson applicationJson, String branchName) { return customJSLibService .getAllJSLibsInApplication(applicationId, branchName, false) .flatMap(customJSLibs -> { @@ -209,7 +209,7 @@ private Mono<ApplicationJson> exportFilteredCustomJSLib( private Mono<ApplicationJson> exportActions( String pageId, - Set<String> validActions, + List<String> validActions, ApplicationJson applicationJson, MappedExportableResourcesDTO mappedResourcesDTO) { return newActionService.findByPageId(pageId).collectList().flatMap(actions -> { @@ -229,7 +229,7 @@ private Mono<ApplicationJson> exportActions( private Mono<ApplicationJson> exportActionCollections( String pageId, - Set<String> validActions, + List<String> validActions, ApplicationJson applicationJson, MappedExportableResourcesDTO mappedResourcesDTO) { return actionCollectionService.findByPageId(pageId).collectList().flatMap(actionCollections -> { diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/imports/internal/PartialImportService.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/imports/internal/PartialImportService.java new file mode 100644 index 000000000000..f328e5096829 --- /dev/null +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/imports/internal/PartialImportService.java @@ -0,0 +1,3 @@ +package com.appsmith.server.imports.internal; + +public interface PartialImportService extends PartialImportServiceCE {} diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/imports/internal/PartialImportServiceCE.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/imports/internal/PartialImportServiceCE.java new file mode 100644 index 000000000000..3fffce596f63 --- /dev/null +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/imports/internal/PartialImportServiceCE.java @@ -0,0 +1,11 @@ +package com.appsmith.server.imports.internal; + +import com.appsmith.server.domains.Application; +import org.springframework.http.codec.multipart.Part; +import reactor.core.publisher.Mono; + +public interface PartialImportServiceCE { + + Mono<Application> importResourceInPage( + String workspaceId, String applicationId, String pageId, String branchName, Part file); +} diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/imports/internal/PartialImportServiceCEImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/imports/internal/PartialImportServiceCEImpl.java new file mode 100644 index 000000000000..63af9fb0dc99 --- /dev/null +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/imports/internal/PartialImportServiceCEImpl.java @@ -0,0 +1,280 @@ +package com.appsmith.server.imports.internal; + +import com.appsmith.external.constants.AnalyticsEvents; +import com.appsmith.external.models.Datasource; +import com.appsmith.server.acl.AclPermission; +import com.appsmith.server.constants.FieldName; +import com.appsmith.server.domains.ActionCollection; +import com.appsmith.server.domains.Application; +import com.appsmith.server.domains.CustomJSLib; +import com.appsmith.server.domains.NewAction; +import com.appsmith.server.domains.NewPage; +import com.appsmith.server.domains.Plugin; +import com.appsmith.server.domains.Workspace; +import com.appsmith.server.dtos.ApplicationJson; +import com.appsmith.server.dtos.ImportingMetaDTO; +import com.appsmith.server.dtos.MappedImportableResourcesDTO; +import com.appsmith.server.exceptions.AppsmithError; +import com.appsmith.server.exceptions.AppsmithException; +import com.appsmith.server.helpers.ce.ImportApplicationPermissionProvider; +import com.appsmith.server.imports.importable.ImportableService; +import com.appsmith.server.newpages.base.NewPageService; +import com.appsmith.server.repositories.PermissionGroupRepository; +import com.appsmith.server.services.AnalyticsService; +import com.appsmith.server.services.ApplicationService; +import com.appsmith.server.services.WorkspaceService; +import com.appsmith.server.solutions.ActionPermission; +import com.appsmith.server.solutions.ApplicationPermission; +import com.appsmith.server.solutions.DatasourcePermission; +import com.appsmith.server.solutions.PagePermission; +import com.appsmith.server.solutions.WorkspacePermission; +import com.google.gson.Gson; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.http.codec.multipart.Part; +import org.springframework.transaction.reactive.TransactionalOperator; +import reactor.core.publisher.Flux; +import reactor.core.publisher.Mono; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; + +@RequiredArgsConstructor +@Slf4j +public class PartialImportServiceCEImpl implements PartialImportServiceCE { + + private final ImportApplicationService importApplicationService; + private final WorkspaceService workspaceService; + private final ApplicationService applicationService; + private final AnalyticsService analyticsService; + private final DatasourcePermission datasourcePermission; + private final WorkspacePermission workspacePermission; + private final ApplicationPermission applicationPermission; + private final PagePermission pagePermission; + private final ActionPermission actionPermission; + private final Gson gson; + private final TransactionalOperator transactionalOperator; + private final PermissionGroupRepository permissionGroupRepository; + private final ImportableService<Plugin> pluginImportableService; + private final ImportableService<NewPage> newPageImportableService; + private final ImportableService<CustomJSLib> customJSLibImportableService; + private final ImportableService<Datasource> datasourceImportableService; + private final ImportableService<NewAction> newActionImportableService; + private final ImportableService<ActionCollection> actionCollectionImportableService; + private final NewPageService newPageService; + + @Override + public Mono<Application> importResourceInPage( + String workspaceId, String applicationId, String pageId, String branchName, Part file) { + /* + 1. Get branchedPageId from pageId and branchName + 2. Get Application Mono + 3. Prepare the Meta DTO's + 4. Get plugin data + 5. Import datasources + 6. Import customJsLib + 7. Import actions + 8. Import actionCollection + */ + + MappedImportableResourcesDTO mappedImportableResourcesDTO = new MappedImportableResourcesDTO(); + + Mono<String> branchedPageIdMono = + newPageService.findBranchedPageId(branchName, pageId, AclPermission.MANAGE_PAGES); + + // Extract file and get App Json + Mono<Application> partiallyImportedAppMono = importApplicationService + .extractApplicationJson(file) + .zipWith(getImportApplicationPermissions()) + .flatMap(tuple -> { + ApplicationJson applicationJson = tuple.getT1(); + ImportApplicationPermissionProvider permissionProvider = tuple.getT2(); + // Set Application in App JSON, remove the pages other than the one to be imported in + // Set the current page in the JSON to be imported + // Debug and get the value from getImportApplicationMono method if any difference + // Modify the Application set in JSON to be imported + + Mono<Workspace> workspaceMono = workspaceService + .findById(workspaceId, permissionProvider.getRequiredPermissionOnTargetWorkspace()) + .switchIfEmpty(Mono.defer(() -> { + log.error( + "No workspace found with id: {} and permission: {}", + workspaceId, + permissionProvider.getRequiredPermissionOnTargetWorkspace()); + return Mono.error(new AppsmithException( + AppsmithError.ACL_NO_RESOURCE_FOUND, FieldName.WORKSPACE, workspaceId)); + })) + .cache(); + + ImportingMetaDTO importingMetaDTO = + new ImportingMetaDTO(workspaceId, applicationId, branchName, false, permissionProvider); + + // Get the Application from DB + Mono<Application> importedApplicationMono = applicationService + .findByBranchNameAndDefaultApplicationId( + branchName, + applicationId, + permissionProvider.getRequiredPermissionOnTargetApplication()) + .cache(); + + return importedApplicationMono + .flatMap(application -> { + applicationJson.setExportedApplication(application); + return Mono.just(applicationJson); + }) + // Import Custom Js Lib and Datasource + .then(getApplicationImportableEntities( + importingMetaDTO, + mappedImportableResourcesDTO, + workspaceMono, + importedApplicationMono, + applicationJson)) + .thenReturn("done") + // Update the pageName map for actions and action collection + .then(paneNameMapForActionAndActionCollectionInAppJson( + branchedPageIdMono, applicationJson, mappedImportableResourcesDTO)) + .thenReturn("done") + // Import Actions and action collection + .then(getActionAndActionCollectionImport( + importingMetaDTO, + mappedImportableResourcesDTO, + workspaceMono, + importedApplicationMono, + applicationJson)) + .thenReturn("done") + .then(Mono.defer(() -> { + Application application = applicationJson.getExportedApplication(); + return newActionImportableService + .updateImportedEntities( + application, importingMetaDTO, mappedImportableResourcesDTO) + .then(newPageImportableService.updateImportedEntities( + application, importingMetaDTO, mappedImportableResourcesDTO)) + .flatMap( + newPage -> applicationService.update(application.getId(), application)); + })); + }) + .as(transactionalOperator::transactional); + + // Send Analytics event + return partiallyImportedAppMono.flatMap(application -> { + final Map<String, Object> eventData = Map.of(FieldName.APPLICATION, application); + + final Map<String, Object> data = Map.of( + FieldName.APPLICATION_ID, application.getId(), + FieldName.WORKSPACE_ID, application.getWorkspaceId(), + FieldName.EVENT_DATA, eventData); + + return analyticsService.sendObjectEvent(AnalyticsEvents.PARTIAL_IMPORT, application, data); + }); + } + + private Mono<ImportApplicationPermissionProvider> getImportApplicationPermissions() { + return permissionGroupRepository.getCurrentUserPermissionGroups().flatMap(userPermissionGroups -> { + ImportApplicationPermissionProvider permissionProvider = ImportApplicationPermissionProvider.builder( + applicationPermission, + pagePermission, + actionPermission, + datasourcePermission, + workspacePermission) + .requiredPermissionOnTargetWorkspace(workspacePermission.getReadPermission()) + .requiredPermissionOnTargetApplication(applicationPermission.getEditPermission()) + .permissionRequiredToCreateDatasource(true) + .permissionRequiredToEditDatasource(true) + .currentUserPermissionGroups(userPermissionGroups) + .build(); + return Mono.just(permissionProvider); + }); + } + + private Mono<Void> getApplicationImportableEntities( + ImportingMetaDTO importingMetaDTO, + MappedImportableResourcesDTO mappedImportableResourcesDTO, + Mono<Workspace> workspaceMono, + Mono<Application> importedApplicationMono, + ApplicationJson applicationJson) { + Mono<Void> customJSLibMono = pluginImportableService.importEntities( + importingMetaDTO, + mappedImportableResourcesDTO, + workspaceMono, + importedApplicationMono, + applicationJson); + + Mono<Void> datasourceMono = datasourceImportableService.importEntities( + importingMetaDTO, + mappedImportableResourcesDTO, + workspaceMono, + importedApplicationMono, + applicationJson); + + Mono<Void> customJsLibMono = customJSLibImportableService.importEntities( + importingMetaDTO, mappedImportableResourcesDTO, null, null, applicationJson); + + return Flux.merge(List.of(customJsLibMono, datasourceMono, customJSLibMono)) + .then(); + } + + private Mono<Void> getActionAndActionCollectionImport( + ImportingMetaDTO importingMetaDTO, + MappedImportableResourcesDTO mappedImportableResourcesDTO, + Mono<Workspace> workspaceMono, + Mono<Application> importedApplicationMono, + ApplicationJson applicationJson) { + Mono<Void> actionMono = newActionImportableService.importEntities( + importingMetaDTO, + mappedImportableResourcesDTO, + workspaceMono, + importedApplicationMono, + applicationJson); + + Mono<Void> actionCollectionMono = actionCollectionImportableService.importEntities( + importingMetaDTO, + mappedImportableResourcesDTO, + workspaceMono, + importedApplicationMono, + applicationJson); + + return Flux.merge(List.of(actionMono, actionCollectionMono)).then(); + } + + private Mono<String> paneNameMapForActionAndActionCollectionInAppJson( + Mono<String> branchedPageIdMono, + ApplicationJson applicationJson, + MappedImportableResourcesDTO mappedImportableResourcesDTO) { + return branchedPageIdMono.flatMap( + pageId -> newPageService.findById(pageId, Optional.empty()).flatMap(newPage -> { + String pageName = newPage.getUnpublishedPage().getName(); + // update page name reference with newPage + Map<String, NewPage> pageNameMap = new HashMap<>(); + pageNameMap.put(pageName, newPage); + mappedImportableResourcesDTO.setPageNameMap(pageNameMap); + + applicationJson.getActionList().forEach(action -> { + action.getPublishedAction().setPageId(pageName); + action.getUnpublishedAction().setPageId(pageName); + if (action.getPublishedAction().getCollectionId() != null) { + String collectionName = action.getPublishedAction() + .getCollectionId() + .split("_")[1]; + action.getPublishedAction().setCollectionId(pageName + "_" + collectionName); + action.getUnpublishedAction().setCollectionId(pageName + "_" + collectionName); + } + + String actionName = action.getId().split("_")[1]; + action.setId(pageName + "_" + actionName); + action.setGitSyncId(null); + }); + + applicationJson.getActionCollectionList().forEach(actionCollection -> { + actionCollection.getPublishedCollection().setPageId(pageName); + actionCollection.getUnpublishedCollection().setPageId(pageName); + + String collectionName = actionCollection.getId().split("_")[1]; + actionCollection.setId(pageName + "_" + collectionName); + actionCollection.setGitSyncId(null); + }); + return Mono.just(pageName); + })); + } +} diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/imports/internal/PartialImportServiceImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/imports/internal/PartialImportServiceImpl.java new file mode 100644 index 000000000000..1db60b46d2ad --- /dev/null +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/imports/internal/PartialImportServiceImpl.java @@ -0,0 +1,72 @@ +package com.appsmith.server.imports.internal; + +import com.appsmith.external.models.Datasource; +import com.appsmith.server.domains.ActionCollection; +import com.appsmith.server.domains.CustomJSLib; +import com.appsmith.server.domains.NewAction; +import com.appsmith.server.domains.NewPage; +import com.appsmith.server.domains.Plugin; +import com.appsmith.server.imports.importable.ImportableService; +import com.appsmith.server.newpages.base.NewPageService; +import com.appsmith.server.repositories.PermissionGroupRepository; +import com.appsmith.server.services.AnalyticsService; +import com.appsmith.server.services.ApplicationService; +import com.appsmith.server.services.WorkspaceService; +import com.appsmith.server.solutions.ActionPermission; +import com.appsmith.server.solutions.ApplicationPermission; +import com.appsmith.server.solutions.DatasourcePermission; +import com.appsmith.server.solutions.PagePermission; +import com.appsmith.server.solutions.WorkspacePermission; +import com.google.gson.Gson; +import lombok.extern.slf4j.Slf4j; +import org.springframework.context.annotation.Primary; +import org.springframework.stereotype.Service; +import org.springframework.transaction.reactive.TransactionalOperator; + +@Slf4j +@Service +@Primary +public class PartialImportServiceImpl extends PartialImportServiceCEImpl implements PartialImportService { + + public PartialImportServiceImpl( + ImportApplicationService importApplicationService, + WorkspaceService workspaceService, + ApplicationService applicationService, + AnalyticsService analyticsService, + DatasourcePermission datasourcePermission, + WorkspacePermission workspacePermission, + ApplicationPermission applicationPermission, + PagePermission pagePermission, + ActionPermission actionPermission, + Gson gson, + TransactionalOperator transactionalOperator, + PermissionGroupRepository permissionGroupRepository, + ImportableService<Plugin> pluginImportableService, + ImportableService<NewPage> newPageImportableService, + ImportableService<CustomJSLib> customJSLibImportableService, + ImportableService<Datasource> datasourceImportableService, + ImportableService<NewAction> newActionImportableService, + ImportableService<ActionCollection> actionCollectionImportableService, + NewPageService newPageService) { + super( + importApplicationService, + workspaceService, + applicationService, + analyticsService, + datasourcePermission, + workspacePermission, + applicationPermission, + pagePermission, + actionPermission, + gson, + transactionalOperator, + permissionGroupRepository, + pluginImportableService, + newPageImportableService, + customJSLibImportableService, + datasourceImportableService, + newActionImportableService, + actionCollectionImportableService, + newPageService); + } +} diff --git a/app/server/appsmith-server/src/test/java/com/appsmith/server/controllers/ApplicationControllerTest.java b/app/server/appsmith-server/src/test/java/com/appsmith/server/controllers/ApplicationControllerTest.java index 520169f8296e..1f2f8c965d78 100644 --- a/app/server/appsmith-server/src/test/java/com/appsmith/server/controllers/ApplicationControllerTest.java +++ b/app/server/appsmith-server/src/test/java/com/appsmith/server/controllers/ApplicationControllerTest.java @@ -11,6 +11,7 @@ import com.appsmith.server.helpers.GitFileUtils; import com.appsmith.server.helpers.RedisUtils; import com.appsmith.server.imports.internal.ImportApplicationService; +import com.appsmith.server.imports.internal.PartialImportService; import com.appsmith.server.services.AnalyticsService; import com.appsmith.server.services.ApplicationPageService; import com.appsmith.server.services.ApplicationService; @@ -83,6 +84,9 @@ public class ApplicationControllerTest { @MockBean PartialExportService partialExportService; + @MockBean + PartialImportService partialImportService; + private String getFileName(int length) { StringBuilder fileName = new StringBuilder(); for (int count = 0; count < length; count++) {
007f598c09fab91169cb9950ca89c8c6b6a06784
2025-02-14 22:13:23
Manish Kumar
chore: git detach and push algorithm refinement (#39298)
false
git detach and push algorithm refinement (#39298)
chore
diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/git/central/CentralGitServiceCEImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/git/central/CentralGitServiceCEImpl.java index f6ab0a0862c5..a4c5052f3caa 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/git/central/CentralGitServiceCEImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/git/central/CentralGitServiceCEImpl.java @@ -76,7 +76,6 @@ import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; import reactor.util.function.Tuple2; -import reactor.util.function.Tuple3; import java.io.IOException; import java.time.Instant; @@ -1600,77 +1599,83 @@ private Mono<String> commitArtifact( /** * Method to remove all the git metadata for the artifact and connected resources. This will remove: * - local repo - * - all the branched artifacts present in DB except for default artifact + * - all the branched artifacts present in DB except for base artifact * * @param branchedArtifactId : id of any branched artifact for the given repo * @param artifactType : type of artifact - * @return : the base artifact after removal of git flow. + * @param gitType: type of git service + * @return : the base artifact after removal of git attributes and other branches. */ + @Override public Mono<? extends Artifact> detachRemote( String branchedArtifactId, ArtifactType artifactType, GitType gitType) { + GitHandlingService gitHandlingService = gitHandlingServiceResolver.getGitHandlingService(gitType); GitArtifactHelper<?> gitArtifactHelper = gitArtifactHelperResolver.getArtifactHelper(artifactType); AclPermission gitConnectPermission = gitArtifactHelper.getArtifactGitConnectPermission(); - Mono<Tuple2<? extends Artifact, ? extends Artifact>> baseAndBranchedArtifactMono = - getBaseAndBranchedArtifacts(branchedArtifactId, artifactType, gitConnectPermission); + Mono<? extends Artifact> branchedArtifactMono = + gitArtifactHelper.getArtifactById(branchedArtifactId, gitConnectPermission); - Mono<? extends Artifact> disconnectMono = baseAndBranchedArtifactMono - .flatMap(artifactTuples -> { - Artifact baseArtifact = artifactTuples.getT1(); + Mono<? extends Artifact> disconnectMono = branchedArtifactMono + .flatMap(branchedArtifact -> { + GitArtifactMetadata branchedGitMetadata = branchedArtifact.getGitArtifactMetadata(); - if (isBaseGitMetadataInvalid(baseArtifact.getGitArtifactMetadata(), gitType)) { + if (branchedArtifact.getGitArtifactMetadata() == null) { return Mono.error(new AppsmithException( AppsmithError.INVALID_GIT_CONFIGURATION, "Please reconfigure the artifact to connect to git repo")); } - GitArtifactMetadata gitArtifactMetadata = baseArtifact.getGitArtifactMetadata(); - ArtifactJsonTransformationDTO jsonTransformationDTO = new ArtifactJsonTransformationDTO(); - jsonTransformationDTO.setRefType(RefType.branch); - jsonTransformationDTO.setWorkspaceId(baseArtifact.getWorkspaceId()); - jsonTransformationDTO.setBaseArtifactId(gitArtifactMetadata.getDefaultArtifactId()); - jsonTransformationDTO.setRepoName(gitArtifactMetadata.getRepoName()); - jsonTransformationDTO.setArtifactType(baseArtifact.getArtifactType()); - jsonTransformationDTO.setRefName(gitArtifactMetadata.getRefName()); - - // Remove the git contents from file system - return Mono.zip( - gitHandlingService.listReferences(jsonTransformationDTO, false), Mono.just(baseArtifact)); - }) - .flatMap(tuple -> { - List<String> localBranches = tuple.getT1(); - Artifact baseArtifact = tuple.getT2(); - - GitArtifactMetadata baseGitMetadata = baseArtifact.getGitArtifactMetadata(); - localBranches.remove(baseGitMetadata.getRefName()); + String baseArtifactId = branchedGitMetadata.getDefaultArtifactId(); + String repoName = branchedGitMetadata.getRepoName(); + String workspaceId = branchedArtifact.getWorkspaceId(); + String refName = branchedGitMetadata.getRefName(); + RefType refType = RefType.branch; - baseArtifact.setGitArtifactMetadata(null); - gitArtifactHelper.resetAttributeInBaseArtifact(baseArtifact); + ArtifactJsonTransformationDTO jsonTransformationDTO = + new ArtifactJsonTransformationDTO(workspaceId, baseArtifactId, repoName, artifactType); - ArtifactJsonTransformationDTO jsonTransformationDTO = new ArtifactJsonTransformationDTO(); - jsonTransformationDTO.setRefType(RefType.branch); - jsonTransformationDTO.setWorkspaceId(baseArtifact.getWorkspaceId()); - jsonTransformationDTO.setBaseArtifactId(baseGitMetadata.getDefaultArtifactId()); - jsonTransformationDTO.setRepoName(baseGitMetadata.getRepoName()); - jsonTransformationDTO.setArtifactType(baseArtifact.getArtifactType()); - jsonTransformationDTO.setRefName(baseGitMetadata.getRefName()); + jsonTransformationDTO.setRefName(refName); + jsonTransformationDTO.setRefType(refType); // Remove the parent artifact branch name from the list Mono<Boolean> removeRepoMono = gitHandlingService.removeRepository(jsonTransformationDTO); - Mono<? extends Artifact> updatedArtifactMono = gitArtifactHelper.saveArtifact(baseArtifact); - Flux<? extends Artifact> deleteAllBranchesFlux = - gitArtifactHelper.deleteAllBranches(branchedArtifactId, localBranches); + AclPermission artifactEditPermission = gitArtifactHelper.getArtifactEditPermission(); + + Mono<? extends Artifact> deleteAllBranchesExceptBase = gitArtifactHelper + .getAllArtifactByBaseId(baseArtifactId, artifactEditPermission) + .flatMap(artifact -> { + if (artifact.getGitArtifactMetadata() == null + || RefType.tag.equals(artifact.getGitArtifactMetadata() + .getRefType())) { + return Mono.just(artifact); + } - return Mono.zip(updatedArtifactMono, removeRepoMono, deleteAllBranchesFlux.collectList()) - .map(Tuple3::getT1); + // it's established that git artifact metadata is not null + if (!artifact.getId().equals(baseArtifactId)) { + return gitArtifactHelper.deleteArtifactByResource(artifact); + } + + // base Artifact condition fulfilled + artifact.setGitArtifactMetadata(null); + gitArtifactHelper.resetAttributeInBaseArtifact(artifact); + + return gitArtifactHelper.saveArtifact(artifact).flatMap(baseArtifact -> { + return gitArtifactHelper.disconnectEntitiesOfBaseArtifact(baseArtifact); + }); + }) + .filter(artifact -> { + return artifact.getId().equals(baseArtifactId); + }) + .next(); + + return Mono.zip(deleteAllBranchesExceptBase, removeRepoMono).map(Tuple2::getT1); }) - .flatMap(updatedBaseArtifact -> { - return gitArtifactHelper - .disconnectEntitiesOfBaseArtifact(updatedBaseArtifact) - .then(gitAnalyticsUtils.addAnalyticsForGitOperation( - AnalyticsEvents.GIT_DISCONNECT, updatedBaseArtifact, false)); + .flatMap(disconnectedBaseArtifact -> { + return gitAnalyticsUtils.addAnalyticsForGitOperation( + AnalyticsEvents.GIT_DISCONNECT, disconnectedBaseArtifact, false); }) .name(GitSpan.OPS_DETACH_REMOTE) .tap(Micrometer.observation(observationRegistry)); diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/git/fs/GitFSServiceCEImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/git/fs/GitFSServiceCEImpl.java index 6b8f5eb355a5..df6fc99f9afc 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/git/fs/GitFSServiceCEImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/git/fs/GitFSServiceCEImpl.java @@ -5,7 +5,6 @@ import com.appsmith.external.dtos.GitRefDTO; import com.appsmith.external.dtos.GitStatusDTO; import com.appsmith.external.dtos.MergeStatusDTO; -import com.appsmith.external.git.constants.GitConstants; import com.appsmith.external.git.constants.GitConstants.GitCommandConstants; import com.appsmith.external.git.constants.GitSpan; import com.appsmith.external.git.constants.ce.RefType; @@ -482,18 +481,17 @@ public Mono<Tuple2<? extends Artifact, String>> commitArtifact( result.append(".\nPush Result : "); return Mono.zip( Mono.just(tuple.getT2()), - pushArtifact(tuple.getT2(), false) + pushArtifact(tuple.getT2()) .map(pushResult -> result.append(pushResult).toString())); }); } /** * Push flow for dehydrated apps - * - * @param branchedArtifact application which needs to be pushed to remote repo + * @param branchedArtifact artifact which needs to be pushed to remote repo * @return Success message */ - protected Mono<String> pushArtifact(Artifact branchedArtifact, boolean isFileLock) { + protected Mono<String> pushArtifact(Artifact branchedArtifact) { ArtifactType artifactType = branchedArtifact.getArtifactType(); GitArtifactHelper<?> gitArtifactHelper = gitArtifactHelperResolver.getArtifactHelper(artifactType); Mono<GitArtifactMetadata> gitArtifactMetadataMono = Mono.just(branchedArtifact.getGitArtifactMetadata()); @@ -515,16 +513,7 @@ protected Mono<String> pushArtifact(Artifact branchedArtifact, boolean isFileLoc // Make sure that ssh Key is unEncrypted for the use. Mono<String> gitPushResult = gitArtifactMetadataMono .flatMap(gitMetadata -> { - return gitRedisUtils - .acquireGitLock( - artifactType, - gitMetadata.getDefaultArtifactId(), - GitConstants.GitCommandConstants.PUSH, - isFileLock) - .thenReturn(branchedArtifact); - }) - .flatMap(artifact -> { - GitArtifactMetadata gitData = artifact.getGitArtifactMetadata(); + GitArtifactMetadata gitData = branchedArtifact.getGitArtifactMetadata(); if (gitData == null || !StringUtils.hasText(gitData.getRefName()) @@ -536,61 +525,55 @@ protected Mono<String> pushArtifact(Artifact branchedArtifact, boolean isFileLoc } Path baseRepoSuffix = gitArtifactHelper.getRepoSuffixPath( - artifact.getWorkspaceId(), gitData.getDefaultArtifactId(), gitData.getRepoName()); + branchedArtifact.getWorkspaceId(), gitData.getDefaultArtifactId(), gitData.getRepoName()); GitAuth gitAuth = gitData.getGitAuth(); return fsGitHandler - .checkoutToBranch( + .pushApplication( baseRepoSuffix, - artifact.getGitArtifactMetadata().getRefName()) - .then(Mono.defer(() -> fsGitHandler - .pushApplication( - baseRepoSuffix, - gitData.getRemoteUrl(), - gitAuth.getPublicKey(), - gitAuth.getPrivateKey(), - gitData.getRefName()) - .zipWith(Mono.just(artifact)))) + gitData.getRemoteUrl(), + gitAuth.getPublicKey(), + gitAuth.getPrivateKey(), + gitData.getRefName()) .onErrorResume(error -> gitAnalyticsUtils .addAnalyticsForGitOperation( AnalyticsEvents.GIT_PUSH, - artifact, + branchedArtifact, error.getClass().getName(), error.getMessage(), - artifact.getGitArtifactMetadata().getIsRepoPrivate()) - .flatMap(application1 -> { + gitData.getIsRepoPrivate()) + .flatMap(artifact -> { + log.error("Error during git push: {}", error.getMessage()); if (error instanceof TransportException) { return Mono.error( new AppsmithException(AppsmithError.INVALID_GIT_SSH_CONFIGURATION)); } + return Mono.error(new AppsmithException( - AppsmithError.GIT_ACTION_FAILED, "push", error.getMessage())); + AppsmithError.GIT_ACTION_FAILED, + GitCommandConstants.PUSH, + error.getMessage())); })); }) - .flatMap(tuple -> { - String pushResult = tuple.getT1(); - Artifact artifact = tuple.getT2(); - return pushArtifactErrorRecovery(pushResult, artifact).zipWith(Mono.just(artifact)); - }) - // Add BE analytics - .flatMap(tuple2 -> { - String pushStatus = tuple2.getT1(); - Artifact artifact = tuple2.getT2(); - Mono<Boolean> fileLockReleasedMono = Mono.just(TRUE).flatMap(flag -> { - if (!TRUE.equals(isFileLock)) { - return Mono.just(flag); - } - return Mono.defer(() -> gitRedisUtils.releaseFileLock( - artifactType, artifact.getGitArtifactMetadata().getDefaultArtifactId(), true)); - }); - - return pushArtifactErrorRecovery(pushStatus, artifact) - .then(fileLockReleasedMono) - .then(gitAnalyticsUtils.addAnalyticsForGitOperation( - AnalyticsEvents.GIT_PUSH, - artifact, - artifact.getGitArtifactMetadata().getIsRepoPrivate())) - .thenReturn(pushStatus); + .flatMap(pushResult -> { + log.info( + "Push result for artifact {} with id {} : {}", + branchedArtifact.getName(), + branchedArtifact.getId(), + pushResult); + + return pushArtifactErrorRecovery(pushResult, branchedArtifact) + .flatMap(pushStatus -> { + // Add analytics + return gitAnalyticsUtils + .addAnalyticsForGitOperation( + AnalyticsEvents.GIT_PUSH, + branchedArtifact, + branchedArtifact + .getGitArtifactMetadata() + .getIsRepoPrivate()) + .thenReturn(pushStatus); + }); }) .name(GitSpan.OPS_PUSH) .tap(Micrometer.observation(observationRegistry)); @@ -622,7 +605,8 @@ private Mono<String> pushArtifactErrorRecovery(String pushResult, Artifact artif AppsmithError.GIT_UPSTREAM_CHANGES.getErrorType(), AppsmithError.GIT_UPSTREAM_CHANGES.getMessage(), gitMetadata.getIsRepoPrivate()) - .flatMap(application1 -> Mono.error(new AppsmithException(AppsmithError.GIT_UPSTREAM_CHANGES))); + .then(Mono.error(new AppsmithException(AppsmithError.GIT_UPSTREAM_CHANGES))); + } else if (pushResult.contains("REJECTED_OTHERREASON") || pushResult.contains("pre-receive hook declined")) { Path path = gitArtifactHelper.getRepoSuffixPath( @@ -632,7 +616,7 @@ private Mono<String> pushArtifactErrorRecovery(String pushResult, Artifact artif .resetHard(path, gitMetadata.getRefName()) .then(Mono.error(new AppsmithException( AppsmithError.GIT_ACTION_FAILED, - "push", + GitCommandConstants.PUSH, "Unable to push changes as pre-receive hook declined. Please make sure that you don't have any rules enabled on the branch " + gitMetadata.getRefName()))); }
d9f20e33ad6140a41395b7f902da3e508f4ca620
2022-12-10 14:00:28
Ankita Kinger
chore: splitting the role name to avoid showing workspace name next to it (#18830)
false
splitting the role name to avoid showing workspace name next to it (#18830)
chore
diff --git a/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/OtherUIFeatures/ExportApplication_spec.js b/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/OtherUIFeatures/ExportApplication_spec.js index f1cf88dabf6c..4e001dccb3bd 100644 --- a/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/OtherUIFeatures/ExportApplication_spec.js +++ b/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/OtherUIFeatures/ExportApplication_spec.js @@ -65,7 +65,6 @@ describe("Export application as a JSON file", function() { cy.get(homePage.shareApp).click({ force: true }); // cy.shareApp(Cypress.env("TESTUSERNAME1"), homePage.adminRole); HomePage.InviteUserToWorkspaceFromApp( - workspaceId, Cypress.env("TESTUSERNAME1"), "Administrator", ); @@ -118,7 +117,6 @@ describe("Export application as a JSON file", function() { cy.get("h2").contains("Drag and drop a widget here"); cy.get(homePage.shareApp).click({ force: true }); HomePage.InviteUserToWorkspaceFromApp( - workspaceId, Cypress.env("TESTUSERNAME1"), "Developer", ); @@ -173,7 +171,6 @@ describe("Export application as a JSON file", function() { cy.get(homePage.shareApp).click({ force: true }); HomePage.InviteUserToWorkspaceFromApp( - workspaceId, Cypress.env("TESTUSERNAME1"), "App Viewer", ); diff --git a/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/Workspace/DeleteWorkspace_spec.js b/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/Workspace/DeleteWorkspace_spec.js index 94ef1bbfc7db..09e33256f688 100644 --- a/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/Workspace/DeleteWorkspace_spec.js +++ b/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/Workspace/DeleteWorkspace_spec.js @@ -1,8 +1,7 @@ /// <reference types="Cypress" /> import { ObjectsRegistry } from "../../../../support/Objects/Registry"; import homePage from "../../../../locators/HomePage"; -let HomePage = ObjectsRegistry.HomePage, - agHelper = ObjectsRegistry.AggregateHelper; +let HomePage = ObjectsRegistry.HomePage; describe("Delete workspace test spec", function() { let newWorkspaceName; diff --git a/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/Workspace/LeaveWorkspaceTest_spec.js b/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/Workspace/LeaveWorkspaceTest_spec.js index 9766ddece862..59a83c633df1 100644 --- a/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/Workspace/LeaveWorkspaceTest_spec.js +++ b/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/Workspace/LeaveWorkspaceTest_spec.js @@ -1,11 +1,8 @@ /// <reference types="Cypress" /> import { ObjectsRegistry } from "../../../../support/Objects/Registry"; -import homePage from "../../../../locators/HomePage"; -let HomePage = ObjectsRegistry.HomePage, - agHelper = ObjectsRegistry.AggregateHelper; +let HomePage = ObjectsRegistry.HomePage; describe("Leave workspace test spec", function() { - let newWorkspaceId; let newWorkspaceName; it("leave workspace menu is visible validation", function() { @@ -13,7 +10,6 @@ describe("Leave workspace test spec", function() { cy.createWorkspace(); cy.wait("@createWorkspace").then((interception) => { newWorkspaceName = interception.response.body.data.name; - newWorkspaceId = interception.response.body.data.name; cy.visit("/applications"); cy.openWorkspaceOptionsPopup(newWorkspaceName); cy.contains("Leave Workspace"); @@ -25,7 +21,6 @@ describe("Leave workspace test spec", function() { cy.createWorkspace(); cy.wait("@createWorkspace").then((interception) => { newWorkspaceName = interception.response.body.data.name; - newWorkspaceId = interception.response.body.data.name; cy.visit("/applications"); cy.openWorkspaceOptionsPopup(newWorkspaceName); cy.contains("Leave Workspace").click(); @@ -42,7 +37,6 @@ describe("Leave workspace test spec", function() { cy.createWorkspace(); cy.wait("@createWorkspace").then((interception) => { newWorkspaceName = interception.response.body.data.name; - newWorkspaceId = interception.response.body.data.name; cy.visit("/applications"); HomePage.InviteUserToWorkspace( newWorkspaceName, diff --git a/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/Workspace/MemberRoles_Spec.ts b/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/Workspace/MemberRoles_Spec.ts index 3c1ed7a364ca..138342b75430 100644 --- a/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/Workspace/MemberRoles_Spec.ts +++ b/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/Workspace/MemberRoles_Spec.ts @@ -1,7 +1,7 @@ import { ObjectsRegistry } from "../../../../support/Objects/Registry"; import HomePage from "../../../../locators/HomePage"; let workspaceId: any, appid: any; -let agHelper = ObjectsRegistry.AggregateHelper, +const agHelper = ObjectsRegistry.AggregateHelper, homePage = ObjectsRegistry.HomePage; describe("Create new workspace and invite user & validate all roles", () => { @@ -50,7 +50,7 @@ describe("Create new workspace and invite user & validate all roles", () => { cy.get(".t--dropdown-option") // .should("have.length", Cypress.env("Edition") === 1 ? 1 : 2) .should("have.length", 1) - .and("contain.text", `App Viewer - ${workspaceId}`); + .and("contain.text", `App Viewer`); cy.get(HomePage.closeBtn).click(); homePage.LaunchAppFromAppHover(); homePage.LogOutviaAPI(); @@ -89,11 +89,7 @@ describe("Create new workspace and invite user & validate all roles", () => { cy.get(".t--dropdown-option") // .should("have.length", Cypress.env("Edition") === 0 ? 2 : 3) .should("have.length", 2) - .and( - "contain.text", - `App Viewer - ${workspaceId}`, - `Developer - ${workspaceId}`, - ); + .and("contain.text", `App Viewer`, `Developer`); cy.get(HomePage.closeBtn).click(); homePage.LogOutviaAPI(); }); @@ -138,15 +134,8 @@ describe("Create new workspace and invite user & validate all roles", () => { cy.get(".t--dropdown-option") // .should("have.length", Cypress.env("Edition") === 0 ? 3 : 4) .should("have.length", 3) - .should( - "contain.text", - `App Viewer - ${workspaceId}`, - `Developer - ${workspaceId}`, - ); - cy.get(".t--dropdown-option").should( - "contain.text", - `Administrator - ${workspaceId}`, - ); + .should("contain.text", `App Viewer`, `Developer`); + cy.get(".t--dropdown-option").should("contain.text", `Administrator`); cy.get(HomePage.closeBtn).click(); homePage.LogOutviaAPI(); }); diff --git a/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/Workspace/ShareAppTests_spec.js b/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/Workspace/ShareAppTests_spec.js index 84f336c9ccde..3ad1f49ce566 100644 --- a/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/Workspace/ShareAppTests_spec.js +++ b/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/Workspace/ShareAppTests_spec.js @@ -3,9 +3,7 @@ import homePage from "../../../../locators/HomePage"; const publish = require("../../../../locators/publishWidgetspage.json"); import { ObjectsRegistry } from "../../../../support/Objects/Registry"; -const commonlocators = require("../../../../locators/commonlocators.json"); -let HomePage = ObjectsRegistry.HomePage, - agHelper = ObjectsRegistry.AggregateHelper; +let HomePage = ObjectsRegistry.HomePage; describe("Create new workspace and share with a user", function() { let workspaceId; @@ -33,7 +31,6 @@ describe("Create new workspace and share with a user", function() { cy.get("h2").contains("Drag and drop a widget here"); cy.get(homePage.shareApp).click({ force: true }); HomePage.InviteUserToWorkspaceFromApp( - workspaceId, Cypress.env("TESTUSERNAME1"), "App Viewer", ); diff --git a/app/client/cypress/support/Pages/HomePage.ts b/app/client/cypress/support/Pages/HomePage.ts index 22536f2d7d25..ff9029cfa0f1 100644 --- a/app/client/cypress/support/Pages/HomePage.ts +++ b/app/client/cypress/support/Pages/HomePage.ts @@ -27,11 +27,9 @@ export class HomePage { private _email = "//input[@type='text' and contains(@class,'bp3-input-ghost')]"; _visibleTextSpan = (spanText: string) => "//span[text()='" + spanText + "']"; - private _userRole = (role: string, workspaceName: string) => + private _userRole = (role: string) => "//div[contains(@class, 'label-container')]//span[1][text()='" + role + - " - " + - workspaceName + "']"; private _manageUsers = ".manageUsers"; @@ -53,8 +51,7 @@ export class HomePage { "//td[text()='" + email + "']/following-sibling::td//span[contains(@class, 't--deleteUser')]"; - private _userRoleDropDown = (role: string, WorkspaceName: string) => - "//span[text()='" + role + " - " + WorkspaceName + "']"; + private _userRoleDropDown = (role: string) => "//span[text()='" + role + "']"; //private _userRoleDropDown = (email: string) => "//td[text()='" + email + "']/following-sibling::td" private _leaveWorkspaceConfirmModal = ".t--member-delete-confirmation-modal"; private _workspaceImportAppModal = ".t--import-application-modal"; @@ -146,7 +143,7 @@ export class HomePage { .first() .click({ force: true }); this.agHelper.Sleep(500); - cy.xpath(this._userRole(role, workspaceName)).click({ force: true }); + cy.xpath(this._userRole(role)).click({ force: true }); this.agHelper.ClickButton("Invite"); cy.wait("@mockPostInvite") .its("request.headers") @@ -317,12 +314,12 @@ export class HomePage { ) { this.OpenMembersPageForWorkspace(workspaceName); cy.log(workspaceName, email, currentRole); - cy.xpath(this._userRoleDropDown(currentRole, workspaceName)) + cy.xpath(this._userRoleDropDown(currentRole)) .first() .click({ force: true }); //cy.xpath(this._userRoleDropDown(email)).first().click({force: true}); - cy.xpath(this._visibleTextSpan(`${newRole} - ${workspaceName}`)) + cy.xpath(this._visibleTextSpan(`${newRole}`)) .last() .click({ force: true }); this.agHelper.Sleep(); @@ -339,11 +336,7 @@ export class HomePage { cy.xpath(this._uploadFile).attachFile(fixtureJson); this.agHelper.Sleep(3500); } - public InviteUserToWorkspaceFromApp( - workspaceName: string, - email: string, - role: string, - ) { + public InviteUserToWorkspaceFromApp(email: string, role: string) { const successMessage = "The user has been invited successfully"; this.StubPostHeaderReq(); cy.xpath(this._email) @@ -353,7 +346,7 @@ export class HomePage { .first() .click({ force: true }); this.agHelper.Sleep(500); - cy.xpath(this._userRole(role, workspaceName)).click({ force: true }); + cy.xpath(this._userRole(role)).click({ force: true }); this.agHelper.ClickButton("Invite"); cy.wait("@mockPostInvite") .its("request.headers") diff --git a/app/client/src/ce/constants/messages.ts b/app/client/src/ce/constants/messages.ts index 0ffac330cfdc..7599d7768f56 100644 --- a/app/client/src/ce/constants/messages.ts +++ b/app/client/src/ce/constants/messages.ts @@ -1138,6 +1138,8 @@ export const APP_THEME_BETA_CARD_CONTENT = () => export const UPGRADE_TO_EE = (authLabel: string) => `Hello, I would like to upgrade and start using ${authLabel} authentication.`; +export const UPGRADE_TO_EE_FEATURE = (feature: string) => + `Hello, I would like to upgrade and start using the ${feature} feature.`; export const UPGRADE_TO_EE_GENERIC = () => `Hello, I would like to upgrade`; export const ADMIN_AUTH_SETTINGS_TITLE = () => "Select Authentication Method"; export const ADMIN_AUTH_SETTINGS_SUBTITLE = () => diff --git a/app/client/src/ce/pages/Upgrade/AccessControlUpgradePage.tsx b/app/client/src/ce/pages/Upgrade/AccessControlUpgradePage.tsx index 4a588cbd1f16..ee0f1a82f938 100644 --- a/app/client/src/ce/pages/Upgrade/AccessControlUpgradePage.tsx +++ b/app/client/src/ce/pages/Upgrade/AccessControlUpgradePage.tsx @@ -16,6 +16,7 @@ import { RESTRICT_PUBLIC_EXPOSURE_DETAIL1, SECURITY_APPS_LEAST_PRIVILEGE, SECURITY_APPS_LEAST_PRIVILEGE_DETAIL1, + UPGRADE_TO_EE_FEATURE, } from "@appsmith/constants/messages"; import useOnUpgrade from "utils/hooks/useOnUpgrade"; @@ -23,6 +24,10 @@ export function AccessControlUpgradePage() { const { onUpgrade } = useOnUpgrade({ logEventName: "ADMIN_SETTINGS_UPGRADE_HOOK", logEventData: { source: "Granular Access Control" }, + intercomMessage: createMessage( + UPGRADE_TO_EE_FEATURE, + "Granular Access Control for teams", + ), }); const header: Header = { diff --git a/app/client/src/ce/pages/Upgrade/AuditLogsUpgradePage.tsx b/app/client/src/ce/pages/Upgrade/AuditLogsUpgradePage.tsx index 8f7a9111c6b5..51f895e851b6 100644 --- a/app/client/src/ce/pages/Upgrade/AuditLogsUpgradePage.tsx +++ b/app/client/src/ce/pages/Upgrade/AuditLogsUpgradePage.tsx @@ -17,6 +17,7 @@ import { SECURITY_AND_COMPLIANCE, SECURITY_AND_COMPLIANCE_DETAIL1, SECURITY_AND_COMPLIANCE_DETAIL2, + UPGRADE_TO_EE_FEATURE, } from "@appsmith/constants/messages"; import useOnUpgrade from "utils/hooks/useOnUpgrade"; @@ -24,6 +25,7 @@ export function AuditLogsUpgradePage() { const { onUpgrade } = useOnUpgrade({ logEventName: "ADMIN_SETTINGS_UPGRADE_HOOK", logEventData: { source: "AuditLogs" }, + intercomMessage: createMessage(UPGRADE_TO_EE_FEATURE, "Audit Logs"), }); const header: Header = { diff --git a/app/client/src/ce/pages/workspace/Members.tsx b/app/client/src/ce/pages/workspace/Members.tsx index 686f965a70f0..c729663c4ab3 100644 --- a/app/client/src/ce/pages/workspace/Members.tsx +++ b/app/client/src/ce/pages/workspace/Members.tsx @@ -360,17 +360,18 @@ export default function MemberSettings(props: PageProps) { ? allRoles.map((role: any) => { return { id: role.id, - name: role.name, + name: role.name?.split(" - ")[0], desc: role.description, }; }) : []; const index = roles.findIndex( (role: { id: string; name: string; desc: string }) => - role.name === cellProps.cell.value, + role.name?.split(" - ")[0] === + cellProps.cell.value?.split(" - ")[0], ); if (data.username === currentUser?.username) { - return cellProps.cell.value; + return cellProps.cell.value?.split(" - ")[0]; } return ( <TableDropdown @@ -423,7 +424,7 @@ export default function MemberSettings(props: PageProps) { ? allRoles.map((role: any) => { return { id: role.id, - value: role.name, + value: role.name?.split(" - ")[0], label: role.description, }; }) @@ -476,7 +477,7 @@ export default function MemberSettings(props: PageProps) { </> {isOwner && ( <Text className="user-role" type={TextType.P1}> - {member.permissionGroupName} + {member.permissionGroupName?.split(" - ")[0]} </Text> )} {!isOwner && ( diff --git a/app/client/src/ce/pages/workspace/WorkspaceInviteUsersForm.tsx b/app/client/src/ce/pages/workspace/WorkspaceInviteUsersForm.tsx index d9d4af35a694..d8aa3e52a99f 100644 --- a/app/client/src/ce/pages/workspace/WorkspaceInviteUsersForm.tsx +++ b/app/client/src/ce/pages/workspace/WorkspaceInviteUsersForm.tsx @@ -376,7 +376,7 @@ function WorkspaceInviteUsersForm(props: any) { : props.roles.map((role: any) => { return { id: role.id, - value: role.name, + value: role.name?.split(" - ")[0], label: role.description, }; }); @@ -565,7 +565,7 @@ function WorkspaceInviteUsersForm(props: any) { </UserInfo> <UserRole> <Text type={TextType.P1}> - {user.permissionGroupName} + {user.permissionGroupName?.split(" - ")[0]} </Text> </UserRole> </User>
c79f93fcfed2966afda3f73021053bfc0acddd5e
2023-02-09 16:59:06
Souma Ghosh
fix: Table filter text loses focus when user is typing (#19951)
false
Table filter text loses focus when user is typing (#19951)
fix
diff --git a/app/client/src/widgets/TableWidgetV2/component/Constants.ts b/app/client/src/widgets/TableWidgetV2/component/Constants.ts index a645382ff23e..ef28a8664f76 100644 --- a/app/client/src/widgets/TableWidgetV2/component/Constants.ts +++ b/app/client/src/widgets/TableWidgetV2/component/Constants.ts @@ -16,6 +16,7 @@ import { } from "widgets/MenuButtonWidget/constants"; import { ColumnTypes } from "../constants"; import { TimePrecision } from "widgets/DatePickerWidget2/constants"; +import { generateReactKey } from "widgets/WidgetUtils"; export type TableSizes = { COLUMN_HEADER_HEIGHT: number; @@ -112,6 +113,7 @@ export type VerticalAlignment = keyof typeof VerticalAlignmentTypes; export type ImageSize = keyof typeof ImageSizes; export interface ReactTableFilter { + id: string; column: string; operator: Operator; condition: Condition; @@ -506,3 +508,11 @@ export enum AddNewRowActions { } export const EDITABLE_CELL_PADDING_OFFSET = 8; + +export const DEFAULT_FILTER = { + id: generateReactKey(), + column: "", + operator: OperatorTypes.OR, + value: "", + condition: "", +}; diff --git a/app/client/src/widgets/TableWidgetV2/component/header/actions/filter/CascadeFields.tsx b/app/client/src/widgets/TableWidgetV2/component/header/actions/filter/CascadeFields.tsx index be8763e03430..f0f8a934c960 100644 --- a/app/client/src/widgets/TableWidgetV2/component/header/actions/filter/CascadeFields.tsx +++ b/app/client/src/widgets/TableWidgetV2/component/header/actions/filter/CascadeFields.tsx @@ -313,6 +313,7 @@ type CascadeFieldProps = { condition: Condition; value: any; operator: Operator; + id: string; index: number; hasAnyFilters: boolean; applyFilter: ( @@ -482,7 +483,7 @@ function CascadeField(props: CascadeFieldProps) { } function Fields(props: CascadeFieldProps & { state: CascadeFieldState }) { - const { applyFilter, hasAnyFilters, index, removeFilter } = props; + const { applyFilter, hasAnyFilters, id, index, removeFilter } = props; const [state, dispatch] = React.useReducer(CaseCaseFieldReducer, props.state); const handleRemoveFilter = () => { dispatch({ type: CascadeFieldActionTypes.DELETE_FILTER }); @@ -534,7 +535,7 @@ function Fields(props: CascadeFieldProps & { state: CascadeFieldState }) { useEffect(() => { if (!isDeleted && isUpdate) { applyFilter( - { operator, column, condition, value }, + { id, operator, column, condition, value }, index, isOperatorChange, ); diff --git a/app/client/src/widgets/TableWidgetV2/component/header/actions/filter/FilterPaneContent.tsx b/app/client/src/widgets/TableWidgetV2/component/header/actions/filter/FilterPaneContent.tsx index 0676e7a25f99..8730c493e6d9 100644 --- a/app/client/src/widgets/TableWidgetV2/component/header/actions/filter/FilterPaneContent.tsx +++ b/app/client/src/widgets/TableWidgetV2/component/header/actions/filter/FilterPaneContent.tsx @@ -7,6 +7,7 @@ import { ReactTableFilter, Operator, OperatorTypes, + DEFAULT_FILTER, } from "../../../Constants"; import { DropdownOption } from "."; import CascadeFields from "./CascadeFields"; @@ -24,6 +25,7 @@ import { ColumnTypes, FilterableColumnTypes, } from "widgets/TableWidgetV2/constants"; +import { generateReactKey } from "utils/generators"; const TableFilterOuterWrapper = styled.div<{ borderRadius?: string; @@ -112,13 +114,6 @@ interface TableFilterProps { borderRadius: string; } -const DEFAULT_FILTER = { - column: "", - operator: OperatorTypes.OR, - value: "", - condition: "", -}; - function TableFilterPaneContent(props: TableFilterProps) { const [filters, updateFilters] = React.useState( new Array<ReactTableFilter>(), @@ -138,7 +133,12 @@ function TableFilterPaneContent(props: TableFilterProps) { if (updatedFilters.length >= 2) { operator = updatedFilters[1].operator; } - updatedFilters.push({ ...DEFAULT_FILTER, operator }); + // New id is generated for new filter here + updatedFilters.push({ + ...DEFAULT_FILTER, + id: generateReactKey(), + operator, + }); updateFilters(updatedFilters); }; @@ -167,11 +167,13 @@ function TableFilterPaneContent(props: TableFilterProps) { .filter((column: { label: string; value: string; type: ColumnTypes }) => { return FilterableColumnTypes.includes(column.type); }); + const hasAnyFilters = !!( filters.length >= 1 && filters[0].column && filters[0].condition ); + return ( <TableFilterOuterWrapper borderRadius={props.borderRadius} @@ -218,8 +220,9 @@ function TableFilterPaneContent(props: TableFilterProps) { columns={columns} condition={filter.condition} hasAnyFilters={hasAnyFilters} + id={filter.id} index={index} - key={index + JSON.stringify(filter)} + key={filter.id} operator={ filters.length >= 2 ? filters[1].operator : filter.operator } diff --git a/app/client/src/widgets/TableWidgetV2/component/header/actions/filter/index.tsx b/app/client/src/widgets/TableWidgetV2/component/header/actions/filter/index.tsx index e98a79dbc20d..f736b7f02e14 100644 --- a/app/client/src/widgets/TableWidgetV2/component/header/actions/filter/index.tsx +++ b/app/client/src/widgets/TableWidgetV2/component/header/actions/filter/index.tsx @@ -8,7 +8,7 @@ import TableFilterPane from "./FilterPane"; import { ReactTableColumnProps, ReactTableFilter, - OperatorTypes, + DEFAULT_FILTER, } from "../../../Constants"; //TODO(abhinav): All of the following imports should not exist in a widget component @@ -44,12 +44,7 @@ function TableFilters(props: TableFilterProps) { useEffect(() => { const filters: ReactTableFilter[] = props.filters ? [...props.filters] : []; if (filters.length === 0) { - filters.push({ - column: "", - operator: OperatorTypes.OR, - value: "", - condition: "", - }); + filters.push({ ...DEFAULT_FILTER }); } updateFilters(filters); }, [props.filters]); diff --git a/app/client/src/widgets/TableWidgetV2/widget/index.tsx b/app/client/src/widgets/TableWidgetV2/widget/index.tsx index 6d14780bc7db..d9113bf5fd60 100644 --- a/app/client/src/widgets/TableWidgetV2/widget/index.tsx +++ b/app/client/src/widgets/TableWidgetV2/widget/index.tsx @@ -27,8 +27,8 @@ import Skeleton from "components/utils/Skeleton"; import { noop, retryPromise } from "utils/AppsmithUtils"; import { ReactTableFilter, - OperatorTypes, AddNewRowActions, + DEFAULT_FILTER, } from "../component/Constants"; import { ActionColumnTypes, @@ -94,14 +94,6 @@ import { TimePrecision } from "widgets/DatePickerWidget2/constants"; const ReactTableComponent = lazy(() => retryPromise(() => import("../component")), ); -const defaultFilter = [ - { - column: "", - operator: OperatorTypes.OR, - value: "", - condition: "", - }, -]; class TableWidgetV2 extends BaseWidget<TableWidgetProps, WidgetState> { inlineEditTimer: number | null = null; @@ -628,7 +620,7 @@ class TableWidgetV2 extends BaseWidget<TableWidgetProps, WidgetState> { this.updateColumnProperties(newTableColumns); } - this.props.updateWidgetMetaProperty("filters", defaultFilter); + this.props.updateWidgetMetaProperty("filters", [DEFAULT_FILTER]); } } @@ -819,7 +811,7 @@ class TableWidgetV2 extends BaseWidget<TableWidgetProps, WidgetState> { this.props.updateWidgetMetaProperty("filters", filters); // Reset Page only when a filter is added - if (!isEmpty(xorWith(filters, defaultFilter, equal))) { + if (!isEmpty(xorWith(filters, [DEFAULT_FILTER], equal))) { this.props.updateWidgetMetaProperty("pageNo", 1); } };
d669cf4e4d7b8f19ee194661ff212917a8cd4ca8
2022-05-30 10:32:54
Abhijeet
chore: Add branch name param for git analytics events (#14133)
false
Add branch name param for git analytics events (#14133)
chore
diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/GitServiceCEImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/GitServiceCEImpl.java index 7e90c3174463..2a3495b724d4 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/GitServiceCEImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/GitServiceCEImpl.java @@ -2424,28 +2424,25 @@ private Mono<Application> addAnalyticsForGitOperation(String eventName, Boolean isRepoPrivate, Boolean isSystemGenerated) { GitApplicationMetadata gitData = application.getGitApplicationMetadata(); - String defaultApplicationId = gitData == null || StringUtils.isEmptyOrNull(gitData.getDefaultApplicationId()) - ? "" - : gitData.getDefaultApplicationId(); - String gitHostingProvider = gitData == null - ? "" - : GitUtils.getGitProviderName(application.getGitApplicationMetadata().getRemoteUrl()); - - Map<String, Object> analyticsProps = new HashMap<>(Map.of("applicationId", defaultApplicationId, - "organizationId", defaultIfNull(application.getOrganizationId(), ""), + Map<String, Object> analyticsProps = new HashMap<>(); + if (gitData != null) { + analyticsProps.put(FieldName.APPLICATION_ID, gitData.getDefaultApplicationId()); + analyticsProps.put(FieldName.BRANCH_NAME, gitData.getBranchName()); + analyticsProps.put("gitHostingProvider", GitUtils.getGitProviderName(gitData.getRemoteUrl())); + } + // Do not include the error data points in the map for success states + if(!StringUtils.isEmptyOrNull(errorMessage) || !StringUtils.isEmptyOrNull(errorType)) { + analyticsProps.put("errorMessage", errorMessage); + analyticsProps.put("errorType", errorType); + } + analyticsProps.putAll(Map.of( + FieldName.ORGANIZATION_ID, defaultIfNull(application.getOrganizationId(), ""), "branchApplicationId", defaultIfNull(application.getId(), ""), "isRepoPrivate", defaultIfNull(isRepoPrivate, ""), - "gitHostingProvider", defaultIfNull(gitHostingProvider, ""), "isSystemGenerated", defaultIfNull(isSystemGenerated, "") )); - return sessionUserService.getCurrentUser() .map(user -> { - // Do not include the error data points in the map for success states - if(!StringUtils.isEmptyOrNull(errorMessage) || !StringUtils.isEmptyOrNull(errorType)) { - analyticsProps.put("errorMessage", errorMessage); - analyticsProps.put("errorType", errorType); - } analyticsService.sendEvent(eventName, user.getUsername(), analyticsProps); return application; });
b568efa1376d363df57d6c00eddc909946dd0d39
2025-03-12 16:28:39
Hetu Nandu
fix: ADS Context Menu issues (#39683)
false
ADS Context Menu issues (#39683)
fix
diff --git a/app/client/packages/design-system/ads/src/List/List.styles.tsx b/app/client/packages/design-system/ads/src/List/List.styles.tsx index 27d4567e12b4..14fcd957fb5e 100644 --- a/app/client/packages/design-system/ads/src/List/List.styles.tsx +++ b/app/client/packages/design-system/ads/src/List/List.styles.tsx @@ -108,11 +108,13 @@ export const StyledListItem = styled.div<{ &[data-rightcontrolvisibility="hover"] { ${RightControlWrapper} { - display: none; + visibility: hidden; + width: 0; } &:hover ${RightControlWrapper} { - display: block; + visibility: visible; + width: auto; } } diff --git a/app/client/src/pages/AppIDE/components/UIEntityListTree/WidgetContextMenu.tsx b/app/client/src/pages/AppIDE/components/UIEntityListTree/WidgetContextMenu.tsx index 9626aa31afdd..bde8eb4018f7 100644 --- a/app/client/src/pages/AppIDE/components/UIEntityListTree/WidgetContextMenu.tsx +++ b/app/client/src/pages/AppIDE/components/UIEntityListTree/WidgetContextMenu.tsx @@ -1,7 +1,6 @@ -import React, { useMemo } from "react"; +import React, { useMemo, useCallback } from "react"; import { useDispatch, useSelector } from "react-redux"; import { getWidgetByID } from "sagas/selectors"; -import { useCallback } from "react"; import { ReduxActionTypes } from "ee/constants/ReduxActionConstants"; import { ENTITY_TYPE } from "ee/entities/DataTree/types"; import { initExplorerEntityNameEdit } from "actions/explorerActions"; @@ -56,6 +55,14 @@ export const WidgetContextMenu = (props: { const deleteWidget = useDeleteWidget(widgetId); + const handleDeleteWidget = useCallback(() => { + // We add a delay to avoid having the focus stuck in the menu trigger which blocks + // the ability to use keyboard shortcuts on the canvas + setTimeout(() => { + deleteWidget(); + }, 0); + }, [deleteWidget]); + const menuContent = useMemo(() => { return ( <> @@ -75,7 +82,7 @@ export const WidgetContextMenu = (props: { <MenuItem className="error-menuitem" disabled={!canManagePages && widget?.isDeletable !== false} - onClick={deleteWidget} + onClick={handleDeleteWidget} startIcon="trash" > {createMessage(CONTEXT_DELETE)} @@ -84,8 +91,8 @@ export const WidgetContextMenu = (props: { ); }, [ canManagePages, - deleteWidget, editWidgetName, + handleDeleteWidget, showBinding, widget?.isDeletable, widgetId,
aee5816a547439435c19d8561482895837adc4ee
2022-02-08 17:13:25
Abhinav Jha
fix: limit validation errors in debugger (#10886)
false
limit validation errors in debugger (#10886)
fix
diff --git a/app/client/src/constants/messages.ts b/app/client/src/constants/messages.ts index 0d1b9a3c0ac4..c57f1d79ed0b 100644 --- a/app/client/src/constants/messages.ts +++ b/app/client/src/constants/messages.ts @@ -1001,3 +1001,12 @@ export const CONTEXT_MOVE = () => "Move to page"; export const CONTEXT_COPY = () => "Copy to page"; export const CONTEXT_DELETE = () => "Delete"; export const CONTEXT_NO_PAGE = () => "No pages"; + +// Validations +export const VALIDATION_ARRAY_UNIQUE = () => + "Array must be unique. Duplicate values found"; +export const VALIDATION_ARRAY_DUPLICATE_PROPERTY_VALUES = () => + "Duplicate values found for the following properties, in the array entries, that must be unique --"; +export const VALIDATION_ARRAY_DISALLOWED_VALUE = () => + "Value is not allowed in this array"; +export const VALIDATION_ARRAY_INVALID_ENTRY = () => "Invalid entry at index:"; diff --git a/app/client/src/workers/helpers.test.ts b/app/client/src/workers/helpers.test.ts new file mode 100644 index 000000000000..d2ec57dec47e --- /dev/null +++ b/app/client/src/workers/helpers.test.ts @@ -0,0 +1,49 @@ +import { findDuplicateIndex } from "./helpers"; + +describe("Worker Helper functions test", () => { + it("Correctly finds the duplicate index in an array of strings", () => { + const input = ["a", "b", "c", "d", "e", "a", "b"]; + const expected = 5; + const result = findDuplicateIndex(input); + expect(result).toStrictEqual(expected); + }); + it("Correctly finds the duplicate index in an array of objects and strings", () => { + const input = [ + "a", + "b", + { a: 1, b: 2 }, + { a: 2, b: 3 }, + "e", + { a: 1, b: 2 }, + "b", + ]; + const expected = 5; + const result = findDuplicateIndex(input); + expect(result).toStrictEqual(expected); + }); + + /* TODO(abhinav): These kinds of issues creep up when dealing with JSON.stringify to make + things simple. So, the ideal solution here is to prevent the + usage of this function for array of objects + */ + it("Correctly ignores the duplicate index in an array of objects and strings, when properties are not ordered", () => { + const input = [ + "a", + "b", + { a: 1, b: 2 }, + { a: 2, b: 3 }, + "e", + { b: 2, a: 1 }, + "b", + ]; + const expected = 6; + const result = findDuplicateIndex(input); + expect(result).toStrictEqual(expected); + }); + it("Correctly returns -1 if no duplicates are found", () => { + const input = ["a", "b", "c", "d", "e", "f", "g"]; + const expected = -1; + const result = findDuplicateIndex(input); + expect(result).toStrictEqual(expected); + }); +}); diff --git a/app/client/src/workers/helpers.ts b/app/client/src/workers/helpers.ts new file mode 100644 index 000000000000..dcf6a88944e5 --- /dev/null +++ b/app/client/src/workers/helpers.ts @@ -0,0 +1,17 @@ +// Finds the first index which is a duplicate value +// Returns -1 if there are no duplicates +// Returns the index of the first duplicate entry it finds + +// Note: This "can" fail if the object entries don't have their properties in the +// same order. +export const findDuplicateIndex = (arr: Array<unknown>) => { + const _uniqSet = new Set(); + let currSetSize = 0; + for (let i = 0; i < arr.length; i++) { + // JSON.stringify because value can be objects + _uniqSet.add(JSON.stringify(arr[i])); + if (_uniqSet.size > currSetSize) currSetSize = _uniqSet.size; + else return i; + } + return -1; +}; diff --git a/app/client/src/workers/validations.test.ts b/app/client/src/workers/validations.test.ts index 3591b747e4c2..0534b355023d 100644 --- a/app/client/src/workers/validations.test.ts +++ b/app/client/src/workers/validations.test.ts @@ -575,12 +575,15 @@ describe("Validate Validators", () => { { isValid: false, parsed: [], - messages: ["Disallowed value: q"], + messages: ["Value is not allowed in this array: q"], }, { isValid: false, parsed: [], - messages: ["Disallowed value: q"], + messages: [ + "Value is not allowed in this array: q", + "Value is not allowed in this array: s", + ], }, { isValid: true, @@ -631,12 +634,15 @@ describe("Validate Validators", () => { { isValid: false, parsed: ["a"], - messages: ["Disallowed value: q"], + messages: ["Value is not allowed in this array: q"], }, { isValid: false, parsed: ["a"], - messages: ["Disallowed value: q"], + messages: [ + "Value is not allowed in this array: q", + "Value is not allowed in this array: s", + ], }, { isValid: true, @@ -657,6 +663,58 @@ describe("Validate Validators", () => { }); }); + it("correctly limits the number of validation errors in array validation", () => { + const input = [ + "a", + "b", + "c", + "d", + "e", + "f", + "g", + "h", + "i", + "j", + "k", + "l", + "m", + "n", + "o", + "p", + ]; + const config = { + type: ValidationTypes.ARRAY, + params: { + children: { + type: ValidationTypes.NUMBER, + params: { + required: true, + allowedValues: [1, 2, 3, 4], + }, + }, + }, + }; + const expected = { + isValid: false, + parsed: [], + messages: [ + "Invalid entry at index: 0. This value does not evaluate to type number Required", + "Invalid entry at index: 1. This value does not evaluate to type number Required", + "Invalid entry at index: 2. This value does not evaluate to type number Required", + "Invalid entry at index: 3. This value does not evaluate to type number Required", + "Invalid entry at index: 4. This value does not evaluate to type number Required", + "Invalid entry at index: 5. This value does not evaluate to type number Required", + "Invalid entry at index: 6. This value does not evaluate to type number Required", + "Invalid entry at index: 7. This value does not evaluate to type number Required", + "Invalid entry at index: 8. This value does not evaluate to type number Required", + "Invalid entry at index: 9. This value does not evaluate to type number Required", + ], + }; + + const result = validate(config, input, DUMMY_WIDGET); + expect(result).toStrictEqual(expected); + }); + it("correctly validates array when required is true", () => { const inputs = [ ["a", "b", "c"], @@ -751,7 +809,7 @@ describe("Validate Validators", () => { { isValid: false, parsed: [], - messages: ["Array must be unique. Duplicate values found"], + messages: ["Array must be unique. Duplicate values found at index: 2"], }, { isValid: false, @@ -1215,6 +1273,53 @@ describe("Validate Validators", () => { }); }); + it("correctly validates uniqueness of keys in array objects", () => { + const config = { + type: ValidationTypes.ARRAY, + params: { + children: { + type: ValidationTypes.OBJECT, + params: { + allowedKeys: [ + { + name: "label", + type: ValidationTypes.TEXT, + params: { + default: "", + required: true, + unique: true, + }, + }, + { + name: "value", + type: ValidationTypes.TEXT, + params: { + default: "", + unique: true, + }, + }, + ], + }, + }, + }, + }; + const input = [ + { label: "Blue", value: "" }, + { label: "Green", value: "" }, + { label: "Red", value: "red" }, + ]; + const expected = { + isValid: false, + parsed: [], + messages: [ + "Duplicate values found for the following properties, in the array entries, that must be unique -- label,value.", + ], + }; + + const result = validate(config, input, DUMMY_WIDGET); + expect(result).toStrictEqual(expected); + }); + it("correctly validates TableProperty", () => { const inputs = [ "a", diff --git a/app/client/src/workers/validations.ts b/app/client/src/workers/validations.ts index 890af53651cc..25abad227663 100644 --- a/app/client/src/workers/validations.ts +++ b/app/client/src/workers/validations.ts @@ -6,6 +6,7 @@ import { Validator, } from "../constants/WidgetValidation"; import _, { + compact, get, isArray, isObject, @@ -24,7 +25,15 @@ import evaluate from "./evaluate"; import getIsSafeURL from "utils/validation/getIsSafeURL"; import * as log from "loglevel"; import { QueryActionConfig } from "entities/Action"; +import { + VALIDATION_ARRAY_DISALLOWED_VALUE, + VALIDATION_ARRAY_DUPLICATE_PROPERTY_VALUES, + VALIDATION_ARRAY_INVALID_ENTRY, + VALIDATION_ARRAY_UNIQUE, +} from "constants/messages"; +import { findDuplicateIndex } from "./helpers"; export const UNDEFINED_VALIDATION = "UNDEFINED_VALIDATION"; +export const VALIDATION_ERROR_COUNT_THRESHOLD = 10; const flat = (array: Record<string, any>[], uniqueParam: string) => { let result: { value: string }[] = []; @@ -106,105 +115,133 @@ function validateArray( value: unknown[], props: Record<string, unknown>, ) { - let _isValid = true; - const _messages: string[] = []; - const whiteList = config.params?.allowedValues; - if (whiteList) { - for (const entry of value) { - if (!whiteList.includes(entry)) { - return { - isValid: false, - parsed: config.params?.default || [], - messages: [`Disallowed value: ${entry}`], - }; - } - } - } - // Check uniqueness of object elements in an array + let _isValid = true; // Let's first assume that this is valid + const _messages: string[] = []; // Initialise messages array + + // Values allowed in the array, converted into a set of unique values + // or an empty set + const allowedValues = new Set(config.params?.allowedValues || []); + + // Keys whose values are supposed to be unique across all values in all objects in the array + let uniqueKeys: Array<string> = []; + const allowedKeyConfigs = config.params?.children?.params?.allowedKeys; if ( config.params?.children?.type === ValidationTypes.OBJECT && - (config.params.children.params?.allowedKeys || []).length > 0 + Array.isArray(allowedKeyConfigs) && + allowedKeyConfigs.length ) { - const allowedKeysCofigArray = - config.params.children.params?.allowedKeys || []; + uniqueKeys = compact( + allowedKeyConfigs.map((allowedKeyConfig) => { + // TODO(abhinav): This is concerning, we now have two ways, + // in which we can define unique keys in an array of objects + // We need to disable one option. + + // If this key is supposed to be unique across all objects in the value array + // We include it in the uniqueKeys list + if (allowedKeyConfig.params?.unique) return allowedKeyConfig.name; + }), + ); + } + + // Concatenate unique keys from config.params?.unique + uniqueKeys = Array.isArray(config.params?.unique) + ? uniqueKeys.concat(config.params?.unique as Array<string>) + : uniqueKeys; + + // Validation configuration for children + const childrenValidationConfig = config.params?.children; + + // Should we validate against disallowed values in the value array? + const shouldVerifyAllowedValues = !!allowedValues.size; // allowedValues is a set - const allowedKeys = (config.params.children.params?.allowedKeys || []).map( - (key) => key.name, + // Do we have validation config for array children? + const shouldValidateChildren = !!childrenValidationConfig; + + // Should array values be unique? This should applies only to primitive values in array children + // If we have to validate children with their own validation config, this should be false (Needs verification) + // If this option is true, shouldArrayValuesHaveUniqueValuesForKeys will become false + const shouldArrayHaveUniqueEntries = config.params?.unique === true; + + // Should we validate for unique values for properties in the array entries? + const shouldArrayValuesHaveUniqueValuesForKeys = + !!uniqueKeys.length && !shouldArrayHaveUniqueEntries; + + // Verify if all values are unique + if (shouldArrayHaveUniqueEntries) { + // Find the index of a duplicate value in array + const duplicateIndex = findDuplicateIndex(value); + if (duplicateIndex !== -1) { + // Bail out early + // Because, we don't want to re-iterate, if this validation fails + return { + isValid: false, + parsed: config.params?.default || [], + messages: [`${VALIDATION_ARRAY_UNIQUE()} at index: ${duplicateIndex}`], + }; + } + } + + if (shouldArrayValuesHaveUniqueValuesForKeys) { + // Loop + // Get only unique entries from the value array + const uniqueEntries = _.uniqWith( + value as Array<Record<string, unknown>>, + (a: Record<string, unknown>, b: Record<string, unknown>) => { + // If any of the keys are the same, we fail the uniqueness test + return uniqueKeys.some((key) => a[key] === b[key]); + }, ); - type ObjectKeys = typeof allowedKeys[number]; - type ItemType = { - [key in ObjectKeys]: string; - }; - const valueWithType = value as ItemType[]; - allowedKeysCofigArray.forEach((allowedKeyConfig) => { - if (allowedKeyConfig.params?.unique) { - const allowedKeyValues = valueWithType.map( - (item) => item[allowedKeyConfig.name], - ); - const normalizedValues = valueWithType.map((item) => - item[allowedKeyConfig.name].toLowerCase(), - ); - // Check if value is duplicated - _messages.push( - ...allowedKeyValues.reduce( - (acc: string[], currentValue, currentIndex) => { - if ( - normalizedValues.indexOf(currentValue.toLowerCase()) !== - currentIndex - ) { - acc.push( - `Duplicated entry at index: ${currentIndex + 1}, key: ${ - allowedKeyConfig.name - }, value: ${currentValue}`, - ); - } - return acc; - }, - [], - ), - ); - if (_messages.length > 0) { - _isValid = false; - } - } - }); + if (uniqueEntries.length !== value.length) { + // Bail out early + // Because, we don't want to re-iterate, if this validation fails + return { + isValid: false, + parsed: config.params?.default || [], + messages: [ + `${VALIDATION_ARRAY_DUPLICATE_PROPERTY_VALUES()} ${uniqueKeys.join( + ",", + )}.`, + ], + }; + } } - const children = config.params?.children; + // Loop + value.every((entry, index) => { + // Validate for allowed values + if (shouldVerifyAllowedValues && !allowedValues.has(entry)) { + _messages.push(`${VALIDATION_ARRAY_DISALLOWED_VALUE()}: ${entry}`); + _isValid = false; + } - if (children) { - value.forEach((entry, index) => { - const validation = validate(children, entry, props); - if (!validation.isValid) { + // validate using validation config + if (shouldValidateChildren && childrenValidationConfig) { + // Validate this entry + const childValidationResult = validate( + childrenValidationConfig, + entry, + props, + ); + + // If invalid, append to messages + if (!childValidationResult.isValid) { _isValid = false; - validation.messages?.map((message) => - _messages.push(`Invalid entry at index: ${index}. ${message}`), - ); - } - }); - } - if (config.params?.unique) { - if (isArray(config.params?.unique)) { - for (const param of config.params?.unique) { - const shouldBeUnique = value.map((entry) => - get(entry, param as string, ""), - ); - if (uniq(shouldBeUnique).length !== value.length) { - _isValid = false; + childValidationResult.messages?.forEach((message) => _messages.push( - `path:${param} must be unique. Duplicate values found`, - ); - break; - } + `${VALIDATION_ARRAY_INVALID_ENTRY()} ${index}. ${message}`, + ), + ); } - } else if ( - uniq(value.map((entry) => JSON.stringify(entry))).length !== value.length - ) { - _isValid = false; - _messages.push(`Array must be unique. Duplicate values found`); } - } + + // Bail out, if the error count threshold has been overcome + // This way, debugger will not have to render too many errors + if (_messages.length >= VALIDATION_ERROR_COUNT_THRESHOLD && !_isValid) { + return false; + } + return true; + }); return { isValid: _isValid, @@ -223,6 +260,7 @@ export const validate = ( value, props, ); + return _result; };
94ebacdf807bd03f8a710daa8e805072bdba3ab3
2023-06-08 08:17:51
Dhruvik Neharia
chore: Add two more sentry logs when REQUEST_NOT_AUTHORISED and PAGE_NOT_FOUND alongwith rejecting respective promises with the whole error object (#24203)
false
Add two more sentry logs when REQUEST_NOT_AUTHORISED and PAGE_NOT_FOUND alongwith rejecting respective promises with the whole error object (#24203)
chore
diff --git a/app/client/src/ce/api/ApiUtils.ts b/app/client/src/ce/api/ApiUtils.ts index 8febf62ce3eb..e0cb46fecbfc 100644 --- a/app/client/src/ce/api/ApiUtils.ts +++ b/app/client/src/ce/api/ApiUtils.ts @@ -200,7 +200,9 @@ export const apiFailureResponseInterceptor = (error: any) => { )}`, }), ); + Sentry.captureException(error); return Promise.reject({ + ...error, code: ERROR_CODES.REQUEST_NOT_AUTHORISED, message: "Unauthorized. Redirecting to login page...", show: false, @@ -212,7 +214,9 @@ export const apiFailureResponseInterceptor = (error: any) => { (SERVER_ERROR_CODES.RESOURCE_NOT_FOUND.includes(errorData.error.code) || SERVER_ERROR_CODES.UNABLE_TO_FIND_PAGE.includes(errorData.error.code)) ) { + Sentry.captureException(error); return Promise.reject({ + ...error, code: ERROR_CODES.PAGE_NOT_FOUND, message: "Resource Not Found", show: false,
c096bb5e5be921465027db59dfb3157db4b70d17
2024-06-07 15:24:07
Rahul Barwal
test: Failing cypress tests due to removal of empty canvas prompts (#34037)
false
Failing cypress tests due to removal of empty canvas prompts (#34037)
test
diff --git a/app/client/cypress/e2e/Regression/ClientSide/OtherUIFeatures/EmptyCanvas_spec.js b/app/client/cypress/e2e/Regression/ClientSide/OtherUIFeatures/EmptyCanvas_spec.js deleted file mode 100644 index a3d9d72532fe..000000000000 --- a/app/client/cypress/e2e/Regression/ClientSide/OtherUIFeatures/EmptyCanvas_spec.js +++ /dev/null @@ -1,31 +0,0 @@ -import { WIDGET } from "../../../../locators/WidgetLocators"; -import { ObjectsRegistry } from "../../../../support/Objects/Registry"; -import EditorNavigation, { - EntityType, -} from "../../../../support/Pages/EditorNavigation"; -import PageList from "../../../../support/Pages/PageList"; - -const { CommonLocators: locators, EntityExplorer: ee } = ObjectsRegistry; - -describe("Empty canvas ctas", () => { - it("1. Ctas validations", () => { - cy.wait(3000); // for page to load, failing in CI - //Ctas should not be shown in the second page - cy.get(locators._emptyCanvasCta).should("be.visible"); - PageList.AddNewPage(); - cy.get(locators._emptyCanvasCta).should("not.exist"); - EditorNavigation.SelectEntityByName("Page1", EntityType.Page); - - //Ctas should continue to show on refresh - cy.get(locators._emptyCanvasCta).should("be.visible"); - cy.reload(); - cy.get(locators._emptyCanvasCta).should("be.visible"); - - //Hide cta on adding a widget - cy.get(locators._emptyCanvasCta).should("be.visible"); - ee.DragDropWidgetNVerify(WIDGET.BUTTON, 200, 200); - cy.get(locators._emptyCanvasCta).should("not.exist"); - PageList.AddNewPage(); - cy.get(locators._emptyCanvasCta).should("not.exist"); - }); -}); diff --git a/app/client/cypress/e2e/Regression/ClientSide/VisualTests/AppPageLayout_spec.js b/app/client/cypress/e2e/Regression/ClientSide/VisualTests/AppPageLayout_spec.js index d46e558fa916..bc76f3bb8b3a 100644 --- a/app/client/cypress/e2e/Regression/ClientSide/VisualTests/AppPageLayout_spec.js +++ b/app/client/cypress/e2e/Regression/ClientSide/VisualTests/AppPageLayout_spec.js @@ -1,5 +1,6 @@ import homePage from "../../../../locators/HomePage"; import * as _ from "../../../../support/Objects/ObjectsCore"; +import PageList from "../../../../support/Pages/PageList"; describe("Visual regression tests", { tags: ["@tag.Visual"] }, () => { // for any changes in UI, update the screenshot in snapshot folder, to do so: @@ -18,7 +19,7 @@ describe("Visual regression tests", { tags: ["@tag.Visual"] }, () => { cy.get("#root").matchImageSnapshot("apppage"); //Layout validation for Quick page wizard - cy.get("[data-testid='generate-app']").click(); + PageList.AddNewPage(Cypress.env("MESSAGES").GENERATE_PAGE_ACTION_TITLE()); cy.wait(2000); // taking screenshot of generate crud page cy.get("#root").matchImageSnapshot("quickPageWizard"); diff --git a/app/client/cypress/locators/GeneratePage.json b/app/client/cypress/locators/GeneratePage.json index fafd5d1c4be2..e6925eb1e742 100644 --- a/app/client/cypress/locators/GeneratePage.json +++ b/app/client/cypress/locators/GeneratePage.json @@ -1,5 +1,4 @@ { - "generateCRUDPageActionCard": "[data-testid='generate-app']", "selectDatasourceDropdown": "[data-testid=t--datasource-dropdown]", "datasourceDropdownOption": "[data-testid=t--datasource-dropdown-option]", "selectTableDropdown": "[data-testid=t--table-dropdown]", diff --git a/app/client/cypress/support/Pages/HomePage.ts b/app/client/cypress/support/Pages/HomePage.ts index ee55d6323b4e..2ae8b77ff87f 100644 --- a/app/client/cypress/support/Pages/HomePage.ts +++ b/app/client/cypress/support/Pages/HomePage.ts @@ -68,7 +68,6 @@ export class HomePage { _applicationName = ".t--application-name"; private _editAppName = "bp3-editable-text-editing"; private _appMenu = ".ads-v2-menu__menu-item-children"; - _buildFromDataTableActionCard = "[data-testid='generate-app']"; private _selectRole = "//span[text()='Select a role']/ancestor::div"; private _searchInput = "input[type='text']"; _appHoverIcon = (action: string) => ".t--application-" + action + "-link";
ff8bcd35c16989ef0643dc24e69367970b40cebe
2023-06-06 23:05:43
Vemparala Surya Vamsi
chore: [One-click binding] design and QA callouts one click binding (#23997)
false
[One-click binding] design and QA callouts one click binding (#23997)
chore
diff --git a/app/client/cypress/e2e/Regression/ClientSide/OneClickBinding/PropertyControl_spec.ts b/app/client/cypress/e2e/Regression/ClientSide/OneClickBinding/PropertyControl_spec.ts index 0c7c5fe3ae8c..4bb4e1ef2056 100644 --- a/app/client/cypress/e2e/Regression/ClientSide/OneClickBinding/PropertyControl_spec.ts +++ b/app/client/cypress/e2e/Regression/ClientSide/OneClickBinding/PropertyControl_spec.ts @@ -1,20 +1,31 @@ import * as _ from "../../../../support/Objects/ObjectsCore"; -import { ChooseAndAssertForm } from "./spec_utility"; -import locator from "../../../../locators/OneClickBindingLocator"; import CommonLocators from "../../../../locators/commonlocators.json"; import DatasourceEditor from "../../../../locators/DatasourcesEditor.json"; +import { OneClickBinding } from "./spec_utility"; +import oneClickBindingLocator from "../../../../locators/OneClickBindingLocator"; +import onboardingLocator from "../../../../locators/FirstTimeUserOnboarding.json"; -describe.skip("One click binding control", () => { +const oneClickBinding = new OneClickBinding(); + +describe("One click binding control", () => { before(() => { - _.entityExplorer.DragDropWidgetNVerify("tablewidgetv2"); + _.entityExplorer.DragDropWidgetNVerify(_.draggableWidgets.TABLE); }); it("1.should check the datasource selector and the form", () => { - _.agHelper.AssertElementExist(locator.datasourceDropdownSelector); - _.agHelper.GetNClick(locator.datasourceDropdownSelector); - _.agHelper.AssertElementAbsence(locator.datasourceQueryBindHeaderSelector); - _.agHelper.AssertElementExist(locator.datasourceGenerateAQuerySelector); - _.agHelper.AssertElementExist(locator.datasourceOtherActionsSelector); + _.agHelper.AssertElementExist( + oneClickBindingLocator.datasourceDropdownSelector, + ); + _.agHelper.GetNClick(oneClickBindingLocator.datasourceDropdownSelector); + _.agHelper.AssertElementAbsence( + oneClickBindingLocator.datasourceQueryBindHeaderSelector, + ); + _.agHelper.AssertElementExist( + oneClickBindingLocator.datasourceGenerateAQuerySelector, + ); + _.agHelper.AssertElementExist( + oneClickBindingLocator.datasourceOtherActionsSelector, + ); _.entityExplorer.NavigateToSwitcher("Explorer"); cy.wait(500); @@ -29,49 +40,64 @@ describe.skip("One click binding control", () => { _.entityExplorer.NavigateToSwitcher("Explorer"); - _.agHelper.GetNClick(locator.datasourceDropdownSelector); + _.agHelper.GetNClick(oneClickBindingLocator.datasourceDropdownSelector); - _.agHelper.AssertElementExist(locator.datasourceQueryBindHeaderSelector); + _.agHelper.AssertElementExist( + oneClickBindingLocator.datasourceQueryBindHeaderSelector, + ); - _.agHelper.AssertElementLength(locator.datasourceQuerySelector, 1); + _.agHelper.AssertElementLength( + oneClickBindingLocator.datasourceQuerySelector, + 1, + ); - _.agHelper.AssertElementExist(locator.datasourceGenerateAQuerySelector); + _.agHelper.AssertElementExist( + oneClickBindingLocator.datasourceGenerateAQuerySelector, + ); - _.agHelper.AssertElementExist(locator.datasourceSelector()); + _.agHelper.AssertElementExist(oneClickBindingLocator.datasourceSelector()); - _.agHelper.AssertElementExist(locator.datasourceOtherActionsSelector); + _.agHelper.AssertElementExist( + oneClickBindingLocator.datasourceOtherActionsSelector, + ); - _.agHelper.AssertElementExist(locator.otherActionSelector()); + _.agHelper.AssertElementExist(oneClickBindingLocator.otherActionSelector()); _.agHelper.AssertElementExist( - locator.otherActionSelector("Connect new datasource"), + oneClickBindingLocator.otherActionSelector("Connect new datasource"), ); - _.agHelper.GetNClick(locator.otherActionSelector("Connect new datasource")); + _.agHelper.GetNClick( + oneClickBindingLocator.otherActionSelector("Connect new datasource"), + ); - _.agHelper.AssertElementExist(locator.datasourcePage); + _.agHelper.AssertElementExist(onboardingLocator.datasourcePage); - _.agHelper.GetNClick(locator.backButton); + _.agHelper.GetNClick(onboardingLocator.datasourceBackBtn); - _.agHelper.GetNClick(locator.datasourceDropdownSelector); + _.agHelper.GetNClick(oneClickBindingLocator.datasourceDropdownSelector); _.agHelper.AssertElementExist( - locator.otherActionSelector("Insert snippet"), + oneClickBindingLocator.otherActionSelector("Insert snippet"), ); - _.agHelper.GetNClick(locator.otherActionSelector("Insert snippet")); + _.agHelper.GetNClick( + oneClickBindingLocator.otherActionSelector("Insert snippet"), + ); _.agHelper.AssertElementExist(CommonLocators.globalSearchModal); _.agHelper.TypeText(CommonLocators.globalSearchInput, "{esc}", 0, true); - _.agHelper.GetNClick(locator.datasourceDropdownSelector); + _.agHelper.GetNClick(oneClickBindingLocator.datasourceDropdownSelector); _.agHelper.AssertElementExist( - locator.otherActionSelector("Insert binding"), + oneClickBindingLocator.otherActionSelector("Insert binding"), ); - _.agHelper.GetNClick(locator.otherActionSelector("Insert binding")); + _.agHelper.GetNClick( + oneClickBindingLocator.otherActionSelector("Insert binding"), + ); _.propPane.ValidatePropertyFieldValue("Table data", "{{}}"); @@ -79,15 +105,17 @@ describe.skip("One click binding control", () => { _.propPane.ToggleJsMode("Table data"); - _.agHelper.GetNClick(locator.datasourceDropdownSelector); + _.agHelper.GetNClick(oneClickBindingLocator.datasourceDropdownSelector); _.agHelper.AssertElementAbsence( - locator.datasourceDropdownOptionSelector("Query1"), + oneClickBindingLocator.datasourceDropdownOptionSelector("Query1"), ); - _.agHelper.GetNClick(locator.datasourceQuerySelector, 0); + _.agHelper.GetNClick(oneClickBindingLocator.datasourceQuerySelector, 0); - _.agHelper.AssertElementExist(locator.dropdownOptionSelector("Query1")); + _.agHelper.AssertElementExist( + oneClickBindingLocator.dropdownOptionSelector("Query1"), + ); _.propPane.ToggleJsMode("Table data"); @@ -97,13 +125,23 @@ describe.skip("One click binding control", () => { _.propPane.ToggleJsMode("Table data"); - ChooseAndAssertForm("New from Users", "Users", "public.users", "gender"); + oneClickBinding.ChooseAndAssertForm( + "New from Users", + "Users", + "public.users", + "gender", + ); _.propPane.MoveToTab("Style"); _.propPane.MoveToTab("Content"); - ChooseAndAssertForm("New from sample Movies", "movies", "movies", "status"); + oneClickBinding.ChooseAndAssertForm( + "New from sample Movies", + "movies", + "movies", + "status", + ); _.entityExplorer.NavigateToSwitcher("Explorer"); @@ -130,14 +168,16 @@ describe.skip("One click binding control", () => { _.entityExplorer.NavigateToSwitcher("Widgets"); - _.agHelper.GetNClick(locator.datasourceDropdownSelector); + _.agHelper.GetNClick(oneClickBindingLocator.datasourceDropdownSelector); - _.agHelper.GetNClick(locator.datasourceSelector("myinvalidds")); + _.agHelper.GetNClick( + oneClickBindingLocator.datasourceSelector("myinvalidds"), + ); cy.wait("@getDatasourceStructure", { timeout: 20000 }); _.agHelper.AssertElementExist( - locator.tableError( + oneClickBindingLocator.tableError( "Appsmith server timed out when fetching structure. Please reach out to appsmith customer support to resolve this.", ), ); diff --git a/app/client/cypress/e2e/Regression/ClientSide/OneClickBinding/TableWidget/index_spec.ts b/app/client/cypress/e2e/Regression/ClientSide/OneClickBinding/TableWidget/index_spec.ts index 6a935b49b669..8b2f6ae3c144 100644 --- a/app/client/cypress/e2e/Regression/ClientSide/OneClickBinding/TableWidget/index_spec.ts +++ b/app/client/cypress/e2e/Regression/ClientSide/OneClickBinding/TableWidget/index_spec.ts @@ -1,13 +1,16 @@ +import oneClickBindingLocator from "../../../../../locators/OneClickBindingLocator"; import * as _ from "../../../../../support/Objects/ObjectsCore"; -import locators from "../../../../../locators/OneClickBindingLocator"; describe("Table widget one click binding feature", () => { it("1.should check that connect data overlay is shown on the table", () => { - _.entityExplorer.DragDropWidgetNVerify("tablewidgetv2"); + _.entityExplorer.DragDropWidgetNVerify(_.draggableWidgets.TABLE); _.agHelper.AssertElementExist(_.table._connectDataHeader); _.agHelper.AssertElementExist(_.table._connectDataButton); // should check that tableData one click property control" - _.propPane.openWidgetPropertyPane(_.draggableWidgets.TABLE); - _.agHelper.AssertElementExist(locators.datasourceDropdownSelector); + _.entityExplorer.SelectEntityByName("Table1", "Widgets"); + + _.agHelper.AssertElementExist( + oneClickBindingLocator.datasourceDropdownSelector, + ); }); }); diff --git a/app/client/cypress/e2e/Regression/ClientSide/OneClickBinding/TableWidget/mongoDB_spec.ts b/app/client/cypress/e2e/Regression/ClientSide/OneClickBinding/TableWidget/mongoDB_spec.ts index 9224c11eaf63..7e05ddd4e9fe 100644 --- a/app/client/cypress/e2e/Regression/ClientSide/OneClickBinding/TableWidget/mongoDB_spec.ts +++ b/app/client/cypress/e2e/Regression/ClientSide/OneClickBinding/TableWidget/mongoDB_spec.ts @@ -1,9 +1,10 @@ -import { WIDGET } from "../../../../../locators/WidgetLocators"; +import oneClickBindingLocator from "../../../../../locators/OneClickBindingLocator"; import * as _ from "../../../../../support/Objects/ObjectsCore"; -import { ChooseAndAssertForm } from "../spec_utility"; -import locators from "../../../../../locators/OneClickBindingLocator"; +import { OneClickBinding } from "../spec_utility"; -describe.skip("one click binding mongodb datasource", function () { +const oneClickBinding = new OneClickBinding(); + +describe("one click binding mongodb datasource", function () { before(() => { _.entityExplorer.DragDropWidgetNVerify(_.draggableWidgets.TABLE, 400); }); @@ -15,16 +16,19 @@ describe.skip("one click binding mongodb datasource", function () { _.dataSources.CreateDataSource("Mongo"); cy.get("@dsName").then((dsName) => { - _.entityExplorer.NavigateToSwitcher("Widgets"); - - (cy as any).openPropertyPane(WIDGET.TABLE); - - ChooseAndAssertForm(`New from ${dsName}`, dsName, "netflix", "creator"); + _.entityExplorer.SelectEntityByName("Table1", "Widgets"); + + oneClickBinding.ChooseAndAssertForm( + `New from ${dsName}`, + dsName, + "netflix", + "creator", + ); }); - _.agHelper.GetNClick(locators.connectData); + _.agHelper.GetNClick(oneClickBindingLocator.connectData); - cy.wait("@postExecute"); + _.agHelper.ValidateNetworkStatus("@postExecute"); _.agHelper.Sleep(2000); //#endregion @@ -36,7 +40,7 @@ describe.skip("one click binding mongodb datasource", function () { _.agHelper.Sleep(); // check if the table rows are present for the given search entry _.agHelper.GetNAssertContains( - '.t--widget-tablewidgetv2 [role="rowgroup"] [role="button"]', + oneClickBindingLocator.validTableRowData, rowWithAValidText, ); //#endregion @@ -89,7 +93,7 @@ describe.skip("one click binding mongodb datasource", function () { //check if that row is present _.agHelper.GetNAssertContains( - '.t--widget-tablewidgetv2 [role="rowgroup"] [role="button"]', + oneClickBindingLocator.validTableRowData, someText, ); //#endregion diff --git a/app/client/cypress/e2e/Regression/ClientSide/OneClickBinding/TableWidget/postgres_spec.ts b/app/client/cypress/e2e/Regression/ClientSide/OneClickBinding/TableWidget/postgres_spec.ts index 2975ee474c82..e6a84e1ff024 100644 --- a/app/client/cypress/e2e/Regression/ClientSide/OneClickBinding/TableWidget/postgres_spec.ts +++ b/app/client/cypress/e2e/Regression/ClientSide/OneClickBinding/TableWidget/postgres_spec.ts @@ -1,9 +1,10 @@ -import { WIDGET } from "../../../../../locators/WidgetLocators"; +import oneClickBindingLocator from "../../../../../locators/OneClickBindingLocator"; import * as _ from "../../../../../support/Objects/ObjectsCore"; -import { ChooseAndAssertForm } from "../spec_utility"; -import locators from "../../../../../locators/OneClickBindingLocator"; +import { OneClickBinding } from "../spec_utility"; -describe.skip("Table widget one click binding feature", () => { +const oneClickBinding = new OneClickBinding(); + +describe("Table widget one click binding feature", () => { it("should check that queries are created and bound to table widget properly", () => { _.entityExplorer.DragDropWidgetNVerify(_.draggableWidgets.TABLE, 400); @@ -14,14 +15,19 @@ describe.skip("Table widget one click binding feature", () => { cy.get("@dsName").then((dsName) => { _.entityExplorer.NavigateToSwitcher("Widgets"); - (cy as any).openPropertyPane(WIDGET.TABLE); + _.entityExplorer.SelectEntityByName("Table1", "Widgets"); - ChooseAndAssertForm(`New from ${dsName}`, dsName, "public.users", "name"); + oneClickBinding.ChooseAndAssertForm( + `New from ${dsName}`, + dsName, + "public.users", + "name", + ); }); - _.agHelper.GetNClick(locators.connectData); + _.agHelper.GetNClick(oneClickBindingLocator.connectData); - cy.wait("@postExecute"); + _.agHelper.ValidateNetworkStatus("@postExecute"); cy.wait(2000); @@ -43,19 +49,19 @@ describe.skip("Table widget one click binding feature", () => { (cy as any).enterTableCellValue(3, 0, " 2016-06-22 19:10:25-07"); - _.agHelper.GetNClick(`[data-testid="datepicker-container"] input`, 0, true); + _.agHelper.GetNClick(oneClickBindingLocator.dateInput, 0, true); - _.agHelper.GetNClick(".DayPicker-Day", 0, true); + _.agHelper.GetNClick(oneClickBindingLocator.dayViewFromDate, 0, true); (cy as any).wait(2000); _.agHelper.GetNClick(_.table._saveNewRow, 0, true); - cy.wait("@postExecute"); + _.agHelper.ValidateNetworkStatus("@postExecute"); _.agHelper.TypeText(_.table._searchInput, "cypress@appsmith"); - cy.wait("@postExecute"); + _.agHelper.ValidateNetworkStatus("@postExecute"); _.agHelper.AssertElementExist(_.table._bodyCell("cypress@appsmith")); @@ -73,9 +79,9 @@ describe.skip("Table widget one click binding feature", () => { (cy as any).saveTableRow(12, 0); - cy.wait("@postExecute"); + _.agHelper.ValidateNetworkStatus("@postExecute"); - cy.wait("@postExecute"); + _.agHelper.ValidateNetworkStatus("@postExecute"); (cy as any).wait(500); @@ -83,7 +89,7 @@ describe.skip("Table widget one click binding feature", () => { _.agHelper.TypeText(_.table._searchInput, "automation@appsmith"); - cy.wait("@postExecute"); + _.agHelper.ValidateNetworkStatus("@postExecute"); (cy as any).wait(2000); @@ -93,7 +99,7 @@ describe.skip("Table widget one click binding feature", () => { _.agHelper.TypeText(_.table._searchInput, "cypress@appsmith"); - cy.wait("@postExecute"); + _.agHelper.ValidateNetworkStatus("@postExecute"); (cy as any).wait(2000); diff --git a/app/client/cypress/e2e/Regression/ClientSide/OneClickBinding/spec_utility.ts b/app/client/cypress/e2e/Regression/ClientSide/OneClickBinding/spec_utility.ts index 42aadf2ec8ca..84c797571f61 100644 --- a/app/client/cypress/e2e/Regression/ClientSide/OneClickBinding/spec_utility.ts +++ b/app/client/cypress/e2e/Regression/ClientSide/OneClickBinding/spec_utility.ts @@ -1,68 +1,62 @@ import * as _ from "../../../../support/Objects/ObjectsCore"; +import oneClickBindingLocator from "../../../../locators/OneClickBindingLocator"; -export function ChooseAndAssertForm(source, selectedSource, table, column) { - _.agHelper.GetNClick(".t--one-click-binding-datasource-selector"); +export class OneClickBinding { + public ChooseAndAssertForm( + source?: string, + selectedSource?: any, + table?: string, + column?: string, + ) { + _.agHelper.GetNClick(oneClickBindingLocator.datasourceDropdownSelector); - _.agHelper.AssertElementAbsence( - '[data-testId="t--one-click-binding-connect-data"]', - ); + _.agHelper.AssertElementAbsence(oneClickBindingLocator.connectData); - _.agHelper.GetNClick( - `[data-testid="t--one-click-binding-datasource-selector--datasource"]:contains(${source})`, - ); + _.agHelper.GetNClick(oneClickBindingLocator.datasourceSelector(source)); - cy.wait("@getDatasourceStructure").should( - "have.nested.property", - "response.body.responseMeta.status", - 200, - ); + cy.wait("@getDatasourceStructure").should( + "have.nested.property", + "response.body.responseMeta.status", + 200, + ); - _.agHelper.Sleep(500); - _.agHelper.AssertElementExist( - '[data-testId="t--one-click-binding-connect-data"]', - ); + _.agHelper.Sleep(500); + _.agHelper.AssertElementExist(oneClickBindingLocator.connectData); - _.agHelper.AssertElementEnabledDisabled( - '[data-testId="t--one-click-binding-connect-data"]', - ); + _.agHelper.AssertElementEnabledDisabled(oneClickBindingLocator.connectData); - _.agHelper.AssertElementExist( - '[data-testid="t--one-click-binding-table-selector"]', - ); + _.agHelper.AssertElementExist( + oneClickBindingLocator.tableOrSpreadsheetDropdown, + ); - _.agHelper.GetNClick('[data-testid="t--one-click-binding-table-selector"]'); + _.agHelper.GetNClick(oneClickBindingLocator.tableOrSpreadsheetDropdown); - _.agHelper.GetNClick( - `.t--one-click-binding-table-selector--table:contains(${table})`, - ); + _.agHelper.GetNClick( + oneClickBindingLocator.tableOrSpreadsheetDropdownOption(table), + ); - _.agHelper.AssertElementExist( - `[data-testid="t--one-click-binding-table-selector"] .rc-select-selection-item:contains(${table})`, - ); + _.agHelper.AssertElementExist( + oneClickBindingLocator.tableOrSpreadsheetSelectedOption(table), + ); - _.agHelper.AssertElementExist( - '[data-testid="t--one-click-binding-column-searchableColumn"]', - ); + _.agHelper.AssertElementExist(oneClickBindingLocator.searchableColumn); - _.agHelper.GetNClick( - '[data-testid="t--one-click-binding-column-searchableColumn"]', - ); + _.agHelper.GetNClick(oneClickBindingLocator.searchableColumn); - _.agHelper.GetNClick( - `.t--one-click-binding-column-searchableColumn--column:contains(${column})`, - ); + _.agHelper.GetNClick( + oneClickBindingLocator.searchableColumnDropdownOption(column), + ); - _.agHelper.AssertElementExist( - `[data-testid="t--one-click-binding-column-searchableColumn"] .rc-select-selection-item:contains(${column})`, - ); + _.agHelper.AssertElementExist( + oneClickBindingLocator.searchableColumnSelectedOption(column), + ); - _.agHelper.AssertElementExist( - '[data-testId="t--one-click-binding-connect-data"]', - ); + _.agHelper.AssertElementExist(oneClickBindingLocator.connectData); - _.agHelper.AssertElementEnabledDisabled( - '[data-testId="t--one-click-binding-connect-data"]', - 0, - false, - ); + _.agHelper.AssertElementEnabledDisabled( + oneClickBindingLocator.connectData, + 0, + false, + ); + } } diff --git a/app/client/cypress/e2e/Regression/ClientSide/Widgets/TableV2/Add_new_row_spec.js b/app/client/cypress/e2e/Regression/ClientSide/Widgets/TableV2/Add_new_row_spec.js index 4fb41d8f2161..6c603de34a37 100644 --- a/app/client/cypress/e2e/Regression/ClientSide/Widgets/TableV2/Add_new_row_spec.js +++ b/app/client/cypress/e2e/Regression/ClientSide/Widgets/TableV2/Add_new_row_spec.js @@ -207,10 +207,8 @@ describe("Table widget Add new row feature's", () => { cy.wait(500); cy.get(`.t--inlined-cell-editor-has-error`).should("not.exist"); cy.enterTableCellValue(0, 0, "22"); - cy.wait(500); cy.get(`.t--inlined-cell-editor-has-error`).should("exist"); cy.enterTableCellValue(0, 0, "#1"); - cy.wait(500); cy.get(`.t--inlined-cell-editor-has-error`).should("not.exist"); propPane.UpdatePropertyFieldValue("Valid", ""); @@ -218,22 +216,17 @@ describe("Table widget Add new row feature's", () => { cy.wait(500); cy.get(`.t--inlined-cell-editor-has-error`).should("not.exist"); cy.enterTableCellValue(0, 0, "22"); - cy.wait(500); cy.get(`.t--inlined-cell-editor-has-error`).should("exist"); cy.enterTableCellValue(0, 0, "#1"); - cy.wait(500); cy.get(`.t--inlined-cell-editor-has-error`).should("not.exist"); propPane.UpdatePropertyFieldValue("Regex", ""); propPane.ToggleOnOrOff("Required", "On"); cy.enterTableCellValue(0, 0, "22"); - cy.wait(500); cy.get(`.t--inlined-cell-editor-has-error`).should("not.exist"); cy.enterTableCellValue(0, 0, "#1"); - cy.wait(500); cy.get(`.t--inlined-cell-editor-has-error`).should("not.exist"); cy.enterTableCellValue(0, 0, ""); - cy.wait(500); cy.get(`.t--inlined-cell-editor-has-error`).should("exist"); cy.get(commonlocators.changeColType).last().click(); @@ -242,37 +235,27 @@ describe("Table widget Add new row feature's", () => { propPane.UpdatePropertyFieldValue("Min", "5"); cy.enterTableCellValue(0, 0, "6"); - cy.wait(500); cy.get(`.t--inlined-cell-editor-has-error`).should("not.exist"); cy.enterTableCellValue(0, 0, "7"); - cy.wait(500); cy.get(`.t--inlined-cell-editor-has-error`).should("not.exist"); cy.enterTableCellValue(0, 0, "4"); - cy.wait(500); cy.get(`.t--inlined-cell-editor-has-error`).should("exist"); cy.enterTableCellValue(0, 0, "3"); - cy.wait(500); cy.get(`.t--inlined-cell-editor-has-error`).should("exist"); cy.enterTableCellValue(0, 0, "8"); - cy.wait(500); cy.get(`.t--inlined-cell-editor-has-error`).should("not.exist"); propPane.UpdatePropertyFieldValue("Min", ""); propPane.UpdatePropertyFieldValue("Max", "5"); cy.enterTableCellValue(0, 0, "6"); - cy.wait(500); cy.get(`.t--inlined-cell-editor-has-error`).should("exist"); cy.enterTableCellValue(0, 0, "7"); - cy.wait(500); cy.get(`.t--inlined-cell-editor-has-error`).should("exist"); cy.enterTableCellValue(0, 0, "4"); - cy.wait(500); cy.get(`.t--inlined-cell-editor-has-error`).should("not.exist"); cy.enterTableCellValue(0, 0, "3"); - cy.wait(500); cy.get(`.t--inlined-cell-editor-has-error`).should("not.exist"); cy.enterTableCellValue(0, 0, "8"); - cy.wait(500); cy.get(`.t--inlined-cell-editor-has-error`).should("exist"); propPane.UpdatePropertyFieldValue("Max", ""); @@ -287,23 +270,18 @@ describe("Table widget Add new row feature's", () => { cy.editTableCell(0, 0); cy.enterTableCellValue(0, 0, "3"); - cy.wait(500); cy.get(`.t--inlined-cell-editor-has-error`).should("exist"); cy.enterTableCellValue(0, 0, "2"); - cy.wait(500); cy.get(`.t--inlined-cell-editor-has-error`).should("not.exist"); cy.discardTableCellValue(0, 0); cy.wait(500); cy.get(".t--add-new-row").click(); cy.wait(1000); cy.enterTableCellValue(0, 0, "3"); - cy.wait(500); cy.get(`.t--inlined-cell-editor-has-error`).should("exist"); cy.enterTableCellValue(0, 0, "2"); - cy.wait(500); cy.get(`.t--inlined-cell-editor-has-error`).should("exist"); cy.enterTableCellValue(0, 0, "1"); - cy.wait(500); cy.get(`.t--inlined-cell-editor-has-error`).should("not.exist"); cy.get(".t--discard-new-row").click({ force: true }); }); @@ -338,10 +316,8 @@ describe("Table widget Add new row feature's", () => { cy.get(".t--save-new-row").should("be.disabled"); cy.get(`.t--inlined-cell-editor-has-error`).should("have.length", 2); cy.enterTableCellValue(0, 0, "1"); - cy.wait(1000); cy.get(`.t--inlined-cell-editor-has-error`).should("have.length", 1); cy.enterTableCellValue(1, 0, "invalid"); - cy.wait(1000); cy.get(`.t--inlined-cell-editor-has-error`).should("have.length", 0); cy.get(".t--save-new-row").should("not.be.disabled"); }); diff --git a/app/client/cypress/e2e/Regression/ClientSide/Widgets/TableV2/freeze_column_spec.js b/app/client/cypress/e2e/Regression/ClientSide/Widgets/TableV2/freeze_column_spec.js index 786a4e4e131f..2d970994cf96 100644 --- a/app/client/cypress/e2e/Regression/ClientSide/Widgets/TableV2/freeze_column_spec.js +++ b/app/client/cypress/e2e/Regression/ClientSide/Widgets/TableV2/freeze_column_spec.js @@ -400,8 +400,7 @@ describe("2. Check column freeze and unfreeze mechanism in page mode", () => { }); after(() => { - cy.openPropertyPane(WIDGET.TABLE); - _.propPane.DeleteWidget(); + _.propPane.DeleteWidgetFromPropertyPane("Table1"); }); }); diff --git a/app/client/cypress/e2e/Regression/ClientSide/Widgets/TableV2/inline_editing_validations_spec.js b/app/client/cypress/e2e/Regression/ClientSide/Widgets/TableV2/inline_editing_validations_spec.js index 8f1afcfeb4d2..c2b2e507cc79 100644 --- a/app/client/cypress/e2e/Regression/ClientSide/Widgets/TableV2/inline_editing_validations_spec.js +++ b/app/client/cypress/e2e/Regression/ClientSide/Widgets/TableV2/inline_editing_validations_spec.js @@ -84,10 +84,8 @@ describe("Table widget inline editing validation functionality", () => { cy.wait(500); cy.get(`.t--inlined-cell-editor-has-error`).should("not.exist"); cy.enterTableCellValue(0, 0, "22"); - cy.wait(500); cy.get(`.t--inlined-cell-editor-has-error`).should("exist"); cy.enterTableCellValue(0, 0, "#1"); - cy.wait(500); cy.get(`.t--inlined-cell-editor-has-error`).should("not.exist"); }); @@ -100,10 +98,8 @@ describe("Table widget inline editing validation functionality", () => { cy.wait(500); cy.get(`.t--inlined-cell-editor-has-error`).should("not.exist"); cy.enterTableCellValue(0, 0, "22"); - cy.wait(500); cy.get(`.t--inlined-cell-editor-has-error`).should("exist"); cy.enterTableCellValue(0, 0, "#1"); - cy.wait(500); cy.get(`.t--inlined-cell-editor-has-error`).should("not.exist"); }); @@ -116,13 +112,10 @@ describe("Table widget inline editing validation functionality", () => { cy.wait(500); cy.get(`.t--inlined-cell-editor-has-error`).should("exist"); cy.enterTableCellValue(0, 0, "22"); - cy.wait(500); cy.get(`.t--inlined-cell-editor-has-error`).should("not.exist"); cy.enterTableCellValue(0, 0, "#1"); - cy.wait(500); cy.get(`.t--inlined-cell-editor-has-error`).should("not.exist"); cy.enterTableCellValue(0, 0, ""); - cy.wait(500); cy.get(`.t--inlined-cell-editor-has-error`).should("exist"); }); }); @@ -143,19 +136,14 @@ describe("Table widget inline editing validation functionality", () => { cy.wait(500); cy.get(`.t--inlined-cell-editor-has-error`).should("not.exist"); cy.enterTableCellValue(0, 0, "6"); - cy.wait(500); cy.get(`.t--inlined-cell-editor-has-error`).should("not.exist"); cy.enterTableCellValue(0, 0, "7"); - cy.wait(500); cy.get(`.t--inlined-cell-editor-has-error`).should("not.exist"); cy.enterTableCellValue(0, 0, "4"); - cy.wait(500); cy.get(`.t--inlined-cell-editor-has-error`).should("exist"); cy.enterTableCellValue(0, 0, "3"); - cy.wait(500); cy.get(`.t--inlined-cell-editor-has-error`).should("exist"); cy.enterTableCellValue(0, 0, "8"); - cy.wait(500); cy.get(`.t--inlined-cell-editor-has-error`).should("not.exist"); }); @@ -174,19 +162,14 @@ describe("Table widget inline editing validation functionality", () => { cy.wait(500); cy.get(`.t--inlined-cell-editor-has-error`).should("not.exist"); cy.enterTableCellValue(0, 0, "6"); - cy.wait(500); cy.get(`.t--inlined-cell-editor-has-error`).should("exist"); cy.enterTableCellValue(0, 0, "7"); - cy.wait(500); cy.get(`.t--inlined-cell-editor-has-error`).should("exist"); cy.enterTableCellValue(0, 0, "4"); - cy.wait(500); cy.get(`.t--inlined-cell-editor-has-error`).should("not.exist"); cy.enterTableCellValue(0, 0, "3"); - cy.wait(500); cy.get(`.t--inlined-cell-editor-has-error`).should("not.exist"); cy.enterTableCellValue(0, 0, "8"); - cy.wait(500); cy.get(`.t--inlined-cell-editor-has-error`).should("exist"); }); }); @@ -200,7 +183,6 @@ describe("Table widget inline editing validation functionality", () => { cy.editTableCell(0, 0); cy.wait(1000); cy.enterTableCellValue(0, 0, "123"); - cy.wait(500); cy.get(".bp3-overlay.error-tooltip .bp3-popover-content").should( "contain", "You got error mate!!", @@ -224,7 +206,6 @@ describe("Table widget inline editing validation functionality", () => { cy.get(`.t--inlined-cell-editor-has-error`).should("exist"); cy.get(widgetsPage.toastAction).should("not.exist"); cy.enterTableCellValue(0, 0, "#1"); - cy.wait(500); cy.saveTableCellValue(0, 0); cy.get(`.t--inlined-cell-editor`).should("not.exist"); cy.get(`.t--inlined-cell-editor-has-error`).should("not.exist"); diff --git a/app/client/cypress/locators/OneClickBindingLocator.ts b/app/client/cypress/locators/OneClickBindingLocator.ts index be9620b866c9..e22126789ced 100644 --- a/app/client/cypress/locators/OneClickBindingLocator.ts +++ b/app/client/cypress/locators/OneClickBindingLocator.ts @@ -20,8 +20,30 @@ export default { `.t--one-click-binding-datasource-selector--other-action${ action ? `:contains(${action})` : "" }`, - datasourcePage: ".t--integrationsHomePage", - backButton: ".t--back-button", + tableOrSpreadsheetDropdown: + '[data-testid="t--one-click-binding-table-selector"]', + tableOrSpreadsheetDropdownOption: (table?: string) => + `.t--one-click-binding-table-selector--table${ + table ? `:contains(${table})` : "" + }`, + tableOrSpreadsheetSelectedOption: (table?: string) => + `[data-testid="t--one-click-binding-table-selector"] .rc-select-selection-item${ + table ? `:contains(${table})` : "" + }`, + searchableColumn: + '[data-testid="t--one-click-binding-column-searchableColumn"]', + searchableColumnDropdownOption: (column?: string) => + `.t--one-click-binding-column-searchableColumn--column${ + column ? `:contains(${column})` : "" + }`, + searchableColumnSelectedOption: (column?: string) => + `[data-testid="t--one-click-binding-column-searchableColumn"] .rc-select-selection-item${ + column ? `:contains(${column})` : "" + }`, + validTableRowData: + '.t--widget-tablewidgetv2 [role="rowgroup"] [role="button"]', tableError: (error: string) => `[data-testId="t--one-click-binding-table-selector--error"]:contains(${error})`, + dateInput: `[data-testid="datepicker-container"] input`, + dayViewFromDate: ".DayPicker-Day", }; diff --git a/app/client/cypress/support/Pages/PropertyPane.ts b/app/client/cypress/support/Pages/PropertyPane.ts index 3982fa06f0bf..86f2a5b89d1c 100644 --- a/app/client/cypress/support/Pages/PropertyPane.ts +++ b/app/client/cypress/support/Pages/PropertyPane.ts @@ -101,13 +101,6 @@ export class PropertyPane { this.isMac ? "{cmd}{a}" : "{ctrl}{a}" }`; - private getWidgetSelector = (widgetType: string) => - `div.t--widget-${widgetType}`; - - public openWidgetPropertyPane(widgetType: string) { - this.agHelper.GetNClick(this.getWidgetSelector(widgetType)); - } - public OpenJsonFormFieldSettings(fieldName: string) { this.agHelper.GetNClick(this._fieldConfig(fieldName)); } @@ -462,10 +455,4 @@ export class PropertyPane { this.agHelper.GetNClick(this._pageName(pageName)); this.agHelper.AssertAutoSave(); } - - public DeleteWidget() { - ObjectsRegistry.AggregateHelper.GetNClick( - `[data-testid="t--delete-widget"]`, - ); - } } diff --git a/app/client/cypress/support/widgetCommands.js b/app/client/cypress/support/widgetCommands.js index c9a6ec85ef20..15a52a9d2df0 100644 --- a/app/client/cypress/support/widgetCommands.js +++ b/app/client/cypress/support/widgetCommands.js @@ -1478,7 +1478,8 @@ Cypress.Commands.add("enterTableCellValue", (x, y, text) => { `[data-colindex="${x}"][data-rowindex="${y}"] .t--inlined-cell-editor input.bp3-input`, ) .focus() - .type(text); + .type(text) + .wait(500); } }); diff --git a/app/client/src/components/editorComponents/WidgetQueryGeneratorForm/CommonControls/DatasourceDropdown/DropdownOption.tsx b/app/client/src/components/editorComponents/WidgetQueryGeneratorForm/CommonControls/DatasourceDropdown/DropdownOption.tsx index 1f7aa689b754..37c353ca5a27 100644 --- a/app/client/src/components/editorComponents/WidgetQueryGeneratorForm/CommonControls/DatasourceDropdown/DropdownOption.tsx +++ b/app/client/src/components/editorComponents/WidgetQueryGeneratorForm/CommonControls/DatasourceDropdown/DropdownOption.tsx @@ -4,6 +4,7 @@ import styled from "styled-components"; const Container = styled.div` display: flex; width: calc(100% - 10px); + height: 100%; `; const LeftSection = styled.div` @@ -12,14 +13,9 @@ const LeftSection = styled.div` align-items: center; `; -const RightSection = styled.div` - width: 16px; -`; - const IconContainer = styled.div` width: 24px; display: flex; - margin-top: 3px; `; const Label = styled.div` @@ -43,11 +39,7 @@ export function DropdownOption(props: Props) { {leftIcon && <IconContainer>{leftIcon}</IconContainer>} <Label>{label}</Label> </LeftSection> - {rightIcon && ( - <RightSection> - <IconContainer>{rightIcon}</IconContainer> - </RightSection> - )} + {rightIcon && <IconContainer>{rightIcon}</IconContainer>} </Container> ); } diff --git a/app/client/src/components/editorComponents/WidgetQueryGeneratorForm/CommonControls/DatasourceDropdown/index.tsx b/app/client/src/components/editorComponents/WidgetQueryGeneratorForm/CommonControls/DatasourceDropdown/index.tsx index 9beda7e315c5..accbbad0399b 100644 --- a/app/client/src/components/editorComponents/WidgetQueryGeneratorForm/CommonControls/DatasourceDropdown/index.tsx +++ b/app/client/src/components/editorComponents/WidgetQueryGeneratorForm/CommonControls/DatasourceDropdown/index.tsx @@ -4,7 +4,6 @@ import { useDatasource } from "./useDatasource"; import { Select, Option, Icon } from "design-system"; import { DropdownOption } from "./DropdownOption"; import styled from "styled-components"; -import { Colors } from "constants/Colors"; import type { DropdownOptionType } from "../../types"; import type { DefaultOptionType } from "rc-select/lib/Select"; import { DATASOURCE_DROPDOWN_SECTIONS } from "../../constants"; @@ -13,7 +12,7 @@ const SectionHeader = styled.div` cursor: default; font-weight: 500; line-height: 19px; - color: ${Colors.GREY_900}; + color: var(--ads-v2-color-gray-600); `; function DatasourceDropdown() { @@ -128,10 +127,10 @@ function DatasourceDropdown() { > <DropdownOption label={ - <> + <span> New from {option.data.isSample ? "sample " : ""} <Bold>{option.label?.replace("sample ", "")}</Bold> - </> + </span> } leftIcon={option.icon} rightIcon={<Icon name="add-box-line" size="md" />} diff --git a/app/client/src/components/editorComponents/WidgetQueryGeneratorForm/ConnectData/index.tsx b/app/client/src/components/editorComponents/WidgetQueryGeneratorForm/ConnectData/index.tsx index 6b021e53a1ad..2b4c9e5a45b9 100644 --- a/app/client/src/components/editorComponents/WidgetQueryGeneratorForm/ConnectData/index.tsx +++ b/app/client/src/components/editorComponents/WidgetQueryGeneratorForm/ConnectData/index.tsx @@ -13,6 +13,7 @@ export function ConnectData() { isDisabled={disabled} isLoading={isLoading} onClick={onClick} + size="md" > Connect data </StyledButton> diff --git a/app/client/src/components/editorComponents/WidgetQueryGeneratorForm/styles.tsx b/app/client/src/components/editorComponents/WidgetQueryGeneratorForm/styles.tsx index eda5d757f87a..b62d33ccda8b 100644 --- a/app/client/src/components/editorComponents/WidgetQueryGeneratorForm/styles.tsx +++ b/app/client/src/components/editorComponents/WidgetQueryGeneratorForm/styles.tsx @@ -18,7 +18,7 @@ export const Label = styled.p` `; export const Bold = styled.span` - font-weight: 700; + font-weight: 500; `; export const Section = styled.div``; @@ -40,13 +40,6 @@ export const RowHeading = styled.p` export const StyledButton = styled(Button)` &&& { width: 100%; - height: 50px !important; - border-radius: 1px !important; - - & > div { - padding: 10px 0px; - height: 36px; - } } `; diff --git a/app/client/src/widgets/TableWidgetV2/component/ConnectDataOverlay.tsx b/app/client/src/widgets/TableWidgetV2/component/ConnectDataOverlay.tsx index 5003f1379df6..5daaaa2295ee 100644 --- a/app/client/src/widgets/TableWidgetV2/component/ConnectDataOverlay.tsx +++ b/app/client/src/widgets/TableWidgetV2/component/ConnectDataOverlay.tsx @@ -1,4 +1,5 @@ import { Colors } from "constants/Colors"; +import { Button } from "design-system"; import React from "react"; import styled from "styled-components"; @@ -30,17 +31,11 @@ const Header = styled.div` font-size: 16px; line-height: 24px; color: ${Colors.GREY_900}; - margin-bottom: 15px; + margin-bottom: 12px; `; -const ConnecData = styled.button` - padding: 6px 15px; - max-width: 250px; - margin-bottom: 15px; - width: 100%; - background: #f86a2b; - color: #fff; - font-size: 12px; +const ConnecData = styled(Button)` + margin-bottom: 16px; `; const Footer = styled.div` @@ -59,6 +54,7 @@ export function ConnectDataOverlay(props: { onConnectData: () => void }) { <ConnecData className="t--cypress-table-overlay-connectdata" onClick={props.onConnectData} + size="md" > Connect data </ConnecData>
34fc5a135fc9528f04c64742f490c2be05d5a932
2023-03-13 15:24:47
Saroj
test: fixing cypress dependency issues (#21323)
false
fixing cypress dependency issues (#21323)
test
diff --git a/app/client/cypress/package.json b/app/client/cypress/package.json index aaf8f30ec99e..499fc20c9948 100644 --- a/app/client/cypress/package.json +++ b/app/client/cypress/package.json @@ -16,6 +16,11 @@ "not op_mini all" ], "devDependencies": { + "@blueprintjs/core": "^3.36.0", + "@blueprintjs/datetime": "^3.23.6", + "@blueprintjs/icons": "^3.10.0", + "@blueprintjs/popover2": "^0.5.0", + "@blueprintjs/select": "^3.10.0", "@typescript-eslint/eslint-plugin": "^5.25.0", "@typescript-eslint/parser": "^5.25.0", "@faker-js/faker": "^7.4.0", @@ -32,6 +37,7 @@ "dotenv": "^8.1.0", "typescript": "4.5.5", "diff": "^5.0.0", - "chalk": "^4.1.1" + "chalk": "^4.1.1", + "tinycolor2": "^1.4.2" } }
2d40060e58649c7ad38442f0f7de6c75ff129350
2024-06-06 14:58:55
Valera Melnikov
fix: preview mode canvas cutoff (#33960)
false
preview mode canvas cutoff (#33960)
fix
diff --git a/app/client/src/layoutSystems/common/mainContainerResizer/MainContainerResizer.tsx b/app/client/src/layoutSystems/common/mainContainerResizer/MainContainerResizer.tsx index 8fcb4c9c1c03..a929e631583b 100644 --- a/app/client/src/layoutSystems/common/mainContainerResizer/MainContainerResizer.tsx +++ b/app/client/src/layoutSystems/common/mainContainerResizer/MainContainerResizer.tsx @@ -60,17 +60,17 @@ export function MainContainerResizer({ enableMainCanvasResizer, isPageInitiated, isPreview, + navigationHeight, }: { isPageInitiated: boolean; - shouldHaveTopMargin: boolean; isPreview: boolean; currentPageId: string; enableMainCanvasResizer: boolean; + navigationHeight?: number; }) { const appLayout = useSelector(getCurrentApplicationLayout); const ref = useRef<HTMLDivElement>(null); const dispatch = useDispatch(); - const topHeaderHeight = "48px"; useEffect(() => { const ele: HTMLElement | null = document.getElementById(CANVAS_VIEWPORT); @@ -170,8 +170,8 @@ export function MainContainerResizer({ }} ref={ref} style={{ - top: isPreview ? topHeaderHeight : "0", - height: isPreview ? `calc(100% - ${topHeaderHeight})` : "100%", + top: isPreview ? navigationHeight : "0", + height: isPreview ? `calc(100% - ${navigationHeight})` : "100%", }} > <div className="canvas-resizer-icon"> diff --git a/app/client/src/pages/Editor/WidgetsEditor/components/MainContainerWrapper.tsx b/app/client/src/pages/Editor/WidgetsEditor/components/MainContainerWrapper.tsx index 5780d42021d8..a60692ce9941 100644 --- a/app/client/src/pages/Editor/WidgetsEditor/components/MainContainerWrapper.tsx +++ b/app/client/src/pages/Editor/WidgetsEditor/components/MainContainerWrapper.tsx @@ -134,8 +134,6 @@ function MainContainerWrapper(props: MainCanvasWrapperProps) { useMainContainerResizer(); const isAnvilLayout = useSelector(getIsAnvilLayout); - const headerHeight = "40px"; - useEffect(() => { return () => { dispatch(forceOpenWidgetPanel(false)); @@ -206,7 +204,7 @@ function MainContainerWrapper(props: MainCanvasWrapperProps) { isPreviewingNavigation={isPreviewingNavigation} navigationHeight={navigationHeight} style={{ - height: isPreviewMode ? `calc(100% - ${headerHeight})` : "auto", + height: isPreviewMode ? `calc(100% - ${navigationHeight})` : "auto", fontFamily: fontFamily, pointerEvents: isAutoCanvasResizing ? "none" : "auto", }} @@ -229,7 +227,7 @@ function MainContainerWrapper(props: MainCanvasWrapperProps) { enableMainCanvasResizer={enableMainContainerResizer && canShowResizer} isPageInitiated={!isPageInitializing && !!widgetsStructure} isPreview={isPreviewMode || isProtectedMode} - shouldHaveTopMargin={shouldHaveTopMargin} + navigationHeight={navigationHeight} /> </> );
cc36bdc0516a3f5b7376632f213f4a5b86390f0d
2021-05-12 13:27:28
Pawan Kumar
fix: TypeError: t.match is not a function (#4445)
false
TypeError: t.match is not a function (#4445)
fix
diff --git a/app/client/src/widgets/ListWidget/ListWidget.tsx b/app/client/src/widgets/ListWidget/ListWidget.tsx index 5b12f324891a..2e41d64f6f2d 100644 --- a/app/client/src/widgets/ListWidget/ListWidget.tsx +++ b/app/client/src/widgets/ListWidget/ListWidget.tsx @@ -1,6 +1,15 @@ import React from "react"; import log from "loglevel"; -import { compact, get, set, xor, isPlainObject, isNumber, round } from "lodash"; +import { + compact, + get, + set, + xor, + isPlainObject, + isNumber, + round, + toString, +} from "lodash"; import * as Sentry from "@sentry/react"; import WidgetFactory from "utils/WidgetFactory"; @@ -226,7 +235,7 @@ class ListWidget extends BaseWidget<ListWidgetProps<WidgetProps>, WidgetState> { const evaluatedValue = evaluatedProperty[itemIndex]; if (isPlainObject(evaluatedValue) || Array.isArray(evaluatedValue)) set(widget, path, JSON.stringify(evaluatedValue)); - else set(widget, path, evaluatedValue); + else set(widget, path, toString(evaluatedValue)); } }); }
6aa577958b59817b3532ddacd638b572138a89f6
2024-09-16 11:36:44
Hetu Nandu
chore: Add common items in the Toolbar of AppPluginEditor (#36324)
false
Add common items in the Toolbar of AppPluginEditor (#36324)
chore
diff --git a/app/client/src/PluginActionEditor/components/PluginActionToolbar.tsx b/app/client/src/PluginActionEditor/components/PluginActionToolbar.tsx index 75ee4dc86bd2..0d2e4f718d78 100644 --- a/app/client/src/PluginActionEditor/components/PluginActionToolbar.tsx +++ b/app/client/src/PluginActionEditor/components/PluginActionToolbar.tsx @@ -1,7 +1,11 @@ -import React from "react"; +import React, { useCallback } from "react"; import { IDEToolbar } from "IDE"; import { Button, Menu, MenuContent, MenuTrigger, Tooltip } from "@appsmith/ads"; import { modText } from "utils/helpers"; +import { usePluginActionContext } from "../PluginActionContext"; +import { useDispatch } from "react-redux"; +import AnalyticsUtil from "ee/utils/AnalyticsUtil"; +import { runAction } from "../../actions/pluginActionActions"; interface PluginActionToolbarProps { runOptions?: React.ReactNode; @@ -10,6 +14,25 @@ interface PluginActionToolbarProps { } const PluginActionToolbar = (props: PluginActionToolbarProps) => { + const { action, datasource, plugin } = usePluginActionContext(); + const dispatch = useDispatch(); + const handleRunClick = useCallback(() => { + AnalyticsUtil.logEvent("RUN_QUERY_CLICK", { + actionName: action.name, + actionId: action.id, + pluginName: plugin.name, + datasourceId: datasource?.id, + isMock: datasource?.isMock, + }); + dispatch(runAction(action.id)); + }, [ + action.id, + action.name, + datasource?.id, + datasource?.isMock, + dispatch, + plugin.name, + ]); return ( <IDEToolbar> <IDEToolbar.Left>{props.children}</IDEToolbar.Left> @@ -20,7 +43,7 @@ const PluginActionToolbar = (props: PluginActionToolbarProps) => { placement="topRight" showArrow={false} > - <Button kind="primary" size="sm"> + <Button kind="primary" onClick={handleRunClick} size="sm"> Run </Button> </Tooltip> @@ -30,7 +53,7 @@ const PluginActionToolbar = (props: PluginActionToolbarProps) => { size="sm" startIcon="settings-2-line" /> - <Menu> + <Menu key={action.id}> <MenuTrigger> <Button isIconButton @@ -39,7 +62,12 @@ const PluginActionToolbar = (props: PluginActionToolbarProps) => { startIcon="more-2-fill" /> </MenuTrigger> - <MenuContent loop style={{ zIndex: 100 }} width="200px"> + <MenuContent + key={action.id} + loop + style={{ zIndex: 100 }} + width="200px" + > {props.menuContent} </MenuContent> </Menu> diff --git a/app/client/src/ce/pages/Editor/AppPluginActionEditor/components/AppPluginActionToolbar.tsx b/app/client/src/ce/pages/Editor/AppPluginActionEditor/components/AppPluginActionToolbar.tsx index ab44ba573b3d..8606cee42fb3 100644 --- a/app/client/src/ce/pages/Editor/AppPluginActionEditor/components/AppPluginActionToolbar.tsx +++ b/app/client/src/ce/pages/Editor/AppPluginActionEditor/components/AppPluginActionToolbar.tsx @@ -1,9 +1,9 @@ import React from "react"; import { PluginActionToolbar } from "PluginActionEditor"; -import { ConvertToModuleCTA } from "./ConvertToModule"; +import AppPluginActionMenu from "./PluginActionMoreActions"; const AppPluginActionToolbar = () => { - return <PluginActionToolbar menuContent={<ConvertToModuleCTA />} />; + return <PluginActionToolbar menuContent={<AppPluginActionMenu />} />; }; export default AppPluginActionToolbar; diff --git a/app/client/src/ce/pages/Editor/AppPluginActionEditor/components/PluginActionMoreActions.tsx b/app/client/src/ce/pages/Editor/AppPluginActionEditor/components/PluginActionMoreActions.tsx new file mode 100644 index 000000000000..d8d37c754dd6 --- /dev/null +++ b/app/client/src/ce/pages/Editor/AppPluginActionEditor/components/PluginActionMoreActions.tsx @@ -0,0 +1,183 @@ +import React, { useCallback, useMemo, useState } from "react"; +import { + getHasDeleteActionPermission, + getHasManageActionPermission, +} from "ee/utils/BusinessFeatures/permissionPageHelpers"; +import { useFeatureFlag } from "utils/hooks/useFeatureFlag"; +import { FEATURE_FLAG } from "ee/entities/FeatureFlag"; +import { usePluginActionContext } from "PluginActionEditor"; +import { + MenuItem, + MenuSub, + MenuSubContent, + MenuSubTrigger, +} from "@appsmith/ads"; +import { + CONFIRM_CONTEXT_DELETE, + CONTEXT_COPY, + CONTEXT_DELETE, + CONTEXT_MOVE, + createMessage, +} from "ee/constants/messages"; +import { useDispatch, useSelector } from "react-redux"; +import { + copyActionRequest, + deleteAction, + moveActionRequest, +} from "actions/pluginActionActions"; +import { getCurrentPageId } from "selectors/editorSelectors"; +import type { Page } from "entities/Page"; +import { getPageList } from "ee/selectors/entitiesSelector"; +import { ConvertToModuleCTA } from "./ConvertToModule"; + +const PageMenuItem = (props: { + page: Page; + onSelect: (id: string) => void; +}) => { + const handleOnSelect = useCallback(() => { + props.onSelect(props.page.pageId); + }, [props]); + return <MenuItem onSelect={handleOnSelect}>{props.page.pageName}</MenuItem>; +}; + +const Copy = () => { + const menuPages = useSelector(getPageList); + const { action } = usePluginActionContext(); + const dispatch = useDispatch(); + + const copyActionToPage = useCallback( + (pageId: string) => + dispatch( + copyActionRequest({ + id: action.id, + destinationPageId: pageId, + name: action.name, + }), + ), + [action.id, action.name, dispatch], + ); + + return ( + <MenuSub> + <MenuSubTrigger startIcon="duplicate"> + {createMessage(CONTEXT_COPY)} + </MenuSubTrigger> + <MenuSubContent> + {menuPages.map((page) => { + return ( + <PageMenuItem + key={page.basePageId} + onSelect={copyActionToPage} + page={page} + /> + ); + })} + </MenuSubContent> + </MenuSub> + ); +}; + +const Move = () => { + const dispatch = useDispatch(); + const { action } = usePluginActionContext(); + + const currentPageId = useSelector(getCurrentPageId); + const allPages = useSelector(getPageList); + const menuPages = useMemo(() => { + return allPages.filter((page) => page.pageId !== currentPageId); + }, [allPages, currentPageId]); + + const moveActionToPage = useCallback( + (destinationPageId: string) => + dispatch( + moveActionRequest({ + id: action.id, + destinationPageId, + originalPageId: currentPageId, + name: action.name, + }), + ), + [dispatch, action.id, action.name, currentPageId], + ); + + return ( + <MenuSub> + <MenuSubTrigger startIcon="swap-horizontal"> + {createMessage(CONTEXT_MOVE)} + </MenuSubTrigger> + <MenuSubContent> + {menuPages.length > 1 ? ( + menuPages.map((page) => { + return ( + <PageMenuItem + key={page.basePageId} + onSelect={moveActionToPage} + page={page} + /> + ); + }) + ) : ( + <MenuItem key="no-pages">No pages</MenuItem> + )} + </MenuSubContent> + </MenuSub> + ); +}; + +const Delete = () => { + const dispatch = useDispatch(); + const { action } = usePluginActionContext(); + + const [confirmDelete, setConfirmDelete] = useState(false); + + const deleteActionFromPage = useCallback(() => { + dispatch(deleteAction({ id: action.id, name: action.name })); + }, [action.id, action.name, dispatch]); + + const handleSelect = useCallback(() => { + confirmDelete ? deleteActionFromPage() : setConfirmDelete(true); + }, [confirmDelete, deleteActionFromPage]); + + const menuLabel = confirmDelete + ? createMessage(CONFIRM_CONTEXT_DELETE) + : createMessage(CONTEXT_DELETE); + + return ( + <MenuItem + className="t--apiFormDeleteBtn error-menuitem" + onSelect={handleSelect} + startIcon="trash" + > + {menuLabel} + </MenuItem> + ); +}; + +const AppPluginActionMenu = () => { + const { action } = usePluginActionContext(); + + const isFeatureEnabled = useFeatureFlag(FEATURE_FLAG.license_gac_enabled); + const isChangePermitted = getHasManageActionPermission( + isFeatureEnabled, + action.userPermissions, + ); + const isDeletePermitted = getHasDeleteActionPermission( + isFeatureEnabled, + action?.userPermissions, + ); + + return ( + <> + <ConvertToModuleCTA /> + {isChangePermitted && ( + <> + <Copy /> + <Move /> + </> + )} + {isDeletePermitted && <Delete />} + </> + ); +}; + +export default AppPluginActionMenu;
347dba5aca831913c83c109aa20dc85a444182bb
2024-09-26 16:58:39
Aman Agarwal
fix: js library load functionality handling for default exports (#36539)
false
js library load functionality handling for default exports (#36539)
fix
diff --git a/app/client/src/workers/Evaluation/handlers/jsLibrary.ts b/app/client/src/workers/Evaluation/handlers/jsLibrary.ts index bdf704f2bab4..ce81c2d7bf5d 100644 --- a/app/client/src/workers/Evaluation/handlers/jsLibrary.ts +++ b/app/client/src/workers/Evaluation/handlers/jsLibrary.ts @@ -128,39 +128,31 @@ export async function installLibrary( // Find keys add that were installed to the global scope. const keysAfterInstallation = Object.keys(self); - const differentiatingKeys = difference( + let differentiatingKeys = difference( keysAfterInstallation, envKeysBeforeInstallation, ); - if ( - differentiatingKeys.length > 0 && - differentiatingKeys.includes("default") - ) { - // Changing default export to library specific name - const uniqueName = generateUniqueAccessor( - url, - takenAccessors, - takenNamesMap, - ); + // Changing default export to library specific name, if default exported + const uniqueName = generateUniqueAccessor( + url, + takenAccessors, + takenNamesMap, + ); - // mapping default functionality to library name accessor - self[uniqueName] = self["default"]; - // deleting the reference of default key from the self object - delete self["default"]; - // mapping all the references of differentiating keys from the self object to the self[uniqueName] key object - differentiatingKeys.map((key) => { - if (key !== "default") { - self[uniqueName][key] = self[key]; - // deleting the references from the self object - delete self[key]; - } - }); - // pushing the uniqueName to the accessor array - accessors.push(uniqueName); - } else { - accessors.push(...differentiatingKeys); - } + movetheDefaultExportedLibraryToAccessorKey( + differentiatingKeys, + uniqueName, + ); + + // Following the same process which was happening earlier + const keysAfterDefaultOperation = Object.keys(self); + + differentiatingKeys = difference( + keysAfterDefaultOperation, + envKeysBeforeInstallation, + ); + accessors.push(...differentiatingKeys); /** * Check the list of installed library to see if their values have changed. @@ -308,7 +300,18 @@ export async function loadLibraries( try { self.importScripts(url); const keysAfter = Object.keys(self); - const defaultAccessors = difference(keysAfter, keysBefore); + let defaultAccessors = difference(keysAfter, keysBefore); + + // Changing default export to library accessors name which was saved when it was installed, if default export present + movetheDefaultExportedLibraryToAccessorKey( + defaultAccessors, + accessors[0], + ); + + // Following the same process which was happening earlier + const keysAfterDefaultOperation = Object.keys(self); + + defaultAccessors = difference(keysAfterDefaultOperation, keysBefore); /** * Installing 2 different version of lodash tries to add the same accessor on the self object. Let take version a & b for example. @@ -447,3 +450,24 @@ export function flattenModule(module: Record<string, any>) { return libModule; } + +// This function will update the self keys only when the diffAccessors has default included in it. +function movetheDefaultExportedLibraryToAccessorKey( + diffAccessors: string[], + uniqAccessor: string, +) { + if (diffAccessors.length > 0 && diffAccessors.includes("default")) { + // mapping default functionality to library name accessor + self[uniqAccessor] = self["default"]; + // deleting the reference of default key from the self object + delete self["default"]; + // mapping all the references of differentiating keys from the self object to the self[uniqAccessor] key object + diffAccessors.map((key) => { + if (key !== "default") { + self[uniqAccessor][key] = self[key]; + // deleting the references from the self object + delete self[key]; + } + }); + } +}
a76b8cad9b5962d56d88022138abdbd694f03187
2021-06-17 18:56:54
Ashok Kumar M
feature: Widget Grouping Phase II (#4825)
false
Widget Grouping Phase II (#4825)
feature
diff --git a/app/client/cypress/fixtures/widgetSelection.json b/app/client/cypress/fixtures/widgetSelection.json new file mode 100644 index 000000000000..2347e0629b5e --- /dev/null +++ b/app/client/cypress/fixtures/widgetSelection.json @@ -0,0 +1,209 @@ +{ + "dsl": { + "widgetName": "MainContainer", + "backgroundColor": "none", + "rightColumn": 1270, + "snapColumns": 64, + "detachFromLayout": true, + "widgetId": "0", + "topRow": 0, + "bottomRow": 820, + "containerStyle": "none", + "snapRows": 125, + "parentRowSpace": 1, + "type": "CANVAS_WIDGET", + "canExtend": true, + "version": 23, + "minHeight": 830, + "parentColumnSpace": 1, + "dynamicTriggerPathList": [], + "dynamicBindingPathList": [], + "leftColumn": 0, + "children": [ + { + "widgetName": "Chart1", + "rightColumn": 26, + "allowHorizontalScroll": false, + "widgetId": "ypstklohw5", + "topRow": 4, + "bottomRow": 36, + "parentRowSpace": 10, + "isVisible": true, + "type": "CHART_WIDGET", + "version": 1, + "parentId": "0", + "isLoading": false, + "chartData": { + "3jzahcrorq": { + "seriesName": "Sales", + "data": [ + { + "x": "Mon", + "y": 10000 + }, + { + "x": "Tue", + "y": 12000 + }, + { + "x": "Wed", + "y": 32000 + }, + { + "x": "Thu", + "y": 28000 + }, + { + "x": "Fri", + "y": 14000 + }, + { + "x": "Sat", + "y": 19000 + }, + { + "x": "Sun", + "y": 36000 + } + ] + } + }, + "yAxisName": "Total Order Revenue $", + "parentColumnSpace": 19.65625, + "chartName": "Last week's revenue", + "leftColumn": 2, + "xAxisName": "Last Week", + "customFusionChartConfig": { + "type": "column2d", + "dataSource": { + "chart": { + "caption": "Last week's revenue", + "xAxisName": "Last Week", + "yAxisName": "Total Order Revenue $", + "theme": "fusion" + }, + "data": [ + { + "label": "Mon", + "value": 10000 + }, + { + "label": "Tue", + "value": 12000 + }, + { + "label": "Wed", + "value": 32000 + }, + { + "label": "Thu", + "value": 28000 + }, + { + "label": "Fri", + "value": 14000 + }, + { + "label": "Sat", + "value": 19000 + }, + { + "label": "Sun", + "value": 36000 + } + ], + "trendlines": [ + { + "line": [ + { + "startvalue": "38000", + "valueOnRight": "1", + "displayvalue": "Weekly Target" + } + ] + } + ] + } + }, + "chartType": "LINE_CHART" + }, + { + "backgroundColor": "#FFFFFF", + "widgetName": "Container1", + "rightColumn": 62, + "widgetId": "6y21iarlp4", + "containerStyle": "card", + "topRow": 11, + "bottomRow": 51, + "parentRowSpace": 10, + "isVisible": true, + "type": "CONTAINER_WIDGET", + "version": 1, + "parentId": "0", + "isLoading": false, + "parentColumnSpace": 19.65625, + "leftColumn": 30, + "children": [ + { + "widgetName": "Canvas1", + "rightColumn": 629, + "detachFromLayout": true, + "widgetId": "jqasr1uss5", + "containerStyle": "none", + "topRow": 0, + "bottomRow": 400, + "parentRowSpace": 1, + "isVisible": true, + "canExtend": false, + "type": "CANVAS_WIDGET", + "version": 1, + "parentId": "6y21iarlp4", + "minHeight": 400, + "isLoading": false, + "parentColumnSpace": 1, + "leftColumn": 0, + "children": [] + } + ] + }, + { + "image": "", + "widgetName": "Image1", + "rightColumn": 22, + "widgetId": "1t50avy6f1", + "topRow": 58, + "bottomRow": 70, + "parentRowSpace": 10, + "isVisible": true, + "type": "IMAGE_WIDGET", + "version": 1, + "parentId": "0", + "isLoading": false, + "maxZoomLevel": 1, + "parentColumnSpace": 19.65625, + "imageShape": "RECTANGLE", + "leftColumn": 6, + "defaultImage": "https://res.cloudinary.com/drako999/image/upload/v1589196259/default.png" + }, + { + "widgetName": "Button1", + "rightColumn": 18, + "isDefaultClickDisabled": true, + "widgetId": "41wgbhd5vp", + "buttonStyle": "PRIMARY_BUTTON", + "topRow": 44, + "bottomRow": 48, + "parentRowSpace": 10, + "isVisible": true, + "type": "BUTTON_WIDGET", + "version": 1, + "parentId": "0", + "isLoading": false, + "parentColumnSpace": 19.65625, + "leftColumn": 10, + "text": "Submit", + "isDisabled": false + } + ] + } + } \ No newline at end of file diff --git a/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/Debugger/Inspect_Element_spec.js b/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/Debugger/Inspect_Element_spec.js index c492494e8832..f565c11a99a7 100644 --- a/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/Debugger/Inspect_Element_spec.js +++ b/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/Debugger/Inspect_Element_spec.js @@ -10,8 +10,6 @@ describe("Inspect Entity", function() { cy.get(".t--debugger").click(); cy.contains(".react-tabs__tab", "Inspect Entity").click(); - - cy.openPropertyPane("inputwidget"); cy.contains(".t--dependencies-item", "Button1").click(); cy.contains(".t--references-item", "Input1"); }); diff --git a/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/Onboarding/Onboarding_spec.js b/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/Onboarding/Onboarding_spec.js index 98de0012e71f..47b1a0e21a06 100644 --- a/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/Onboarding/Onboarding_spec.js +++ b/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/Onboarding/Onboarding_spec.js @@ -50,7 +50,7 @@ describe("Onboarding", function() { // Add widget cy.get(".t--add-widget").click(); - cy.dragAndDropToCanvas("tablewidget", { x: 360, y: 20 }); + cy.dragAndDropToCanvas("tablewidget", { x: 360, y: 40 }); // wait for animation duration // eslint-disable-next-line cypress/no-unnecessary-waiting diff --git a/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/WidgetSelection/WidgetSelection_spec.js b/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/WidgetSelection/WidgetSelection_spec.js new file mode 100644 index 000000000000..ea436086a3c4 --- /dev/null +++ b/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/WidgetSelection/WidgetSelection_spec.js @@ -0,0 +1,27 @@ +const dsl = require("../../../../fixtures/widgetSelection.json"); + +describe("Widget Selection", function() { + before(() => { + cy.addDsl(dsl); + }); + + it("Multi Select widgets using cmd + click", function() { + cy.get(`#${dsl.dsl.children[0].widgetId}`).click({ + ctrlKey: true, + }); + cy.get(`#${dsl.dsl.children[1].widgetId}`).click({ + ctrlKey: true, + }); + cy.get(`.t--widget-propertypane-toggle`).should("have.length", 2); + cy.get(`#${dsl.dsl.children[2].widgetId}`).click({ + ctrlKey: true, + }); + cy.get(`.t--widget-propertypane-toggle`).should("have.length", 3); + cy.get(`#${dsl.dsl.children[0].widgetId}`).click({ + ctrlKey: true, + }); + cy.get(`.t--widget-propertypane-toggle`) + .not(`[style *= "background: rgb(255, 224, 210);"]`) // Excluding focused widgets. + .should("have.length", 2); + }); +}); diff --git a/app/client/cypress/support/commands.js b/app/client/cypress/support/commands.js index 5d7ead70f5ae..da41dfddd17e 100644 --- a/app/client/cypress/support/commands.js +++ b/app/client/cypress/support/commands.js @@ -2023,8 +2023,8 @@ Cypress.Commands.add("dragAndDropToCanvas", (widgetType, { x, y }) => { .trigger("mousedown", { button: 0 }, { force: true }) .trigger("mousemove", x, y, { force: true }); cy.get(explorer.dropHere) - .click(x, y + 20) - .trigger("mouseup", x, y + 20, { force: true }); + .trigger("mousemove", x, y) + .trigger("mouseup", x, y + 20); }); Cypress.Commands.add("executeDbQuery", (queryName) => { diff --git a/app/client/src/actions/canvasSelectionActions.ts b/app/client/src/actions/canvasSelectionActions.ts new file mode 100644 index 000000000000..e9030b14e2ee --- /dev/null +++ b/app/client/src/actions/canvasSelectionActions.ts @@ -0,0 +1,22 @@ +import { ReduxAction, ReduxActionTypes } from "constants/ReduxActionConstants"; +import { SelectedArenaDimensions } from "pages/common/CanvasSelectionArena"; + +export const setCanvasSelectionStateAction = (start: boolean) => { + return { + type: start + ? ReduxActionTypes.START_CANVAS_SELECTION + : ReduxActionTypes.STOP_CANVAS_SELECTION, + }; +}; + +export const selectAllWidgetsInAreaAction = ( + selectionArena: SelectedArenaDimensions, + snapToNextColumn: boolean, + snapToNextRow: boolean, + isMultiSelect: boolean, +): ReduxAction<any> => { + return { + type: ReduxActionTypes.SELECT_WIDGETS_IN_AREA, + payload: { selectionArena, snapToNextColumn, snapToNextRow, isMultiSelect }, + }; +}; diff --git a/app/client/src/actions/widgetActions.tsx b/app/client/src/actions/widgetActions.tsx index be7a5674d487..e45f15e366a2 100644 --- a/app/client/src/actions/widgetActions.tsx +++ b/app/client/src/actions/widgetActions.tsx @@ -63,29 +63,6 @@ export const focusWidget = ( payload: { widgetId }, }); -export const selectWidget = ( - widgetId?: string, - isMultiSelect?: boolean, -): ReduxAction<{ widgetId?: string; isMultiSelect?: boolean }> => ({ - type: ReduxActionTypes.SELECT_WIDGET, - payload: { widgetId, isMultiSelect }, -}); - -export const selectAllWidgets = ( - widgetIds?: string[], -): ReduxAction<{ widgetIds?: string[] }> => { - return { - type: ReduxActionTypes.SELECT_MULTIPLE_WIDGETS, - payload: { widgetIds }, - }; -}; - -export const selectAllWidgetsInit = () => { - return { - type: ReduxActionTypes.SELECT_MULTIPLE_WIDGETS_INIT, - }; -}; - export const showModal = (id: string) => { return { type: ReduxActionTypes.SHOW_MODAL, diff --git a/app/client/src/actions/widgetSelectionActions.ts b/app/client/src/actions/widgetSelectionActions.ts new file mode 100644 index 000000000000..730ab56ec18f --- /dev/null +++ b/app/client/src/actions/widgetSelectionActions.ts @@ -0,0 +1,58 @@ +import { ReduxActionTypes, ReduxAction } from "constants/ReduxActionConstants"; + +export const selectWidgetAction = ( + widgetId?: string, + isMultiSelect?: boolean, +): ReduxAction<{ widgetId?: string; isMultiSelect?: boolean }> => ({ + type: ReduxActionTypes.SELECT_WIDGET, + payload: { widgetId, isMultiSelect }, +}); + +export const selectWidgetInitAction = ( + widgetId?: string, + isMultiSelect?: boolean, +): ReduxAction<{ widgetId?: string; isMultiSelect?: boolean }> => ({ + type: ReduxActionTypes.SELECT_WIDGET_INIT, + payload: { widgetId, isMultiSelect }, +}); + +export const selectAllWidgetsAction = ( + widgetIds?: string[], +): ReduxAction<{ widgetIds?: string[] }> => { + return { + type: ReduxActionTypes.SELECT_MULTIPLE_WIDGETS, + payload: { widgetIds }, + }; +}; + +export const selectMultipleWidgetsAction = ( + widgetIds?: string[], +): ReduxAction<{ widgetIds?: string[] }> => { + return { + type: ReduxActionTypes.SELECT_WIDGETS, + payload: { widgetIds }, + }; +}; + +export const deselectMultipleWidgetsAction = ( + widgetIds?: string[], +): ReduxAction<{ widgetIds?: string[] }> => { + return { + type: ReduxActionTypes.DESELECT_WIDGETS, + payload: { widgetIds }, + }; +}; + +export const selectAllWidgetsInitAction = () => { + return { + type: ReduxActionTypes.SELECT_MULTIPLE_WIDGETS_INIT, + }; +}; + +export const shiftSelectWidgetsEntityExplorerInitAction = ( + widgetId: string, + siblingWidgets: string[], +): ReduxAction<{ widgetId: string; siblingWidgets: string[] }> => ({ + type: ReduxActionTypes.SHIFT_SELECT_WIDGET_INIT, + payload: { widgetId, siblingWidgets }, +}); diff --git a/app/client/src/components/designSystems/appsmith/ContainerComponent.tsx b/app/client/src/components/designSystems/appsmith/ContainerComponent.tsx index d4c5116bd48d..ea0be6d3aeff 100644 --- a/app/client/src/components/designSystems/appsmith/ContainerComponent.tsx +++ b/app/client/src/components/designSystems/appsmith/ContainerComponent.tsx @@ -2,7 +2,7 @@ import React, { ReactNode, useRef, useEffect, RefObject } from "react"; import styled, { css } from "styled-components"; import tinycolor from "tinycolor2"; import { ComponentProps } from "./BaseComponent"; -import { getBorderCSSShorthand, invisible } from "constants/DefaultTheme"; +import { invisible } from "constants/DefaultTheme"; import { Color } from "constants/Colors"; import { generateClassName, getCanvasClassName } from "utils/generators"; @@ -18,7 +18,7 @@ const StyledContainerComponent = styled.div< ${(props) => props.containerStyle !== "none" ? ` - border: ${getBorderCSSShorthand(props.theme.borders[2])}; + box-shadow: 0px 0px 0px 1px #E7E7E7; border-radius: 0;` : ""} height: 100%; diff --git a/app/client/src/components/designSystems/appsmith/PositionedContainer.tsx b/app/client/src/components/designSystems/appsmith/PositionedContainer.tsx index 8f4342ca91ba..3520d793edcc 100644 --- a/app/client/src/components/designSystems/appsmith/PositionedContainer.tsx +++ b/app/client/src/components/designSystems/appsmith/PositionedContainer.tsx @@ -7,8 +7,11 @@ import { useClickOpenPropPane } from "utils/hooks/useClickOpenPropPane"; import { stopEventPropagation } from "utils/AppsmithUtils"; import { Layers } from "constants/Layers"; -const PositionedWidget = styled.div``; - +const PositionedWidget = styled.div` + &:hover { + z-index: ${Layers.positionedWidget + 1} !important; + } +`; type PositionedContainerProps = { style: BaseStyle; children: ReactNode; @@ -24,7 +27,6 @@ export function PositionedContainer(props: PositionedContainerProps) { const y = props.style.yPosition + (props.style.yPositionUnit || "px"); const padding = WIDGET_PADDING; const openPropertyPane = useClickOpenPropPane(); - // memoized classname const containerClassName = useMemo(() => { return ( diff --git a/app/client/src/components/designSystems/appsmith/TabsComponent.tsx b/app/client/src/components/designSystems/appsmith/TabsComponent.tsx index db529b820ca0..06c79f905b98 100644 --- a/app/client/src/components/designSystems/appsmith/TabsComponent.tsx +++ b/app/client/src/components/designSystems/appsmith/TabsComponent.tsx @@ -6,7 +6,6 @@ import { TabContainerWidgetProps, } from "widgets/Tabs/TabsWidget"; import { generateClassName, getCanvasClassName } from "utils/generators"; -import { getBorderCSSShorthand } from "constants/DefaultTheme"; import ScrollIndicator from "components/ads/ScrollIndicator"; interface TabsComponentProps extends ComponentProps { @@ -37,9 +36,8 @@ const TabsContainerWrapper = styled.div<{ width: 100%; justify-content: center; align-items: center; - border: ${(props) => getBorderCSSShorthand(props.theme.borders[2])}; + box-shadow: 0px 0px 0px 1px #e7e7e7; border-radius: 0; - box-shadow: none; overflow: hidden; `; diff --git a/app/client/src/components/editorComponents/Debugger/DebuggerTabs.tsx b/app/client/src/components/editorComponents/Debugger/DebuggerTabs.tsx index 03a260a9c5ac..a541ee2cbba9 100644 --- a/app/client/src/components/editorComponents/Debugger/DebuggerTabs.tsx +++ b/app/client/src/components/editorComponents/Debugger/DebuggerTabs.tsx @@ -15,6 +15,7 @@ import { DEBUGGER_LOGS, INSPECT_ENTITY, } from "constants/messages"; +import { stopEventPropagation } from "utils/AppsmithUtils"; const TABS_HEADER_HEIGHT = 36; @@ -77,7 +78,7 @@ function DebuggerTabs(props: DebuggerTabsProps) { const onClose = () => dispatch(showDebugger(false)); return ( - <Container ref={panelRef}> + <Container onClick={stopEventPropagation} ref={panelRef}> <Resizer panelRef={panelRef} /> <TabComponent onSelect={onTabSelect} diff --git a/app/client/src/components/editorComponents/Debugger/EntityLink.tsx b/app/client/src/components/editorComponents/Debugger/EntityLink.tsx index e93197787a1b..b51e4208d108 100644 --- a/app/client/src/components/editorComponents/Debugger/EntityLink.tsx +++ b/app/client/src/components/editorComponents/Debugger/EntityLink.tsx @@ -2,7 +2,7 @@ import { DATA_SOURCES_EDITOR_ID_URL } from "constants/routes"; import { PluginType } from "entities/Action"; import { ENTITY_TYPE, SourceEntity } from "entities/AppsmithConsole"; import { getActionConfig } from "pages/Editor/Explorer/Actions/helpers"; -import { useNavigateToWidget } from "pages/Editor/Explorer/Widgets/WidgetEntity"; +import { useNavigateToWidget } from "pages/Editor/Explorer/Widgets/useNavigateToWidget"; import React, { useCallback } from "react"; import { useSelector } from "react-redux"; import { AppState } from "reducers"; @@ -71,7 +71,7 @@ function WidgetLink(props: EntityLinkProps) { AnalyticsUtil.logEvent("DEBUGGER_ENTITY_NAVIGATION", { entityType: "WIDGET", }); - }, []); + }, [navigateToWidget]); return ( <Link diff --git a/app/client/src/components/editorComponents/Debugger/hooks.ts b/app/client/src/components/editorComponents/Debugger/hooks.ts index aca5c9f5789c..e6aad46e7614 100644 --- a/app/client/src/components/editorComponents/Debugger/hooks.ts +++ b/app/client/src/components/editorComponents/Debugger/hooks.ts @@ -4,7 +4,7 @@ import { useParams } from "react-router"; import { ENTITY_TYPE, Message } from "entities/AppsmithConsole"; import { AppState } from "reducers"; import { getActionConfig } from "pages/Editor/Explorer/Actions/helpers"; -import { useNavigateToWidget } from "pages/Editor/Explorer/Widgets/WidgetEntity"; +import { useNavigateToWidget } from "pages/Editor/Explorer/Widgets/useNavigateToWidget"; import { getWidget } from "sagas/selectors"; import { getDataTree } from "selectors/dataTreeSelectors"; import { diff --git a/app/client/src/components/editorComponents/Debugger/index.tsx b/app/client/src/components/editorComponents/Debugger/index.tsx index 3a7ceb08fa85..86d987f91418 100644 --- a/app/client/src/components/editorComponents/Debugger/index.tsx +++ b/app/client/src/components/editorComponents/Debugger/index.tsx @@ -11,6 +11,7 @@ import AnalyticsUtil from "utils/AnalyticsUtil"; import { Colors } from "constants/Colors"; import { getTypographyByKey } from "constants/DefaultTheme"; import { Layers } from "constants/Layers"; +import { stopEventPropagation } from "utils/AppsmithUtils"; const Container = styled.div<{ errorCount: number }>` z-index: ${Layers.debugger}; @@ -61,11 +62,12 @@ function Debugger() { (state: AppState) => state.ui.debugger.isOpen, ); - const onClick = () => { + const onClick = (e: any) => { AnalyticsUtil.logEvent("OPEN_DEBUGGER", { source: "CANVAS", }); dispatch(showDebuggerAction(true)); + stopEventPropagation(e); }; if (!showDebugger) diff --git a/app/client/src/components/editorComponents/DragLayerComponent.tsx b/app/client/src/components/editorComponents/DragLayerComponent.tsx index a4c82fa59e4f..a26bae3b0216 100644 --- a/app/client/src/components/editorComponents/DragLayerComponent.tsx +++ b/app/client/src/components/editorComponents/DragLayerComponent.tsx @@ -4,11 +4,14 @@ import { useDragLayer, XYCoord } from "react-dnd"; import DropZone from "./Dropzone"; import { noCollision, currentDropRow } from "utils/WidgetPropsUtils"; import { OccupiedSpace } from "constants/editorConstants"; -import { CONTAINER_GRID_PADDING } from "constants/WidgetConstants"; +import { + CONTAINER_GRID_PADDING, + GridDefaults, +} from "constants/WidgetConstants"; import { DropTargetContext } from "./DropTargetComponent"; import { scrollElementIntoParentCanvasView } from "utils/helpers"; import { getNearestParentCanvas } from "utils/generators"; - +const GRID_POINT_SIZE = 1; const WrappedDragLayer = styled.div<{ columnWidth: number; rowHeight: number; @@ -17,23 +20,28 @@ const WrappedDragLayer = styled.div<{ }>` position: absolute; pointer-events: none; - left: ${(props) => (props.noPad ? "0" : `${CONTAINER_GRID_PADDING}px;`)}; - top: ${(props) => (props.noPad ? "0" : `${CONTAINER_GRID_PADDING}px;`)}; + left: ${(props) => + props.noPad ? "0" : `${CONTAINER_GRID_PADDING - GRID_POINT_SIZE}px;`}; + top: ${(props) => + props.noPad ? "0" : `${CONTAINER_GRID_PADDING - GRID_POINT_SIZE}px;`}; height: ${(props) => - props.noPad ? `100%` : `calc(100% - ${CONTAINER_GRID_PADDING}px)`}; + props.noPad + ? `100%` + : `calc(100% - ${(CONTAINER_GRID_PADDING - GRID_POINT_SIZE) * 2}px)`}; width: ${(props) => - props.noPad ? `100%` : `calc(100% - ${CONTAINER_GRID_PADDING}px)`}; + props.noPad + ? `100%` + : `calc(100% - ${(CONTAINER_GRID_PADDING - GRID_POINT_SIZE) * 2}px)`}; background-image: radial-gradient( - circle, - ${(props) => props.theme.colors.grid} 1px, + circle at ${GRID_POINT_SIZE}px ${GRID_POINT_SIZE}px, + ${(props) => props.theme.colors.grid} ${GRID_POINT_SIZE}px, transparent 0 ); - background-size: ${(props) => props.columnWidth}px - ${(props) => props.rowHeight}px; - background-position: -${(props) => props.columnWidth / 2 - 3.5}px -${( - props, - ) => props.rowHeight / 2 - 1.5}px; + background-size: ${(props) => + props.columnWidth - GRID_POINT_SIZE / GridDefaults.DEFAULT_GRID_COLUMNS}px + ${(props) => + props.rowHeight - GRID_POINT_SIZE / GridDefaults.DEFAULT_GRID_COLUMNS}px; `; type DragLayerProps = { diff --git a/app/client/src/components/editorComponents/DraggableComponent.tsx b/app/client/src/components/editorComponents/DraggableComponent.tsx index 62111a81fe23..19f0b04e9bd3 100644 --- a/app/client/src/components/editorComponents/DraggableComponent.tsx +++ b/app/client/src/components/editorComponents/DraggableComponent.tsx @@ -7,12 +7,12 @@ import { useSelector } from "react-redux"; import { AppState } from "reducers"; import { getColorWithOpacity } from "constants/DefaultTheme"; import { - useWidgetSelection, useShowPropertyPane, useWidgetDragResize, } from "utils/hooks/dragResizeHooks"; import AnalyticsUtil from "utils/AnalyticsUtil"; import { commentModeSelector } from "selectors/commentsSelectors"; +import { useWidgetSelection } from "utils/hooks/useWidgetSelection"; const DraggableWrapper = styled.div` display: block; diff --git a/app/client/src/components/editorComponents/DropTargetComponent.tsx b/app/client/src/components/editorComponents/DropTargetComponent.tsx index 631cf4f8a18b..e62988f78879 100644 --- a/app/client/src/components/editorComponents/DropTargetComponent.tsx +++ b/app/client/src/components/editorComponents/DropTargetComponent.tsx @@ -28,10 +28,10 @@ import { AppState } from "reducers"; import { useSelector } from "react-redux"; import { useShowPropertyPane, - useWidgetSelection, useCanvasSnapRowsUpdateHook, } from "utils/hooks/dragResizeHooks"; import { getOccupiedSpaces } from "selectors/editorSelectors"; +import { useWidgetSelection } from "utils/hooks/useWidgetSelection"; type DropTargetComponentProps = WidgetProps & { children?: ReactNode; @@ -250,13 +250,12 @@ export function DropTargetComponent(props: DropTargetComponentProps) { ? `${Math.max(rows * props.snapRowSpace, props.minHeight)}px` : "100%"; - const border = + const boxShadow = (isResizing || isDragging) && isExactlyOver && props.widgetId === MAIN_CONTAINER_WIDGET_ID - ? "1px solid #DDDDDD" - : "1px solid transparent"; - + ? "0px 0px 0px 1px #DDDDDD" + : "0px 0px 0px 1px transparent"; const dropRef = !props.dropDisabled ? drop : undefined; return ( @@ -269,7 +268,7 @@ export function DropTargetComponent(props: DropTargetComponentProps) { ref={dropRef} style={{ height, - border, + boxShadow, }} > {props.children} diff --git a/app/client/src/components/editorComponents/GlobalSearch/index.tsx b/app/client/src/components/editorComponents/GlobalSearch/index.tsx index ec1c11cc97ec..04a2f21771db 100644 --- a/app/client/src/components/editorComponents/GlobalSearch/index.tsx +++ b/app/client/src/components/editorComponents/GlobalSearch/index.tsx @@ -20,7 +20,7 @@ import SearchContext from "./GlobalSearchContext"; import Description from "./Description"; import ResultsNotFound from "./ResultsNotFound"; import { getActions, getAllPageWidgets } from "selectors/entitiesSelector"; -import { useNavigateToWidget } from "pages/Editor/Explorer/Widgets/WidgetEntity"; +import { useNavigateToWidget } from "pages/Editor/Explorer/Widgets/useNavigateToWidget"; import { toggleShowGlobalSearchModal, setGlobalSearchQuery, diff --git a/app/client/src/components/editorComponents/ResizableComponent.tsx b/app/client/src/components/editorComponents/ResizableComponent.tsx index 41763f349a41..7ae580853865 100644 --- a/app/client/src/components/editorComponents/ResizableComponent.tsx +++ b/app/client/src/components/editorComponents/ResizableComponent.tsx @@ -16,7 +16,6 @@ import { } from "./ResizableUtils"; import { useShowPropertyPane, - useWidgetSelection, useWidgetDragResize, } from "utils/hooks/dragResizeHooks"; import { useSelector } from "react-redux"; @@ -39,6 +38,7 @@ import { scrollElementIntoParentCanvasView } from "utils/helpers"; import { getNearestParentCanvas } from "utils/generators"; import { getOccupiedSpaces } from "selectors/editorSelectors"; import { commentModeSelector } from "selectors/commentsSelectors"; +import { useWidgetSelection } from "utils/hooks/useWidgetSelection"; export type ResizableComponentProps = WidgetProps & { paddingOffset: number; diff --git a/app/client/src/components/editorComponents/WidgetNameComponent/index.tsx b/app/client/src/components/editorComponents/WidgetNameComponent/index.tsx index c4e1d5473c38..d53981b0f315 100644 --- a/app/client/src/components/editorComponents/WidgetNameComponent/index.tsx +++ b/app/client/src/components/editorComponents/WidgetNameComponent/index.tsx @@ -4,15 +4,13 @@ import { useSelector } from "react-redux"; import { AppState } from "reducers"; import { PropertyPaneReduxState } from "reducers/uiReducers/propertyPaneReducer"; import SettingsControl, { Activities } from "./SettingsControl"; -import { - useShowPropertyPane, - useWidgetSelection, -} from "utils/hooks/dragResizeHooks"; +import { useShowPropertyPane } from "utils/hooks/dragResizeHooks"; import AnalyticsUtil from "utils/AnalyticsUtil"; import { WidgetType, WidgetTypes } from "constants/WidgetConstants"; import PerformanceTracker, { PerformanceTransactionName, } from "utils/PerformanceTracker"; +import { useWidgetSelection } from "utils/hooks/useWidgetSelection"; const PositionStyle = styled.div<{ topRow: number }>` position: absolute; diff --git a/app/client/src/constants/DefaultTheme.tsx b/app/client/src/constants/DefaultTheme.tsx index 139b66eb84cf..f647e9200be0 100644 --- a/app/client/src/constants/DefaultTheme.tsx +++ b/app/client/src/constants/DefaultTheme.tsx @@ -318,7 +318,7 @@ export type Theme = { smallHeaderHeight: string; homePage: any; sidebarWidth: string; - canvasPadding: string; + canvasBottomPadding: number; sideNav: { minWidth: number; maxWidth: number; @@ -2334,7 +2334,7 @@ export const theme: Theme = { }, headerHeight: "48px", smallHeaderHeight: "35px", - canvasPadding: "0 0 200px 0", + canvasBottomPadding: 200, sideNav: { maxWidth: 220, minWidth: 50, diff --git a/app/client/src/constants/ReduxActionConstants.tsx b/app/client/src/constants/ReduxActionConstants.tsx index 06cf80a08491..68c65a9f79a1 100644 --- a/app/client/src/constants/ReduxActionConstants.tsx +++ b/app/client/src/constants/ReduxActionConstants.tsx @@ -92,6 +92,8 @@ export const ReduxActionTypes: { [key: string]: string } = { LOAD_WIDGET_PANE: "LOAD_WIDGET_PANE", ZOOM_IN_CANVAS: "ZOOM_IN_CANVAS", ZOOM_OUT_CANVAS: "ZOOM_OUT_CANVAS", + START_CANVAS_SELECTION: "START_CANVAS_SELECTION", + STOP_CANVAS_SELECTION: "STOP_CANVAS_SELECTION", UNDO_CANVAS_ACTION: "UNDO_CANVAS_ACTION", REDO_CANVAS_ACTION: "REDO_CANVAS_ACTION", LOAD_WIDGET_CONFIG: "LOAD_WIDGET_CONFIG", @@ -288,9 +290,13 @@ export const ReduxActionTypes: { [key: string]: string } = { INVITED_USER_SIGNUP_SUCCESS: "INVITED_USER_SIGNUP_SUCCESS", INVITED_USER_SIGNUP_INIT: "INVITED_USER_SIGNUP_INIT", DISABLE_WIDGET_DRAG: "DISABLE_WIDGET_DRAG", + SELECT_WIDGET_INIT: "SELECT_WIDGET_INIT", + SHIFT_SELECT_WIDGET_INIT: "SHIFT_SELECT_WIDGET_INIT", SELECT_WIDGET: "SELECT_WIDGET", SELECT_MULTIPLE_WIDGETS: "SELECT_MULTIPLE_WIDGETS", SELECT_MULTIPLE_WIDGETS_INIT: "SELECT_MULTIPLE_WIDGETS_INIT", + DESELECT_WIDGETS: "DESELECT_WIDGETS", + SELECT_WIDGETS: "SELECT_WIDGETS", FOCUS_WIDGET: "FOCUS_WIDGET", SET_WIDGET_DRAGGING: "SET_WIDGET_DRAGGING", SET_WIDGET_RESIZING: "SET_WIDGET_RESIZING", @@ -434,6 +440,7 @@ export const ReduxActionTypes: { [key: string]: string } = { RESET_UNREAD_RELEASES_COUNT: "RESET_UNREAD_RELEASES_COUNT", SET_LOADING_ENTITIES: "SET_LOADING_ENTITIES", RESET_CURRENT_APPLICATION: "RESET_CURRENT_APPLICATION", + SELECT_WIDGETS_IN_AREA: "SELECT_WIDGETS_IN_AREA", RESET_APPLICATION_WIDGET_STATE_REQUEST: "RESET_APPLICATION_WIDGET_STATE_REQUEST", SAAS_GET_OAUTH_ACCESS_TOKEN: "SAAS_GET_OAUTH_ACCESS_TOKEN", diff --git a/app/client/src/constants/WidgetConstants.tsx b/app/client/src/constants/WidgetConstants.tsx index d3f23f17a8d3..aa461eec73db 100644 --- a/app/client/src/constants/WidgetConstants.tsx +++ b/app/client/src/constants/WidgetConstants.tsx @@ -107,11 +107,12 @@ export const GridDefaults = { CANVAS_EXTENSION_OFFSET: 2, }; -// calculated as (GridDefaults.DEFAULT_GRID_ROW_HEIGHT / 2) * 0.8; +// Note: Widget Padding + Container Padding === DEFAULT_GRID_ROW_HEIGHT to gracefully lose one row when a container is used, +// which wud allow the user to place elements centered inside a container(columns are rendered proportionaly so it take cares of itselves). + export const CONTAINER_GRID_PADDING = - GridDefaults.DEFAULT_GRID_ROW_HEIGHT * 0.4; + GridDefaults.DEFAULT_GRID_ROW_HEIGHT * 0.6; -// calculated as (GridDefaults.DEFAULT_GRID_ROW_HEIGHT / 0.5) * 0.2; export const WIDGET_PADDING = GridDefaults.DEFAULT_GRID_ROW_HEIGHT * 0.4; export const WIDGET_CLASSNAME_PREFIX = "WIDGET_"; diff --git a/app/client/src/pages/Editor/Canvas.tsx b/app/client/src/pages/Editor/Canvas.tsx index f1bb5c20da5e..8ac942be689e 100644 --- a/app/client/src/pages/Editor/Canvas.tsx +++ b/app/client/src/pages/Editor/Canvas.tsx @@ -19,6 +19,7 @@ const Canvas = memo((props: CanvasProps) => { <ArtBoard className="t--canvas-artboard" data-testid="t--canvas-artboard" + id="art-board" width={props.dsl.rightColumn} > {props.dsl.widgetId && diff --git a/app/client/src/pages/Editor/Explorer/Entity/CollapseToggle.tsx b/app/client/src/pages/Editor/Explorer/Entity/CollapseToggle.tsx index 4184636cfbc2..dfa4db366e7a 100644 --- a/app/client/src/pages/Editor/Explorer/Entity/CollapseToggle.tsx +++ b/app/client/src/pages/Editor/Explorer/Entity/CollapseToggle.tsx @@ -6,12 +6,12 @@ import { Colors } from "constants/Colors"; export function CollapseToggle(props: { isOpen: boolean; isVisible: boolean; - onClick: () => void; + onClick: (e: any) => void; disabled: boolean; className: string; }) { const handleClick = (e: any) => { - props.onClick(); + props.onClick(e); e.stopPropagation(); }; const icon: IconName = props.isOpen diff --git a/app/client/src/pages/Editor/Explorer/Entity/index.tsx b/app/client/src/pages/Editor/Explorer/Entity/index.tsx index 508daf07606d..e64bba16044a 100644 --- a/app/client/src/pages/Editor/Explorer/Entity/index.tsx +++ b/app/client/src/pages/Editor/Explorer/Entity/index.tsx @@ -35,9 +35,13 @@ export const EntityItem = styled.div<{ active: boolean; step: number; spaced: boolean; + highlight: boolean; }>` position: relative; + border-top: ${(props) => (props.highlight ? "1px solid #e7e7e7" : "none")}; + border-bottom: ${(props) => (props.highlight ? "1px solid #e7e7e7" : "none")}; font-size: 12px; + user-select: none; padding-left: ${(props) => props.step * props.theme.spaces[2] + props.theme.spaces[2]}px; background: ${(props) => (props.active ? Colors.TUNDORA : "none")}; @@ -91,10 +95,11 @@ export type EntityProps = { className?: string; name: string; children?: ReactNode; + highlight?: boolean; icon: ReactNode; rightIcon?: ReactNode; disabled?: boolean; - action?: () => void; + action?: (e: any) => void; active?: boolean; isDefaultExpanded?: boolean; onCreate?: () => void; @@ -127,11 +132,11 @@ export const Entity = forwardRef( }, [props.searchKeyword]); /* eslint-enable react-hooks/exhaustive-deps */ - const toggleChildren = () => { + const toggleChildren = (e: any) => { // Make sure this entity is enabled before toggling the collpse of children. !props.disabled && open(!isOpen); if (props.runActionOnExpand && !isOpen) { - props.action && props.action(); + props.action && props.action(e); } if (props.onToggle) { @@ -145,9 +150,9 @@ export const Entity = forwardRef( ); }; - const handleClick = () => { - if (props.action) props.action(); - else toggleChildren(); + const handleClick = (e: any) => { + if (props.action) props.action(e); + else toggleChildren(e); }; const itemRef = useRef<HTMLDivElement | null>(null); @@ -161,6 +166,10 @@ export const Entity = forwardRef( > <EntityItem active={!!props.active} + className={`${props.highlight ? "highlighted" : ""} ${ + props.active ? "active" : "" + }`} + highlight={!!props.highlight} spaced={!!props.children} step={props.step} > diff --git a/app/client/src/pages/Editor/Explorer/EntityExplorer.test.tsx b/app/client/src/pages/Editor/Explorer/EntityExplorer.test.tsx new file mode 100644 index 000000000000..d6ba906d44f4 --- /dev/null +++ b/app/client/src/pages/Editor/Explorer/EntityExplorer.test.tsx @@ -0,0 +1,229 @@ +import { act, fireEvent, render } from "test/testUtils"; +import { + buildChildren, + widgetCanvasFactory, +} from "test/factories/WidgetFactoryUtils"; +import React from "react"; +import { MockPageDSL } from "test/testCommon"; +import Sidebar from "components/editorComponents/Sidebar"; +import { generateReactKey } from "utils/generators"; +jest.useFakeTimers(); +describe("Entity Explorer tests", () => { + it("Should render Widgets tree in entity explorer", () => { + const children: any = buildChildren([{ type: "TABS_WIDGET" }]); + const dsl: any = widgetCanvasFactory.build({ + children, + }); + const component = render( + <MockPageDSL dsl={dsl}> + <Sidebar /> + </MockPageDSL>, + ); + const widgetsTree: any = component.queryByText("Widgets"); + act(() => { + fireEvent.click(widgetsTree); + jest.runAllTimers(); + }); + const tabsWidget = component.queryByText(children[0].widgetName); + expect(tabsWidget).toBeTruthy(); + }); + + it("Select widget on entity explorer", () => { + const children: any = buildChildren([{ type: "TABS_WIDGET" }]); + const dsl: any = widgetCanvasFactory.build({ + children, + }); + const component = render( + <MockPageDSL dsl={dsl}> + <Sidebar /> + </MockPageDSL>, + ); + const widgetsTree: any = component.queryByText("Widgets"); + act(() => { + fireEvent.click(widgetsTree); + jest.runAllTimers(); + }); + const tabsWidget: any = component.queryByText(children[0].widgetName); + act(() => { + fireEvent.click(tabsWidget); + jest.runAllTimers(); + }); + const highlighted = component.container.getElementsByClassName( + "highlighted active", + ); + expect(highlighted.length).toBe(1); + }); + + it("CMD + click Multi Select widget on entity explorer", () => { + const children: any = buildChildren([ + { type: "CHECKBOX_WIDGET", parentId: "0" }, + { type: "SWITCH_WIDGET", parentId: "0" }, + ]); + const dsl: any = widgetCanvasFactory.build({ + children, + }); + const component = render( + <MockPageDSL dsl={dsl}> + <Sidebar /> + </MockPageDSL>, + ); + const widgetsTree: any = component.queryByText("Widgets"); + act(() => { + fireEvent.click(widgetsTree); + jest.runAllTimers(); + }); + const checkBox: any = component.queryByText(children[0].widgetName); + act(() => { + fireEvent.click(checkBox); + jest.runAllTimers(); + }); + const switchWidget: any = component.queryByText(children[1].widgetName); + + act(() => { + fireEvent.click(switchWidget, { + ctrlKey: true, + }); + jest.runAllTimers(); + }); + const highlighted = component.container.querySelectorAll( + "div.widget > .highlighted.active", + ); + const active = component.container.querySelectorAll("div.widget > .active"); + expect(highlighted.length).toBe(1); + expect(active.length).toBe(2); + }); + + it("Shift + Click Multi Select widget on entity explorer", () => { + const children: any = buildChildren([ + { type: "CHECKBOX_WIDGET", parentId: "0" }, + { type: "SWITCH_WIDGET", parentId: "0" }, + { type: "BUTTON_WIDGET", parentId: "0" }, + ]); + const dsl: any = widgetCanvasFactory.build({ + children, + }); + const component = render( + <MockPageDSL dsl={dsl}> + <Sidebar /> + </MockPageDSL>, + ); + const widgetsTree: any = component.queryByText("Widgets"); + act(() => { + fireEvent.click(widgetsTree); + jest.runAllTimers(); + }); + const buttonWidget: any = component.queryByText(children[2].widgetName); + + act(() => { + fireEvent.click(buttonWidget, { + shiftKey: true, + }); + jest.runAllTimers(); + }); + const highlighted = component.container.querySelectorAll( + "div.widget > .highlighted.active", + ); + const active = component.container.querySelectorAll("div.widget > .active"); + expect(highlighted.length).toBe(1); + expect(active.length).toBe(3); + }); + + it("Shift + Click Deselect Non Siblings", () => { + 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", + }, + { type: "CHART_WIDGET" }, + ]); + const dsl: any = widgetCanvasFactory.build({ + children: containerChildren, + }); + const component = render( + <MockPageDSL dsl={dsl}> + <Sidebar /> + </MockPageDSL>, + ); + const widgetsTree: any = component.queryByText("Widgets"); + act(() => { + fireEvent.click(widgetsTree); + jest.runAllTimers(); + }); + const containerWidget: any = component.queryByText( + containerChildren[0].widgetName, + ); + + act(() => { + fireEvent.click(containerWidget); + jest.runAllTimers(); + }); + let highlighted = component.container.querySelectorAll( + "div.widget > .highlighted.active", + ); + let active = component.container.querySelectorAll("div.widget > .active"); + expect(highlighted.length).toBe(1); + expect(active.length).toBe(1); + const collapsible: any = active[0].parentElement?.querySelector( + ".bp3-icon.bp3-icon-caret-right", + ); + fireEvent.click(collapsible); + const buttonWidget: any = component.queryByText(children[2].widgetName); + act(() => { + fireEvent.click(buttonWidget, { + shiftKey: true, + }); + jest.runAllTimers(); + }); + highlighted = component.container.querySelectorAll( + "div.widget > .highlighted.active", + ); + active = component.container.querySelectorAll("div.widget > .active"); + expect(highlighted.length).toBe(1); + expect(active.length).toBe(1); + const checkBoxWidget: any = component.queryByText(children[0].widgetName); + act(() => { + fireEvent.click(checkBoxWidget, { + shiftKey: true, + }); + jest.runAllTimers(); + }); + highlighted = component.container.querySelectorAll( + "div.widget > .highlighted.active", + ); + active = component.container.querySelectorAll("div.widget > .active"); + expect(highlighted.length).toBe(1); + expect(active.length).toBe(3); + const chartWidget: any = component.queryByText( + containerChildren[1].widgetName, + ); + act(() => { + fireEvent.click(chartWidget, { + shiftKey: true, + }); + jest.runAllTimers(); + }); + highlighted = component.container.querySelectorAll( + "div.widget > .highlighted.active", + ); + active = component.container.querySelectorAll("div.widget > .active"); + expect(highlighted.length).toBe(1); + expect(active.length).toBe(1); + }); +}); diff --git a/app/client/src/pages/Editor/Explorer/Widgets/WidgetEntity.tsx b/app/client/src/pages/Editor/Explorer/Widgets/WidgetEntity.tsx index 4c959e173cdf..a94ebaf13be0 100644 --- a/app/client/src/pages/Editor/Explorer/Widgets/WidgetEntity.tsx +++ b/app/client/src/pages/Editor/Explorer/Widgets/WidgetEntity.tsx @@ -4,16 +4,7 @@ import { WidgetProps } from "widgets/BaseWidget"; import { WidgetTypes, WidgetType } from "constants/WidgetConstants"; import { useParams } from "react-router"; import { ExplorerURLParams } from "../helpers"; -import { BUILDER_PAGE_URL } from "constants/routes"; -import history from "utils/history"; -import { flashElementById } from "utils/helpers"; -import { useDispatch, useSelector } from "react-redux"; -import { - forceOpenPropertyPane, - showModal, - closeAllModals, -} from "actions/widgetActions"; -import { useWidgetSelection } from "utils/hooks/dragResizeHooks"; +import { useSelector } from "react-redux"; import { AppState } from "reducers"; import { getWidgetIcon } from "../ExplorerIcons"; @@ -23,85 +14,63 @@ import { ENTITY_TYPE } from "entities/DataTree/dataTreeFactory"; import EntityProperties from "../Entity/EntityProperties"; import { CanvasStructure } from "reducers/uiReducers/pageCanvasStructureReducer"; import CurrentPageEntityProperties from "../Entity/CurrentPageEntityProperties"; +import { getSelectedWidget, getSelectedWidgets } from "selectors/ui"; +import { useNavigateToWidget } from "./useNavigateToWidget"; export type WidgetTree = WidgetProps & { children?: WidgetTree[] }; const UNREGISTERED_WIDGETS: WidgetType[] = [WidgetTypes.ICON_WIDGET]; -export const navigateToCanvas = ( - params: ExplorerURLParams, - currentPath: string, - widgetPageId: string, - widgetId: string, -) => { - const canvasEditorURL = `${BUILDER_PAGE_URL( - params.applicationId, - widgetPageId, - )}`; - if (currentPath !== canvasEditorURL) { - history.push(`${canvasEditorURL}#${widgetId}`); - } -}; - -export const useNavigateToWidget = () => { - const params = useParams<ExplorerURLParams>(); - const dispatch = useDispatch(); - const { selectWidget } = useWidgetSelection(); - - const navigateToWidget = useCallback( - ( - widgetId: string, - widgetType: WidgetType, - pageId: string, - isWidgetSelected?: boolean, - parentModalId?: string, - ) => { - if (widgetType === WidgetTypes.MODAL_WIDGET) { - dispatch(showModal(widgetId)); - return; - } - if (parentModalId) dispatch(showModal(parentModalId)); - else dispatch(closeAllModals()); - navigateToCanvas(params, window.location.pathname, pageId, widgetId); - flashElementById(widgetId); - if (!isWidgetSelected) selectWidget(widgetId); - dispatch(forceOpenPropertyPane(widgetId)); - }, - [dispatch, params, selectWidget], - ); - - return { navigateToWidget }; -}; - const useWidget = ( widgetId: string, widgetType: WidgetType, pageId: string, + widgetsInStep: string[], parentModalId?: string, ) => { - const selectedWidget = useSelector( - (state: AppState) => state.ui.widgetDragResize.lastSelectedWidget, + const selectedWidgets = useSelector(getSelectedWidgets); + const lastSelectedWidget = useSelector(getSelectedWidget); + const isWidgetSelected = useMemo( + () => selectedWidgets && selectedWidgets.includes(widgetId), + [selectedWidgets, widgetId], ); - const isWidgetSelected = useMemo(() => selectedWidget === widgetId, [ - selectedWidget, - widgetId, - ]); + + const multipleWidgetsSelected = selectedWidgets && selectedWidgets.length > 1; const { navigateToWidget } = useNavigateToWidget(); const boundNavigateToWidget = useCallback( - () => + (e: any) => { + const isMultiSelect = e.metaKey || e.ctrlKey; + const isShiftSelect = e.shiftKey; navigateToWidget( widgetId, widgetType, pageId, isWidgetSelected, parentModalId, - ), - [widgetId, widgetType, pageId, isWidgetSelected, parentModalId], + isMultiSelect, + isShiftSelect, + widgetsInStep, + ); + }, + [ + widgetId, + widgetType, + pageId, + isWidgetSelected, + parentModalId, + widgetsInStep, + navigateToWidget, + ], ); - return { navigateToWidget: boundNavigateToWidget, isWidgetSelected }; + return { + navigateToWidget: boundNavigateToWidget, + isWidgetSelected, + multipleWidgetsSelected, + lastSelectedWidget, + }; }; export type WidgetEntityProps = { @@ -114,6 +83,7 @@ export type WidgetEntityProps = { parentModalId?: string; searchKeyword?: string; isDefaultExpanded?: boolean; + widgetsInStep: string[]; }; export const WidgetEntity = memo((props: WidgetEntityProps) => { @@ -123,10 +93,16 @@ export const WidgetEntity = memo((props: WidgetEntityProps) => { ); let shouldExpand = false; if (widgetsToExpand.includes(props.widgetId)) shouldExpand = true; - const { isWidgetSelected, navigateToWidget } = useWidget( + const { + isWidgetSelected, + lastSelectedWidget, + multipleWidgetsSelected, + navigateToWidget, + } = useWidget( props.widgetId, props.widgetType, props.pageId, + props.widgetsInStep, props.parentModalId, ); @@ -150,13 +126,19 @@ export const WidgetEntity = memo((props: WidgetEntityProps) => { /> ); + const showContextMenu = props.pageId === pageId && !multipleWidgetsSelected; + const widgetsInStep = props?.childWidgets + ? props?.childWidgets?.map((child) => child.widgetId) + : []; + return ( <Entity action={navigateToWidget} active={isWidgetSelected} className="widget" - contextMenu={props.pageId === pageId && contextMenu} + contextMenu={showContextMenu && contextMenu} entityId={props.widgetId} + highlight={lastSelectedWidget === props.widgetId} icon={getWidgetIcon(props.widgetType)} isDefaultExpanded={ shouldExpand || @@ -182,6 +164,7 @@ export const WidgetEntity = memo((props: WidgetEntityProps) => { widgetId={child.widgetId} widgetName={child.widgetName} widgetType={child.type} + widgetsInStep={widgetsInStep} /> ))} {!(props.childWidgets && props.childWidgets.length > 0) && diff --git a/app/client/src/pages/Editor/Explorer/Widgets/WidgetGroup.tsx b/app/client/src/pages/Editor/Explorer/Widgets/WidgetGroup.tsx index 4cd0ed234fbd..f2c5fefd47e7 100644 --- a/app/client/src/pages/Editor/Explorer/Widgets/WidgetGroup.tsx +++ b/app/client/src/pages/Editor/Explorer/Widgets/WidgetGroup.tsx @@ -9,8 +9,8 @@ import { ExplorerURLParams } from "../helpers"; import { BUILDER_PAGE_URL } from "constants/routes"; import { Link } from "react-router-dom"; import styled from "styled-components"; -import { AppState } from "reducers"; import { CanvasStructure } from "reducers/uiReducers/pageCanvasStructureReducer"; +import { getSelectedWidgets } from "selectors/ui"; type ExplorerWidgetGroupProps = { pageId: string; @@ -31,9 +31,7 @@ const StyledLink = styled(Link)` export const ExplorerWidgetGroup = memo((props: ExplorerWidgetGroupProps) => { const params = useParams<ExplorerURLParams>(); - const selectedWidget = useSelector( - (state: AppState) => state.ui.widgetDragResize.lastSelectedWidget, - ); + const selectedWidgets = useSelector(getSelectedWidgets); const childNode = ( <EntityPlaceholder step={props.step + 1}> @@ -53,6 +51,9 @@ export const ExplorerWidgetGroup = memo((props: ExplorerWidgetGroupProps) => { </EntityPlaceholder> ); + const widgetsInStep = + props.widgets?.children?.map((child) => child.widgetId) || []; + return ( <Entity className={`group widgets ${props.addWidgetsFn ? "current" : ""}`} @@ -61,7 +62,8 @@ export const ExplorerWidgetGroup = memo((props: ExplorerWidgetGroupProps) => { icon={widgetIcon} isDefaultExpanded={ !!props.searchKeyword || - (params.pageId === props.pageId && !!selectedWidget) + (params.pageId === props.pageId && + !!(selectedWidgets && selectedWidgets.length)) } key={props.pageId + "_widgets"} name="Widgets" @@ -79,6 +81,7 @@ export const ExplorerWidgetGroup = memo((props: ExplorerWidgetGroupProps) => { widgetId={child.widgetId} widgetName={child.widgetName} widgetType={child.type} + widgetsInStep={widgetsInStep} /> ))} {(!props.widgets?.children || props.widgets?.children.length === 0) && diff --git a/app/client/src/pages/Editor/Explorer/Widgets/useNavigateToWidget.ts b/app/client/src/pages/Editor/Explorer/Widgets/useNavigateToWidget.ts new file mode 100644 index 000000000000..e445204aa6da --- /dev/null +++ b/app/client/src/pages/Editor/Explorer/Widgets/useNavigateToWidget.ts @@ -0,0 +1,75 @@ +import { useCallback } from "react"; +import { WidgetTypes, WidgetType } from "constants/WidgetConstants"; +import { useParams } from "react-router"; +import { ExplorerURLParams } from "../helpers"; +import { flashElementById } from "utils/helpers"; +import { useDispatch, useSelector } from "react-redux"; +import { + forceOpenPropertyPane, + showModal, + closeAllModals, +} from "actions/widgetActions"; +import { useWidgetSelection } from "utils/hooks/useWidgetSelection"; +import { navigateToCanvas } from "./utils"; +import { getCurrentPageWidgets } from "selectors/entitiesSelector"; + +export const useNavigateToWidget = () => { + const params = useParams<ExplorerURLParams>(); + const allWidgets = useSelector(getCurrentPageWidgets); + const dispatch = useDispatch(); + const { + selectWidget, + shiftSelectWidgetEntityExplorer, + } = useWidgetSelection(); + const multiSelectWidgets = (widgetId: string, pageId: string) => { + navigateToCanvas(params, window.location.pathname, pageId, widgetId); + flashElementById(widgetId); + selectWidget(widgetId, true); + }; + + const selectSingleWidget = ( + widgetId: string, + widgetType: WidgetType, + pageId: string, + parentModalId?: string, + ) => { + if (widgetType === WidgetTypes.MODAL_WIDGET) { + dispatch(showModal(widgetId)); + return; + } + if (parentModalId) dispatch(showModal(parentModalId)); + else dispatch(closeAllModals()); + selectWidget(widgetId, false); + navigateToCanvas(params, window.location.pathname, pageId, widgetId); + flashElementById(widgetId); + dispatch(forceOpenPropertyPane(widgetId)); + }; + + const navigateToWidget = useCallback( + ( + widgetId: string, + widgetType: WidgetType, + pageId: string, + isWidgetSelected?: boolean, + parentModalId?: string, + isMultiSelect?: boolean, + isShiftSelect?: boolean, + widgetsInStep?: string[], + ) => { + // restrict multi-select across pages + if (widgetId && (isMultiSelect || isShiftSelect) && !allWidgets[widgetId]) + return; + + if (isShiftSelect) { + shiftSelectWidgetEntityExplorer(widgetId, widgetsInStep || []); + } else if (isMultiSelect) { + multiSelectWidgets(widgetId, pageId); + } else { + selectSingleWidget(widgetId, widgetType, pageId, parentModalId); + } + }, + [dispatch, params, selectWidget, allWidgets], + ); + + return { navigateToWidget }; +}; diff --git a/app/client/src/pages/Editor/Explorer/Widgets/utils.ts b/app/client/src/pages/Editor/Explorer/Widgets/utils.ts new file mode 100644 index 000000000000..a4dfd4bf4f37 --- /dev/null +++ b/app/client/src/pages/Editor/Explorer/Widgets/utils.ts @@ -0,0 +1,18 @@ +import { ExplorerURLParams } from "../helpers"; +import { BUILDER_PAGE_URL } from "constants/routes"; +import history from "utils/history"; + +export const navigateToCanvas = ( + params: ExplorerURLParams, + currentPath: string, + widgetPageId: string, + widgetId: string, +) => { + const canvasEditorURL = `${BUILDER_PAGE_URL( + params.applicationId, + widgetPageId, + )}`; + if (currentPath !== canvasEditorURL) { + history.push(`${canvasEditorURL}#${widgetId}`); + } +}; diff --git a/app/client/src/pages/Editor/GlobalHotKeys.tsx b/app/client/src/pages/Editor/GlobalHotKeys.tsx index ce374351e0c3..00dace7be351 100644 --- a/app/client/src/pages/Editor/GlobalHotKeys.tsx +++ b/app/client/src/pages/Editor/GlobalHotKeys.tsx @@ -9,9 +9,11 @@ import { cutWidget, deleteSelectedWidget, pasteWidget, - selectAllWidgetsInit, - selectAllWidgets, } from "actions/widgetActions"; +import { + selectAllWidgetsInitAction, + selectAllWidgetsAction, +} from "actions/widgetSelectionActions"; import { toggleShowGlobalSearchModal } from "actions/globalSearchActions"; import { isMac } from "utils/helpers"; import { getSelectedWidget, getSelectedWidgets } from "selectors/ui"; @@ -248,8 +250,8 @@ const mapDispatchToProps = (dispatch: any) => { resetCommentMode: () => dispatch(setCommentModeAction(false)), openDebugger: () => dispatch(showDebugger()), closeProppane: () => dispatch(closePropertyPane()), - selectAllWidgetsInit: () => dispatch(selectAllWidgetsInit()), - deselectAllWidgets: () => dispatch(selectAllWidgets([])), + selectAllWidgetsInit: () => dispatch(selectAllWidgetsInitAction()), + deselectAllWidgets: () => dispatch(selectAllWidgetsAction([])), executeAction: () => dispatch(runActionViaShortcut()), }; }; diff --git a/app/client/src/pages/Editor/PropertyPane/index.tsx b/app/client/src/pages/Editor/PropertyPane/index.tsx index b262fb0e712f..06cd443ec69c 100644 --- a/app/client/src/pages/Editor/PropertyPane/index.tsx +++ b/app/client/src/pages/Editor/PropertyPane/index.tsx @@ -28,11 +28,8 @@ import PropertyControlsGenerator from "./Generator"; import PaneWrapper from "components/editorComponents/PaneWrapper"; import { EditorTheme } from "components/editorComponents/CodeEditor/EditorConfig"; import { ThemeMode, getCurrentThemeMode } from "selectors/themeSelectors"; -import { - deleteSelectedWidget, - copyWidget, - selectWidget, -} from "actions/widgetActions"; +import { deleteSelectedWidget, copyWidget } from "actions/widgetActions"; +import { selectWidgetInitAction } from "actions/widgetSelectionActions"; import { ControlIcons } from "icons/ControlIcons"; import { FormIcons } from "icons/FormIcons"; import PropertyPaneHelpButton from "pages/Editor/PropertyPaneHelpButton"; @@ -324,7 +321,7 @@ const mapDispatchToProps = (dispatch: any): PropertyPaneFunctions => { }, }, }); - dispatch(selectWidget(widgetId)); + dispatch(selectWidgetInitAction(widgetId)); }, hidePropertyPane: () => dispatch({ diff --git a/app/client/src/pages/Editor/WidgetCard.tsx b/app/client/src/pages/Editor/WidgetCard.tsx index 12fdcbbf7612..a3fceadc750a 100644 --- a/app/client/src/pages/Editor/WidgetCard.tsx +++ b/app/client/src/pages/Editor/WidgetCard.tsx @@ -4,13 +4,11 @@ import blankImage from "assets/images/blank.png"; import { WidgetCardProps } from "widgets/BaseWidget"; import styled from "styled-components"; import { WidgetIcons } from "icons/WidgetIcons"; -import { - useWidgetDragResize, - useWidgetSelection, -} from "utils/hooks/dragResizeHooks"; +import { useWidgetDragResize } from "utils/hooks/dragResizeHooks"; import AnalyticsUtil from "utils/AnalyticsUtil"; import { generateReactKey } from "utils/generators"; import { Colors } from "constants/Colors"; +import { useWidgetSelection } from "utils/hooks/useWidgetSelection"; type CardProps = { details: WidgetCardProps; diff --git a/app/client/src/pages/Editor/WidgetsEditor.tsx b/app/client/src/pages/Editor/WidgetsEditor.tsx index 9e50109c1ee0..5886fd120611 100644 --- a/app/client/src/pages/Editor/WidgetsEditor.tsx +++ b/app/client/src/pages/Editor/WidgetsEditor.tsx @@ -11,7 +11,6 @@ import { import Centered from "components/designSystems/appsmith/CenteredWrapper"; import EditorContextProvider from "components/editorComponents/EditorContextProvider"; import { Spinner } from "@blueprintjs/core"; -import { useWidgetSelection } from "utils/hooks/dragResizeHooks"; import AnalyticsUtil from "utils/AnalyticsUtil"; import * as log from "loglevel"; import { getCanvasClassName } from "utils/generators"; @@ -26,6 +25,7 @@ import { MainContainerLayoutControl } from "./MainContainerLayoutControl"; import { useDynamicAppLayout } from "utils/hooks/useDynamicAppLayout"; import Debugger from "components/editorComponents/Debugger"; import { closePropertyPane } from "actions/widgetActions"; +import { useWidgetSelection } from "utils/hooks/useWidgetSelection"; const EditorWrapper = styled.div` display: flex; @@ -42,6 +42,7 @@ const CanvasContainer = styled.section` position: relative; overflow-x: auto; overflow-y: auto; + padding-top: 1px; &:before { position: absolute; top: 0; diff --git a/app/client/src/pages/Editor/routes.tsx b/app/client/src/pages/Editor/routes.tsx index a508661d0cff..72e0b6dc5293 100644 --- a/app/client/src/pages/Editor/routes.tsx +++ b/app/client/src/pages/Editor/routes.tsx @@ -27,10 +27,7 @@ import { getProviderTemplatesURL, } from "constants/routes"; import styled from "styled-components"; -import { - useShowPropertyPane, - useWidgetSelection, -} from "utils/hooks/dragResizeHooks"; +import { useShowPropertyPane } from "utils/hooks/dragResizeHooks"; import { closeAllModals } from "actions/widgetActions"; import { useDispatch } from "react-redux"; import PerformanceTracker, { @@ -41,6 +38,7 @@ import * as Sentry from "@sentry/react"; const SentryRoute = Sentry.withSentryRouting(Route); import { SaaSEditorRoutes } from "./SaaSEditor/routes"; +import { useWidgetSelection } from "utils/hooks/useWidgetSelection"; const Wrapper = styled.div<{ isVisible: boolean }>` position: absolute; diff --git a/app/client/src/pages/common/ArtBoard.tsx b/app/client/src/pages/common/ArtBoard.tsx index 19b9b19dde0f..351056630a20 100644 --- a/app/client/src/pages/common/ArtBoard.tsx +++ b/app/client/src/pages/common/ArtBoard.tsx @@ -6,5 +6,5 @@ export default styled.div<{ width: number }>` background: ${(props) => { return props.theme.colors.artboard; }}; - padding: ${(props) => props.theme.canvasPadding}; + padding: 0 0 ${(props) => props.theme.canvasBottomPadding}px 0px; `; diff --git a/app/client/src/pages/common/CanvasSelectionArena.test.tsx b/app/client/src/pages/common/CanvasSelectionArena.test.tsx new file mode 100644 index 000000000000..d6e43b6412a9 --- /dev/null +++ b/app/client/src/pages/common/CanvasSelectionArena.test.tsx @@ -0,0 +1,129 @@ +import { fireEvent, render } from "test/testUtils"; +import Canvas from "pages/Editor/Canvas"; +import React from "react"; +import { + buildChildren, + widgetCanvasFactory, +} from "test/factories/WidgetFactoryUtils"; +import { MockPageDSL, syntheticTestMouseEvent } from "test/testCommon"; +import { MAIN_CONTAINER_WIDGET_ID } from "constants/WidgetConstants"; + +describe("Canvas selection test cases", () => { + it("Should select using canvas draw", () => { + const children: any = buildChildren([ + { + type: "TABS_WIDGET", + topRow: 5, + bottomRow: 30, + leftColumn: 5, + rightColumn: 30, + }, + { + type: "SWITCH_WIDGET", + topRow: 5, + bottomRow: 10, + leftColumn: 40, + rightColumn: 48, + }, + ]); + const dsl: any = widgetCanvasFactory.build({ + children, + }); + const component = render( + <MockPageDSL dsl={dsl}> + <Canvas dsl={dsl} /> + </MockPageDSL>, + ); + let selectionCanvas: any = component.queryByTestId( + `canvas-${MAIN_CONTAINER_WIDGET_ID}`, + ); + expect(selectionCanvas.style.zIndex).toBe(""); + fireEvent.mouseDown(selectionCanvas); + + selectionCanvas = component.queryByTestId( + `canvas-${MAIN_CONTAINER_WIDGET_ID}`, + ); + + expect(selectionCanvas.style.zIndex).toBe("2"); + fireEvent.mouseUp(selectionCanvas); + selectionCanvas = component.queryByTestId( + `canvas-${MAIN_CONTAINER_WIDGET_ID}`, + ); + + expect(selectionCanvas.style.zIndex).toBe(""); + }); + + it("Should select all elements using canvas from top to bottom", () => { + const children: any = buildChildren([ + { + type: "TABS_WIDGET", + topRow: 1, + bottomRow: 3, + leftColumn: 1, + rightColumn: 3, + }, + { + type: "SWITCH_WIDGET", + topRow: 1, + bottomRow: 2, + leftColumn: 5, + rightColumn: 13, + }, + ]); + const dsl: any = widgetCanvasFactory.build({ + children, + }); + const component = render( + <MockPageDSL dsl={dsl}> + <Canvas dsl={dsl} /> + </MockPageDSL>, + ); + const selectionCanvas: any = component.queryByTestId( + `canvas-${MAIN_CONTAINER_WIDGET_ID}`, + ); + fireEvent( + selectionCanvas, + syntheticTestMouseEvent( + new MouseEvent("mousedown", { + bubbles: true, + cancelable: true, + }), + { + offsetX: 10, + offsetY: 10, + }, + ), + ); + fireEvent( + selectionCanvas, + syntheticTestMouseEvent( + new MouseEvent("mousemove", { + bubbles: true, + cancelable: true, + }), + { + offsetX: dsl.rightColumn * 4, + offsetY: dsl.bottomRow * 4, + }, + ), + ); + + fireEvent( + selectionCanvas, + syntheticTestMouseEvent( + new MouseEvent("mouseup", { + bubbles: true, + cancelable: true, + }), + { + offsetX: dsl.rightColumn * 4, + offsetY: dsl.bottomRow * 4, + }, + ), + ); + const selectedWidgets = component.queryAllByTestId( + "t--widget-propertypane-toggle", + ); + expect(selectedWidgets.length).toBe(2); + }); +}); diff --git a/app/client/src/pages/common/CanvasSelectionArena.tsx b/app/client/src/pages/common/CanvasSelectionArena.tsx new file mode 100644 index 000000000000..1d718a10a8ec --- /dev/null +++ b/app/client/src/pages/common/CanvasSelectionArena.tsx @@ -0,0 +1,249 @@ +import { + selectAllWidgetsInAreaAction, + setCanvasSelectionStateAction, +} from "actions/canvasSelectionActions"; +import { theme } from "constants/DefaultTheme"; +import { MAIN_CONTAINER_WIDGET_ID } from "constants/WidgetConstants"; +import { throttle } from "lodash"; +import React, { memo, useEffect, useCallback } from "react"; +import { useDispatch, useSelector } from "react-redux"; +import { AppState } from "reducers"; +import { APP_MODE } from "reducers/entityReducers/appReducer"; +import { getWidget } from "sagas/selectors"; +import { getAppMode } from "selectors/applicationSelectors"; +import { + getCurrentApplicationLayout, + getCurrentPageId, +} from "selectors/editorSelectors"; +import styled from "styled-components"; + +const StyledSelectionCanvas = styled.canvas` + position: absolute; + top: 0px; + left: 0px; + height: calc(100% + ${(props) => props.theme.canvasBottomPadding}px); + width: 100%; + overflow-y: auto; +`; + +export interface SelectedArenaDimensions { + top: number; + left: number; + width: number; + height: number; +} + +export const CanvasSelectionArena = memo( + ({ widgetId }: { widgetId: string }) => { + const dispatch = useDispatch(); + const appMode = useSelector(getAppMode); + + const mainContainer = useSelector((state: AppState) => + getWidget(state, MAIN_CONTAINER_WIDGET_ID), + ); + const currentPageId = useSelector(getCurrentPageId); + const appLayout = useSelector(getCurrentApplicationLayout); + const throttledWidgetSelection = useCallback( + throttle( + ( + selectionDimensions: SelectedArenaDimensions, + snapToNextColumn: boolean, + snapToNextRow: boolean, + isMultiSelect: boolean, + ) => { + dispatch( + selectAllWidgetsInAreaAction( + selectionDimensions, + snapToNextColumn, + snapToNextRow, + isMultiSelect, + ), + ); + }, + 150, + { + leading: true, + trailing: true, + }, + ), + [widgetId], + ); + useEffect(() => { + if (appMode === APP_MODE.EDIT) { + const selectionCanvas: any = document.getElementById( + `canvas-${widgetId}`, + ); + const canvasCtx = selectionCanvas.getContext("2d"); + const initRectangle = (): SelectedArenaDimensions => ({ + top: 0, + left: 0, + width: 0, + height: 0, + }); + let selectionRectangle: SelectedArenaDimensions = initRectangle(); + let isMultiSelect = false; + let isDragging = false; + + const init = () => { + const { height, width } = selectionCanvas.getBoundingClientRect(); + if (height && width) { + selectionCanvas.width = mainContainer.rightColumn; + selectionCanvas.height = + mainContainer.bottomRow + theme.canvasBottomPadding; + } + selectionCanvas.addEventListener("click", onClick, false); + selectionCanvas.addEventListener("mousedown", onMouseDown, false); + selectionCanvas.addEventListener("mouseup", onMouseUp, false); + selectionCanvas.addEventListener("mousemove", onMouseMove, false); + selectionCanvas.addEventListener("mouseleave", onMouseLeave, false); + selectionCanvas.addEventListener("mouseenter", onMouseEnter, false); + }; + + const getSelectionDimensions = () => { + return { + top: + selectionRectangle.height < 0 + ? selectionRectangle.top - Math.abs(selectionRectangle.height) + : selectionRectangle.top, + left: + selectionRectangle.width < 0 + ? selectionRectangle.left - Math.abs(selectionRectangle.width) + : selectionRectangle.left, + width: Math.abs(selectionRectangle.width), + height: Math.abs(selectionRectangle.height), + }; + }; + + const selectWidgetsInit = ( + selectionDimensions: SelectedArenaDimensions, + isMultiSelect: boolean, + ) => { + if ( + selectionDimensions.left && + selectionDimensions.top && + selectionDimensions.width && + selectionDimensions.height + ) { + const snapToNextColumn = selectionRectangle.height < 0; + const snapToNextRow = selectionRectangle.width < 0; + throttledWidgetSelection( + selectionDimensions, + snapToNextColumn, + snapToNextRow, + isMultiSelect, + ); + } + }; + + const drawRectangle = ( + selectionDimensions: SelectedArenaDimensions, + ) => { + const strokeWidth = 1; + canvasCtx.setLineDash([5]); + canvasCtx.strokeStyle = "rgb(84, 132, 236)"; + canvasCtx.strokeRect( + selectionDimensions.left - strokeWidth, + selectionDimensions.top - strokeWidth, + selectionDimensions.width + 2 * strokeWidth, + selectionDimensions.height + 2 * strokeWidth, + ); + canvasCtx.fillStyle = "rgb(84, 132, 236, 0.06)"; + canvasCtx.fillRect( + selectionDimensions.left, + selectionDimensions.top, + selectionDimensions.width, + selectionDimensions.height, + ); + }; + + const onMouseLeave = () => { + document.body.addEventListener("mouseup", onMouseUp, false); + }; + + const onMouseEnter = () => { + document.body.removeEventListener("mouseup", onMouseUp); + }; + + const onClick = (e: any) => { + if ( + Math.abs(selectionRectangle.height) + + Math.abs(selectionRectangle.width) > + 0 + ) { + if (!isDragging) { + // cant set this in onMouseUp coz click seems to happen after onMouseUp. + selectionRectangle = initRectangle(); + } + e.stopPropagation(); + } + }; + + const onMouseDown = (e: any) => { + isMultiSelect = e.ctrlKey || e.metaKey || e.shiftKey; + selectionRectangle.left = e.offsetX - selectionCanvas.offsetLeft; + selectionRectangle.top = e.offsetY - selectionCanvas.offsetTop; + selectionRectangle.width = 0; + selectionRectangle.height = 0; + isDragging = true; + dispatch(setCanvasSelectionStateAction(true)); + // bring the canvas to the top layer + selectionCanvas.style.zIndex = 2; + }; + const onMouseUp = () => { + if (isDragging) { + isDragging = false; + canvasCtx.clearRect( + 0, + 0, + selectionCanvas.width, + selectionCanvas.height, + ); + selectionCanvas.style.zIndex = null; + dispatch(setCanvasSelectionStateAction(false)); + } + }; + const onMouseMove = (e: any) => { + if (isDragging) { + selectionRectangle.width = + e.offsetX - selectionCanvas.offsetLeft - selectionRectangle.left; + selectionRectangle.height = + e.offsetY - selectionCanvas.offsetTop - selectionRectangle.top; + canvasCtx.clearRect( + 0, + 0, + selectionCanvas.width, + selectionCanvas.height, + ); + const selectionDimensions = getSelectionDimensions(); + drawRectangle(selectionDimensions); + selectWidgetsInit(selectionDimensions, isMultiSelect); + } + }; + if (appMode === APP_MODE.EDIT) { + init(); + } + return () => { + selectionCanvas.removeEventListener("mousedown", onMouseDown); + selectionCanvas.removeEventListener("mouseup", onMouseUp); + selectionCanvas.removeEventListener("mousemove", onMouseMove); + selectionCanvas.removeEventListener("mouseleave", onMouseLeave); + selectionCanvas.removeEventListener("mouseenter", onMouseEnter); + selectionCanvas.removeEventListener("click", onClick); + }; + } + }, [ + appLayout, + currentPageId, + mainContainer.rightColumn, + mainContainer.bottomRow, + ]); + + return appMode === APP_MODE.EDIT ? ( + <StyledSelectionCanvas + data-testid={`canvas-${widgetId}`} + id={`canvas-${widgetId}`} + /> + ) : null; + }, +); +CanvasSelectionArena.displayName = "CanvasSelectionArena"; diff --git a/app/client/src/reducers/index.tsx b/app/client/src/reducers/index.tsx index 1ab0c49ee56e..0099c6d984bb 100644 --- a/app/client/src/reducers/index.tsx +++ b/app/client/src/reducers/index.tsx @@ -46,6 +46,7 @@ import { WebsocketReduxState } from "./uiReducers/websocketReducer"; import { DebuggerReduxState } from "./uiReducers/debuggerReducer"; import { TourReducerState } from "./uiReducers/tourReducer"; import { NotificationReducerState } from "./uiReducers/notificationsReducer"; +import { CanvasSelectionState } from "./uiReducers/canvasSelectionReducer"; const appReducer = combineReducers({ entities: entityReducer, @@ -90,6 +91,7 @@ export interface AppState { debugger: DebuggerReduxState; tour: TourReducerState; notifications: NotificationReducerState; + canvasSelection: CanvasSelectionState; }; entities: { canvasWidgets: CanvasWidgetsReduxState; diff --git a/app/client/src/reducers/uiReducers/canvasSelectionReducer.ts b/app/client/src/reducers/uiReducers/canvasSelectionReducer.ts new file mode 100644 index 000000000000..8d1d3ebde772 --- /dev/null +++ b/app/client/src/reducers/uiReducers/canvasSelectionReducer.ts @@ -0,0 +1,21 @@ +import { createImmerReducer } from "utils/AppsmithUtils"; +import { ReduxActionTypes } from "constants/ReduxActionConstants"; + +const initialState: CanvasSelectionState = { + isDraggingForSelection: false, +}; + +export const canvasSelectionReducer = createImmerReducer(initialState, { + [ReduxActionTypes.START_CANVAS_SELECTION]: (state: CanvasSelectionState) => { + state.isDraggingForSelection = true; + }, + [ReduxActionTypes.STOP_CANVAS_SELECTION]: (state: CanvasSelectionState) => { + state.isDraggingForSelection = false; + }, +}); + +export type CanvasSelectionState = { + isDraggingForSelection: boolean; +}; + +export default canvasSelectionReducer; diff --git a/app/client/src/reducers/uiReducers/dragResizeReducer.ts b/app/client/src/reducers/uiReducers/dragResizeReducer.ts index c7cd1a6dc3d7..f3aaddc486a0 100644 --- a/app/client/src/reducers/uiReducers/dragResizeReducer.ts +++ b/app/client/src/reducers/uiReducers/dragResizeReducer.ts @@ -46,10 +46,8 @@ export const widgetDraggingReducer = createImmerReducer(initialState, { } else if (!!widgetId) { state.selectedWidgets = [...state.selectedWidgets, widgetId]; } - if (state.selectedWidgets.length === 1) { - state.lastSelectedWidget = state.selectedWidgets[0]; - } else { - state.lastSelectedWidget = ""; + if (state.selectedWidgets.length > 0) { + state.lastSelectedWidget = removeSelection ? "" : widgetId; } } else { state.lastSelectedWidget = action.payload.widgetId; @@ -60,21 +58,40 @@ export const widgetDraggingReducer = createImmerReducer(initialState, { } } }, + [ReduxActionTypes.DESELECT_WIDGETS]: ( + state: WidgetDragResizeState, + action: ReduxAction<{ widgetIds?: string[] }>, + ) => { + const { widgetIds } = action.payload; + if (widgetIds) { + state.selectedWidgets = state.selectedWidgets.filter( + (each) => !widgetIds.includes(each), + ); + } + }, [ReduxActionTypes.SELECT_MULTIPLE_WIDGETS]: ( state: WidgetDragResizeState, action: ReduxAction<{ widgetIds?: string[] }>, ) => { const { widgetIds } = action.payload; if (widgetIds) { + state.selectedWidgets = widgetIds || []; if (widgetIds.length > 1) { - state.selectedWidgets = widgetIds || []; state.lastSelectedWidget = ""; } else { - state.selectedWidgets = []; state.lastSelectedWidget = widgetIds[0]; } } }, + [ReduxActionTypes.SELECT_WIDGETS]: ( + state: WidgetDragResizeState, + action: ReduxAction<{ widgetIds?: string[] }>, + ) => { + const { widgetIds } = action.payload; + if (widgetIds) { + state.selectedWidgets = [...state.selectedWidgets, ...widgetIds]; + } + }, [ReduxActionTypes.FOCUS_WIDGET]: ( state: WidgetDragResizeState, action: ReduxAction<{ widgetId?: string }>, diff --git a/app/client/src/reducers/uiReducers/index.tsx b/app/client/src/reducers/uiReducers/index.tsx index 7f05e2b5800a..f8f9a85893d2 100644 --- a/app/client/src/reducers/uiReducers/index.tsx +++ b/app/client/src/reducers/uiReducers/index.tsx @@ -31,6 +31,7 @@ import websocketReducer from "./websocketReducer"; import debuggerReducer from "./debuggerReducer"; import tourReducer from "./tourReducer"; import notificationsReducer from "./notificationsReducer"; +import canvasSelectionReducer from "./canvasSelectionReducer"; const uiReducer = combineReducers({ widgetSidebar: widgetSidebarReducer, @@ -65,6 +66,7 @@ const uiReducer = combineReducers({ debugger: debuggerReducer, tour: tourReducer, notifications: notificationsReducer, + canvasSelection: canvasSelectionReducer, }); export default uiReducer; diff --git a/app/client/src/sagas/ModalSagas.ts b/app/client/src/sagas/ModalSagas.ts index c32442e056d7..b878edf3e119 100644 --- a/app/client/src/sagas/ModalSagas.ts +++ b/app/client/src/sagas/ModalSagas.ts @@ -116,7 +116,7 @@ export function* showModalSaga(action: ReduxAction<{ modalId: string }>) { }); yield put({ - type: ReduxActionTypes.SELECT_WIDGET, + type: ReduxActionTypes.SELECT_WIDGET_INIT, payload: { widgetId: action.payload.modalId }, }); yield put(focusWidget(action.payload.modalId)); diff --git a/app/client/src/sagas/OnboardingSagas.ts b/app/client/src/sagas/OnboardingSagas.ts index 0a3372fc4ce1..01e771f2ed32 100644 --- a/app/client/src/sagas/OnboardingSagas.ts +++ b/app/client/src/sagas/OnboardingSagas.ts @@ -83,7 +83,7 @@ import { getQueryIdFromURL } from "pages/Editor/Explorer/helpers"; import { RenderModes, WidgetTypes } from "constants/WidgetConstants"; import { generateReactKey } from "utils/generators"; import { forceOpenPropertyPane } from "actions/widgetActions"; -import { navigateToCanvas } from "pages/Editor/Explorer/Widgets/WidgetEntity"; +import { navigateToCanvas } from "pages/Editor/Explorer/Widgets/utils"; import { batchUpdateWidgetProperty, updateWidgetPropertyRequest, @@ -667,7 +667,7 @@ function* addWidget(widgetConfig: any) { newWidget.newWidgetId, ); yield put({ - type: ReduxActionTypes.SELECT_WIDGET, + type: ReduxActionTypes.SELECT_WIDGET_INIT, payload: { widgetId: newWidget.newWidgetId }, }); yield put(forceOpenPropertyPane(newWidget.newWidgetId)); @@ -785,7 +785,7 @@ function* addOnSubmitHandler() { inputWidget.widgetId, ); yield put({ - type: ReduxActionTypes.SELECT_WIDGET, + type: ReduxActionTypes.SELECT_WIDGET_INIT, payload: { widgetId: inputWidget.widgetId }, }); yield put(forceOpenPropertyPane(inputWidget.widgetId)); diff --git a/app/client/src/sagas/RecentEntitiesSagas.ts b/app/client/src/sagas/RecentEntitiesSagas.ts index ecbef6f83a9f..bcbaf77415ca 100644 --- a/app/client/src/sagas/RecentEntitiesSagas.ts +++ b/app/client/src/sagas/RecentEntitiesSagas.ts @@ -73,7 +73,7 @@ function* handlePathUpdated( export default function* recentEntitiesSagas() { yield all([ - takeLatest(ReduxActionTypes.SELECT_WIDGET, handleSelectWidget), + takeLatest(ReduxActionTypes.SELECT_WIDGET_INIT, handleSelectWidget), takeLatest(ReduxActionTypes.HANDLE_PATH_UPDATED, handlePathUpdated), ]); } diff --git a/app/client/src/sagas/SelectionCanvasSagas.ts b/app/client/src/sagas/SelectionCanvasSagas.ts new file mode 100644 index 000000000000..4eadab3e7405 --- /dev/null +++ b/app/client/src/sagas/SelectionCanvasSagas.ts @@ -0,0 +1,134 @@ +import { selectAllWidgetsAction } from "actions/widgetSelectionActions"; +import { OccupiedSpace } from "constants/editorConstants"; +import { ReduxAction, ReduxActionTypes } from "constants/ReduxActionConstants"; +import { + CONTAINER_GRID_PADDING, + MAIN_CONTAINER_WIDGET_ID, + WIDGET_PADDING, + GridDefaults, +} from "constants/WidgetConstants"; +import { isEqual } from "lodash"; +import { SelectedArenaDimensions } from "pages/common/CanvasSelectionArena"; +import { all, cancel, put, select, take, takeLatest } from "redux-saga/effects"; +import { getOccupiedSpaces } from "selectors/editorSelectors"; +import { getSelectedWidgets } from "selectors/ui"; +import { snapToGrid } from "utils/helpers"; +import { areIntersecting } from "utils/WidgetPropsUtils"; +import { WidgetProps } from "widgets/BaseWidget"; +import { getWidget } from "./selectors"; + +interface StartingSelectionState { + lastSelectedWidgets: string[]; + mainContainer: WidgetProps; + widgetOccupiedSpaces: + | { + [containerWidgetId: string]: OccupiedSpace[]; + } + | undefined; +} +function* selectAllWidgetsInAreaSaga( + StartingSelectionState: StartingSelectionState, + action: ReduxAction<any>, +) { + const { + lastSelectedWidgets, + mainContainer, + widgetOccupiedSpaces, + } = StartingSelectionState; + const { + isMultiSelect, + selectionArena, + snapToNextColumn, + snapToNextRow, + }: { + selectionArena: SelectedArenaDimensions; + snapToNextColumn: boolean; + snapToNextRow: boolean; + isMultiSelect: boolean; + } = action.payload; + + const padding = CONTAINER_GRID_PADDING + WIDGET_PADDING; + const snapSpace = { + snapColumnWidth: + (mainContainer.rightColumn - 2 * padding) / mainContainer.snapColumns, + snapColumnHeight: GridDefaults.DEFAULT_GRID_ROW_HEIGHT, + }; + // we use snapToNextRow, snapToNextColumn to determine if the selection rectangle is inverted + // so to snap not to the next column or row like we usually do, + // but to snap it to the one before it coz the rectangle is inverted. + const topLeftCorner = snapToGrid( + snapSpace.snapColumnWidth, + snapSpace.snapColumnHeight, + selectionArena.left - (snapToNextRow ? snapSpace.snapColumnWidth : 0), + selectionArena.top - (snapToNextColumn ? snapSpace.snapColumnHeight : 0), + ); + const bottomRightCorner = snapToGrid( + snapSpace.snapColumnWidth, + snapSpace.snapColumnHeight, + selectionArena.left + selectionArena.width, + selectionArena.top + selectionArena.height, + ); + + if (widgetOccupiedSpaces) { + const mainContainerWidgets = widgetOccupiedSpaces[MAIN_CONTAINER_WIDGET_ID]; + const widgets = Object.values(mainContainerWidgets || {}); + const widgetsToBeSelected = widgets.filter((eachWidget) => { + const { bottom, left, right, top } = eachWidget; + return areIntersecting( + { bottom, left, right, top }, + { + bottom: bottomRightCorner[1], + right: bottomRightCorner[0], + top: topLeftCorner[1], + left: topLeftCorner[0], + }, + ); + }); + const widgetIdsToSelect = widgetsToBeSelected.map((each) => each.id); + const filteredLastSelectedWidgets = isMultiSelect + ? lastSelectedWidgets.filter((each) => !widgetIdsToSelect.includes(each)) + : lastSelectedWidgets; + const filteredWidgetsToSelect = isMultiSelect + ? [ + ...filteredLastSelectedWidgets, + ...widgetIdsToSelect.filter( + (each) => !lastSelectedWidgets.includes(each), + ), + ] + : widgetIdsToSelect; + const currentSelectedWidgets: string[] = yield select(getSelectedWidgets); + + if (!isEqual(filteredWidgetsToSelect, currentSelectedWidgets)) { + yield put(selectAllWidgetsAction(filteredWidgetsToSelect)); + } + } +} + +function* startCanvasSelectionSaga() { + const lastSelectedWidgets: string[] = yield select(getSelectedWidgets); + const mainContainer: WidgetProps = yield select( + getWidget, + MAIN_CONTAINER_WIDGET_ID, + ); + const widgetOccupiedSpaces: + | { + [containerWidgetId: string]: OccupiedSpace[]; + } + | undefined = yield select(getOccupiedSpaces); + const selectionTask = yield takeLatest( + ReduxActionTypes.SELECT_WIDGETS_IN_AREA, + selectAllWidgetsInAreaSaga, + { lastSelectedWidgets, mainContainer, widgetOccupiedSpaces }, + ); + yield take(ReduxActionTypes.STOP_CANVAS_SELECTION); + yield cancel(selectionTask); +} + +export default function* selectionCanvasSagas() { + yield all([ + takeLatest( + ReduxActionTypes.START_CANVAS_SELECTION, + startCanvasSelectionSaga, + ), + ]); +} diff --git a/app/client/src/sagas/WidgetOperationSagas.tsx b/app/client/src/sagas/WidgetOperationSagas.tsx index 7669036f94b4..c205d512277e 100644 --- a/app/client/src/sagas/WidgetOperationSagas.tsx +++ b/app/client/src/sagas/WidgetOperationSagas.tsx @@ -19,7 +19,6 @@ import { import { getSelectedWidget, getWidget, - getWidgetImmediateChildren, getWidgetMetaProps, getWidgets, } from "./selectors"; @@ -30,6 +29,7 @@ import { import { all, call, + fork, put, select, takeEvery, @@ -84,7 +84,7 @@ import { generateReactKey } from "utils/generators"; import { flashElementById } from "utils/helpers"; import AnalyticsUtil from "utils/AnalyticsUtil"; import log from "loglevel"; -import { navigateToCanvas } from "pages/Editor/Explorer/Widgets/WidgetEntity"; +import { navigateToCanvas } from "pages/Editor/Explorer/Widgets/utils"; import { getCurrentApplicationId, getCurrentPageId, @@ -92,9 +92,9 @@ import { import { closePropertyPane, forceOpenPropertyPane, - selectAllWidgets, - selectWidget, } from "actions/widgetActions"; +import { selectWidgetInitAction } from "actions/widgetSelectionActions"; + import { getDataTree } from "selectors/dataTreeSelectors"; import { clearEvalPropertyCacheOfWidget, @@ -119,18 +119,18 @@ import { WIDGET_DELETE, WIDGET_BULK_DELETE, ERROR_WIDGET_COPY_NOT_ALLOWED, - SELECT_ALL_WIDGETS_MSG, } from "constants/messages"; import AppsmithConsole from "utils/AppsmithConsole"; import { ENTITY_TYPE } from "entities/AppsmithConsole"; import LOG_TYPE from "entities/AppsmithConsole/logtype"; import { doesTriggerPathsContainPropertyPath, + getWidgetChildren, handleSpecificCasesWhilePasting, } from "./WidgetOperationUtils"; import { getSelectedWidgets } from "selectors/ui"; import { getParentWithEnhancementFn } from "./WidgetEnhancementHelpers"; - +import { widgetSelectionSagas } from "./WidgetSelectionSagas"; function* getChildWidgetProps( parent: FlattenedWidgetProps, params: WidgetAddChild, @@ -494,7 +494,7 @@ export function* deleteAllSelectedWidgetsSaga( ); yield put(updateAndSaveLayout(finalWidgets)); - yield put(selectWidget("")); + yield put(selectWidgetInitAction("")); const bulkDeleteKey = selectedWidgets.join(","); const saveStatus: boolean = yield saveDeletedWidgets( falttendedWidgets, @@ -1286,31 +1286,6 @@ const unsetPropertyPath = (obj: Record<string, unknown>, path: string) => { return obj; }; -function* getWidgetChildren(widgetId: string): any { - const childrenIds: string[] = []; - const widget = yield select(getWidget, widgetId); - // When a form widget tries to resetChildrenMetaProperties - // But one or more of its container like children - // have just been deleted, widget can be undefined - if (widget === undefined) { - return []; - } - const { children = [] } = widget; - if (children && children.length) { - for (const childIndex in children) { - if (children.hasOwnProperty(childIndex)) { - const child = children[childIndex]; - childrenIds.push(child); - const grandChildren = yield call(getWidgetChildren, child); - if (grandChildren.length) { - childrenIds.push(...grandChildren); - } - } - } - } - return childrenIds; -} - function* resetChildrenMetaSaga(action: ReduxAction<{ widgetId: string }>) { const parentWidgetId = action.payload.widgetId; const childrenIds: string[] = yield call(getWidgetChildren, parentWidgetId); @@ -1719,7 +1694,7 @@ function* pasteWidgetSaga() { // Flash the newly pasted widget once the DSL is re-rendered setTimeout(() => flashElementById(newWidgetId), 100); yield put({ - type: ReduxActionTypes.SELECT_WIDGET, + type: ReduxActionTypes.SELECT_WIDGET_INIT, payload: { widgetId: newWidgetId }, }); } @@ -1827,7 +1802,7 @@ function* addTableWidgetFromQuerySaga(action: ReduxAction<string>) { newWidget.newWidgetId, ); yield put({ - type: ReduxActionTypes.SELECT_WIDGET, + type: ReduxActionTypes.SELECT_WIDGET_INIT, payload: { widgetId: newWidget.newWidgetId }, }); yield put(forceOpenPropertyPane(newWidget.newWidgetId)); @@ -1839,56 +1814,8 @@ function* addTableWidgetFromQuerySaga(action: ReduxAction<string>) { } } -// The following is computed to be used in the entity explorer -// Every time a widget is selected, we need to expand widget entities -// in the entity explorer so that the selected widget is visible -function* selectedWidgetAncestrySaga( - action: ReduxAction<{ widgetId: string }>, -) { - try { - const canvasWidgets = yield select(getWidgets); - const widgetIdsExpandList = []; - const selectedWidget = action.payload.widgetId; - - // Make sure that the selected widget exists in canvasWidgets - let widgetId = canvasWidgets[selectedWidget] - ? canvasWidgets[selectedWidget].parentId - : undefined; - // If there is a parentId for the selectedWidget - if (widgetId) { - // Keep including the parent until we reach the main container - while (widgetId !== MAIN_CONTAINER_WIDGET_ID) { - widgetIdsExpandList.push(widgetId); - if (canvasWidgets[widgetId] && canvasWidgets[widgetId].parentId) - widgetId = canvasWidgets[widgetId].parentId; - else break; - } - } - yield put({ - type: ReduxActionTypes.SET_SELECTED_WIDGET_ANCESTORY, - payload: widgetIdsExpandList, - }); - } catch (error) { - log.debug("Could not compute selected widget's ancestry", error); - } -} - -function* selectAllWidgetsSaga() { - const allWidgetsOnMainContainer: string[] = yield select( - getWidgetImmediateChildren, - MAIN_CONTAINER_WIDGET_ID, - ); - if (allWidgetsOnMainContainer && allWidgetsOnMainContainer.length) { - yield put(selectAllWidgets(allWidgetsOnMainContainer)); - Toaster.show({ - text: createMessage(SELECT_ALL_WIDGETS_MSG), - variant: Variant.info, - duration: 3000, - }); - } -} - export default function* widgetOperationSagas() { + yield fork(widgetSelectionSagas); yield all([ takeEvery( ReduxActionTypes.ADD_TABLE_WIDGET_FROM_QUERY, @@ -1933,10 +1860,5 @@ export default function* widgetOperationSagas() { takeEvery(ReduxActionTypes.UNDO_DELETE_WIDGET, undoDeleteSaga), takeEvery(ReduxActionTypes.CUT_SELECTED_WIDGET, cutWidgetSaga), takeEvery(ReduxActionTypes.WIDGET_ADD_CHILDREN, addChildrenSaga), - takeLatest(ReduxActionTypes.SELECT_WIDGET, selectedWidgetAncestrySaga), - takeLatest( - ReduxActionTypes.SELECT_MULTIPLE_WIDGETS_INIT, - selectAllWidgetsSaga, - ), ]); } diff --git a/app/client/src/sagas/WidgetOperationUtils.ts b/app/client/src/sagas/WidgetOperationUtils.ts index a4e477b5e388..23433a1f6016 100644 --- a/app/client/src/sagas/WidgetOperationUtils.ts +++ b/app/client/src/sagas/WidgetOperationUtils.ts @@ -4,7 +4,9 @@ import { } from "constants/WidgetConstants"; import { cloneDeep, get, isString, filter, set } from "lodash"; import { FlattenedWidgetProps } from "reducers/entityReducers/canvasWidgetsReducer"; +import { call, select } from "redux-saga/effects"; import { getDynamicBindings } from "utils/DynamicBindingUtils"; +import { getWidget } from "./selectors"; /** * checks if triggerpaths contains property path passed @@ -197,3 +199,28 @@ export const handleSpecificCasesWhilePasting = ( return widgets; }; + +export function* getWidgetChildren(widgetId: string): any { + const childrenIds: string[] = []; + const widget = yield select(getWidget, widgetId); + // When a form widget tries to resetChildrenMetaProperties + // But one or more of its container like children + // have just been deleted, widget can be undefined + if (widget === undefined) { + return []; + } + const { children = [] } = widget; + if (children && children.length) { + for (const childIndex in children) { + if (children.hasOwnProperty(childIndex)) { + const child = children[childIndex]; + childrenIds.push(child); + const grandChildren = yield call(getWidgetChildren, child); + if (grandChildren.length) { + childrenIds.push(...grandChildren); + } + } + } + } + return childrenIds; +} diff --git a/app/client/src/sagas/WidgetSelectionSagas.ts b/app/client/src/sagas/WidgetSelectionSagas.ts new file mode 100644 index 000000000000..861f9da36173 --- /dev/null +++ b/app/client/src/sagas/WidgetSelectionSagas.ts @@ -0,0 +1,153 @@ +import { ReduxAction, ReduxActionTypes } from "constants/ReduxActionConstants"; +import { MAIN_CONTAINER_WIDGET_ID } from "constants/WidgetConstants"; +import { all, put, select, takeLatest } from "redux-saga/effects"; +import { getWidgetImmediateChildren, getWidgets } from "./selectors"; +import log from "loglevel"; +import { + deselectMultipleWidgetsAction, + selectAllWidgetsAction, + selectMultipleWidgetsAction, + selectWidgetAction, + selectWidgetInitAction, +} from "actions/widgetSelectionActions"; +import { Toaster } from "components/ads/Toast"; +import { createMessage, SELECT_ALL_WIDGETS_MSG } from "constants/messages"; +import { Variant } from "components/ads/common"; +import { getSelectedWidget, getSelectedWidgets } from "selectors/ui"; + +// The following is computed to be used in the entity explorer +// Every time a widget is selected, we need to expand widget entities +// in the entity explorer so that the selected widget is visible +function* selectedWidgetAncestrySaga( + action: ReduxAction<{ widgetId: string; isMultiSelect: boolean }>, +) { + try { + const canvasWidgets = yield select(getWidgets); + const widgetIdsExpandList = []; + const { isMultiSelect, widgetId: selectedWidget } = action.payload; + + // Make sure that the selected widget exists in canvasWidgets + let widgetId = canvasWidgets[selectedWidget] + ? canvasWidgets[selectedWidget].parentId + : undefined; + // If there is a parentId for the selectedWidget + if (widgetId) { + // Keep including the parent until we reach the main container + while (widgetId !== MAIN_CONTAINER_WIDGET_ID) { + widgetIdsExpandList.push(widgetId); + if (canvasWidgets[widgetId] && canvasWidgets[widgetId].parentId) + widgetId = canvasWidgets[widgetId].parentId; + else break; + } + } + if (isMultiSelect) { + // Deselect the parents if this is a Multi select. + const parentsToDeselect = widgetIdsExpandList.filter( + (each) => each !== selectedWidget, + ); + if (parentsToDeselect && parentsToDeselect.length) { + yield put(deselectMultipleWidgetsAction(parentsToDeselect)); + } + } + + yield put({ + type: ReduxActionTypes.SET_SELECTED_WIDGET_ANCESTORY, + payload: widgetIdsExpandList, + }); + } catch (error) { + log.debug("Could not compute selected widget's ancestry", error); + } +} + +function* selectAllWidgetsSaga() { + const allWidgetsOnMainContainer: string[] = yield select( + getWidgetImmediateChildren, + MAIN_CONTAINER_WIDGET_ID, + ); + if (allWidgetsOnMainContainer && allWidgetsOnMainContainer.length) { + yield put(selectAllWidgetsAction(allWidgetsOnMainContainer)); + Toaster.show({ + text: createMessage(SELECT_ALL_WIDGETS_MSG), + variant: Variant.info, + duration: 3000, + }); + } +} + +function* deselectNonSiblingsOfWidgetSaga( + action: ReduxAction<{ widgetId: string; isMultiSelect: boolean }>, +) { + const { isMultiSelect, widgetId } = action.payload; + if (isMultiSelect) { + const allWidgets = yield select(getWidgets); + const parentId = allWidgets[widgetId].parentId; + const childWidgets: string[] = yield select( + getWidgetImmediateChildren, + parentId, + ); + const currentSelectedWidgets: string[] = yield select(getSelectedWidgets); + + const nonSiblings = currentSelectedWidgets.filter( + (each) => !childWidgets.includes(each), + ); + if (nonSiblings && nonSiblings.length) { + yield put( + deselectMultipleWidgetsAction( + nonSiblings.filter((each) => each !== widgetId), + ), + ); + } + } +} + +function* selectWidgetSaga( + action: ReduxAction<{ widgetId: string; isMultiSelect: boolean }>, +) { + const { isMultiSelect, widgetId } = action.payload; + yield put(selectWidgetAction(widgetId, isMultiSelect)); +} + +function* shiftSelectWidgetsSaga( + action: ReduxAction<{ widgetId: string; siblingWidgets: string[] }>, +) { + const { siblingWidgets, widgetId } = action.payload; + const selectedWidgets: string[] = yield select(getSelectedWidgets); + const lastSelectedWidget: string = yield select(getSelectedWidget); + const lastSelectedWidgetIndex = siblingWidgets.indexOf(lastSelectedWidget); + const isWidgetSelected = selectedWidgets.includes(widgetId); + if (!isWidgetSelected && lastSelectedWidgetIndex > -1) { + const selectedWidgetIndex = siblingWidgets.indexOf(widgetId); + const start = + lastSelectedWidgetIndex < selectedWidgetIndex + ? lastSelectedWidgetIndex + : selectedWidgetIndex; + const end = + lastSelectedWidgetIndex < selectedWidgetIndex + ? selectedWidgetIndex + : lastSelectedWidgetIndex; + const unSelectedSiblings = siblingWidgets.slice(start + 1, end); + if (unSelectedSiblings && unSelectedSiblings.length) { + yield put(selectMultipleWidgetsAction(unSelectedSiblings)); + } + } + yield put(selectWidgetInitAction(widgetId, true)); +} + +export function* widgetSelectionSagas() { + yield all([ + takeLatest( + ReduxActionTypes.SHIFT_SELECT_WIDGET_INIT, + shiftSelectWidgetsSaga, + ), + takeLatest(ReduxActionTypes.SELECT_WIDGET_INIT, selectWidgetSaga), + takeLatest(ReduxActionTypes.SELECT_WIDGET_INIT, selectedWidgetAncestrySaga), + takeLatest( + ReduxActionTypes.SELECT_WIDGET_INIT, + deselectNonSiblingsOfWidgetSaga, + ), + takeLatest( + ReduxActionTypes.SELECT_MULTIPLE_WIDGETS_INIT, + selectAllWidgetsSaga, + ), + ]); +} diff --git a/app/client/src/sagas/index.tsx b/app/client/src/sagas/index.tsx index ef47bc620a3c..b01b9e92c40e 100644 --- a/app/client/src/sagas/index.tsx +++ b/app/client/src/sagas/index.tsx @@ -20,7 +20,7 @@ import modalSagas from "./ModalSagas"; import batchSagas from "./BatchSagas"; import themeSagas from "./ThemeSaga"; import evaluationsSaga from "./EvaluationsSaga"; -import onboardingSaga from "./OnboardingSagas"; +import onboardingSagas from "./OnboardingSagas"; import utilSagas from "./UtilSagas"; import saaSPaneSagas from "./SaaSPaneSagas"; import actionExecutionChangeListeners from "./WidgetLoadingSaga"; @@ -31,6 +31,7 @@ import websocketSagas from "./WebsocketSagas/WebsocketSagas"; import debuggerSagas from "./DebuggerSagas"; import tourSagas from "./TourSagas"; import notificationsSagas from "./NotificationsSagas"; +import selectionCanvasSagas from "./SelectionCanvasSagas"; import log from "loglevel"; import * as sentry from "@sentry/react"; @@ -56,19 +57,18 @@ const sagas = [ batchSagas, themeSagas, evaluationsSaga, - onboardingSaga, + onboardingSagas, actionExecutionChangeListeners, utilSagas, - saaSPaneSagas, globalSearchSagas, recentEntitiesSagas, commentSagas, websocketSagas, debuggerSagas, - utilSagas, saaSPaneSagas, tourSagas, notificationsSagas, + selectionCanvasSagas, ]; export function* rootSaga(sagasToRun = sagas) { diff --git a/app/client/src/selectors/entitiesSelector.ts b/app/client/src/selectors/entitiesSelector.ts index cbcfcdf01f76..15ea44b6e582 100644 --- a/app/client/src/selectors/entitiesSelector.ts +++ b/app/client/src/selectors/entitiesSelector.ts @@ -299,7 +299,12 @@ export const getCanvasWidgets = (state: AppState): CanvasWidgetsReduxState => state.entities.canvasWidgets; const getPageWidgets = (state: AppState) => state.ui.pageWidgets; - +export const getCurrentPageWidgets = createSelector( + getPageWidgets, + getCurrentPageId, + (widgetsByPage, currentPageId) => + currentPageId ? widgetsByPage[currentPageId] : {}, +); export const getAllWidgetsMap = createSelector( getPageWidgets, (widgetsByPage) => { diff --git a/app/client/src/utils/WidgetPropsUtils.tsx b/app/client/src/utils/WidgetPropsUtils.tsx index f92778a2551a..81cf3c07fbc6 100644 --- a/app/client/src/utils/WidgetPropsUtils.tsx +++ b/app/client/src/utils/WidgetPropsUtils.tsx @@ -39,6 +39,7 @@ import WidgetConfigResponse, { GRID_DENSITY_MIGRATION_V1, } from "mockResponses/WidgetConfigResponse"; import CanvasWidgetsNormalizer from "normalizers/CanvasWidgetsNormalizer"; +import { theme } from "../../src/constants/DefaultTheme"; export type WidgetOperationParams = { operation: WidgetOperation; @@ -523,13 +524,20 @@ export function migrateChartDataFromArrayToObject( return currentDSL; } +const pixelToNumber = (pixel: string) => { + if (pixel.includes("px")) { + return parseInt(pixel.split("px").join("")); + } + return 0; +}; + export const calculateDynamicHeight = ( canvasWidgets: { [widgetId: string]: FlattenedWidgetProps; } = {}, presentMinimumHeight = CANVAS_DEFAULT_HEIGHT_PX, ) => { - let minmumHeight = presentMinimumHeight; + let minimumHeight = presentMinimumHeight; const nextAvailableRow = nextAvailableRowInContainer( MAIN_CONTAINER_WIDGET_ID, canvasWidgets, @@ -538,19 +546,19 @@ export const calculateDynamicHeight = ( const gridRowHeight = GridDefaults.DEFAULT_GRID_ROW_HEIGHT; const calculatedCanvasHeight = nextAvailableRow * gridRowHeight; // DGRH - DEFAULT_GRID_ROW_HEIGHT - // View Mode: Header height + Page Selection Tab = 2 * DGRH (approx) - // Edit Mode: Header height + Canvas control = 2 * DGRH (approx) - // buffer = DGRH, it's not 2 * DGRH coz we already add a buffer on the canvas which is also equal to DGRH. - const buffer = gridRowHeight; + // View Mode: Header height + Page Selection Tab = 8 * DGRH (approx) + // Edit Mode: Header height + Canvas control = 8 * DGRH (approx) + // buffer: ~8 grid row height + const buffer = gridRowHeight + 2 * pixelToNumber(theme.smallHeaderHeight); const calculatedMinHeight = Math.floor((screenHeight - buffer) / gridRowHeight) * gridRowHeight; if ( calculatedCanvasHeight < screenHeight && calculatedMinHeight !== presentMinimumHeight ) { - minmumHeight = calculatedMinHeight; + minimumHeight = calculatedMinHeight; } - return minmumHeight; + return minimumHeight; }; export const migrateInitialValues = ( @@ -940,7 +948,7 @@ export const getDropZoneOffsets = ( ); }; -const areIntersecting = (r1: Rect, r2: Rect) => { +export const areIntersecting = (r1: Rect, r2: Rect) => { return !( r2.left >= r1.right || r2.right <= r1.left || diff --git a/app/client/src/utils/hooks/dragResizeHooks.tsx b/app/client/src/utils/hooks/dragResizeHooks.tsx index 3732c514c416..65039ba6282b 100644 --- a/app/client/src/utils/hooks/dragResizeHooks.tsx +++ b/app/client/src/utils/hooks/dragResizeHooks.tsx @@ -1,10 +1,5 @@ import { useDispatch, useSelector } from "react-redux"; import { ReduxActionTypes } from "constants/ReduxActionConstants"; -import { - focusWidget, - selectAllWidgets, - selectWidget, -} from "actions/widgetActions"; import { useCallback, useEffect, useState } from "react"; import { commentModeSelector } from "selectors/commentsSelectors"; @@ -69,22 +64,6 @@ export const useCanvasSnapRowsUpdateHook = () => { return updateCanvasSnapRows; }; -export const useWidgetSelection = () => { - const dispatch = useDispatch(); - return { - selectWidget: useCallback( - (widgetId?: string, isMultiSelect?: boolean) => { - dispatch(selectWidget(widgetId, isMultiSelect)); - }, - [dispatch], - ), - focusWidget: useCallback( - (widgetId?: string) => dispatch(focusWidget(widgetId)), - [dispatch], - ), - deselectAll: useCallback(() => dispatch(selectAllWidgets([])), [dispatch]), - }; -}; export const useWidgetDragResize = () => { const dispatch = useDispatch(); return { diff --git a/app/client/src/utils/hooks/useClickOpenPropPane.tsx b/app/client/src/utils/hooks/useClickOpenPropPane.tsx index 9a5b7cf0fb04..a5166abae5e1 100644 --- a/app/client/src/utils/hooks/useClickOpenPropPane.tsx +++ b/app/client/src/utils/hooks/useClickOpenPropPane.tsx @@ -1,8 +1,5 @@ import { get } from "lodash"; -import { - useShowPropertyPane, - useWidgetSelection, -} from "utils/hooks/dragResizeHooks"; +import { useShowPropertyPane } from "utils/hooks/dragResizeHooks"; import { getCurrentWidgetId, getIsPropertyPaneVisible, @@ -14,6 +11,7 @@ import { CanvasWidgetsReduxState } from "reducers/entityReducers/canvasWidgetsRe import { APP_MODE } from "reducers/entityReducers/appReducer"; import { getAppMode } from "selectors/applicationSelectors"; import { getWidgets } from "sagas/selectors"; +import { useWidgetSelection } from "./useWidgetSelection"; /** * @@ -85,14 +83,14 @@ export const useClickOpenPropPane = () => { (!isPropPaneVisible && selectedWidgetId === focusedWidgetId) || selectedWidgetId !== focusedWidgetId ) { - const isMultiSelect = e.metaKey || e.ctrlKey; + const isMultiSelect = e.metaKey || e.ctrlKey || e.shiftKey; if (parentWidgetToOpen) { - selectWidget(parentWidgetToOpen.widgetId); + selectWidget(parentWidgetToOpen.widgetId, isMultiSelect); focusWidget(parentWidgetToOpen.widgetId); showPropertyPane(parentWidgetToOpen.widgetId, undefined, true); } else { - selectWidget(focusedWidgetId); + selectWidget(focusedWidgetId, isMultiSelect); focusWidget(focusedWidgetId); showPropertyPane(focusedWidgetId, undefined, true); } diff --git a/app/client/src/utils/hooks/useWidgetSelection.ts b/app/client/src/utils/hooks/useWidgetSelection.ts new file mode 100644 index 000000000000..2be038fe031b --- /dev/null +++ b/app/client/src/utils/hooks/useWidgetSelection.ts @@ -0,0 +1,36 @@ +import { useDispatch } from "react-redux"; +import { focusWidget } from "actions/widgetActions"; +import { + selectAllWidgetsAction, + selectWidgetInitAction, + shiftSelectWidgetsEntityExplorerInitAction, +} from "actions/widgetSelectionActions"; + +import { useCallback } from "react"; + +export const useWidgetSelection = () => { + const dispatch = useDispatch(); + return { + selectWidget: useCallback( + (widgetId?: string, isMultiSelect?: boolean) => { + dispatch(selectWidgetInitAction(widgetId, isMultiSelect)); + }, + [dispatch], + ), + shiftSelectWidgetEntityExplorer: useCallback( + (widgetId: string, siblingWidgets: string[]) => { + dispatch( + shiftSelectWidgetsEntityExplorerInitAction(widgetId, siblingWidgets), + ); + }, + [dispatch], + ), + focusWidget: useCallback( + (widgetId?: string) => dispatch(focusWidget(widgetId)), + [dispatch], + ), + deselectAll: useCallback(() => dispatch(selectAllWidgetsAction([])), [ + dispatch, + ]), + }; +}; diff --git a/app/client/src/widgets/ContainerWidget.tsx b/app/client/src/widgets/ContainerWidget.tsx index ea3e3f0657dc..09f3f493e9ae 100644 --- a/app/client/src/widgets/ContainerWidget.tsx +++ b/app/client/src/widgets/ContainerWidget.tsx @@ -6,6 +6,7 @@ import { GridDefaults, CONTAINER_GRID_PADDING, WIDGET_PADDING, + MAIN_CONTAINER_WIDGET_ID, } from "constants/WidgetConstants"; import WidgetFactory from "utils/WidgetFactory"; import ContainerComponent, { @@ -14,7 +15,7 @@ import ContainerComponent, { import { WidgetType, WidgetTypes } from "constants/WidgetConstants"; import BaseWidget, { WidgetProps, WidgetState } from "./BaseWidget"; import { VALIDATION_TYPES } from "constants/WidgetValidation"; - +import { CanvasSelectionArena } from "pages/common/CanvasSelectionArena"; class ContainerWidget extends BaseWidget< ContainerWidgetProps<WidgetProps>, WidgetState @@ -63,11 +64,21 @@ class ContainerWidget extends BaseWidget< getSnapSpaces = () => { const { componentWidth } = this.getComponentDimensions(); - const padding = (CONTAINER_GRID_PADDING + WIDGET_PADDING) * 2; + // For all widgets inside a container, we remove both container padding as well as widget padding from component width + let padding = (CONTAINER_GRID_PADDING + WIDGET_PADDING) * 2; + if ( + this.props.widgetId === MAIN_CONTAINER_WIDGET_ID || + this.props.type === "CONTAINER_WIDGET" + ) { + //For MainContainer and any Container Widget padding doesn't exist coz there is already container padding. + padding = CONTAINER_GRID_PADDING * 2; + } + if (this.props.noPad) { + // Widgets like ListWidget choose to have no container padding so will only have widget padding + padding = WIDGET_PADDING * 2; + } let width = componentWidth; - if (!this.props.noPad) width -= padding; - else width -= WIDGET_PADDING * 2; - + width -= padding; return { snapRowSpace: GridDefaults.DEFAULT_GRID_ROW_HEIGHT, snapColumnSpace: componentWidth @@ -111,6 +122,9 @@ class ContainerWidget extends BaseWidget< renderAsContainerComponent(props: ContainerWidgetProps<WidgetProps>) { return ( <ContainerComponent {...props}> + {this.props.widgetId === MAIN_CONTAINER_WIDGET_ID && ( + <CanvasSelectionArena widgetId={MAIN_CONTAINER_WIDGET_ID} /> + )} {/* without the wrapping div onClick events are triggered twice */} <>{this.renderChildren()}</> </ContainerComponent> diff --git a/app/client/src/widgets/ListWidget/ListComponent.tsx b/app/client/src/widgets/ListWidget/ListComponent.tsx index 226feb5acd56..c55dd41bdc06 100644 --- a/app/client/src/widgets/ListWidget/ListComponent.tsx +++ b/app/client/src/widgets/ListWidget/ListComponent.tsx @@ -6,7 +6,6 @@ import { ListWidgetProps } from "./ListWidget"; import { WidgetProps } from "widgets/BaseWidget"; import { generateClassName, getCanvasClassName } from "utils/generators"; import { ComponentProps } from "components/designSystems/appsmith/BaseComponent"; -import { getBorderCSSShorthand } from "constants/DefaultTheme"; interface GridComponentProps extends ComponentProps { children?: ReactNode; @@ -73,7 +72,7 @@ export const ListComponentLoading = styled.div<{ width: 100%; position: relative; overflow: hidden; - border: ${(props) => getBorderCSSShorthand(props.theme.borders[2])}; + box-shadow: 0px 0px 0px 1px #e7e7e7; & > div { background: ${(props) => props.backgroundColor ?? "white"}; diff --git a/app/client/test/sagas.ts b/app/client/test/sagas.ts index e563dd6e3e05..e44156e80e71 100644 --- a/app/client/test/sagas.ts +++ b/app/client/test/sagas.ts @@ -10,7 +10,6 @@ import queryPaneSagas from "../src/sagas/QueryPaneSagas"; import modalSagas from "../src/sagas/ModalSagas"; import batchSagas from "../src/sagas/BatchSagas"; import themeSagas from "../src/sagas/ThemeSaga"; -import onboardingSaga from "../src/sagas/OnboardingSagas"; import utilSagas from "../src/sagas/UtilSagas"; import saaSPaneSagas from "../src/sagas/SaaSPaneSagas"; import actionExecutionChangeListeners from "../src/sagas/WidgetLoadingSaga"; @@ -25,6 +24,9 @@ import { watchActionExecutionSagas } from "../src/sagas/ActionExecutionSagas"; import widgetOperationSagas from "../src/sagas/WidgetOperationSagas"; import applicationSagas from "../src/sagas/ApplicationSagas"; import { watchDatasourcesSagas } from "../src/sagas/DatasourcesSagas"; +import tourSagas from "../src/sagas/TourSagas"; +import notificationsSagas from "../src/sagas/NotificationsSagas"; +import selectionCanvasSagas from "../src/sagas/SelectionCanvasSagas"; export const sagasToRunForTests = [ initSagas, @@ -45,7 +47,6 @@ export const sagasToRunForTests = [ modalSagas, batchSagas, themeSagas, - onboardingSaga, actionExecutionChangeListeners, utilSagas, saaSPaneSagas, @@ -54,6 +55,7 @@ export const sagasToRunForTests = [ commentSagas, websocketSagas, debuggerSagas, - utilSagas, - saaSPaneSagas, + tourSagas, + notificationsSagas, + selectionCanvasSagas, ]; diff --git a/app/client/test/testCommon.tsx b/app/client/test/testCommon.tsx index ee3740ff6a69..203690b05985 100644 --- a/app/client/test/testCommon.tsx +++ b/app/client/test/testCommon.tsx @@ -1,17 +1,26 @@ import { getCanvasWidgetsPayload } from "sagas/PageSagas"; import { updateCurrentPage } from "actions/pageActions"; import { editorInitializer } from "utils/EditorUtils"; -import { ReduxActionTypes } from "constants/ReduxActionConstants"; +import { + PageListPayload, + ReduxActionTypes, +} from "constants/ReduxActionConstants"; import { initEditor } from "actions/initActions"; import { useDispatch } from "react-redux"; +import { extractCurrentDSL } from "utils/WidgetPropsUtils"; +import { setAppMode } from "actions/pageActions"; +import { APP_MODE } from "reducers/entityReducers/appReducer"; export const useMockDsl = (dsl: any) => { const dispatch = useDispatch(); + dispatch(setAppMode(APP_MODE.EDIT)); const mockResp: any = { data: { id: "page_id", name: "Page1", applicationId: "app_id", + isDefault: true, + isHidden: false, layouts: [ { id: "layout_id", @@ -23,6 +32,30 @@ export const useMockDsl = (dsl: any) => { }, }; const canvasWidgetsPayload = getCanvasWidgetsPayload(mockResp); + dispatch({ + type: ReduxActionTypes.FETCH_PAGE_DSLS_SUCCESS, + payload: [ + { + pageId: mockResp.data.id, + dsl: extractCurrentDSL(mockResp), + }, + ], + }); + const pages: PageListPayload = [ + { + pageName: mockResp.data.name, + pageId: mockResp.data.id, + isDefault: mockResp.data.isDefault, + isHidden: !!mockResp.data.isHidden, + }, + ]; + dispatch({ + type: ReduxActionTypes.FETCH_PAGE_LIST_SUCCESS, + payload: { + pages, + applicationId: mockResp.data.applicationId, + }, + }); dispatch({ type: "UPDATE_LAYOUT", payload: { widgets: canvasWidgetsPayload.widgets }, @@ -35,6 +68,18 @@ export function MockPageDSL({ dsl, children }: any) { useMockDsl(dsl); return children; } + +export const syntheticTestMouseEvent = ( + event: MouseEvent, + optionsToAdd = {}, +) => { + const options = Object.entries(optionsToAdd); + options.forEach(([key, value]) => { + Object.defineProperty(event, key, { get: () => value }); + }); + return event; +}; + export function MockApplication({ children }: any) { editorInitializer(); const dispatch = useDispatch(); diff --git a/app/client/test/testUtils.tsx b/app/client/test/testUtils.tsx index 22134739c5be..9c4d8f812021 100644 --- a/app/client/test/testUtils.tsx +++ b/app/client/test/testUtils.tsx @@ -1,6 +1,6 @@ import React, { ReactElement } from "react"; import { render, RenderOptions, queries } from "@testing-library/react"; -import { Provider, useDispatch } from "react-redux"; +import { Provider } from "react-redux"; import { ThemeProvider } from "../src/constants/DefaultTheme"; import { getCurrentThemeDetails } from "../src/selectors/themeSelectors"; import * as customQueries from "./customQueries"; @@ -8,12 +8,6 @@ import { BrowserRouter } from "react-router-dom"; import appReducer, { AppState } from "reducers"; import { DndProvider } from "react-dnd"; import TouchBackend from "react-dnd-touch-backend"; -import { noop } from "utils/AppsmithUtils"; -import { getCanvasWidgetsPayload } from "sagas/PageSagas"; -import { updateCurrentPage } from "actions/pageActions"; -import { editorInitializer } from "utils/EditorUtils"; -import { ReduxActionTypes } from "constants/ReduxActionConstants"; -import { initEditor } from "actions/initActions"; import { applyMiddleware, compose, createStore } from "redux"; import { reduxBatch } from "@manaflair/redux-batch"; import createSagaMiddleware from "redux-saga";
cb6997bcf098959ec425b7d1de5aad624eea2097
2020-06-23 11:59:22
Tejaaswini
fix: Deactivate invite button and hide delete
false
Deactivate invite button and hide delete
fix
diff --git a/app/client/src/pages/Applications/ApplicationCard.tsx b/app/client/src/pages/Applications/ApplicationCard.tsx index 6fda8e5fcc76..d37f429d6e12 100644 --- a/app/client/src/pages/Applications/ApplicationCard.tsx +++ b/app/client/src/pages/Applications/ApplicationCard.tsx @@ -178,7 +178,7 @@ export const ApplicationCard = (props: ApplicationCardProps) => { label: "Duplicate", }); } - if (props.delete) { + if (props.delete && hasEditPermission) { moreActionItems.push({ value: "delete", onSelect: deleteApp, @@ -209,15 +209,17 @@ export const ApplicationCard = (props: ApplicationCardProps) => { </Control> </Link> )} - <ContextDropdown - options={moreActionItems} - toggle={{ - type: "icon", - icon: "MORE_VERTICAL_CONTROL", - iconSize: theme.fontSizes[APPLICATION_CONTROL_FONTSIZE_INDEX], - }} - className="more" - /> + {!!moreActionItems.length && ( + <ContextDropdown + options={moreActionItems} + toggle={{ + type: "icon", + icon: "MORE_VERTICAL_CONTROL", + iconSize: theme.fontSizes[APPLICATION_CONTROL_FONTSIZE_INDEX], + }} + className="more" + /> + )} </ApplicationTitle> <Link className="t--application-view-link" to={viewApplicationURL}> <ApplicationImage className="image-container"> diff --git a/app/client/src/pages/organization/InviteUsersFromv2.tsx b/app/client/src/pages/organization/InviteUsersFromv2.tsx index 10904ea239d7..c6218d8587ff 100644 --- a/app/client/src/pages/organization/InviteUsersFromv2.tsx +++ b/app/client/src/pages/organization/InviteUsersFromv2.tsx @@ -79,7 +79,7 @@ const StyledButton = styled(Button)` } `; -const validate = (values: { users: string; role: string }) => { +const validateFormValues = (values: { users: string; role: string }) => { if (values.users && values.users.length > 0) { const _users = values.users.split(",").filter(Boolean); @@ -99,6 +99,19 @@ const validate = (values: { users: string; role: string }) => { } }; +const validate = (values: any) => { + const errors: any = {}; + if (!(values.users && values.users.length > 0)) { + errors["users"] = INVITE_USERS_VALIDATION_EMAILS_EMPTY; + } + + if (values.role === undefined || values.role?.trim().length === 0) { + errors["role"] = INVITE_USERS_VALIDATION_ROLE_EMPTY; + } + + return errors; +}; + const InviteUsersForm = (props: any) => { const { handleSubmit, @@ -110,6 +123,7 @@ const InviteUsersForm = (props: any) => { error, fetchUser, fetchAllRoles, + valid, } = props; useEffect(() => { fetchUser(props.orgId); @@ -119,7 +133,7 @@ const InviteUsersForm = (props: any) => { return ( <StyledForm onSubmit={handleSubmit((values: any, dispatch: any) => { - validate(values); + validateFormValues(values); return inviteUsersToOrg({ ...values, orgId: props.orgId }, dispatch); })} > @@ -146,6 +160,7 @@ const InviteUsersForm = (props: any) => { </div> <StyledButton className="invite" + disabled={!valid} text="Invite" filled intent="primary" @@ -205,6 +220,7 @@ export default connect( InviteUsersToOrgFormValues, { fetchAllRoles: (orgId: string) => void; roles?: any } >({ + validate, form: INVITE_USERS_TO_ORG_FORM, })(InviteUsersForm), ); diff --git a/app/client/src/pages/organization/settings.tsx b/app/client/src/pages/organization/settings.tsx index 6a37c52c68eb..eff599e4fdf2 100644 --- a/app/client/src/pages/organization/settings.tsx +++ b/app/client/src/pages/organization/settings.tsx @@ -185,7 +185,7 @@ export const OrgSettings = (props: PageProps) => { username={props.username} /> } - position={Position.BOTTOM} + position={Position.BOTTOM_LEFT} > <StyledDropDown> {props.roleName}
9fc8e9a21667d331b5a9b3ae38ecee7a5ca3308c
2022-07-11 14:33:37
akash-codemonk
fix: query param seperator in signup url (#15074)
false
query param seperator in signup url (#15074)
fix
diff --git a/app/client/src/ce/pages/UserAuth/SignUp.tsx b/app/client/src/ce/pages/UserAuth/SignUp.tsx index dedb5f8bb30c..e13cfe980abd 100644 --- a/app/client/src/ce/pages/UserAuth/SignUp.tsx +++ b/app/client/src/ce/pages/UserAuth/SignUp.tsx @@ -114,13 +114,17 @@ export function SignUp(props: SignUpFormProps) { showError = true; } - let signupURL = "/api/v1/" + SIGNUP_SUBMIT_PATH; - if (queryParams.has("appId")) { - signupURL += `?appId=${queryParams.get("appId")}`; + const signupURL = new URL( + `/api/v1/` + SIGNUP_SUBMIT_PATH, + window.location.origin, + ); + const appId = queryParams.get("appId"); + if (appId) { + signupURL.searchParams.append("appId", appId); } else { const redirectUrl = queryParams.get("redirectUrl"); if (redirectUrl != null && getIsSafeRedirectURL(redirectUrl)) { - signupURL += `?redirectUrl=${encodeURIComponent(redirectUrl)}`; + signupURL.searchParams.append("redirectUrl", redirectUrl); } } @@ -138,12 +142,11 @@ export function SignUp(props: SignUpFormProps) { action: "submit", }) .then(function(token: any) { - formElement && - formElement.setAttribute( - "action", - `${signupURL}?recaptchaToken=${token}`, - ); - formElement && formElement.submit(); + if (formElement) { + signupURL.searchParams.append("recaptchaToken", token); + formElement.setAttribute("action", signupURL.toString()); + formElement.submit(); + } }); } else { formElement && formElement.submit(); @@ -170,7 +173,7 @@ export function SignUp(props: SignUpFormProps) { )} {!disableLoginForm && ( <SpacedSubmitForm - action={signupURL} + action={signupURL.toString()} id="signup-form" method="POST" onSubmit={(e) => handleSubmit(e)}
4cdbe89586a88c56cbe76f801c8d2070e2d8e6de
2024-03-13 14:50:03
Shrikant Sharat Kandula
chore: Add separate request/response views (#31640)
false
Add separate request/response views (#31640)
chore
diff --git a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/ce/ActionCE_DTO.java b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/ce/ActionCE_DTO.java index 1fc01c4c05dd..e9887f3d244c 100644 --- a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/ce/ActionCE_DTO.java +++ b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/ce/ActionCE_DTO.java @@ -16,9 +16,9 @@ import com.appsmith.external.models.PluginType; import com.appsmith.external.models.Policy; import com.appsmith.external.models.Property; +import com.appsmith.external.views.ResponseOnly; import com.appsmith.external.views.Views; import com.fasterxml.jackson.annotation.JsonFormat; -import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonView; import lombok.Getter; import lombok.NoArgsConstructor; @@ -88,9 +88,8 @@ public class ActionCE_DTO implements Identifiable, Executable { ActionConfiguration actionConfiguration; // this attribute carries error messages while processing the actionCollection - @JsonProperty(access = JsonProperty.Access.READ_ONLY) @Transient - @JsonView(Views.Public.class) + @JsonView(ResponseOnly.class) List<ErrorDTO> errorReports; @JsonView(Views.Public.class) @@ -106,23 +105,19 @@ public class ActionCE_DTO implements Identifiable, Executable { @JsonView(Views.Public.class) List<Property> dynamicBindingPathList; - @JsonProperty(access = JsonProperty.Access.READ_ONLY) - @JsonView(Views.Public.class) + @JsonView(ResponseOnly.class) Boolean isValid; - @JsonProperty(access = JsonProperty.Access.READ_ONLY) - @JsonView(Views.Public.class) + @JsonView(ResponseOnly.class) Set<String> invalids; @Transient - @JsonProperty(access = JsonProperty.Access.READ_ONLY) - @JsonView(Views.Public.class) + @JsonView(ResponseOnly.class) Set<String> messages = new HashSet<>(); // This is a list of keys that the client whose values the client needs to send during action execution. // These are the Mustache keys that the server will replace before invoking the API - @JsonProperty(access = JsonProperty.Access.READ_ONLY) - @JsonView(Views.Public.class) + @JsonView(ResponseOnly.class) Set<String> jsonPathKeys; @JsonView(Views.Internal.class) diff --git a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/views/RequestOnly.java b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/views/RequestOnly.java new file mode 100644 index 000000000000..2e2fc0a71680 --- /dev/null +++ b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/views/RequestOnly.java @@ -0,0 +1,7 @@ +package com.appsmith.external.views; + +/** + * Intended to annotate fields that can be set by HTTP request payloads, but should NOT be included + * in HTTP responses sent back to the client. + */ +public interface RequestOnly extends Views.Public {} diff --git a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/views/ResponseOnly.java b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/views/ResponseOnly.java new file mode 100644 index 000000000000..d49817913154 --- /dev/null +++ b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/views/ResponseOnly.java @@ -0,0 +1,8 @@ +package com.appsmith.external.views; + +/** + * Intended to mark entity/DTO fields that should be included as part of HTTP responses, but should + * be ignored as part of HTTP requests. For example, if a field is marked with this annotation, in + * a class used with {@code @RequestBody}, it's value will NOT be deserialized. + */ +public interface ResponseOnly extends Views.Public {} diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/controllers/ActionController.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/controllers/ActionController.java index 62d9ec7d33d0..ccff2b83bee5 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/controllers/ActionController.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/controllers/ActionController.java @@ -6,23 +6,19 @@ import com.appsmith.server.refactors.applications.RefactoringService; import com.appsmith.server.services.LayoutActionService; import com.appsmith.server.solutions.ActionExecutionSolution; -import io.micrometer.observation.ObservationRegistry; -import lombok.extern.slf4j.Slf4j; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController @RequestMapping(Url.ACTION_URL) -@Slf4j public class ActionController extends ActionControllerCE { public ActionController( LayoutActionService layoutActionService, NewActionService newActionService, RefactoringService refactoringService, - ActionExecutionSolution actionExecutionSolution, - ObservationRegistry observationRegistry) { + ActionExecutionSolution actionExecutionSolution) { - super(layoutActionService, newActionService, refactoringService, actionExecutionSolution, observationRegistry); + super(layoutActionService, newActionService, refactoringService, actionExecutionSolution); } } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/controllers/ce/ActionControllerCE.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/controllers/ce/ActionControllerCE.java index 6dc5d69ae205..30d360c091dc 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/controllers/ce/ActionControllerCE.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/controllers/ce/ActionControllerCE.java @@ -2,6 +2,7 @@ import com.appsmith.external.models.ActionDTO; import com.appsmith.external.models.ActionExecutionResult; +import com.appsmith.external.views.RequestOnly; import com.appsmith.external.views.Views; import com.appsmith.server.constants.FieldName; import com.appsmith.server.constants.Url; @@ -16,7 +17,6 @@ import com.appsmith.server.services.LayoutActionService; import com.appsmith.server.solutions.ActionExecutionSolution; import com.fasterxml.jackson.annotation.JsonView; -import io.micrometer.observation.ObservationRegistry; import jakarta.validation.Valid; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; @@ -48,30 +48,25 @@ public class ActionControllerCE { private final NewActionService newActionService; private final RefactoringService refactoringService; private final ActionExecutionSolution actionExecutionSolution; - private final ObservationRegistry observationRegistry; @Autowired public ActionControllerCE( LayoutActionService layoutActionService, NewActionService newActionService, RefactoringService refactoringService, - ActionExecutionSolution actionExecutionSolution, - ObservationRegistry observationRegistry) { + ActionExecutionSolution actionExecutionSolution) { this.layoutActionService = layoutActionService; this.newActionService = newActionService; this.refactoringService = refactoringService; this.actionExecutionSolution = actionExecutionSolution; - this.observationRegistry = observationRegistry; } @JsonView(Views.Public.class) @PostMapping @ResponseStatus(HttpStatus.CREATED) public Mono<ResponseDTO<ActionDTO>> createAction( - @Valid @RequestBody ActionDTO resource, - @RequestHeader(name = FieldName.BRANCH_NAME, required = false) String branchName, - @RequestHeader(name = "Origin", required = false) String originHeader, - ServerWebExchange exchange) { + @Valid @RequestBody @JsonView(RequestOnly.class) ActionDTO resource, + @RequestHeader(name = FieldName.BRANCH_NAME, required = false) String branchName) { log.debug("Going to create resource {}", resource.getClass().getName()); return layoutActionService .createSingleActionWithBranch(resource, branchName) @@ -82,7 +77,7 @@ public Mono<ResponseDTO<ActionDTO>> createAction( @PutMapping("/{defaultActionId}") public Mono<ResponseDTO<ActionDTO>> updateAction( @PathVariable String defaultActionId, - @Valid @RequestBody ActionDTO resource, + @Valid @RequestBody @JsonView(RequestOnly.class) ActionDTO resource, @RequestHeader(name = FieldName.BRANCH_NAME, required = false) String branchName) { log.debug("Going to update resource with defaultActionId: {}, branch: {}", defaultActionId, branchName); return layoutActionService @@ -178,9 +173,6 @@ public Mono<ResponseDTO<ActionDTO>> deleteAction( * <p> * The controller function is primarily used with param applicationId by the client to fetch the actions in edit * mode. - * - * @param params - * @return */ @JsonView(Views.Public.class) @GetMapping("")
e71876f3b60207ceb746dbc58b5f6f4a8658d6ea
2024-04-28 17:31:42
Shrikant Sharat Kandula
chore: Add search method to Bridge API (#32999)
false
Add search method to Bridge API (#32999)
chore
diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/helpers/ce/bridge/Bridge.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/helpers/ce/bridge/Bridge.java index aa979820ae54..a02683d6aaf8 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/helpers/ce/bridge/Bridge.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/helpers/ce/bridge/Bridge.java @@ -30,6 +30,13 @@ public static <T extends BaseDomain> BridgeQuery<T> or(BridgeQuery<T>... items) return q; } + public static <T extends BaseDomain> BridgeQuery<T> or(Collection<BridgeQuery<T>> items) { + final BridgeQuery<T> q = new BridgeQuery<>(); + q.checks.add( + new Criteria().orOperator(items.stream().map(c -> (Criteria) c).toList())); + return q; + } + @SafeVarargs public static <T extends BaseDomain> BridgeQuery<T> and(BridgeQuery<T>... items) { final BridgeQuery<T> q = new BridgeQuery<>(); @@ -72,10 +79,15 @@ public static <T extends BaseDomain> BridgeQuery<T> equal(@NonNull String key, b return Bridge.<T>query().equal(key, value); } + @Deprecated public static <T extends BaseDomain> BridgeQuery<T> regexMatchIgnoreCase(@NonNull String key, String regexPattern) { return Bridge.<T>query().regexMatchIgnoreCase(key, regexPattern); } + public static <T extends BaseDomain> BridgeQuery<T> searchIgnoreCase(@NonNull String key, @NonNull String needle) { + return Bridge.<T>query().searchIgnoreCase(key, needle); + } + public static <T extends BaseDomain> BridgeQuery<T> in(@NonNull String key, @NonNull Collection<String> value) { return Bridge.<T>query().in(key, value); } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/helpers/ce/bridge/BridgeQuery.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/helpers/ce/bridge/BridgeQuery.java index 335ab1f89fdd..a56fd39e8e90 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/helpers/ce/bridge/BridgeQuery.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/helpers/ce/bridge/BridgeQuery.java @@ -63,6 +63,15 @@ public BridgeQuery<T> regexMatchIgnoreCase(@NonNull String key, @NonNull String return this; } + public BridgeQuery<T> searchIgnoreCase(@NonNull String key, @NonNull String needle) { + if (key.contains(".")) { + throw new UnsupportedOperationException("Search-ignore-case is not supported for nested fields"); + } + + checks.add(Criteria.where(key).regex(".*" + Pattern.quote(needle) + ".*", "i")); + return this; + } + public BridgeQuery<T> in(@NonNull String key, @NonNull Collection<String> value) { checks.add(Criteria.where(key).in(value)); return this; diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/searchentities/SearchEntitySolutionCEImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/searchentities/SearchEntitySolutionCEImpl.java index eddd2004d216..7f969ae88aee 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/searchentities/SearchEntitySolutionCEImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/searchentities/SearchEntitySolutionCEImpl.java @@ -1,7 +1,6 @@ package com.appsmith.server.searchentities; import com.appsmith.server.applications.base.ApplicationService; -import com.appsmith.server.constants.FieldName; import com.appsmith.server.domains.Application; import com.appsmith.server.domains.Workspace; import com.appsmith.server.dtos.SearchEntityDTO; @@ -65,7 +64,7 @@ public Mono<SearchEntityDTO> searchEntity( if (shouldSearchEntity(Workspace.class, entities)) { workspacesMono = workspaceService .filterByEntityFieldsWithoutPublicAccess( - List.of(FieldName.NAME), + List.of(Workspace.Fields.name), searchString, pageable, sort, @@ -77,7 +76,7 @@ public Mono<SearchEntityDTO> searchEntity( if (shouldSearchEntity(Application.class, entities)) { applicationsMono = applicationService .filterByEntityFieldsWithoutPublicAccess( - List.of(FieldName.NAME), + List.of(Application.Fields.name), searchString, pageable, sort, diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/BaseService.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/BaseService.java index 4aa1cbc47c41..cf5f204e6aa7 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/BaseService.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/BaseService.java @@ -15,17 +15,16 @@ import lombok.extern.slf4j.Slf4j; import org.springframework.data.domain.Pageable; import org.springframework.data.domain.Sort; -import org.springframework.data.mongodb.core.query.Criteria; import org.springframework.util.MultiValueMap; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; import java.io.Serializable; import java.time.Instant; +import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; -import java.util.regex.Pattern; @Slf4j @RequiredArgsConstructor @@ -154,13 +153,15 @@ public Flux<T> filterByEntityFields( if (searchableEntityFields == null || searchableEntityFields.isEmpty()) { return Flux.error(new AppsmithException(AppsmithError.INVALID_PARAMETER, ENTITY_FIELDS)); } - List<Criteria> criteriaList = searchableEntityFields.stream() - .map(fieldName -> Criteria.where(fieldName).regex(".*" + Pattern.quote(searchString) + ".*", "i")) - .toList(); - Criteria criteria = new Criteria().orOperator(criteriaList); + + List<BridgeQuery<T>> criteria = new ArrayList<>(); + for (String fieldName : searchableEntityFields) { + criteria.add(Bridge.searchIgnoreCase(fieldName, searchString)); + } + Flux<T> result = repository .queryBuilder() - .criteria(criteria) + .criteria(Bridge.or(criteria)) .permission(permission) .sort(sort) .all(); @@ -190,14 +191,15 @@ public Flux<T> filterByEntityFieldsWithoutPublicAccess( if (searchableEntityFields == null || searchableEntityFields.isEmpty()) { return Flux.error(new AppsmithException(AppsmithError.INVALID_PARAMETER, ENTITY_FIELDS)); } - List<Criteria> criteriaList = searchableEntityFields.stream() - .map(fieldName -> Criteria.where(fieldName).regex(".*" + Pattern.quote(searchString) + ".*", "i")) - .toList(); - Criteria criteria = new Criteria().orOperator(criteriaList); + + List<BridgeQuery<T>> criteria = new ArrayList<>(); + for (String fieldName : searchableEntityFields) { + criteria.add(Bridge.searchIgnoreCase(fieldName, searchString)); + } Flux<T> result = repository .queryBuilder() - .criteria(criteria) + .criteria(Bridge.or(criteria)) .permission(permission) .sort(sort) .includeAnonymousUserPermissions(false)
b4570847e29be76eb7ebf706ee9b02fd8474abcb
2023-04-10 13:25:17
Shrikant Sharat Kandula
chore: Disable all caching during dev time (#22173)
false
Disable all caching during dev time (#22173)
chore
diff --git a/app/client/start-https.sh b/app/client/start-https.sh index 67a6f3a9577b..efe890d6eec6 100755 --- a/app/client/start-https.sh +++ b/app/client/start-https.sh @@ -262,6 +262,11 @@ $(if [[ $use_https == 1 ]]; then echo " # https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/frame-ancestors add_header Content-Security-Policy \"frame-ancestors ${APPSMITH_ALLOWED_FRAME_ANCESTORS-'self' *}\"; + # Disable caching completely. This is dev-time config, caching causes more problems than it solves. + # Taken from <https://stackoverflow.com/a/2068407/151048>. + add_header Cache-Control 'no-store, must-revalidate' always; + proxy_hide_header Cache-Control; # Hide it, if present in upstream's response. + sub_filter_once off; location / { proxy_pass $frontend;
2f2f5a6bf4e6965240a58318b62903590a3ee929
2024-09-25 16:29:21
Pawan Kumar
chore: Refactor API (#36412)
false
Refactor API (#36412)
chore
diff --git a/app/client/packages/utils/src/compose/compose.ts b/app/client/packages/utils/src/compose/compose.ts new file mode 100644 index 000000000000..3fd17574c163 --- /dev/null +++ b/app/client/packages/utils/src/compose/compose.ts @@ -0,0 +1,4 @@ +export const compose = + <T>(...fns: Array<(arg: T) => T>) => + (x: T) => + fns.reduce((acc, fn) => fn(acc), x); diff --git a/app/client/packages/utils/src/compose/index.ts b/app/client/packages/utils/src/compose/index.ts new file mode 100644 index 000000000000..cbcc7441207c --- /dev/null +++ b/app/client/packages/utils/src/compose/index.ts @@ -0,0 +1 @@ +export { compose } from "./compose"; diff --git a/app/client/packages/utils/src/index.ts b/app/client/packages/utils/src/index.ts index 7ea2e7134f23..442a65511ef1 100644 --- a/app/client/packages/utils/src/index.ts +++ b/app/client/packages/utils/src/index.ts @@ -1 +1,2 @@ export * from "./object"; +export * from "./compose"; diff --git a/app/client/src/api/Api.ts b/app/client/src/api/Api.ts index 206f38a1f55a..1eff364c4d04 100644 --- a/app/client/src/api/Api.ts +++ b/app/client/src/api/Api.ts @@ -1,15 +1,13 @@ -import type { AxiosInstance, AxiosRequestConfig } from "axios"; import axios from "axios"; -import { REQUEST_TIMEOUT_MS } from "ee/constants/ApiConstants"; -import { convertObjectToQueryParams } from "utils/URLUtils"; +import type { AxiosInstance, AxiosRequestConfig } from "axios"; import { - apiFailureResponseInterceptor, apiRequestInterceptor, + apiFailureResponseInterceptor, apiSuccessResponseInterceptor, - blockedApiRoutesForAirgapInterceptor, -} from "ee/api/ApiUtils"; +} from "./interceptors"; +import { REQUEST_TIMEOUT_MS } from "ee/constants/ApiConstants"; +import { convertObjectToQueryParams } from "utils/URLUtils"; -//TODO(abhinav): Refactor this to make more composable. export const apiRequestConfig = { baseURL: "/api/", timeout: REQUEST_TIMEOUT_MS, @@ -21,16 +19,7 @@ export const apiRequestConfig = { const axiosInstance: AxiosInstance = axios.create(); -const requestInterceptors = [ - blockedApiRoutesForAirgapInterceptor, - apiRequestInterceptor, -]; - -requestInterceptors.forEach((interceptor) => { - // TODO: Fix this the next time the file is edited - // eslint-disable-next-line @typescript-eslint/no-explicit-any - axiosInstance.interceptors.request.use(interceptor as any); -}); +axiosInstance.interceptors.request.use(apiRequestInterceptor); axiosInstance.interceptors.response.use( apiSuccessResponseInterceptor, diff --git a/app/client/src/api/ConsolidatedPageLoadApi.tsx b/app/client/src/api/ConsolidatedPageLoadApi.tsx deleted file mode 100644 index 473b9a093015..000000000000 --- a/app/client/src/api/ConsolidatedPageLoadApi.tsx +++ /dev/null @@ -1,26 +0,0 @@ -import Api from "./Api"; -import type { AxiosPromise } from "axios"; -import type { ApiResponse } from "api/ApiResponses"; - -import type { InitConsolidatedApi } from "sagas/InitSagas"; - -class ConsolidatedPageLoadApi extends Api { - static url = "v1/consolidated-api"; - static consolidatedApiViewUrl = `${ConsolidatedPageLoadApi.url}/view`; - static consolidatedApiEditUrl = `${ConsolidatedPageLoadApi.url}/edit`; - - static async getConsolidatedPageLoadDataView(params: { - applicationId?: string; - defaultPageId?: string; - }): Promise<AxiosPromise<ApiResponse<InitConsolidatedApi>>> { - return Api.get(ConsolidatedPageLoadApi.consolidatedApiViewUrl, params); - } - static async getConsolidatedPageLoadDataEdit(params: { - applicationId?: string; - defaultPageId?: string; - }): Promise<AxiosPromise<ApiResponse<InitConsolidatedApi>>> { - return Api.get(ConsolidatedPageLoadApi.consolidatedApiEditUrl, params); - } -} - -export default ConsolidatedPageLoadApi; diff --git a/app/client/src/api/__tests__/apiFailureResponseInterceptors.ts b/app/client/src/api/__tests__/apiFailureResponseInterceptors.ts new file mode 100644 index 000000000000..7802d608b81e --- /dev/null +++ b/app/client/src/api/__tests__/apiFailureResponseInterceptors.ts @@ -0,0 +1,225 @@ +import axios from "axios"; +import type { AxiosError } from "axios"; + +import { + apiFailureResponseInterceptor, + apiSuccessResponseInterceptor, +} from "api/interceptors"; +import type { ApiResponse } from "api/types"; +import { + createMessage, + ERROR_0, + ERROR_413, + ERROR_500, + SERVER_API_TIMEOUT_ERROR, +} from "ee/constants/messages"; +import { ERROR_CODES } from "ee/constants/ApiConstants"; +import { UserCancelledActionExecutionError } from "sagas/ActionExecution/errorUtils"; + +describe("Api success response interceptors", () => { + beforeAll(() => { + axios.interceptors.response.use( + apiSuccessResponseInterceptor, + apiFailureResponseInterceptor, + ); + }); + + it("checks 413 error", async () => { + axios.defaults.adapter = async () => { + return Promise.reject({ + response: { + status: 413, + }, + } as AxiosError); + }; + + try { + await axios.get("https://example.com"); + } catch (error) { + expect((error as AxiosError<ApiResponse>).response?.status).toBe(413); + expect((error as AxiosError<ApiResponse>).message).toBe( + createMessage(ERROR_413, 100), + ); + expect( + (error as AxiosError<ApiResponse> & { statusCode?: string }).statusCode, + ).toBe("AE-APP-4013"); + } + + axios.defaults.adapter = undefined; + }); + + it("checks the response message when request is made when user is offline", async () => { + const onlineGetter: jest.SpyInstance = jest.spyOn( + window.navigator, + "onLine", + "get", + ); + + onlineGetter.mockReturnValue(false); + axios.defaults.adapter = async () => { + return new Promise((resolve, reject) => { + reject({ + message: "Network Error", + } as AxiosError); + }); + }; + + try { + await axios.get("https://example.com"); + } catch (error) { + expect((error as AxiosError<ApiResponse>).message).toBe( + createMessage(ERROR_0), + ); + } + + onlineGetter.mockRestore(); + axios.defaults.adapter = undefined; + }); + + it("checks if it throws UserCancelledActionExecutionError user cancels the request ", async () => { + const cancelToken = axios.CancelToken.source(); + + axios.defaults.adapter = async () => { + return new Promise((resolve, reject) => { + cancelToken.cancel("User cancelled the request"); + + reject({ + message: "User cancelled the request", + } as AxiosError); + }); + }; + + try { + await axios.get("https://example.com", { + cancelToken: cancelToken.token, + }); + } catch (error) { + expect(error).toBeInstanceOf(UserCancelledActionExecutionError); + } + + axios.defaults.adapter = undefined; + }); + + it("checks the response message when request fails for exeuction action urls", async () => { + axios.defaults.adapter = async () => { + return Promise.reject({ + response: { + status: 500, + statusText: "Internal Server Error", + headers: { + "content-length": 1, + }, + config: { + headers: { + timer: "1000", + }, + }, + }, + config: { + url: "/v1/actions/execute", + }, + }); + }; + + const url = "/v1/actions/execute"; + const response = await axios.get(url); + + expect(response).toHaveProperty("clientMeta"); + + axios.defaults.adapter = undefined; + }); + + it("checks the error response in case of timeout", async () => { + axios.defaults.adapter = async () => { + return Promise.reject({ + code: "ECONNABORTED", + message: "timeout of 1000ms exceeded", + }); + }; + + try { + await axios.get("https://example.com"); + } catch (error) { + expect((error as AxiosError<ApiResponse>).message).toBe( + createMessage(SERVER_API_TIMEOUT_ERROR), + ); + expect((error as AxiosError<ApiResponse>).code).toBe( + ERROR_CODES.REQUEST_TIMEOUT, + ); + } + + axios.defaults.adapter = undefined; + }); + + it("checks the error response in case of server error", async () => { + axios.defaults.adapter = async () => { + return Promise.reject({ + response: { + status: 502, + }, + }); + }; + + try { + await axios.get("https://example.com"); + } catch (error) { + expect((error as AxiosError<ApiResponse>).message).toBe( + createMessage(ERROR_500), + ); + expect((error as AxiosError<ApiResponse>).code).toBe( + ERROR_CODES.SERVER_ERROR, + ); + } + + axios.defaults.adapter = undefined; + }); + + it("checks error response in case of unauthorized error", async () => { + axios.defaults.adapter = async () => { + return Promise.reject({ + response: { + status: 401, + }, + }); + }; + + try { + await axios.get("https://example.com"); + } catch (error) { + expect((error as AxiosError<ApiResponse>).message).toBe( + "Unauthorized. Redirecting to login page...", + ); + expect((error as AxiosError<ApiResponse>).code).toBe( + ERROR_CODES.REQUEST_NOT_AUTHORISED, + ); + } + }); + + it("checks error response in case of not found error", async () => { + axios.defaults.adapter = async () => { + return Promise.reject({ + response: { + data: { + responseMeta: { + status: 404, + error: { + code: "AE-ACL-4004", + }, + }, + }, + }, + }); + }; + + try { + await axios.get("https://example.com"); + } catch (error) { + expect((error as AxiosError<ApiResponse>).message).toBe( + "Resource Not Found", + ); + expect((error as AxiosError<ApiResponse>).code).toBe( + ERROR_CODES.PAGE_NOT_FOUND, + ); + } + }); +}); diff --git a/app/client/src/api/__tests__/apiRequestInterceptors.ts b/app/client/src/api/__tests__/apiRequestInterceptors.ts new file mode 100644 index 000000000000..8a90efc3d4ba --- /dev/null +++ b/app/client/src/api/__tests__/apiRequestInterceptors.ts @@ -0,0 +1,121 @@ +import axios from "axios"; +import { + addGitBranchHeader, + blockAirgappedRoutes, + addRequestedByHeader, + addEnvironmentHeader, + increaseGitApiTimeout, + addAnonymousUserIdHeader, + addPerformanceMonitoringHeaders, +} from "api/interceptors/request"; + +describe("Api request interceptors", () => { + beforeAll(() => { + axios.defaults.adapter = async (config) => { + return new Promise((resolve) => { + resolve({ + data: "Test data", + status: 200, + statusText: "OK", + headers: { + "content-length": 123, + "content-type": "application/json", + }, + config, + }); + }); + }; + }); + + it("checks if the request config has timer in the headers", async () => { + const url = "v1/actions/execute"; + const identifier = axios.interceptors.request.use( + addPerformanceMonitoringHeaders, + ); + const response = await axios.get(url); + + expect(response.config.headers).toHaveProperty("timer"); + + axios.interceptors.request.eject(identifier); + }); + + it("checks if the request config has anonymousUserId in the headers", async () => { + const url = "v1/actions/execute"; + const identifier = axios.interceptors.request.use((config) => + addAnonymousUserIdHeader(config, { + segmentEnabled: true, + anonymousId: "anonymousUserId", + }), + ); + const response = await axios.get(url); + + expect(response.config.headers).toHaveProperty("x-anonymous-user-id"); + expect(response.config.headers["x-anonymous-user-id"]).toBe( + "anonymousUserId", + ); + + axios.interceptors.request.eject(identifier); + }); + + it("checks if the request config has csrfToken in the headers", async () => { + const url = "v1/actions/execute"; + const identifier = axios.interceptors.request.use(addRequestedByHeader); + const response = await axios.post(url); + + expect(response.config.headers).toHaveProperty("X-Requested-By"); + expect(response.config.headers["X-Requested-By"]).toBe("Appsmith"); + + axios.interceptors.request.eject(identifier); + }); + + it("checks if the request config has gitBranch in the headers", async () => { + const url = "v1/"; + const identifier = axios.interceptors.request.use((config) => { + return addGitBranchHeader(config, { branch: "master" }); + }); + const response = await axios.get(url); + + expect(response.config.headers).toHaveProperty("branchName"); + expect(response.config.headers["branchName"]).toBe("master"); + + axios.interceptors.request.eject(identifier); + }); + + it("checks if the request config has environmentId in the headers", async () => { + const url = "v1/saas"; + const identifier = axios.interceptors.request.use((config) => { + return addEnvironmentHeader(config, { env: "default" }); + }); + + const response = await axios.get(url); + + expect(response.config.headers).toHaveProperty("X-Appsmith-EnvironmentId"); + expect(response.config.headers["X-Appsmith-EnvironmentId"]).toBe("default"); + + axios.interceptors.request.eject(identifier); + }); + + it("checks if request is 200 ok when isAirgapped is true", async () => { + const url = "v1/saas"; + const identifier = axios.interceptors.request.use((config) => { + return blockAirgappedRoutes(config, { isAirgapped: true }); + }); + const response = await axios.get(url); + + expect(response.data).toBeNull(); + expect(response.status).toBe(200); + expect(response.statusText).toBe("OK"); + + axios.interceptors.request.eject(identifier); + }); + + it("checks if the request config has a timeout of 120s", async () => { + const url = "v1/git/"; + const identifier = axios.interceptors.request.use(increaseGitApiTimeout); + const response = await axios.get(url); + + expect(response.config.timeout).toBe(120000); + + axios.interceptors.request.eject(identifier); + }); +}); diff --git a/app/client/src/api/__tests__/apiSucessResponseInterceptors.ts b/app/client/src/api/__tests__/apiSucessResponseInterceptors.ts new file mode 100644 index 000000000000..1b8963577d41 --- /dev/null +++ b/app/client/src/api/__tests__/apiSucessResponseInterceptors.ts @@ -0,0 +1,40 @@ +import axios from "axios"; +import { apiSuccessResponseInterceptor } from "api/interceptors"; + +describe("Api success response interceptors", () => { + beforeAll(() => { + axios.interceptors.response.use(apiSuccessResponseInterceptor); + axios.defaults.adapter = async (config) => { + return new Promise((resolve) => { + resolve({ + data: { + data: "Test data", + }, + status: 200, + statusText: "OK", + headers: { + "content-length": 123, + "content-type": "application/json", + }, + config, + }); + }); + }; + }); + + it("checks response for non-action-execution url", async () => { + const url = "/v1/sass"; + const response = await axios.get(url); + + expect(response.data).toBe("Test data"); + }); + + it("checks response for action-execution url", async () => { + const url = "/v1/actions/execute"; + const response = await axios.get(url); + + expect(response).toHaveProperty("data"); + expect(response.data).toBe("Test data"); + expect(response).toHaveProperty("clientMeta"); + }); +}); diff --git a/app/client/src/api/core/api.ts b/app/client/src/api/core/api.ts new file mode 100644 index 000000000000..ecfb9e74f099 --- /dev/null +++ b/app/client/src/api/core/api.ts @@ -0,0 +1,31 @@ +import type { AxiosResponseData } from "api/types"; + +import { apiFactory } from "./factory"; + +const apiInstance = apiFactory(); + +export async function get<T>(...args: Parameters<typeof apiInstance.get>) { + // Note: we are passing AxiosResponseData as the second type argument to set the default type of the response data.The reason + // is we modify the response data in the responseSuccessInterceptor to return `.data` property from the axios response so that we can + // just `response.data` instead of `response.data.data`. So we have to make sure that the response data's type matches what we do in the interceptor. + return apiInstance.get<T, AxiosResponseData<T>>(...args); +} + +export async function post<T>(...args: Parameters<typeof apiInstance.post>) { + return apiInstance.post<T, AxiosResponseData<T>>(...args); +} + +export async function put<T>(...args: Parameters<typeof apiInstance.put>) { + return apiInstance.put<T, AxiosResponseData<T>>(...args); +} + +// Note: _delete is used instead of delete because delete is a reserved keyword in JavaScript +async function _delete<T>(...args: Parameters<typeof apiInstance.delete>) { + return apiInstance.delete<T, AxiosResponseData<T>>(...args); +} + +export { _delete as delete }; + +export async function patch<T>(...args: Parameters<typeof apiInstance.patch>) { + return apiInstance.patch<T, AxiosResponseData<T>>(...args); +} diff --git a/app/client/src/api/core/factory.ts b/app/client/src/api/core/factory.ts new file mode 100644 index 000000000000..b0b75ada3885 --- /dev/null +++ b/app/client/src/api/core/factory.ts @@ -0,0 +1,17 @@ +import axios from "axios"; +import { DEFAULT_AXIOS_CONFIG } from "ee/constants/ApiConstants"; +import { apiRequestInterceptor } from "api/interceptors/request/apiRequestInterceptor"; +import { apiSuccessResponseInterceptor } from "api/interceptors/response/apiSuccessResponseInterceptor"; +import { apiFailureResponseInterceptor } from "api/interceptors/response/apiFailureResponseInterceptor"; + +export function apiFactory() { + const axiosInstance = axios.create(DEFAULT_AXIOS_CONFIG); + + axiosInstance.interceptors.request.use(apiRequestInterceptor); + axiosInstance.interceptors.response.use( + apiSuccessResponseInterceptor, + apiFailureResponseInterceptor, + ); + + return axiosInstance; +} diff --git a/app/client/src/api/core/index.ts b/app/client/src/api/core/index.ts new file mode 100644 index 000000000000..ed3655362f50 --- /dev/null +++ b/app/client/src/api/core/index.ts @@ -0,0 +1,2 @@ +export * as api from "./api"; +export { apiFactory } from "./factory"; diff --git a/app/client/src/api/helpers/addExecutionMetaProperties.ts b/app/client/src/api/helpers/addExecutionMetaProperties.ts new file mode 100644 index 000000000000..e4fba5c6152e --- /dev/null +++ b/app/client/src/api/helpers/addExecutionMetaProperties.ts @@ -0,0 +1,12 @@ +import type { AxiosResponse } from "axios"; + +export const addExecutionMetaProperties = (response: AxiosResponse) => { + const clientMeta = { + size: response.headers["content-length"], + duration: Number( + performance.now() - response.config.headers.timer, + ).toFixed(), + }; + + return { ...response.data, clientMeta }; +}; diff --git a/app/client/src/api/helpers/index.ts b/app/client/src/api/helpers/index.ts new file mode 100644 index 000000000000..1cd96da7b8cb --- /dev/null +++ b/app/client/src/api/helpers/index.ts @@ -0,0 +1,3 @@ +export { is404orAuthPath } from "./is404orAuthPath"; +export { validateJsonResponseMeta } from "./validateJsonResponseMeta"; +export { addExecutionMetaProperties } from "./addExecutionMetaProperties"; diff --git a/app/client/src/api/helpers/is404orAuthPath.ts b/app/client/src/api/helpers/is404orAuthPath.ts new file mode 100644 index 000000000000..10d4193ebbc1 --- /dev/null +++ b/app/client/src/api/helpers/is404orAuthPath.ts @@ -0,0 +1,5 @@ +export const is404orAuthPath = () => { + const pathName = window.location.pathname; + + return /^\/404/.test(pathName) || /^\/user\/\w+/.test(pathName); +}; diff --git a/app/client/src/api/helpers/validateJsonResponseMeta.ts b/app/client/src/api/helpers/validateJsonResponseMeta.ts new file mode 100644 index 000000000000..de295660abdb --- /dev/null +++ b/app/client/src/api/helpers/validateJsonResponseMeta.ts @@ -0,0 +1,14 @@ +import * as Sentry from "@sentry/react"; +import type { AxiosResponse } from "axios"; +import { CONTENT_TYPE_HEADER_KEY } from "constants/ApiEditorConstants/CommonApiConstants"; + +export const validateJsonResponseMeta = (response: AxiosResponse) => { + if ( + response.headers[CONTENT_TYPE_HEADER_KEY] === "application/json" && + !response.data.responseMeta + ) { + Sentry.captureException(new Error("Api responded without response meta"), { + contexts: { response: response.data }, + }); + } +}; diff --git a/app/client/src/api/index.ts b/app/client/src/api/index.ts new file mode 100644 index 000000000000..b2221a94a89f --- /dev/null +++ b/app/client/src/api/index.ts @@ -0,0 +1 @@ +export * from "./services"; diff --git a/app/client/src/api/interceptors/index.ts b/app/client/src/api/interceptors/index.ts new file mode 100644 index 000000000000..346dac3b386b --- /dev/null +++ b/app/client/src/api/interceptors/index.ts @@ -0,0 +1,2 @@ +export * from "./request"; +export * from "./response"; diff --git a/app/client/src/api/interceptors/request/addAnonymousUserIdHeader.ts b/app/client/src/api/interceptors/request/addAnonymousUserIdHeader.ts new file mode 100644 index 000000000000..d87e95c63072 --- /dev/null +++ b/app/client/src/api/interceptors/request/addAnonymousUserIdHeader.ts @@ -0,0 +1,16 @@ +import type { InternalAxiosRequestConfig } from "axios"; + +export const addAnonymousUserIdHeader = ( + config: InternalAxiosRequestConfig, + options: { anonymousId?: string; segmentEnabled?: boolean }, +) => { + const { anonymousId, segmentEnabled } = options; + + config.headers = config.headers || {}; + + if (segmentEnabled && anonymousId) { + config.headers["x-anonymous-user-id"] = anonymousId; + } + + return config; +}; diff --git a/app/client/src/api/interceptors/request/addEnvironmentHeader.ts b/app/client/src/api/interceptors/request/addEnvironmentHeader.ts new file mode 100644 index 000000000000..82c9d89fc418 --- /dev/null +++ b/app/client/src/api/interceptors/request/addEnvironmentHeader.ts @@ -0,0 +1,19 @@ +import type { InternalAxiosRequestConfig } from "axios"; +import { ENV_ENABLED_ROUTES_REGEX } from "ee/constants/ApiConstants"; + +export const addEnvironmentHeader = ( + config: InternalAxiosRequestConfig, + options: { env: string }, +) => { + const { env } = options; + + config.headers = config.headers || {}; + + if (ENV_ENABLED_ROUTES_REGEX.test(config.url?.split("?")[0] || "")) { + if (env) { + config.headers["X-Appsmith-EnvironmentId"] = env; + } + } + + return config; +}; diff --git a/app/client/src/api/interceptors/request/addGitBranchHeader.ts b/app/client/src/api/interceptors/request/addGitBranchHeader.ts new file mode 100644 index 000000000000..b15105bcb833 --- /dev/null +++ b/app/client/src/api/interceptors/request/addGitBranchHeader.ts @@ -0,0 +1,16 @@ +import type { InternalAxiosRequestConfig } from "axios"; + +export const addGitBranchHeader = ( + config: InternalAxiosRequestConfig, + options: { branch?: string }, +) => { + const { branch } = options; + + config.headers = config.headers || {}; + + if (branch) { + config.headers.branchName = branch; + } + + return config; +}; diff --git a/app/client/src/api/interceptors/request/addPerformanceMonitoringHeaders.ts b/app/client/src/api/interceptors/request/addPerformanceMonitoringHeaders.ts new file mode 100644 index 000000000000..53ec7ad1bdef --- /dev/null +++ b/app/client/src/api/interceptors/request/addPerformanceMonitoringHeaders.ts @@ -0,0 +1,10 @@ +import type { InternalAxiosRequestConfig } from "axios"; + +export const addPerformanceMonitoringHeaders = ( + config: InternalAxiosRequestConfig, +) => { + config.headers = config.headers || {}; + config.headers["timer"] = performance.now(); + + return config; +}; diff --git a/app/client/src/api/interceptors/request/addRequestedByHeader.ts b/app/client/src/api/interceptors/request/addRequestedByHeader.ts new file mode 100644 index 000000000000..c64a363dc87c --- /dev/null +++ b/app/client/src/api/interceptors/request/addRequestedByHeader.ts @@ -0,0 +1,13 @@ +import type { InternalAxiosRequestConfig } from "axios"; + +export const addRequestedByHeader = (config: InternalAxiosRequestConfig) => { + config.headers = config.headers || {}; + + const methodUpper = config.method?.toUpperCase(); + + if (methodUpper && methodUpper !== "GET" && methodUpper !== "HEAD") { + config.headers["X-Requested-By"] = "Appsmith"; + } + + return config; +}; diff --git a/app/client/src/api/interceptors/request/apiRequestInterceptor.ts b/app/client/src/api/interceptors/request/apiRequestInterceptor.ts new file mode 100644 index 000000000000..8f7919c067dc --- /dev/null +++ b/app/client/src/api/interceptors/request/apiRequestInterceptor.ts @@ -0,0 +1,64 @@ +import store from "store"; +import { compose } from "@appsmith/utils"; +import { getAppsmithConfigs } from "ee/configs"; +import AnalyticsUtil from "ee/utils/AnalyticsUtil"; +import { isAirgapped } from "ee/utils/airgapHelpers"; +import type { InternalAxiosRequestConfig } from "axios"; + +import getQueryParamsObject from "utils/getQueryParamsObject"; +import { addRequestedByHeader } from "./addRequestedByHeader"; +import { increaseGitApiTimeout } from "./increaseGitApiTimeout"; +import { getCurrentGitBranch } from "selectors/gitSyncSelectors"; +import { getCurrentEnvironmentId } from "ee/selectors/environmentSelectors"; +import { addGitBranchHeader as _addGitBranchHeader } from "./addGitBranchHeader"; +import { addPerformanceMonitoringHeaders } from "./addPerformanceMonitoringHeaders"; +import { addEnvironmentHeader as _addEnvironmentHeader } from "./addEnvironmentHeader"; +import { blockAirgappedRoutes as _blockAirgappedRoutes } from "./blockAirgappedRoutes"; +import { addAnonymousUserIdHeader as _addAnonymousUserIdHeader } from "./addAnonymousUserIdHeader"; + +/** + * Note: Why can't we use store.getState() or isGapgapped() directly in the interceptor? + * The main reason is to easily test the interceptor. When we use store.getState() or isAirgapped() directly in the interceptor, + * we need to mock the store or isAirgapped() in the test file and it becomes difficult and messy mocking things just to test the interceptor. + */ +const blockAirgappedRoutes = (config: InternalAxiosRequestConfig) => { + const isAirgappedInstance = isAirgapped(); + + return _blockAirgappedRoutes(config, { isAirgapped: isAirgappedInstance }); +}; + +const addGitBranchHeader = (config: InternalAxiosRequestConfig) => { + const state = store.getState(); + const branch = getCurrentGitBranch(state) || getQueryParamsObject().branch; + + return _addGitBranchHeader(config, { branch }); +}; + +const addEnvironmentHeader = (config: InternalAxiosRequestConfig) => { + const state = store.getState(); + const activeEnv = getCurrentEnvironmentId(state); + + return _addEnvironmentHeader(config, { env: activeEnv }); +}; + +const addAnonymousUserIdHeader = (config: InternalAxiosRequestConfig) => { + const appsmithConfig = getAppsmithConfigs(); + const anonymousId = AnalyticsUtil.getAnonymousId(); + const segmentEnabled = appsmithConfig.segment.enabled; + + return _addAnonymousUserIdHeader(config, { anonymousId, segmentEnabled }); +}; + +export const apiRequestInterceptor = (config: InternalAxiosRequestConfig) => { + const interceptorPipeline = compose<InternalAxiosRequestConfig>( + blockAirgappedRoutes, + addRequestedByHeader, + addGitBranchHeader, + increaseGitApiTimeout, + addEnvironmentHeader, + addAnonymousUserIdHeader, + addPerformanceMonitoringHeaders, + ); + + return interceptorPipeline(config); +}; diff --git a/app/client/src/api/interceptors/request/blockAirgappedRoutes.ts b/app/client/src/api/interceptors/request/blockAirgappedRoutes.ts new file mode 100644 index 000000000000..d8d4d54ee805 --- /dev/null +++ b/app/client/src/api/interceptors/request/blockAirgappedRoutes.ts @@ -0,0 +1,29 @@ +import type { InternalAxiosRequestConfig } from "axios"; +import { BLOCKED_ROUTES_REGEX } from "ee/constants/ApiConstants"; + +const blockAirgappedRoutes = ( + request: InternalAxiosRequestConfig, + options: { isAirgapped: boolean }, +) => { + const { url } = request; + const { isAirgapped } = options; + + if (isAirgapped && url && BLOCKED_ROUTES_REGEX.test(url)) { + request.adapter = async (config) => { + return new Promise((resolve) => { + resolve({ + data: null, + status: 200, + statusText: "OK", + headers: {}, + config, + request, + }); + }); + }; + } + + return request; +}; + +export { blockAirgappedRoutes }; diff --git a/app/client/src/api/interceptors/request/increaseGitApiTimeout.ts b/app/client/src/api/interceptors/request/increaseGitApiTimeout.ts new file mode 100644 index 000000000000..4aa20d7611cd --- /dev/null +++ b/app/client/src/api/interceptors/request/increaseGitApiTimeout.ts @@ -0,0 +1,9 @@ +import type { InternalAxiosRequestConfig } from "axios"; + +export const increaseGitApiTimeout = (config: InternalAxiosRequestConfig) => { + if (config.url?.indexOf("/git/") !== -1) { + config.timeout = 1000 * 120; + } + + return config; +}; diff --git a/app/client/src/api/interceptors/request/index.ts b/app/client/src/api/interceptors/request/index.ts new file mode 100644 index 000000000000..6f9957f00ec2 --- /dev/null +++ b/app/client/src/api/interceptors/request/index.ts @@ -0,0 +1,8 @@ +export { addGitBranchHeader } from "./addGitBranchHeader"; +export { blockAirgappedRoutes } from "./blockAirgappedRoutes"; +export { addRequestedByHeader } from "./addRequestedByHeader"; +export { addEnvironmentHeader } from "./addEnvironmentHeader"; +export { apiRequestInterceptor } from "./apiRequestInterceptor"; +export { increaseGitApiTimeout } from "./increaseGitApiTimeout"; +export { addAnonymousUserIdHeader } from "./addAnonymousUserIdHeader"; +export { addPerformanceMonitoringHeaders } from "./addPerformanceMonitoringHeaders"; diff --git a/app/client/src/api/interceptors/response/apiFailureResponseInterceptor.ts b/app/client/src/api/interceptors/response/apiFailureResponseInterceptor.ts new file mode 100644 index 000000000000..eae6f6162126 --- /dev/null +++ b/app/client/src/api/interceptors/response/apiFailureResponseInterceptor.ts @@ -0,0 +1,33 @@ +import type { AxiosError } from "axios"; +import type { ApiResponse, ErrorHandler } from "api/types"; + +import * as failureHandlers from "./failureHandlers"; + +export const apiFailureResponseInterceptor = async ( + error: AxiosError<ApiResponse>, +) => { + const handlers: ErrorHandler[] = [ + failureHandlers.handle413Error, + failureHandlers.handleOfflineError, + failureHandlers.handleCancelError, + failureHandlers.handleExecuteActionError, + failureHandlers.handleTimeoutError, + failureHandlers.handleServerError, + failureHandlers.handleUnauthorizedError, + failureHandlers.handleNotFoundError, + ]; + + for (const handler of handlers) { + const result = await handler(error); + + if (result !== null) { + return result; + } + } + + if (error?.response?.data.responseMeta) { + return Promise.resolve(error.response.data); + } + + return Promise.resolve(error); +}; diff --git a/app/client/src/api/interceptors/response/apiSuccessResponseInterceptor.ts b/app/client/src/api/interceptors/response/apiSuccessResponseInterceptor.ts new file mode 100644 index 000000000000..ca18a9ea4329 --- /dev/null +++ b/app/client/src/api/interceptors/response/apiSuccessResponseInterceptor.ts @@ -0,0 +1,16 @@ +import { + validateJsonResponseMeta, + addExecutionMetaProperties, +} from "api/helpers"; +import type { AxiosResponse } from "axios"; +import { EXECUTION_ACTION_REGEX } from "ee/constants/ApiConstants"; + +export const apiSuccessResponseInterceptor = (response: AxiosResponse) => { + if (response?.config?.url?.match(EXECUTION_ACTION_REGEX)) { + return addExecutionMetaProperties(response); + } + + validateJsonResponseMeta(response); + + return response.data; +}; diff --git a/app/client/src/api/interceptors/response/failureHandlers/handle413Error.ts b/app/client/src/api/interceptors/response/failureHandlers/handle413Error.ts new file mode 100644 index 000000000000..301b1c2c97a8 --- /dev/null +++ b/app/client/src/api/interceptors/response/failureHandlers/handle413Error.ts @@ -0,0 +1,25 @@ +import type { AxiosError } from "axios"; +import { + createMessage, + ERROR_413, + GENERIC_API_EXECUTION_ERROR, +} from "ee/constants/messages"; + +export const handle413Error = async (error: AxiosError) => { + if (error?.response?.status === 413) { + return Promise.reject({ + ...error, + clientDefinedError: true, + statusCode: "AE-APP-4013", + message: createMessage(ERROR_413, 100), + pluginErrorDetails: { + appsmithErrorCode: "AE-APP-4013", + appsmithErrorMessage: createMessage(ERROR_413, 100), + errorType: "INTERNAL_ERROR", // this value is from the server, hence cannot construct enum type. + title: createMessage(GENERIC_API_EXECUTION_ERROR), + }, + }); + } + + return null; +}; diff --git a/app/client/src/api/interceptors/response/failureHandlers/handleCancelError.ts b/app/client/src/api/interceptors/response/failureHandlers/handleCancelError.ts new file mode 100644 index 000000000000..f579d8bc90b4 --- /dev/null +++ b/app/client/src/api/interceptors/response/failureHandlers/handleCancelError.ts @@ -0,0 +1,11 @@ +import axios from "axios"; +import type { AxiosError } from "axios"; +import { UserCancelledActionExecutionError } from "sagas/ActionExecution/errorUtils"; + +export async function handleCancelError(error: AxiosError) { + if (axios.isCancel(error)) { + throw new UserCancelledActionExecutionError(); + } + + return null; +} diff --git a/app/client/src/api/interceptors/response/failureHandlers/handleExecuteActionError.ts b/app/client/src/api/interceptors/response/failureHandlers/handleExecuteActionError.ts new file mode 100644 index 000000000000..6a1e0c4f277d --- /dev/null +++ b/app/client/src/api/interceptors/response/failureHandlers/handleExecuteActionError.ts @@ -0,0 +1,14 @@ +import type { AxiosError, AxiosResponse } from "axios"; +import { addExecutionMetaProperties } from "api/helpers"; +import { EXECUTION_ACTION_REGEX } from "ee/constants/ApiConstants"; + +export function handleExecuteActionError(error: AxiosError) { + const isExecutionActionURL = + error.config && error?.config?.url?.match(EXECUTION_ACTION_REGEX); + + if (isExecutionActionURL) { + return addExecutionMetaProperties(error?.response as AxiosResponse); + } + + return null; +} diff --git a/app/client/src/api/interceptors/response/failureHandlers/handleMissingResponseMeta.ts b/app/client/src/api/interceptors/response/failureHandlers/handleMissingResponseMeta.ts new file mode 100644 index 000000000000..4153a6f868bc --- /dev/null +++ b/app/client/src/api/interceptors/response/failureHandlers/handleMissingResponseMeta.ts @@ -0,0 +1,17 @@ +import type { AxiosError } from "axios"; +import * as Sentry from "@sentry/react"; +import type { ApiResponse } from "api/types"; + +export const handleMissingResponseMeta = async ( + error: AxiosError<ApiResponse>, +) => { + if (error.response?.data && !error.response.data.responseMeta) { + Sentry.captureException(new Error("Api responded without response meta"), { + contexts: { response: { ...error.response.data } }, + }); + + return Promise.reject(error.response.data); + } + + return null; +}; diff --git a/app/client/src/api/interceptors/response/failureHandlers/handleNotFoundError.ts b/app/client/src/api/interceptors/response/failureHandlers/handleNotFoundError.ts new file mode 100644 index 000000000000..21e2aa42f313 --- /dev/null +++ b/app/client/src/api/interceptors/response/failureHandlers/handleNotFoundError.ts @@ -0,0 +1,34 @@ +import { + API_STATUS_CODES, + ERROR_CODES, + SERVER_ERROR_CODES, +} from "ee/constants/ApiConstants"; +import * as Sentry from "@sentry/react"; +import type { AxiosError } from "axios"; +import type { ApiResponse } from "api/types"; +import { is404orAuthPath } from "api/helpers"; + +export async function handleNotFoundError(error: AxiosError<ApiResponse>) { + if (is404orAuthPath()) return null; + + const errorData = + error?.response?.data.responseMeta ?? ({} as ApiResponse["responseMeta"]); + + if ( + errorData.status === API_STATUS_CODES.RESOURCE_NOT_FOUND && + errorData.error?.code && + (SERVER_ERROR_CODES.RESOURCE_NOT_FOUND.includes(errorData.error?.code) || + SERVER_ERROR_CODES.UNABLE_TO_FIND_PAGE.includes(errorData?.error?.code)) + ) { + Sentry.captureException(error); + + return Promise.reject({ + ...error, + code: ERROR_CODES.PAGE_NOT_FOUND, + message: "Resource Not Found", + show: false, + }); + } + + return null; +} diff --git a/app/client/src/api/interceptors/response/failureHandlers/handleOfflineError.ts b/app/client/src/api/interceptors/response/failureHandlers/handleOfflineError.ts new file mode 100644 index 000000000000..2fa9fa16492f --- /dev/null +++ b/app/client/src/api/interceptors/response/failureHandlers/handleOfflineError.ts @@ -0,0 +1,13 @@ +import type { AxiosError } from "axios"; +import { createMessage, ERROR_0 } from "ee/constants/messages"; + +export const handleOfflineError = async (error: AxiosError) => { + if (!window.navigator.onLine) { + return Promise.reject({ + ...error, + message: createMessage(ERROR_0), + }); + } + + return null; +}; diff --git a/app/client/src/api/interceptors/response/failureHandlers/handleServerError.ts b/app/client/src/api/interceptors/response/failureHandlers/handleServerError.ts new file mode 100644 index 000000000000..2092d72b0079 --- /dev/null +++ b/app/client/src/api/interceptors/response/failureHandlers/handleServerError.ts @@ -0,0 +1,15 @@ +import type { AxiosError } from "axios"; +import { createMessage, ERROR_500 } from "ee/constants/messages"; +import { API_STATUS_CODES, ERROR_CODES } from "ee/constants/ApiConstants"; + +export const handleServerError = async (error: AxiosError) => { + if (error.response?.status === API_STATUS_CODES.SERVER_ERROR) { + return Promise.reject({ + ...error, + code: ERROR_CODES.SERVER_ERROR, + message: createMessage(ERROR_500), + }); + } + + return null; +}; diff --git a/app/client/src/api/interceptors/response/failureHandlers/handleTimeoutError.ts b/app/client/src/api/interceptors/response/failureHandlers/handleTimeoutError.ts new file mode 100644 index 000000000000..ffff3eafe768 --- /dev/null +++ b/app/client/src/api/interceptors/response/failureHandlers/handleTimeoutError.ts @@ -0,0 +1,22 @@ +import type { AxiosError } from "axios"; +import { + ERROR_CODES, + TIMEOUT_ERROR_REGEX, + AXIOS_CONNECTION_ABORTED_CODE, +} from "ee/constants/ApiConstants"; +import { createMessage, SERVER_API_TIMEOUT_ERROR } from "ee/constants/messages"; + +export const handleTimeoutError = async (error: AxiosError) => { + if ( + error.code === AXIOS_CONNECTION_ABORTED_CODE && + error.message?.match(TIMEOUT_ERROR_REGEX) + ) { + return Promise.reject({ + ...error, + message: createMessage(SERVER_API_TIMEOUT_ERROR), + code: ERROR_CODES.REQUEST_TIMEOUT, + }); + } + + return null; +}; diff --git a/app/client/src/api/interceptors/response/failureHandlers/handleUnauthorizedError.ts b/app/client/src/api/interceptors/response/failureHandlers/handleUnauthorizedError.ts new file mode 100644 index 000000000000..343ec7022e48 --- /dev/null +++ b/app/client/src/api/interceptors/response/failureHandlers/handleUnauthorizedError.ts @@ -0,0 +1,34 @@ +import store from "store"; +import type { AxiosError } from "axios"; +import * as Sentry from "@sentry/react"; +import { is404orAuthPath } from "api/helpers"; +import { logoutUser } from "actions/userActions"; +import { AUTH_LOGIN_URL } from "constants/routes"; +import { API_STATUS_CODES, ERROR_CODES } from "ee/constants/ApiConstants"; + +export const handleUnauthorizedError = async (error: AxiosError) => { + if (is404orAuthPath()) return null; + + if (error.response?.status === API_STATUS_CODES.REQUEST_NOT_AUTHORISED) { + const currentUrl = `${window.location.href}`; + + store.dispatch( + logoutUser({ + redirectURL: `${AUTH_LOGIN_URL}?redirectUrl=${encodeURIComponent( + currentUrl, + )}`, + }), + ); + + Sentry.captureException(error); + + return Promise.reject({ + ...error, + code: ERROR_CODES.REQUEST_NOT_AUTHORISED, + message: "Unauthorized. Redirecting to login page...", + show: false, + }); + } + + return null; +}; diff --git a/app/client/src/api/interceptors/response/failureHandlers/index.ts b/app/client/src/api/interceptors/response/failureHandlers/index.ts new file mode 100644 index 000000000000..2352095f1deb --- /dev/null +++ b/app/client/src/api/interceptors/response/failureHandlers/index.ts @@ -0,0 +1,9 @@ +export { handle413Error } from "./handle413Error"; +export { handleServerError } from "./handleServerError"; +export { handleCancelError } from "./handleCancelError"; +export { handleOfflineError } from "./handleOfflineError"; +export { handleTimeoutError } from "./handleTimeoutError"; +export { handleNotFoundError } from "./handleNotFoundError"; +export { handleUnauthorizedError } from "./handleUnauthorizedError"; +export { handleExecuteActionError } from "./handleExecuteActionError"; +export { handleMissingResponseMeta } from "./handleMissingResponseMeta"; diff --git a/app/client/src/api/interceptors/response/index.ts b/app/client/src/api/interceptors/response/index.ts new file mode 100644 index 000000000000..5177d545922d --- /dev/null +++ b/app/client/src/api/interceptors/response/index.ts @@ -0,0 +1,2 @@ +export { apiFailureResponseInterceptor } from "./apiFailureResponseInterceptor"; +export { apiSuccessResponseInterceptor } from "./apiSuccessResponseInterceptor"; diff --git a/app/client/src/api/services/AppThemingApi/api.ts b/app/client/src/api/services/AppThemingApi/api.ts new file mode 100644 index 000000000000..e7d22dfed85c --- /dev/null +++ b/app/client/src/api/services/AppThemingApi/api.ts @@ -0,0 +1,38 @@ +import { api } from "api/core"; +import type { AppTheme } from "entities/AppTheming"; + +const baseURL = "/v1"; + +export async function fetchThemes(applicationId: string) { + const url = `${baseURL}/themes/applications/${applicationId}`; + + return api.get<AppTheme[]>(url); +} + +export async function fetchSelected(applicationId: string, mode = "EDIT") { + const url = `${baseURL}/themes/applications/${applicationId}/current`; + + return api.get<AppTheme[]>(url, { params: { mode } }); +} + +export async function updateTheme(applicationId: string, theme: AppTheme) { + const url = `${baseURL}/themes/applications/${applicationId}`; + const payload = { + ...theme, + new: undefined, + }; + + return api.put<AppTheme[]>(url, payload); +} + +export async function changeTheme(applicationId: string, theme: AppTheme) { + const url = `${baseURL}/applications/${applicationId}/themes/${theme.id}`; + + return api.patch<AppTheme[]>(url, theme); +} + +export async function deleteTheme(themeId: string) { + const url = `${baseURL}/themes/${themeId}`; + + return api.delete<AppTheme[]>(url); +} diff --git a/app/client/src/api/services/AppThemingApi/index.ts b/app/client/src/api/services/AppThemingApi/index.ts new file mode 100644 index 000000000000..d158c5764011 --- /dev/null +++ b/app/client/src/api/services/AppThemingApi/index.ts @@ -0,0 +1 @@ +export * from "./api"; diff --git a/app/client/src/api/services/ConsolidatedPageLoadApi/api.ts b/app/client/src/api/services/ConsolidatedPageLoadApi/api.ts new file mode 100644 index 000000000000..4772853c901e --- /dev/null +++ b/app/client/src/api/services/ConsolidatedPageLoadApi/api.ts @@ -0,0 +1,20 @@ +import { api } from "api/core"; +import type { InitConsolidatedApi } from "sagas/InitSagas"; + +const BASE_URL = "v1/consolidated-api"; +const VIEW_URL = `${BASE_URL}/view`; +const EDIT_URL = `${BASE_URL}/edit`; + +export const getConsolidatedPageLoadDataView = async (params: { + applicationId?: string; + defaultPageId?: string; +}) => { + return api.get<InitConsolidatedApi>(VIEW_URL, { params }); +}; + +export const getConsolidatedPageLoadDataEdit = async (params: { + applicationId?: string; + defaultPageId?: string; +}) => { + return api.get<InitConsolidatedApi>(EDIT_URL, { params }); +}; diff --git a/app/client/src/api/services/ConsolidatedPageLoadApi/index.ts b/app/client/src/api/services/ConsolidatedPageLoadApi/index.ts new file mode 100644 index 000000000000..d158c5764011 --- /dev/null +++ b/app/client/src/api/services/ConsolidatedPageLoadApi/index.ts @@ -0,0 +1 @@ +export * from "./api"; diff --git a/app/client/src/api/services/index.ts b/app/client/src/api/services/index.ts new file mode 100644 index 000000000000..b1e3b877481d --- /dev/null +++ b/app/client/src/api/services/index.ts @@ -0,0 +1,2 @@ +export * as AppThemingApi from "./AppThemingApi"; +export * as ConsolidatedPageLoadApi from "./ConsolidatedPageLoadApi"; diff --git a/app/client/src/api/types.ts b/app/client/src/api/types.ts new file mode 100644 index 000000000000..4ce60997efff --- /dev/null +++ b/app/client/src/api/types.ts @@ -0,0 +1,24 @@ +import type { AxiosError, AxiosResponse } from "axios"; + +export interface ApiResponseError { + code: string; + message: string; +} + +export interface ApiResponseMeta { + status: number; + success: boolean; + error?: ApiResponseError; +} + +export interface ApiResponse<T = unknown> { + responseMeta: ApiResponseMeta; + data: T; + code?: string; +} + +export type AxiosResponseData<T> = AxiosResponse<ApiResponse<T>>["data"]; + +export type ErrorHandler = ( + error: AxiosError<ApiResponse>, +) => Promise<unknown | null>; diff --git a/app/client/src/ce/api/ApiUtils.test.ts b/app/client/src/ce/api/ApiUtils.test.ts deleted file mode 100644 index c1848f77605c..000000000000 --- a/app/client/src/ce/api/ApiUtils.test.ts +++ /dev/null @@ -1,127 +0,0 @@ -import { - apiRequestInterceptor, - apiSuccessResponseInterceptor, - apiFailureResponseInterceptor, - axiosConnectionAbortedCode, -} from "./ApiUtils"; -import type { AxiosRequestConfig, AxiosResponse } from "axios"; -import type { ActionExecutionResponse } from "api/ActionAPI"; -import { - createMessage, - ERROR_0, - SERVER_API_TIMEOUT_ERROR, -} from "ee/constants/messages"; -import { ERROR_CODES } from "ee/constants/ApiConstants"; -import * as Sentry from "@sentry/react"; - -describe("axios api interceptors", () => { - describe("Axios api request interceptor", () => { - it("adds timer to the request object", () => { - const request: AxiosRequestConfig = { - url: "https://app.appsmith.com/v1/api/actions/execute", - }; - const interceptedRequest = apiRequestInterceptor(request); - - expect(interceptedRequest).toHaveProperty("timer"); - }); - }); - - describe("Axios api response success interceptor", () => { - it("transforms an action execution response", () => { - const response: AxiosResponse = { - data: "Test data", - headers: { - "content-length": 123, - "content-type": "application/json", - }, - config: { - url: "https://app.appsmith.com/v1/api/actions/execute", - // @ts-expect-error: type mismatch - timer: 0, - }, - }; - - const interceptedResponse: ActionExecutionResponse = - apiSuccessResponseInterceptor(response); - - expect(interceptedResponse).toHaveProperty("clientMeta"); - expect(interceptedResponse.clientMeta).toHaveProperty("size"); - expect(interceptedResponse.clientMeta.size).toBe(123); - expect(interceptedResponse.clientMeta).toHaveProperty("duration"); - }); - - it("just returns the response data for other requests", () => { - const response: AxiosResponse = { - data: "Test data", - headers: { - "content-type": "application/json", - }, - config: { - url: "https://app.appsmith.com/v1/api/actions", - //@ts-expect-error: type mismatch - timer: 0, - }, - }; - - const interceptedResponse: ActionExecutionResponse = - apiSuccessResponseInterceptor(response); - - expect(interceptedResponse).toBe("Test data"); - }); - }); - - describe("Api response failure interceptor", () => { - beforeEach(() => { - jest.restoreAllMocks(); - }); - - it("checks for no internet errors", () => { - jest.spyOn(navigator, "onLine", "get").mockReturnValue(false); - const interceptedResponse = apiFailureResponseInterceptor({}); - - expect(interceptedResponse).rejects.toStrictEqual({ - message: createMessage(ERROR_0), - }); - }); - - it.todo("handles axios cancel gracefully"); - - it("handles timeout errors", () => { - const error = { - code: axiosConnectionAbortedCode, - message: "timeout of 10000ms exceeded", - }; - const interceptedResponse = apiFailureResponseInterceptor(error); - - expect(interceptedResponse).rejects.toStrictEqual({ - message: createMessage(SERVER_API_TIMEOUT_ERROR), - code: ERROR_CODES.REQUEST_TIMEOUT, - }); - }); - - it("checks for response meta", () => { - const sentrySpy = jest.spyOn(Sentry, "captureException"); - const response: AxiosResponse = { - data: "Test data", - headers: { - "content-type": "application/json", - }, - config: { - url: "https://app.appsmith.com/v1/api/user", - //@ts-expect-error: type mismatch - timer: 0, - }, - }; - - apiSuccessResponseInterceptor(response); - expect(sentrySpy).toHaveBeenCalled(); - - const interceptedFailureResponse = apiFailureResponseInterceptor({ - response, - }); - - expect(interceptedFailureResponse).rejects.toStrictEqual("Test data"); - expect(sentrySpy).toHaveBeenCalled(); - }); - }); -}); diff --git a/app/client/src/ce/api/ApiUtils.ts b/app/client/src/ce/api/ApiUtils.ts index b157db36686e..9db9f45e1d7e 100644 --- a/app/client/src/ce/api/ApiUtils.ts +++ b/app/client/src/ce/api/ApiUtils.ts @@ -1,289 +1,7 @@ -import { - createMessage, - ERROR_0, - ERROR_413, - ERROR_500, - GENERIC_API_EXECUTION_ERROR, - SERVER_API_TIMEOUT_ERROR, -} from "ee/constants/messages"; -import type { AxiosRequestConfig, AxiosResponse } from "axios"; -import axios from "axios"; -import { - API_STATUS_CODES, - ERROR_CODES, - SERVER_ERROR_CODES, -} from "ee/constants/ApiConstants"; -import log from "loglevel"; -import type { ActionExecutionResponse } from "api/ActionAPI"; -import store from "store"; -import { logoutUser } from "actions/userActions"; -import { AUTH_LOGIN_URL } from "constants/routes"; -import { getCurrentGitBranch } from "selectors/gitSyncSelectors"; -import getQueryParamsObject from "utils/getQueryParamsObject"; -import { UserCancelledActionExecutionError } from "sagas/ActionExecution/errorUtils"; -import AnalyticsUtil from "ee/utils/AnalyticsUtil"; -import { getAppsmithConfigs } from "ee/configs"; -import * as Sentry from "@sentry/react"; -import { CONTENT_TYPE_HEADER_KEY } from "constants/ApiEditorConstants/CommonApiConstants"; -import { isAirgapped } from "ee/utils/airgapHelpers"; -import { getCurrentEnvironmentId } from "ee/selectors/environmentSelectors"; import { UNUSED_ENV_ID } from "constants/EnvironmentContants"; -import { ID_EXTRACTION_REGEX } from "ee/constants/routes/appRoutes"; - -const executeActionRegex = /actions\/execute/; -const timeoutErrorRegex = /timeout of (\d+)ms exceeded/; - -export const axiosConnectionAbortedCode = "ECONNABORTED"; -const appsmithConfig = getAppsmithConfigs(); export const DEFAULT_ENV_ID = UNUSED_ENV_ID; -export const BLOCKED_ROUTES = [ - "v1/app-templates", - "v1/datasources/mocks", - "v1/usage-pulse", - "v1/applications/releaseItems", - "v1/saas", -]; - -export const BLOCKED_ROUTES_REGEX = new RegExp( - `^(${BLOCKED_ROUTES.join("|")})($|/)`, -); - -export const ENV_ENABLED_ROUTES = [ - `v1/datasources/${ID_EXTRACTION_REGEX}/structure`, - `/v1/datasources/${ID_EXTRACTION_REGEX}/trigger`, - "v1/actions/execute", - "v1/saas", -]; - -export const ENV_ENABLED_ROUTES_REGEX = new RegExp( - `^(${ENV_ENABLED_ROUTES.join("|")})($|/)`, -); - -// TODO: Fix this the next time the file is edited -// eslint-disable-next-line @typescript-eslint/no-explicit-any -const makeExecuteActionResponse = (response: any): ActionExecutionResponse => ({ - ...response.data, - clientMeta: { - size: response.headers["content-length"], - duration: Number(performance.now() - response.config.timer).toFixed(), - }, -}); - -const is404orAuthPath = () => { - const pathName = window.location.pathname; - - return /^\/404/.test(pathName) || /^\/user\/\w+/.test(pathName); -}; - -export const blockedApiRoutesForAirgapInterceptor = async ( - config: AxiosRequestConfig, -) => { - const { url } = config; - - const isAirgappedInstance = isAirgapped(); - - if (isAirgappedInstance && url && BLOCKED_ROUTES_REGEX.test(url)) { - return Promise.resolve({ data: null, status: 200 }); - } - - return config; -}; - -// Request interceptor will add a timer property to the request. -// this will be used to calculate the time taken for an action -// execution request -export const apiRequestInterceptor = (config: AxiosRequestConfig) => { - config.headers = config.headers ?? {}; - - // Add header for CSRF protection. - const methodUpper = config.method?.toUpperCase(); - - if (methodUpper && methodUpper !== "GET" && methodUpper !== "HEAD") { - config.headers["X-Requested-By"] = "Appsmith"; - } - - const state = store.getState(); - const branch = getCurrentGitBranch(state) || getQueryParamsObject().branch; - - if (branch && config.headers) { - config.headers.branchName = branch; - } - - if (config.url?.indexOf("/git/") !== -1) { - config.timeout = 1000 * 120; // increase timeout for git specific APIs - } - - if (ENV_ENABLED_ROUTES_REGEX.test(config.url?.split("?")[0] || "")) { - // Add header for environment name - const activeEnv = getCurrentEnvironmentId(state); - - if (activeEnv && config.headers) { - config.headers["X-Appsmith-EnvironmentId"] = activeEnv; - } - } - - const anonymousId = AnalyticsUtil.getAnonymousId(); - - appsmithConfig.segment.enabled && - anonymousId && - (config.headers["x-anonymous-user-id"] = anonymousId); - - return { ...config, timer: performance.now() }; -}; - -// On success of an API, if the api is an action execution, -// add the client meta object with size and time taken info -// otherwise just return the data -export const apiSuccessResponseInterceptor = ( - response: AxiosResponse, -): AxiosResponse["data"] => { - if (response.config.url) { - if (response.config.url.match(executeActionRegex)) { - return makeExecuteActionResponse(response); - } - } - - if ( - response.headers[CONTENT_TYPE_HEADER_KEY] === "application/json" && - !response.data.responseMeta - ) { - Sentry.captureException(new Error("Api responded without response meta"), { - contexts: { response: response.data }, - }); - } - - return response.data; -}; - -// Handle different api failure scenarios -// TODO: Fix this the next time the file is edited -// eslint-disable-next-line @typescript-eslint/no-explicit-any -export const apiFailureResponseInterceptor = async (error: any) => { - // this can be extended to other errors we want to catch. - // in this case it is 413. - if (error && error?.response && error?.response.status === 413) { - return Promise.reject({ - ...error, - clientDefinedError: true, - statusCode: "AE-APP-4013", - message: createMessage(ERROR_413, 100), - pluginErrorDetails: { - appsmithErrorCode: "AE-APP-4013", - appsmithErrorMessage: createMessage(ERROR_413, 100), - errorType: "INTERNAL_ERROR", // this value is from the server, hence cannot construct enum type. - title: createMessage(GENERIC_API_EXECUTION_ERROR), - }, - }); - } - - // Return error when there is no internet - if (!window.navigator.onLine) { - return Promise.reject({ - ...error, - message: createMessage(ERROR_0), - }); - } - - // Return if the call was cancelled via cancel token - if (axios.isCancel(error)) { - throw new UserCancelledActionExecutionError(); - } - - // Return modified response if action execution failed - if (error.config && error.config.url.match(executeActionRegex)) { - return makeExecuteActionResponse(error.response); - } - - // Return error if any timeout happened in other api calls - if ( - error.code === axiosConnectionAbortedCode && - error.message && - error.message.match(timeoutErrorRegex) - ) { - return Promise.reject({ - ...error, - message: createMessage(SERVER_API_TIMEOUT_ERROR), - code: ERROR_CODES.REQUEST_TIMEOUT, - }); - } - - if (error.response) { - if (error.response.status === API_STATUS_CODES.SERVER_ERROR) { - return Promise.reject({ - ...error, - code: ERROR_CODES.SERVER_ERROR, - message: createMessage(ERROR_500), - }); - } - - // The request was made and the server responded with a status code - // that falls out of the range of 2xx - if (!is404orAuthPath()) { - const currentUrl = `${window.location.href}`; - - if (error.response.status === API_STATUS_CODES.REQUEST_NOT_AUTHORISED) { - // Redirect to login and set a redirect url. - store.dispatch( - logoutUser({ - redirectURL: `${AUTH_LOGIN_URL}?redirectUrl=${encodeURIComponent( - currentUrl, - )}`, - }), - ); - Sentry.captureException(error); - - return Promise.reject({ - ...error, - code: ERROR_CODES.REQUEST_NOT_AUTHORISED, - message: "Unauthorized. Redirecting to login page...", - show: false, - }); - } - - const errorData = error.response.data.responseMeta ?? {}; - - if ( - errorData.status === API_STATUS_CODES.RESOURCE_NOT_FOUND && - (SERVER_ERROR_CODES.RESOURCE_NOT_FOUND.includes(errorData.error.code) || - SERVER_ERROR_CODES.UNABLE_TO_FIND_PAGE.includes(errorData.error.code)) - ) { - Sentry.captureException(error); - - return Promise.reject({ - ...error, - code: ERROR_CODES.PAGE_NOT_FOUND, - message: "Resource Not Found", - show: false, - }); - } - } - - if (error.response.data.responseMeta) { - return Promise.resolve(error.response.data); - } - - Sentry.captureException(new Error("Api responded without response meta"), { - contexts: { response: error.response.data }, - }); - - return Promise.reject(error.response.data); - } else if (error.request) { - // The request was made but no response was received - // `error.request` is an instance of XMLHttpRequest in the browser and an instance of - // http.ClientRequest in node.js - log.error(error.request); - } else { - // Something happened in setting up the request that triggered an Error - log.error("Error", error.message); - } - - log.debug(error.config); - - return Promise.resolve(error); -}; - // function to get the default environment export const getDefaultEnvId = () => { return DEFAULT_ENV_ID; diff --git a/app/client/src/ce/constants/ApiConstants.tsx b/app/client/src/ce/constants/ApiConstants.tsx index 75ad958e7889..b1c7a6c7ee26 100644 --- a/app/client/src/ce/constants/ApiConstants.tsx +++ b/app/client/src/ce/constants/ApiConstants.tsx @@ -1,3 +1,7 @@ +import type { CreateAxiosDefaults } from "axios"; +import { ID_EXTRACTION_REGEX } from "constants/routes"; +import { UNUSED_ENV_ID } from "constants/EnvironmentContants"; + export const REQUEST_TIMEOUT_MS = 20000; export const DEFAULT_ACTION_TIMEOUT = 10000; export const DEFAULT_EXECUTE_ACTION_TIMEOUT_MS = 15000; @@ -5,6 +9,44 @@ export const DEFAULT_TEST_DATA_SOURCE_TIMEOUT_MS = 30000; export const DEFAULT_APPSMITH_AI_QUERY_TIMEOUT_MS = 60000; export const FILE_UPLOAD_TRIGGER_TIMEOUT_MS = 60000; +export const DEFAULT_AXIOS_CONFIG: CreateAxiosDefaults = { + baseURL: "/api/", + timeout: REQUEST_TIMEOUT_MS, + headers: { + "Content-Type": "application/json", + }, + withCredentials: true, +}; + +export const EXECUTION_ACTION_REGEX = /actions\/execute/; +export const TIMEOUT_ERROR_REGEX = /timeout of (\d+)ms exceeded/; +export const AXIOS_CONNECTION_ABORTED_CODE = "ECONNABORTED"; + +export const DEFAULT_ENV_ID = UNUSED_ENV_ID; + +export const BLOCKED_ROUTES = [ + "v1/app-templates", + "v1/datasources/mocks", + "v1/usage-pulse", + "v1/applications/releaseItems", + "v1/saas", +]; + +export const BLOCKED_ROUTES_REGEX = new RegExp( + `^(${BLOCKED_ROUTES.join("|")})($|/)`, +); + +export const ENV_ENABLED_ROUTES = [ + `v1/datasources/${ID_EXTRACTION_REGEX}/structure`, + `/v1/datasources/${ID_EXTRACTION_REGEX}/trigger`, + "v1/actions/execute", + "v1/saas", +]; + +export const ENV_ENABLED_ROUTES_REGEX = new RegExp( + `^(${ENV_ENABLED_ROUTES.join("|")})($|/)`, +); + export enum API_STATUS_CODES { REQUEST_NOT_AUTHORISED = 401, RESOURCE_NOT_FOUND = 404, diff --git a/app/client/src/ce/sagas/PageSagas.tsx b/app/client/src/ce/sagas/PageSagas.tsx index 2ab7c28753ea..12e52ba930c5 100644 --- a/app/client/src/ce/sagas/PageSagas.tsx +++ b/app/client/src/ce/sagas/PageSagas.tsx @@ -149,7 +149,7 @@ import type { LayoutSystemTypes } from "layoutSystems/types"; import { getIsAnvilLayout } from "layoutSystems/anvil/integrations/selectors"; import { convertToBasePageIdSelector } from "selectors/pageListSelectors"; import type { Page } from "entities/Page"; -import ConsolidatedPageLoadApi from "api/ConsolidatedPageLoadApi"; +import { ConsolidatedPageLoadApi } from "api"; export const checkIfMigrationIsNeeded = ( fetchPageResponse?: FetchPageResponse, diff --git a/app/client/src/sagas/AppThemingSaga.tsx b/app/client/src/sagas/AppThemingSaga.tsx index 5a4de787d424..3f57b894e4bc 100644 --- a/app/client/src/sagas/AppThemingSaga.tsx +++ b/app/client/src/sagas/AppThemingSaga.tsx @@ -11,8 +11,15 @@ import { ReduxActionErrorTypes, ReduxActionTypes, } from "ee/constants/ReduxActionConstants"; -import ThemingApi from "api/AppThemingApi"; -import { all, takeLatest, put, select, call } from "redux-saga/effects"; +import { AppThemingApi } from "api"; +import { + all, + takeLatest, + put, + select, + call, + type SagaReturnType, +} from "redux-saga/effects"; import { toast } from "@appsmith/ads"; import { CHANGE_APP_THEME, @@ -31,8 +38,6 @@ import { getBetaFlag, setBetaFlag, STORAGE_KEYS } from "utils/storage"; import type { UpdateWidgetPropertyPayload } from "actions/controlActions"; import { batchUpdateMultipleWidgetProperties } from "actions/controlActions"; import { getPropertiesToUpdateForReset } from "entities/AppTheming/utils"; -import type { ApiResponse } from "api/ApiResponses"; -import type { AppTheme } from "entities/AppTheming"; import type { CanvasWidgetsReduxState } from "reducers/entityReducers/canvasWidgetsReducer"; import { getCurrentApplicationId, @@ -75,11 +80,10 @@ export function* fetchAppThemes(action: ReduxAction<FetchAppThemesAction>) { try { const { applicationId, themes } = action.payload; - const response: ApiResponse<AppTheme> = yield call( - getFromServerWhenNoPrefetchedResult, - themes, - async () => ThemingApi.fetchThemes(applicationId), - ); + const response: SagaReturnType<typeof AppThemingApi.fetchThemes> = + yield call(getFromServerWhenNoPrefetchedResult, themes, async () => + AppThemingApi.fetchThemes(applicationId), + ); yield put({ type: ReduxActionTypes.FETCH_APP_THEMES_SUCCESS, @@ -112,11 +116,10 @@ export function* fetchAppSelectedTheme( const applicationVersion = yield select(selectApplicationVersion); try { - const response: ApiResponse<AppTheme[]> = yield call( - getFromServerWhenNoPrefetchedResult, - currentTheme, - async () => ThemingApi.fetchSelected(applicationId, mode), - ); + const response: SagaReturnType<typeof AppThemingApi.fetchSelected> = + yield call(getFromServerWhenNoPrefetchedResult, currentTheme, async () => + AppThemingApi.fetchSelected(applicationId, mode), + ); if (response?.data) { yield put({ @@ -161,7 +164,7 @@ export function* updateSelectedTheme( const canvasWidgets: CanvasWidgetsReduxState = yield select(getCanvasWidgets); try { - yield ThemingApi.updateTheme(applicationId, theme); + yield AppThemingApi.updateTheme(applicationId, theme); yield put({ type: ReduxActionTypes.UPDATE_SELECTED_APP_THEME_SUCCESS, @@ -197,7 +200,7 @@ export function* changeSelectedTheme( const canvasWidgets: CanvasWidgetsReduxState = yield select(getCanvasWidgets); try { - yield ThemingApi.changeTheme(applicationId, theme); + yield AppThemingApi.changeTheme(applicationId, theme); yield put({ type: ReduxActionTypes.CHANGE_SELECTED_APP_THEME_SUCCESS, @@ -235,7 +238,7 @@ export function* deleteTheme(action: ReduxAction<DeleteAppThemeAction>) { const { name, themeId } = action.payload; try { - yield ThemingApi.deleteTheme(themeId); + yield AppThemingApi.deleteTheme(themeId); yield put({ type: ReduxActionTypes.DELETE_APP_THEME_SUCCESS, @@ -289,15 +292,15 @@ function* setDefaultSelectedThemeOnError() { try { // Fetch all system themes - const response: ApiResponse<AppTheme[]> = - yield ThemingApi.fetchThemes(applicationId); + const response: SagaReturnType<typeof AppThemingApi.fetchThemes> = + yield AppThemingApi.fetchThemes(applicationId); // Gets default theme const theme = find(response.data, { name: "Default" }); if (theme) { // Update API call to set current theme to default - yield ThemingApi.changeTheme(applicationId, theme); + yield AppThemingApi.changeTheme(applicationId, theme); yield put({ type: ReduxActionTypes.FETCH_SELECTED_APP_THEME_SUCCESS, payload: theme, diff --git a/app/client/src/sagas/DatasourcesSagas.ts b/app/client/src/sagas/DatasourcesSagas.ts index bbe7de399c48..40cff1e2c294 100644 --- a/app/client/src/sagas/DatasourcesSagas.ts +++ b/app/client/src/sagas/DatasourcesSagas.ts @@ -401,7 +401,9 @@ function* handleDatasourceDeleteRedirect(deletedDatasourceId: string) { // Go to the add datasource if the last item is deleted if (remainingDatasources.length === 0) { - history.push(integrationEditorURL({ selectedTab: INTEGRATION_TABS.NEW })); + yield call(() => + history.push(integrationEditorURL({ selectedTab: INTEGRATION_TABS.NEW })), + ); return; } diff --git a/app/client/src/sagas/ErrorSagas.tsx b/app/client/src/sagas/ErrorSagas.tsx index 3e3e06854c84..1669fb5c4cad 100644 --- a/app/client/src/sagas/ErrorSagas.tsx +++ b/app/client/src/sagas/ErrorSagas.tsx @@ -29,7 +29,7 @@ import { import store from "store"; import * as Sentry from "@sentry/react"; -import { axiosConnectionAbortedCode } from "ee/api/ApiUtils"; +import { AXIOS_CONNECTION_ABORTED_CODE } from "ee/constants/ApiConstants"; import { getLoginUrl } from "ee/utils/adminSettingsHelpers"; import type { PluginErrorDetails } from "api/ActionAPI"; import showToast from "sagas/ToastSagas"; @@ -104,7 +104,7 @@ export function* validateResponse( } // letting `apiFailureResponseInterceptor` handle it this case - if (response?.code === axiosConnectionAbortedCode) { + if (response?.code === AXIOS_CONNECTION_ABORTED_CODE) { return false; } diff --git a/app/client/src/sagas/InitSagas.ts b/app/client/src/sagas/InitSagas.ts index fc6a0343c30d..497222db194d 100644 --- a/app/client/src/sagas/InitSagas.ts +++ b/app/client/src/sagas/InitSagas.ts @@ -81,8 +81,8 @@ import type { FetchPageResponse, FetchPageResponseData } from "api/PageApi"; import type { AppTheme } from "entities/AppTheming"; import type { Datasource } from "entities/Datasource"; import type { Plugin, PluginFormPayload } from "api/PluginApi"; -import ConsolidatedPageLoadApi from "api/ConsolidatedPageLoadApi"; -import { axiosConnectionAbortedCode } from "ee/api/ApiUtils"; +import { ConsolidatedPageLoadApi } from "api"; +import { AXIOS_CONNECTION_ABORTED_CODE } from "ee/constants/ApiConstants"; import { endSpan, startNestedSpan, @@ -254,7 +254,7 @@ export function* getInitResponses({ if (!isValidResponse) { // its only invalid when there is a axios related error - throw new Error("Error occured " + axiosConnectionAbortedCode); + throw new Error("Error occured " + AXIOS_CONNECTION_ABORTED_CODE); } // TODO: Fix this the next time the file is edited // eslint-disable-next-line @typescript-eslint/no-explicit-any diff --git a/app/client/src/sagas/helper.ts b/app/client/src/sagas/helper.ts index 38ad773c4cbe..c720022a3f5a 100644 --- a/app/client/src/sagas/helper.ts +++ b/app/client/src/sagas/helper.ts @@ -20,7 +20,7 @@ import set from "lodash/set"; import log from "loglevel"; import { isPlainObject, isString } from "lodash"; import { DATA_BIND_REGEX_GLOBAL } from "constants/BindingsConstants"; -import { apiFailureResponseInterceptor } from "ee/api/ApiUtils"; +import { apiFailureResponseInterceptor } from "api/interceptors"; import { klonaLiteWithTelemetry } from "utils/helpers"; // function to extract all objects that have dynamic values @@ -237,7 +237,9 @@ export function* getFromServerWhenNoPrefetchedResult( }, status, }, - }); + // TODO: Fix this the next time the file is edited + // eslint-disable-next-line @typescript-eslint/no-explicit-any + } as any); return resp; }
ff6d8244d77641c2118e9ee06d020dc9be521cc6
2023-01-19 20:20:15
balajisoundar
chore: send anonymous id from segment for anonymous users in usage pulse call (#19775)
false
send anonymous id from segment for anonymous users in usage pulse call (#19775)
chore
diff --git a/app/client/src/ce/sagas/userSagas.tsx b/app/client/src/ce/sagas/userSagas.tsx index d1e88dd31c37..d99b384e94c5 100644 --- a/app/client/src/ce/sagas/userSagas.tsx +++ b/app/client/src/ce/sagas/userSagas.tsx @@ -1,4 +1,4 @@ -import { call, put, race, select, take } from "redux-saga/effects"; +import { call, fork, put, race, select, take } from "redux-saga/effects"; import { ReduxAction, ReduxActionWithPromise, @@ -55,7 +55,10 @@ import { getFirstTimeUserOnboardingApplicationId, getFirstTimeUserOnboardingIntroModalVisibility, } from "utils/storage"; -import { initializeAnalyticsAndTrackers } from "utils/AppsmithUtils"; +import { + initializeAnalyticsAndTrackers, + initializeSegmentWithoutTracking, +} from "utils/AppsmithUtils"; import { getAppsmithConfigs } from "ce/configs"; import { getSegmentState } from "selectors/analyticsSelectors"; import { @@ -124,6 +127,34 @@ export function* waitForSegmentInit(skipWithAnonymousId: boolean) { } } +/* + * Function to initiate usage tracking + * - For anonymous users we need segement id, so if telemetry is off + * we're intiating segment without tracking and once we get the id, + * analytics object is purged. + */ +export function* initiateUsageTracking(payload: { + isAnonymousUser: boolean; + enableTelemetry: boolean; +}) { + const appsmithConfigs = getAppsmithConfigs(); + + //To make sure that we're not tracking from previous session. + UsagePulse.stopTrackingActivity(); + + if (payload.isAnonymousUser) { + if (payload.enableTelemetry && appsmithConfigs.segment.enabled) { + UsagePulse.userAnonymousId = AnalyticsUtil.getAnonymousId(); + } else { + yield initializeSegmentWithoutTracking(); + UsagePulse.userAnonymousId = AnalyticsUtil.getAnonymousId(); + AnalyticsUtil.removeAnalytics(); + } + } + + UsagePulse.startTrackingActivity(); +} + export function* getCurrentUserSaga() { try { PerformanceTracker.startAsyncTracking( @@ -132,6 +163,7 @@ export function* getCurrentUserSaga() { const response: ApiResponse = yield call(UserApi.getCurrentUser); const isValidResponse: boolean = yield validateResponse(response); + if (isValidResponse) { //@ts-expect-error: response is of type unknown const { enableTelemetry } = response.data; @@ -148,23 +180,8 @@ export function* getCurrentUserSaga() { yield put(segmentInitUncertain()); } } - } else if ( - //@ts-expect-error: response is of type unknown - response.data.isAnonymous && - //@ts-expect-error: response is of type unknown - response.data.username === ANONYMOUS_USERNAME - ) { - /* - * We're initializing the segment api regardless of the enableTelemetry flag - * So we can use segement Id to fingerprint anonymous user in usage pulse call - */ - //NOTE: commenting for now to fix a flaky cypress issue - // yield initializeSegmentWithoutTracking(); } - //To make sure that we're not tracking from previous session. - UsagePulse.stopTrackingActivity(); - if ( //@ts-expect-error: response is of type unknown !response.data.isAnonymous && @@ -173,16 +190,16 @@ export function* getCurrentUserSaga() { ) { //@ts-expect-error: response is of type unknown enableTelemetry && AnalyticsUtil.identifyUser(response.data); - } else { - UsagePulse.userAnonymousId = "anonymousId"; - - if (!enableTelemetry) { - AnalyticsUtil.removeAnalytics(); - } } - UsagePulse.startTrackingActivity(); - + /* + * Forking it as we don't want to block application flow + */ + yield fork(initiateUsageTracking, { + //@ts-expect-error: response is of type unknown + isAnonymousUser: response.data.isAnonymous, + enableTelemetry, + }); yield put(initAppLevelSocketConnection()); yield put(initPageLevelSocketConnection()); yield put({
a13d3d82bed11bd87f7503560382c2424bbf0cd1
2024-02-07 18:26:21
sneha122
feat: expires in field added in oauth2 api datasource (#30866)
false
expires in field added in oauth2 api datasource (#30866)
feat
diff --git a/app/client/src/entities/Datasource/RestAPIForm.ts b/app/client/src/entities/Datasource/RestAPIForm.ts index 57b44981f0de..b1075e70fd90 100644 --- a/app/client/src/entities/Datasource/RestAPIForm.ts +++ b/app/client/src/entities/Datasource/RestAPIForm.ts @@ -88,6 +88,7 @@ export interface AuthorizationCode extends Oauth2Common { authorizationUrl: string; customAuthenticationParameters: Property[]; isAuthorized: boolean; + expiresIn: number; } export interface Basic { diff --git a/app/client/src/pages/Editor/DataSourceEditor/RestAPIDatasourceForm.tsx b/app/client/src/pages/Editor/DataSourceEditor/RestAPIDatasourceForm.tsx index 30cea60ff978..b519889d9ed8 100644 --- a/app/client/src/pages/Editor/DataSourceEditor/RestAPIDatasourceForm.tsx +++ b/app/client/src/pages/Editor/DataSourceEditor/RestAPIDatasourceForm.tsx @@ -844,6 +844,16 @@ class DatasourceRestAPIEditor extends React.Component<Props> { false, )} </FormInputContainer> + <FormInputContainer data-location-id={btoa("authentication.expiresIn")}> + {this.renderInputTextControlViaFormControl({ + configProperty: "authentication.expiresIn", + label: "Authorization expires in (seconds)", + placeholderText: "3600", + dataType: "NUMBER", + encrypted: false, + isRequired: false, + })} + </FormInputContainer> {!_.get(formData.authentication, "isAuthorizationHeader", true) && this.renderOauth2CommonAdvanced()} diff --git a/app/client/src/transformers/RestAPIDatasourceFormTransformer.ts b/app/client/src/transformers/RestAPIDatasourceFormTransformer.ts index 8b910c7f295b..6149cd1b0881 100644 --- a/app/client/src/transformers/RestAPIDatasourceFormTransformer.ts +++ b/app/client/src/transformers/RestAPIDatasourceFormTransformer.ts @@ -183,6 +183,7 @@ const formToDatasourceAuthentication = ( customAuthenticationParameters: cleanupProperties( authentication.customAuthenticationParameters, ), + expiresIn: authentication.expiresIn, }; } } @@ -281,6 +282,7 @@ const datasourceToFormAuthentication = ( typeof authentication.isAuthorizationHeader === "undefined" ? true : !!authentication.isAuthorizationHeader, + expiresIn: authentication.expiresIn, }; } } diff --git a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/helpers/restApiUtils/connections/OAuth2AuthorizationCode.java b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/helpers/restApiUtils/connections/OAuth2AuthorizationCode.java index e3dd90b31b17..2ed7016797bd 100644 --- a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/helpers/restApiUtils/connections/OAuth2AuthorizationCode.java +++ b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/helpers/restApiUtils/connections/OAuth2AuthorizationCode.java @@ -2,6 +2,7 @@ import com.appsmith.external.constants.Authentication; import com.appsmith.external.exceptions.pluginExceptions.StaleConnectionException; +import com.appsmith.external.helpers.restApiUtils.helpers.OAuth2Utils; import com.appsmith.external.models.AuthenticationDTO; import com.appsmith.external.models.AuthenticationResponse; import com.appsmith.external.models.DatasourceConfiguration; @@ -142,16 +143,7 @@ private Mono<OAuth2> generateOAuth2Token(DatasourceConfiguration datasourceConfi if (issuedAtResponse != null) { issuedAt = Instant.ofEpochMilli(Long.parseLong((String) issuedAtResponse)); } - - // We expect at least one of the following to be present - Object expiresAtResponse = mappedResponse.get(Authentication.EXPIRES_AT); - Object expiresInResponse = mappedResponse.get(Authentication.EXPIRES_IN); - Instant expiresAt = null; - if (expiresAtResponse != null) { - expiresAt = Instant.ofEpochSecond(Long.parseLong(String.valueOf(expiresAtResponse))); - } else if (expiresInResponse != null) { - expiresAt = issuedAt.plusSeconds(Long.parseLong(String.valueOf(expiresInResponse))); - } + Instant expiresAt = OAuth2Utils.getAuthenticationExpiresAt(oAuth2, mappedResponse, issuedAt); authenticationResponse.setExpiresAt(expiresAt); authenticationResponse.setIssuedAt(issuedAt); if (mappedResponse.containsKey(Authentication.REFRESH_TOKEN)) { diff --git a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/helpers/restApiUtils/helpers/OAuth2Utils.java b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/helpers/restApiUtils/helpers/OAuth2Utils.java new file mode 100644 index 000000000000..6ae04ebeb5b9 --- /dev/null +++ b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/helpers/restApiUtils/helpers/OAuth2Utils.java @@ -0,0 +1,30 @@ +package com.appsmith.external.helpers.restApiUtils.helpers; + +import com.appsmith.external.constants.Authentication; +import com.appsmith.external.models.OAuth2; +import org.springframework.util.StringUtils; + +import java.time.Instant; +import java.util.Map; + +public class OAuth2Utils { + public static Instant getAuthenticationExpiresAt(OAuth2 oAuth2, Map<String, Object> response, Instant issuedAt) { + Instant expiresAt = null; + String expiresIn = oAuth2.getExpiresIn(); + // If expires_in property in datasource form is left blank when creating ds, + // We expect at least one of the following to be present + if (StringUtils.isEmpty(expiresIn)) { + Object expiresAtResponse = response.get(Authentication.EXPIRES_AT); + Object expiresInResponse = response.get(Authentication.EXPIRES_IN); + if (expiresAtResponse != null) { + expiresAt = Instant.ofEpochSecond(Long.parseLong(String.valueOf(expiresAtResponse))); + } else if (expiresInResponse != null) { + expiresAt = issuedAt.plusSeconds(Long.parseLong(String.valueOf(expiresInResponse))); + } + } else { + // we have expires_in field from datasource config, we will always use that + expiresAt = issuedAt.plusSeconds(Long.parseLong(expiresIn)); + } + return expiresAt; + } +} diff --git a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/OAuth2.java b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/OAuth2.java index 16a3f6507136..8e8b1a7b44c3 100644 --- a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/OAuth2.java +++ b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/OAuth2.java @@ -56,6 +56,8 @@ public enum RefreshTokenClientCredentialsLocation { String authorizationUrl; + String expiresIn; + String accessTokenUrl; @Transient diff --git a/app/server/appsmith-interfaces/src/test/java/com/appsmith/external/helpers/restApiUtils/helpers/OAuth2UtilsTest.java b/app/server/appsmith-interfaces/src/test/java/com/appsmith/external/helpers/restApiUtils/helpers/OAuth2UtilsTest.java new file mode 100644 index 000000000000..a91afc4e507c --- /dev/null +++ b/app/server/appsmith-interfaces/src/test/java/com/appsmith/external/helpers/restApiUtils/helpers/OAuth2UtilsTest.java @@ -0,0 +1,59 @@ +package com.appsmith.external.helpers.restApiUtils.helpers; + +import com.appsmith.external.models.OAuth2; +import org.junit.jupiter.api.Test; + +import java.io.IOException; +import java.time.Instant; +import java.util.HashMap; +import java.util.Map; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +public class OAuth2UtilsTest { + @Test + public void testGetAuthenticationExpiresAt_validateExpiresAtIfExpiresInPresent() throws IOException { + OAuth2 oAuth2 = new OAuth2(); + oAuth2.setExpiresIn("120"); + + Map<String, Object> response = new HashMap<String, Object>(); + Instant issuedAt = Instant.now(); + Integer defaultOauth2ExpiresInTimeInSeconds = 3600; + Instant expiresAt = issuedAt.plusSeconds(defaultOauth2ExpiresInTimeInSeconds); + response.put("expires_in", defaultOauth2ExpiresInTimeInSeconds); + + // Since expiresIn is present in oauth2 object, it will override expires_in coming from oauth2 response + Instant expiresAtExpected = issuedAt.plusSeconds(Long.parseLong(oAuth2.getExpiresIn())); + + Instant expiresAtCalculated = OAuth2Utils.getAuthenticationExpiresAt(oAuth2, response, issuedAt); + assertEquals(expiresAtExpected, expiresAtCalculated); + } + + @Test + public void testGetAuthenticationExpiresAt_validateExpiresAtIfExpiresInAbsent() throws IOException { + OAuth2 oAuth2 = new OAuth2(); + + Map<String, Object> response = new HashMap<String, Object>(); + Instant issuedAt = Instant.now(); + Integer defaultOauth2ExpiresInTimeInSeconds = 3600; + + // expiresAtExpected will be calculated based on expires_in value coming from response, + // as oauth2 object does not have any value for expires_in + Instant expiresAtExpected = issuedAt.plusSeconds(defaultOauth2ExpiresInTimeInSeconds); + response.put("expires_in", defaultOauth2ExpiresInTimeInSeconds); + + Instant expiresAtCalculated = OAuth2Utils.getAuthenticationExpiresAt(oAuth2, response, issuedAt); + assertEquals(expiresAtExpected, expiresAtCalculated); + } + + @Test + public void testGetAuthenticationExpiresAt_validateExpiresAtIfBothExpiresInAbsent() throws IOException { + OAuth2 oAuth2 = new OAuth2(); + Map<String, Object> response = new HashMap<String, Object>(); + Instant issuedAt = Instant.now(); + + // Since both oauth2 expiresIn and response expires_in is not present, expiresAt would be null + Instant expiresAtCalculated = OAuth2Utils.getAuthenticationExpiresAt(oAuth2, response, issuedAt); + assertEquals(null, expiresAtCalculated); + } +} diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ce/AuthenticationServiceCEImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ce/AuthenticationServiceCEImpl.java index 400391f4db76..4aa2e431d873 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ce/AuthenticationServiceCEImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ce/AuthenticationServiceCEImpl.java @@ -5,6 +5,7 @@ import com.appsmith.external.exceptions.pluginExceptions.AppsmithPluginError; import com.appsmith.external.exceptions.pluginExceptions.AppsmithPluginException; import com.appsmith.external.helpers.SSLHelper; +import com.appsmith.external.helpers.restApiUtils.helpers.OAuth2Utils; import com.appsmith.external.models.AuthenticationDTO; import com.appsmith.external.models.AuthenticationResponse; import com.appsmith.external.models.Datasource; @@ -294,16 +295,7 @@ public Mono<String> getAccessTokenForGenericOAuth2(AuthorizationCodeCallbackDTO if (issuedAtResponse != null) { issuedAt = Instant.ofEpochMilli(Long.parseLong((String) issuedAtResponse)); } - // We expect at least one of the following to be present - Object expiresAtResponse = response.get(Authentication.EXPIRES_AT); - Object expiresInResponse = response.get(Authentication.EXPIRES_IN); - Instant expiresAt = null; - if (expiresAtResponse != null) { - expiresAt = - Instant.ofEpochSecond(Long.parseLong(String.valueOf(expiresAtResponse))); - } else if (expiresInResponse != null) { - expiresAt = issuedAt.plusSeconds(Long.parseLong(String.valueOf(expiresInResponse))); - } + Instant expiresAt = OAuth2Utils.getAuthenticationExpiresAt(oAuth2, response, issuedAt); authenticationResponse.setExpiresAt(expiresAt); // Replacing with returned scope instead if (scope != null && !scope.isBlank()) { diff --git a/app/server/appsmith-server/src/test/java/com/appsmith/server/solutions/ApplicationForkingServiceTests.java b/app/server/appsmith-server/src/test/java/com/appsmith/server/solutions/ApplicationForkingServiceTests.java index e1bedc8e2258..65eaabc4eb02 100644 --- a/app/server/appsmith-server/src/test/java/com/appsmith/server/solutions/ApplicationForkingServiceTests.java +++ b/app/server/appsmith-server/src/test/java/com/appsmith/server/solutions/ApplicationForkingServiceTests.java @@ -1480,6 +1480,7 @@ public void cloneApplicationForkWithConfigurationTrueWithActionsThrice() { "client id", "client secret", "auth url", + "180", "access token url", "scope", Set.of("scope1", "scope2", "scope3"), @@ -1708,6 +1709,7 @@ public void cloneApplicationForkWithConfigurationFalseWithActionsThrice() { "client id", "client secret", "auth url", + "180", "access token url", "scope", Set.of("scope1", "scope2", "scope3"),
4a65d6cc2d211b1db19997d48d3aed6e006f0914
2024-02-01 11:16:55
Hetu Nandu
fix: Api bug test (#30824)
false
Api bug test (#30824)
fix
diff --git a/app/client/cypress/e2e/Regression/ServerSide/ApiTests/API_Bugs_Spec.js b/app/client/cypress/e2e/Regression/ServerSide/ApiTests/API_Bugs_Spec.js index 1b5e3904cb3a..7ff63399d5dc 100644 --- a/app/client/cypress/e2e/Regression/ServerSide/ApiTests/API_Bugs_Spec.js +++ b/app/client/cypress/e2e/Regression/ServerSide/ApiTests/API_Bugs_Spec.js @@ -1,5 +1,7 @@ import EditorNavigation, { EntityType, + PageLeftPane, + PagePaneSegment, } from "../../../../support/Pages/EditorNavigation"; const commonlocators = require("../../../../locators/commonlocators.json"); @@ -54,7 +56,7 @@ describe("Rest Bugs tests", { tags: ["@tag.Datasource"] }, function () { ); agHelper.PressEscape(); - EditorNavigation.SelectEntityByName("Page1", EntityType.Page); + PageLeftPane.switchSegment(PagePaneSegment.UI); agHelper.ClickButton("Invoke APIs!"); cy.wait(12000); // for all api calls to complete!
77575fdae02e2e7d91f58ef8333c89a6ae9faf73
2023-12-06 11:42:09
Rudraprasad Das
fix: git azure url special char support (#29319)
false
git azure url special char support (#29319)
fix
diff --git a/app/client/src/pages/Editor/gitSync/utils.test.ts b/app/client/src/pages/Editor/gitSync/utils.test.ts index 0b0288391a03..dce39bd59826 100644 --- a/app/client/src/pages/Editor/gitSync/utils.test.ts +++ b/app/client/src/pages/Editor/gitSync/utils.test.ts @@ -29,6 +29,8 @@ const validUrls = [ "[email protected]:org__v3/(((something)/(other)/(thing).git", "[email protected]:org__org/repoName.git", "git@gitlab__abcd.test.org:org__org/repoName.git", + "[email protected]:v3/something/with%20space%20(some)/geo-mantis", + "[email protected]:v3/something/with%20space%20some/geo-mantis", ]; const invalidUrls = [ diff --git a/app/client/src/pages/Editor/gitSync/utils.ts b/app/client/src/pages/Editor/gitSync/utils.ts index da5f3cf67d14..7bcdbde49467 100644 --- a/app/client/src/pages/Editor/gitSync/utils.ts +++ b/app/client/src/pages/Editor/gitSync/utils.ts @@ -19,7 +19,7 @@ export const getIsStartingWithRemoteBranches = ( }; const GIT_REMOTE_URL_PATTERN = - /^((git|ssh)|(git@[\w\-\.]+))(:(\/\/)?)([\w\.@\:\/\-~\(\)]+)[^\/]$/im; + /^((git|ssh)|(git@[\w\-\.]+))(:(\/\/)?)([\w\.@\:\/\-~\(\)%]+)[^\/]$/im; const gitRemoteUrlRegExp = new RegExp(GIT_REMOTE_URL_PATTERN);
5acc08c57cac18a1d4357bc0c833a0e1ece2bc41
2022-11-18 15:53:24
arunvjn
chore: linting performance improvement (#18101)
false
linting performance improvement (#18101)
chore
diff --git a/app/client/src/components/editorComponents/CodeEditor/index.tsx b/app/client/src/components/editorComponents/CodeEditor/index.tsx index fd7e168964c5..35b6abeffd51 100644 --- a/app/client/src/components/editorComponents/CodeEditor/index.tsx +++ b/app/client/src/components/editorComponents/CodeEditor/index.tsx @@ -385,6 +385,7 @@ class CodeEditor extends Component<Props, State> { } return nextState.isFocused || !!nextProps.isJSObject || !areErrorsEqual; } + return true; } @@ -413,6 +414,9 @@ class CodeEditor extends Component<Props, State> { }, 200); } this.editor.operation(() => { + if (prevProps.lintErrors !== this.props.lintErrors) + this.lintCode(this.editor); + if (this.state.isFocused) return; // const currentMode = this.editor.getOption("mode"); const editorValue = this.editor.getValue(); @@ -906,6 +910,7 @@ class CodeEditor extends Component<Props, State> { const { evalErrors, pathEvaluatedValue } = this.getPropertyValidation( dataTreePath, ); + let errors = evalErrors, isInvalid = evalErrors.length > 0, evaluated = evaluatedValue; @@ -921,9 +926,6 @@ class CodeEditor extends Component<Props, State> { if (this.props.isInvalid !== undefined) { isInvalid = Boolean(this.props.isInvalid); } - /* Evaluation results for snippet snippets */ - this.lintCode(this.editor); - const showEvaluatedValue = this.state.isFocused && !hideEvaluatedValue && @@ -1046,9 +1048,7 @@ const mapStateToProps = (state: AppState, props: EditorProps) => ({ datasources: state.entities.datasources, pluginIdToImageLocation: getPluginIdToImageLocation(state), recentEntities: getRecentEntityIds(state), - lintErrors: props.dataTreePath - ? getEntityLintErrors(state, props.dataTreePath) - : [], + lintErrors: getEntityLintErrors(state, props.dataTreePath), editorIsFocused: getIsCodeEditorFocused(state, getEditorIdentifier(props)), editorLastCursorPosition: getCodeEditorLastCursorPosition( state, diff --git a/app/client/src/reducers/lintingReducers/lintErrorsReducers.ts b/app/client/src/reducers/lintingReducers/lintErrorsReducers.ts index d7c1f20e4cd8..0d9246141589 100644 --- a/app/client/src/reducers/lintingReducers/lintErrorsReducers.ts +++ b/app/client/src/reducers/lintingReducers/lintErrorsReducers.ts @@ -2,6 +2,7 @@ import { ReduxActionTypes } from "@appsmith/constants/ReduxActionConstants"; import { LintError } from "utils/DynamicBindingUtils"; import { createImmerReducer } from "utils/ReducerUtils"; import { SetLintErrorsAction } from "actions/lintingActions"; +import { isEqual } from "lodash"; export interface LintErrors { [entityName: string]: LintError[]; @@ -16,9 +17,9 @@ export const lintErrorReducer = createImmerReducer(initialState, { action: SetLintErrorsAction, ) => { const { errors } = action.payload; - return { - ...state, - ...errors, - }; + for (const entityName of Object.keys(errors)) { + if (isEqual(state[entityName], errors[entityName])) continue; + state[entityName] = errors[entityName]; + } }, }); diff --git a/app/client/src/selectors/dataTreeSelectors.ts b/app/client/src/selectors/dataTreeSelectors.ts index 46915440d459..0f4542325ab6 100644 --- a/app/client/src/selectors/dataTreeSelectors.ts +++ b/app/client/src/selectors/dataTreeSelectors.ts @@ -6,7 +6,6 @@ import { getPluginEditorConfigs, getJSCollectionsForCurrentPage, } from "./entitiesSelector"; -import { ActionDataState } from "reducers/entityReducers/actionsReducer"; import { DataTree, DataTreeFactory, @@ -86,24 +85,7 @@ export const getWidgetEvalValues = createSelector( // there isn't a response already export const getDataTreeForAutocomplete = createSelector( getDataTree, - getActionsForCurrentPage, - getJSCollectionsForCurrentPage, - (tree: DataTree, actions: ActionDataState) => { - //js actions needs to be added - const cachedResponses: Record<string, any> = {}; - if (actions && actions.length) { - actions.forEach((action) => { - if (!(action.config.name in tree) && action.config.cacheResponse) { - try { - cachedResponses[action.config.name] = JSON.parse( - action.config.cacheResponse, - ); - } catch (e) { - cachedResponses[action.config.name] = action.config.cacheResponse; - } - } - }); - } + (tree: DataTree) => { return tree; }, ); diff --git a/app/client/src/selectors/lintingSelectors.ts b/app/client/src/selectors/lintingSelectors.ts index 7893a1a892e8..8cebc580d005 100644 --- a/app/client/src/selectors/lintingSelectors.ts +++ b/app/client/src/selectors/lintingSelectors.ts @@ -1,10 +1,14 @@ import { AppState } from "@appsmith/reducers"; import { get } from "lodash"; import { LintErrors } from "reducers/lintingReducers/lintErrorsReducers"; +import { LintError } from "utils/DynamicBindingUtils"; export const getAllLintErrors = (state: AppState): LintErrors => state.linting.errors; -export const getEntityLintErrors = (state: AppState, path: string) => { - return get(state.linting.errors, path) ?? []; +const emptyLint: LintError[] = []; + +export const getEntityLintErrors = (state: AppState, path?: string) => { + if (!path) return emptyLint; + return get(state.linting.errors, path, emptyLint); }; diff --git a/app/client/src/workers/Linting/utils.ts b/app/client/src/workers/Linting/utils.ts index 05ce62ee2670..acb86b5321c3 100644 --- a/app/client/src/workers/Linting/utils.ts +++ b/app/client/src/workers/Linting/utils.ts @@ -23,6 +23,8 @@ import { CustomLintErrorCode, CUSTOM_LINT_ERRORS, IGNORED_LINT_ERRORS, + INVALID_JSOBJECT_START_STATEMENT, + JS_OBJECT_START_STATEMENT, SUPPORTED_WEB_APIS, } from "components/editorComponents/CodeEditor/constants"; import { @@ -50,6 +52,7 @@ import { } from "workers/Evaluation/evaluationUtils"; import { LintErrors } from "reducers/lintingReducers/lintErrorsReducers"; import { JSUpdate } from "utils/JSPaneUtils"; +import { Severity } from "entities/AppsmithConsole"; export function getlintErrorsFromTree( pathsToLint: string[], @@ -155,6 +158,27 @@ function lintBindingPath( globalData: ReturnType<typeof createGlobalData>, ) { let lintErrors: LintError[] = []; + + if (isJSAction(entity)) { + if (!entity.body) return lintErrors; + if (!entity.body.startsWith(JS_OBJECT_START_STATEMENT)) { + return lintErrors.concat([ + { + errorType: PropertyEvaluationErrorType.LINT, + errorSegment: "", + originalBinding: entity.body, + line: 0, + ch: 0, + code: entity.body, + variables: [], + raw: entity.body, + errorMessage: INVALID_JSOBJECT_START_STATEMENT, + severity: Severity.ERROR, + }, + ]); + } + } + const { propertyPath } = getEntityNameAndPropertyPath(fullPropertyPath); // Get the {{binding}} bound values const { jsSnippets, stringSegments } = getDynamicBindings(
ab3ebc94f53ef1b824f690b7d009f66cb01ff731
2023-10-16 18:03:53
Aishwarya-U-R
test: Cypress | Skip MsSQL_Basic_Spec.ts spec in CI (#28074)
false
Cypress | Skip MsSQL_Basic_Spec.ts spec in CI (#28074)
test
diff --git a/app/client/cypress_ci_custom.config.ts b/app/client/cypress_ci_custom.config.ts index 025ee811370d..9ffd3a80b29c 100644 --- a/app/client/cypress_ci_custom.config.ts +++ b/app/client/cypress_ci_custom.config.ts @@ -58,6 +58,8 @@ export default defineConfig({ "cypress/e2e/EE/Enterprise/MultipleEnv/ME_airtable_spec.ts", "cypress/e2e/Regression/ServerSide/Datasources/ElasticSearch_Basic_Spec.ts", "cypress/e2e/Regression/ServerSide/Datasources/Oracle_Spec.ts", + "cypress/e2e/Regression/ClientSide/Widgets/Others/MapWidget_Spec.ts", + "cypress/e2e/Sanity/Datasources/MsSQL_Basic_Spec.ts", ], }, });
7da11d9eca0c1ce13b7cf0d95e49c0b4f7979ef5
2024-01-29 19:03:46
Jacques Ikot
chore: remove redundant template components and rename accordingly (#30623)
false
remove redundant template components and rename accordingly (#30623)
chore
diff --git a/app/client/src/pages/Templates/Filters.tsx b/app/client/src/pages/Templates/Filters.tsx deleted file mode 100644 index a70154f7af9f..000000000000 --- a/app/client/src/pages/Templates/Filters.tsx +++ /dev/null @@ -1,210 +0,0 @@ -import React, { useMemo } from "react"; -import styled from "styled-components"; -import { useDispatch, useSelector } from "react-redux"; -import { Checkbox, Text } from "design-system"; -import { filterTemplates } from "actions/templateActions"; -import { - getFilterListSelector, - getTemplateFilterSelector, -} from "selectors/templatesSelectors"; -import { thinScrollbar } from "constants/DefaultTheme"; -import AnalyticsUtil from "utils/AnalyticsUtil"; - -const FilterWrapper = styled.div` - overflow: auto; - height: calc(100vh - ${(props) => props.theme.homePage.header + 256}px); - ${thinScrollbar} - - .more { - padding-left: ${(props) => props.theme.spaces[11]}px; - margin-top: ${(props) => props.theme.spaces[2]}px; - cursor: pointer; - } - - .hide { - visibility: hidden; - } -`; - -const FilterItemWrapper = styled.div<{ selected: boolean }>` - padding: ${(props) => - `${props.theme.spaces[4]}px 0px 0px ${props.theme.spaces[11] - 10}px `}; - - .ads-v2-checkbox__label { - line-height: 16px; - } -`; - -const StyledFilterCategory = styled(Text)` - margin-bottom: 16px; - padding-left: ${(props) => props.theme.spaces[6]}px; - font-weight: bold; - text-transform: capitalize; - font-size: 13px; - - &.title { - margin-bottom: ${(props) => props.theme.spaces[12] - 10}px; - color: var(--ads-v2-color-fg-emphasis); - } -`; - -const ListWrapper = styled.div` - margin-top: ${(props) => props.theme.spaces[4]}px; -`; - -const FilterCategoryWrapper = styled.div` - padding-bottom: ${(props) => props.theme.spaces[13] - 11}px; -`; - -export interface Filter { - label: string; - value?: string; -} - -interface FilterItemProps { - item: Filter; - selected: boolean; - onSelect: (item: string, action: string) => void; -} - -interface FilterCategoryProps { - label: string; - filterList: Filter[]; - selectedFilters: string[]; -} - -function FilterItem({ item, onSelect, selected }: FilterItemProps) { - const onClick = () => { - const action = selected ? "remove" : "add"; - const filterValue = item?.value ?? item.label; - onSelect(filterValue, action); - if (action === "add") { - AnalyticsUtil.logEvent("TEMPLATE_FILTER_SELECTED", { - filter: filterValue, - }); - } - }; - - return ( - <FilterItemWrapper selected={selected}> - <Checkbox - // backgroundColor={Colors.GREY_900} - // className="filter" - isSelected={selected} - name={item.label} - onChange={onClick} - value={item.label} - > - {item.label} - </Checkbox> - </FilterItemWrapper> - ); -} - -function FilterCategory({ - filterList, - label, - selectedFilters, -}: FilterCategoryProps) { - const filterLabelsToDisplay: Record<string, string> = useMemo( - () => ({ - functions: "teams", - }), - [], - ); - // const [expand, setExpand] = useState(!!selectedFilters.length); - const dispatch = useDispatch(); - // This indicates how many filter items do we want to show, the rest are hidden - // behind show more. - const FILTERS_TO_SHOW = 4; - const onSelect = (item: string, type: string) => { - if (type === "add") { - dispatch(filterTemplates(label, [...selectedFilters, item])); - } else { - dispatch( - filterTemplates( - label, - selectedFilters.filter((selectedItem) => selectedItem !== item), - ), - ); - } - }; - - // const toggleExpand = () => { - // setExpand((expand) => !expand); - // }; - - const isSelected = (filter: Filter) => { - return selectedFilters.includes(filter?.value ?? filter.label); - }; - - return ( - <FilterCategoryWrapper> - <StyledFilterCategory kind="body-m" renderAs="h4"> - {`${filterLabelsToDisplay[label] ?? label} `} - {!!selectedFilters.length && `(${selectedFilters.length})`} - </StyledFilterCategory> - <ListWrapper> - {filterList.slice(0, FILTERS_TO_SHOW).map((filter) => { - return ( - <FilterItem - item={filter} - key={filter.label} - onSelect={onSelect} - selected={isSelected(filter)} - /> - ); - })} - <> - {filterList.slice(FILTERS_TO_SHOW).map((filter) => { - return ( - <FilterItem - item={filter} - key={filter.label} - onSelect={onSelect} - selected={isSelected(filter)} - /> - ); - })} - </> - {/* We will be adding this back later */} - {/* {!!filterList.slice(FILTERS_TO_SHOW).length && ( - <Text - className={`more ${selectedFilters.length && expand && "hide"}`} - onClick={toggleExpand} - type={TextType.BUTTON_SMALL} - underline - > - {expand - ? `- ${createMessage(SHOW_LESS)}` - : `+ ${filterList.slice(FILTERS_TO_SHOW).length} ${createMessage( - MORE, - )}`} - </Text> - )} */} - </ListWrapper> - </FilterCategoryWrapper> - ); -} - -function Filters() { - const filters = useSelector(getFilterListSelector); - const selectedFilters = useSelector(getTemplateFilterSelector); - - return ( - <FilterWrapper className="filter-wrapper"> - {Object.keys(filters).map((filter) => { - return ( - <FilterCategory - filterList={filters[filter]} - key={filter} - label={filter} - selectedFilters={selectedFilters[filter] ?? []} - /> - ); - })} - </FilterWrapper> - ); -} - -export default Filters; diff --git a/app/client/src/pages/Templates/StartWithTemplates.tsx b/app/client/src/pages/Templates/StartWithTemplates.tsx index 485d712f0f40..393db5e37fd0 100644 --- a/app/client/src/pages/Templates/StartWithTemplates.tsx +++ b/app/client/src/pages/Templates/StartWithTemplates.tsx @@ -1,3 +1,4 @@ +import { getIsFetchingApplications } from "@appsmith/selectors/selectedWorkspaceSelectors"; import type { Template as TemplateInterface } from "api/TemplatesApi"; import React from "react"; import { useSelector } from "react-redux"; @@ -8,9 +9,8 @@ import { } from "selectors/templatesSelectors"; import styled from "styled-components"; import AnalyticsUtil from "utils/AnalyticsUtil"; -import { StartWithTemplateContent } from "./StartWithTemplateContent"; -import { getIsFetchingApplications } from "@appsmith/selectors/selectedWorkspaceSelectors"; -import StartWithTemplateFilters from "./StartWithTemplateFilter"; +import TemplateFilters from "./TemplateFilters"; +import { TemplateContent } from "./TemplateContent"; const FiltersWrapper = styled.div` width: ${(props) => props.theme.homePage.sidebar}px; @@ -72,7 +72,7 @@ const StartWithTemplates = ({ return ( <> <TemplateContentWrapper> - <StartWithTemplateContent + <TemplateContent filterWithAllowPageImport={isModalLayout} isForkingEnabled={isForkingEnabled} isModalLayout={!!isModalLayout} @@ -83,7 +83,7 @@ const StartWithTemplates = ({ {!isLoading && ( <FiltersWrapper> - <StartWithTemplateFilters initialFilters={initialFilters} /> + <TemplateFilters initialFilters={initialFilters} /> </FiltersWrapper> )} </> diff --git a/app/client/src/pages/Templates/Template/LargeTemplate.tsx b/app/client/src/pages/Templates/Template/LargeTemplate.tsx deleted file mode 100644 index 13cb4a3403d4..000000000000 --- a/app/client/src/pages/Templates/Template/LargeTemplate.tsx +++ /dev/null @@ -1,36 +0,0 @@ -import { getTypographyByKey } from "design-system-old"; -import styled from "styled-components"; -import { TemplateLayout } from "./index"; - -const LargeTemplate = styled(TemplateLayout)` - border: 1px solid var(--ads-v2-color-border); - display: flex; - flex: 1; - flex-direction: column; - cursor: pointer; - &:hover { - border-color: var(--ads-v2-color-border-emphasis); - } - - && { - .title { - ${getTypographyByKey("h1")} - } - .categories { - ${getTypographyByKey("h4")} - font-weight: normal; - } - .description { - ${getTypographyByKey("p1")} - flex: 1; - } - } - - .image-wrapper { - transition: all 1s ease-out; - width: 100%; - height: 270px; - } -`; - -export default LargeTemplate; diff --git a/app/client/src/pages/Templates/Template/TemplateCard.test.tsx b/app/client/src/pages/Templates/Template/TemplateCard.test.tsx index 6bdf439103b7..9f1e156d84e6 100644 --- a/app/client/src/pages/Templates/Template/TemplateCard.test.tsx +++ b/app/client/src/pages/Templates/Template/TemplateCard.test.tsx @@ -19,11 +19,6 @@ jest.mock("react-redux", () => { }; }); -jest.mock("./LargeTemplate", () => ({ - __esModule: true, - default: () => <div data-testid="mocked-large-template" />, -})); - const BaseTemplateRender = () => ( <ThemeProvider theme={lightTheme}> <TemplateLayout diff --git a/app/client/src/pages/Templates/Template/index.tsx b/app/client/src/pages/Templates/Template/index.tsx index c81faab9906f..675aea5d28d5 100644 --- a/app/client/src/pages/Templates/Template/index.tsx +++ b/app/client/src/pages/Templates/Template/index.tsx @@ -5,7 +5,6 @@ import type { Template as TemplateInterface } from "api/TemplatesApi"; import { Button, Tooltip, Text } from "design-system"; import ForkTemplateDialog from "../ForkTemplate"; import DatasourceChip from "../DatasourceChip"; -import LargeTemplate from "./LargeTemplate"; import { createMessage, FORK_THIS_TEMPLATE, @@ -87,11 +86,7 @@ export interface TemplateProps { } const Template = (props: TemplateProps) => { - if (props.size) { - return <LargeTemplate {...props} />; - } else { - return <TemplateLayout {...props} />; - } + return <TemplateLayout {...props} />; }; export interface TemplateLayoutProps extends TemplateProps { diff --git a/app/client/src/pages/Templates/TemplateContent.tsx b/app/client/src/pages/Templates/TemplateContent.tsx deleted file mode 100644 index 7b5afc6ca9e8..000000000000 --- a/app/client/src/pages/Templates/TemplateContent.tsx +++ /dev/null @@ -1,102 +0,0 @@ -import { setTemplateSearchQuery } from "actions/templateActions"; -import { ReduxActionTypes } from "@appsmith/constants/ReduxActionConstants"; -import { SEARCH_TEMPLATES } from "@appsmith/constants/messages"; -import { getIsFetchingApplications } from "@appsmith/selectors/selectedWorkspaceSelectors"; -import { SearchInput } from "design-system"; -import { createMessage } from "design-system-old/build/constants/messages"; -import { debounce } from "lodash"; -import React, { useEffect } from "react"; -import { useSelector, useDispatch } from "react-redux"; -import { - getTemplateSearchQuery, - isFetchingTemplatesSelector, - getSearchedTemplateList, - getTemplateFiltersLength, -} from "selectors/templatesSelectors"; -import AnalyticsUtil from "utils/AnalyticsUtil"; -import { ResultsCount } from "."; -import { SearchWrapper } from "./StartWithTemplateFilter/StyledComponents"; -import type { Template } from "api/TemplatesApi"; -import TemplateList from "./TemplateList"; -import LoadingScreen from "./TemplatesModal/LoadingScreen"; - -interface TemplatesContentProps { - onTemplateClick?: (id: string) => void; - onForkTemplateClick?: (template: Template) => void; - stickySearchBar?: boolean; - isForkingEnabled: boolean; - filterWithAllowPageImport?: boolean; -} -const INPUT_DEBOUNCE_TIMER = 500; -function TemplatesContent(props: TemplatesContentProps) { - const templateSearchQuery = useSelector(getTemplateSearchQuery); - const isFetchingApplications = useSelector(getIsFetchingApplications); - const isFetchingTemplates = useSelector(isFetchingTemplatesSelector); - const isLoading = isFetchingApplications || isFetchingTemplates; - const dispatch = useDispatch(); - const onChange = debounce((query: string) => { - dispatch(setTemplateSearchQuery(query)); - AnalyticsUtil.logEvent("TEMPLATES_SEARCH_INPUT_EVENT", { query }); - }, INPUT_DEBOUNCE_TIMER); - const filterWithAllowPageImport = props.filterWithAllowPageImport || false; - const templates = useSelector(getSearchedTemplateList).filter((template) => - filterWithAllowPageImport ? !!template.allowPageImport : true, - ); - const filterCount = useSelector(getTemplateFiltersLength); - - useEffect(() => { - dispatch({ - type: ReduxActionTypes.RESET_TEMPLATE_FILTERS, - }); - }, []); - let resultsText = - templates.length > 1 - ? `Showing all ${templates.length} templates` - : templates.length === 1 - ? "Showing 1 template" - : "No templates to show"; - - if (templates.length) { - resultsText += - filterCount > 1 - ? ` matching ${filterCount} filters` - : filterCount === 1 - ? " matching 1 filter" - : ""; - } - - if (isLoading) { - return <LoadingScreen text="Loading templates" />; - } - - return ( - <> - <SearchWrapper sticky={props.stickySearchBar}> - <div className="templates-search"> - <SearchInput - data-testid={"t--application-search-input"} - isDisabled={isLoading} - onChange={onChange} - placeholder={createMessage(SEARCH_TEMPLATES)} - value={templateSearchQuery} - /> - </div> - </SearchWrapper> - <ResultsCount - data-testid="t--application-templates-results-header" - kind="heading-m" - renderAs="h1" - > - {resultsText} - </ResultsCount> - <TemplateList - isForkingEnabled={props.isForkingEnabled} - onForkTemplateClick={props.onForkTemplateClick} - onTemplateClick={props.onTemplateClick} - templates={templates} - /> - </> - ); -} - -export default TemplatesContent; diff --git a/app/client/src/pages/Templates/StartWithTemplateContent/StyledComponents.tsx b/app/client/src/pages/Templates/TemplateContent/StyledComponents.tsx similarity index 100% rename from app/client/src/pages/Templates/StartWithTemplateContent/StyledComponents.tsx rename to app/client/src/pages/Templates/TemplateContent/StyledComponents.tsx diff --git a/app/client/src/pages/Templates/StartWithTemplateContent/index.tsx b/app/client/src/pages/Templates/TemplateContent/index.tsx similarity index 94% rename from app/client/src/pages/Templates/StartWithTemplateContent/index.tsx rename to app/client/src/pages/Templates/TemplateContent/index.tsx index 109f9f356afb..b1d43b6df041 100644 --- a/app/client/src/pages/Templates/StartWithTemplateContent/index.tsx +++ b/app/client/src/pages/Templates/TemplateContent/index.tsx @@ -26,7 +26,7 @@ import { } from "./StyledComponents"; import FixedHeightTemplate from "../Template/FixedHeightTemplate"; -interface StartWithTemplateListProps { +interface TemplateListProps { isForkingEnabled: boolean; isModalLayout?: boolean; templates: TemplateInterface[]; @@ -34,7 +34,7 @@ interface StartWithTemplateListProps { onForkTemplateClick?: (template: TemplateInterface) => void; } -function StartWithTemplateList(props: StartWithTemplateListProps) { +function TemplateList(props: TemplateListProps) { const selectedFilters = useSelector(getTemplateFilterSelector); const onlyBuildingBlocksFilterSet = @@ -110,7 +110,7 @@ function StartWithTemplateList(props: StartWithTemplateListProps) { ); } -interface StartWithTemplateContentProps { +interface TemplateContentProps { isModalLayout?: boolean; onTemplateClick?: (id: string) => void; onForkTemplateClick?: (template: TemplateInterface) => void; @@ -119,7 +119,7 @@ interface StartWithTemplateContentProps { filterWithAllowPageImport?: boolean; } -export function StartWithTemplateContent(props: StartWithTemplateContentProps) { +export function TemplateContent(props: TemplateContentProps) { const isFetchingApplications = useSelector(getIsFetchingApplications); const isFetchingTemplates = useSelector(isFetchingTemplatesSelector); const isLoading = isFetchingApplications || isFetchingTemplates; @@ -134,7 +134,7 @@ export function StartWithTemplateContent(props: StartWithTemplateContentProps) { } return ( - <StartWithTemplateList + <TemplateList isForkingEnabled={props.isForkingEnabled} isModalLayout={props.isModalLayout} onForkTemplateClick={props.onForkTemplateClick} diff --git a/app/client/src/pages/Templates/StartWithTemplateFilter/StyledComponents.tsx b/app/client/src/pages/Templates/TemplateFilters/StyledComponents.tsx similarity index 100% rename from app/client/src/pages/Templates/StartWithTemplateFilter/StyledComponents.tsx rename to app/client/src/pages/Templates/TemplateFilters/StyledComponents.tsx diff --git a/app/client/src/pages/Templates/StartWithTemplateFilter/TemplateFilter.test.tsx b/app/client/src/pages/Templates/TemplateFilters/TemplateFilter.test.tsx similarity index 94% rename from app/client/src/pages/Templates/StartWithTemplateFilter/TemplateFilter.test.tsx rename to app/client/src/pages/Templates/TemplateFilters/TemplateFilter.test.tsx index 804db0eef52b..b285f5840813 100644 --- a/app/client/src/pages/Templates/StartWithTemplateFilter/TemplateFilter.test.tsx +++ b/app/client/src/pages/Templates/TemplateFilters/TemplateFilter.test.tsx @@ -5,7 +5,7 @@ import configureStore from "redux-mock-store"; import { Provider } from "react-redux"; import { ThemeProvider } from "styled-components"; -import StartWithTemplateFilters from "./index"; +import TemplateFilters from "./index"; import { lightTheme } from "selectors/themeSelectors"; import { ReduxActionTypes } from "@appsmith/constants/ReduxActionConstants"; import { @@ -15,7 +15,7 @@ import { const mockStore = configureStore([]); -describe("<StartWithTemplateFilters />", () => { +describe("<TemplateFilters />", () => { let store: any; beforeEach(() => { @@ -41,12 +41,12 @@ describe("<StartWithTemplateFilters />", () => { const BaseComponentRender = () => ( <Provider store={store}> <ThemeProvider theme={lightTheme}> - <StartWithTemplateFilters /> + <TemplateFilters /> </ThemeProvider> </Provider> ); - it("renders StartWithTemplateFilters component correctly", () => { + it("renders TemplateFilters component correctly", () => { render(<BaseComponentRender />); const filterItems = screen.getAllByTestId("t--templates-filter-item"); expect( @@ -75,7 +75,7 @@ describe("<StartWithTemplateFilters />", () => { render( <Provider store={store}> <ThemeProvider theme={lightTheme}> - <StartWithTemplateFilters /> + <TemplateFilters /> </ThemeProvider> </Provider>, ); diff --git a/app/client/src/pages/Templates/StartWithTemplateFilter/index.tsx b/app/client/src/pages/Templates/TemplateFilters/index.tsx similarity index 98% rename from app/client/src/pages/Templates/StartWithTemplateFilter/index.tsx rename to app/client/src/pages/Templates/TemplateFilters/index.tsx index 3f52a2b473ba..6aa81c4b0fc3 100644 --- a/app/client/src/pages/Templates/StartWithTemplateFilter/index.tsx +++ b/app/client/src/pages/Templates/TemplateFilters/index.tsx @@ -195,7 +195,7 @@ const FilterCategory = ({ }; const INPUT_DEBOUNCE_TIMER = 500; -const StartWithTemplateFilters = (props: FilterWrapperProps) => { +const TemplateFilters = (props: FilterWrapperProps) => { const dispatch = useDispatch(); const filters = useSelector(getFilterListSelector); const selectedFilters = useSelector(getTemplateFilterSelector); @@ -251,4 +251,4 @@ const StartWithTemplateFilters = (props: FilterWrapperProps) => { ); }; -export default StartWithTemplateFilters; +export default TemplateFilters; diff --git a/app/client/src/pages/Templates/TemplateList.tsx b/app/client/src/pages/Templates/TemplateList.tsx deleted file mode 100644 index eca3e5b3849f..000000000000 --- a/app/client/src/pages/Templates/TemplateList.tsx +++ /dev/null @@ -1,63 +0,0 @@ -import React from "react"; -import styled from "styled-components"; -import Masonry from "react-masonry-css"; -import Template from "./Template"; -import type { Template as TemplateInterface } from "api/TemplatesApi"; -import RequestTemplate from "./Template/RequestTemplate"; - -const breakpointColumnsObject = { - default: 4, - 3000: 3, - 1500: 3, - 1024: 2, - 800: 1, -}; - -const Wrapper = styled.div` - padding: 0 11px; - // padding-right: ${(props) => props.theme.spaces[12]}px; - // padding-left: ${(props) => props.theme.spaces[12]}px; - - .grid { - display: flex; - // margin-left: ${(props) => -props.theme.spaces[9]}px; - } - - .grid_column { - padding: 11px; - // padding-left: ${(props) => props.theme.spaces[9]}px; - } -`; - -interface TemplateListProps { - isForkingEnabled: boolean; - templates: TemplateInterface[]; - onTemplateClick?: (id: string) => void; - onForkTemplateClick?: (template: TemplateInterface) => void; -} - -function TemplateList(props: TemplateListProps) { - return ( - <Wrapper> - <Masonry - breakpointCols={breakpointColumnsObject} - className="grid" - columnClassName="grid_column" - > - {props.templates.map((template) => ( - <Template - hideForkTemplateButton={props.isForkingEnabled} - key={template.id} - onClick={props.onTemplateClick} - onForkTemplateClick={props.onForkTemplateClick} - size="large" - template={template} - /> - ))} - <RequestTemplate /> - </Masonry> - </Wrapper> - ); -} - -export default TemplateList; diff --git a/app/client/src/pages/Templates/TemplatesModal/TemplateList.tsx b/app/client/src/pages/Templates/TemplatesModal/TemplateList.tsx index bae8efa04e64..081aab00d0aa 100644 --- a/app/client/src/pages/Templates/TemplatesModal/TemplateList.tsx +++ b/app/client/src/pages/Templates/TemplatesModal/TemplateList.tsx @@ -12,8 +12,8 @@ import { } from "selectors/templatesSelectors"; import styled from "styled-components"; import LoadingScreen from "./LoadingScreen"; -import { StartWithTemplateContent } from "../StartWithTemplateContent"; -import StartWithTemplateFilters from "../StartWithTemplateFilter"; +import TemplateFilters from "../TemplateFilters"; +import { TemplateContent } from "../TemplateContent"; const Wrapper = styled.div` display: flex; @@ -64,10 +64,10 @@ function TemplateList(props: TemplateListProps) { <Wrapper className="flex flex-col"> <div className="flex"> <FilterWrapper> - <StartWithTemplateFilters /> + <TemplateFilters /> </FilterWrapper> <ListWrapper> - <StartWithTemplateContent + <TemplateContent filterWithAllowPageImport isForkingEnabled={false} onForkTemplateClick={onForkTemplateClick} diff --git a/app/client/src/pages/Templates/index.tsx b/app/client/src/pages/Templates/index.tsx index 9678f354e91d..cf37347b8430 100644 --- a/app/client/src/pages/Templates/index.tsx +++ b/app/client/src/pages/Templates/index.tsx @@ -15,11 +15,12 @@ import { } from "selectors/templatesSelectors"; import styled from "styled-components"; import { editorInitializer } from "utils/editor/EditorUtils"; -import { getFetchedWorkspaces } from "@appsmith/selectors/workspaceSelectors"; -import { StartWithTemplateContent } from "./StartWithTemplateContent"; -import StartWithTemplateFilters from "./StartWithTemplateFilter"; -import TemplateView from "./TemplateView"; + import { fetchAllWorkspaces } from "@appsmith/actions/workspaceActions"; +import TemplateFilters from "./TemplateFilters"; +import { TemplateContent } from "./TemplateContent"; +import TemplateView from "./TemplateView"; +import { getFetchedWorkspaces } from "@appsmith/selectors/workspaceSelectors"; const SentryRoute = Sentry.withSentryRouting(Route); @@ -118,11 +119,11 @@ function Templates() { <SidebarWrapper> <SecondaryWrapper> <ReconnectDatasourceModal /> - <StartWithTemplateFilters /> + <TemplateFilters /> </SecondaryWrapper> </SidebarWrapper> <TemplateListWrapper> - <StartWithTemplateContent isForkingEnabled={!!workspaceList.length} /> + <TemplateContent isForkingEnabled={!!workspaceList.length} /> </TemplateListWrapper> </PageWrapper> ); diff --git a/app/client/src/selectors/templatesSelectors.tsx b/app/client/src/selectors/templatesSelectors.tsx index bc2c18aa9a26..0f2771afff75 100644 --- a/app/client/src/selectors/templatesSelectors.tsx +++ b/app/client/src/selectors/templatesSelectors.tsx @@ -3,7 +3,7 @@ import Fuse from "fuse.js"; import type { AppState } from "@appsmith/reducers"; import { createSelector } from "reselect"; import { getDefaultPlugins } from "@appsmith/selectors/entitiesSelector"; -import type { Filter } from "pages/Templates/Filters"; +import type { Filter } from "pages/Templates/TemplateFilters"; import { getFetchedWorkspaces } from "@appsmith/selectors/workspaceSelectors"; import type { Workspace } from "@appsmith/constants/workspaceConstants"; import { hasCreateNewAppPermission } from "@appsmith/utils/permissionHelpers";
4c76406d60a2417e57b63b0a4c4c3a3356258c8b
2024-01-09 16:56:05
Rudraprasad Das
fix: fixing loader color issue (#30109)
false
fixing loader color issue (#30109)
fix
diff --git a/app/client/src/pages/Editor/gitSync/QuickGitActions/index.tsx b/app/client/src/pages/Editor/gitSync/QuickGitActions/index.tsx index 615c10b85969..1bc5692b2cc7 100644 --- a/app/client/src/pages/Editor/gitSync/QuickGitActions/index.tsx +++ b/app/client/src/pages/Editor/gitSync/QuickGitActions/index.tsx @@ -199,7 +199,7 @@ const getQuickActionButtons = ({ icon: "down-arrow-2", onClick: () => !pullDisabled && pull(), tooltipText: pullTooltipMessage, - disabled: pullDisabled, + disabled: !showPullLoadingState && pullDisabled, loading: showPullLoadingState, }, {
e567c6a037c0c4b3c18beb135eb3fb4a493397c3
2023-04-17 11:31:07
Aswath K
fix: Table V1 to support Auto Layout. Added auto-height for DatePicker (#22360)
false
Table V1 to support Auto Layout. Added auto-height for DatePicker (#22360)
fix
diff --git a/app/client/src/widgets/DatePickerWidget2/index.ts b/app/client/src/widgets/DatePickerWidget2/index.ts index ca3bb5b2e590..6ed3d768c084 100644 --- a/app/client/src/widgets/DatePickerWidget2/index.ts +++ b/app/client/src/widgets/DatePickerWidget2/index.ts @@ -62,6 +62,9 @@ export const CONFIG = { labelPosition: LabelPosition.Top, labelTextSize: "0.875rem", }, + autoDimension: { + height: true, + }, widgetSize: [ { viewportMinWidth: 0, diff --git a/app/client/src/widgets/TableWidget/index.ts b/app/client/src/widgets/TableWidget/index.ts index 0682cd77699d..483694382717 100644 --- a/app/client/src/widgets/TableWidget/index.ts +++ b/app/client/src/widgets/TableWidget/index.ts @@ -1,5 +1,6 @@ import { Colors } from "constants/Colors"; import { cloneDeep, set } from "lodash"; +import { ResponsiveBehavior } from "utils/autoLayout/constants"; import { combineDynamicBindings, getDynamicBindings, @@ -18,6 +19,7 @@ export const CONFIG = { hideCard: true, needsHeightForContent: true, defaults: { + responsiveBehavior: ResponsiveBehavior.Fill, rows: 28, columns: 34, animateLoading: true, @@ -209,6 +211,18 @@ export const CONFIG = { delimiter: ",", version: 3, }, + autoLayout: { + widgetSize: [ + { + viewportMinWidth: 0, + configuration: () => { + return { + minWidth: "280px", + }; + }, + }, + ], + }, properties: { derived: Widget.getDerivedPropertiesMap(), default: Widget.getDefaultPropertiesMap(),
05a01a6f58c9e1b4babccbd98166c034f9d56f83
2023-09-01 12:45:32
Anagh Hegde
chore: update stale lock time (#26826)
false
update stale lock time (#26826)
chore
diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/helpers/GitFileUtils.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/helpers/GitFileUtils.java index cdf438f409f8..00994b19afb4 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/helpers/GitFileUtils.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/helpers/GitFileUtils.java @@ -76,7 +76,7 @@ public class GitFileUtils { // Number of seconds after lock file is stale @Value("${appsmith.index.lock.file.time}") - public static final int INDEX_LOCK_FILE_STALE_TIME = 900; + public static final int INDEX_LOCK_FILE_STALE_TIME = 300; // Only include the application helper fields in metadata object private static final Set<String> blockedMetadataFields = Set.of( diff --git a/app/server/appsmith-server/src/main/resources/application.properties b/app/server/appsmith-server/src/main/resources/application.properties index 240dbc38d36e..dfb83bfd9c0f 100644 --- a/app/server/appsmith-server/src/main/resources/application.properties +++ b/app/server/appsmith-server/src/main/resources/application.properties @@ -114,4 +114,4 @@ appsmith.rts.port=${APPSMITH_RTS_PORT:8091} appsmith.internal.password=${APPSMITH_INTERNAL_PASSWORD:} # GIT stale index.lock file valid time -appsmith.index.lock.file.time=${APPSMITH_INDEX_LOCK_FILE_TIME:900} +appsmith.index.lock.file.time=${APPSMITH_INDEX_LOCK_FILE_TIME:300}
9e7d1d85f8ef63d6488bf8dc642e231599b05c96
2023-10-18 14:02:09
Nilesh Sarupriya
chore: invite unique emails to workspace (#28151)
false
invite unique emails to workspace (#28151)
chore
diff --git a/app/client/src/ce/pages/workspace/InviteUsersForm.tsx b/app/client/src/ce/pages/workspace/InviteUsersForm.tsx index b8bf34b7baa4..5e7a67d17977 100644 --- a/app/client/src/ce/pages/workspace/InviteUsersForm.tsx +++ b/app/client/src/ce/pages/workspace/InviteUsersForm.tsx @@ -388,7 +388,7 @@ function InviteUsersForm(props: any) { const validEmails = usersAsStringsArray.filter((user: string) => isEmail(user), ); - const validEmailsString = validEmails.join(","); + const validEmailsString = [...new Set(validEmails)].join(","); invitedEmails.current = validEmails; AnalyticsUtil.logEvent("INVITE_USER", { diff --git a/app/client/src/ce/sagas/userSagas.tsx b/app/client/src/ce/sagas/userSagas.tsx index 2bde6af6ffd3..c8b7a91c6aec 100644 --- a/app/client/src/ce/sagas/userSagas.tsx +++ b/app/client/src/ce/sagas/userSagas.tsx @@ -351,10 +351,11 @@ export function* inviteUsers( ) { const { data, reject, resolve } = action.payload; try { - const response: ApiResponse = yield callAPI(UserApi.inviteUser, { - usernames: data.usernames, - permissionGroupId: data.permissionGroupId, - }); + const response: ApiResponse<{ id: string; username: string }[]> = + yield callAPI(UserApi.inviteUser, { + usernames: data.usernames, + permissionGroupId: data.permissionGroupId, + }); const isValidResponse: boolean = yield validateResponse(response, false); if (!isValidResponse) { let errorMessage = `${data.usernames}: `; @@ -367,12 +368,14 @@ export function* inviteUsers( workspaceId: data.workspaceId, }, }); + const { data: responseData } = response; yield put({ type: ReduxActionTypes.INVITED_USERS_TO_WORKSPACE, payload: { workspaceId: data.workspaceId, - users: data.usernames.map((name: string) => ({ - username: name, + users: responseData.map((user: { id: string; username: string }) => ({ + userId: user.id, + username: user.username, permissionGroupId: data.permissionGroupId, })), }, diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ce/UserAndAccessManagementServiceCEImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ce/UserAndAccessManagementServiceCEImpl.java index 4d4c963f718b..67f6a225993b 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ce/UserAndAccessManagementServiceCEImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ce/UserAndAccessManagementServiceCEImpl.java @@ -25,10 +25,11 @@ import reactor.util.function.Tuple2; import reactor.util.function.Tuples; -import java.util.ArrayList; import java.util.HashMap; +import java.util.HashSet; import java.util.List; import java.util.Map; +import java.util.Set; import java.util.stream.Collectors; import static java.lang.Boolean.TRUE; @@ -97,7 +98,7 @@ public Mono<List<User>> inviteUsers(InviteUsersDTO inviteUsersDTO, String origin return Mono.error(new AppsmithException(AppsmithError.INVALID_PARAMETER, FieldName.ROLE)); } - List<String> usernames = new ArrayList<>(); + Set<String> usernames = new HashSet<>(); for (String username : originalUsernames) { usernames.add(username.toLowerCase()); } diff --git a/app/server/appsmith-server/src/test/java/com/appsmith/server/services/WorkspaceServiceTest.java b/app/server/appsmith-server/src/test/java/com/appsmith/server/services/WorkspaceServiceTest.java index 4c7e148cf4ee..2aeb50a51903 100644 --- a/app/server/appsmith-server/src/test/java/com/appsmith/server/services/WorkspaceServiceTest.java +++ b/app/server/appsmith-server/src/test/java/com/appsmith/server/services/WorkspaceServiceTest.java @@ -1840,4 +1840,32 @@ void testWorkspaceUpdate_checkAdditionalFieldsArePresentAfterUpdate() { mongoTemplate.count(queryWorkspaceWithAdditionalField, Workspace.class); assertThat(countWorkspaceWithAdditionalFieldAfterUpdate).isEqualTo(1); } + + @Test + @WithUserDetails(value = "api_user") + void testInviteDuplicateUsers_shouldReturnUniqueUsers() { + String testName = "test"; + List<String> duplicateUsernames = List.of(testName + "[email protected]", testName + "[email protected]"); + Workspace createdWorkspace = workspaceService.create(workspace).block(); + assertThat(createdWorkspace).isNotNull(); + assertThat(createdWorkspace.getDefaultPermissionGroups()).isNotEmpty(); + List<PermissionGroup> defaultWorkspaceRoles = permissionGroupRepository + .findAllById(createdWorkspace.getDefaultPermissionGroups()) + .collectList() + .block(); + assertThat(defaultWorkspaceRoles) + .hasSize(createdWorkspace.getDefaultPermissionGroups().size()); + + InviteUsersDTO inviteUsersDTO = new InviteUsersDTO(); + inviteUsersDTO.setUsernames(duplicateUsernames); + inviteUsersDTO.setPermissionGroupId(defaultWorkspaceRoles.get(0).getId()); + + // Invited users list contains duplicate users. + List<User> userList = userAndAccessManagementService + .inviteUsers(inviteUsersDTO, "test") + .block(); + assertThat(userList).hasSize(1); + User invitedUser = userList.get(0); + assertThat(invitedUser.getUsername()).isEqualTo(testName + "[email protected]"); + } }
2e90243fc6878ba768180204d1b98ba520784246
2023-11-13 12:38:04
Aman Agarwal
fix: schema accordions don't open on search, placeholder for search input (#28785)
false
schema accordions don't open on search, placeholder for search input (#28785)
fix
diff --git a/app/client/cypress/e2e/Regression/ClientSide/BugTests/Bug28750_Spec.ts b/app/client/cypress/e2e/Regression/ClientSide/BugTests/Bug28750_Spec.ts new file mode 100644 index 000000000000..971849a204f9 --- /dev/null +++ b/app/client/cypress/e2e/Regression/ClientSide/BugTests/Bug28750_Spec.ts @@ -0,0 +1,24 @@ +import { agHelper, dataSources } from "../../../../support/Objects/ObjectsCore"; +import { featureFlagIntercept } from "../../../../support/Objects/FeatureFlags"; + +describe("Datasource structure schema preview data", () => { + before(() => { + featureFlagIntercept({ ab_gsheet_schema_enabled: true }); + dataSources.CreateMockDB("Users"); + }); + + it( + "excludeForAirgap", + "1. Verify if the schema table accordions is collapsed in case of search", + () => { + agHelper.TypeText( + dataSources._datasourceStructureSearchInput, + "public.us", + ); + agHelper.Sleep(1000); + agHelper.AssertElementAbsence( + `${dataSources._dsStructurePreviewMode} ${dataSources._datasourceSchemaColumn}`, + ); + }, + ); +}); diff --git a/app/client/cypress/support/Pages/DataSources.ts b/app/client/cypress/support/Pages/DataSources.ts index 91bedefd818d..94d9aa4fdde3 100644 --- a/app/client/cypress/support/Pages/DataSources.ts +++ b/app/client/cypress/support/Pages/DataSources.ts @@ -256,7 +256,7 @@ export class DataSources { `//div[contains(@class, 'datasourceStructure-query-editor')]//div[contains(@class, 't--entity-name')][text()='${schemaName}']`; private _datasourceSchemaRefreshBtn = ".datasourceStructure-refresh"; private _datasourceStructureHeader = ".datasourceStructure-header"; - private _datasourceColumnSchemaInQueryEditor = ".t--datasource-column"; + _datasourceSchemaColumn = ".t--datasource-column"; _datasourceStructureSearchInput = ".datasourceStructure-search input"; _jsModeSortingControl = ".t--actionConfiguration\\.formData\\.sortBy\\.data"; public _queryEditorCollapsibleIcon = ".collapsible-icon"; @@ -299,6 +299,7 @@ export class DataSources { _gSheetQueryPlaceholder = ".CodeMirror-placeholder"; _dsNameInExplorer = (dsName: string) => `div.t--entity-name:contains('${dsName}')`; + _dsStructurePreviewMode = ".datasourceStructure-datasource-view-mode"; public AssertDSEditViewMode(mode: AppModes) { if (mode == "Edit") this.agHelper.AssertElementAbsence(this._editButton); @@ -1478,7 +1479,7 @@ export class DataSources { public VerifyColumnSchemaOnQueryEditor(schema: string, index = 0) { this.agHelper - .GetElement(this._datasourceColumnSchemaInQueryEditor) + .GetElement(this._datasourceSchemaColumn) .eq(index) .contains(schema); } diff --git a/app/client/src/ce/constants/messages.ts b/app/client/src/ce/constants/messages.ts index 520803044417..5a075b4d372f 100644 --- a/app/client/src/ce/constants/messages.ts +++ b/app/client/src/ce/constants/messages.ts @@ -753,7 +753,7 @@ export const EMPTY_ACTIVE_DATA_SOURCES = () => "No active datasources found."; export const SCHEMA_NOT_AVAILABLE = () => "Schema not available"; export const TABLE_NOT_FOUND = () => "Table not found."; export const DATASOURCE_STRUCTURE_INPUT_PLACEHOLDER_TEXT = () => - "Search for table or attribute"; + "Search for table"; export const SCHEMA_LABEL = () => "Schema"; export const STRUCTURE_NOT_FETCHED = () => "We could not fetch the schema of the database."; diff --git a/app/client/src/pages/Editor/DatasourceInfo/DatasourceStructure.tsx b/app/client/src/pages/Editor/DatasourceInfo/DatasourceStructure.tsx index 0e602acb2140..d59a51f77c40 100644 --- a/app/client/src/pages/Editor/DatasourceInfo/DatasourceStructure.tsx +++ b/app/client/src/pages/Editor/DatasourceInfo/DatasourceStructure.tsx @@ -28,7 +28,6 @@ interface DatasourceStructureItemProps { datasourceId: string; context: DatasourceStructureContext; isDefaultOpen?: boolean; - forceExpand?: boolean; currentActionId: string; onEntityTableClick?: (table: string) => void; tableName?: string; @@ -150,7 +149,6 @@ const DatasourceStructureItem = memo((props: DatasourceStructureItemProps) => { collapseRef={collapseRef} contextMenu={templateMenu} entityId={`${props.datasourceId}-${dbStructure.name}-${props.context}`} - forceExpand={props.forceExpand} icon={datasourceTableIcon} isDefaultExpanded={props?.isDefaultOpen} name={dbStructure.name} @@ -177,7 +175,6 @@ type DatasourceStructureProps = Partial<DatasourceStructureItemProps> & { datasourceId: string; context: DatasourceStructureContext; isDefaultOpen?: boolean; - forceExpand?: boolean; currentActionId: string; }; diff --git a/app/client/src/pages/Editor/DatasourceInfo/DatasourceStructureContainer.tsx b/app/client/src/pages/Editor/DatasourceInfo/DatasourceStructureContainer.tsx index 2c15e8d499dd..b13d25a8a2e1 100644 --- a/app/client/src/pages/Editor/DatasourceInfo/DatasourceStructureContainer.tsx +++ b/app/client/src/pages/Editor/DatasourceInfo/DatasourceStructureContainer.tsx @@ -59,7 +59,6 @@ const Container = (props: Props) => { const [datasourceStructure, setDatasourceStructure] = useState< DatasourceStructureType | undefined >(props.datasourceStructure); - const [hasSearchedOccured, setHasSearchedOccured] = useState(false); const { isOpened: isWalkthroughOpened, popFeature } = useContext(WalkthroughContext) || {}; @@ -96,12 +95,6 @@ const Container = (props: Props) => { const handleOnChange = (value: string) => { if (!props.datasourceStructure?.tables?.length) return; - if (value.length > 0) { - !hasSearchedOccured && setHasSearchedOccured(true); - } else { - hasSearchedOccured && setHasSearchedOccured(false); - } - const filteredDastasourceStructure = props.datasourceStructure.tables.filter((table) => table.name.toLowerCase().includes(value.toLowerCase()), @@ -141,7 +134,6 @@ const Container = (props: Props) => { context={props.context} currentActionId={props.currentActionId || ""} datasourceId={props.datasourceId} - forceExpand={hasSearchedOccured} // If set, then it doesn't set the context menu to generate query from templates onEntityTableClick={props.onEntityTableClick} step={props.step + 1}
c281600ea79c522c9fa4ded650f4ded49b08a876
2023-12-13 16:16:27
ashit-rath
chore: refactor create jsobject under modules (#29555)
false
refactor create jsobject under modules (#29555)
chore
diff --git a/app/client/src/ce/entities/DataTree/dataTreeJSAction.test.ts b/app/client/src/ce/entities/DataTree/dataTreeJSAction.test.ts index ea1533dd1fb8..11e95541cf3e 100644 --- a/app/client/src/ce/entities/DataTree/dataTreeJSAction.test.ts +++ b/app/client/src/ce/entities/DataTree/dataTreeJSAction.test.ts @@ -1,6 +1,6 @@ import { PluginType } from "entities/Action"; import { generateDataTreeJSAction } from "./dataTreeJSAction"; -import type { JSCollectionData } from "reducers/entityReducers/jsActionsReducer"; +import type { JSCollectionData } from "@appsmith/reducers/entityReducers/jsActionsReducer"; describe("generateDataTreeJSAction", () => { it("generate js collection in data tree", () => { diff --git a/app/client/src/ce/entities/DataTree/dataTreeJSAction.ts b/app/client/src/ce/entities/DataTree/dataTreeJSAction.ts index dde74ef38c14..8add6cc7d260 100644 --- a/app/client/src/ce/entities/DataTree/dataTreeJSAction.ts +++ b/app/client/src/ce/entities/DataTree/dataTreeJSAction.ts @@ -1,5 +1,5 @@ import { ENTITY_TYPE_VALUE } from "entities/DataTree/dataTreeFactory"; -import type { JSCollectionData } from "reducers/entityReducers/jsActionsReducer"; +import type { JSCollectionData } from "@appsmith/reducers/entityReducers/jsActionsReducer"; import { EvaluationSubstitutionType } from "entities/DataTree/dataTreeFactory"; import type { DependencyMap } from "utils/DynamicBindingUtils"; import type { diff --git a/app/client/src/ce/entities/DataTree/types.ts b/app/client/src/ce/entities/DataTree/types.ts index d6ef0b763f23..17678d2bdd55 100644 --- a/app/client/src/ce/entities/DataTree/types.ts +++ b/app/client/src/ce/entities/DataTree/types.ts @@ -13,7 +13,7 @@ import type { WidgetProps } from "widgets/BaseWidget"; import type { CanvasWidgetsReduxState } from "reducers/entityReducers/canvasWidgetsReducer"; import type { MetaState } from "reducers/entityReducers/metaReducer"; import type { AppDataState } from "reducers/entityReducers/appReducer"; -import type { JSCollectionDataState } from "reducers/entityReducers/jsActionsReducer"; +import type { JSCollectionDataState } from "@appsmith/reducers/entityReducers/jsActionsReducer"; import type { AppTheme } from "entities/AppTheming"; import type { LoadingEntitiesState } from "reducers/evaluationReducers/loadingEntitiesReducer"; import type { LayoutSystemTypes } from "layoutSystems/types"; diff --git a/app/client/src/ce/pages/Editor/Explorer/helpers.tsx b/app/client/src/ce/pages/Editor/Explorer/helpers.tsx index a31c673c6b1b..a330457fe70d 100644 --- a/app/client/src/ce/pages/Editor/Explorer/helpers.tsx +++ b/app/client/src/ce/pages/Editor/Explorer/helpers.tsx @@ -18,7 +18,7 @@ import { SAAS_EDITOR_DATASOURCE_ID_PATH, } from "pages/Editor/SaaSEditor/constants"; import type { ActionData } from "@appsmith/reducers/entityReducers/actionsReducer"; -import type { JSCollectionData } from "reducers/entityReducers/jsActionsReducer"; +import type { JSCollectionData } from "@appsmith/reducers/entityReducers/jsActionsReducer"; import type { PluginType } from "entities/Action"; import localStorage from "utils/localStorage"; diff --git a/app/client/src/ce/reducers/entityReducers/index.ts b/app/client/src/ce/reducers/entityReducers/index.ts index 2ee6f497f5ea..728408b482e0 100644 --- a/app/client/src/ce/reducers/entityReducers/index.ts +++ b/app/client/src/ce/reducers/entityReducers/index.ts @@ -4,7 +4,7 @@ import canvasWidgetsReducer from "reducers/entityReducers/canvasWidgetsReducer"; import canvasWidgetsStructureReducer from "reducers/entityReducers/canvasWidgetsStructureReducer"; import metaWidgetsReducer from "reducers/entityReducers/metaWidgetsReducer"; import datasourceReducer from "reducers/entityReducers/datasourceReducer"; -import jsActionsReducer from "reducers/entityReducers/jsActionsReducer"; +import jsActionsReducer from "@appsmith/reducers/entityReducers/jsActionsReducer"; import jsExecutionsReducer from "reducers/entityReducers/jsExecutionsReducer"; import metaReducer from "reducers/entityReducers/metaReducer"; import pageListReducer from "reducers/entityReducers/pageListReducer"; diff --git a/app/client/src/reducers/entityReducers/jsActionsReducer.tsx b/app/client/src/ce/reducers/entityReducers/jsActionsReducer.tsx similarity index 98% rename from app/client/src/reducers/entityReducers/jsActionsReducer.tsx rename to app/client/src/ce/reducers/entityReducers/jsActionsReducer.tsx index b7d722a1bee1..0d1d085b0ed2 100644 --- a/app/client/src/reducers/entityReducers/jsActionsReducer.tsx +++ b/app/client/src/ce/reducers/entityReducers/jsActionsReducer.tsx @@ -8,7 +8,8 @@ import { import { set, keyBy, findIndex, unset } from "lodash"; import produce from "immer"; -const initialState: JSCollectionDataState = []; +export const initialState: JSCollectionDataState = []; + export interface JSCollectionData { isLoading: boolean; config: JSCollection; @@ -42,7 +43,7 @@ export interface JSExecutionError { export type BatchedJSExecutionData = Record<string, JSExecutionData[]>; export type BatchedJSExecutionErrors = Record<string, JSExecutionError[]>; -const jsActionsReducer = createReducer(initialState, { +export const handlers = { [ReduxActionTypes.FETCH_JS_ACTIONS_SUCCESS]: ( state: JSCollectionDataState, action: ReduxAction<JSCollection[]>, @@ -461,6 +462,8 @@ const jsActionsReducer = createReducer(initialState, { } return jsCollection; }), -}); +}; + +const jsActionsReducer = createReducer(initialState, handlers); export default jsActionsReducer; diff --git a/app/client/src/ce/reducers/index.tsx b/app/client/src/ce/reducers/index.tsx index 134e58e3ca95..9dc8ca10a2a0 100644 --- a/app/client/src/ce/reducers/index.tsx +++ b/app/client/src/ce/reducers/index.tsx @@ -45,7 +45,7 @@ import type { DebuggerReduxState } from "reducers/uiReducers/debuggerReducer"; import type { TourReducerState } from "reducers/uiReducers/tourReducer"; import type { TableFilterPaneReduxState } from "reducers/uiReducers/tableFilterPaneReducer"; import type { JsPaneReduxState } from "reducers/uiReducers/jsPaneReducer"; -import type { JSCollectionDataState } from "reducers/entityReducers/jsActionsReducer"; +import type { JSCollectionDataState } from "@appsmith/reducers/entityReducers/jsActionsReducer"; import type { CanvasSelectionState } from "reducers/uiReducers/canvasSelectionReducer"; import type { JSObjectNameReduxState } from "reducers/uiReducers/jsObjectNameReducer"; import type { GitSyncReducerState } from "reducers/uiReducers/gitSyncReducer"; diff --git a/app/client/src/ce/reducers/uiReducers/editorContextReducer.ts b/app/client/src/ce/reducers/uiReducers/editorContextReducer.ts index f039d49aaf16..c0b2ac38a25f 100644 --- a/app/client/src/ce/reducers/uiReducers/editorContextReducer.ts +++ b/app/client/src/ce/reducers/uiReducers/editorContextReducer.ts @@ -63,6 +63,7 @@ export const entitySections = { Datasources: "Datasources", Libraries: "Libraries", Queries: "Queries", + JSModules: "JSModules", }; export const isSubEntities = (name: string): boolean => { diff --git a/app/client/src/ce/sagas/JSActionSagas.ts b/app/client/src/ce/sagas/JSActionSagas.ts index ca2806387f2a..4cad608d0a75 100644 --- a/app/client/src/ce/sagas/JSActionSagas.ts +++ b/app/client/src/ce/sagas/JSActionSagas.ts @@ -48,7 +48,7 @@ import type { } from "api/PageApi"; import PageApi from "api/PageApi"; import { updateCanvasWithDSL } from "@appsmith/sagas/PageSagas"; -import type { JSCollectionData } from "reducers/entityReducers/jsActionsReducer"; +import type { JSCollectionData } from "@appsmith/reducers/entityReducers/jsActionsReducer"; import type { ApiResponse } from "api/ApiResponses"; import AppsmithConsole from "utils/AppsmithConsole"; import { ENTITY_TYPE } from "entities/AppsmithConsole"; diff --git a/app/client/src/ce/selectors/entitiesSelector.ts b/app/client/src/ce/selectors/entitiesSelector.ts index f822666c6b7d..b1704335d319 100644 --- a/app/client/src/ce/selectors/entitiesSelector.ts +++ b/app/client/src/ce/selectors/entitiesSelector.ts @@ -23,7 +23,7 @@ import type { AppStoreState } from "reducers/entityReducers/appReducer"; import type { JSCollectionData, JSCollectionDataState, -} from "reducers/entityReducers/jsActionsReducer"; +} from "@appsmith/reducers/entityReducers/jsActionsReducer"; import type { DefaultPlugin, GenerateCRUDEnabledPluginMap, diff --git a/app/client/src/ce/utils/FilterInternalProperties/getEntityPeekData.ts b/app/client/src/ce/utils/FilterInternalProperties/getEntityPeekData.ts index e91f1a9b56c5..d6ac292afe41 100644 --- a/app/client/src/ce/utils/FilterInternalProperties/getEntityPeekData.ts +++ b/app/client/src/ce/utils/FilterInternalProperties/getEntityPeekData.ts @@ -12,7 +12,7 @@ import type { DataTree, DataTreeEntity, } from "entities/DataTree/dataTreeTypes"; -import type { JSCollectionDataState } from "reducers/entityReducers/jsActionsReducer"; +import type { JSCollectionDataState } from "@appsmith/reducers/entityReducers/jsActionsReducer"; export const getEntityPeekData: Record< string, diff --git a/app/client/src/ce/utils/autocomplete/EntityDefinitions.test.ts b/app/client/src/ce/utils/autocomplete/EntityDefinitions.test.ts index 730299ebf873..2c5f390160e5 100644 --- a/app/client/src/ce/utils/autocomplete/EntityDefinitions.test.ts +++ b/app/client/src/ce/utils/autocomplete/EntityDefinitions.test.ts @@ -1,5 +1,5 @@ import { PluginType } from "entities/Action"; -import type { JSCollectionData } from "reducers/entityReducers/jsActionsReducer"; +import type { JSCollectionData } from "@appsmith/reducers/entityReducers/jsActionsReducer"; import { getPropsForJSActionEntity } from "@appsmith/utils/autocomplete/EntityDefinitions"; const jsObject: JSCollectionData = { diff --git a/app/client/src/ce/utils/autocomplete/EntityDefinitions.ts b/app/client/src/ce/utils/autocomplete/EntityDefinitions.ts index 9c2ac14bfcee..38e0db42fac0 100644 --- a/app/client/src/ce/utils/autocomplete/EntityDefinitions.ts +++ b/app/client/src/ce/utils/autocomplete/EntityDefinitions.ts @@ -3,7 +3,7 @@ import { generateTypeDef } from "utils/autocomplete/defCreatorUtils"; import type { AppsmithEntity } from "@appsmith/entities/DataTree/types"; import _ from "lodash"; import { EVALUATION_PATH } from "utils/DynamicBindingUtils"; -import type { JSCollectionData } from "reducers/entityReducers/jsActionsReducer"; +import type { JSCollectionData } from "@appsmith/reducers/entityReducers/jsActionsReducer"; import type { Def } from "tern"; import type { ActionEntity } from "@appsmith/entities/DataTree/types"; diff --git a/app/client/src/components/editorComponents/ActionCreator/helpers.tsx b/app/client/src/components/editorComponents/ActionCreator/helpers.tsx index 4cbe03ee157e..8d743418d4d6 100644 --- a/app/client/src/components/editorComponents/ActionCreator/helpers.tsx +++ b/app/client/src/components/editorComponents/ActionCreator/helpers.tsx @@ -25,7 +25,7 @@ import type { ActionData, ActionDataState, } from "@appsmith/reducers/entityReducers/actionsReducer"; -import type { JSCollectionData } from "reducers/entityReducers/jsActionsReducer"; +import type { JSCollectionData } from "@appsmith/reducers/entityReducers/jsActionsReducer"; import { getCurrentPageId } from "selectors/editorSelectors"; import { getCurrentActions, diff --git a/app/client/src/components/editorComponents/GlobalSearch/useRecentEntities.tsx b/app/client/src/components/editorComponents/GlobalSearch/useRecentEntities.tsx index 7baa55aeee9e..982dd0ab04b4 100644 --- a/app/client/src/components/editorComponents/GlobalSearch/useRecentEntities.tsx +++ b/app/client/src/components/editorComponents/GlobalSearch/useRecentEntities.tsx @@ -8,7 +8,7 @@ import { } from "@appsmith/selectors/entitiesSelector"; import { SEARCH_ITEM_TYPES } from "./utils"; import { get } from "lodash"; -import type { JSCollectionData } from "reducers/entityReducers/jsActionsReducer"; +import type { JSCollectionData } from "@appsmith/reducers/entityReducers/jsActionsReducer"; import { FocusEntity } from "navigation/FocusEntity"; import type { DataTreeEntityObject } from "@appsmith/entities/DataTree/types"; import { useMemo } from "react"; diff --git a/app/client/src/components/editorComponents/JSResponseView.tsx b/app/client/src/components/editorComponents/JSResponseView.tsx index 81c3563ca9ff..fd990323d4d2 100644 --- a/app/client/src/components/editorComponents/JSResponseView.tsx +++ b/app/client/src/components/editorComponents/JSResponseView.tsx @@ -23,7 +23,7 @@ import type { JSAction } from "entities/JSCollection"; import ReadOnlyEditor from "components/editorComponents/ReadOnlyEditor"; import { Text } from "design-system"; import LoadingOverlayScreen from "components/editorComponents/LoadingOverlayScreen"; -import type { JSCollectionData } from "reducers/entityReducers/jsActionsReducer"; +import type { JSCollectionData } from "@appsmith/reducers/entityReducers/jsActionsReducer"; import type { EvaluationError } from "utils/DynamicBindingUtils"; import { DEBUGGER_TAB_KEYS } from "./Debugger/helpers"; import EntityBottomTabs from "./EntityBottomTabs"; diff --git a/app/client/src/ee/reducers/entityReducers/jsActionsReducer.tsx b/app/client/src/ee/reducers/entityReducers/jsActionsReducer.tsx new file mode 100644 index 000000000000..c30b9ec5ea76 --- /dev/null +++ b/app/client/src/ee/reducers/entityReducers/jsActionsReducer.tsx @@ -0,0 +1,4 @@ +export * from "ce/reducers/entityReducers/jsActionsReducer"; +import { default as CE_jsActionsReducer } from "ce/reducers/entityReducers/jsActionsReducer"; + +export default CE_jsActionsReducer; diff --git a/app/client/src/pages/Editor/Explorer/Entity/EntityProperties.tsx b/app/client/src/pages/Editor/Explorer/Entity/EntityProperties.tsx index 04ca88641c0f..93d90a6af060 100644 --- a/app/client/src/pages/Editor/Explorer/Entity/EntityProperties.tsx +++ b/app/client/src/pages/Editor/Explorer/Entity/EntityProperties.tsx @@ -18,7 +18,7 @@ import { getCurrentPageId } from "selectors/editorSelectors"; import classNames from "classnames"; import styled from "styled-components"; import { ReduxActionTypes } from "@appsmith/constants/ReduxActionConstants"; -import type { JSCollectionData } from "reducers/entityReducers/jsActionsReducer"; +import type { JSCollectionData } from "@appsmith/reducers/entityReducers/jsActionsReducer"; import AnalyticsUtil from "utils/AnalyticsUtil"; import { EntityClassNames } from "."; import { Button } from "design-system"; diff --git a/app/client/src/pages/Editor/Explorer/JSActions/helpers.tsx b/app/client/src/pages/Editor/Explorer/JSActions/helpers.tsx index f9451b7efbec..0d9f9a949681 100644 --- a/app/client/src/pages/Editor/Explorer/JSActions/helpers.tsx +++ b/app/client/src/pages/Editor/Explorer/JSActions/helpers.tsx @@ -1,6 +1,6 @@ import { getNextEntityName } from "utils/AppsmithUtils"; import { groupBy } from "lodash"; -import type { JSCollectionData } from "reducers/entityReducers/jsActionsReducer"; +import type { JSCollectionData } from "@appsmith/reducers/entityReducers/jsActionsReducer"; import { selectJSCollections } from "selectors/editorSelectors"; import store from "store"; diff --git a/app/client/src/pages/Editor/JSEditor/Form.tsx b/app/client/src/pages/Editor/JSEditor/Form.tsx index 14dcde7898f7..9174316f9890 100644 --- a/app/client/src/pages/Editor/JSEditor/Form.tsx +++ b/app/client/src/pages/Editor/JSEditor/Form.tsx @@ -69,7 +69,7 @@ import { getHasExecuteActionPermission, getHasManageActionPermission, } from "@appsmith/utils/BusinessFeatures/permissionPageHelpers"; -import type { JSCollectionData } from "reducers/entityReducers/jsActionsReducer"; +import type { JSCollectionData } from "@appsmith/reducers/entityReducers/jsActionsReducer"; interface JSFormProps { jsCollectionData: JSCollectionData; diff --git a/app/client/src/sagas/EvalWorkerActionSagas.ts b/app/client/src/sagas/EvalWorkerActionSagas.ts index ccde4fbc6988..47214db22196 100644 --- a/app/client/src/sagas/EvalWorkerActionSagas.ts +++ b/app/client/src/sagas/EvalWorkerActionSagas.ts @@ -8,7 +8,7 @@ import { storeLogs } from "../sagas/DebuggerSagas"; import type { BatchedJSExecutionData, BatchedJSExecutionErrors, -} from "reducers/entityReducers/jsActionsReducer"; +} from "@appsmith/reducers/entityReducers/jsActionsReducer"; import type { TMessage } from "utils/MessageUtil"; import { MessageType } from "utils/MessageUtil"; import type { ResponsePayload } from "../sagas/EvaluationsSaga"; diff --git a/app/client/src/sagas/GitSyncSagas.ts b/app/client/src/sagas/GitSyncSagas.ts index f68b073130d2..1a4fcb5398de 100644 --- a/app/client/src/sagas/GitSyncSagas.ts +++ b/app/client/src/sagas/GitSyncSagas.ts @@ -118,7 +118,7 @@ import { getJSCollections, } from "@appsmith/selectors/entitiesSelector"; import type { Action } from "entities/Action"; -import type { JSCollectionDataState } from "reducers/entityReducers/jsActionsReducer"; +import type { JSCollectionDataState } from "@appsmith/reducers/entityReducers/jsActionsReducer"; import { toast } from "design-system"; import { updateGitDefaultBranchSaga } from "@appsmith/sagas/GitExtendedSagas"; diff --git a/app/client/src/sagas/JSPaneSagas.ts b/app/client/src/sagas/JSPaneSagas.ts index ec61500e2b5a..0ff9837f917f 100644 --- a/app/client/src/sagas/JSPaneSagas.ts +++ b/app/client/src/sagas/JSPaneSagas.ts @@ -25,10 +25,10 @@ import { import type { JSCollectionData, JSCollectionDataState, -} from "reducers/entityReducers/jsActionsReducer"; +} from "@appsmith/reducers/entityReducers/jsActionsReducer"; import { createNewJSFunctionName } from "utils/AppsmithUtils"; import { getQueryParams } from "utils/URLUtils"; -import type { JSCollection, JSAction } from "entities/JSCollection"; +import type { JSCollection, JSAction, Variable } from "entities/JSCollection"; import { createJSCollectionRequest } from "actions/jsActionActions"; import history from "utils/history"; import { executeJSFunction } from "./EvaluationsSaga"; @@ -40,6 +40,7 @@ import { createDummyJSCollectionActions, } from "utils/JSPaneUtils"; import type { + CreateJSCollectionRequest, JSCollectionCreateUpdateResponse, RefactorAction, SetFunctionPropertyPayload, @@ -96,6 +97,14 @@ import { getJSActionPathNameToDisplay, } from "@appsmith/utils/actionExecutionUtils"; +export interface GenerateDefaultJSObjectProps { + name: string; + workspaceId: string; + body: string; + actions: Partial<JSAction>[]; + variables: Variable[]; +} + const CONSOLE_DOT_LOG_INVOCATION_REGEX = /console.log[.call | .apply]*\s*\(.*?\)/gm; @@ -105,48 +114,65 @@ function* handleCreateNewJsActionSaga( const workspaceId: string = yield select(getCurrentWorkspaceId); const applicationId: string = yield select(getCurrentApplicationId); const { from, pageId } = action.payload; - const pluginId: string = yield select( - getPluginIdOfPackageName, - PluginPackageName.JS, - ); - if (pageId && pluginId) { + + if (pageId) { const jsActions: JSCollectionDataState = yield select(getJSCollections); const pageJSActions = jsActions.filter( (a: JSCollectionData) => a.config.pageId === pageId, ); const newJSCollectionName = createNewJSFunctionName(pageJSActions, pageId); - const { actions, body } = createDummyJSCollectionActions( - pageId, + const { actions, body, variables } = createDummyJSCollectionActions( workspaceId, + { + pageId, + }, ); + + const defaultJSObject: CreateJSCollectionRequest = + yield generateDefaultJSObject({ + name: newJSCollectionName, + workspaceId, + actions, + body, + variables, + }); + yield put( createJSCollectionRequest({ from: from, request: { - name: newJSCollectionName, + ...defaultJSObject, pageId, - workspaceId, - pluginId, - body: body, - variables: [ - { - name: "myVar1", - value: [], - }, - { - name: "myVar2", - value: {}, - }, - ], - actions: actions, applicationId, - pluginType: PluginType.JS, }, }), ); } } +export function* generateDefaultJSObject({ + actions, + body, + name, + variables, + workspaceId, +}: GenerateDefaultJSObjectProps) { + const pluginId: string = yield select( + getPluginIdOfPackageName, + PluginPackageName.JS, + ); + + return { + name, + workspaceId, + pluginId, + body: body, + variables, + actions: actions, + pluginType: PluginType.JS, + }; +} + function* handleJSCollectionCreatedSaga( actionPayload: ReduxAction<JSCollection>, ) { diff --git a/app/client/src/utils/AppsmithUtils.tsx b/app/client/src/utils/AppsmithUtils.tsx index 71361eae7a87..9d285a6e1a98 100644 --- a/app/client/src/utils/AppsmithUtils.tsx +++ b/app/client/src/utils/AppsmithUtils.tsx @@ -9,7 +9,7 @@ import _, { isPlainObject } from "lodash"; import * as log from "loglevel"; import { osName } from "react-device-detect"; import type { ActionDataState } from "@appsmith/reducers/entityReducers/actionsReducer"; -import type { JSCollectionData } from "reducers/entityReducers/jsActionsReducer"; +import type { JSCollectionData } from "@appsmith/reducers/entityReducers/jsActionsReducer"; import AnalyticsUtil from "./AnalyticsUtil"; export const initializeAnalyticsAndTrackers = async () => { diff --git a/app/client/src/utils/FilterInternalProperties/JsAction.ts b/app/client/src/utils/FilterInternalProperties/JsAction.ts index ead880bed5a8..6d1c0b15a74f 100644 --- a/app/client/src/utils/FilterInternalProperties/JsAction.ts +++ b/app/client/src/utils/FilterInternalProperties/JsAction.ts @@ -1,6 +1,6 @@ import type { JSActionEntity } from "@appsmith/entities/DataTree/types"; import type { DataTree } from "entities/DataTree/dataTreeTypes"; -import type { JSCollectionData } from "reducers/entityReducers/jsActionsReducer"; +import type { JSCollectionData } from "@appsmith/reducers/entityReducers/jsActionsReducer"; export const getJsActionPeekData = ( jsAction: JSCollectionData, diff --git a/app/client/src/utils/FilterInternalProperties/__tests__/index.test.ts b/app/client/src/utils/FilterInternalProperties/__tests__/index.test.ts index 7afeac206c6a..5680fd042b66 100644 --- a/app/client/src/utils/FilterInternalProperties/__tests__/index.test.ts +++ b/app/client/src/utils/FilterInternalProperties/__tests__/index.test.ts @@ -10,7 +10,7 @@ import type { } from "@appsmith/entities/DataTree/types"; import { registerWidgets } from "WidgetProvider/factory/registrationHelper"; import InputWidget from "widgets/InputWidgetV2"; -import type { JSCollectionData } from "reducers/entityReducers/jsActionsReducer"; +import type { JSCollectionData } from "@appsmith/reducers/entityReducers/jsActionsReducer"; describe("filterInternalProperties tests", () => { beforeAll(() => { diff --git a/app/client/src/utils/FilterInternalProperties/index.ts b/app/client/src/utils/FilterInternalProperties/index.ts index 3f3065a1f4fd..a3a0da152d10 100644 --- a/app/client/src/utils/FilterInternalProperties/index.ts +++ b/app/client/src/utils/FilterInternalProperties/index.ts @@ -4,7 +4,7 @@ import type { DataTree, DataTreeEntity, } from "entities/DataTree/dataTreeTypes"; -import type { JSCollectionDataState } from "reducers/entityReducers/jsActionsReducer"; +import type { JSCollectionDataState } from "@appsmith/reducers/entityReducers/jsActionsReducer"; export const filterInternalProperties = ( objectName: string, diff --git a/app/client/src/utils/JSPaneUtils.tsx b/app/client/src/utils/JSPaneUtils.tsx index bf9bfdef9f67..80cd36ec3c19 100644 --- a/app/client/src/utils/JSPaneUtils.tsx +++ b/app/client/src/utils/JSPaneUtils.tsx @@ -200,8 +200,8 @@ export const pushLogsForObjectUpdate = ( }; export const createDummyJSCollectionActions = ( - pageId: string, workspaceId: string, + additionalParams: Record<string, unknown> = {}, ) => { const body = "export default {\n\tmyVar1: [],\n\tmyVar2: {},\n\tmyFun1 () {\n\t\t//\twrite code here\n\t\t//\tthis.myVar1 = [1,2,3]\n\t},\n\tasync myFun2 () {\n\t\t//\tuse async-await or promises\n\t\t//\tawait storeValue('varName', 'hello world')\n\t}\n}"; @@ -209,7 +209,6 @@ export const createDummyJSCollectionActions = ( const actions = [ { name: "myFun1", - pageId, workspaceId, executeOnLoad: false, actionConfiguration: { @@ -218,10 +217,10 @@ export const createDummyJSCollectionActions = ( jsArguments: [], }, clientSideExecution: true, + ...additionalParams, }, { name: "myFun2", - pageId, workspaceId, executeOnLoad: false, actionConfiguration: { @@ -230,10 +229,24 @@ export const createDummyJSCollectionActions = ( jsArguments: [], }, clientSideExecution: true, + ...additionalParams, }, ]; + + const variables = [ + { + name: "myVar1", + value: [], + }, + { + name: "myVar2", + value: {}, + }, + ]; + return { actions, body, + variables, }; }; diff --git a/app/client/src/utils/NavigationSelector/JsChildren.ts b/app/client/src/utils/NavigationSelector/JsChildren.ts index 7cd6fcfa2b08..7de1b48f4402 100644 --- a/app/client/src/utils/NavigationSelector/JsChildren.ts +++ b/app/client/src/utils/NavigationSelector/JsChildren.ts @@ -2,7 +2,7 @@ import type { JSActionEntity } from "@appsmith/entities/DataTree/types"; import type { DataTree } from "entities/DataTree/dataTreeTypes"; import { ENTITY_TYPE_VALUE } from "entities/DataTree/dataTreeFactory"; import { keyBy } from "lodash"; -import type { JSCollectionData } from "reducers/entityReducers/jsActionsReducer"; +import type { JSCollectionData } from "@appsmith/reducers/entityReducers/jsActionsReducer"; import { jsCollectionIdURL } from "@appsmith/RouteBuilder"; import type { EntityNavigationData, diff --git a/app/client/src/workers/Evaluation/JSObject/utils.ts b/app/client/src/workers/Evaluation/JSObject/utils.ts index 1555fda8bac5..aa7f14994512 100644 --- a/app/client/src/workers/Evaluation/JSObject/utils.ts +++ b/app/client/src/workers/Evaluation/JSObject/utils.ts @@ -16,7 +16,7 @@ import type { JSCollectionData, JSExecutionData, JSExecutionError, -} from "reducers/entityReducers/jsActionsReducer"; +} from "@appsmith/reducers/entityReducers/jsActionsReducer"; import { select } from "redux-saga/effects"; import type { JSAction } from "entities/JSCollection"; import { getAllJSCollections } from "@appsmith/selectors/entitiesSelector";
13d6450616e050125e2ead05b656b627c56ddf80
2022-03-03 23:06:34
Abhijeet
chore: Soft delete resources across Appsmith board for delete operation (#11555)
false
Soft delete resources across Appsmith board for delete operation (#11555)
chore
diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/controllers/ce/BaseController.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/controllers/ce/BaseController.java index db695a275c29..159956eaa4a0 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/controllers/ce/BaseController.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/controllers/ce/BaseController.java @@ -82,7 +82,7 @@ public Mono<ResponseDTO<T>> update(@PathVariable ID id, public Mono<ResponseDTO<T>> delete(@PathVariable ID id, @RequestHeader(name = FieldName.BRANCH_NAME, required = false) String branchName) { log.debug("Going to delete resource from base controller with id: {}", id); - return service.deleteByIdAndBranchName(id, branchName) + return service.archiveByIdAndBranchName(id, branchName) .map(deletedResource -> new ResponseDTO<>(HttpStatus.OK.value(), deletedResource, null)); } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/dtos/ActionDTO.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/dtos/ActionDTO.java index 8a0971863162..946eb520f9ad 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/dtos/ActionDTO.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/dtos/ActionDTO.java @@ -105,6 +105,7 @@ public class ActionDTO { @JsonFormat(pattern = "yyyy-MM-dd'T'HH:mm:ss'Z'", timezone = "UTC") Instant deletedAt = null; + @Deprecated @JsonFormat(pattern = "yyyy-MM-dd'T'HH:mm:ss'Z'", timezone = "UTC") Instant archivedAt = null; diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/migrations/DatabaseChangelog2.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/migrations/DatabaseChangelog2.java index 38e5fb0e6ecf..6844cdbee17a 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/migrations/DatabaseChangelog2.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/migrations/DatabaseChangelog2.java @@ -1,7 +1,10 @@ package com.appsmith.server.migrations; +import com.appsmith.server.domains.NewAction; import com.appsmith.server.domains.Plugin; +import com.appsmith.server.domains.QNewAction; import com.appsmith.server.domains.QPlugin; +import com.appsmith.server.dtos.ActionDTO; import com.github.cloudyrock.mongock.ChangeLog; import com.github.cloudyrock.mongock.ChangeSet; import com.github.cloudyrock.mongock.driver.mongodb.springdata.v3.decorator.impl.MongockTemplate; @@ -10,7 +13,12 @@ import org.springframework.data.mongodb.core.query.Query; import org.springframework.data.mongodb.core.query.Update; +import java.time.Instant; +import java.util.List; + import static com.appsmith.server.repositories.BaseAppsmithRepositoryImpl.fieldName; +import static org.springframework.data.mongodb.core.query.Criteria.where; +import static org.springframework.data.mongodb.core.query.Query.query; @Slf4j @ChangeLog(order = "002") @@ -37,4 +45,37 @@ public void fixPluginTitleCasing(MongockTemplate mongockTemplate) { ); } + @ChangeSet(order = "002", id = "deprecate-archivedAt-in-action", author = "") + public void deprecateArchivedAtForNewAction(MongockTemplate mongockTemplate) { + // Update actions + final Query actionQuery = query(where(fieldName(QNewAction.newAction.applicationId)).exists(true)) + .addCriteria(where(fieldName(QNewAction.newAction.unpublishedAction) + "." + fieldName(QNewAction.newAction.unpublishedAction.archivedAt)).exists(true)); + + actionQuery.fields() + .include(fieldName(QNewAction.newAction.id)) + .include(fieldName(QNewAction.newAction.unpublishedAction) + "." + fieldName(QNewAction.newAction.unpublishedAction.archivedAt)); + + List<NewAction> actions = mongockTemplate.find(actionQuery, NewAction.class); + + for (NewAction action : actions) { + + final Update update = new Update(); + + ActionDTO unpublishedAction = action.getUnpublishedAction(); + if (unpublishedAction != null) { + final Instant archivedAt = unpublishedAction.getArchivedAt(); + update.set( + fieldName(QNewAction.newAction.unpublishedAction) + "." + fieldName(QNewAction.newAction.unpublishedAction.deletedAt), + archivedAt + ); + update.unset(fieldName(QNewAction.newAction.unpublishedAction) + "." + fieldName(QNewAction.newAction.unpublishedAction.archivedAt)); + } + mongockTemplate.updateFirst( + query(where(fieldName(QNewAction.newAction.id)).is(action.getId())), + update, + NewAction.class + ); + } + } + } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/migrations/HelperMethods.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/migrations/HelperMethods.java new file mode 100644 index 000000000000..b420b57be4f0 --- /dev/null +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/migrations/HelperMethods.java @@ -0,0 +1,21 @@ +package com.appsmith.server.migrations; + +import com.appsmith.server.domains.NewAction; +import com.appsmith.server.dtos.ActionDTO; + +import java.time.Instant; +import java.util.List; + +public class HelperMethods { + // Migration for deprecating archivedAt field in ActionDTO + public static void updateArchivedAtByDeletedATForActions(List<NewAction> actionList) { + for (NewAction newAction : actionList) { + ActionDTO unpublishedAction = newAction.getUnpublishedAction(); + if (unpublishedAction != null) { + final Instant archivedAt = unpublishedAction.getArchivedAt(); + unpublishedAction.setDeletedAt(archivedAt); + unpublishedAction.setArchivedAt(null); + } + } + } +} diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/migrations/JsonSchemaMigration.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/migrations/JsonSchemaMigration.java index 454914c6504a..3fca615be099 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/migrations/JsonSchemaMigration.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/migrations/JsonSchemaMigration.java @@ -35,6 +35,10 @@ private static ApplicationJson migrateServerSchema(ApplicationJson applicationJs case 0: case 1: + // Migration for deprecating archivedAt field in ActionDTO + HelperMethods.updateArchivedAtByDeletedATForActions(applicationJson.getActionList()); + + case 2: default: // Unable to detect the severSchema diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/migrations/JsonSchemaVersions.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/migrations/JsonSchemaVersions.java index 7fc66bd40f48..fd830f1b3944 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/migrations/JsonSchemaVersions.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/migrations/JsonSchemaVersions.java @@ -12,6 +12,6 @@ */ @Getter public class JsonSchemaVersions { - public final static Integer serverVersion = 1; + public final static Integer serverVersion = 2; public final static Integer clientVersion = 1; } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/BaseService.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/BaseService.java index 21c3cdfe15ee..ae78118fd266 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/BaseService.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/BaseService.java @@ -140,7 +140,7 @@ protected DBObject getDbObject(Object o) { } @Override - public Mono<T> delete(ID id) { + public Mono<T> archiveById(ID id) { return Mono.error(new AppsmithException(AppsmithError.UNSUPPORTED_OPERATION)); } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/CrudService.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/CrudService.java index 0163766f1988..c6c7ad9bab81 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/CrudService.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/CrudService.java @@ -22,10 +22,10 @@ default Mono<T> findByIdAndBranchName(ID id, String branchName) { return this.getById(id); } - Mono<T> delete(ID id); + Mono<T> archiveById(ID id); - default Mono<T> deleteByIdAndBranchName(ID id, String branchName) { - return this.delete(id); + default Mono<T> archiveByIdAndBranchName(ID id, String branchName) { + return this.archiveById(id); } Mono<T> addPolicies(ID id, Set<Policy> policies); diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/ActionCollectionServiceCE.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/ActionCollectionServiceCE.java index 25af8c186cd2..9ceec2b28c53 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/ActionCollectionServiceCE.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/ActionCollectionServiceCE.java @@ -52,4 +52,6 @@ public interface ActionCollectionServiceCE extends CrudService<ActionCollection, Mono<ActionCollection> findByBranchNameAndDefaultCollectionId(String branchName, String defaultCollectionId, AclPermission permission); + Mono<List<ActionCollection>> archiveActionCollectionByApplicationId(String applicationId, AclPermission permission); + } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/ActionCollectionServiceCEImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/ActionCollectionServiceCEImpl.java index 1f54717138b5..059758644fb0 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/ActionCollectionServiceCEImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/ActionCollectionServiceCEImpl.java @@ -26,6 +26,7 @@ import org.springframework.data.domain.Sort; import org.springframework.data.mongodb.core.ReactiveMongoTemplate; import org.springframework.data.mongodb.core.convert.MongoConverter; +import org.springframework.util.CollectionUtils; import org.springframework.util.LinkedMultiValueMap; import org.springframework.util.MultiValueMap; import reactor.core.publisher.Flux; @@ -166,7 +167,7 @@ public Mono<ActionCollectionDTO> splitValidActionsByViewMode(ActionCollectionDTO actionCollectionDTO.setPluginType(actionsList.get(0).getPluginType()); } actionsList.forEach(action -> { - if (action.getArchivedAt() == null) { + if (action.getDeletedAt() == null) { validActionList.add(action); } else { archivedActionList.add(action); @@ -320,8 +321,8 @@ public Mono<ActionCollectionDTO> deleteUnpublishedActionCollection(String id) { .collectList() .then(repository.save(toDelete)); } else { - // This actionCollection was never published. This can be safely deleted from the db - modifiedActionCollectionMono = this.delete(toDelete.getId()); + // This actionCollection was never published. This document can be safely archived + modifiedActionCollectionMono = this.archiveById(toDelete.getId()); } return modifiedActionCollectionMono; @@ -376,13 +377,34 @@ public Mono<ActionCollectionDTO> findActionCollectionDTObyIdAndViewMode(String i .flatMap(action -> this.generateActionCollectionByViewMode(action, viewMode)); } + @Override + public Mono<List<ActionCollection>> archiveActionCollectionByApplicationId(String applicationId, AclPermission permission) { + return repository.findByApplicationId(applicationId, permission, null) + .flatMap(actionCollection -> { + Set<String> actionIds = new HashSet<>(); + actionIds.addAll(actionCollection.getUnpublishedCollection().getDefaultToBranchedActionIdsMap().values()); + if (actionCollection.getPublishedCollection() != null + && !CollectionUtils.isEmpty(actionCollection.getPublishedCollection().getDefaultToBranchedActionIdsMap())) { + actionIds.addAll(actionCollection.getPublishedCollection().getDefaultToBranchedActionIdsMap().values()); + } + return Flux.fromIterable(actionIds) + .flatMap(newActionService::archiveById) + .onErrorResume(throwable -> { + log.error(throwable.getMessage()); + return Mono.empty(); + }) + .then(repository.archive(actionCollection)); + }) + .collectList(); + } + @Override public Flux<ActionCollection> findByPageId(String pageId) { return repository.findByPageId(pageId); } @Override - public Mono<ActionCollection> delete(String id) { + public Mono<ActionCollection> archiveById(String id) { Mono<ActionCollection> actionCollectionMono = repository.findById(id) .switchIfEmpty(Mono.error(new AppsmithException(AppsmithError.NO_RESOURCE_FOUND, FieldName.ACTION, id))) .cache(); @@ -395,14 +417,14 @@ public Mono<ActionCollection> delete(String id) { actionIds.addAll(unpublishedCollection.getDefaultToBranchedActionIdsMap().values()); actionIds.addAll(unpublishedCollection.getDefaultToBranchedArchivedActionIdsMap().values()); } - if (publishedCollection != null && publishedCollection.getDefaultToBranchedActionIdsMap() != null) { + if (publishedCollection != null && !CollectionUtils.isEmpty(publishedCollection.getDefaultToBranchedActionIdsMap())) { actionIds.addAll(publishedCollection.getDefaultToBranchedActionIdsMap().values()); actionIds.addAll(publishedCollection.getDefaultToBranchedArchivedActionIdsMap().values()); } return actionIds; }) .flatMapMany(Flux::fromIterable) - .flatMap(actionId -> newActionService.delete(actionId) + .flatMap(actionId -> newActionService.archiveById(actionId) // return an empty action so that the filter can remove it from the list .onErrorResume(throwable -> { log.debug("Failed to delete action with id {} for collection with id: {}", actionId, id); @@ -411,17 +433,17 @@ public Mono<ActionCollection> delete(String id) { })) .collectList() .flatMap(actionList -> actionCollectionMono) - .flatMap(actionCollection -> repository.delete(actionCollection).thenReturn(actionCollection)) + .flatMap(actionCollection -> repository.archive(actionCollection).thenReturn(actionCollection)) .flatMap(analyticsService::sendDeleteEvent); } @Override - public Mono<ActionCollection> deleteByIdAndBranchName(String id, String branchName) { + public Mono<ActionCollection> archiveByIdAndBranchName(String id, String branchName) { Mono<ActionCollection> branchedCollectionMono = this.findByBranchNameAndDefaultCollectionId(branchName, id, MANAGE_ACTIONS); return branchedCollectionMono .map(ActionCollection::getId) - .flatMap(this::delete) + .flatMap(this::archiveById) .map(responseUtils::updateActionCollectionWithDefaultResources); } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/AnalyticsServiceCE.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/AnalyticsServiceCE.java index 798380a8376e..bd8a1bd95793 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/AnalyticsServiceCE.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/AnalyticsServiceCE.java @@ -33,6 +33,4 @@ public interface AnalyticsServiceCE { <T extends BaseDomain> Mono<T> sendDeleteEvent(T object, Map<String, Object> extraProperties); <T extends BaseDomain> Mono<T> sendDeleteEvent(T object); - - <T extends BaseDomain> Mono<T> sendArchiveEvent(T object); } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/AnalyticsServiceCEImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/AnalyticsServiceCEImpl.java index 251f584e9976..c468ac0b86d9 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/AnalyticsServiceCEImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/AnalyticsServiceCEImpl.java @@ -206,12 +206,4 @@ public <T extends BaseDomain> Mono<T> sendDeleteEvent(T object, Map<String, Obje public <T extends BaseDomain> Mono<T> sendDeleteEvent(T object) { return sendDeleteEvent(object, null); } - - public <T extends BaseDomain> Mono<T> sendArchiveEvent(T object) { - return sendArchiveEvent(object, null); - } - - private <T extends BaseDomain> Mono<T> sendArchiveEvent(T object, Map<String, Object> extraProperties) { - return sendObjectEvent(AnalyticsEvents.ARCHIVE, object, extraProperties); - } } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/ApplicationPageServiceCEImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/ApplicationPageServiceCEImpl.java index 17b0f3a98558..f5469c66b9a8 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/ApplicationPageServiceCEImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/ApplicationPageServiceCEImpl.java @@ -412,9 +412,10 @@ public Mono<Application> deleteApplication(String id) { } public Mono<Application> deleteApplicationByResource(Application application) { - log.debug("Archiving pages for applicationId: {}", application.getId()); - return Mono.when(newPageService.archivePagesByApplicationId(application.getId(), MANAGE_PAGES), - newActionService.archiveActionsByApplicationId(application.getId(), MANAGE_ACTIONS)) + log.debug("Archiving pages, actions and actionCollections for applicationId: {}", application.getId()); + return newPageService.archivePagesByApplicationId(application.getId(), MANAGE_PAGES) + .then(actionCollectionService.archiveActionCollectionByApplicationId(application.getId(), MANAGE_ACTIONS)) + .then(newActionService.archiveActionsByApplicationId(application.getId(), MANAGE_ACTIONS)) .thenReturn(application) .flatMap(applicationService::archive) .flatMap(analyticsService::sendDeleteEvent); @@ -879,7 +880,7 @@ public Mono<Application> publish(String applicationId, boolean isPublishedManual publishedPageIds.addAll(editedPageIds); publishedPageIds.removeAll(editedPageIds); - Mono<List<Boolean>> archivePageListMono; + Mono<List<NewPage>> archivePageListMono; if (!publishedPageIds.isEmpty()) { archivePageListMono = Flux.fromStream(publishedPageIds.stream()) .flatMap(id -> commentThreadRepository.archiveByPageId(id, ApplicationMode.PUBLISHED) @@ -916,9 +917,9 @@ public Mono<Application> publish(String applicationId, boolean isPublishedManual Flux<NewAction> publishedActionsFlux = newActionService .findAllByApplicationIdAndViewMode(applicationId, false, MANAGE_ACTIONS, null) .flatMap(newAction -> { - // If the action was deleted in edit mode, now this can be safely deleted from the repository + // If the action was deleted in edit mode, now this document can be safely archived if (newAction.getUnpublishedAction().getDeletedAt() != null) { - return newActionService.delete(newAction.getId()) + return newActionService.archive(newAction) .then(Mono.empty()); } // Publish the action by copying the unpublished actionDTO to published actionDTO @@ -933,7 +934,7 @@ public Mono<Application> publish(String applicationId, boolean isPublishedManual .flatMap(collection -> { // If the collection was deleted in edit mode, now this can be safely deleted from the repository if (collection.getUnpublishedCollection().getDeletedAt() != null) { - return actionCollectionService.delete(collection.getId()) + return actionCollectionService.archiveById(collection.getId()) .then(Mono.empty()); } // Publish the collection by copying the unpublished collectionDTO to published collectionDTO diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/DatasourceServiceCEImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/DatasourceServiceCEImpl.java index 2db1b5ea94bb..78ce625ab873 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/DatasourceServiceCEImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/DatasourceServiceCEImpl.java @@ -393,7 +393,7 @@ public Flux<Datasource> saveAll(List<Datasource> datasourceList) { } @Override - public Mono<Datasource> delete(String id) { + public Mono<Datasource> archiveById(String id) { return repository .findById(id, MANAGE_DATASOURCES) .switchIfEmpty(Mono.error(new AppsmithException(AppsmithError.NO_RESOURCE_FOUND, FieldName.DATASOURCE, id))) @@ -410,9 +410,9 @@ public Mono<Datasource> delete(String id) { } @Override - public Mono<Datasource> deleteByIdAndBranchName(String id, String branchName) { + public Mono<Datasource> archiveByIdAndBranchName(String id, String branchName) { // Ignore branchName as datasources are branch independent entity - return this.delete(id); + return this.archiveById(id); } } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/LayoutCollectionServiceCEImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/LayoutCollectionServiceCEImpl.java index eaeb7f172456..78d656394e2b 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/LayoutCollectionServiceCEImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/LayoutCollectionServiceCEImpl.java @@ -459,7 +459,7 @@ public Mono<ActionCollectionDTO> updateUnpublishedActionCollection(String id, final Mono<Map<String, String>> newValidActionIdsMono = branchedActionCollectionMono .flatMap(branchedActionCollection -> Flux.fromIterable(actionCollectionDTO.getActions()) .flatMap(actionDTO -> { - actionDTO.setArchivedAt(null); + actionDTO.setDeletedAt(null); actionDTO.setPageId(branchedActionCollection.getUnpublishedCollection().getPageId()); actionDTO.setApplicationId(branchedActionCollection.getApplicationId()); if (actionDTO.getId() == null) { @@ -496,7 +496,7 @@ public Mono<ActionCollectionDTO> updateUnpublishedActionCollection(String id, .flatMap(branchedActionCollection -> Flux.fromIterable(actionCollectionDTO.getArchivedActions()) .flatMap(actionDTO -> { actionDTO.setCollectionId(branchedActionCollection.getId()); - actionDTO.setArchivedAt(Instant.now()); + actionDTO.setDeletedAt(Instant.now()); actionDTO.setPageId(branchedActionCollection.getUnpublishedCollection().getPageId()); if (actionDTO.getId() == null) { actionDTO.getDatasource().setOrganizationId(actionCollectionDTO.getOrganizationId()); diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/NewActionServiceCE.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/NewActionServiceCE.java index a82be3854ddf..13599dbe0299 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/NewActionServiceCE.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/NewActionServiceCE.java @@ -79,7 +79,9 @@ public interface NewActionServiceCE extends CrudService<NewAction, String> { Flux<NewAction> findByPageId(String pageId); - Mono<NewAction> archive(String id); + Mono<NewAction> archive(NewAction newAction); + + Mono<NewAction> archiveById(String id); Mono<List<NewAction>> archiveActionsByApplicationId(String applicationId, AclPermission permission); diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/NewActionServiceCEImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/NewActionServiceCEImpl.java index 465cc4118fb8..36165c565f39 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/NewActionServiceCEImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/NewActionServiceCEImpl.java @@ -1159,8 +1159,8 @@ public Mono<ActionDTO> deleteUnpublishedAction(String id) { toDelete.getUnpublishedAction().setDeletedAt(Instant.now()); newActionMono = repository.save(toDelete); } else { - // This action was never published. This can be safely deleted from the db - newActionMono = repository.delete(toDelete).thenReturn(toDelete); + // This action was never published. This document can be safely archived + newActionMono = repository.archive(toDelete).thenReturn(toDelete); } return newActionMono; @@ -1493,39 +1493,36 @@ private List<LayoutActionUpdateDTO> addActionUpdatesForActionNames(List<ActionDT } @Override - public Mono<NewAction> delete(String id) { + public Mono<NewAction> archiveById(String id) { Mono<NewAction> actionMono = repository.findById(id) .switchIfEmpty(Mono.error(new AppsmithException(AppsmithError.NO_RESOURCE_FOUND, FieldName.ACTION, id))); return actionMono - .flatMap(toDelete -> repository.delete(toDelete).thenReturn(toDelete)) + .flatMap(toDelete -> repository.archive(toDelete).thenReturn(toDelete)) .flatMap(analyticsService::sendDeleteEvent); } @Override - public Mono<NewAction> deleteByIdAndBranchName(String id, String branchName) { + public Mono<NewAction> archiveByIdAndBranchName(String id, String branchName) { Mono<NewAction> branchedActionMono = this.findByBranchNameAndDefaultActionId(branchName, id, MANAGE_ACTIONS); return branchedActionMono - .flatMap(newAction -> this.delete(newAction.getId())) + .flatMap(branchedAction -> this.archiveById(branchedAction.getId())) .map(responseUtils::updateNewActionWithDefaultResources); } @Override - public Mono<NewAction> archive(String id) { - Mono<NewAction> actionMono = repository.findById(id) - .switchIfEmpty(Mono.error(new AppsmithException(AppsmithError.NO_RESOURCE_FOUND, FieldName.ACTION, id))); - return actionMono - .flatMap(toArchive -> { - toArchive.getUnpublishedAction().setArchivedAt(Instant.now()); - return repository.save(toArchive); - }) - .flatMap(analyticsService::sendArchiveEvent); + public Mono<NewAction> archive(NewAction newAction) { + return repository.archive(newAction); } @Override public Mono<List<NewAction>> archiveActionsByApplicationId(String applicationId, AclPermission permission) { return repository.findByApplicationId(applicationId, permission) .flatMap(repository::archive) + .onErrorResume(throwable -> { + log.error(throwable.getMessage()); + return Mono.empty(); + }) .collectList(); } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/NewPageServiceCE.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/NewPageServiceCE.java index 70bb5aef44e2..7bbcab604694 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/NewPageServiceCE.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/NewPageServiceCE.java @@ -60,7 +60,7 @@ Mono<ApplicationPagesDTO> findApplicationPagesByApplicationIdViewMode( Mono<NewPage> archive(NewPage page); - Mono<Boolean> archiveById(String id); + Mono<NewPage> archiveById(String id); Flux<NewPage> saveAll(List<NewPage> pages); diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/NewPageServiceCEImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/NewPageServiceCEImpl.java index fcc7613b34fd..abbc8eab304d 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/NewPageServiceCEImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/NewPageServiceCEImpl.java @@ -470,8 +470,14 @@ public Mono<NewPage> archive(NewPage page) { } @Override - public Mono<Boolean> archiveById(String id) { - return repository.archiveById(id); + public Mono<NewPage> archiveById(String id) { + Mono<NewPage> pageMono = this.findById(id, MANAGE_PAGES) + .switchIfEmpty(Mono.error(new AppsmithException(AppsmithError.NO_RESOURCE_FOUND, FieldName.PAGE_ID, id))) + .cache(); + + return pageMono + .flatMap(newPage -> repository.archiveById(id)) + .then(pageMono); } @Override diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/OrganizationServiceCE.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/OrganizationServiceCE.java index 1cdd387762f9..67af1ac865bd 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/OrganizationServiceCE.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/OrganizationServiceCE.java @@ -43,5 +43,5 @@ public interface OrganizationServiceCE extends CrudService<Organization, String> Flux<Organization> getAll(); - Mono<Organization> delete(String s); + Mono<Organization> archiveById(String s); } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/OrganizationServiceCEImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/OrganizationServiceCEImpl.java index f754753d3c7f..e7728f337d54 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/OrganizationServiceCEImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/OrganizationServiceCEImpl.java @@ -352,7 +352,7 @@ public Flux<Organization> getAll() { } @Override - public Mono<Organization> delete(String organizationId) { + public Mono<Organization> archiveById(String organizationId) { return applicationRepository.countByOrganizationId(organizationId).flatMap(appCount -> { if(appCount == 0) { // no application found under this organization // fetching the org first to make sure user has permission to archive diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/ThemeServiceCEImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/ThemeServiceCEImpl.java index 06c669989240..c50d0e7ec615 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/ThemeServiceCEImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/ThemeServiceCEImpl.java @@ -315,7 +315,7 @@ private Mono<Theme> deletePublishedCustomizedThemeCopy(String themeId) { } @Override - public Mono<Theme> delete(String themeId) { + public Mono<Theme> archiveById(String themeId) { return repository.findById(themeId, MANAGE_THEMES) .switchIfEmpty(Mono.error( new AppsmithException(AppsmithError.NO_RESOURCE_FOUND, FieldName.APPLICATION, FieldName.THEME)) diff --git a/app/server/appsmith-server/src/test/java/com/appsmith/server/services/ActionCollectionServiceImplTest.java b/app/server/appsmith-server/src/test/java/com/appsmith/server/services/ActionCollectionServiceImplTest.java index 21ee43b85575..d021fdd71043 100644 --- a/app/server/appsmith-server/src/test/java/com/appsmith/server/services/ActionCollectionServiceImplTest.java +++ b/app/server/appsmith-server/src/test/java/com/appsmith/server/services/ActionCollectionServiceImplTest.java @@ -455,7 +455,7 @@ public void testUpdateUnpublishedActionCollection_withModifiedCollection_returns .collect(Collectors.toSet()) .containsAll(Set.of("testActionId1", "testActionId3"))); Assert.assertEquals("testActionId2", actionCollectionDTO1.getArchivedActions().get(0).getId()); - Assert.assertTrue(archivedAfter.isBefore(actionCollectionDTO1.getArchivedActions().get(0).getArchivedAt())); + Assert.assertTrue(archivedAfter.isBefore(actionCollectionDTO1.getArchivedActions().get(0).getDeletedAt())); }) .verifyComplete(); } @@ -570,7 +570,7 @@ public void testDeleteUnpublishedActionCollection_withoutPublishedCollectionAndN .thenReturn(Mono.just(actionCollection)); Mockito - .when(actionCollectionRepository.delete(Mockito.any())) + .when(actionCollectionRepository.archive(Mockito.any())) .thenReturn(Mono.empty()); final Mono<ActionCollectionDTO> actionCollectionDTOMono = actionCollectionService.deleteUnpublishedActionCollection("testCollectionId"); @@ -603,11 +603,11 @@ public void testDeleteUnpublishedActionCollection_withoutPublishedCollectionAndW .thenReturn(Mono.just(actionCollection)); Mockito - .when(newActionService.delete(Mockito.any())) + .when(newActionService.archiveById(Mockito.any())) .thenReturn(Mono.just(new NewAction())); Mockito - .when(actionCollectionRepository.delete(Mockito.any())) + .when(actionCollectionRepository.archive(Mockito.any())) .thenReturn(Mono.empty()); final Mono<ActionCollectionDTO> actionCollectionDTOMono = actionCollectionService.deleteUnpublishedActionCollection("testCollectionId"); diff --git a/app/server/appsmith-server/src/test/java/com/appsmith/server/services/ApplicationServiceTest.java b/app/server/appsmith-server/src/test/java/com/appsmith/server/services/ApplicationServiceTest.java index c6de905dd200..cc55b0606753 100644 --- a/app/server/appsmith-server/src/test/java/com/appsmith/server/services/ApplicationServiceTest.java +++ b/app/server/appsmith-server/src/test/java/com/appsmith/server/services/ApplicationServiceTest.java @@ -21,6 +21,7 @@ import com.appsmith.server.domains.Organization; import com.appsmith.server.domains.Plugin; import com.appsmith.server.domains.PluginType; +import com.appsmith.server.domains.QNewAction; import com.appsmith.server.domains.Theme; import com.appsmith.server.domains.User; import com.appsmith.server.dtos.ActionCollectionDTO; @@ -55,6 +56,8 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.mock.mockito.MockBean; +import org.springframework.data.mongodb.core.ReactiveMongoOperations; +import org.springframework.data.mongodb.core.query.Query; import org.springframework.http.HttpMethod; import org.springframework.security.test.context.support.WithUserDetails; import org.springframework.test.annotation.DirtiesContext; @@ -66,6 +69,7 @@ import reactor.core.publisher.Mono; import reactor.test.StepVerifier; import reactor.util.function.Tuple2; +import reactor.util.function.Tuple3; import java.time.Duration; import java.util.ArrayList; @@ -74,6 +78,7 @@ import java.util.HashSet; import java.util.List; import java.util.Map; +import java.util.Optional; import java.util.Set; import java.util.stream.Collectors; @@ -89,8 +94,11 @@ import static com.appsmith.server.acl.AclPermission.READ_DATASOURCES; import static com.appsmith.server.acl.AclPermission.READ_PAGES; import static com.appsmith.server.constants.FieldName.DEFAULT_PAGE_LAYOUT; +import static com.appsmith.server.repositories.BaseAppsmithRepositoryImpl.fieldName; import static com.appsmith.server.services.ApplicationPageServiceImpl.EVALUATION_VERSION; import static org.assertj.core.api.Assertions.assertThat; +import static org.springframework.data.mongodb.core.query.Criteria.where; +import static org.springframework.data.mongodb.core.query.Query.query; @RunWith(SpringRunner.class) @SpringBootTest @@ -161,6 +169,9 @@ public class ApplicationServiceTest { @MockBean PluginExecutor pluginExecutor; + @Autowired + ReactiveMongoOperations mongoOperations; + String orgId; static Plugin testPlugin = new Plugin(); @@ -208,6 +219,15 @@ public void setup() { } } + private Mono<? extends BaseDomain> getArchivedResource(String id, Class<? extends BaseDomain> domainClass) { + Query query = new Query(where("id").is(id)); + + final Query actionQuery = query(where(fieldName(QNewAction.newAction.applicationId)).exists(true)) + .addCriteria(where(fieldName(QNewAction.newAction.unpublishedAction) + "." + fieldName(QNewAction.newAction.unpublishedAction.archivedAt)).exists(true)); + + return mongoOperations.findOne(query, domainClass); + } + @Test @WithUserDetails(value = "api_user") public void createApplicationWithNullName() { @@ -1490,6 +1510,120 @@ public void basicPublishApplicationTest() { .verifyComplete(); } + /** + * Method to test if the action, pages and actionCollection are archived after the application is published + */ + @Test + @WithUserDetails(value = "api_user") + public void publishApplication_withArchivedUnpublishedResources_resourcesArchived() { + + /* + 1. Create application + 2. Add action and actionCollection + 3. Publish application + 4. Delete page in edit mode + 5. Publish application + 6. Page, action and actionCollection should be soft deleted + */ + Application testApplication = new Application(); + String appName = "Publish Application With Archived Page"; + testApplication.setName(appName); + testApplication.setAppLayout(new Application.AppLayout(Application.AppLayout.Type.DESKTOP)); + Mono<Tuple3<NewAction, ActionCollection, NewPage>> resultMono = applicationPageService.createApplication(testApplication, orgId) + .flatMap(application -> { + PageDTO page = new PageDTO(); + page.setName("New Page"); + page.setApplicationId(application.getId()); + Layout defaultLayout = newPageService.createDefaultLayout(); + List<Layout> layouts = new ArrayList<>(); + layouts.add(defaultLayout); + page.setLayouts(layouts); + return Mono.zip( + applicationPageService.createPage(page), + pluginRepository.findByPackageName("installed-plugin") + ); + }) + .flatMap(tuple -> { + final PageDTO page = tuple.getT1(); + final Plugin installedPlugin = tuple.getT2(); + final Datasource datasource = new Datasource(); + datasource.setName("Default Database"); + datasource.setOrganizationId(orgId); + datasource.setPluginId(installedPlugin.getId()); + datasource.setDatasourceConfiguration(new DatasourceConfiguration()); + + ActionDTO action = new ActionDTO(); + action.setName("publishActionTest"); + action.setPageId(page.getId()); + action.setExecuteOnLoad(true); + ActionConfiguration actionConfiguration = new ActionConfiguration(); + actionConfiguration.setHttpMethod(HttpMethod.GET); + action.setActionConfiguration(actionConfiguration); + action.setDatasource(datasource); + + // Save actionCollection + ActionCollectionDTO actionCollectionDTO = new ActionCollectionDTO(); + actionCollectionDTO.setName("publishCollectionTest"); + actionCollectionDTO.setPageId(page.getId()); + actionCollectionDTO.setPluginId(datasource.getPluginId()); + actionCollectionDTO.setApplicationId(testApplication.getId()); + actionCollectionDTO.setOrganizationId(testApplication.getOrganizationId()); + actionCollectionDTO.setVariables(List.of(new JSValue("test", "String", "test", true))); + ActionDTO action1 = new ActionDTO(); + action1.setName("publishApplicationTest"); + action1.setActionConfiguration(new ActionConfiguration()); + actionCollectionDTO.setActions(List.of(action1)); + actionCollectionDTO.setPluginType(PluginType.JS); + + return layoutActionService.createSingleAction(action) + .zipWith(layoutCollectionService.createCollection(actionCollectionDTO)) + .flatMap(tuple1 -> { + ActionDTO savedAction = tuple1.getT1(); + ActionCollectionDTO savedActionCollection = tuple1.getT2(); + return applicationPageService.publish(testApplication.getId(), true) + .then(applicationPageService.deleteUnpublishedPage(page.getId())) + .then(applicationPageService.publish(testApplication.getId(), true)) + .then( + Mono.zip( + (Mono<NewAction>) this.getArchivedResource(savedAction.getId(), NewAction.class), + (Mono<ActionCollection>) this.getArchivedResource(savedActionCollection.getId(), ActionCollection.class), + (Mono<NewPage>) this.getArchivedResource(page.getId(), NewPage.class) + )); + }); + }) + .cache(); + + Mono<NewAction> archivedActionFromActionCollectionMono = resultMono + .flatMap(tuple -> { + final Optional<String> actionId = tuple.getT2().getUnpublishedCollection().getDefaultToBranchedActionIdsMap().values() + .stream() + .findFirst(); + return (Mono<NewAction>) this.getArchivedResource(actionId.get(), NewAction.class); + }); + + StepVerifier + .create(resultMono.zipWith(archivedActionFromActionCollectionMono)) + .assertNext(tuple -> { + NewAction archivedAction = tuple.getT1().getT1(); + ActionCollection archivedActionCollection = tuple.getT1().getT2(); + NewPage archivedPage = tuple.getT1().getT3(); + NewAction archivedActionFromActionCollection = tuple.getT2(); + + assertThat(archivedAction.getDeletedAt()).isNotNull(); + assertThat(archivedAction.getDeleted()).isTrue(); + + assertThat(archivedActionCollection.getDeletedAt()).isNotNull(); + assertThat(archivedActionCollection.getDeleted()).isTrue(); + + assertThat(archivedPage.getDeletedAt()).isNotNull(); + assertThat(archivedPage.getDeleted()).isTrue(); + + assertThat(archivedActionFromActionCollection.getDeletedAt()).isNotNull(); + assertThat(archivedActionFromActionCollection.getDeleted()).isTrue(); + }) + .verifyComplete(); + } + @Test @WithUserDetails(value = "api_user") public void publishApplication_withGitConnectedApp_success() { @@ -2181,13 +2315,19 @@ public void generateSshKeyPair_WhenDefaultApplicationIdSet_DefaultApplicationUpd @Test @WithUserDetails(value = "api_user") - public void deleteApplicationWithPagesAndActions() { - + public void deleteApplication_withPagesActionsAndActionCollections_resourcesArchived() { + + /* + 1. Create application + 2. Add page, action and actionCollection + 5. Delete application + 6. Page, action and actionCollection should be soft deleted + */ Application testApplication = new Application(); String appName = "deleteApplicationWithPagesAndActions"; testApplication.setName(appName); - Mono<NewAction> resultMono = applicationPageService.createApplication(testApplication, orgId) + Mono<Tuple3<NewAction, ActionCollection, NewPage>> resultMono = applicationPageService.createApplication(testApplication, orgId) .flatMap(application -> { PageDTO page = new PageDTO(); page.setName("New Page"); @@ -2220,17 +2360,65 @@ public void deleteApplicationWithPagesAndActions() { action.setActionConfiguration(actionConfiguration); action.setDatasource(datasource); + // Save actionCollection + ActionCollectionDTO actionCollectionDTO = new ActionCollectionDTO(); + actionCollectionDTO.setName("testCollection1"); + actionCollectionDTO.setPageId(page.getId()); + actionCollectionDTO.setPluginId(datasource.getPluginId()); + actionCollectionDTO.setApplicationId(testApplication.getId()); + actionCollectionDTO.setOrganizationId(testApplication.getOrganizationId()); + actionCollectionDTO.setVariables(List.of(new JSValue("test", "String", "test", true))); + ActionDTO action1 = new ActionDTO(); + action1.setName("archivePageTest"); + action1.setActionConfiguration(new ActionConfiguration()); + actionCollectionDTO.setActions(List.of(action1)); + actionCollectionDTO.setPluginType(PluginType.JS); + return layoutActionService.createSingleAction(action) - .flatMap(action1 -> { + .zipWith(layoutCollectionService.createCollection(actionCollectionDTO)) + .flatMap(tuple1 -> { + ActionDTO savedAction = tuple1.getT1(); + ActionCollectionDTO savedActionCollection = tuple1.getT2(); return applicationService.findById(page.getApplicationId(), MANAGE_APPLICATIONS) .flatMap(application -> applicationPageService.deleteApplication(application.getId())) - .flatMap(ignored -> newActionService.findById(action1.getId())); + .flatMap(ignored -> + Mono.zip( + (Mono<NewAction>) this.getArchivedResource(savedAction.getId(), NewAction.class), + (Mono<ActionCollection>) this.getArchivedResource(savedActionCollection.getId(), ActionCollection.class), + (Mono<NewPage>) this.getArchivedResource(page.getId(), NewPage.class) + )); }); + }) + .cache(); + + Mono<NewAction> archivedActionFromActionCollectionMono = resultMono + .flatMap(tuple -> { + final Optional<String> actionId = tuple.getT2().getUnpublishedCollection().getDefaultToBranchedActionIdsMap().values() + .stream() + .findFirst(); + return (Mono<NewAction>) this.getArchivedResource(actionId.get(), NewAction.class); }); StepVerifier - .create(resultMono) - // Since the action should be deleted, we exmpty the Mono to complete empty. + .create(resultMono.zipWith(archivedActionFromActionCollectionMono)) + .assertNext(tuple -> { + NewAction archivedAction = tuple.getT1().getT1(); + ActionCollection archivedActionCollection = tuple.getT1().getT2(); + NewPage archivedPage = tuple.getT1().getT3(); + NewAction archivedActionFromActionCollection = tuple.getT2(); + + assertThat(archivedAction.getDeletedAt()).isNotNull(); + assertThat(archivedAction.getDeleted()).isTrue(); + + assertThat(archivedActionCollection.getDeletedAt()).isNotNull(); + assertThat(archivedActionCollection.getDeleted()).isTrue(); + + assertThat(archivedPage.getDeletedAt()).isNotNull(); + assertThat(archivedPage.getDeleted()).isTrue(); + + assertThat(archivedActionFromActionCollection.getDeletedAt()).isNotNull(); + assertThat(archivedActionFromActionCollection.getDeleted()).isTrue(); + }) .verifyComplete(); } diff --git a/app/server/appsmith-server/src/test/java/com/appsmith/server/services/DatasourceServiceTest.java b/app/server/appsmith-server/src/test/java/com/appsmith/server/services/DatasourceServiceTest.java index 70a2016dbd1d..760465ae5685 100644 --- a/app/server/appsmith-server/src/test/java/com/appsmith/server/services/DatasourceServiceTest.java +++ b/app/server/appsmith-server/src/test/java/com/appsmith/server/services/DatasourceServiceTest.java @@ -499,7 +499,7 @@ public void deleteDatasourceWithoutActions() { return datasource; }) .flatMap(datasourceService::create) - .flatMap(datasource1 -> datasourceService.delete(datasource1.getId())); + .flatMap(datasource1 -> datasourceService.archiveById(datasource1.getId())); StepVerifier .create(datasourceMono) @@ -571,7 +571,7 @@ public void deleteDatasourceWithActions() { return layoutActionService.createSingleAction(action).thenReturn(datasource); }) - .flatMap(datasource -> datasourceService.delete(datasource.getId())); + .flatMap(datasource -> datasourceService.archiveById(datasource.getId())); StepVerifier .create(datasourceMono) @@ -640,7 +640,7 @@ public void deleteDatasourceWithDeletedActions() { .then(applicationPageService.deleteApplication(application.getId())) .thenReturn(datasource); }) - .flatMap(datasource -> datasourceService.delete(datasource.getId())); + .flatMap(datasource -> datasourceService.archiveById(datasource.getId())); StepVerifier .create(datasourceMono) diff --git a/app/server/appsmith-server/src/test/java/com/appsmith/server/services/OrganizationServiceTest.java b/app/server/appsmith-server/src/test/java/com/appsmith/server/services/OrganizationServiceTest.java index 145f8e9dab92..4c907aeedc63 100644 --- a/app/server/appsmith-server/src/test/java/com/appsmith/server/services/OrganizationServiceTest.java +++ b/app/server/appsmith-server/src/test/java/com/appsmith/server/services/OrganizationServiceTest.java @@ -1095,7 +1095,7 @@ public void delete_WhenOrgHasApp_ThrowsException() { application.setName("Test app to test delete org"); return applicationPageService.createApplication(application); }).flatMap(application -> - organizationService.delete(application.getOrganizationId()) + organizationService.archiveById(application.getOrganizationId()) ); StepVerifier @@ -1123,7 +1123,7 @@ public void delete_WithoutManagePermission_ThrowsException() { Mono<Organization> deleteOrgMono = organizationRepository.save(organization) .flatMap(savedOrg -> - organizationService.delete(savedOrg.getId()) + organizationService.archiveById(savedOrg.getId()) ); StepVerifier @@ -1140,7 +1140,7 @@ public void delete_WhenOrgHasNoApp_OrgIsDeleted() { Mono<Organization> deleteOrgMono = organizationService.create(organization) .flatMap(savedOrg -> - organizationService.delete(savedOrg.getId()) + organizationService.archiveById(savedOrg.getId()) .then(organizationRepository.findById(savedOrg.getId())) ); diff --git a/app/server/appsmith-server/src/test/java/com/appsmith/server/services/ThemeServiceTest.java b/app/server/appsmith-server/src/test/java/com/appsmith/server/services/ThemeServiceTest.java index 06a74df0bd2b..a3358d1d39dc 100644 --- a/app/server/appsmith-server/src/test/java/com/appsmith/server/services/ThemeServiceTest.java +++ b/app/server/appsmith-server/src/test/java/com/appsmith/server/services/ThemeServiceTest.java @@ -652,7 +652,7 @@ public void persistCurrentTheme_WhenSystemThemeIsSet_NewApplicationThemeCreated( @WithUserDetails("api_user") @Test public void delete_WhenSystemTheme_NotAllowed() { - StepVerifier.create(themeService.getDefaultThemeId().flatMap(themeService::delete)) + StepVerifier.create(themeService.getDefaultThemeId().flatMap(themeService::archiveById)) .expectError(AppsmithException.class) .verify(); } @@ -671,7 +671,7 @@ public void delete_WhenUnsavedCustomizedTheme_NotAllowed() { Theme themeCustomization = new Theme(); themeCustomization.setName("Updated name"); return themeService.updateTheme(savedApplication.getId(), themeCustomization); - }).flatMap(customizedTheme -> themeService.delete(customizedTheme.getId())); + }).flatMap(customizedTheme -> themeService.archiveById(customizedTheme.getId())); StepVerifier.create(deleteThemeMono) .expectErrorMessage(AppsmithError.UNSUPPORTED_OPERATION.getMessage()) @@ -693,7 +693,7 @@ public void delete_WhenSavedCustomizedTheme_ThemeIsDeleted() { themeCustomization.setName("Updated name"); return themeService.persistCurrentTheme(savedApplication.getId(), themeCustomization); }) - .flatMap(customizedTheme -> themeService.delete(customizedTheme.getId()) + .flatMap(customizedTheme -> themeService.archiveById(customizedTheme.getId()) .then(themeService.getThemeById(customizedTheme.getId(), READ_THEMES))); StepVerifier.create(deleteThemeMono).verifyComplete();
fc30554cb557bd038ac6b241bce7f0658dc73016
2021-08-17 13:41:41
Sumit Kumar
fix: Redis plugin: extract cmd and args based on regex (#6648)
false
Redis plugin: extract cmd and args based on regex (#6648)
fix
diff --git a/app/server/appsmith-plugins/redisPlugin/src/main/java/com/external/plugins/RedisPlugin.java b/app/server/appsmith-plugins/redisPlugin/src/main/java/com/external/plugins/RedisPlugin.java index d156efcb105c..e6908d9f07f8 100644 --- a/app/server/appsmith-plugins/redisPlugin/src/main/java/com/external/plugins/RedisPlugin.java +++ b/app/server/appsmith-plugins/redisPlugin/src/main/java/com/external/plugins/RedisPlugin.java @@ -30,17 +30,22 @@ import java.net.URI; import java.time.Duration; -import java.util.Arrays; +import java.util.ArrayList; +import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; +import java.util.regex.Matcher; +import java.util.regex.Pattern; import java.util.stream.Collectors; import static com.appsmith.external.constants.ActionConstants.ACTION_CONFIGURATION_BODY; public class RedisPlugin extends BasePlugin { private static final int CONNECTION_TIMEOUT = 60; + private static final String CMD_KEY = "cmd"; + private static final String ARGS_KEY = "args"; public RedisPlugin(PluginWrapper wrapper) { super(wrapper); @@ -68,21 +73,29 @@ public Mono<ActionExecutionResult> execute(JedisPool jedisPool, String.format("Body is null or empty [%s]", query))); } - // First value will be the redis command and others are arguments for that command - String[] bodySplitted = query.trim().split("\\s+"); + Map cmdAndArgs = getCommandAndArgs(query.trim()); + if (!cmdAndArgs.containsKey(CMD_KEY)) { + return Mono.error( + new AppsmithPluginException( + AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, + "Appsmith server has failed to parse your Redis query. Are you sure it's" + + " been formatted correctly." + ) + ); + } Protocol.Command command; try { // Commands are in upper case - command = Protocol.Command.valueOf(bodySplitted[0].toUpperCase()); + command = Protocol.Command.valueOf((String) cmdAndArgs.get(CMD_KEY)); } catch (IllegalArgumentException exc) { return Mono.error(new AppsmithPluginException(AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, - String.format("Not a valid Redis command:%s", bodySplitted[0]))); + String.format("Not a valid Redis command: %s", cmdAndArgs.get(CMD_KEY)))); } Object commandOutput; - if (bodySplitted.length > 1) { - commandOutput = jedis.sendCommand(command, Arrays.copyOfRange(bodySplitted, 1, bodySplitted.length)); + if (cmdAndArgs.containsKey(ARGS_KEY)) { + commandOutput = jedis.sendCommand(command, (String[]) cmdAndArgs.get(ARGS_KEY)); } else { commandOutput = jedis.sendCommand(command); } @@ -125,6 +138,39 @@ public Mono<ActionExecutionResult> execute(JedisPool jedisPool, .subscribeOn(scheduler); } + private Map getCommandAndArgs(String query) { + /** + * - This regex matches either a whole word, or anything inside double quotes. If something is inside + * single quotes then it gets matched like a whole word + * - e.g. if the query string is: set key 'test match' "my val" '{"a":"b"}', then the regex matches the following: + * (1) set + * (2) key + * (3) 'test match' + * (4) "my val" + * (5) '{"a":"b"}' + * Please note that the above example string is not a valid redis cmd and is only mentioned here for info. + */ + String redisCmdRegex = "\\\"[^\\\"]+\\\"|'[^']+'|[\\S]+"; + Pattern pattern = Pattern.compile(redisCmdRegex); + Matcher matcher = pattern.matcher(query); + Map<String, Object> cmdAndArgs = new HashMap<>(); + List<String> args = new ArrayList<>(); + while (matcher.find()) { + if (!cmdAndArgs.containsKey(CMD_KEY)) { + cmdAndArgs.put(CMD_KEY, matcher.group().toUpperCase()); + } + else { + args.add(matcher.group()); + } + } + + if (args.size() > 0) { + cmdAndArgs.put(ARGS_KEY, args.toArray(new String[0])); + } + + return cmdAndArgs; + } + // This will be updated as we encounter different outputs. private List<Map<String, String>> processCommandOutput(Object commandOutput) { if (commandOutput == null) { @@ -141,7 +187,6 @@ private List<Map<String, String>> processCommandOutput(Object commandOutput) { } } - /** * - Config taken from https://www.baeldung.com/jedis-java-redis-client-library * - To understand what these config mean: diff --git a/app/server/appsmith-plugins/redisPlugin/src/test/java/com/external/plugins/RedisPluginTest.java b/app/server/appsmith-plugins/redisPlugin/src/test/java/com/external/plugins/RedisPluginTest.java index 09b241184bcf..f00aaff1d980 100644 --- a/app/server/appsmith-plugins/redisPlugin/src/test/java/com/external/plugins/RedisPluginTest.java +++ b/app/server/appsmith-plugins/redisPlugin/src/test/java/com/external/plugins/RedisPluginTest.java @@ -241,12 +241,13 @@ public void itShouldExecuteCommandWithArgs() { expectedRequestParams.toString()); }).verifyComplete(); - // Setting a key - ActionConfiguration setActionConfiguration = new ActionConfiguration(); - setActionConfiguration.setBody("SET key value"); + // Set keys + ActionConfiguration setActionConfigurationManyKeys = new ActionConfiguration(); + setActionConfigurationManyKeys.setBody("mset key1 value key2 \"value\" key3 \"my value\" key4 'value' key5 'my " + + "value' key6 '{\"a\":\"b\"}'"); actionExecutionResultMono = jedisPoolMono .flatMap(jedisPool -> pluginExecutor.execute(jedisPool, datasourceConfiguration, - setActionConfiguration)); + setActionConfigurationManyKeys)); StepVerifier.create(actionExecutionResultMono) .assertNext(actionExecutionResult -> { Assert.assertNotNull(actionExecutionResult); @@ -255,16 +256,23 @@ public void itShouldExecuteCommandWithArgs() { Assert.assertEquals("OK", node.get("result").asText()); }).verifyComplete(); - // Getting the key + // Verify the keys + ActionConfiguration getActionConfigurationManyKeys = new ActionConfiguration(); + getActionConfigurationManyKeys.setBody("mget key1 key2 key3 key4 key5 key6"); actionExecutionResultMono = jedisPoolMono .flatMap(jedisPool -> pluginExecutor.execute(jedisPool, datasourceConfiguration, - getActionConfiguration)); + getActionConfigurationManyKeys)); StepVerifier.create(actionExecutionResultMono) .assertNext(actionExecutionResult -> { Assert.assertNotNull(actionExecutionResult); Assert.assertNotNull(actionExecutionResult.getBody()); - final JsonNode node = ((ArrayNode) actionExecutionResult.getBody()).get(0); - Assert.assertEquals("value", node.get("result").asText()); + final JsonNode node = ((ArrayNode) actionExecutionResult.getBody()); + Assert.assertEquals("value", node.get(0).get("result").asText()); + Assert.assertEquals("\"value\"", node.get(1).get("result").asText()); + Assert.assertEquals("\"my value\"", node.get(2).get("result").asText()); + Assert.assertEquals("'value'", node.get(3).get("result").asText()); + Assert.assertEquals("'my value'", node.get(4).get("result").asText()); + Assert.assertEquals("'{\"a\":\"b\"}'", node.get(5).get("result").asText()); }).verifyComplete(); }
692e394e731ebde5ae408b3a533475c379a4f2eb
2024-12-30 15:53:32
Rudraprasad Das
chore: git mod - integration app (#38315)
false
git mod - integration app (#38315)
chore
diff --git a/app/client/packages/design-system/ads/src/Icon/Icon.provider.tsx b/app/client/packages/design-system/ads/src/Icon/Icon.provider.tsx index d12bc1f519d5..611ccff4f2a4 100644 --- a/app/client/packages/design-system/ads/src/Icon/Icon.provider.tsx +++ b/app/client/packages/design-system/ads/src/Icon/Icon.provider.tsx @@ -1103,6 +1103,10 @@ const ContentTypeRaw = importSvg( async () => import("../__assets__/icons/ads/content-type-raw.svg"), ); +const CloudIconV2 = importSvg( + async () => import("../__assets__/icons/ads/cloudy-line.svg"), +); + const NotionIcon = importSvg( async () => import("../__assets__/icons/ads/notion.svg"), ); @@ -1225,6 +1229,7 @@ const ICON_LOOKUP = { "close-modal": CloseLineIcon, "close-x": CloseLineIcon, "cloud-off-line": CloudOfflineIcon, + "cloud-v2": CloudIconV2, "collapse-control": CollapseIcon, "column-freeze": ColumnFreeze, "column-unfreeze": SubtractIcon, diff --git a/app/client/src/api/interceptors/request/apiRequestInterceptor.ts b/app/client/src/api/interceptors/request/apiRequestInterceptor.ts index 5371cbbcf23c..4a9d2ed633cc 100644 --- a/app/client/src/api/interceptors/request/apiRequestInterceptor.ts +++ b/app/client/src/api/interceptors/request/apiRequestInterceptor.ts @@ -30,6 +30,7 @@ const blockAirgappedRoutes = (config: InternalAxiosRequestConfig) => { const addGitBranchHeader = (config: InternalAxiosRequestConfig) => { const state = store.getState(); + // ! git mod - not sure how to replace this, we could directly read state if required const branch = getCurrentGitBranch(state) || getQueryParamsObject().branch; return _addGitBranchHeader(config, { branch }); diff --git a/app/client/src/ce/entities/FeatureFlag.ts b/app/client/src/ce/entities/FeatureFlag.ts index d3048a86f9f1..4e3020fd98e2 100644 --- a/app/client/src/ce/entities/FeatureFlag.ts +++ b/app/client/src/ce/entities/FeatureFlag.ts @@ -48,6 +48,7 @@ export const FEATURE_FLAG = { "release_table_html_column_type_enabled", release_gs_all_sheets_options_enabled: "release_gs_all_sheets_options_enabled", + release_git_modularisation_enabled: "release_git_modularisation_enabled", ab_premium_datasources_view_enabled: "ab_premium_datasources_view_enabled", kill_session_recordings_enabled: "kill_session_recordings_enabled", config_mask_session_recordings_enabled: @@ -95,6 +96,7 @@ export const DEFAULT_FEATURE_FLAG_VALUE: FeatureFlags = { release_evaluation_scope_cache: false, release_table_html_column_type_enabled: false, release_gs_all_sheets_options_enabled: false, + release_git_modularisation_enabled: false, ab_premium_datasources_view_enabled: false, kill_session_recordings_enabled: false, config_user_session_recordings_enabled: true, diff --git a/app/client/src/ce/navigation/FocusStrategy/AppIDEFocusStrategy.ts b/app/client/src/ce/navigation/FocusStrategy/AppIDEFocusStrategy.ts index 5729a7e8c59d..fe5440f22f27 100644 --- a/app/client/src/ce/navigation/FocusStrategy/AppIDEFocusStrategy.ts +++ b/app/client/src/ce/navigation/FocusStrategy/AppIDEFocusStrategy.ts @@ -2,7 +2,6 @@ import { all, select, take } from "redux-saga/effects"; import type { FocusPath, FocusStrategy } from "sagas/FocusRetentionSaga"; import type { AppsmithLocationState } from "utils/history"; import { NavigationMethod } from "utils/history"; -import { getCurrentGitBranch } from "selectors/gitSyncSelectors"; import type { FocusEntityInfo } from "navigation/FocusEntity"; import { FocusEntity, @@ -18,6 +17,7 @@ import { widgetListURL, } from "ee/RouteBuilder"; import AppIDEFocusElements from "../FocusElements/AppIDE"; +import { selectGitApplicationCurrentBranch } from "selectors/gitModSelectors"; function shouldSetState( prevPath: string, @@ -86,8 +86,17 @@ const isPageChange = (prevPath: string, currentPath: string) => { ); }; -export const createEditorFocusInfoKey = (basePageId: string, branch?: string) => - `EDITOR_STATE.${basePageId}#${branch}`; +export const createEditorFocusInfoKey = ( + basePageId: string, + branch: string | null = null, +) => { + const r = branch + ? `EDITOR_STATE.${basePageId}#${branch}` + : `EDITOR_STATE.${basePageId}`; + + return r; +}; + export const createEditorFocusInfo = (basePageId: string, branch?: string) => ({ key: createEditorFocusInfoKey(basePageId, branch), entityInfo: { @@ -109,7 +118,9 @@ export const AppIDEFocusStrategy: FocusStrategy = { return []; } - const branch: string | undefined = yield select(getCurrentGitBranch); + const branch: string | undefined = yield select( + selectGitApplicationCurrentBranch, + ); const entities: Array<{ entityInfo: FocusEntityInfo; key: string }> = []; const prevEntityInfo = identifyEntityFromPath(previousPath); const currentEntityInfo = identifyEntityFromPath(currentPath); @@ -136,7 +147,9 @@ export const AppIDEFocusStrategy: FocusStrategy = { return entities; }, *getEntitiesForStore(path: string, currentPath: string) { - const branch: string | undefined = yield select(getCurrentGitBranch); + const branch: string | undefined = yield select( + selectGitApplicationCurrentBranch, + ); const entities: Array<FocusPath> = []; const currentFocusEntityInfo = identifyEntityFromPath(currentPath); const prevFocusEntityInfo = identifyEntityFromPath(path); @@ -179,7 +192,9 @@ export const AppIDEFocusStrategy: FocusStrategy = { appState: EditorState.EDITOR, params: prevFocusEntityInfo.params, }, - key: `EDITOR_STATE.${prevFocusEntityInfo.params.basePageId}#${branch}`, + key: branch + ? `EDITOR_STATE.${prevFocusEntityInfo.params.basePageId}#${branch}` + : `EDITOR_STATE.${prevFocusEntityInfo.params.basePageId}`, }); } diff --git a/app/client/src/ce/pages/Applications/CreateNewAppsOption.test.tsx b/app/client/src/ce/pages/Applications/CreateNewAppsOption.test.tsx index 180268afb6a9..06940dc36fcc 100644 --- a/app/client/src/ce/pages/Applications/CreateNewAppsOption.test.tsx +++ b/app/client/src/ce/pages/Applications/CreateNewAppsOption.test.tsx @@ -9,6 +9,10 @@ import CreateNewAppsOption from "./CreateNewAppsOption"; import { BrowserRouter as Router } from "react-router-dom"; import { unitTestBaseMockStore } from "layoutSystems/common/dropTarget/unitTestUtils"; +jest.mock("selectors/gitModSelectors", () => ({ + selectCombinedPreviewMode: jest.fn(() => false), +})); + const defaultStoreState = { ...unitTestBaseMockStore, tenant: { diff --git a/app/client/src/ce/pages/Applications/index.tsx b/app/client/src/ce/pages/Applications/index.tsx index edd2b60af280..19b45abd74e1 100644 --- a/app/client/src/ce/pages/Applications/index.tsx +++ b/app/client/src/ce/pages/Applications/index.tsx @@ -122,7 +122,6 @@ import { MOBILE_MAX_WIDTH } from "constants/AppConstants"; import { Indices } from "constants/Layers"; import ImportModal from "pages/common/ImportModal"; import SharedUserList from "pages/common/SharedUserList"; -import GitSyncModal from "pages/Editor/gitSync/GitSyncModal"; import ReconnectDatasourceModal from "pages/Editor/gitSync/ReconnectDatasourceModal"; import RepoLimitExceededErrorModal from "pages/Editor/gitSync/RepoLimitExceededErrorModal"; import AnalyticsUtil from "ee/utils/AnalyticsUtil"; @@ -133,6 +132,15 @@ import { getAssetUrl } from "ee/utils/airgapHelpers"; import { ASSETS_CDN_URL } from "constants/ThirdPartyConstants"; import { LayoutSystemTypes } from "layoutSystems/types"; import { getIsAnvilLayoutEnabled } from "layoutSystems/anvil/integrations/selectors"; +import OldGitSyncModal from "pages/Editor/gitSync/GitSyncModal"; +import { useGitModEnabled } from "pages/Editor/gitSync/hooks/modHooks"; +import { GitImportModal as NewGitImportModal } from "git"; + +function GitImportModal() { + const isGitModEnabled = useGitModEnabled(); + + return isGitModEnabled ? <NewGitImportModal /> : <OldGitSyncModal isImport />; +} export const { cloudHosting } = getAppsmithConfigs(); @@ -955,7 +963,7 @@ export function ApplicationsSection(props: any) { isMobile={isMobile} > {workspacesListComponent} - <GitSyncModal isImport /> + <GitImportModal /> <ReconnectDatasourceModal /> </ApplicationContainer> ); diff --git a/app/client/src/ce/pages/Editor/IDE/MainPane/useRoutes.tsx b/app/client/src/ce/pages/Editor/IDE/MainPane/useRoutes.tsx index cac3ae6f84a8..8f16afc63327 100644 --- a/app/client/src/ce/pages/Editor/IDE/MainPane/useRoutes.tsx +++ b/app/client/src/ce/pages/Editor/IDE/MainPane/useRoutes.tsx @@ -34,12 +34,12 @@ import DataSourceEditor from "pages/Editor/DataSourceEditor"; import DatasourceBlankState from "pages/Editor/DataSourceEditor/DatasourceBlankState"; import type { RouteProps } from "react-router"; import { useSelector } from "react-redux"; -import { combinedPreviewModeSelector } from "selectors/editorSelectors"; import { lazy, Suspense } from "react"; import React from "react"; import { retryPromise } from "utils/AppsmithUtils"; import Skeleton from "widgets/Skeleton"; +import { selectCombinedPreviewMode } from "selectors/gitModSelectors"; const FirstTimeUserOnboardingChecklist = lazy(async () => retryPromise( @@ -67,7 +67,7 @@ export interface RouteReturnType extends RouteProps { */ function useRoutes(path: string): RouteReturnType[] { - const isPreviewMode = useSelector(combinedPreviewModeSelector); + const isPreviewMode = useSelector(selectCombinedPreviewMode); return [ { diff --git a/app/client/src/ce/reducers/index.tsx b/app/client/src/ce/reducers/index.tsx index f6bb8801940e..73842c65b5df 100644 --- a/app/client/src/ce/reducers/index.tsx +++ b/app/client/src/ce/reducers/index.tsx @@ -77,6 +77,8 @@ import type { ActiveField } from "reducers/uiReducers/activeFieldEditorReducer"; import type { SelectedWorkspaceReduxState } from "ee/reducers/uiReducers/selectedWorkspaceReducer"; import type { ConsolidatedPageLoadState } from "reducers/uiReducers/consolidatedPageLoadReducer"; import type { BuildingBlocksReduxState } from "reducers/uiReducers/buildingBlockReducer"; +import type { GitArtifactRootReduxState, GitGlobalReduxState } from "git"; +import { gitReducer } from "git/store"; export const reducerObject = { entities: entityReducer, @@ -86,6 +88,7 @@ export const reducerObject = { settings: SettingsReducer, tenant: tenantReducer, linting: lintErrorReducer, + git: gitReducer, }; export interface AppState { @@ -176,4 +179,8 @@ export interface AppState { // TODO: Fix this the next time the file is edited // eslint-disable-next-line @typescript-eslint/no-explicit-any tenant: TenantReduxState<any>; + git: { + global: GitGlobalReduxState; + artifacts: GitArtifactRootReduxState; + }; } diff --git a/app/client/src/ce/reducers/uiReducers/applicationsReducer.tsx b/app/client/src/ce/reducers/uiReducers/applicationsReducer.tsx index dd2f5b5c4060..97830da22ff3 100644 --- a/app/client/src/ce/reducers/uiReducers/applicationsReducer.tsx +++ b/app/client/src/ce/reducers/uiReducers/applicationsReducer.tsx @@ -25,6 +25,8 @@ import { import produce from "immer"; import { isEmpty } from "lodash"; import type { ApplicationPayload } from "entities/Application"; +import { gitConnectSuccess, type GitConnectSuccessPayload } from "git"; +import type { PayloadAction } from "@reduxjs/toolkit"; export const initialState: ApplicationsReduxState = { isSavingAppName: false, @@ -744,6 +746,20 @@ export const handlers = { isSavingNavigationSetting: false, }; }, + // git + [gitConnectSuccess.type]: ( + state: ApplicationsReduxState, + action: PayloadAction<GitConnectSuccessPayload>, + ) => { + return { + ...state, + currentApplication: { + ...state.currentApplication, + gitApplicationMetadata: + action.payload.responseData.gitApplicationMetadata, + }, + }; + }, }; const applicationsReducer = createReducer(initialState, handlers); diff --git a/app/client/src/ce/sagas/PageSagas.tsx b/app/client/src/ce/sagas/PageSagas.tsx index d1c8e1e86837..aad81e9f8720 100644 --- a/app/client/src/ce/sagas/PageSagas.tsx +++ b/app/client/src/ce/sagas/PageSagas.tsx @@ -75,7 +75,6 @@ import { import { IncorrectBindingError, validateResponse } from "sagas/ErrorSagas"; import type { ApiResponse } from "api/ApiResponses"; import { - combinedPreviewModeSelector, getCurrentApplicationId, getCurrentLayoutId, getCurrentPageId, @@ -128,7 +127,6 @@ import { getPageList } from "ee/selectors/entitiesSelector"; import { setPreviewModeAction } from "actions/editorActions"; import { SelectionRequestType } from "sagas/WidgetSelectUtils"; import { toast } from "@appsmith/ads"; -import { getCurrentGitBranch } from "selectors/gitSyncSelectors"; import type { MainCanvasReduxState } from "reducers/uiReducers/mainCanvasReducer"; import { UserCancelledActionExecutionError } from "sagas/ActionExecution/errorUtils"; import { getInstanceId } from "ee/selectors/tenantSelectors"; @@ -150,6 +148,10 @@ import { getIsAnvilLayout } from "layoutSystems/anvil/integrations/selectors"; import { convertToBasePageIdSelector } from "selectors/pageListSelectors"; import type { Page } from "entities/Page"; import { ConsolidatedPageLoadApi } from "api"; +import { + selectCombinedPreviewMode, + selectGitApplicationCurrentBranch, +} from "selectors/gitModSelectors"; export const checkIfMigrationIsNeeded = ( fetchPageResponse?: FetchPageResponse, @@ -172,7 +174,9 @@ export function* refreshTheApp() { const currentPageId: string = yield select(getCurrentPageId); const defaultBasePageId: string = yield select(getDefaultBasePageId); const pagesList: Page[] = yield select(getPageList); - const gitBranch: string = yield select(getCurrentGitBranch); + const gitBranch: string | undefined = yield select( + selectGitApplicationCurrentBranch, + ); const isCurrentPageIdInList = pagesList.filter((page) => page.pageId === currentPageId).length > 0; @@ -637,7 +641,7 @@ export function* saveLayoutSaga(action: ReduxAction<{ isRetry?: boolean }>) { try { const currentPageId: string = yield select(getCurrentPageId); const currentPage: Page = yield select(getPageById(currentPageId)); - const isPreviewMode: boolean = yield select(combinedPreviewModeSelector); + const isPreviewMode: boolean = yield select(selectCombinedPreviewMode); const appMode: APP_MODE | undefined = yield select(getAppMode); @@ -1401,7 +1405,7 @@ export function* setCanvasCardsStateSaga(action: ReduxAction<string>) { } export function* setPreviewModeInitSaga(action: ReduxAction<boolean>) { - const isPreviewMode: boolean = yield select(combinedPreviewModeSelector); + const isPreviewMode: boolean = yield select(selectCombinedPreviewMode); if (action.payload) { // we animate out elements and then move to the canvas diff --git a/app/client/src/ce/sagas/index.tsx b/app/client/src/ce/sagas/index.tsx index 844f9406af82..af60e7dc4b93 100644 --- a/app/client/src/ce/sagas/index.tsx +++ b/app/client/src/ce/sagas/index.tsx @@ -52,6 +52,7 @@ import sendSideBySideWidgetHoverAnalyticsEventSaga from "sagas/AnalyticsSaga"; /* Sagas that are registered by a module that is designed to be independent of the core platform */ import ternSagas from "sagas/TernSaga"; +import gitSagas from "git/sagas"; export const sagas = [ initSagas, @@ -106,4 +107,5 @@ export const sagas = [ ternSagas, ideSagas, sendSideBySideWidgetHoverAnalyticsEventSaga, + gitSagas, ]; diff --git a/app/client/src/ce/selectors/entitiesSelector.ts b/app/client/src/ce/selectors/entitiesSelector.ts index a020e93ad13a..57daa5964caf 100644 --- a/app/client/src/ce/selectors/entitiesSelector.ts +++ b/app/client/src/ce/selectors/entitiesSelector.ts @@ -51,7 +51,7 @@ import { getEntityNameAndPropertyPath } from "ee/workers/Evaluation/evaluationUt import { getFormValues } from "redux-form"; import { TEMP_DATASOURCE_ID } from "constants/Datasource"; import type { Module } from "ee/constants/ModuleConstants"; -import { getAnvilSpaceDistributionStatus } from "layoutSystems/anvil/integrations/selectors"; +// import { getAnvilSpaceDistributionStatus } from "layoutSystems/anvil/integrations/selectors"; import { getCurrentWorkflowActions, getCurrentWorkflowJSActions, @@ -159,47 +159,48 @@ export const getDatasourceStructureById = ( return state.entities.datasources.structure[id]; }; +// ! git mod - the following function is not getting used /** * Selector to indicate if the widget name should be shown/drawn on canvas */ -export const getShouldShowWidgetName = createSelector( - (state: AppState) => state.ui.widgetDragResize.isResizing, - (state: AppState) => state.ui.widgetDragResize.isDragging, - (state: AppState) => state.ui.editor.isPreviewMode, - (state: AppState) => state.ui.widgetDragResize.isAutoCanvasResizing, - getAnvilSpaceDistributionStatus, - // cannot import other selectors, breaks the app - (state) => { - const gitMetaData = - state.ui.applications.currentApplication?.gitApplicationMetadata; - const isGitConnected = !!(gitMetaData && gitMetaData?.remoteUrl); - const currentBranch = gitMetaData?.branchName; - const { protectedBranches = [] } = state.ui.gitSync; - - if (!isGitConnected || !currentBranch) { - return false; - } else { - return protectedBranches.includes(currentBranch); - } - }, - ( - isResizing, - isDragging, - isPreviewMode, - isAutoCanvasResizing, - isDistributingSpace, - isProtectedMode, - ) => { - return ( - !isResizing && - !isDragging && - !isPreviewMode && - !isAutoCanvasResizing && - !isDistributingSpace && - !isProtectedMode - ); - }, -); +// export const getShouldShowWidgetName = createSelector( +// (state: AppState) => state.ui.widgetDragResize.isResizing, +// (state: AppState) => state.ui.widgetDragResize.isDragging, +// (state: AppState) => state.ui.editor.isPreviewMode, +// (state: AppState) => state.ui.widgetDragResize.isAutoCanvasResizing, +// getAnvilSpaceDistributionStatus, +// // cannot import other selectors, breaks the app +// (state) => { +// const gitMetaData = +// state.ui.applications.currentApplication?.gitApplicationMetadata; +// const isGitConnected = !!(gitMetaData && gitMetaData?.remoteUrl); +// const currentBranch = gitMetaData?.branchName; +// const { protectedBranches = [] } = state.ui.gitSync; + +// if (!isGitConnected || !currentBranch) { +// return false; +// } else { +// return protectedBranches.includes(currentBranch); +// } +// }, +// ( +// isResizing, +// isDragging, +// isPreviewMode, +// isAutoCanvasResizing, +// isDistributingSpace, +// isProtectedMode, +// ) => { +// return ( +// !isResizing && +// !isDragging && +// !isPreviewMode && +// !isAutoCanvasResizing && +// !isDistributingSpace && +// !isProtectedMode +// ); +// }, +// ); export const getDatasourceTableColumns = (datasourceId: string, tableName: string) => (state: AppState) => { diff --git a/app/client/src/components/BottomBar/index.tsx b/app/client/src/components/BottomBar/index.tsx index 565844eacfb4..1b7ad839d868 100644 --- a/app/client/src/components/BottomBar/index.tsx +++ b/app/client/src/components/BottomBar/index.tsx @@ -1,5 +1,4 @@ -import React from "react"; -import QuickGitActions from "pages/Editor/gitSync/QuickGitActions"; +import React, { useCallback } from "react"; import { DebuggerTrigger } from "components/editorComponents/Debugger"; import HelpButton from "pages/Editor/HelpButton"; import ManualUpgrades from "./ManualUpgrades"; @@ -16,19 +15,30 @@ import { softRefreshActions } from "actions/pluginActionActions"; import { START_SWITCH_ENVIRONMENT } from "ee/constants/messages"; import { getIsAnvilEnabledInCurrentApplication } from "layoutSystems/anvil/integrations/selectors"; import PackageUpgradeStatus from "ee/components/BottomBar/PackageUpgradeStatus"; +import OldGitQuickActions from "pages/Editor/gitSync/QuickGitActions"; +import { GitQuickActions } from "git"; +import { useGitModEnabled } from "pages/Editor/gitSync/hooks/modHooks"; + +function GitActions() { + const isGitModEnabled = useGitModEnabled(); + + return isGitModEnabled ? <GitQuickActions /> : <OldGitQuickActions />; +} export default function BottomBar() { const appId = useSelector(getCurrentApplicationId) || ""; - const isPreviewMode = useSelector(previewModeSelector); - const dispatch = useDispatch(); // We check if the current application is an Anvil application. // If it is an Anvil application, we remove the Git features from the bottomBar // as they donot yet work correctly with Anvil. const isAnvilEnabled = useSelector(getIsAnvilEnabledInCurrentApplication); + const isPreviewMode = useSelector(previewModeSelector); + const isGitEnabled = !isAnvilEnabled && !isPreviewMode; + + const dispatch = useDispatch(); - const onChangeEnv = () => { + const onChangeEnv = useCallback(() => { dispatch(softRefreshActions()); - }; + }, [dispatch]); return ( <Container> @@ -41,7 +51,7 @@ export default function BottomBar() { viewMode={isPreviewMode} /> )} - {!isPreviewMode && !isAnvilEnabled && <QuickGitActions />} + {isGitEnabled && <GitActions />} </Wrapper> {!isPreviewMode && ( <Wrapper> diff --git a/app/client/src/components/designSystems/appsmith/header/DeployLinkButton.tsx b/app/client/src/components/designSystems/appsmith/header/DeployLinkButton.tsx index 3257d962223b..91eea09ab4ab 100644 --- a/app/client/src/components/designSystems/appsmith/header/DeployLinkButton.tsx +++ b/app/client/src/components/designSystems/appsmith/header/DeployLinkButton.tsx @@ -1,8 +1,7 @@ import type { ReactNode } from "react"; -import React from "react"; +import React, { useCallback } from "react"; import { Menu, MenuItem, MenuContent, MenuTrigger } from "@appsmith/ads"; import { useSelector, useDispatch } from "react-redux"; -import { getIsGitConnected } from "selectors/gitSyncSelectors"; import { setIsGitSyncModalOpen } from "actions/gitSyncActions"; import { GitSyncModalTab } from "entities/GitSync"; import AnalyticsUtil from "ee/utils/AnalyticsUtil"; @@ -14,32 +13,54 @@ import { Button } from "@appsmith/ads"; import { KBEditorMenuItem } from "ee/pages/Editor/KnowledgeBase/KBEditorMenuItem"; import { useHasConnectToGitPermission } from "pages/Editor/gitSync/hooks/gitPermissionHooks"; import { getIsAnvilEnabledInCurrentApplication } from "layoutSystems/anvil/integrations/selectors"; +import { + useGitConnected, + useGitModEnabled, +} from "pages/Editor/gitSync/hooks/modHooks"; +import { GitDeployMenuItems as GitDeployMenuItemsNew } from "git"; -interface Props { - trigger: ReactNode; - link: string; -} +function GitDeployMenuItems() { + const isGitModEnabled = useGitModEnabled(); -export const DeployLinkButton = (props: Props) => { const dispatch = useDispatch(); - const isGitConnected = useSelector(getIsGitConnected); - const isConnectToGitPermitted = useHasConnectToGitPermission(); - // We check if the current application is an Anvil application. - // If it is an Anvil application, we remove the Git features from the deploy button - // as they donot yet work correctly with Anvil. - const isAnvilEnabled = useSelector(getIsAnvilEnabledInCurrentApplication); - - const goToGitConnectionPopup = () => { + const goToGitConnectionPopup = useCallback(() => { AnalyticsUtil.logEvent("GS_CONNECT_GIT_CLICK", { source: "Deploy button", }); + dispatch( setIsGitSyncModalOpen({ isOpen: true, tab: GitSyncModalTab.GIT_CONNECTION, }), ); - }; + }, [dispatch]); + + return isGitModEnabled ? ( + <GitDeployMenuItemsNew /> + ) : ( + <MenuItem + className="t--connect-to-git-btn" + onClick={goToGitConnectionPopup} + startIcon="git-branch" + > + {CONNECT_TO_GIT_OPTION()} + </MenuItem> + ); +} + +interface Props { + trigger: ReactNode; + link: string; +} + +export const DeployLinkButton = (props: Props) => { + const isGitConnected = useGitConnected(); + const isConnectToGitPermitted = useHasConnectToGitPermission(); + // We check if the current application is an Anvil application. + // If it is an Anvil application, we remove the Git features from the deploy button + // as they donot yet work correctly with Anvil. + const isAnvilEnabled = useSelector(getIsAnvilEnabledInCurrentApplication); return ( <Menu> @@ -54,13 +75,7 @@ export const DeployLinkButton = (props: Props) => { </MenuTrigger> <MenuContent> {!isGitConnected && isConnectToGitPermitted && !isAnvilEnabled && ( - <MenuItem - className="t--connect-to-git-btn" - onClick={goToGitConnectionPopup} - startIcon="git-branch" - > - {CONNECT_TO_GIT_OPTION()} - </MenuItem> + <GitDeployMenuItems /> )} <MenuItem className="t--current-deployed-preview-btn" diff --git a/app/client/src/components/editorComponents/ApiResponseView.test.tsx b/app/client/src/components/editorComponents/ApiResponseView.test.tsx index 11601be68554..9ad68895e52f 100644 --- a/app/client/src/components/editorComponents/ApiResponseView.test.tsx +++ b/app/client/src/components/editorComponents/ApiResponseView.test.tsx @@ -17,6 +17,10 @@ jest.mock("./EntityBottomTabs", () => ({ default: () => <div />, })); +jest.mock("selectors/gitModSelectors", () => ({ + selectCombinedPreviewMode: jest.fn(() => false), +})); + const mockStore = configureStore([]); const storeState = { diff --git a/app/client/src/components/editorComponents/GlobalSearch/HelpBar.tsx b/app/client/src/components/editorComponents/GlobalSearch/HelpBar.tsx index c52eb62c9ef2..0a8fb41ffabe 100644 --- a/app/client/src/components/editorComponents/GlobalSearch/HelpBar.tsx +++ b/app/client/src/components/editorComponents/GlobalSearch/HelpBar.tsx @@ -1,14 +1,13 @@ -import React from "react"; +import React, { useCallback } from "react"; import styled from "styled-components"; -import { connect } from "react-redux"; +import { useDispatch } from "react-redux"; import { getTypographyByKey, Text, TextType } from "@appsmith/ads-old"; import { Icon } from "@appsmith/ads"; import { setGlobalSearchCategory } from "actions/globalSearchActions"; import AnalyticsUtil from "ee/utils/AnalyticsUtil"; import { modText } from "utils/helpers"; import { filterCategories, SEARCH_CATEGORY_ID } from "./utils"; -import { protectedModeSelector } from "selectors/gitSyncSelectors"; -import type { AppState } from "ee/reducers"; +import { useGitProtectedMode } from "pages/Editor/gitSync/hooks/modHooks"; const StyledHelpBar = styled.button` padding: 0 var(--ads-v2-spaces-3); @@ -42,12 +41,18 @@ const StyledHelpBar = styled.button` } `; -interface Props { - toggleShowModal: () => void; - isProtectedMode: boolean; -} +function HelpBar() { + const isProtectedMode = useGitProtectedMode(); + + const dispatch = useDispatch(); + + const toggleShowModal = useCallback(() => { + AnalyticsUtil.logEvent("OPEN_OMNIBAR", { source: "NAVBAR_CLICK" }); + dispatch( + setGlobalSearchCategory(filterCategories[SEARCH_CATEGORY_ID.INIT]), + ); + }, [dispatch]); -function HelpBar({ isProtectedMode, toggleShowModal }: Props) { return ( <StyledHelpBar className="t--global-search-modal-trigger" @@ -63,19 +68,4 @@ function HelpBar({ isProtectedMode, toggleShowModal }: Props) { ); } -const mapStateToProps = (state: AppState) => ({ - isProtectedMode: protectedModeSelector(state), -}); - -// TODO: Fix this the next time the file is edited -// eslint-disable-next-line @typescript-eslint/no-explicit-any -const mapDispatchToProps = (dispatch: any) => ({ - toggleShowModal: () => { - AnalyticsUtil.logEvent("OPEN_OMNIBAR", { source: "NAVBAR_CLICK" }); - dispatch( - setGlobalSearchCategory(filterCategories[SEARCH_CATEGORY_ID.INIT]), - ); - }, -}); - -export default connect(mapStateToProps, mapDispatchToProps)(HelpBar); +export default HelpBar; diff --git a/app/client/src/components/gitContexts/GitApplicationContextProvider.tsx b/app/client/src/components/gitContexts/GitApplicationContextProvider.tsx new file mode 100644 index 000000000000..728636e2f6dd --- /dev/null +++ b/app/client/src/components/gitContexts/GitApplicationContextProvider.tsx @@ -0,0 +1,36 @@ +import React from "react"; +import { useSelector } from "react-redux"; +import { GitArtifactType, GitContextProvider } from "git"; +import { getCurrentApplication } from "ee/selectors/applicationSelectors"; +import { hasCreateNewAppPermission } from "ee/utils/permissionHelpers"; +import { setWorkspaceIdForImport } from "ee/actions/applicationActions"; +import { getCurrentAppWorkspace } from "ee/selectors/selectedWorkspaceSelectors"; +import { applicationStatusTransformer } from "git/artifact-helpers/application"; + +interface GitApplicationContextProviderProps { + children: React.ReactNode; +} + +export default function GitApplicationContextProvider({ + children, +}: GitApplicationContextProviderProps) { + const artifactType = GitArtifactType.Application; + const application = useSelector(getCurrentApplication); + const workspace = useSelector(getCurrentAppWorkspace); + const isCreateNewApplicationPermitted = hasCreateNewAppPermission( + workspace.userPermissions, + ); + + return ( + <GitContextProvider + artifact={application ?? null} + artifactType={artifactType} + baseArtifactId={application?.baseId ?? ""} + isCreateArtifactPermitted={isCreateNewApplicationPermitted} + setWorkspaceIdForImport={setWorkspaceIdForImport} + statusTransformer={applicationStatusTransformer} + > + {children} + </GitContextProvider> + ); +} diff --git a/app/client/src/entities/Engine/AppEditorEngine.ts b/app/client/src/entities/Engine/AppEditorEngine.ts index f5b0f04b228b..a0bfb5372c20 100644 --- a/app/client/src/entities/Engine/AppEditorEngine.ts +++ b/app/client/src/entities/Engine/AppEditorEngine.ts @@ -1,14 +1,4 @@ import { fetchMockDatasources } from "actions/datasourceActions"; -import { - fetchGitProtectedBranchesInit, - fetchGitStatusInit, - remoteUrlInputValue, - resetPullMergeStatus, - fetchBranchesInit, - triggerAutocommitInitAction, - getGitMetadataInitAction, -} from "actions/gitSyncActions"; -import { restoreRecentEntitiesRequest } from "actions/globalSearchActions"; import { resetEditorSuccess } from "actions/initActions"; import { fetchAllPageEntityCompletion, @@ -24,7 +14,6 @@ import { ReduxActionErrorTypes, ReduxActionTypes, } from "ee/constants/ReduxActionConstants"; -import { addBranchParam } from "constants/routes"; import type { APP_MODE } from "entities/App"; import { call, fork, put, select, spawn } from "redux-saga/effects"; import type { EditConsolidatedApi } from "sagas/InitSagas"; @@ -33,12 +22,9 @@ import { reportSWStatus, waitForWidgetConfigBuild, } from "sagas/InitSagas"; -import { - getCurrentGitBranch, - isGitPersistBranchEnabledSelector, -} from "selectors/gitSyncSelectors"; +import { isGitPersistBranchEnabledSelector } from "selectors/gitSyncSelectors"; import AnalyticsUtil from "ee/utils/AnalyticsUtil"; -import history from "utils/history"; +// import history from "utils/history"; import type { AppEnginePayload } from "."; import AppEngine, { ActionsNotFoundError, @@ -71,6 +57,24 @@ import { endSpan, startNestedSpan } from "instrumentation/generateTraces"; import { getCurrentUser } from "selectors/usersSelectors"; import type { User } from "constants/userConstants"; import log from "loglevel"; +import { gitArtifactActions } from "git/store/gitArtifactSlice"; +import { restoreRecentEntitiesRequest } from "actions/globalSearchActions"; +import { + fetchBranchesInit, + fetchGitProtectedBranchesInit, + fetchGitStatusInit, + getGitMetadataInitAction, + remoteUrlInputValue, + resetPullMergeStatus, + triggerAutocommitInitAction, +} from "actions/gitSyncActions"; +import history from "utils/history"; +import { addBranchParam } from "constants/routes"; +import { + selectGitApplicationCurrentBranch, + selectGitModEnabled, +} from "selectors/gitModSelectors"; +import { applicationArtifact } from "git/artifact-helpers/application"; export default class AppEditorEngine extends AppEngine { constructor(mode: APP_MODE) { @@ -281,6 +285,9 @@ export default class AppEditorEngine extends AppEngine { const currentApplication: ApplicationPayload = yield select( getCurrentApplication, ); + const currentBranch: string | undefined = yield select( + selectGitApplicationCurrentBranch, + ); const isGitPersistBranchEnabled: boolean = yield select( isGitPersistBranchEnabledSelector, @@ -288,7 +295,6 @@ export default class AppEditorEngine extends AppEngine { if (isGitPersistBranchEnabled) { const currentUser: User = yield select(getCurrentUser); - const currentBranch: string = yield select(getCurrentGitBranch); if (currentUser?.email && currentApplication?.baseId && currentBranch) { yield setLatestGitBranchInLocal( @@ -317,6 +323,15 @@ export default class AppEditorEngine extends AppEngine { }); } + if (currentApplication?.id) { + yield put( + restoreRecentEntitiesRequest({ + applicationId: currentApplication.id, + branch: currentBranch, + }), + ); + } + if (isFirstTimeUserOnboardingComplete) { yield put({ type: ReduxActionTypes.SET_FIRST_TIME_USER_ONBOARDING_APPLICATION_IDS, @@ -359,22 +374,32 @@ export default class AppEditorEngine extends AppEngine { public *loadGit(applicationId: string, rootSpan: Span) { const loadGitSpan = startNestedSpan("AppEditorEngine.loadGit", rootSpan); + const isGitModEnabled: boolean = yield select(selectGitModEnabled); - const branchInStore: string = yield select(getCurrentGitBranch); + if (isGitModEnabled) { + const currentApplication: ApplicationPayload = yield select( + getCurrentApplication, + ); - yield put( - restoreRecentEntitiesRequest({ - applicationId, - branch: branchInStore, - }), - ); - // init of temporary remote url from old application - yield put(remoteUrlInputValue({ tempRemoteUrl: "" })); - // add branch query to path and fetch status + yield put( + gitArtifactActions.initGitForEditor({ + artifactDef: applicationArtifact(currentApplication.baseId), + artifact: currentApplication, + }), + ); + } else { + const currentBranch: string = yield select( + selectGitApplicationCurrentBranch, + ); + + // init of temporary remote url from old application + yield put(remoteUrlInputValue({ tempRemoteUrl: "" })); + // add branch query to path and fetch status - if (branchInStore) { - history.replace(addBranchParam(branchInStore)); - yield fork(this.loadGitInBackground); + if (currentBranch) { + history.replace(addBranchParam(currentBranch)); + yield fork(this.loadGitInBackground); + } } endSpan(loadGitSpan); @@ -383,7 +408,6 @@ export default class AppEditorEngine extends AppEngine { private *loadGitInBackground() { yield put(fetchBranchesInit()); yield put(fetchGitProtectedBranchesInit()); - yield put(fetchGitProtectedBranchesInit()); yield put(getGitMetadataInitAction()); yield put(triggerAutocommitInitAction()); yield put(fetchGitStatusInit({ compareRemote: true })); diff --git a/app/client/src/entities/Engine/index.ts b/app/client/src/entities/Engine/index.ts index aadfd66a4316..b4eb39475753 100644 --- a/app/client/src/entities/Engine/index.ts +++ b/app/client/src/entities/Engine/index.ts @@ -17,10 +17,10 @@ import history from "utils/history"; import type URLRedirect from "entities/URLRedirect/index"; import URLGeneratorFactory from "entities/URLRedirect/factory"; import { updateBranchLocally } from "actions/gitSyncActions"; -import { getCurrentGitBranch } from "selectors/gitSyncSelectors"; import { restoreIDEEditorViewMode } from "actions/ideActions"; import type { Span } from "instrumentation/types"; import { endSpan, startNestedSpan } from "instrumentation/generateTraces"; +import { selectGitApplicationCurrentBranch } from "selectors/gitModSelectors"; export interface AppEnginePayload { applicationId?: string; @@ -114,12 +114,13 @@ export default abstract class AppEngine { } const application: ApplicationPayload = yield select(getCurrentApplication); - const currentGitBranch: ReturnType<typeof getCurrentGitBranch> = - yield select(getCurrentGitBranch); + const currentBranch: string | undefined = yield select( + selectGitApplicationCurrentBranch, + ); yield put( updateAppStore( - getPersistentAppStore(application.id, branch || currentGitBranch), + getPersistentAppStore(application.id, branch || currentBranch), ), ); const defaultPageId: string = yield select(getDefaultPageId); diff --git a/app/client/src/git/artifact-helpers/application/applicationArtifact.ts b/app/client/src/git/artifact-helpers/application/applicationArtifact.ts new file mode 100644 index 000000000000..7337db575ac6 --- /dev/null +++ b/app/client/src/git/artifact-helpers/application/applicationArtifact.ts @@ -0,0 +1,11 @@ +import { GitArtifactType } from "git/constants/enums"; +import type { GitArtifactDef } from "git/store/types"; + +export default function applicationArtifact( + baseApplicationId: string, +): GitArtifactDef { + return { + artifactType: GitArtifactType.Application, + baseArtifactId: baseApplicationId, + }; +} diff --git a/app/client/src/git/artifactHelpers/application/statusTransformer.ts b/app/client/src/git/artifact-helpers/application/applicationStatusTransformer.ts similarity index 62% rename from app/client/src/git/artifactHelpers/application/statusTransformer.ts rename to app/client/src/git/artifact-helpers/application/applicationStatusTransformer.ts index 9ac95d9c424e..b803cddfea66 100644 --- a/app/client/src/git/artifactHelpers/application/statusTransformer.ts +++ b/app/client/src/git/artifact-helpers/application/applicationStatusTransformer.ts @@ -1,6 +1,11 @@ import type { FetchStatusResponseData } from "git/requests/fetchStatusRequest.types"; import { objectKeys } from "@appsmith/utils"; -import type { StatusTreeStruct } from "git/components/StatusChanges/StatusTree"; +import { + createMessage, + NOT_PUSHED_YET, + TRY_TO_PULL, +} from "ee/constants/messages"; +import type { StatusTreeStruct } from "git/components/StatusChanges/types"; const ICON_LOOKUP = { query: "query", @@ -8,19 +13,29 @@ const ICON_LOOKUP = { page: "page-line", datasource: "database-2-line", jsLib: "package", + settings: "settings-v3", + theme: "sip-line", + remote: "git-commit", + package: "package", + module: "package", + moduleInstance: "package", }; interface TreeNodeDef { subject: string; verb: string; type: keyof typeof ICON_LOOKUP; + extra?: string; } function createTreeNode(nodeDef: TreeNodeDef) { - return { - icon: ICON_LOOKUP[nodeDef.type], - message: `${nodeDef.subject} ${nodeDef.verb}`, - }; + let message = `${nodeDef.subject} ${nodeDef.verb}`; + + if (nodeDef.extra) { + message += ` ${nodeDef.extra}`; + } + + return { icon: ICON_LOOKUP[nodeDef.type], message }; } function determineVerbForDefs(defs: TreeNodeDef[]) { @@ -45,7 +60,11 @@ function createTreeNodeGroup(nodeDefs: TreeNodeDef[], subject: string) { return { icon: ICON_LOOKUP[nodeDefs[0].type], message: `${nodeDefs.length} ${subject} ${determineVerbForDefs(nodeDefs)}`, - children: nodeDefs.map(createTreeNode), + children: nodeDefs + .sort((a, b) => + a.subject.localeCompare(b.subject, undefined, { sensitivity: "base" }), + ) + .map(createTreeNode), }; } @@ -125,6 +144,10 @@ function statusPageTransformer(status: FetchStatusResponseData) { tree.push({ ...createTreeNode(pageDef), children }); }); + tree.sort((a, b) => + a.message.localeCompare(b.message, undefined, { sensitivity: "base" }), + ); + objectKeys(pageDefLookup).forEach((page) => { if (!pageEntityDefLookup[page]) { tree.push(createTreeNode(pageDefLookup[page])); @@ -186,13 +209,121 @@ function statusJsLibTransformer(status: FetchStatusResponseData) { return tree; } +function statusRemoteCountTransformer(status: FetchStatusResponseData) { + const { aheadCount, behindCount } = status; + const tree = [] as StatusTreeStruct[]; + + if (behindCount > 0) { + tree.push( + createTreeNode({ + subject: `${behindCount} commit${behindCount > 1 ? "s" : ""}`, + verb: "behind", + type: "remote", + extra: createMessage(TRY_TO_PULL), + }), + ); + } + + if (aheadCount > 0) { + tree.push( + createTreeNode({ + subject: `${aheadCount} commit${aheadCount > 1 ? "s" : ""}`, + verb: "ahead", + type: "remote", + extra: createMessage(NOT_PUSHED_YET), + }), + ); + } + + return tree; +} + +function statusSettingsTransformer(status: FetchStatusResponseData) { + const { modified } = status; + const tree = [] as StatusTreeStruct[]; + + if (modified.includes("application.json")) { + tree.push( + createTreeNode({ + subject: "Application settings", + verb: "modified", + type: "settings", + }), + ); + } + + return tree; +} + +function statusThemeTransformer(status: FetchStatusResponseData) { + const { modified } = status; + const tree = [] as StatusTreeStruct[]; + + if (modified.includes("theme.json")) { + tree.push( + createTreeNode({ + subject: "Theme", + verb: "modified", + type: "theme", + }), + ); + } + + return tree; +} + +function statusPackagesTransformer(status: FetchStatusResponseData) { + const { + modifiedModuleInstances = 0, + modifiedModules = 0, + modifiedPackages = 0, + } = status; + const tree = [] as StatusTreeStruct[]; + + if (modifiedPackages > 0) { + tree.push( + createTreeNode({ + subject: `${modifiedPackages} package${modifiedPackages > 1 ? "s" : ""}`, + verb: "modified", + type: "package", + }), + ); + } + + if (modifiedModules > 0) { + tree.push( + createTreeNode({ + subject: `${modifiedModules} module${modifiedModules > 1 ? "s" : ""}`, + verb: "modified", + type: "module", + }), + ); + } + + if (modifiedModuleInstances > 0) { + tree.push( + createTreeNode({ + subject: `${modifiedModuleInstances} module instance${modifiedModuleInstances > 1 ? "s" : ""}`, + verb: "modified", + type: "moduleInstance", + }), + ); + } + + return tree; +} + export default function applicationStatusTransformer( status: FetchStatusResponseData, ) { const tree = [ + ...statusRemoteCountTransformer(status), ...statusPageTransformer(status), ...statusDatasourceTransformer(status), ...statusJsLibTransformer(status), + ...statusSettingsTransformer(status), + ...statusThemeTransformer(status), + ...statusPackagesTransformer(status), ] as StatusTreeStruct[]; return tree; diff --git a/app/client/src/git/artifact-helpers/application/index.ts b/app/client/src/git/artifact-helpers/application/index.ts new file mode 100644 index 000000000000..579a99c7d975 --- /dev/null +++ b/app/client/src/git/artifact-helpers/application/index.ts @@ -0,0 +1,2 @@ +export { default as applicationArtifact } from "./applicationArtifact"; +export { default as applicationStatusTransformer } from "./applicationStatusTransformer"; diff --git a/app/client/src/git/ce/components/GitModals/index.tsx b/app/client/src/git/ce/components/GitModals/index.tsx index a5fcb8c7be36..8bd094fa1ffe 100644 --- a/app/client/src/git/ce/components/GitModals/index.tsx +++ b/app/client/src/git/ce/components/GitModals/index.tsx @@ -1,5 +1,6 @@ import ConflictErrorModal from "git/components/ConflictErrorModal"; import ConnectModal from "git/components/ConnectModal"; +import ConnectSuccessModal from "git/components/ConnectSuccessModal"; import DisableAutocommitModal from "git/components/DisableAutocommitModal"; import DisconnectModal from "git/components/DisconnectModal"; import OpsModal from "git/components/OpsModal"; @@ -10,6 +11,7 @@ function GitModals() { return ( <> <ConnectModal /> + <ConnectSuccessModal /> <OpsModal /> <SettingsModal /> <DisconnectModal /> diff --git a/app/client/src/git/ce/hooks/useDefaultBranch.ts b/app/client/src/git/ce/hooks/useDefaultBranch.ts index 6bc27c1c08c0..53a0f4a1fb01 100644 --- a/app/client/src/git/ce/hooks/useDefaultBranch.ts +++ b/app/client/src/git/ce/hooks/useDefaultBranch.ts @@ -1,17 +1,11 @@ -import { useGitContext } from "git/components/GitContextProvider"; -import { selectDefaultBranch } from "git/store/selectors/gitSingleArtifactSelectors"; -import type { GitRootState } from "git/store/types"; -import { useSelector } from "react-redux"; +import useArtifactSelector from "git/hooks/useArtifactSelector"; +import { selectDefaultBranch } from "git/store/selectors/gitArtifactSelectors"; function useDefaultBranch() { - const { artifactDef } = useGitContext(); - - const defaultBranch = useSelector((state: GitRootState) => - selectDefaultBranch(state, artifactDef), - ); + const defaultBranch = useArtifactSelector(selectDefaultBranch); return { - defaultBranch, + defaultBranch: defaultBranch ?? null, }; } diff --git a/app/client/src/git/components/ConflictErrorModal/ConflictErrorModalView.tsx b/app/client/src/git/components/ConflictErrorModal/ConflictErrorModalView.tsx index d59ff023af40..5090e39c7643 100644 --- a/app/client/src/git/components/ConflictErrorModal/ConflictErrorModalView.tsx +++ b/app/client/src/git/components/ConflictErrorModal/ConflictErrorModalView.tsx @@ -6,7 +6,7 @@ import { CONFLICTS_FOUND_WHILE_PULLING_CHANGES, } from "ee/constants/messages"; -import { Button } from "@appsmith/ads"; +import { Button, Flex } from "@appsmith/ads"; import noop from "lodash/noop"; import ConflictError from "../ConflictError"; @@ -62,18 +62,12 @@ function ConflictErrorModalView({ > <div className={Classes.OVERLAY_CONTENT}> <div className="git-error-popup"> - <div - // ! case: remove inline styles - style={{ - display: "flex", - justifyContent: "space-between", - }} - > - <div style={{ display: "flex", alignItems: "center" }}> + <Flex justifyContent="space-between"> + <Flex alignItems="center"> <span className="title"> {createMessage(CONFLICTS_FOUND_WHILE_PULLING_CHANGES)} </span> - </div> + </Flex> <Button isIconButton kind="tertiary" @@ -81,7 +75,7 @@ function ConflictErrorModalView({ size="sm" startIcon="close-modal" /> - </div> + </Flex> <ConflictError /> </div> </div> diff --git a/app/client/src/git/components/ConflictErrorModal/index.tsx b/app/client/src/git/components/ConflictErrorModal/index.tsx index db9568836032..a67a429aff35 100644 --- a/app/client/src/git/components/ConflictErrorModal/index.tsx +++ b/app/client/src/git/components/ConflictErrorModal/index.tsx @@ -3,11 +3,11 @@ import ConflictErrorModalView from "./ConflictErrorModalView"; import useOps from "git/hooks/useOps"; export default function ConflictErrorModal() { - const { conflictErrorModalOpen, toggleConflictErrorModal } = useOps(); + const { isConflictErrorModalOpen, toggleConflictErrorModal } = useOps(); return ( <ConflictErrorModalView - isConflictErrorModalOpen={conflictErrorModalOpen} + isConflictErrorModalOpen={isConflictErrorModalOpen} toggleConflictErrorModal={toggleConflictErrorModal} /> ); diff --git a/app/client/src/git/components/ConnectModal/ConnectInitialize/AddDeployKey.test.tsx b/app/client/src/git/components/ConnectModal/ConnectInitialize/AddDeployKey.test.tsx deleted file mode 100644 index 176dc5247887..000000000000 --- a/app/client/src/git/components/ConnectModal/ConnectInitialize/AddDeployKey.test.tsx +++ /dev/null @@ -1,231 +0,0 @@ -import React from "react"; -import { render, screen, fireEvent, waitFor } from "@testing-library/react"; -import type { AddDeployKeyProps } from "./AddDeployKey"; -import AddDeployKey from "./AddDeployKey"; -import AnalyticsUtil from "ee/utils/AnalyticsUtil"; -import "@testing-library/jest-dom"; - -jest.mock("ee/utils/AnalyticsUtil", () => ({ - logEvent: jest.fn(), -})); - -jest.mock("copy-to-clipboard", () => ({ - __esModule: true, - default: () => true, -})); - -const DEFAULT_DOCS_URL = - "https://docs.appsmith.com/advanced-concepts/version-control-with-git/connecting-to-git-repository"; - -const defaultProps: AddDeployKeyProps = { - connectError: null, - isLoading: false, - onChange: jest.fn(), - value: { - gitProvider: "github", - isAddedDeployKey: false, - remoteUrl: "[email protected]:owner/repo.git", - }, - fetchSSHKey: jest.fn(), - generateSSHKey: jest.fn(), - isFetchSSHKeyLoading: false, - isGenerateSSHKeyLoading: false, - sshPublicKey: "ecdsa-sha2-nistp256 AAAAE2VjZHNhAAAIBaj...", -}; - -describe("AddDeployKey Component", () => { - beforeEach(() => { - jest.clearAllMocks(); - }); - - it("renders without crashing and shows default UI", () => { - render(<AddDeployKey {...defaultProps} />); - expect( - screen.getByText("Add deploy key & give write access"), - ).toBeInTheDocument(); - expect(screen.getByRole("combobox")).toBeInTheDocument(); - // Should show ECDSA by default since sshKeyPair includes "ecdsa" - expect( - screen.getByText(defaultProps.sshPublicKey as string), - ).toBeInTheDocument(); - expect( - screen.getByText("I've added the deploy key and gave it write access"), - ).toBeInTheDocument(); - }); - - it("calls fetchSSHKey if modal is open and not importing", () => { - render(<AddDeployKey {...defaultProps} isImport={false} />); - expect(defaultProps.fetchSSHKey).toHaveBeenCalledTimes(1); - }); - - it("does not call fetchSSHKey if importing", () => { - render(<AddDeployKey {...defaultProps} isImport />); - expect(defaultProps.fetchSSHKey).not.toHaveBeenCalled(); - }); - - it("shows dummy key loader if loading keys", () => { - render( - <AddDeployKey {...defaultProps} isFetchSSHKeyLoading sshPublicKey="" />, - ); - // The actual key text should not be displayed - expect(screen.queryByText("ecdsa-sha2-nistp256")).not.toBeInTheDocument(); - }); - - it("changes SSH key type when user selects a different type and triggers generateSSHKey if needed", async () => { - const generateSSHKey = jest.fn(); - - render( - <AddDeployKey - {...defaultProps} - generateSSHKey={generateSSHKey} - sshPublicKey="" // No key to force generation - />, - ); - - fireEvent.mouseDown(screen.getByRole("combobox")); - const rsaOption = screen.getByText("RSA 4096"); - - fireEvent.click(rsaOption); - - await waitFor(() => { - expect(generateSSHKey).toHaveBeenCalledWith("RSA", false); - }); - }); - - it("displays a generic error when errorData is provided and error code is not AE-GIT-4032 or AE-GIT-4033", () => { - // eslint-disable-next-line react-perf/jsx-no-new-object-as-prop - const connectError = { - code: "GENERIC-ERROR", - errorType: "Some Error", - message: "Something went wrong", - }; - - render(<AddDeployKey {...defaultProps} connectError={connectError} />); - expect(screen.getByText("Some Error")).toBeInTheDocument(); - expect(screen.getByText("Something went wrong")).toBeInTheDocument(); - }); - - it("displays a misconfiguration error if error code is AE-GIT-4032", () => { - // eslint-disable-next-line react-perf/jsx-no-new-object-as-prop - const connectError = { - code: "AE-GIT-4032", - errorType: "SSH Key Error", - message: "SSH Key misconfiguration", - }; - - render(<AddDeployKey {...defaultProps} connectError={connectError} />); - expect(screen.getByText("SSH key misconfiguration")).toBeInTheDocument(); - expect( - screen.getByText( - "It seems that your SSH key hasn't been added to your repository. To proceed, please revisit the steps below and configure your SSH key correctly.", - ), - ).toBeInTheDocument(); - }); - - it("invokes onChange callback when checkbox is toggled", () => { - const onChange = jest.fn(); - - render(<AddDeployKey {...defaultProps} onChange={onChange} />); - const checkbox = screen.getByTestId("t--added-deploy-key-checkbox"); - - fireEvent.click(checkbox); - expect(onChange).toHaveBeenCalledWith({ isAddedDeployKey: true }); - }); - - it("calls AnalyticsUtil on copy button click", () => { - render(<AddDeployKey {...defaultProps} />); - const copyButton = screen.getByTestId("t--copy-generic"); - - fireEvent.click(copyButton); - expect(AnalyticsUtil.logEvent).toHaveBeenCalledWith( - "GS_COPY_SSH_KEY_BUTTON_CLICK", - ); - }); - - it("hides copy button when connectLoading is true", () => { - render(<AddDeployKey {...defaultProps} isLoading />); - expect(screen.queryByTestId("t--copy-generic")).not.toBeInTheDocument(); - }); - - it("shows repository settings link if gitProvider is known and not 'others'", () => { - render(<AddDeployKey {...defaultProps} />); - const link = screen.getByRole("link", { name: "repository settings." }); - - expect(link).toHaveAttribute( - "href", - "https://github.com/owner/repo/settings/keys", - ); - }); - - it("does not show repository link if gitProvider = 'others'", () => { - render( - <AddDeployKey - {...defaultProps} - // eslint-disable-next-line react-perf/jsx-no-new-object-as-prop - value={{ gitProvider: "others", remoteUrl: "[email protected]:repo.git" }} - />, - ); - expect( - screen.queryByRole("link", { name: "repository settings." }), - ).not.toBeInTheDocument(); - }); - - it("shows collapsible section if gitProvider is not 'others'", () => { - render( - <AddDeployKey - {...defaultProps} - // eslint-disable-next-line react-perf/jsx-no-new-object-as-prop - value={{ - gitProvider: "gitlab", - remoteUrl: "[email protected]:owner/repo.git", - }} - />, - ); - expect( - screen.getByText("How to paste SSH Key in repo and give write access?"), - ).toBeInTheDocument(); - expect(screen.getByAltText("Add deploy key in gitlab")).toBeInTheDocument(); - }); - - it("does not display collapsible if gitProvider = 'others'", () => { - render( - <AddDeployKey - {...defaultProps} - // eslint-disable-next-line react-perf/jsx-no-new-object-as-prop - value={{ gitProvider: "others", remoteUrl: "[email protected]:repo.git" }} - />, - ); - expect( - screen.queryByText("How to paste SSH Key in repo and give write access?"), - ).not.toBeInTheDocument(); - }); - - it("uses default documentation link if none provided", () => { - render(<AddDeployKey {...defaultProps} />); - const docsLink = screen.getByRole("link", { name: "Read Docs" }); - - expect(docsLink).toHaveAttribute("href", DEFAULT_DOCS_URL); - }); - - it("generates SSH key if none is present and conditions are met", async () => { - const fetchSSHKey = jest.fn(); - const generateSSHKey = jest.fn(); - - render( - <AddDeployKey - {...defaultProps} - fetchSSHKey={fetchSSHKey} - generateSSHKey={generateSSHKey} - isFetchSSHKeyLoading={false} - isGenerateSSHKeyLoading={false} - sshPublicKey="" - />, - ); - - expect(fetchSSHKey).toHaveBeenCalledTimes(1); - - await waitFor(() => { - expect(generateSSHKey).toHaveBeenCalledWith("ECDSA", false); - }); - }); -}); diff --git a/app/client/src/git/components/ConnectModal/ConnectInitialize/AddDeployKey.tsx b/app/client/src/git/components/ConnectModal/ConnectInitialize/AddDeployKey.tsx index 75a4a7a50e86..09dcb7df1122 100644 --- a/app/client/src/git/components/ConnectModal/ConnectInitialize/AddDeployKey.tsx +++ b/app/client/src/git/components/ConnectModal/ConnectInitialize/AddDeployKey.tsx @@ -135,93 +135,83 @@ const DEPLOY_DOCS_URL = "https://docs.appsmith.com/advanced-concepts/version-control-with-git/connecting-to-git-repository"; export interface AddDeployKeyProps { - connectError: GitApiError | null; - fetchSSHKey: () => void; - generateSSHKey: (keyType: string, isImport?: boolean) => void; - isFetchSSHKeyLoading: boolean; - isGenerateSSHKeyLoading: boolean; - isImport?: boolean; - isLoading: boolean; + error: GitApiError | null; + isSubmitLoading: boolean; + isSSHKeyLoading: boolean; onChange: (args: Partial<ConnectFormDataState>) => void; + onFetchSSHKey?: () => void; + onGenerateSSHKey: (keyType: string) => void; sshPublicKey: string | null; value: Partial<ConnectFormDataState> | null; } function AddDeployKey({ - connectError = null, - fetchSSHKey = noop, - generateSSHKey = noop, - isFetchSSHKeyLoading = false, - isGenerateSSHKeyLoading = false, - isImport = false, - isLoading = false, + error = null, + isSSHKeyLoading = false, + isSubmitLoading = false, onChange = noop, + onFetchSSHKey = noop, + onGenerateSSHKey = noop, sshPublicKey = null, value = null, }: AddDeployKeyProps) { const [fetched, setFetched] = useState(false); - const [sshKeyType, setSshKeyType] = useState<string>(); + const [keyType, setKeyType] = useState<string>(); useEffect( function fetchKeyPairOnInitEffect() { - if (!isImport) { - if (!fetched) { - fetchSSHKey(); - setFetched(true); - // doesn't support callback anymore - // fetchSSHKey({ - // onSuccessCallback: () => { - // setFetched(true); - // }, - // onErrorCallback: () => { - // setFetched(true); - // }, - // }); - } - } else { - if (!fetched) { - setFetched(true); - } + if (!fetched) { + onFetchSSHKey(); + setFetched(true); + // doesn't support callback anymore + // fetchSSHKey({ + // onSuccessCallback: () => { + // setFetched(true); + // }, + // onErrorCallback: () => { + // setFetched(true); + // }, + // }); } }, - [isImport, fetched, fetchSSHKey], + [fetched, onFetchSSHKey], ); useEffect( function setSSHKeyTypeonInitEffect() { - if (fetched && !isFetchSSHKeyLoading) { + if (fetched && !isSSHKeyLoading) { if (sshPublicKey && sshPublicKey.includes("rsa")) { - setSshKeyType("RSA"); + setKeyType("RSA"); } else if ( !sshPublicKey && value?.remoteUrl && value.remoteUrl.toString().toLocaleLowerCase().includes("azure") ) { - setSshKeyType("RSA"); + setKeyType("RSA"); } else { - setSshKeyType("ECDSA"); + setKeyType("ECDSA"); } } }, - [fetched, sshPublicKey, isFetchSSHKeyLoading, value?.remoteUrl], + [fetched, sshPublicKey, value?.remoteUrl, isSSHKeyLoading], ); useEffect( function generateSSHOnInitEffect() { if ( - (sshKeyType && !sshPublicKey) || - (sshKeyType && !sshPublicKey?.includes(sshKeyType.toLowerCase())) + (keyType && !sshPublicKey) || + (keyType && !sshPublicKey?.includes(keyType.toLowerCase())) ) { - generateSSHKey(sshKeyType, isImport); + onGenerateSSHKey(keyType); // doesn't support callback anymore - // generateSSHKey(sshKeyType, { + // generateSSHKey(keyType, { // onSuccessCallback: () => { // toast.show("SSH Key generated successfully", { kind: "success" }); // }, // }); } }, - [sshKeyType, sshPublicKey, generateSSHKey, isImport], + [keyType, sshPublicKey, onGenerateSSHKey], ); const repositorySettingsUrl = getRepositorySettingsUrl( @@ -229,7 +219,7 @@ function AddDeployKey({ value?.remoteUrl, ); - const loading = isFetchSSHKeyLoading || isGenerateSSHKeyLoading; + // const loading = isFetchSSHKeyLoading || isGenerateSSHKeyLoading; const onCopy = useCallback(() => { AnalyticsUtil.logEvent("GS_COPY_SSH_KEY_BUTTON_CLICK"); @@ -244,19 +234,19 @@ function AddDeployKey({ return ( <> - {connectError && - connectError.code !== "AE-GIT-4033" && - connectError.code !== "AE-GIT-4032" && ( + {error && + error.code !== "AE-GIT-4033" && + error.code !== "AE-GIT-4032" && ( <ErrorCallout kind="error"> <Text kind="heading-xs" renderAs="h3"> - {connectError.errorType} + {error.errorType} </Text> - <Text renderAs="p">{connectError.message}</Text> + <Text renderAs="p">{error.message}</Text> </ErrorCallout> )} {/* hardcoding message because server doesn't support feature flag. Will change this later */} - {connectError && connectError.code === "AE-GIT-4032" && ( + {error && error.code === "AE-GIT-4032" && ( <ErrorCallout kind="error"> <Text kind="heading-xs" renderAs="h3"> {createMessage(ERROR_SSH_KEY_MISCONF_TITLE)} @@ -301,20 +291,20 @@ function AddDeployKey({ Now, give write access to it. </WellText> <FieldContainer> - <StyledSelect onChange={setSshKeyType} size="sm" value={sshKeyType}> + <StyledSelect onChange={setKeyType} size="sm" value={keyType}> <Option value="ECDSA">ECDSA 256</Option> <Option value="RSA">RSA 4096</Option> </StyledSelect> - {!loading ? ( + {!isSSHKeyLoading ? ( <DeployedKeyContainer> <StyledIcon color="var(--ads-v2-color-fg)" name="key-2-line" size="md" /> - <KeyType>{sshKeyType}</KeyType> + <KeyType>{keyType}</KeyType> <KeyText>{sshPublicKey}</KeyText> - {!isLoading && ( + {!isSubmitLoading && ( <CopyButton onCopy={onCopy} tooltipMessage={createMessage(COPY_SSH_KEY)} diff --git a/app/client/src/git/components/ConnectModal/ConnectInitialize/ChooseGitProvider.test.tsx b/app/client/src/git/components/ConnectModal/ConnectInitialize/ChooseGitProvider.test.tsx index 62a5f43858db..8d536c71686d 100644 --- a/app/client/src/git/components/ConnectModal/ConnectInitialize/ChooseGitProvider.test.tsx +++ b/app/client/src/git/components/ConnectModal/ConnectInitialize/ChooseGitProvider.test.tsx @@ -23,8 +23,7 @@ const defaultProps = { isImport: false, canCreateNewArtifact: true, toggleConnectModal: jest.fn(), - isCreateArtifactPermitted: true, - setImportWorkspaceId: jest.fn(), + onOpenImport: jest.fn(), }; describe("ChooseGitProvider Component", () => { @@ -169,19 +168,19 @@ describe("ChooseGitProvider Component", () => { }); it("clicking on 'Import via git' link calls onImportFromCalloutLinkClick", () => { - const mockSetImportWorkspaceId = jest.fn(); + const onOpenImport = jest.fn(); render( <Router> <ChooseGitProvider {...defaultProps} - setImportWorkspaceId={mockSetImportWorkspaceId} + onOpenImport={onOpenImport} value={{ gitProvider: "github", gitEmptyRepoExists: "no" }} /> </Router>, ); fireEvent.click(screen.getByText("Import via git")); - expect(mockSetImportWorkspaceId).toHaveBeenCalledTimes(1); + expect(onOpenImport).toHaveBeenCalledTimes(1); }); it("when isImport = true, shows a checkbox for existing repo", () => { @@ -214,11 +213,11 @@ describe("ChooseGitProvider Component", () => { }); it("respects canCreateNewArtifact and device conditions for links", () => { - // If canCreateNewArtifact is false, "Import via git" should not appear even if conditions are met + // If onOpenImport is null, "Import via git" should not appear even if conditions are met render( <ChooseGitProvider {...defaultProps} - isCreateArtifactPermitted={false} + onOpenImport={null} value={{ gitProvider: "github", gitEmptyRepoExists: "no" }} />, ); diff --git a/app/client/src/git/components/ConnectModal/ConnectInitialize/ChooseGitProvider.tsx b/app/client/src/git/components/ConnectModal/ConnectInitialize/ChooseGitProvider.tsx index d24c31de20de..b8aceed5baf4 100644 --- a/app/client/src/git/components/ConnectModal/ConnectInitialize/ChooseGitProvider.tsx +++ b/app/client/src/git/components/ConnectModal/ConnectInitialize/ChooseGitProvider.tsx @@ -34,9 +34,7 @@ import { } from "ee/constants/messages"; import log from "loglevel"; import type { ConnectFormDataState } from "./types"; -import history from "utils/history"; import { useIsMobileDevice } from "utils/hooks/useDeviceDetect"; -import AnalyticsUtil from "ee/utils/AnalyticsUtil"; const WellInnerContainer = styled.div` padding-left: 16px; @@ -53,21 +51,17 @@ export type GitProvider = (typeof GIT_PROVIDERS)[number]; interface ChooseGitProviderProps { artifactType: string; - isCreateArtifactPermitted: boolean; isImport?: boolean; onChange: (args: Partial<ConnectFormDataState>) => void; - setImportWorkspaceId: () => void; - toggleConnectModal: (open: boolean) => void; + onOpenImport: (() => void) | null; value: Partial<ConnectFormDataState>; } function ChooseGitProvider({ artifactType, - isCreateArtifactPermitted, isImport = false, onChange = noop, - setImportWorkspaceId = noop, - toggleConnectModal = noop, + onOpenImport = null, value = {}, }: ChooseGitProviderProps) { const isMobile = useIsMobileDevice(); @@ -97,19 +91,19 @@ function ChooseGitProvider({ [onChange], ); - const handleClickOnImport = useCallback(() => { - toggleConnectModal(false); - history.push("/applications"); - setImportWorkspaceId(); - toggleConnectModal(true); - AnalyticsUtil.logEvent("GS_IMPORT_VIA_GIT_DURING_GC"); - }, [setImportWorkspaceId, toggleConnectModal]); + // const handleClickOnImport = useCallback(() => { + // toggleConnectModal(false); + // history.push("/applications"); + // setImportWorkspaceId(); + // toggleConnectModal(true); + // AnalyticsUtil.logEvent("GS_IMPORT_VIA_GIT_DURING_GC"); + // }, [setImportWorkspaceId, toggleConnectModal]); const importCalloutLinks = useMemo(() => { - return !isMobile && isCreateArtifactPermitted - ? [{ children: "Import via git", onClick: handleClickOnImport }] + return !isMobile && onOpenImport && typeof onOpenImport === "function" + ? [{ children: "Import via git", onClick: onOpenImport }] : []; - }, [handleClickOnImport, isCreateArtifactPermitted, isMobile]); + }, [onOpenImport, isMobile]); return ( <> @@ -208,7 +202,7 @@ function ChooseGitProvider({ )} </WellInnerContainer> </WellContainer> - {!isImport && value?.gitEmptyRepoExists === "no" ? ( + {!isImport && onOpenImport && value?.gitEmptyRepoExists === "no" ? ( <Callout kind="info" links={importCalloutLinks}> {createMessage(IMPORT_ARTIFACT_IF_NOT_EMPTY, artifactType)} </Callout> diff --git a/app/client/src/git/components/ConnectModal/ConnectInitialize/GenerateSSH.test.tsx b/app/client/src/git/components/ConnectModal/ConnectInitialize/GenerateSSH.test.tsx index d082ee44546d..fc53b8531a4f 100644 --- a/app/client/src/git/components/ConnectModal/ConnectInitialize/GenerateSSH.test.tsx +++ b/app/client/src/git/components/ConnectModal/ConnectInitialize/GenerateSSH.test.tsx @@ -16,7 +16,7 @@ const defaultProps = { gitProvider: "github" as GitProvider, remoteUrl: "", }, - connectError: null, + error: null, }; describe("GenerateSSH Component", () => { @@ -38,7 +38,7 @@ describe("GenerateSSH Component", () => { code: "AE-GIT-4033", }; - render(<GenerateSSH {...defaultProps} connectError={errorData} />); + render(<GenerateSSH {...defaultProps} error={errorData} />); expect( screen.getByText("The repo you added isn't empty"), ).toBeInTheDocument(); @@ -55,7 +55,7 @@ describe("GenerateSSH Component", () => { code: "SOME_OTHER_ERROR", }; - render(<GenerateSSH {...defaultProps} connectError={errorData} />); + render(<GenerateSSH {...defaultProps} error={errorData} />); expect( screen.queryByText("The repo you added isn't empty"), ).not.toBeInTheDocument(); diff --git a/app/client/src/git/components/ConnectModal/ConnectInitialize/GenerateSSH.tsx b/app/client/src/git/components/ConnectModal/ConnectInitialize/GenerateSSH.tsx index 5318b0bd8554..6a8b7536f903 100644 --- a/app/client/src/git/components/ConnectModal/ConnectInitialize/GenerateSSH.tsx +++ b/app/client/src/git/components/ConnectModal/ConnectInitialize/GenerateSSH.tsx @@ -41,17 +41,13 @@ interface GenerateSSHState { interface GenerateSSHProps { onChange: (args: Partial<GenerateSSHState>) => void; value: Partial<GenerateSSHState>; - connectError: GitApiError | null; + error: GitApiError | null; } const CONNECTING_TO_GIT_DOCS_URL = "https://docs.appsmith.com/advanced-concepts/version-control-with-git/connecting-to-git-repository"; -function GenerateSSH({ - connectError, - onChange = noop, - value = {}, -}: GenerateSSHProps) { +function GenerateSSH({ error, onChange = noop, value = {} }: GenerateSSHProps) { const [isTouched, setIsTouched] = useState(false); const isInvalid = isTouched && @@ -69,7 +65,7 @@ function GenerateSSH({ return ( <> {/* hardcoding messages because server doesn't support feature flag. Will change this later */} - {connectError && connectError?.code === "AE-GIT-4033" && ( + {error && error?.code === "AE-GIT-4033" && ( <ErrorCallout kind="error"> <Text kind="heading-xs" renderAs="h3"> {createMessage(ERROR_REPO_NOT_EMPTY_TITLE)} diff --git a/app/client/src/git/components/ConnectModal/ConnectInitialize/index.test.tsx b/app/client/src/git/components/ConnectModal/ConnectInitialize/index.test.tsx index 6ac8b83b0761..21f46cf03525 100644 --- a/app/client/src/git/components/ConnectModal/ConnectInitialize/index.test.tsx +++ b/app/client/src/git/components/ConnectModal/ConnectInitialize/index.test.tsx @@ -21,19 +21,15 @@ jest.mock("@appsmith/ads", () => ({ const defaultProps = { artifactType: "Application", - connect: jest.fn(), - connectError: null, - fetchSSHKey: jest.fn(), - generateSSHKey: jest.fn(), - gitImport: jest.fn(), - isConnectLoading: false, - isFetchSSHKeyLoading: false, - isGenerateSSHKeyLoading: false, - isGitImportLoading: false, + error: null, + onFetchSSHKey: jest.fn(), + onGenerateSSHKey: jest.fn(), + isSubmitLoading: false, + isSSHKeyLoading: false, isImport: false, + onSubmit: jest.fn(), + onOpenImport: null, sshPublicKey: "ssh-rsa AAAAB3...", - isCreateArtifactPermitted: true, - setImportWorkspaceId: jest.fn(), toggleConnectModal: jest.fn(), }; @@ -126,7 +122,7 @@ describe("ConnectModal Component", () => { completeAddDeployKeyStep(); await waitFor(() => { - expect(defaultProps.connect).toHaveBeenCalledWith( + expect(defaultProps.onSubmit).toHaveBeenCalledWith( expect.objectContaining({ remoteUrl: "[email protected]:user/repo.git", gitProfile: { @@ -139,14 +135,14 @@ describe("ConnectModal Component", () => { }); }); - it("calls gitImport on completing AddDeployKey step in import mode", async () => { + it("calls onSubmit on completing AddDeployKey step in import mode", async () => { render(<ConnectInitialize {...defaultProps} isImport />); completeChooseProviderStep(true); completeGenerateSSHKeyStep(); completeAddDeployKeyStep(); await waitFor(() => { - expect(defaultProps.gitImport).toHaveBeenCalledWith( + expect(defaultProps.onSubmit).toHaveBeenCalledWith( expect.objectContaining({ remoteUrl: "[email protected]:user/repo.git", gitProfile: { @@ -167,13 +163,11 @@ describe("ConnectModal Component", () => { message: "", }; - rerender( - <ConnectInitialize {...defaultProps} connectError={connectError} />, - ); + rerender(<ConnectInitialize {...defaultProps} error={connectError} />); }); const { rerender } = render( - <ConnectInitialize {...defaultProps} connect={mockConnect} />, + <ConnectInitialize {...defaultProps} onSubmit={mockConnect} />, ); completeChooseProviderStep(); @@ -216,7 +210,7 @@ describe("ConnectModal Component", () => { }); it("renders loading state and removes buttons when connecting", () => { - render(<ConnectInitialize {...defaultProps} isConnectLoading />); + render(<ConnectInitialize {...defaultProps} isSubmitLoading />); expect( screen.getByText("Please wait while we connect to Git..."), ).toBeInTheDocument(); diff --git a/app/client/src/git/components/ConnectModal/ConnectInitialize/index.tsx b/app/client/src/git/components/ConnectModal/ConnectInitialize/index.tsx index 05046d250d09..72ba9d797c1d 100644 --- a/app/client/src/git/components/ConnectModal/ConnectInitialize/index.tsx +++ b/app/client/src/git/components/ConnectModal/ConnectInitialize/index.tsx @@ -71,41 +71,31 @@ interface StyledModalFooterProps { loading?: boolean; } -interface ConnectModalViewProps { +export interface ConnectInitializeProps { artifactType: string; - connect: (params: ConnectRequestParams) => void; - connectError: GitApiError | null; - fetchSSHKey: () => void; - generateSSHKey: (keyType: string) => void; - gitImport: (params: GitImportRequestParams) => void; - isConnectLoading: boolean; - isCreateArtifactPermitted: boolean; - isFetchSSHKeyLoading: boolean; - isGenerateSSHKeyLoading: boolean; - isGitImportLoading: boolean; + error: GitApiError | null; isImport: boolean; - setImportWorkspaceId: () => void; + isSSHKeyLoading: boolean; + isSubmitLoading: boolean; + onFetchSSHKey: () => void; + onGenerateSSHKey: (keyType: string) => void; + onOpenImport: (() => void) | null; + onSubmit: (params: ConnectRequestParams | GitImportRequestParams) => void; sshPublicKey: string | null; - toggleConnectModal: (open: boolean) => void; } function ConnectInitialize({ artifactType, - connect = noop, - connectError = null, - fetchSSHKey = noop, - generateSSHKey = noop, - gitImport = noop, - isConnectLoading = false, - isCreateArtifactPermitted = false, - isFetchSSHKeyLoading = false, - isGenerateSSHKeyLoading = false, - isGitImportLoading = false, + error = null, isImport = false, - setImportWorkspaceId = noop, + isSSHKeyLoading = false, + isSubmitLoading = false, + onFetchSSHKey = noop, + onGenerateSSHKey = noop, + onOpenImport = null, + onSubmit = noop, sshPublicKey = null, - toggleConnectModal = noop, -}: ConnectModalViewProps) { +}: ConnectInitializeProps) { const nextStepText = { [GIT_CONNECT_STEPS.CHOOSE_PROVIDER]: createMessage(CONFIGURE_GIT), [GIT_CONNECT_STEPS.GENERATE_SSH_KEY]: createMessage(GENERATE_SSH_KEY_STEP), @@ -127,8 +117,8 @@ function ConnectInitialize({ GIT_CONNECT_STEPS.CHOOSE_PROVIDER, ); - const isLoading = - (!isImport && isConnectLoading) || (isImport && isGitImportLoading); + // const isSubmitLoading = + // (!isImport && isConnectLoading) || (isImport && isGitImportLoading); const currentIndex = steps.findIndex((s) => s.key === activeStep); @@ -181,43 +171,40 @@ function ConnectInitialize({ }; if (formData.remoteUrl) { - if (!isImport) { - AnalyticsUtil.logEvent( - "GS_CONNECT_BUTTON_ON_GIT_SYNC_MODAL_CLICK", - { repoUrl: formData?.remoteUrl, connectFlow: "v2" }, - ); - connect({ - remoteUrl: formData.remoteUrl, - gitProfile, - }); - } else { - gitImport({ - remoteUrl: formData.remoteUrl, - gitProfile, - }); - } + onSubmit({ + remoteUrl: formData.remoteUrl, + gitProfile, + }); + // if (!isImport) { + // AnalyticsUtil.logEvent( + // "GS_CONNECT_BUTTON_ON_GIT_SYNC_MODAL_CLICK", + // { repoUrl: formData?.remoteUrl, connectFlow: "v2" }, + // ); + // connect({ + // remoteUrl: formData.remoteUrl, + // gitProfile, + // }); + // } else { + // gitImport({ + // remoteUrl: formData.remoteUrl, + // gitProfile, + // }); + // } } break; } } } - }, [ - activeStep, - connect, - currentIndex, - formData.remoteUrl, - gitImport, - isImport, - ]); + }, [activeStep, currentIndex, formData.remoteUrl, onSubmit]); useEffect( function changeStepOnErrorEffect() { - if (connectError?.code === GitErrorCodes.REPO_NOT_EMPTY) { + if (error?.code === GitErrorCodes.REPO_NOT_EMPTY) { setActiveStep(GIT_CONNECT_STEPS.GENERATE_SSH_KEY); } }, - [connectError?.code], + [error?.code], ); return ( @@ -236,45 +223,38 @@ function ConnectInitialize({ {activeStep === GIT_CONNECT_STEPS.CHOOSE_PROVIDER && ( <ChooseGitProvider artifactType={artifactType} - isCreateArtifactPermitted={isCreateArtifactPermitted} isImport={isImport} onChange={handleChange} - setImportWorkspaceId={setImportWorkspaceId} - toggleConnectModal={toggleConnectModal} + onOpenImport={onOpenImport} value={formData} /> )} {activeStep === GIT_CONNECT_STEPS.GENERATE_SSH_KEY && ( - <GenerateSSH - connectError={connectError} - onChange={handleChange} - value={formData} - /> + <GenerateSSH error={error} onChange={handleChange} value={formData} /> )} {activeStep === GIT_CONNECT_STEPS.ADD_DEPLOY_KEY && ( <AddDeployKey - connectError={connectError} - fetchSSHKey={fetchSSHKey} - generateSSHKey={generateSSHKey} - isFetchSSHKeyLoading={isFetchSSHKeyLoading} - isGenerateSSHKeyLoading={isGenerateSSHKeyLoading} - isLoading={isLoading} + error={error} + isSSHKeyLoading={isSSHKeyLoading} + isSubmitLoading={isSubmitLoading} onChange={handleChange} + onFetchSSHKey={onFetchSSHKey} + onGenerateSSHKey={onGenerateSSHKey} sshPublicKey={sshPublicKey} value={formData} /> )} </StyledModalBody> - <StyledModalFooter loading={isLoading}> - {isLoading && ( + <StyledModalFooter loading={isSubmitLoading}> + {isSubmitLoading && ( <Statusbar - completed={!isLoading} + completed={!isSubmitLoading} message={createMessage( isImport ? GIT_IMPORT_WAITING : GIT_CONNECT_WAITING, )} /> )} - {!isLoading && ( + {!isSubmitLoading && ( <Button data-testid="t--git-connect-next-button" endIcon={ @@ -289,10 +269,10 @@ function ConnectInitialize({ )} {possibleSteps.includes(activeStep) && currentIndex > 0 && - !isLoading && ( + !isSubmitLoading && ( <Button data-testid="t--git-connect-prev-button" - isDisabled={isLoading} + isDisabled={isSubmitLoading} kind="secondary" onClick={handlePreviousStep} size="md" diff --git a/app/client/src/git/components/ConnectModal/ConnectModalView.tsx b/app/client/src/git/components/ConnectModal/ConnectModalView.tsx index 0146a5cf9237..1732a6099ff7 100644 --- a/app/client/src/git/components/ConnectModal/ConnectModalView.tsx +++ b/app/client/src/git/components/ConnectModal/ConnectModalView.tsx @@ -1,12 +1,9 @@ import { Modal, ModalContent } from "@appsmith/ads"; -import type { ConnectRequestParams } from "git/requests/connectRequest.types"; -import type { GitImportRequestParams } from "git/requests/gitImportRequest.types"; -import type { GitApiError } from "git/store/types"; import React, { useCallback } from "react"; -import ConnectInitialize from "./ConnectInitialize"; -import ConnectSuccess from "./ConnectSuccess"; +import ConnectInitialize, { + type ConnectInitializeProps, +} from "./ConnectInitialize"; import { noop } from "lodash"; -import type { GitSettingsTab } from "git/constants/enums"; import styled from "styled-components"; const StyledModalContent = styled(ModalContent)` @@ -19,82 +16,33 @@ const StyledModalContent = styled(ModalContent)` } `; -interface ConnectModalViewProps { - artifactType: string; - connect: (params: ConnectRequestParams) => void; - connectError: GitApiError | null; - fetchSSHKey: () => void; - generateSSHKey: (keyType: string) => void; - gitImport: (params: GitImportRequestParams) => void; - isConnectLoading: boolean; - isConnectModalOpen: boolean; - isFetchSSHKeyLoading: boolean; - isGenerateSSHKeyLoading: boolean; - isGitImportLoading: boolean; - isImport: boolean; - resetFetchSSHKey: () => void; - resetGenerateSSHKey: () => void; - sshPublicKey: string | null; - toggleConnectModal: (open: boolean) => void; - isGitConnected: boolean; - remoteUrl: string | null; - toggleSettingsModal: ( - open: boolean, - tab?: keyof typeof GitSettingsTab, - ) => void; - defaultBranch: string | null; - repoName: string | null; - setImportWorkspaceId: () => void; - isCreateArtifactPermitted: boolean; +interface ConnectModalViewProps extends ConnectInitializeProps { + isModalOpen: boolean; + resetSSHKey: () => void; + toggleModalOpen: (open: boolean) => void; } function ConnectModalView({ - defaultBranch = null, - isConnectModalOpen = false, - isGitConnected = false, - remoteUrl = null, - repoName = null, - resetFetchSSHKey = noop, - resetGenerateSSHKey = noop, - toggleConnectModal = noop, - toggleSettingsModal = noop, + isModalOpen = false, + resetSSHKey = noop, + toggleModalOpen = noop, ...rest }: ConnectModalViewProps) { const handleModalOpenChange = useCallback( (open: boolean) => { if (!open) { - resetFetchSSHKey(); - resetGenerateSSHKey(); + resetSSHKey(); } - toggleConnectModal(open); + toggleModalOpen(open); }, - [resetFetchSSHKey, resetGenerateSSHKey, toggleConnectModal], + [resetSSHKey, toggleModalOpen], ); return ( - <Modal onOpenChange={handleModalOpenChange} open={isConnectModalOpen}> + <Modal onOpenChange={handleModalOpenChange} open={isModalOpen}> <StyledModalContent data-testid="t--git-connect-modal"> - {isConnectModalOpen ? ( - // need fragment to arrange conditions properly - // eslint-disable-next-line react/jsx-no-useless-fragment - <> - {isGitConnected ? ( - <ConnectSuccess - defaultBranch={defaultBranch} - remoteUrl={remoteUrl} - repoName={repoName} - toggleConnectModal={toggleConnectModal} - toggleSettingsModal={toggleSettingsModal} - /> - ) : ( - <ConnectInitialize - toggleConnectModal={toggleConnectModal} - {...rest} - /> - )} - </> - ) : null} + {isModalOpen ? <ConnectInitialize {...rest} /> : null} </StyledModalContent> </Modal> ); diff --git a/app/client/src/git/components/ConnectModal/index.tsx b/app/client/src/git/components/ConnectModal/index.tsx index a8f268132d95..651626e933a7 100644 --- a/app/client/src/git/components/ConnectModal/index.tsx +++ b/app/client/src/git/components/ConnectModal/index.tsx @@ -1,67 +1,78 @@ -import React from "react"; +import React, { useCallback } from "react"; import ConnectModalView from "./ConnectModalView"; import { useGitContext } from "../GitContextProvider"; import useConnect from "git/hooks/useConnect"; -import useMetadata from "git/hooks/useMetadata"; -import useSettings from "git/hooks/useSettings"; +import { GitArtifactType } from "git/constants/enums"; +import type { ConnectRequestParams } from "git/requests/connectRequest.types"; +import AnalyticsUtil from "ee/utils/AnalyticsUtil"; +import useSSHKey from "git/hooks/useSSHKey"; +import useImport from "git/hooks/useImport"; +import history from "utils/history"; -interface ConnectModalProps { - isImport?: boolean; -} - -function ConnectModal({ isImport = false }: ConnectModalProps) { +function ConnectModal() { const { artifactDef, isCreateArtifactPermitted, setImportWorkspaceId } = useGitContext(); const { connect, connectError, - fetchSSHKey, - generateSSHKey, - gitImport, isConnectLoading, isConnectModalOpen, + toggleConnectModal, + } = useConnect(); + const { toggleImportModal } = useImport(); + const { + fetchSSHKey, + generateSSHKey, isFetchSSHKeyLoading, isGenerateSSHKeyLoading, - isGitImportLoading, resetFetchSSHKey, resetGenerateSSHKey, sshKey, - toggleConnectModal, - } = useConnect(); - const { isGitConnected, metadata } = useMetadata(); - const { toggleSettingsModal } = useSettings(); + } = useSSHKey(); - const { artifactType } = artifactDef; + const artifactType = artifactDef?.artifactType ?? GitArtifactType.Application; const sshPublicKey = sshKey?.publicKey ?? null; - const remoteUrl = metadata?.remoteUrl ?? null; - const repoName = metadata?.repoName ?? null; - const defaultBranch = metadata?.defaultBranchName ?? null; + const isSSHKeyLoading = isFetchSSHKeyLoading || isGenerateSSHKeyLoading; + + const onSubmit = useCallback( + (params: ConnectRequestParams) => { + AnalyticsUtil.logEvent("GS_CONNECT_BUTTON_ON_GIT_SYNC_MODAL_CLICK", { + repoUrl: params?.remoteUrl, + connectFlow: "v2", + }); + connect(params); + }, + [connect], + ); + + const onOpenImport = useCallback(() => { + toggleConnectModal(false); + history.push("/applications"); + setImportWorkspaceId(); + toggleImportModal(true); + AnalyticsUtil.logEvent("GS_IMPORT_VIA_GIT_DURING_GC"); + }, [setImportWorkspaceId, toggleConnectModal, toggleImportModal]); + + const resetSSHKey = useCallback(() => { + resetFetchSSHKey(); + resetGenerateSSHKey(); + }, [resetFetchSSHKey, resetGenerateSSHKey]); return ( <ConnectModalView artifactType={artifactType} - connect={connect} - connectError={connectError} - defaultBranch={defaultBranch} - fetchSSHKey={fetchSSHKey} - generateSSHKey={generateSSHKey} - gitImport={gitImport} - isConnectLoading={isConnectLoading} - isConnectModalOpen={isConnectModalOpen} - isCreateArtifactPermitted={isCreateArtifactPermitted} - isFetchSSHKeyLoading={isFetchSSHKeyLoading} - isGenerateSSHKeyLoading={isGenerateSSHKeyLoading} - isGitConnected={isGitConnected} - isGitImportLoading={isGitImportLoading} - isImport={isImport} - remoteUrl={remoteUrl} - repoName={repoName} - resetFetchSSHKey={resetFetchSSHKey} - resetGenerateSSHKey={resetGenerateSSHKey} - setImportWorkspaceId={setImportWorkspaceId} + error={connectError} + isImport={false} + isModalOpen={isConnectModalOpen} + isSSHKeyLoading={isSSHKeyLoading} + isSubmitLoading={isConnectLoading} + onFetchSSHKey={fetchSSHKey} + onGenerateSSHKey={generateSSHKey} + onOpenImport={isCreateArtifactPermitted ? onOpenImport : null} + onSubmit={onSubmit} + resetSSHKey={resetSSHKey} sshPublicKey={sshPublicKey} - toggleConnectModal={toggleConnectModal} - toggleSettingsModal={toggleSettingsModal} + toggleModalOpen={toggleConnectModal} /> ); } diff --git a/app/client/src/git/components/ConnectModal/ConnectSuccess/index.tsx b/app/client/src/git/components/ConnectSuccessModal/ConnectSuccessModalView.tsx similarity index 64% rename from app/client/src/git/components/ConnectModal/ConnectSuccess/index.tsx rename to app/client/src/git/components/ConnectSuccessModal/ConnectSuccessModalView.tsx index 47f762b6bb5b..af8390a76321 100644 --- a/app/client/src/git/components/ConnectModal/ConnectSuccess/index.tsx +++ b/app/client/src/git/components/ConnectSuccessModal/ConnectSuccessModalView.tsx @@ -17,13 +17,15 @@ import { Text, Link, Tooltip, + Modal, + ModalContent, } from "@appsmith/ads"; import React, { useCallback } from "react"; import styled from "styled-components"; import AnalyticsUtil from "ee/utils/AnalyticsUtil"; import { DOCS_BRANCH_PROTECTION_URL } from "constants/ThirdPartyConstants"; import noop from "lodash/noop"; -import type { GitSettingsTab } from "git/constants/enums"; +import { GitSettingsTab } from "git/constants/enums"; const TitleText = styled(Text)` flex: 1; @@ -51,15 +53,15 @@ function ConnectionSuccessTitle() { ); } -interface ConnectSuccessModalViewProps { +interface ConnectSuccessContentProps { repoName: string | null; defaultBranch: string | null; } -function ConnectSuccessModalView({ +function ConnectSuccessContent({ defaultBranch, repoName, -}: ConnectSuccessModalViewProps) { +}: ConnectSuccessContentProps) { return ( <> <div className="flex gap-x-4 mb-6"> @@ -112,67 +114,84 @@ function ConnectSuccessModalView({ ); } -interface ConnectSuccessProps { +const StyledModalContent = styled(ModalContent)` + &&& { + width: 640px; + transform: none !important; + top: 100px; + left: calc(50% - 320px); + max-height: calc(100vh - 200px); + } +`; + +export interface ConnectSuccessModalViewProps { defaultBranch: string | null; + isConnectSuccessModalOpen: boolean; remoteUrl: string | null; repoName: string | null; - toggleConnectModal: (open: boolean) => void; + toggleConnectSuccessModal: (open: boolean) => void; toggleSettingsModal: ( open: boolean, tab?: keyof typeof GitSettingsTab, ) => void; } -function ConnectSuccess({ - defaultBranch, +function ConnectSuccessModalView({ + defaultBranch = null, + isConnectSuccessModalOpen = false, remoteUrl = null, - repoName, - toggleConnectModal = noop, + repoName = null, + toggleConnectSuccessModal = noop, toggleSettingsModal = noop, -}: ConnectSuccessProps) { +}: ConnectSuccessModalViewProps) { const handleStartGit = useCallback(() => { - toggleConnectModal(false); + toggleConnectSuccessModal(false); AnalyticsUtil.logEvent("GS_START_USING_GIT", { repoUrl: remoteUrl, }); - }, [remoteUrl, toggleConnectModal]); + }, [remoteUrl, toggleConnectSuccessModal]); const handleOpenSettings = useCallback(() => { - toggleConnectModal(false); - toggleSettingsModal(true); + toggleConnectSuccessModal(false); + toggleSettingsModal(true, GitSettingsTab.Branch); AnalyticsUtil.logEvent("GS_OPEN_GIT_SETTINGS", { repoUrl: remoteUrl, }); - }, [remoteUrl, toggleConnectModal, toggleSettingsModal]); + }, [remoteUrl, toggleConnectSuccessModal, toggleSettingsModal]); return ( - <> - <ModalBody data-testid="t--git-success-modal-body"> - <ConnectionSuccessTitle /> - <ConnectSuccessModalView - defaultBranch={defaultBranch} - repoName={repoName} - /> - </ModalBody> - <ModalFooter> - <Button - data-testid="t--git-success-modal-open-settings-cta" - kind="secondary" - onClick={handleOpenSettings} - size="md" - > - {createMessage(GIT_CONNECT_SUCCESS_ACTION_SETTINGS)} - </Button> - <Button - data-testid="t--git-success-modal-start-using-git-cta" - onClick={handleStartGit} - size="md" - > - {createMessage(GIT_CONNECT_SUCCESS_ACTION_CONTINUE)} - </Button> - </ModalFooter> - </> + <Modal + onOpenChange={toggleConnectSuccessModal} + open={isConnectSuccessModalOpen} + > + <StyledModalContent data-testid="t--git-connect-modal"> + <ModalBody data-testid="t--git-success-modal-body"> + <ConnectionSuccessTitle /> + <ConnectSuccessContent + defaultBranch={defaultBranch} + repoName={repoName} + /> + </ModalBody> + <ModalFooter> + <Button + data-testid="t--git-success-modal-open-settings-cta" + kind="secondary" + onClick={handleOpenSettings} + size="md" + > + {createMessage(GIT_CONNECT_SUCCESS_ACTION_SETTINGS)} + </Button> + <Button + data-testid="t--git-success-modal-start-using-git-cta" + onClick={handleStartGit} + size="md" + > + {createMessage(GIT_CONNECT_SUCCESS_ACTION_CONTINUE)} + </Button> + </ModalFooter> + </StyledModalContent> + </Modal> ); } -export default ConnectSuccess; +export default ConnectSuccessModalView; diff --git a/app/client/src/git/components/ConnectSuccessModal/index.tsx b/app/client/src/git/components/ConnectSuccessModal/index.tsx new file mode 100644 index 000000000000..c492e5aa4bb3 --- /dev/null +++ b/app/client/src/git/components/ConnectSuccessModal/index.tsx @@ -0,0 +1,29 @@ +import React from "react"; +import ConnectSuccessModalView from "./ConnectSuccessModalView"; +import useMetadata from "git/hooks/useMetadata"; +import useConnect from "git/hooks/useConnect"; +import useSettings from "git/hooks/useSettings"; + +function ConnectSuccessModal() { + const { isConnectSuccessModalOpen, toggleConnectSuccessModal } = useConnect(); + const { toggleSettingsModal } = useSettings(); + + const { metadata } = useMetadata(); + + const remoteUrl = metadata?.remoteUrl ?? null; + const repoName = metadata?.repoName ?? null; + const defaultBranch = metadata?.defaultBranchName ?? null; + + return ( + <ConnectSuccessModalView + defaultBranch={defaultBranch} + isConnectSuccessModalOpen={isConnectSuccessModalOpen} + remoteUrl={remoteUrl} + repoName={repoName} + toggleConnectSuccessModal={toggleConnectSuccessModal} + toggleSettingsModal={toggleSettingsModal} + /> + ); +} + +export default ConnectSuccessModal; diff --git a/app/client/src/git/components/DeployMenuItems/DeployMenuItemsView.tsx b/app/client/src/git/components/DeployMenuItems/DeployMenuItemsView.tsx new file mode 100644 index 000000000000..09ce5be3178a --- /dev/null +++ b/app/client/src/git/components/DeployMenuItems/DeployMenuItemsView.tsx @@ -0,0 +1,32 @@ +import React, { useCallback } from "react"; +import { MenuItem } from "@appsmith/ads"; +import { CONNECT_TO_GIT_OPTION, createMessage } from "ee/constants/messages"; +import AnalyticsUtil from "ee/utils/AnalyticsUtil"; +import noop from "lodash/noop"; + +interface DeployMenuItemsViewProps { + toggleConnectModal: (open: boolean) => void; +} + +function DeployMenuItemsView({ + toggleConnectModal = noop, +}: DeployMenuItemsViewProps) { + const handleClickOnConnect = useCallback(() => { + AnalyticsUtil.logEvent("GS_CONNECT_GIT_CLICK", { + source: "Deploy button", + }); + toggleConnectModal(true); + }, [toggleConnectModal]); + + return ( + <MenuItem + className="t--connect-to-git-btn" + onClick={handleClickOnConnect} + startIcon="git-branch" + > + {createMessage(CONNECT_TO_GIT_OPTION)} + </MenuItem> + ); +} + +export default DeployMenuItemsView; diff --git a/app/client/src/git/components/DeployMenuItems/index.tsx b/app/client/src/git/components/DeployMenuItems/index.tsx new file mode 100644 index 000000000000..de6c61f9af9b --- /dev/null +++ b/app/client/src/git/components/DeployMenuItems/index.tsx @@ -0,0 +1,11 @@ +import useConnect from "git/hooks/useConnect"; +import React from "react"; +import DeployMenuItemsView from "./DeployMenuItemsView"; + +function DeployMenuItems() { + const { toggleConnectModal } = useConnect(); + + return <DeployMenuItemsView toggleConnectModal={toggleConnectModal} />; +} + +export default DeployMenuItems; diff --git a/app/client/src/git/components/GitContextProvider/index.tsx b/app/client/src/git/components/GitContextProvider/index.tsx index 4d4b88b4f6ad..89736de113eb 100644 --- a/app/client/src/git/components/GitContextProvider/index.tsx +++ b/app/client/src/git/components/GitContextProvider/index.tsx @@ -2,14 +2,12 @@ import React, { createContext, useCallback, useContext, useMemo } from "react"; import type { GitArtifactType } from "git/constants/enums"; import type { ApplicationPayload } from "entities/Application"; import type { FetchStatusResponseData } from "git/requests/fetchStatusRequest.types"; -import type { StatusTreeStruct } from "../StatusChanges/StatusTree"; import { useDispatch } from "react-redux"; +import type { GitArtifactDef } from "git/store/types"; +import type { StatusTreeStruct } from "../StatusChanges/types"; export interface GitContextValue { - artifactDef: { - artifactType: keyof typeof GitArtifactType; - baseArtifactId: string; - }; + artifactDef: GitArtifactDef | null; artifact: ApplicationPayload | null; statusTransformer: ( status: FetchStatusResponseData, @@ -27,8 +25,8 @@ export const useGitContext = () => { }; interface GitContextProviderProps { - artifactType: keyof typeof GitArtifactType; - baseArtifactId: string; + artifactType: keyof typeof GitArtifactType | null; + baseArtifactId: string | null; artifact: ApplicationPayload | null; isCreateArtifactPermitted: boolean; setWorkspaceIdForImport: (params: { @@ -50,10 +48,13 @@ export default function GitContextProvider({ setWorkspaceIdForImport, statusTransformer, }: GitContextProviderProps) { - const artifactDef = useMemo( - () => ({ artifactType, baseArtifactId }), - [artifactType, baseArtifactId], - ); + const artifactDef = useMemo(() => { + if (artifactType && baseArtifactId) { + return { artifactType, baseArtifactId }; + } + + return null; + }, [artifactType, baseArtifactId]); const dispatch = useDispatch(); diff --git a/app/client/src/git/components/GlobalProfile/GlobalProfileView.tsx b/app/client/src/git/components/GlobalProfile/GlobalProfileView.tsx new file mode 100644 index 000000000000..ddb2d7935387 --- /dev/null +++ b/app/client/src/git/components/GlobalProfile/GlobalProfileView.tsx @@ -0,0 +1,148 @@ +import React, { useCallback, useEffect, useState } from "react"; +import { + createMessage, + AUTHOR_EMAIL, + AUTHOR_NAME, + SUBMIT, +} from "ee/constants/messages"; +import { Classes } from "@blueprintjs/core"; +import { Button, Input, toast } from "@appsmith/ads"; +import { emailValidator } from "@appsmith/ads-old"; +import styled from "styled-components"; +import type { FetchGlobalProfileResponseData } from "git/requests/fetchGlobalProfileRequest.types"; +import type { UpdateGlobalProfileInitPayload } from "git/store/actions/updateGlobalProfileActions"; +import noop from "lodash/noop"; + +const Wrapper = styled.div` + width: 320px; + & > div { + margin-bottom: 16px; + } +`; + +const FieldWrapper = styled.div` + .user-profile-image-picker { + width: 166px; + margin-top: 4px; + } +`; + +const Loader = styled.div` + height: 38px; + width: 320px; + border-radius: 0; +`; + +interface GlobalProfileViewProps { + globalProfile: FetchGlobalProfileResponseData | null; + isFetchGlobalProfileLoading: boolean; + isUpdateGlobalProfileLoading: boolean; + updateGlobalProfile: (data: UpdateGlobalProfileInitPayload) => void; +} + +export default function GlobalProfileView({ + globalProfile = null, + isFetchGlobalProfileLoading = false, + isUpdateGlobalProfileLoading = false, + updateGlobalProfile = noop, +}: GlobalProfileViewProps) { + const [areFormValuesUpdated, setAreFormValuesUpdated] = useState(false); + + const [authorName, setAuthorNameInState] = useState( + globalProfile?.authorName, + ); + const [authorEmail, setAuthorEmailInState] = useState( + globalProfile?.authorEmail, + ); + + const isSubmitDisabled = !authorName || !authorEmail || !areFormValuesUpdated; + + const isLoading = isFetchGlobalProfileLoading || isUpdateGlobalProfileLoading; + + const setAuthorName = useCallback( + (value: string) => { + setAuthorNameInState(value); + + if (authorName) setAreFormValuesUpdated(true); + }, + [authorName], + ); + + const setAuthorEmail = useCallback( + (value: string) => { + setAuthorEmailInState(value); + + if (authorEmail) setAreFormValuesUpdated(true); + }, + [authorEmail], + ); + + const onClickUpdate = useCallback(() => { + if (authorName && authorEmail && emailValidator(authorEmail).isValid) { + setAreFormValuesUpdated(false); + updateGlobalProfile({ authorName, authorEmail }); + } else { + toast.show("Please enter valid user details"); + } + }, [authorEmail, authorName, updateGlobalProfile]); + + useEffect( + function resetOnInitEffect() { + setAreFormValuesUpdated(false); + setAuthorNameInState(globalProfile?.authorName ?? ""); + setAuthorEmailInState(globalProfile?.authorEmail ?? ""); + }, + [globalProfile], + ); + + return ( + <Wrapper> + <FieldWrapper> + {isLoading && <Loader className={Classes.SKELETON} />} + {!isLoading && ( + <Input + data-testid="t--git-author-name" + isRequired + label={createMessage(AUTHOR_NAME)} + labelPosition="top" + onChange={setAuthorName} + placeholder={createMessage(AUTHOR_NAME)} + renderAs="input" + size="md" + type="text" + value={authorName} + /> + )} + </FieldWrapper> + <FieldWrapper> + {isLoading && <Loader className={Classes.SKELETON} />} + {!isLoading && ( + <Input + data-testid="t--git-author-email" + isRequired + label={createMessage(AUTHOR_EMAIL)} + labelPosition="top" + onChange={setAuthorEmail} + placeholder={createMessage(AUTHOR_EMAIL)} + renderAs="input" + size="md" + type="text" + value={authorEmail} + /> + )} + </FieldWrapper> + <FieldWrapper> + <div style={{ flex: 1, display: "flex", justifyContent: "flex-end" }}> + <Button + isDisabled={isSubmitDisabled} + isLoading={isLoading} + onClick={onClickUpdate} + size="md" + > + {createMessage(SUBMIT)} + </Button> + </div> + </FieldWrapper> + </Wrapper> + ); +} diff --git a/app/client/src/git/components/GlobalProfile/index.tsx b/app/client/src/git/components/GlobalProfile/index.tsx new file mode 100644 index 000000000000..5ecc06e70c87 --- /dev/null +++ b/app/client/src/git/components/GlobalProfile/index.tsx @@ -0,0 +1,23 @@ +import useGlobalProfile from "git/hooks/useGlobalProfile"; +import React from "react"; +import GlobalProfileView from "./GlobalProfileView"; + +function GlobalProfile() { + const { + globalProfile, + isFetchGlobalProfileLoading, + isUpdateGlobalProfileLoading, + updateGlobalProfile, + } = useGlobalProfile(); + + return ( + <GlobalProfileView + globalProfile={globalProfile} + isFetchGlobalProfileLoading={isFetchGlobalProfileLoading} + isUpdateGlobalProfileLoading={isUpdateGlobalProfileLoading} + updateGlobalProfile={updateGlobalProfile} + /> + ); +} + +export default GlobalProfile; diff --git a/app/client/src/git/components/ImportModal/index.tsx b/app/client/src/git/components/ImportModal/index.tsx index f55a468d702b..8192fa9e88a7 100644 --- a/app/client/src/git/components/ImportModal/index.tsx +++ b/app/client/src/git/components/ImportModal/index.tsx @@ -1,8 +1,51 @@ -import React from "react"; -import ConnectModal from "../ConnectModal"; +import React, { useCallback } from "react"; +import ConnectModalView from "../ConnectModal/ConnectModalView"; +import type { GitImportRequestParams } from "git/requests/gitImportRequest.types"; +import useImport from "git/hooks/useImport"; +import useGlobalSSHKey from "git/hooks/useGlobalSSHKey"; +import noop from "lodash/noop"; function ImportModal() { - return <ConnectModal isImport />; + const { + gitImport, + gitImportError, + isGitImportLoading, + isImportModalOpen, + toggleImportModal, + } = useImport(); + const { + fetchGlobalSSHKey, + globalSSHKey, + isFetchGlobalSSHKeyLoading, + resetGlobalSSHKey, + } = useGlobalSSHKey(); + + const sshPublicKey = globalSSHKey?.publicKey ?? null; + + const onSubmit = useCallback( + (params: GitImportRequestParams) => { + gitImport(params); + }, + [gitImport], + ); + + return ( + <ConnectModalView + artifactType="artifact" + error={gitImportError} + isImport + isModalOpen={isImportModalOpen} + isSSHKeyLoading={isFetchGlobalSSHKeyLoading} + isSubmitLoading={isGitImportLoading} + onFetchSSHKey={noop} + onGenerateSSHKey={fetchGlobalSSHKey} + onOpenImport={null} + onSubmit={onSubmit} + resetSSHKey={resetGlobalSSHKey} + sshPublicKey={sshPublicKey} + toggleModalOpen={toggleImportModal} + /> + ); } export default ImportModal; diff --git a/app/client/src/git/components/OpsModal/TabDeploy/DeployPreview.tsx b/app/client/src/git/components/OpsModal/TabDeploy/DeployPreview.tsx index 79abbe1439dc..311019abdc24 100644 --- a/app/client/src/git/components/OpsModal/TabDeploy/DeployPreview.tsx +++ b/app/client/src/git/components/OpsModal/TabDeploy/DeployPreview.tsx @@ -1,4 +1,4 @@ -import React from "react"; +import React, { useCallback, useEffect, useState } from "react"; import styled from "styled-components"; import { useSelector } from "react-redux"; @@ -15,32 +15,47 @@ import SuccessTick from "pages/common/SuccessTick"; import { howMuchTimeBeforeText } from "utils/helpers"; import AnalyticsUtil from "ee/utils/AnalyticsUtil"; import { viewerURL } from "ee/RouteBuilder"; -import { Link, Text } from "@appsmith/ads"; -import { importSvg } from "@appsmith/ads-old"; +import { Icon, Link, Text } from "@appsmith/ads"; -const CloudyIcon = importSvg( - async () => import("assets/icons/ads/cloudy-line.svg"), -); +const StyledIcon = styled(Icon)` + svg { + width: 30px; + height: 30px; + } +`; const Container = styled.div` display: flex; flex: 1; flex-direction: row; gap: ${(props) => props.theme.spaces[6]}px; - - .cloud-icon { - stroke: var(--ads-v2-color-fg); - } `; -export default function DeployPreview() { - // ! case: should reset after timer - const showSuccess = false; +interface DeployPreviewProps { + isCommitSuccess: boolean; +} + +export default function DeployPreview({ isCommitSuccess }: DeployPreviewProps) { + const [showSuccess, setShowSuccess] = useState(false); + + useEffect( + function startTimerForCommitSuccessEffect() { + if (isCommitSuccess) { + setShowSuccess(true); + const timer = setTimeout(() => { + setShowSuccess(false); + }, 5000); + + return () => clearTimeout(timer); + } + }, + [isCommitSuccess], + ); const basePageId = useSelector(getCurrentBasePageId); const lastDeployedAt = useSelector(getApplicationLastDeployedAt); - const showDeployPreview = () => { + const showDeployPreview = useCallback(() => { AnalyticsUtil.logEvent("GS_LAST_DEPLOYED_PREVIEW_LINK_CLICK", { source: "GIT_DEPLOY_MODAL", }); @@ -49,7 +64,7 @@ export default function DeployPreview() { }); window.open(path, "_blank"); - }; + }, [basePageId]); const lastDeployedAtMsg = lastDeployedAt ? `${createMessage(LATEST_DP_SUBTITLE)} ${howMuchTimeBeforeText( @@ -66,7 +81,7 @@ export default function DeployPreview() { {showSuccess ? ( <SuccessTick height="30px" width="30px" /> ) : ( - <CloudyIcon className="cloud-icon" /> + <StyledIcon color="var(--ads-v2-color-fg)" name="cloud-v2" /> )} </div> <div> diff --git a/app/client/src/git/components/OpsModal/TabDeploy/TabDeployView.tsx b/app/client/src/git/components/OpsModal/TabDeploy/TabDeployView.tsx index d22c93f79b97..a2db0f28805d 100644 --- a/app/client/src/git/components/OpsModal/TabDeploy/TabDeployView.tsx +++ b/app/client/src/git/components/OpsModal/TabDeploy/TabDeployView.tsx @@ -108,6 +108,7 @@ function TabDeployView({ statusBehindCount = 0, statusIsClean = false, }: TabDeployViewProps) { + const [hasSubmitted, setHasSubmitted] = useState(false); const hasChangesToCommit = !statusIsClean; const commitInputRef = useRef<HTMLInputElement>(null); const [commitMessage, setCommitMessage] = useState( @@ -157,6 +158,10 @@ function TabDeployView({ ((pullRequired && !isConflicting) || (statusBehindCount > 0 && statusIsClean)); + const isCommitSuccess = useMemo(() => { + return hasSubmitted && !isCommitLoading; + }, [isCommitLoading, hasSubmitted]); + useEffect( function focusCommitInputEffect() { if (!commitInputDisabled && commitInputRef.current) { @@ -200,6 +205,7 @@ function TabDeployView({ }); if (currentBranch) { + setHasSubmitted(true); commit(commitMessage.trim()); } }, [commit, commitMessage, currentBranch]); @@ -353,7 +359,9 @@ function TabDeployView({ /> )} - {!pullRequired && !isConflicting && <DeployPreview />} + {!pullRequired && !isConflicting && ( + <DeployPreview isCommitSuccess={isCommitSuccess} /> + )} </div> </ModalBody> <StyledModalFooter key="footer"> diff --git a/app/client/src/git/components/OpsModal/index.tsx b/app/client/src/git/components/OpsModal/index.tsx index 114439c29902..66ea3ddf0182 100644 --- a/app/client/src/git/components/OpsModal/index.tsx +++ b/app/client/src/git/components/OpsModal/index.tsx @@ -1,14 +1,15 @@ import React from "react"; import OpsModalView from "./OpsModalView"; -import useProtectedBranches from "git/hooks/useProtectedBranches"; import useMetadata from "git/hooks/useMetadata"; import useStatus from "git/hooks/useStatus"; import useOps from "git/hooks/useOps"; +import useProtectedMode from "git/hooks/useProtectedMode"; +import { GitOpsTab } from "git/constants/enums"; export default function OpsModal() { - const { opsModalOpen, opsModalTab, toggleOpsModal } = useOps(); + const { isOpsModalOpen, opsModalTab, toggleOpsModal } = useOps(); const { fetchStatus } = useStatus(); - const { isProtectedMode } = useProtectedBranches(); + const isProtectedMode = useProtectedMode(); const { metadata } = useMetadata(); @@ -17,9 +18,9 @@ export default function OpsModal() { return ( <OpsModalView fetchStatus={fetchStatus} - isOpsModalOpen={opsModalOpen} + isOpsModalOpen={isOpsModalOpen} isProtectedMode={isProtectedMode} - opsModalTab={opsModalTab} + opsModalTab={opsModalTab ?? GitOpsTab.Deploy} repoName={repoName} toggleOpsModal={toggleOpsModal} /> diff --git a/app/client/src/git/components/ProtectedBranchCallout/ProtectedBranchCalloutView.tsx b/app/client/src/git/components/ProtectedBranchCallout/ProtectedBranchCalloutView.tsx new file mode 100644 index 000000000000..89b37bbfa239 --- /dev/null +++ b/app/client/src/git/components/ProtectedBranchCallout/ProtectedBranchCalloutView.tsx @@ -0,0 +1,85 @@ +import React, { useCallback, useMemo } from "react"; +import { Callout } from "@appsmith/ads"; +import styled from "styled-components"; +import { + BRANCH_PROTECTION_CALLOUT_CREATE_BRANCH, + BRANCH_PROTECTION_CALLOUT_MSG, + BRANCH_PROTECTION_CALLOUT_UNPROTECT, + BRANCH_PROTECTION_CALLOUT_UNPROTECT_LOADING, + createMessage, +} from "ee/constants/messages"; +import { noop } from "lodash"; +import type { FetchProtectedBranchesResponseData } from "git/requests/fetchProtectedBranchesRequest.types"; + +export const PROTECTED_CALLOUT_HEIGHT = 70; + +const StyledCallout = styled(Callout)` + height: ${PROTECTED_CALLOUT_HEIGHT}px; + overflow-y: hidden; +`; + +interface ProtectedBranchCalloutViewProps { + currentBranch: string | null; + isUpdateProtectedBranchesLoading: boolean; + protectedBranches: FetchProtectedBranchesResponseData | null; + toggleBranchPopup: (isOpen: boolean) => void; + updateProtectedBranches: (branches: string[]) => void; +} + +function ProtectedBranchCalloutView({ + currentBranch = null, + isUpdateProtectedBranchesLoading = false, + protectedBranches = null, + toggleBranchPopup = noop, + updateProtectedBranches = noop, +}: ProtectedBranchCalloutViewProps) { + const handleClickOnNewBranch = useCallback(() => { + toggleBranchPopup(true); + }, [toggleBranchPopup]); + + const handleClickOnUnprotect = useCallback(() => { + const allBranches = protectedBranches || []; + const remainingBranches = allBranches.filter( + (protectedBranch) => protectedBranch !== currentBranch, + ); + + updateProtectedBranches(remainingBranches); + }, [currentBranch, protectedBranches, updateProtectedBranches]); + + const links = useMemo( + () => [ + { + key: "create-branch", + "data-testid": "t--git-protected-create-branch-cta", + children: createMessage(BRANCH_PROTECTION_CALLOUT_CREATE_BRANCH), + onClick: handleClickOnNewBranch, + }, + { + key: "unprotect", + "data-testid": "t--git-protected-unprotect-branch-cta", + children: isUpdateProtectedBranchesLoading + ? createMessage(BRANCH_PROTECTION_CALLOUT_UNPROTECT_LOADING) + : createMessage(BRANCH_PROTECTION_CALLOUT_UNPROTECT), + onClick: handleClickOnUnprotect, + isDisabled: isUpdateProtectedBranchesLoading, + }, + ], + [ + handleClickOnNewBranch, + handleClickOnUnprotect, + isUpdateProtectedBranchesLoading, + ], + ); + + return ( + <StyledCallout + data-testid="t--git-protected-branch-callout" + kind="info" + links={links} + > + {createMessage(BRANCH_PROTECTION_CALLOUT_MSG)} + </StyledCallout> + ); +} + +export default ProtectedBranchCalloutView; diff --git a/app/client/src/git/components/ProtectedBranchCallout/index.tsx b/app/client/src/git/components/ProtectedBranchCallout/index.tsx new file mode 100644 index 000000000000..aca08dfc1e87 --- /dev/null +++ b/app/client/src/git/components/ProtectedBranchCallout/index.tsx @@ -0,0 +1,33 @@ +import React from "react"; +import ProtectedBranchCalloutView from "./ProtectedBranchCalloutView"; +import useProtectedBranches from "git/hooks/useProtectedBranches"; +import useCurrentBranch from "git/hooks/useCurrentBranch"; +import useBranches from "git/hooks/useBranches"; +import useProtectedMode from "git/hooks/useProtectedMode"; + +function ProtectedBranchCallout() { + const isProtectedMode = useProtectedMode(); + const currentBranch = useCurrentBranch(); + const { toggleBranchPopup } = useBranches(); + const { + isUpdateProtectedBranchesLoading, + protectedBranches, + updateProtectedBranches, + } = useProtectedBranches(); + + if (!isProtectedMode) { + return null; + } + + return ( + <ProtectedBranchCalloutView + currentBranch={currentBranch} + isUpdateProtectedBranchesLoading={isUpdateProtectedBranchesLoading} + protectedBranches={protectedBranches} + toggleBranchPopup={toggleBranchPopup} + updateProtectedBranches={updateProtectedBranches} + /> + ); +} + +export default ProtectedBranchCallout; diff --git a/app/client/src/git/components/QuickActions/QuickActionsView.test.tsx b/app/client/src/git/components/QuickActions/QuickActionsView.test.tsx index 6e696ddffe55..f6bc193bfc7e 100644 --- a/app/client/src/git/components/QuickActions/QuickActionsView.test.tsx +++ b/app/client/src/git/components/QuickActions/QuickActionsView.test.tsx @@ -29,7 +29,7 @@ describe("QuickActionsView Component", () => { isConnectPermitted: true, isDiscardLoading: false, isFetchStatusLoading: false, - isGitConnected: false, + isConnected: false, isProtectedMode: false, isPullFailing: false, isPullLoading: false, @@ -48,7 +48,7 @@ describe("QuickActionsView Component", () => { jest.clearAllMocks(); }); - it("should render ConnectButton when isGitConnected is false", () => { + it("should render ConnectButton when isConnected is false", () => { render( <ThemeProvider theme={theme}> <QuickActionsView {...defaultProps} /> @@ -57,10 +57,10 @@ describe("QuickActionsView Component", () => { expect(screen.getByTestId("connect-button")).toBeInTheDocument(); }); - it("should render QuickActionButtons when isGitConnected is true", () => { + it("should render QuickActionButtons when isConnected is true", () => { const props = { ...defaultProps, - isGitConnected: true, + isConnected: true, }; const { container } = render( @@ -86,7 +86,7 @@ describe("QuickActionsView Component", () => { it("should render Statusbar when isAutocommitEnabled and isPollingAutocommit are true", () => { const props = { ...defaultProps, - isGitConnected: true, + isConnected: true, isAutocommitEnabled: true, isAutocommitPolling: true, }; @@ -106,7 +106,7 @@ describe("QuickActionsView Component", () => { it("should call onCommitClick when commit button is clicked", () => { const props = { ...defaultProps, - isGitConnected: true, + isConnected: true, }; const { container } = render( @@ -131,7 +131,7 @@ describe("QuickActionsView Component", () => { it("should call onPullClick when pull button is clicked", () => { const props = { ...defaultProps, - isGitConnected: true, + isConnected: true, isDiscardLoading: false, isPullLoading: false, isFetchStatusLoading: false, @@ -159,7 +159,7 @@ describe("QuickActionsView Component", () => { it("should call onMerge when merge button is clicked", () => { const props = { ...defaultProps, - isGitConnected: true, + isConnected: true, }; const { container } = render( @@ -184,7 +184,7 @@ describe("QuickActionsView Component", () => { it("should call onSettingsClick when settings button is clicked", () => { const props = { ...defaultProps, - isGitConnected: true, + isConnected: true, }; const { container } = render( @@ -209,7 +209,7 @@ describe("QuickActionsView Component", () => { it("should disable commit button when isProtectedMode is true", () => { const props = { ...defaultProps, - isGitConnected: true, + isConnected: true, isProtectedMode: true, }; @@ -228,7 +228,7 @@ describe("QuickActionsView Component", () => { it("should show loading state on pull button when showPullLoadingState is true", () => { const props = { ...defaultProps, - isGitConnected: true, + isConnected: true, isPullLoading: true, }; @@ -250,7 +250,7 @@ describe("QuickActionsView Component", () => { it("should display changesToCommit count on commit button", () => { const props = { ...defaultProps, - isGitConnected: true, + isConnected: true, statusChangeCount: 5, }; @@ -267,7 +267,7 @@ describe("QuickActionsView Component", () => { it("should not display count on commit button when isProtectedMode is true", () => { const props = { ...defaultProps, - isGitConnected: true, + isConnected: true, isProtectedMode: true, statusChangeCount: 5, }; @@ -292,7 +292,7 @@ describe("QuickActionsView Component", () => { const props = { ...defaultProps, - isGitConnected: true, + isConnected: true, }; const { container } = render( @@ -310,7 +310,7 @@ describe("QuickActionsView Component", () => { it("should show behindCount on pull button", () => { const props = { ...defaultProps, - isGitConnected: true, + isConnected: true, statusBehindCount: 3, statusIsClean: true, }; diff --git a/app/client/src/git/components/QuickActions/QuickActionsView.tsx b/app/client/src/git/components/QuickActions/QuickActionsView.tsx index 396984788015..274dd00f3dba 100644 --- a/app/client/src/git/components/QuickActions/QuickActionsView.tsx +++ b/app/client/src/git/components/QuickActions/QuickActionsView.tsx @@ -33,7 +33,7 @@ interface QuickActionsViewProps { isConnectPermitted: boolean; isDiscardLoading: boolean; isFetchStatusLoading: boolean; - isGitConnected: boolean; + isConnected: boolean; isProtectedMode: boolean; isPullFailing: boolean; isPullLoading: boolean; @@ -57,10 +57,10 @@ function QuickActionsView({ isAutocommitEnabled = false, isAutocommitPolling = false, isBranchPopupOpen = false, + isConnected = false, isConnectPermitted = false, isDiscardLoading = false, isFetchStatusLoading = false, - isGitConnected = false, isProtectedMode = false, isPullFailing = false, isPullLoading = false, @@ -131,7 +131,7 @@ function QuickActionsView({ toggleConnectModal(true); }, [toggleConnectModal]); - return isGitConnected ? ( + return isConnected ? ( <Container> <BranchButton currentBranch={currentBranch} diff --git a/app/client/src/git/components/QuickActions/index.tsx b/app/client/src/git/components/QuickActions/index.tsx index 2b03ee8bdd1d..af155116075e 100644 --- a/app/client/src/git/components/QuickActions/index.tsx +++ b/app/client/src/git/components/QuickActions/index.tsx @@ -1,25 +1,25 @@ import React from "react"; import QuickActionsView from "./QuickActionsView"; import useStatusChangeCount from "./hooks/useStatusChangeCount"; -import useProtectedBranches from "git/hooks/useProtectedBranches"; import useGitPermissions from "git/hooks/useGitPermissions"; import useAutocommit from "git/hooks/useAutocommit"; import useSettings from "git/hooks/useSettings"; -import useMetadata from "git/hooks/useMetadata"; import useConnect from "git/hooks/useConnect"; import useDiscard from "git/hooks/useDiscard"; import usePull from "git/hooks/usePull"; import useStatus from "git/hooks/useStatus"; import useOps from "git/hooks/useOps"; import useBranches from "git/hooks/useBranches"; +import useConnected from "git/hooks/useConnected"; +import useProtectedMode from "git/hooks/useProtectedMode"; function QuickActions() { + const isConnected = useConnected(); const { toggleOpsModal } = useOps(); const { isFetchStatusLoading, status } = useStatus(); const { isPullLoading, pull, pullError } = usePull(); const { discard, isDiscardLoading } = useDiscard(); - const { isGitConnected } = useMetadata(); - const { isProtectedMode } = useProtectedBranches(); + const isProtectedMode = useProtectedMode(); const { isConnectPermitted } = useGitPermissions(); const { isAutocommitEnabled, @@ -43,9 +43,9 @@ function QuickActions() { isAutocommitPolling={isAutocommitPolling} isBranchPopupOpen={isBranchPopupOpen} isConnectPermitted={isConnectPermitted} + isConnected={isConnected} isDiscardLoading={isDiscardLoading} isFetchStatusLoading={isFetchStatusLoading} - isGitConnected={isGitConnected} isProtectedMode={isProtectedMode} isPullFailing={isPullFailing} isPullLoading={isPullLoading} diff --git a/app/client/src/git/components/SettingsModal/index.tsx b/app/client/src/git/components/SettingsModal/index.tsx index 47ca695ab500..968c8030312e 100644 --- a/app/client/src/git/components/SettingsModal/index.tsx +++ b/app/client/src/git/components/SettingsModal/index.tsx @@ -2,6 +2,7 @@ import React from "react"; import SettingsModalView from "./SettingsModalView"; import useGitPermissions from "git/hooks/useGitPermissions"; import useSettings from "git/hooks/useSettings"; +import { GitSettingsTab } from "git/constants/enums"; function SettingsModal() { const { isSettingsModalOpen, settingsModalTab, toggleSettingsModal } = @@ -21,7 +22,7 @@ function SettingsModal() { isManageDefaultBranchPermitted={isManageDefaultBranchPermitted} isManageProtectedBranchesPermitted={isManageProtectedBranchesPermitted} isSettingsModalOpen={isSettingsModalOpen} - settingsModalTab={settingsModalTab} + settingsModalTab={settingsModalTab ?? GitSettingsTab.General} toggleSettingsModal={toggleSettingsModal} /> ); diff --git a/app/client/src/git/components/StatusChanges/StatusChangesView.tsx b/app/client/src/git/components/StatusChanges/StatusChangesView.tsx index c3768c0d866c..f8e6f0c41dfa 100644 --- a/app/client/src/git/components/StatusChanges/StatusChangesView.tsx +++ b/app/client/src/git/components/StatusChanges/StatusChangesView.tsx @@ -1,14 +1,19 @@ import type { FetchStatusResponseData } from "git/requests/fetchStatusRequest.types"; import React, { useMemo } from "react"; -import type { StatusTreeStruct } from "./StatusTree"; import StatusTree from "./StatusTree"; -import { Text } from "@appsmith/ads"; +import { Callout, Text } from "@appsmith/ads"; import { createMessage } from "@appsmith/ads-old"; import { CHANGES_SINCE_LAST_DEPLOYMENT, FETCH_GIT_STATUS, } from "ee/constants/messages"; -import StatusLoader from "pages/Editor/gitSync/components/StatusLoader"; +import StatusLoader from "./StatusLoader"; +import type { StatusTreeStruct } from "./types"; +import styled from "styled-components"; + +const CalloutContainer = styled.div` + margin-top: 16px; +`; const noopStatusTransformer = () => null; @@ -49,6 +54,11 @@ export default function StatusChangesView({ {createMessage(CHANGES_SINCE_LAST_DEPLOYMENT)} </Text> <StatusTree tree={statusTree} /> + {status.migrationMessage ? ( + <CalloutContainer> + <Callout kind="info">{status.migrationMessage}</Callout> + </CalloutContainer> + ) : null} </div> ); } diff --git a/app/client/src/git/components/StatusChanges/StatusLoader.tsx b/app/client/src/git/components/StatusChanges/StatusLoader.tsx index bc0427bd6521..9026b75b38fa 100644 --- a/app/client/src/git/components/StatusChanges/StatusLoader.tsx +++ b/app/client/src/git/components/StatusChanges/StatusLoader.tsx @@ -6,16 +6,18 @@ const LoaderWrapper = styled.div` display: flex; flex-direction: row; align-items: center; - margin-top: ${(props) => `${props.theme.spaces[3]}px`}; + margin-bottom: 8px; +`; + +const LoaderText = styled(Text)` + margin-left: 8px; `; function StatusLoader({ loaderMsg }: { loaderMsg: string }) { return ( <LoaderWrapper data-testid="t--git-merge-loader"> <Spinner size="md" /> - <Text kind={"body-m"} style={{ marginLeft: 8 }}> - {loaderMsg} - </Text> + <LoaderText kind="body-m">{loaderMsg}</LoaderText> </LoaderWrapper> ); } diff --git a/app/client/src/git/components/StatusChanges/StatusTree.tsx b/app/client/src/git/components/StatusChanges/StatusTree.tsx index 289d2d28b796..437163d394df 100644 --- a/app/client/src/git/components/StatusChanges/StatusTree.tsx +++ b/app/client/src/git/components/StatusChanges/StatusTree.tsx @@ -7,12 +7,17 @@ import { Text, } from "@appsmith/ads"; import clsx from "clsx"; +import styled from "styled-components"; +import type { StatusTreeStruct } from "./types"; -export interface StatusTreeStruct { - icon: string; - message: string; - children?: StatusTreeStruct[]; -} +const StyledCollapsible = styled(Collapsible)` + gap: 0; +`; + +const StyledCollapsibleHeader = styled(CollapsibleHeader)` + padding-top: 0; + padding-bottom: 0; +`; interface StatusTreeNodeProps { icon: string; @@ -43,29 +48,31 @@ interface SingleStatusTreeProps { function SingleStatusTree({ depth = 1, tree }: SingleStatusTreeProps) { if (!tree) return null; + const noEmphasis = depth > 1 && !tree.children; + if (!tree.children) { return ( <StatusTreeNode icon={tree.icon} message={tree.message} - noEmphasis={depth > 2} + noEmphasis={noEmphasis} /> ); } return ( - <Collapsible className="!mt-0 !gap-0"> - <CollapsibleHeader> + <StyledCollapsible className="space-y-2"> + <StyledCollapsibleHeader arrowPosition="start"> <StatusTreeNode icon={tree.icon} message={tree.message} /> - </CollapsibleHeader> + </StyledCollapsibleHeader> <CollapsibleContent - className={clsx("ml-6", depth < 2 ? "space-y-2" : "space-y-1")} + className={clsx("ml-6", noEmphasis ? "space-y-1" : "space-y-2")} > {tree.children.map((child, index) => ( <SingleStatusTree depth={depth + 1} key={index} tree={child} /> ))} </CollapsibleContent> - </Collapsible> + </StyledCollapsible> ); } diff --git a/app/client/src/git/components/StatusChanges/types.ts b/app/client/src/git/components/StatusChanges/types.ts new file mode 100644 index 000000000000..61a8e074714b --- /dev/null +++ b/app/client/src/git/components/StatusChanges/types.ts @@ -0,0 +1,5 @@ +export interface StatusTreeStruct { + icon: string; + message: string; + children?: StatusTreeStruct[]; +} diff --git a/app/client/src/git/components/index.tsx b/app/client/src/git/components/index.tsx deleted file mode 100644 index c3a1640dbd01..000000000000 --- a/app/client/src/git/components/index.tsx +++ /dev/null @@ -1,3 +0,0 @@ -export { default as GitModals } from "git/ee/components/GitModals"; -export { default as GitImportModal } from "./ImportModal"; -export { default as GitQuickActions } from "./QuickActions"; diff --git a/app/client/src/git/hooks/useArtifactSelector.ts b/app/client/src/git/hooks/useArtifactSelector.ts new file mode 100644 index 000000000000..dba2a0808bf3 --- /dev/null +++ b/app/client/src/git/hooks/useArtifactSelector.ts @@ -0,0 +1,29 @@ +import { useGitContext } from "git/components/GitContextProvider"; +import type { GitArtifactDef, GitRootState } from "git/store/types"; +import { useSelector } from "react-redux"; +import type { Tail } from "redux-saga/effects"; + +/** + * This hook is used to select data from the redux store based on the artifactDef. + **/ +export default function useArtifactSelector< + // need any type to properly infer the return type + /* eslint-disable @typescript-eslint/no-explicit-any */ + Fn extends (state: any, artifactDef: GitArtifactDef, ...args: any[]) => any, +>(selector: Fn, ...args: Tail<Tail<Parameters<Fn>>>): ReturnType<Fn> | null { + const { artifactDef } = useGitContext(); + + return useSelector((state: GitRootState) => { + if (typeof selector !== "function" || !artifactDef) { + return null; + } + + const { artifactType, baseArtifactId } = artifactDef; + + if (!state.git?.artifacts?.[artifactType]?.[baseArtifactId]) { + return null; + } + + return selector(state, artifactDef, ...args); + }); +} diff --git a/app/client/src/git/hooks/useAutocommit.ts b/app/client/src/git/hooks/useAutocommit.ts index 73d7d955caca..91ad0e8aaae5 100644 --- a/app/client/src/git/hooks/useAutocommit.ts +++ b/app/client/src/git/hooks/useAutocommit.ts @@ -6,50 +6,50 @@ import { selectAutocommitPolling, selectToggleAutocommitState, selectTriggerAutocommitState, -} from "git/store/selectors/gitSingleArtifactSelectors"; -import type { GitRootState } from "git/store/types"; +} from "git/store/selectors/gitArtifactSelectors"; import { useCallback } from "react"; -import { useDispatch, useSelector } from "react-redux"; +import { useDispatch } from "react-redux"; +import useArtifactSelector from "./useArtifactSelector"; export default function useAutocommit() { const { artifactDef } = useGitContext(); const dispatch = useDispatch(); - const toggleAutocommitState = useSelector((state: GitRootState) => - selectToggleAutocommitState(state, artifactDef), + const toggleAutocommitState = useArtifactSelector( + selectToggleAutocommitState, ); - const triggerAutocommitState = useSelector((state: GitRootState) => - selectTriggerAutocommitState(state, artifactDef), + const triggerAutocommitState = useArtifactSelector( + selectTriggerAutocommitState, ); const toggleAutocommit = useCallback(() => { - dispatch(gitArtifactActions.toggleAutocommitInit(artifactDef)); + if (artifactDef) { + dispatch(gitArtifactActions.toggleAutocommitInit({ artifactDef })); + } }, [artifactDef, dispatch]); - const isAutocommitDisableModalOpen = useSelector((state: GitRootState) => - selectAutocommitDisableModalOpen(state, artifactDef), + const isAutocommitDisableModalOpen = useArtifactSelector( + selectAutocommitDisableModalOpen, ); const toggleAutocommitDisableModal = useCallback( (open: boolean) => { - dispatch( - gitArtifactActions.toggleAutocommitDisableModal({ - ...artifactDef, - open, - }), - ); + if (artifactDef) { + dispatch( + gitArtifactActions.toggleAutocommitDisableModal({ + artifactDef, + open, + }), + ); + } }, [artifactDef, dispatch], ); - const isAutocommitEnabled = useSelector((state: GitRootState) => - selectAutocommitEnabled(state, artifactDef), - ); + const isAutocommitEnabled = useArtifactSelector(selectAutocommitEnabled); - const isAutocommitPolling = useSelector((state: GitRootState) => - selectAutocommitPolling(state, artifactDef), - ); + const isAutocommitPolling = useArtifactSelector(selectAutocommitPolling); return { isToggleAutocommitLoading: toggleAutocommitState?.loading ?? false, @@ -57,9 +57,9 @@ export default function useAutocommit() { toggleAutocommit, isTriggerAutocommitLoading: triggerAutocommitState?.loading ?? false, triggerAutocommitError: triggerAutocommitState?.error ?? null, - isAutocommitDisableModalOpen, + isAutocommitDisableModalOpen: isAutocommitDisableModalOpen ?? false, toggleAutocommitDisableModal, - isAutocommitEnabled, - isAutocommitPolling, + isAutocommitEnabled: isAutocommitEnabled ?? false, + isAutocommitPolling: isAutocommitPolling ?? false, }; } diff --git a/app/client/src/git/hooks/useBranches.ts b/app/client/src/git/hooks/useBranches.ts index 4a0ecead44d7..fe85a318b8d4 100644 --- a/app/client/src/git/hooks/useBranches.ts +++ b/app/client/src/git/hooks/useBranches.ts @@ -8,103 +8,105 @@ import { selectCreateBranchState, selectDeleteBranchState, selectCurrentBranch, -} from "git/store/selectors/gitSingleArtifactSelectors"; -import type { GitRootState } from "git/store/types"; +} from "git/store/selectors/gitArtifactSelectors"; import { useCallback } from "react"; -import { useDispatch, useSelector } from "react-redux"; +import { useDispatch } from "react-redux"; +import useArtifactSelector from "./useArtifactSelector"; export default function useBranches() { - const { artifactDef } = useGitContext(); + const { artifact, artifactDef } = useGitContext(); + const artifactId = artifact?.id; const dispatch = useDispatch(); // fetch branches - const branchesState = useSelector((state: GitRootState) => - selectFetchBranchesState(state, artifactDef), - ); + const branchesState = useArtifactSelector(selectFetchBranchesState); + const fetchBranches = useCallback(() => { - dispatch( - gitArtifactActions.fetchBranchesInit({ - ...artifactDef, - pruneBranches: true, - }), - ); - }, [artifactDef, dispatch]); + if (artifactDef && artifactId) { + dispatch( + gitArtifactActions.fetchBranchesInit({ + artifactId, + artifactDef, + pruneBranches: true, + }), + ); + } + }, [artifactDef, artifactId, dispatch]); // create branch - const createBranchState = useSelector((state: GitRootState) => - selectCreateBranchState(state, artifactDef), - ); + const createBranchState = useArtifactSelector(selectCreateBranchState); const createBranch = useCallback( (branchName: string) => { - dispatch( - gitArtifactActions.createBranchInit({ - ...artifactDef, - branchName, - }), - ); + if (artifactDef && artifactId) { + dispatch( + gitArtifactActions.createBranchInit({ + artifactDef, + artifactId, + branchName, + }), + ); + } }, - [artifactDef, dispatch], + [artifactDef, artifactId, dispatch], ); // delete branch - const deleteBranchState = useSelector((state: GitRootState) => - selectDeleteBranchState(state, artifactDef), - ); + const deleteBranchState = useArtifactSelector(selectDeleteBranchState); const deleteBranch = useCallback( (branchName: string) => { - dispatch( - gitArtifactActions.deleteBranchInit({ - ...artifactDef, - branchName, - }), - ); + if (artifactDef && artifactId) { + dispatch( + gitArtifactActions.deleteBranchInit({ + artifactId, + artifactDef, + branchName, + }), + ); + } }, - [artifactDef, dispatch], + [artifactDef, artifactId, dispatch], ); // checkout branch - const checkoutBranchState = useSelector((state: GitRootState) => - selectCheckoutBranchState(state, artifactDef), - ); + const checkoutBranchState = useArtifactSelector(selectCheckoutBranchState); const checkoutBranch = useCallback( (branchName: string) => { - dispatch( - gitArtifactActions.checkoutBranchInit({ - ...artifactDef, - branchName, - }), - ); + if (artifactDef && artifactId) { + dispatch( + gitArtifactActions.checkoutBranchInit({ + artifactDef, + artifactId, + branchName, + }), + ); + } }, - [artifactDef, dispatch], + [artifactDef, artifactId, dispatch], ); - const checkoutDestBranch = useSelector((state: GitRootState) => - selectCheckoutDestBranch(state, artifactDef), - ); + const checkoutDestBranch = useArtifactSelector(selectCheckoutDestBranch); // derived - const currentBranch = useSelector((state: GitRootState) => - selectCurrentBranch(state, artifactDef), - ); + const currentBranch = useArtifactSelector(selectCurrentBranch); // git branch list popup - const isBranchPopupOpen = useSelector((state: GitRootState) => - selectBranchPopupOpen(state, artifactDef), - ); + const isBranchPopupOpen = useArtifactSelector(selectBranchPopupOpen); const toggleBranchPopup = useCallback( (open: boolean) => { - dispatch( - gitArtifactActions.toggleBranchPopup({ - ...artifactDef, - open, - }), - ); + if (artifactDef) { + dispatch( + gitArtifactActions.toggleBranchPopup({ + artifactDef, + open, + }), + ); + } }, [artifactDef, dispatch], ); return { - branches: branchesState?.value, + branches: branchesState?.value ?? null, isFetchBranchesLoading: branchesState?.loading ?? false, fetchBranchesError: branchesState?.error ?? null, fetchBranches, @@ -119,7 +121,7 @@ export default function useBranches() { checkoutBranch, checkoutDestBranch, currentBranch: currentBranch ?? null, - isBranchPopupOpen, + isBranchPopupOpen: isBranchPopupOpen ?? false, toggleBranchPopup, }; } diff --git a/app/client/src/git/hooks/useCommit.ts b/app/client/src/git/hooks/useCommit.ts index 56f78cc11bcd..6a468046a84b 100644 --- a/app/client/src/git/hooks/useCommit.ts +++ b/app/client/src/git/hooks/useCommit.ts @@ -1,38 +1,43 @@ import { useGitContext } from "git/components/GitContextProvider"; import { gitArtifactActions } from "git/store/gitArtifactSlice"; -import { selectCommitState } from "git/store/selectors/gitSingleArtifactSelectors"; -import type { GitRootState } from "git/store/types"; +import { selectCommitState } from "git/store/selectors/gitArtifactSelectors"; import { useCallback } from "react"; -import { useDispatch, useSelector } from "react-redux"; +import { useDispatch } from "react-redux"; +import useArtifactSelector from "./useArtifactSelector"; export default function useCommit() { - const { artifactDef } = useGitContext(); + const { artifact, artifactDef } = useGitContext(); + const artifactId = artifact?.id; + const dispatch = useDispatch(); - const commitState = useSelector((state: GitRootState) => - selectCommitState(state, artifactDef), - ); + const commitState = useArtifactSelector(selectCommitState); const commit = useCallback( (commitMessage: string) => { - dispatch( - gitArtifactActions.commitInit({ - ...artifactDef, - commitMessage, - doPush: true, - }), - ); + if (artifactDef && artifactId) { + dispatch( + gitArtifactActions.commitInit({ + artifactId, + artifactDef, + commitMessage, + doPush: true, + }), + ); + } }, - [artifactDef, dispatch], + [artifactDef, artifactId, dispatch], ); const clearCommitError = useCallback(() => { - dispatch(gitArtifactActions.clearCommitError(artifactDef)); + if (artifactDef) { + dispatch(gitArtifactActions.clearCommitError({ artifactDef })); + } }, [artifactDef, dispatch]); return { isCommitLoading: commitState?.loading ?? false, - commitError: commitState?.error, + commitError: commitState?.error ?? null, commit, clearCommitError, }; diff --git a/app/client/src/git/hooks/useConnect.ts b/app/client/src/git/hooks/useConnect.ts index 1064ce7ff26e..884addac0fd7 100644 --- a/app/client/src/git/hooks/useConnect.ts +++ b/app/client/src/git/hooks/useConnect.ts @@ -4,82 +4,53 @@ import { gitArtifactActions } from "git/store/gitArtifactSlice"; import { selectConnectModalOpen, selectConnectState, - selectFetchSSHKeysState, - selectGenerateSSHKeyState, - selectGitImportState, -} from "git/store/selectors/gitSingleArtifactSelectors"; -import type { GitRootState } from "git/store/types"; + selectConnectSuccessModalOpen, +} from "git/store/selectors/gitArtifactSelectors"; import { useCallback } from "react"; import { useDispatch } from "react-redux"; -import { useSelector } from "react-redux"; +import useArtifactSelector from "./useArtifactSelector"; export default function useConnect() { const { artifactDef } = useGitContext(); const dispatch = useDispatch(); - const connectState = useSelector((state: GitRootState) => - selectConnectState(state, artifactDef), - ); + const connectState = useArtifactSelector(selectConnectState); const connect = useCallback( (params: ConnectRequestParams) => { - dispatch(gitArtifactActions.connectInit({ ...artifactDef, ...params })); - }, - [artifactDef, dispatch], - ); - - const gitImportState = useSelector((state: GitRootState) => - selectGitImportState(state, artifactDef), - ); - - const gitImport = useCallback( - (params) => { - dispatch(gitArtifactActions.gitImportInit({ ...artifactDef, ...params })); + if (artifactDef) { + dispatch(gitArtifactActions.connectInit({ artifactDef, ...params })); + } }, [artifactDef, dispatch], ); - const fetchSSHKeyState = useSelector((state: GitRootState) => - selectFetchSSHKeysState(state, artifactDef), - ); - - const fetchSSHKey = useCallback(() => { - dispatch(gitArtifactActions.fetchSSHKeyInit(artifactDef)); - }, [artifactDef, dispatch]); - - const resetFetchSSHKey = useCallback(() => { - dispatch(gitArtifactActions.resetFetchSSHKey(artifactDef)); - }, [artifactDef, dispatch]); - - const generateSSHKeyState = useSelector((state: GitRootState) => - selectGenerateSSHKeyState(state, artifactDef), - ); + const isConnectModalOpen = useArtifactSelector(selectConnectModalOpen); - const generateSSHKey = useCallback( - (keyType: string, isImport: boolean = false) => { - dispatch( - gitArtifactActions.generateSSHKeyInit({ - ...artifactDef, - keyType, - isImport, - }), - ); + const toggleConnectModal = useCallback( + (open: boolean) => { + if (artifactDef) { + dispatch(gitArtifactActions.toggleConnectModal({ artifactDef, open })); + } }, [artifactDef, dispatch], ); - const resetGenerateSSHKey = useCallback(() => { - dispatch(gitArtifactActions.resetGenerateSSHKey(artifactDef)); - }, [artifactDef, dispatch]); - - const isConnectModalOpen = useSelector((state: GitRootState) => - selectConnectModalOpen(state, artifactDef), + const isConnectSuccessModalOpen = useArtifactSelector( + selectConnectSuccessModalOpen, ); - const toggleConnectModal = useCallback( + const toggleConnectSuccessModal = useCallback( (open: boolean) => { - dispatch(gitArtifactActions.toggleConnectModal({ ...artifactDef, open })); + if (artifactDef) { + dispatch( + gitArtifactActions.toggleConnectSuccessModal({ + artifactDef, + open, + }), + ); + } }, [artifactDef, dispatch], ); @@ -88,19 +59,9 @@ export default function useConnect() { isConnectLoading: connectState?.loading ?? false, connectError: connectState?.error ?? null, connect, - isGitImportLoading: gitImportState?.loading ?? false, - gitImportError: gitImportState?.error ?? null, - gitImport, - sshKey: fetchSSHKeyState?.value ?? null, - isFetchSSHKeyLoading: fetchSSHKeyState?.loading ?? false, - fetchSSHKeyError: fetchSSHKeyState?.error ?? null, - fetchSSHKey, - resetFetchSSHKey, - isGenerateSSHKeyLoading: generateSSHKeyState?.loading ?? false, - generateSSHKeyError: generateSSHKeyState?.error ?? null, - generateSSHKey, - resetGenerateSSHKey, - isConnectModalOpen, + isConnectModalOpen: isConnectModalOpen ?? false, toggleConnectModal, + isConnectSuccessModalOpen: isConnectSuccessModalOpen ?? false, + toggleConnectSuccessModal, }; } diff --git a/app/client/src/git/hooks/useConnected.ts b/app/client/src/git/hooks/useConnected.ts new file mode 100644 index 000000000000..39cfa55ca245 --- /dev/null +++ b/app/client/src/git/hooks/useConnected.ts @@ -0,0 +1,8 @@ +import { selectConnected } from "git/store/selectors/gitArtifactSelectors"; +import useArtifactSelector from "./useArtifactSelector"; + +export default function useConnected() { + const isConnected = useArtifactSelector(selectConnected); + + return isConnected ?? false; +} diff --git a/app/client/src/git/hooks/useCurrentBranch.ts b/app/client/src/git/hooks/useCurrentBranch.ts new file mode 100644 index 000000000000..797d8d598ba5 --- /dev/null +++ b/app/client/src/git/hooks/useCurrentBranch.ts @@ -0,0 +1,8 @@ +import { selectCurrentBranch } from "git/store/selectors/gitArtifactSelectors"; +import useArtifactSelector from "./useArtifactSelector"; + +export default function useCurrentBranch() { + const currentBranch = useArtifactSelector(selectCurrentBranch); + + return currentBranch; +} diff --git a/app/client/src/git/hooks/useDiscard.ts b/app/client/src/git/hooks/useDiscard.ts index 2f71c11608f9..19818cb7f8fa 100644 --- a/app/client/src/git/hooks/useDiscard.ts +++ b/app/client/src/git/hooks/useDiscard.ts @@ -1,24 +1,26 @@ import { useGitContext } from "git/components/GitContextProvider"; import { gitArtifactActions } from "git/store/gitArtifactSlice"; -import { selectDiscardState } from "git/store/selectors/gitSingleArtifactSelectors"; -import type { GitRootState } from "git/store/types"; +import { selectDiscardState } from "git/store/selectors/gitArtifactSelectors"; import { useCallback } from "react"; -import { useDispatch, useSelector } from "react-redux"; +import { useDispatch } from "react-redux"; +import useArtifactSelector from "./useArtifactSelector"; export default function useDiscard() { const { artifactDef } = useGitContext(); const dispatch = useDispatch(); - const discardState = useSelector((state: GitRootState) => - selectDiscardState(state, artifactDef), - ); + const discardState = useArtifactSelector(selectDiscardState); const discard = useCallback(() => { - dispatch(gitArtifactActions.discardInit(artifactDef)); + if (artifactDef) { + dispatch(gitArtifactActions.discardInit({ artifactDef })); + } }, [artifactDef, dispatch]); const clearDiscardError = useCallback(() => { - dispatch(gitArtifactActions.clearDiscardError(artifactDef)); + if (artifactDef) { + dispatch(gitArtifactActions.clearDiscardError({ artifactDef })); + } }, [artifactDef, dispatch]); return { diff --git a/app/client/src/git/hooks/useDisconnect.ts b/app/client/src/git/hooks/useDisconnect.ts index 36dfd2cf8cf9..42fd878319fd 100644 --- a/app/client/src/git/hooks/useDisconnect.ts +++ b/app/client/src/git/hooks/useDisconnect.ts @@ -4,10 +4,10 @@ import { selectDisconnectArtifactName, selectDisconnectBaseArtifactId, selectDisconnectState, -} from "git/store/selectors/gitSingleArtifactSelectors"; -import type { GitRootState } from "git/store/types"; +} from "git/store/selectors/gitArtifactSelectors"; import { useCallback } from "react"; -import { useDispatch, useSelector } from "react-redux"; +import { useDispatch } from "react-redux"; +import useArtifactSelector from "./useArtifactSelector"; export default function useDisconnect() { const { artifact, artifactDef } = useGitContext(); @@ -15,30 +15,38 @@ export default function useDisconnect() { const dispatch = useDispatch(); - const disconnectState = useSelector((state: GitRootState) => - selectDisconnectState(state, artifactDef), - ); + const disconnectState = useArtifactSelector(selectDisconnectState); const disconnect = useCallback(() => { - dispatch(gitArtifactActions.disconnectInit(artifactDef)); + if (artifactDef) { + dispatch( + gitArtifactActions.disconnectInit({ + artifactDef, + }), + ); + } }, [artifactDef, dispatch]); - const disconnectBaseArtifactId = useSelector((state: GitRootState) => - selectDisconnectBaseArtifactId(state, artifactDef), + const disconnectBaseArtifactId = useArtifactSelector( + selectDisconnectBaseArtifactId, ); - const disconnectArtifactName = useSelector((state: GitRootState) => - selectDisconnectArtifactName(state, artifactDef), + const disconnectArtifactName = useArtifactSelector( + selectDisconnectArtifactName, ); const openDisconnectModal = useCallback(() => { - dispatch( - gitArtifactActions.openDisconnectModal({ ...artifactDef, artifactName }), - ); + if (artifactDef) { + dispatch( + gitArtifactActions.openDisconnectModal({ artifactDef, artifactName }), + ); + } }, [artifactDef, artifactName, dispatch]); const closeDisconnectModal = useCallback(() => { - dispatch(gitArtifactActions.closeDisconnectModal(artifactDef)); + if (artifactDef) { + dispatch(gitArtifactActions.closeDisconnectModal({ artifactDef })); + } }, [artifactDef, dispatch]); return { diff --git a/app/client/src/git/hooks/useGitPermissions.ts b/app/client/src/git/hooks/useGitPermissions.ts index 3279dcd3e00e..13ca2404a161 100644 --- a/app/client/src/git/hooks/useGitPermissions.ts +++ b/app/client/src/git/hooks/useGitPermissions.ts @@ -10,47 +10,46 @@ import { useMemo } from "react"; export default function useGitPermissions() { const { artifact, artifactDef } = useGitContext(); - const { artifactType } = artifactDef; const isConnectPermitted = useMemo(() => { if (artifact) { - if (artifactType === GitArtifactType.Application) { + if (artifactDef?.artifactType === GitArtifactType.Application) { return hasConnectToGitPermission(artifact.userPermissions); } } return false; - }, [artifact, artifactType]); + }, [artifact, artifactDef?.artifactType]); const isManageDefaultBranchPermitted = useMemo(() => { if (artifact) { - if (artifactType === GitArtifactType.Application) { + if (artifactDef?.artifactType === GitArtifactType.Application) { return hasManageDefaultBranchPermission(artifact.userPermissions); } } return false; - }, [artifact, artifactType]); + }, [artifact, artifactDef?.artifactType]); const isManageProtectedBranchesPermitted = useMemo(() => { if (artifact) { - if (artifactType === GitArtifactType.Application) { + if (artifactDef?.artifactType === GitArtifactType.Application) { return hasManageProtectedBranchesPermission(artifact.userPermissions); } } return false; - }, [artifact, artifactType]); + }, [artifact, artifactDef?.artifactType]); const isManageAutocommitPermitted = useMemo(() => { if (artifact) { - if (artifactType === GitArtifactType.Application) { + if (artifactDef?.artifactType === GitArtifactType.Application) { return hasManageAutoCommitPermission(artifact.userPermissions); } } return false; - }, [artifact, artifactType]); + }, [artifact, artifactDef?.artifactType]); return { isConnectPermitted, diff --git a/app/client/src/git/hooks/useGlobalProfile.ts b/app/client/src/git/hooks/useGlobalProfile.ts index f319f9c1f5db..3cc3a80aad98 100644 --- a/app/client/src/git/hooks/useGlobalProfile.ts +++ b/app/client/src/git/hooks/useGlobalProfile.ts @@ -1,9 +1,9 @@ import type { UpdateGlobalProfileRequestParams } from "git/requests/updateGlobalProfileRequest.types"; -import { gitConfigActions } from "git/store/gitConfigSlice"; +import { gitGlobalActions } from "git/store/gitGlobalSlice"; import { selectFetchGlobalProfileState, selectUpdateGlobalProfileState, -} from "git/store/selectors/gitConfigSelectors"; +} from "git/store/selectors/gitGlobalSelectors"; import type { GitRootState } from "git/store/types"; import { useCallback } from "react"; @@ -16,7 +16,7 @@ export default function useGlobalProfile() { ); const fetchGlobalProfile = useCallback(() => { - dispatch(gitConfigActions.fetchGlobalProfileInit()); + dispatch(gitGlobalActions.fetchGlobalProfileInit()); }, [dispatch]); const updateGlobalProfileState = useSelector((state: GitRootState) => @@ -25,7 +25,7 @@ export default function useGlobalProfile() { const updateGlobalProfile = useCallback( (params: UpdateGlobalProfileRequestParams) => { - dispatch(gitConfigActions.updateGlobalProfileInit(params)); + dispatch(gitGlobalActions.updateGlobalProfileInit(params)); }, [dispatch], ); diff --git a/app/client/src/git/hooks/useGlobalSSHKey.ts b/app/client/src/git/hooks/useGlobalSSHKey.ts new file mode 100644 index 000000000000..ac7216045a6a --- /dev/null +++ b/app/client/src/git/hooks/useGlobalSSHKey.ts @@ -0,0 +1,29 @@ +import { useCallback } from "react"; +import { useDispatch, useSelector } from "react-redux"; +import { selectFetchGlobalSSHKeyState } from "git/store/selectors/gitGlobalSelectors"; +import { gitGlobalActions } from "git/store/gitGlobalSlice"; + +export default function useGlobalSSHKey() { + const dispatch = useDispatch(); + + const globalSSHKeyState = useSelector(selectFetchGlobalSSHKeyState); + + const fetchGlobalSSHKey = useCallback( + (keyType: string) => { + dispatch(gitGlobalActions.fetchGlobalSSHKeyInit({ keyType })); + }, + [dispatch], + ); + + const resetGlobalSSHKey = useCallback(() => { + dispatch(gitGlobalActions.resetGlobalSSHKey()); + }, [dispatch]); + + return { + globalSSHKey: globalSSHKeyState?.value ?? null, + globalSSHKeyError: globalSSHKeyState?.error ?? null, + isFetchGlobalSSHKeyLoading: globalSSHKeyState?.loading ?? false, + fetchGlobalSSHKey, + resetGlobalSSHKey, + }; +} diff --git a/app/client/src/git/hooks/useImport.ts b/app/client/src/git/hooks/useImport.ts new file mode 100644 index 000000000000..62069b888d68 --- /dev/null +++ b/app/client/src/git/hooks/useImport.ts @@ -0,0 +1,38 @@ +import { useCallback } from "react"; +import { useDispatch, useSelector } from "react-redux"; +import { + selectGitImportState, + selectImportModalOpen, +} from "git/store/selectors/gitGlobalSelectors"; +import { gitGlobalActions } from "git/store/gitGlobalSlice"; +import type { GitImportRequestParams } from "git/requests/gitImportRequest.types"; + +export default function useImport() { + const dispatch = useDispatch(); + + const gitImportState = useSelector(selectGitImportState); + + const gitImport = useCallback( + (params: GitImportRequestParams) => { + dispatch(gitGlobalActions.gitImportInit(params)); + }, + [dispatch], + ); + + const isImportModalOpen = useSelector(selectImportModalOpen); + + const toggleImportModal = useCallback( + (open: boolean) => { + dispatch(gitGlobalActions.toggleImportModal({ open })); + }, + [dispatch], + ); + + return { + isGitImportLoading: gitImportState?.loading ?? false, + gitImportError: gitImportState?.error ?? null, + gitImport, + isImportModalOpen: isImportModalOpen ?? false, + toggleImportModal, + }; +} diff --git a/app/client/src/git/hooks/useLocalProfile.ts b/app/client/src/git/hooks/useLocalProfile.ts index e770ad6356bc..8d77899a7602 100644 --- a/app/client/src/git/hooks/useLocalProfile.ts +++ b/app/client/src/git/hooks/useLocalProfile.ts @@ -4,36 +4,40 @@ import { gitArtifactActions } from "git/store/gitArtifactSlice"; import { selectFetchLocalProfileState, selectUpdateLocalProfileState, -} from "git/store/selectors/gitSingleArtifactSelectors"; -import type { GitRootState } from "git/store/types"; +} from "git/store/selectors/gitArtifactSelectors"; import { useCallback } from "react"; -import { useDispatch, useSelector } from "react-redux"; +import { useDispatch } from "react-redux"; +import useArtifactSelector from "./useArtifactSelector"; export default function useLocalProfile() { const { artifactDef } = useGitContext(); const dispatch = useDispatch(); - const fetchLocalProfileState = useSelector((state: GitRootState) => - selectFetchLocalProfileState(state, artifactDef), + const fetchLocalProfileState = useArtifactSelector( + selectFetchLocalProfileState, ); const fetchLocalProfile = useCallback(() => { - dispatch(gitArtifactActions.fetchLocalProfileInit(artifactDef)); + if (artifactDef) { + dispatch(gitArtifactActions.fetchLocalProfileInit({ artifactDef })); + } }, [artifactDef, dispatch]); - const updateLocalProfileState = useSelector((state: GitRootState) => - selectUpdateLocalProfileState(state, artifactDef), + const updateLocalProfileState = useArtifactSelector( + selectUpdateLocalProfileState, ); const updateLocalProfile = useCallback( (params: UpdateLocalProfileRequestParams) => { - dispatch( - gitArtifactActions.updateLocalProfileInit({ - ...artifactDef, - ...params, - }), - ); + if (artifactDef) { + dispatch( + gitArtifactActions.updateLocalProfileInit({ + artifactDef, + ...params, + }), + ); + } }, [artifactDef, dispatch], ); diff --git a/app/client/src/git/hooks/useMerge.ts b/app/client/src/git/hooks/useMerge.ts index f7394601b191..8fa79b16049f 100644 --- a/app/client/src/git/hooks/useMerge.ts +++ b/app/client/src/git/hooks/useMerge.ts @@ -3,10 +3,10 @@ import { gitArtifactActions } from "git/store/gitArtifactSlice"; import { selectMergeState, selectMergeStatusState, -} from "git/store/selectors/gitSingleArtifactSelectors"; -import type { GitRootState } from "git/store/types"; +} from "git/store/selectors/gitArtifactSelectors"; import { useCallback } from "react"; -import { useDispatch, useSelector } from "react-redux"; +import { useDispatch } from "react-redux"; +import useArtifactSelector from "./useArtifactSelector"; export default function useMerge() { const { artifact, artifactDef } = useGitContext(); @@ -14,44 +14,46 @@ export default function useMerge() { const dispatch = useDispatch(); // merge - const mergeState = useSelector((state: GitRootState) => - selectMergeState(state, artifactDef), - ); + const mergeState = useArtifactSelector(selectMergeState); const merge = useCallback(() => { - dispatch(gitArtifactActions.mergeInit(artifactDef)); + if (artifactDef) { + dispatch(gitArtifactActions.mergeInit({ artifactDef })); + } }, [artifactDef, dispatch]); // merge status - const mergeStatusState = useSelector((state: GitRootState) => - selectMergeStatusState(state, artifactDef), - ); + const mergeStatusState = useArtifactSelector(selectMergeStatusState); const fetchMergeStatus = useCallback( (sourceBranch: string, destinationBranch: string) => { - dispatch( - gitArtifactActions.fetchMergeStatusInit({ - ...artifactDef, - artifactId: artifactId ?? "", - sourceBranch, - destinationBranch, - }), - ); + if (artifactDef) { + dispatch( + gitArtifactActions.fetchMergeStatusInit({ + artifactDef, + artifactId: artifactId ?? "", + sourceBranch, + destinationBranch, + }), + ); + } }, [artifactId, artifactDef, dispatch], ); const clearMergeStatus = useCallback(() => { - dispatch(gitArtifactActions.clearMergeStatus(artifactDef)); + if (artifactDef) { + dispatch(gitArtifactActions.clearMergeStatus({ artifactDef })); + } }, [artifactDef, dispatch]); return { isMergeLoading: mergeState?.loading ?? false, - mergeError: mergeState?.error, + mergeError: mergeState?.error ?? null, merge, - mergeStatus: mergeStatusState?.value, + mergeStatus: mergeStatusState?.value ?? null, isFetchMergeStatusLoading: mergeStatusState?.loading ?? false, - fetchMergeStatusError: mergeStatusState?.error, + fetchMergeStatusError: mergeStatusState?.error ?? null, fetchMergeStatus, clearMergeStatus, }; diff --git a/app/client/src/git/hooks/useMetadata.ts b/app/client/src/git/hooks/useMetadata.ts index 9bd5356ad763..2ccd15d7ec89 100644 --- a/app/client/src/git/hooks/useMetadata.ts +++ b/app/client/src/git/hooks/useMetadata.ts @@ -1,26 +1,12 @@ -import { useGitContext } from "git/components/GitContextProvider"; -import { - selectGitConnected, - selectMetadataState, -} from "git/store/selectors/gitSingleArtifactSelectors"; -import type { GitRootState } from "git/store/types"; -import { useSelector } from "react-redux"; +import { selectMetadataState } from "git/store/selectors/gitArtifactSelectors"; +import useArtifactSelector from "./useArtifactSelector"; export default function useMetadata() { - const { artifactDef } = useGitContext(); - - const metadataState = useSelector((state: GitRootState) => - selectMetadataState(state, artifactDef), - ); - - const isGitConnected = useSelector((state: GitRootState) => - selectGitConnected(state, artifactDef), - ); + const metadataState = useArtifactSelector(selectMetadataState); return { metadata: metadataState?.value ?? null, isFetchMetadataLoading: metadataState?.loading ?? false, fetchMetadataError: metadataState?.error ?? null, - isGitConnected, }; } diff --git a/app/client/src/git/hooks/useOps.ts b/app/client/src/git/hooks/useOps.ts index 32eec997cf25..9b15bd035d85 100644 --- a/app/client/src/git/hooks/useOps.ts +++ b/app/client/src/git/hooks/useOps.ts @@ -5,10 +5,10 @@ import { selectConflictErrorModalOpen, selectOpsModalOpen, selectOpsModalTab, -} from "git/store/selectors/gitSingleArtifactSelectors"; -import type { GitRootState } from "git/store/types"; +} from "git/store/selectors/gitArtifactSelectors"; import { useCallback } from "react"; -import { useDispatch, useSelector } from "react-redux"; +import { useDispatch } from "react-redux"; +import useArtifactSelector from "./useArtifactSelector"; export default function useOps() { const { artifactDef } = useGitContext(); @@ -16,42 +16,40 @@ export default function useOps() { const dispatch = useDispatch(); // ops modal - const opsModalOpen = useSelector((state: GitRootState) => - selectOpsModalOpen(state, artifactDef), - ); + const opsModalOpen = useArtifactSelector(selectOpsModalOpen); - const opsModalTab = useSelector((state: GitRootState) => - selectOpsModalTab(state, artifactDef), - ); + const opsModalTab = useArtifactSelector(selectOpsModalTab); const toggleOpsModal = useCallback( (open: boolean, tab: keyof typeof GitOpsTab = GitOpsTab.Deploy) => { - dispatch( - gitArtifactActions.toggleOpsModal({ ...artifactDef, open, tab }), - ); + if (artifactDef) { + dispatch(gitArtifactActions.toggleOpsModal({ artifactDef, open, tab })); + } }, [artifactDef, dispatch], ); // conflict error modal - const conflictErrorModalOpen = useSelector((state: GitRootState) => - selectConflictErrorModalOpen(state, artifactDef), + const conflictErrorModalOpen = useArtifactSelector( + selectConflictErrorModalOpen, ); const toggleConflictErrorModal = useCallback( (open: boolean) => { - dispatch( - gitArtifactActions.toggleConflictErrorModal({ ...artifactDef, open }), - ); + if (artifactDef) { + dispatch( + gitArtifactActions.toggleConflictErrorModal({ artifactDef, open }), + ); + } }, [artifactDef, dispatch], ); return { opsModalTab, - opsModalOpen, + isOpsModalOpen: opsModalOpen ?? false, toggleOpsModal, - conflictErrorModalOpen, + isConflictErrorModalOpen: conflictErrorModalOpen ?? false, toggleConflictErrorModal, }; } diff --git a/app/client/src/git/hooks/useProtectedBranches.ts b/app/client/src/git/hooks/useProtectedBranches.ts index fa3b2ef89307..6ec68ee23b74 100644 --- a/app/client/src/git/hooks/useProtectedBranches.ts +++ b/app/client/src/git/hooks/useProtectedBranches.ts @@ -2,55 +2,55 @@ import { useGitContext } from "git/components/GitContextProvider"; import { gitArtifactActions } from "git/store/gitArtifactSlice"; import { selectFetchProtectedBranchesState, - selectProtectedMode, selectUpdateProtectedBranchesState, -} from "git/store/selectors/gitSingleArtifactSelectors"; -import type { GitRootState } from "git/store/types"; +} from "git/store/selectors/gitArtifactSelectors"; import { useCallback } from "react"; -import { useDispatch, useSelector } from "react-redux"; +import { useDispatch } from "react-redux"; +import useArtifactSelector from "./useArtifactSelector"; function useProtectedBranches() { const { artifactDef } = useGitContext(); const dispatch = useDispatch(); - const fetchProtectedBranchesState = useSelector((state: GitRootState) => - selectFetchProtectedBranchesState(state, artifactDef), + const fetchProtectedBranchesState = useArtifactSelector( + selectFetchProtectedBranchesState, ); const fetchProtectedBranches = useCallback(() => { - dispatch(gitArtifactActions.fetchProtectedBranchesInit(artifactDef)); + if (artifactDef) { + dispatch(gitArtifactActions.fetchProtectedBranchesInit({ artifactDef })); + } }, [dispatch, artifactDef]); - const updateProtectedBranchesState = useSelector((state: GitRootState) => - selectUpdateProtectedBranchesState(state, artifactDef), + const updateProtectedBranchesState = useArtifactSelector( + selectUpdateProtectedBranchesState, ); const updateProtectedBranches = useCallback( (branches: string[]) => { - dispatch( - gitArtifactActions.updateProtectedBranchesInit({ - ...artifactDef, - branchNames: branches, - }), - ); + if (artifactDef) { + dispatch( + gitArtifactActions.updateProtectedBranchesInit({ + artifactDef, + branchNames: branches, + }), + ); + } }, [dispatch, artifactDef], ); - const isProtectedMode = useSelector((state: GitRootState) => - selectProtectedMode(state, artifactDef), - ); - return { - protectedBranches: fetchProtectedBranchesState.value, - isFetchProtectedBranchesLoading: fetchProtectedBranchesState.loading, - fetchProtectedBranchesError: fetchProtectedBranchesState.error, + protectedBranches: fetchProtectedBranchesState?.value ?? null, + isFetchProtectedBranchesLoading: + fetchProtectedBranchesState?.loading ?? false, + fetchProtectedBranchesError: fetchProtectedBranchesState?.error ?? null, fetchProtectedBranches, - isUpdateProtectedBranchesLoading: updateProtectedBranchesState.loading, - updateProtectedBranchesError: updateProtectedBranchesState.error, + isUpdateProtectedBranchesLoading: + updateProtectedBranchesState?.loading ?? false, + updateProtectedBranchesError: updateProtectedBranchesState?.error ?? null, updateProtectedBranches, - isProtectedMode, }; } diff --git a/app/client/src/git/hooks/useProtectedMode.ts b/app/client/src/git/hooks/useProtectedMode.ts new file mode 100644 index 000000000000..e8e86e9f04a2 --- /dev/null +++ b/app/client/src/git/hooks/useProtectedMode.ts @@ -0,0 +1,8 @@ +import { selectProtectedMode } from "git/store/selectors/gitArtifactSelectors"; +import useArtifactSelector from "./useArtifactSelector"; + +export default function useProtectedMode() { + const isProtectedMode = useArtifactSelector(selectProtectedMode); + + return isProtectedMode ?? false; +} diff --git a/app/client/src/git/hooks/usePull.ts b/app/client/src/git/hooks/usePull.ts index 992866f2c277..19900c98f38e 100644 --- a/app/client/src/git/hooks/usePull.ts +++ b/app/client/src/git/hooks/usePull.ts @@ -1,26 +1,26 @@ import { useGitContext } from "git/components/GitContextProvider"; import { gitArtifactActions } from "git/store/gitArtifactSlice"; -import { selectPullState } from "git/store/selectors/gitSingleArtifactSelectors"; -import type { GitRootState } from "git/store/types"; +import { selectPullState } from "git/store/selectors/gitArtifactSelectors"; import { useCallback } from "react"; -import { useDispatch, useSelector } from "react-redux"; +import { useDispatch } from "react-redux"; +import useArtifactSelector from "./useArtifactSelector"; export default function usePull() { const { artifact, artifactDef } = useGitContext(); const artifactId = artifact?.id; const dispatch = useDispatch(); - const pullState = useSelector((state: GitRootState) => - selectPullState(state, artifactDef), - ); + const pullState = useArtifactSelector(selectPullState); const pull = useCallback(() => { - dispatch( - gitArtifactActions.pullInit({ - ...artifactDef, - artifactId: artifactId ?? "", - }), - ); + if (artifactDef) { + dispatch( + gitArtifactActions.pullInit({ + artifactDef, + artifactId: artifactId ?? "", + }), + ); + } }, [artifactDef, artifactId, dispatch]); return { diff --git a/app/client/src/git/hooks/useSSHKey.ts b/app/client/src/git/hooks/useSSHKey.ts new file mode 100644 index 000000000000..93c95ade8d31 --- /dev/null +++ b/app/client/src/git/hooks/useSSHKey.ts @@ -0,0 +1,63 @@ +import { useGitContext } from "git/components/GitContextProvider"; +import { gitArtifactActions } from "git/store/gitArtifactSlice"; +import { + selectFetchSSHKeysState, + selectGenerateSSHKeyState, +} from "git/store/selectors/gitArtifactSelectors"; +import { useCallback } from "react"; +import { useDispatch } from "react-redux"; +import useArtifactSelector from "./useArtifactSelector"; + +export default function useSSHKey() { + const { artifactDef } = useGitContext(); + + const dispatch = useDispatch(); + + const fetchSSHKeyState = useArtifactSelector(selectFetchSSHKeysState); + + const fetchSSHKey = useCallback(() => { + if (artifactDef) { + dispatch(gitArtifactActions.fetchSSHKeyInit({ artifactDef })); + } + }, [artifactDef, dispatch]); + + const resetFetchSSHKey = useCallback(() => { + if (artifactDef) { + dispatch(gitArtifactActions.resetFetchSSHKey({ artifactDef })); + } + }, [artifactDef, dispatch]); + + const generateSSHKeyState = useArtifactSelector(selectGenerateSSHKeyState); + + const generateSSHKey = useCallback( + (keyType: string) => { + if (artifactDef) { + dispatch( + gitArtifactActions.generateSSHKeyInit({ + artifactDef, + keyType, + }), + ); + } + }, + [artifactDef, dispatch], + ); + + const resetGenerateSSHKey = useCallback(() => { + if (artifactDef) { + dispatch(gitArtifactActions.resetGenerateSSHKey({ artifactDef })); + } + }, [artifactDef, dispatch]); + + return { + sshKey: fetchSSHKeyState?.value ?? null, + isFetchSSHKeyLoading: fetchSSHKeyState?.loading ?? false, + fetchSSHKeyError: fetchSSHKeyState?.error ?? null, + fetchSSHKey, + resetFetchSSHKey, + isGenerateSSHKeyLoading: generateSSHKeyState?.loading ?? false, + generateSSHKeyError: generateSSHKeyState?.error ?? null, + generateSSHKey, + resetGenerateSSHKey, + }; +} diff --git a/app/client/src/git/hooks/useSettings.ts b/app/client/src/git/hooks/useSettings.ts index d94f9c0e530b..0a8b48aa368c 100644 --- a/app/client/src/git/hooks/useSettings.ts +++ b/app/client/src/git/hooks/useSettings.ts @@ -4,39 +4,37 @@ import { gitArtifactActions } from "git/store/gitArtifactSlice"; import { selectSettingsModalOpen, selectSettingsModalTab, -} from "git/store/selectors/gitSingleArtifactSelectors"; -import type { GitRootState } from "git/store/types"; +} from "git/store/selectors/gitArtifactSelectors"; import { useCallback } from "react"; -import { useDispatch, useSelector } from "react-redux"; +import { useDispatch } from "react-redux"; +import useArtifactSelector from "./useArtifactSelector"; export default function useSettings() { const { artifactDef } = useGitContext(); const dispatch = useDispatch(); - const settingsModalOpen = useSelector((state: GitRootState) => - selectSettingsModalOpen(state, artifactDef), - ); + const settingsModalOpen = useArtifactSelector(selectSettingsModalOpen); - const settingsModalTab = useSelector((state: GitRootState) => - selectSettingsModalTab(state, artifactDef), - ); + const settingsModalTab = useArtifactSelector(selectSettingsModalTab); const toggleSettingsModal = useCallback( ( open: boolean, tab: keyof typeof GitSettingsTab = GitSettingsTab.General, ) => { - dispatch( - gitArtifactActions.toggleSettingsModal({ ...artifactDef, open, tab }), - ); + if (artifactDef) { + dispatch( + gitArtifactActions.toggleSettingsModal({ artifactDef, open, tab }), + ); + } }, [artifactDef, dispatch], ); return { isSettingsModalOpen: settingsModalOpen ?? false, - settingsModalTab: settingsModalTab ?? GitSettingsTab.General, + settingsModalTab: settingsModalTab, toggleSettingsModal, }; } diff --git a/app/client/src/git/hooks/useStatus.ts b/app/client/src/git/hooks/useStatus.ts index 97b09b57498a..37a5584911aa 100644 --- a/app/client/src/git/hooks/useStatus.ts +++ b/app/client/src/git/hooks/useStatus.ts @@ -1,31 +1,33 @@ import { useGitContext } from "git/components/GitContextProvider"; import { gitArtifactActions } from "git/store/gitArtifactSlice"; -import { selectStatusState } from "git/store/selectors/gitSingleArtifactSelectors"; -import type { GitRootState } from "git/store/types"; +import { selectStatusState } from "git/store/selectors/gitArtifactSelectors"; import { useCallback } from "react"; -import { useDispatch, useSelector } from "react-redux"; +import { useDispatch } from "react-redux"; +import useArtifactSelector from "./useArtifactSelector"; export default function useStatus() { - const { artifactDef } = useGitContext(); + const { artifact, artifactDef } = useGitContext(); + const artifactId = artifact?.id; const dispatch = useDispatch(); - const statusState = useSelector((state: GitRootState) => - selectStatusState(state, artifactDef), - ); + const statusState = useArtifactSelector(selectStatusState); const fetchStatus = useCallback(() => { - dispatch( - gitArtifactActions.fetchStatusInit({ - ...artifactDef, - compareRemote: true, - }), - ); - }, [artifactDef, dispatch]); + if (artifactDef && artifactId) { + dispatch( + gitArtifactActions.fetchStatusInit({ + artifactId, + artifactDef, + compareRemote: true, + }), + ); + } + }, [artifactDef, artifactId, dispatch]); return { - status: statusState?.value, + status: statusState?.value ?? null, isFetchStatusLoading: statusState?.loading ?? false, - fetchStatusError: statusState?.error, + fetchStatusError: statusState?.error ?? null, fetchStatus, }; } diff --git a/app/client/src/git/index.ts b/app/client/src/git/index.ts new file mode 100644 index 000000000000..892ca77d7f43 --- /dev/null +++ b/app/client/src/git/index.ts @@ -0,0 +1,39 @@ +// enums +export { GitArtifactType, GitOpsTab } from "./constants/enums"; + +// components +export { default as GitContextProvider } from "./components/GitContextProvider"; +export { default as GitModals } from "./ee/components/GitModals"; +export { default as GitImportModal } from "./components/ImportModal"; +export { default as GitQuickActions } from "./components/QuickActions"; +export { default as GitProtectedBranchCallout } from "./components/ProtectedBranchCallout"; +export { default as GitGlobalProfile } from "./components/GlobalProfile"; +export { default as GitDeployMenuItems } from "./components/DeployMenuItems"; + +// hooks +export { default as useGitCurrentBranch } from "./hooks/useCurrentBranch"; +export { default as useGitProtectedMode } from "./hooks/useProtectedMode"; +export { default as useGitConnected } from "./hooks/useConnected"; +export { default as useGitOps } from "./hooks/useOps"; + +// actions +import { gitGlobalActions } from "./store/gitGlobalSlice"; +export const fetchGitGlobalProfile = gitGlobalActions.fetchGlobalProfileInit; +export const toggleGitImportModal = gitGlobalActions.toggleImportModal; + +import { gitArtifactActions } from "./store/gitArtifactSlice"; +export const gitConnectSuccess = gitArtifactActions.connectSuccess; + +// selectors +export { + selectCurrentBranch as selectGitCurrentBranch, + selectProtectedMode as selectGitProtectedMode, +} from "./store/selectors/gitArtifactSelectors"; + +// types +export type { + GitArtifactDef, + GitArtifactRootReduxState, + GitGlobalReduxState, +} from "./store/types"; +export type { ConnectSuccessPayload as GitConnectSuccessPayload } from "./store/actions/connectActions"; diff --git a/app/client/src/git/requests/connectRequest.types.ts b/app/client/src/git/requests/connectRequest.types.ts index 7e31cf32bf82..d47cc4114b21 100644 --- a/app/client/src/git/requests/connectRequest.types.ts +++ b/app/client/src/git/requests/connectRequest.types.ts @@ -1,4 +1,5 @@ import type { ApiResponse } from "api/types"; +import type { ApplicationPayload } from "entities/Application"; export interface ConnectRequestParams { remoteUrl: string; @@ -9,20 +10,6 @@ export interface ConnectRequestParams { }; } -export interface ConnectResponseData { - id: string; - baseId: string; - gitApplicationMetadata: { - branchName: string; - browserSupportedRemoteUrl: string; - defaultApplicationId: string; - defaultArtifactId: string; - defaultBranchName: string; - isRepoPrivate: boolean; - lastCommitedAt: string; - remoteUrl: string; - repoName: string; - }; -} +export interface ConnectResponseData extends ApplicationPayload {} export type ConnectResponse = ApiResponse<ConnectResponseData>; diff --git a/app/client/src/git/requests/disconnectRequest.types.ts b/app/client/src/git/requests/disconnectRequest.types.ts index 2cbf5969ccca..b1cd5827d951 100644 --- a/app/client/src/git/requests/disconnectRequest.types.ts +++ b/app/client/src/git/requests/disconnectRequest.types.ts @@ -1,7 +1,6 @@ import type { ApiResponse } from "api/types"; +import type { ApplicationPayload } from "entities/Application"; -export interface DisconnectResponseData { - [key: string]: string; -} +export interface DisconnectResponseData extends ApplicationPayload {} export type DisconnectResponse = ApiResponse<DisconnectResponseData>; diff --git a/app/client/src/git/requests/fetchGlobalSSHKeyRequest.ts b/app/client/src/git/requests/fetchGlobalSSHKeyRequest.ts new file mode 100644 index 000000000000..00d900637f42 --- /dev/null +++ b/app/client/src/git/requests/fetchGlobalSSHKeyRequest.ts @@ -0,0 +1,15 @@ +import type { AxiosPromise } from "axios"; +import { GIT_BASE_URL } from "./constants"; +import Api from "api/Api"; +import type { + FetchGlobalSSHKeyRequestParams, + FetchGlobalSSHKeyResponse, +} from "./fetchGlobalSSHKeyRequest.types"; + +export default async function fetchGlobalSSHKeyRequest( + params: FetchGlobalSSHKeyRequestParams, +): AxiosPromise<FetchGlobalSSHKeyResponse> { + const url = `${GIT_BASE_URL}/import/keys?keyType=${params.keyType}`; + + return Api.get(url); +} diff --git a/app/client/src/git/requests/fetchGlobalSSHKeyRequest.types.ts b/app/client/src/git/requests/fetchGlobalSSHKeyRequest.types.ts new file mode 100644 index 000000000000..7b092ceccff2 --- /dev/null +++ b/app/client/src/git/requests/fetchGlobalSSHKeyRequest.types.ts @@ -0,0 +1,15 @@ +import type { ApiResponse } from "api/types"; + +export interface FetchGlobalSSHKeyRequestParams { + keyType: string; +} + +export interface FetchGlobalSSHKeyResponseData { + publicKey: string; + docUrl: string; + isRegeneratedKey: boolean; + regeneratedKey: boolean; +} + +export type FetchGlobalSSHKeyResponse = + ApiResponse<FetchGlobalSSHKeyResponseData>; diff --git a/app/client/src/git/requests/fetchStatusRequest.types.ts b/app/client/src/git/requests/fetchStatusRequest.types.ts index c4400688b794..feb064d3618d 100644 --- a/app/client/src/git/requests/fetchStatusRequest.types.ts +++ b/app/client/src/git/requests/fetchStatusRequest.types.ts @@ -24,6 +24,7 @@ export interface FetchStatusResponseData { modifiedDatasources: number; modifiedJSLibs: number; modifiedJSObjects: number; + modifiedPackages: number; modifiedModuleInstances: number; modifiedModules: number; modifiedPages: number; diff --git a/app/client/src/git/requests/generateSSHKeyRequest.ts b/app/client/src/git/requests/generateSSHKeyRequest.ts index 896426347f30..b0bea4f20ff8 100644 --- a/app/client/src/git/requests/generateSSHKeyRequest.ts +++ b/app/client/src/git/requests/generateSSHKeyRequest.ts @@ -3,16 +3,14 @@ import type { GenerateSSHKeyRequestParams, GenerateSSHKeyResponse, } from "./generateSSHKeyRequest.types"; -import { APPLICATION_BASE_URL, GIT_BASE_URL } from "./constants"; +import { APPLICATION_BASE_URL } from "./constants"; import Api from "api/Api"; export default async function generateSSHKeyRequest( baseApplicationId: string, params: GenerateSSHKeyRequestParams, ): AxiosPromise<GenerateSSHKeyResponse> { - const url = params.isImport - ? `${GIT_BASE_URL}/import/keys?keyType=${params.keyType}` - : `${APPLICATION_BASE_URL}/ssh-keypair/${baseApplicationId}?keyType=${params.keyType}`; + const url = `${APPLICATION_BASE_URL}/ssh-keypair/${baseApplicationId}?keyType=${params.keyType}`; - return params.isImport ? Api.get(url) : Api.post(url); + return Api.post(url); } diff --git a/app/client/src/git/requests/generateSSHKeyRequest.types.ts b/app/client/src/git/requests/generateSSHKeyRequest.types.ts index 45374e42d5b1..fbc4a4c0e959 100644 --- a/app/client/src/git/requests/generateSSHKeyRequest.types.ts +++ b/app/client/src/git/requests/generateSSHKeyRequest.types.ts @@ -2,7 +2,6 @@ import type { ApiResponse } from "api/types"; export interface GenerateSSHKeyRequestParams { keyType: string; - isImport: boolean; } export interface GenerateSSHKeyResponseData { diff --git a/app/client/src/git/requests/gitImportRequest.types.ts b/app/client/src/git/requests/gitImportRequest.types.ts index 9f76b379c9cc..4eb29b11a88b 100644 --- a/app/client/src/git/requests/gitImportRequest.types.ts +++ b/app/client/src/git/requests/gitImportRequest.types.ts @@ -1,4 +1,6 @@ import type { ApiResponse } from "api/types"; +import type { ApplicationResponsePayload } from "ee/api/ApplicationApi"; +import type { Datasource } from "entities/Datasource"; export interface GitImportRequestParams { remoteUrl: string; @@ -10,19 +12,9 @@ export interface GitImportRequestParams { } export interface GitImportResponseData { - id: string; - baseId: string; - gitApplicationMetadata: { - branchName: string; - browserSupportedRemoteUrl: string; - defaultApplicationId: string; - defaultArtifactId: string; - defaultBranchName: string; - isRepoPrivate: boolean; - lastCommitedAt: string; - remoteUrl: string; - repoName: string; - }; + application: ApplicationResponsePayload; + isPartialImport: boolean; + unconfiguredDatasourceList?: Datasource[]; } export type GitImportResponse = ApiResponse<GitImportResponseData>; diff --git a/app/client/src/git/sagas/checkoutBranchSaga.ts b/app/client/src/git/sagas/checkoutBranchSaga.ts index 34e48434626c..7fc454f36bc0 100644 --- a/app/client/src/git/sagas/checkoutBranchSaga.ts +++ b/app/client/src/git/sagas/checkoutBranchSaga.ts @@ -25,8 +25,7 @@ import { captureException } from "@sentry/react"; export default function* checkoutBranchSaga( action: GitArtifactPayloadAction<CheckoutBranchInitPayload>, ) { - const { artifactType, baseArtifactId, branchName } = action.payload; - const basePayload = { artifactType, baseArtifactId }; + const { artifactDef, artifactId, branchName } = action.payload; let response: CheckoutBranchResponse | undefined; try { @@ -34,12 +33,12 @@ export default function* checkoutBranchSaga( branchName, }; - response = yield call(checkoutBranchRequest, baseArtifactId, params); + response = yield call(checkoutBranchRequest, artifactId, params); const isValidResponse: boolean = yield validateResponse(response); if (response && isValidResponse) { - if (artifactType === GitArtifactType.Application) { - yield put(gitArtifactActions.checkoutBranchSuccess(basePayload)); + if (artifactDef.artifactType === GitArtifactType.Application) { + yield put(gitArtifactActions.checkoutBranchSuccess({ artifactDef })); const trimmedBranch = branchName.replace(/^origin\//, ""); const destinationHref = addBranchParam(trimmedBranch); @@ -49,7 +48,7 @@ export default function* checkoutBranchSaga( yield put( gitArtifactActions.toggleBranchPopup({ - ...basePayload, + artifactDef, open: false, }), ); @@ -118,7 +117,7 @@ export default function* checkoutBranchSaga( yield put( gitArtifactActions.checkoutBranchError({ - ...basePayload, + artifactDef, error, }), ); diff --git a/app/client/src/git/sagas/commitSaga.ts b/app/client/src/git/sagas/commitSaga.ts index 159021acc145..7ebcb70b9a71 100644 --- a/app/client/src/git/sagas/commitSaga.ts +++ b/app/client/src/git/sagas/commitSaga.ts @@ -17,8 +17,7 @@ import { validateResponse } from "sagas/ErrorSagas"; export default function* commitSaga( action: GitArtifactPayloadAction<CommitInitPayload>, ) { - const { artifactType, baseArtifactId } = action.payload; - const basePayload = { artifactType, baseArtifactId }; + const { artifactDef, artifactId } = action.payload; let response: CommitResponse | undefined; @@ -28,20 +27,21 @@ export default function* commitSaga( doPush: action.payload.doPush, }; - response = yield call(commitRequest, baseArtifactId, params); + response = yield call(commitRequest, artifactId, params); const isValidResponse: boolean = yield validateResponse(response, false); if (isValidResponse) { - yield put(gitArtifactActions.commitSuccess(basePayload)); + yield put(gitArtifactActions.commitSuccess({ artifactDef })); yield put( gitArtifactActions.fetchStatusInit({ - ...basePayload, + artifactDef, + artifactId, compareRemote: true, }), ); - if (artifactType === GitArtifactType.Application) { + if (artifactDef.artifactType === GitArtifactType.Application) { // ! case for updating lastDeployedAt in application manually? } } @@ -52,13 +52,13 @@ export default function* commitSaga( if (error.code === GitErrorCodes.REPO_LIMIT_REACHED) { yield put( gitArtifactActions.toggleRepoLimitErrorModal({ - ...basePayload, + artifactDef, open: true, }), ); } - yield put(gitArtifactActions.commitError({ ...basePayload, error })); + yield put(gitArtifactActions.commitError({ artifactDef, error })); } else { log.error(e); captureException(e); diff --git a/app/client/src/git/sagas/connectSaga.ts b/app/client/src/git/sagas/connectSaga.ts index b13c2f6c2c2a..b6de0cdea53e 100644 --- a/app/client/src/git/sagas/connectSaga.ts +++ b/app/client/src/git/sagas/connectSaga.ts @@ -8,7 +8,7 @@ import { GitArtifactType, GitErrorCodes } from "../constants/enums"; import type { GitArtifactPayloadAction } from "../store/types"; import type { ConnectInitPayload } from "../store/actions/connectActions"; -import { call, put } from "redux-saga/effects"; +import { call, put, select } from "redux-saga/effects"; // Internal dependencies import { validateResponse } from "sagas/ErrorSagas"; @@ -17,12 +17,12 @@ import history from "utils/history"; import { addBranchParam } from "constants/routes"; import log from "loglevel"; import { captureException } from "@sentry/react"; +import { getCurrentPageId } from "selectors/editorSelectors"; export default function* connectSaga( action: GitArtifactPayloadAction<ConnectInitPayload>, ) { - const { artifactType, baseArtifactId } = action.payload; - const basePayload = { artifactType, baseArtifactId }; + const { artifactDef } = action.payload; let response: ConnectResponse | undefined; @@ -32,34 +32,50 @@ export default function* connectSaga( gitProfile: action.payload.gitProfile, }; - response = yield call(connectRequest, baseArtifactId, params); + response = yield call(connectRequest, artifactDef.baseArtifactId, params); const isValidResponse: boolean = yield validateResponse(response, false); if (response && isValidResponse) { - yield put(gitArtifactActions.connectSuccess(basePayload)); + yield put( + gitArtifactActions.connectSuccess({ + artifactDef, + responseData: response.data, + }), + ); // needs to happen only when artifactType is application - if (artifactType === GitArtifactType.Application) { - const { branchedPageId } = action.payload; + if (artifactDef.artifactType === GitArtifactType.Application) { + const pageId: string = yield select(getCurrentPageId); - if (branchedPageId) { - yield put(fetchPageAction(branchedPageId)); - } + yield put(fetchPageAction(pageId)); + + const branch = response.data?.gitApplicationMetadata?.branchName; + + if (branch) { + const newUrl = addBranchParam(branch); - const branch = response.data.gitApplicationMetadata.branchName; - const newUrl = addBranchParam(branch); + history.replace(newUrl); + } - history.replace(newUrl); // ! case for updating lastDeployedAt in application manually? } yield put( gitArtifactActions.initGitForEditor({ - ...basePayload, + artifactDef, artifact: response.data, }), ); + yield put( + gitArtifactActions.toggleConnectModal({ artifactDef, open: false }), + ); + yield put( + gitArtifactActions.toggleConnectSuccessModal({ + artifactDef, + open: true, + }), + ); } } catch (e) { if (response && response.responseMeta.error) { @@ -68,13 +84,13 @@ export default function* connectSaga( if (GitErrorCodes.REPO_LIMIT_REACHED === error.code) { yield put( gitArtifactActions.toggleRepoLimitErrorModal({ - ...basePayload, + artifactDef, open: true, }), ); } - yield put(gitArtifactActions.connectError({ ...basePayload, error })); + yield put(gitArtifactActions.connectError({ artifactDef, error })); } else { log.error(e); captureException(e); diff --git a/app/client/src/git/sagas/createBranchSaga.ts b/app/client/src/git/sagas/createBranchSaga.ts index 7796f43d74bd..d8aa65418977 100644 --- a/app/client/src/git/sagas/createBranchSaga.ts +++ b/app/client/src/git/sagas/createBranchSaga.ts @@ -16,8 +16,8 @@ import log from "loglevel"; export default function* createBranchSaga( action: GitArtifactPayloadAction<CreateBranchInitPayload>, ) { - const { artifactType, baseArtifactId } = action.payload; - const basePayload = { artifactType, baseArtifactId }; + const { artifactDef, artifactId } = action.payload; + const basePayload = { artifactDef }; let response: CreateBranchResponse | undefined; try { @@ -25,27 +25,29 @@ export default function* createBranchSaga( branchName: action.payload.branchName, }; - response = yield call(createBranchRequest, baseArtifactId, params); + response = yield call(createBranchRequest, artifactId, params); const isValidResponse: boolean = yield validateResponse(response); if (isValidResponse) { yield put(gitArtifactActions.createBranchSuccess(basePayload)); yield put( gitArtifactActions.toggleBranchPopup({ - ...basePayload, + artifactDef, open: false, }), ); yield put( gitArtifactActions.fetchBranchesInit({ - ...basePayload, + artifactDef, + artifactId, pruneBranches: true, }), ); yield put( gitArtifactActions.checkoutBranchInit({ - ...basePayload, + artifactDef, + artifactId, branchName: action.payload.branchName, }), ); @@ -56,7 +58,7 @@ export default function* createBranchSaga( yield put( gitArtifactActions.createBranchError({ - ...basePayload, + artifactDef, error, }), ); diff --git a/app/client/src/git/sagas/deleteBranchSaga.ts b/app/client/src/git/sagas/deleteBranchSaga.ts index 4f6bdde2f7fc..ecf560889f1c 100644 --- a/app/client/src/git/sagas/deleteBranchSaga.ts +++ b/app/client/src/git/sagas/deleteBranchSaga.ts @@ -16,8 +16,7 @@ import { captureException } from "@sentry/react"; export default function* deleteBranchSaga( action: GitArtifactPayloadAction<DeleteBranchInitPayload>, ) { - const { artifactType, baseArtifactId } = action.payload; - const basePayload = { artifactType, baseArtifactId }; + const { artifactDef, artifactId } = action.payload; let response: DeleteBranchResponse | undefined; try { @@ -25,14 +24,19 @@ export default function* deleteBranchSaga( branchName: action.payload.branchName, }; - response = yield call(deleteBranchRequest, baseArtifactId, params); + response = yield call( + deleteBranchRequest, + artifactDef.baseArtifactId, + params, + ); const isValidResponse: boolean = yield validateResponse(response); if (isValidResponse) { - yield put(gitArtifactActions.deleteBranchSuccess(basePayload)); + yield put(gitArtifactActions.deleteBranchSuccess({ artifactDef })); yield put( gitArtifactActions.fetchBranchesInit({ - ...basePayload, + artifactDef, + artifactId, pruneBranches: true, }), ); @@ -41,12 +45,7 @@ export default function* deleteBranchSaga( if (response && response.responseMeta.error) { const { error } = response.responseMeta; - yield put( - gitArtifactActions.deleteBranchError({ - ...basePayload, - error, - }), - ); + yield put(gitArtifactActions.deleteBranchError({ artifactDef, error })); } else { log.error(e); captureException(e); diff --git a/app/client/src/git/sagas/disconnectSaga.ts b/app/client/src/git/sagas/disconnectSaga.ts index 3dc25f1ff079..ef6315c25cd5 100644 --- a/app/client/src/git/sagas/disconnectSaga.ts +++ b/app/client/src/git/sagas/disconnectSaga.ts @@ -12,26 +12,30 @@ import { validateResponse } from "sagas/ErrorSagas"; import history from "utils/history"; export default function* disconnectSaga(action: GitArtifactPayloadAction) { - const { artifactType, baseArtifactId } = action.payload; - const artifactDef = { artifactType, baseArtifactId }; + const { artifactDef } = action.payload; let response: DisconnectResponse | undefined; try { - response = yield call(disconnectRequest, baseArtifactId); + response = yield call(disconnectRequest, artifactDef.baseArtifactId); const isValidResponse: boolean = yield validateResponse(response); if (response && isValidResponse) { - yield put(gitArtifactActions.disconnectSuccess(artifactDef)); + yield put(gitArtifactActions.disconnectSuccess({ artifactDef })); const url = new URL(window.location.href); url.searchParams.delete(GIT_BRANCH_QUERY_KEY); - history.push(url.toString().slice(url.origin.length)); - yield put(gitArtifactActions.closeDisconnectModal(artifactDef)); - // !case: why? - // yield put(importAppViaGitStatusReset()); + history.replace(url.toString().slice(url.origin.length)); + yield put(gitArtifactActions.unmount({ artifactDef })); + yield put( + gitArtifactActions.initGitForEditor({ + artifactDef, + artifact: response.data, + }), + ); + yield put(gitArtifactActions.closeDisconnectModal({ artifactDef })); yield put( gitArtifactActions.toggleOpsModal({ - ...artifactDef, + artifactDef, open: false, tab: GitOpsTab.Deploy, }), @@ -52,7 +56,7 @@ export default function* disconnectSaga(action: GitArtifactPayloadAction) { if (response && response.responseMeta.error) { const { error } = response.responseMeta; - yield put(gitArtifactActions.disconnectError({ ...artifactDef, error })); + yield put(gitArtifactActions.disconnectError({ artifactDef, error })); } else { log.error(e); captureException(e); diff --git a/app/client/src/git/sagas/fetchBranchesSaga.ts b/app/client/src/git/sagas/fetchBranchesSaga.ts index 465310e01a4f..5141db03e34f 100644 --- a/app/client/src/git/sagas/fetchBranchesSaga.ts +++ b/app/client/src/git/sagas/fetchBranchesSaga.ts @@ -14,8 +14,7 @@ import { captureException } from "@sentry/react"; export default function* fetchBranchesSaga( action: GitArtifactPayloadAction<FetchBranchesInitPayload>, ) { - const { artifactType, baseArtifactId } = action.payload; - const basePayload = { artifactType, baseArtifactId }; + const { artifactDef, artifactId } = action.payload; let response: FetchBranchesResponse | undefined; try { @@ -23,13 +22,13 @@ export default function* fetchBranchesSaga( pruneBranches: action.payload.pruneBranches, }; - response = yield call(fetchBranchesRequest, baseArtifactId, params); + response = yield call(fetchBranchesRequest, artifactId, params); const isValidResponse: boolean = yield validateResponse(response, false); if (response && isValidResponse) { yield put( gitArtifactActions.fetchBranchesSuccess({ - ...basePayload, + artifactDef, responseData: response.data, }), ); @@ -40,7 +39,7 @@ export default function* fetchBranchesSaga( yield put( gitArtifactActions.fetchBranchesError({ - ...basePayload, + artifactDef, error, }), ); diff --git a/app/client/src/git/sagas/fetchGlobalProfileSaga.ts b/app/client/src/git/sagas/fetchGlobalProfileSaga.ts index 71e7ca1a9c29..86713acf8787 100644 --- a/app/client/src/git/sagas/fetchGlobalProfileSaga.ts +++ b/app/client/src/git/sagas/fetchGlobalProfileSaga.ts @@ -1,12 +1,12 @@ import { call, put } from "redux-saga/effects"; import fetchGlobalProfileRequest from "../requests/fetchGlobalProfileRequest"; import type { FetchGlobalProfileResponse } from "../requests/fetchGlobalProfileRequest.types"; -import { gitConfigActions } from "../store/gitConfigSlice"; // internal dependencies import { validateResponse } from "sagas/ErrorSagas"; import log from "loglevel"; import { captureException } from "@sentry/react"; +import { gitGlobalActions } from "git/store/gitGlobalSlice"; export default function* fetchGlobalProfileSaga() { let response: FetchGlobalProfileResponse | undefined; @@ -18,7 +18,7 @@ export default function* fetchGlobalProfileSaga() { if (response && isValidResponse) { yield put( - gitConfigActions.fetchGlobalProfileSuccess({ + gitGlobalActions.fetchGlobalProfileSuccess({ responseData: response.data, }), ); @@ -28,7 +28,7 @@ export default function* fetchGlobalProfileSaga() { const { error } = response.responseMeta; yield put( - gitConfigActions.fetchGlobalProfileError({ + gitGlobalActions.fetchGlobalProfileError({ error, }), ); diff --git a/app/client/src/git/sagas/fetchGlobalSSHKeySaga.ts b/app/client/src/git/sagas/fetchGlobalSSHKeySaga.ts new file mode 100644 index 000000000000..e72711961844 --- /dev/null +++ b/app/client/src/git/sagas/fetchGlobalSSHKeySaga.ts @@ -0,0 +1,44 @@ +import { captureException } from "@sentry/react"; +import fetchGlobalSSHKeyRequest from "git/requests/fetchGlobalSSHKeyRequest"; +import type { + GenerateSSHKeyRequestParams, + GenerateSSHKeyResponse, +} from "git/requests/generateSSHKeyRequest.types"; +import type { FetchGlobalSSHKeyInitPayload } from "git/store/actions/fetchGlobalSSHKeyActions"; +import { gitGlobalActions } from "git/store/gitGlobalSlice"; +import type { GitArtifactPayloadAction } from "git/store/types"; +import log from "loglevel"; +import { call, put } from "redux-saga/effects"; +import { validateResponse } from "sagas/ErrorSagas"; + +export function* fetchGlobalSSHKeySaga( + action: GitArtifactPayloadAction<FetchGlobalSSHKeyInitPayload>, +) { + let response: GenerateSSHKeyResponse | undefined; + + try { + const params: GenerateSSHKeyRequestParams = { + keyType: action.payload.keyType, + }; + + response = yield call(fetchGlobalSSHKeyRequest, params); + const isValidResponse: boolean = yield validateResponse(response); + + if (response && isValidResponse) { + yield put( + gitGlobalActions.fetchGlobalSSHKeySuccess({ + responseData: response.data, + }), + ); + } + } catch (e) { + if (response && response.responseMeta.error) { + const { error } = response.responseMeta; + + yield put(gitGlobalActions.fetchGlobalSSHKeyError({ error })); + } else { + log.error(e); + captureException(e); + } + } +} diff --git a/app/client/src/git/sagas/fetchLocalProfileSaga.ts b/app/client/src/git/sagas/fetchLocalProfileSaga.ts index c568129beab9..28f24ef2198d 100644 --- a/app/client/src/git/sagas/fetchLocalProfileSaga.ts +++ b/app/client/src/git/sagas/fetchLocalProfileSaga.ts @@ -10,18 +10,17 @@ import { captureException } from "@sentry/react"; export default function* fetchLocalProfileSaga( action: GitArtifactPayloadAction, ) { - const { artifactType, baseArtifactId } = action.payload; - const basePayload = { artifactType, baseArtifactId }; + const { artifactDef } = action.payload; let response: FetchLocalProfileResponse | undefined; try { - response = yield call(fetchLocalProfileRequest, baseArtifactId); + response = yield call(fetchLocalProfileRequest, artifactDef.baseArtifactId); const isValidResponse: boolean = yield validateResponse(response); if (response && isValidResponse) { yield put( gitArtifactActions.fetchLocalProfileSuccess({ - ...basePayload, + artifactDef, responseData: response.data, }), ); @@ -31,7 +30,7 @@ export default function* fetchLocalProfileSaga( const { error } = response.responseMeta; yield put( - gitArtifactActions.fetchLocalProfileError({ ...basePayload, error }), + gitArtifactActions.fetchLocalProfileError({ artifactDef, error }), ); } else { log.error(e); diff --git a/app/client/src/git/sagas/fetchMergeStatusSaga.ts b/app/client/src/git/sagas/fetchMergeStatusSaga.ts index 684233de206d..024954b017c5 100644 --- a/app/client/src/git/sagas/fetchMergeStatusSaga.ts +++ b/app/client/src/git/sagas/fetchMergeStatusSaga.ts @@ -14,8 +14,7 @@ import { validateResponse } from "sagas/ErrorSagas"; export default function* fetchMergeStatusSaga( action: GitArtifactPayloadAction<FetchMergeStatusInitPayload>, ) { - const { artifactId, artifactType, baseArtifactId } = action.payload; - const basePayload = { artifactType, baseArtifactId }; + const { artifactDef, artifactId } = action.payload; let response: FetchMergeStatusResponse | undefined; try { @@ -30,7 +29,7 @@ export default function* fetchMergeStatusSaga( if (response && isValidResponse) { yield put( gitArtifactActions.fetchMergeStatusSuccess({ - ...basePayload, + artifactDef, responseData: response.data, }), ); @@ -40,10 +39,7 @@ export default function* fetchMergeStatusSaga( const { error } = response.responseMeta; yield put( - gitArtifactActions.fetchMergeStatusError({ - ...basePayload, - error, - }), + gitArtifactActions.fetchMergeStatusError({ artifactDef, error }), ); } else { log.error(e); diff --git a/app/client/src/git/sagas/fetchMetadataSaga.ts b/app/client/src/git/sagas/fetchMetadataSaga.ts index 3e2029b6c6b8..9f8285847ee7 100644 --- a/app/client/src/git/sagas/fetchMetadataSaga.ts +++ b/app/client/src/git/sagas/fetchMetadataSaga.ts @@ -8,18 +8,17 @@ import { call, put } from "redux-saga/effects"; import { validateResponse } from "sagas/ErrorSagas"; export default function* fetchMetadataSaga(action: GitArtifactPayloadAction) { - const { artifactType, baseArtifactId } = action.payload; - const basePayload = { artifactType, baseArtifactId }; + const { artifactDef } = action.payload; let response: FetchMetadataResponse | undefined; try { - response = yield call(fetchMetadataRequest, baseArtifactId); + response = yield call(fetchMetadataRequest, artifactDef.baseArtifactId); const isValidResponse: boolean = yield validateResponse(response, false); if (response && isValidResponse) { yield put( gitArtifactActions.fetchMetadataSuccess({ - ...basePayload, + artifactDef, responseData: response.data, }), ); @@ -30,7 +29,7 @@ export default function* fetchMetadataSaga(action: GitArtifactPayloadAction) { yield put( gitArtifactActions.fetchMetadataError({ - ...basePayload, + artifactDef, error, }), ); diff --git a/app/client/src/git/sagas/fetchProtectedBranchesSaga.ts b/app/client/src/git/sagas/fetchProtectedBranchesSaga.ts index 9c81123ea26f..62f36f8ce93c 100644 --- a/app/client/src/git/sagas/fetchProtectedBranchesSaga.ts +++ b/app/client/src/git/sagas/fetchProtectedBranchesSaga.ts @@ -10,19 +10,21 @@ import { validateResponse } from "sagas/ErrorSagas"; export default function* fetchProtectedBranchesSaga( action: GitArtifactPayloadAction, ) { - const { artifactType, baseArtifactId } = action.payload; - const basePayload = { artifactType, baseArtifactId }; + const { artifactDef } = action.payload; let response: FetchProtectedBranchesResponse | undefined; try { - response = yield call(fetchProtectedBranchesRequest, baseArtifactId); + response = yield call( + fetchProtectedBranchesRequest, + artifactDef.baseArtifactId, + ); const isValidResponse: boolean = yield validateResponse(response); if (response && isValidResponse) { yield put( gitArtifactActions.fetchProtectedBranchesSuccess({ - ...basePayload, + artifactDef, responseData: response.data, }), ); @@ -33,7 +35,7 @@ export default function* fetchProtectedBranchesSaga( yield put( gitArtifactActions.fetchProtectedBranchesError({ - ...basePayload, + artifactDef, error, }), ); diff --git a/app/client/src/git/sagas/fetchSSHKeySaga.ts b/app/client/src/git/sagas/fetchSSHKeySaga.ts index 02f797edae66..16736e92f5d1 100644 --- a/app/client/src/git/sagas/fetchSSHKeySaga.ts +++ b/app/client/src/git/sagas/fetchSSHKeySaga.ts @@ -8,18 +8,17 @@ import { call, put } from "redux-saga/effects"; import { validateResponse } from "sagas/ErrorSagas"; export function* fetchSSHKeySaga(action: GitArtifactPayloadAction) { - const { artifactType, baseArtifactId } = action.payload; - const artifactDef = { artifactType, baseArtifactId }; + const { artifactDef } = action.payload; let response: FetchSSHKeyResponse | undefined; try { - response = yield call(fetchSSHKeyRequest, baseArtifactId); + response = yield call(fetchSSHKeyRequest, artifactDef.baseArtifactId); const isValidResponse: boolean = yield validateResponse(response, false); if (response && isValidResponse) { yield put( gitArtifactActions.fetchSSHKeySuccess({ - ...artifactDef, + artifactDef, responseData: response.data, }), ); @@ -28,7 +27,7 @@ export function* fetchSSHKeySaga(action: GitArtifactPayloadAction) { if (response && response.responseMeta.error) { const { error } = response.responseMeta; - yield put(gitArtifactActions.fetchSSHKeyError({ ...artifactDef, error })); + yield put(gitArtifactActions.fetchSSHKeyError({ artifactDef, error })); } else { log.error(e); captureException(e); diff --git a/app/client/src/git/sagas/fetchStatusSaga.ts b/app/client/src/git/sagas/fetchStatusSaga.ts index 4c714a22c0da..733f18cce776 100644 --- a/app/client/src/git/sagas/fetchStatusSaga.ts +++ b/app/client/src/git/sagas/fetchStatusSaga.ts @@ -11,18 +11,17 @@ import { validateResponse } from "sagas/ErrorSagas"; export default function* fetchStatusSaga( action: GitArtifactPayloadAction<FetchStatusInitPayload>, ) { - const { artifactType, baseArtifactId } = action.payload; - const basePayload = { artifactType, baseArtifactId }; + const { artifactDef, artifactId } = action.payload; let response: FetchStatusResponse | undefined; try { - response = yield call(fetchStatusRequest, baseArtifactId); + response = yield call(fetchStatusRequest, artifactId); const isValidResponse: boolean = yield validateResponse(response); if (response && isValidResponse) { yield put( gitArtifactActions.fetchStatusSuccess({ - ...basePayload, + artifactDef, responseData: response.data, }), ); @@ -33,7 +32,7 @@ export default function* fetchStatusSaga( yield put( gitArtifactActions.fetchStatusError({ - ...basePayload, + artifactDef, error, }), ); diff --git a/app/client/src/git/sagas/generateSSHKeySaga.ts b/app/client/src/git/sagas/generateSSHKeySaga.ts index 09773f9dc0d4..afbccf24b2e6 100644 --- a/app/client/src/git/sagas/generateSSHKeySaga.ts +++ b/app/client/src/git/sagas/generateSSHKeySaga.ts @@ -15,23 +15,25 @@ import { validateResponse } from "sagas/ErrorSagas"; export function* generateSSHKeySaga( action: GitArtifactPayloadAction<GenerateSSHKeyInitPayload>, ) { - const { artifactType, baseArtifactId } = action.payload; - const artifactDef = { artifactType, baseArtifactId }; + const { artifactDef } = action.payload; let response: GenerateSSHKeyResponse | undefined; try { const params: GenerateSSHKeyRequestParams = { keyType: action.payload.keyType, - isImport: action.payload.isImport, }; - response = yield call(generateSSHKeyRequest, baseArtifactId, params); + response = yield call( + generateSSHKeyRequest, + artifactDef.baseArtifactId, + params, + ); const isValidResponse: boolean = yield validateResponse(response); if (response && isValidResponse) { yield put( gitArtifactActions.generateSSHKeySuccess({ - ...artifactDef, + artifactDef, responseData: response.data, }), ); @@ -43,15 +45,13 @@ export function* generateSSHKeySaga( if (GitErrorCodes.REPO_LIMIT_REACHED === error.code) { yield put( gitArtifactActions.toggleRepoLimitErrorModal({ - ...artifactDef, + artifactDef, open: true, }), ); } - yield put( - gitArtifactActions.generateSSHKeyError({ ...artifactDef, error }), - ); + yield put(gitArtifactActions.generateSSHKeyError({ artifactDef, error })); } else { log.error(e); captureException(e); diff --git a/app/client/src/git/sagas/gitImportSaga.ts b/app/client/src/git/sagas/gitImportSaga.ts new file mode 100644 index 000000000000..ecf3d718ae08 --- /dev/null +++ b/app/client/src/git/sagas/gitImportSaga.ts @@ -0,0 +1,92 @@ +import log from "loglevel"; +import { call, put, select } from "redux-saga/effects"; +import { validateResponse } from "sagas/ErrorSagas"; +import history from "utils/history"; +import { toast } from "@appsmith/ads"; +import type { PayloadAction } from "@reduxjs/toolkit"; +import { captureException } from "@sentry/react"; +import gitImportRequest from "git/requests/gitImportRequest"; +import type { GitImportResponse } from "git/requests/gitImportRequest.types"; +import type { GitImportInitPayload } from "git/store/actions/gitImportActions"; +import { gitGlobalActions } from "git/store/gitGlobalSlice"; +import { createMessage, IMPORT_APP_SUCCESSFUL } from "ee/constants/messages"; +import { builderURL } from "ee/RouteBuilder"; +import { getWorkspaceIdForImport } from "ee/selectors/applicationSelectors"; +import { showReconnectDatasourceModal } from "ee/actions/applicationActions"; +import type { Workspace } from "ee/constants/workspaceConstants"; +import { getFetchedWorkspaces } from "ee/selectors/workspaceSelectors"; + +export default function* gitImportSaga( + action: PayloadAction<GitImportInitPayload>, +) { + const { ...params } = action.payload; + const workspaceId: string = yield select(getWorkspaceIdForImport); + + let response: GitImportResponse | undefined; + + try { + response = yield call(gitImportRequest, workspaceId, params); + const isValidResponse: boolean = yield validateResponse(response); + + if (response && isValidResponse) { + const allWorkspaces: Workspace[] = yield select(getFetchedWorkspaces); + const currentWorkspace = allWorkspaces.filter( + (el: Workspace) => el.id === workspaceId, + ); + + if (currentWorkspace.length > 0) { + const { application, isPartialImport, unconfiguredDatasourceList } = + response.data; + + yield put(gitGlobalActions.gitImportSuccess()); + yield put(gitGlobalActions.toggleImportModal({ open: false })); + + // there is configuration-missing datasources + if (isPartialImport) { + yield put( + showReconnectDatasourceModal({ + application: application, + unConfiguredDatasourceList: unconfiguredDatasourceList ?? [], + workspaceId, + }), + ); + } else { + let basePageId = ""; + + if (application.pages && application.pages.length > 0) { + const defaultPage = application.pages.find( + (eachPage) => !!eachPage.isDefault, + ); + + basePageId = defaultPage ? defaultPage.baseId : ""; + } + + const pageURL = builderURL({ + basePageId, + }); + + history.push(pageURL); + toast.show(createMessage(IMPORT_APP_SUCCESSFUL), { + kind: "success", + }); + } + } + } + } catch (e) { + // const isRepoLimitReachedError: boolean = yield call( + // handleRepoLimitReachedError, + // response, + // ); + + // if (isRepoLimitReachedError) return; + + if (response?.responseMeta?.error) { + yield put( + gitGlobalActions.gitImportError({ error: response.responseMeta.error }), + ); + } else { + log.error(e); + captureException(e); + } + } +} diff --git a/app/client/src/git/sagas/index.ts b/app/client/src/git/sagas/index.ts index 13e19bd4c9f8..61c0a0747330 100644 --- a/app/client/src/git/sagas/index.ts +++ b/app/client/src/git/sagas/index.ts @@ -8,7 +8,6 @@ import { import type { TakeableChannel } from "redux-saga"; import type { PayloadAction } from "@reduxjs/toolkit"; import { objectKeys } from "@appsmith/utils"; -import { gitConfigActions } from "../store/gitConfigSlice"; import { gitArtifactActions } from "../store/gitArtifactSlice"; import connectSaga from "./connectSaga"; import commitSaga from "./commitSaga"; @@ -37,6 +36,9 @@ import { blockingActionSagas as blockingActionSagasExtended, nonBlockingActionSagas as nonBlockingActionSagasExtended, } from "git/ee/sagas"; +import { gitGlobalActions } from "git/store/gitGlobalSlice"; +import { fetchGlobalSSHKeySaga } from "./fetchGlobalSSHKeySaga"; +import gitImportSaga from "./gitImportSaga"; const blockingActionSagas: Record< string, @@ -50,6 +52,9 @@ const blockingActionSagas: Record< [gitArtifactActions.connectInit.type]: connectSaga, [gitArtifactActions.disconnectInit.type]: disconnectSaga, + // import + [gitGlobalActions.gitImportInit.type]: gitImportSaga, + // ops [gitArtifactActions.commitInit.type]: commitSaga, [gitArtifactActions.fetchStatusInit.type]: fetchStatusSaga, @@ -65,8 +70,8 @@ const blockingActionSagas: Record< // user profiles [gitArtifactActions.fetchLocalProfileInit.type]: fetchLocalProfileSaga, [gitArtifactActions.updateLocalProfileInit.type]: updateLocalProfileSaga, - [gitConfigActions.fetchGlobalProfileInit.type]: fetchGlobalProfileSaga, - [gitConfigActions.updateGlobalProfileInit.type]: updateGlobalProfileSaga, + [gitGlobalActions.fetchGlobalProfileInit.type]: fetchGlobalProfileSaga, + [gitGlobalActions.updateGlobalProfileInit.type]: updateGlobalProfileSaga, // protected branches [gitArtifactActions.fetchProtectedBranchesInit.type]: @@ -93,6 +98,7 @@ const nonBlockingActionSagas: Record< // ssh key [gitArtifactActions.fetchSSHKeyInit.type]: fetchSSHKeySaga, [gitArtifactActions.generateSSHKeyInit.type]: generateSSHKeySaga, + [gitGlobalActions.fetchGlobalSSHKeyInit.type]: fetchGlobalSSHKeySaga, // EE ...nonBlockingActionSagasExtended, diff --git a/app/client/src/git/sagas/initGitSaga.ts b/app/client/src/git/sagas/initGitSaga.ts index aa50efce17b1..b880b1854c41 100644 --- a/app/client/src/git/sagas/initGitSaga.ts +++ b/app/client/src/git/sagas/initGitSaga.ts @@ -7,24 +7,25 @@ import { put, take } from "redux-saga/effects"; export default function* initGitForEditorSaga( action: GitArtifactPayloadAction<InitGitForEditorPayload>, ) { - const { artifact, artifactType, baseArtifactId } = action.payload; - const basePayload = { artifactType, baseArtifactId }; + const { artifact, artifactDef } = action.payload; + const artifactId = artifact?.id; - yield put(gitArtifactActions.mount(basePayload)); + yield put(gitArtifactActions.mount({ artifactDef })); - if (artifactType === GitArtifactType.Application) { - if (!!artifact.gitApplicationMetadata?.remoteUrl) { - yield put(gitArtifactActions.fetchMetadataInit(basePayload)); + if (artifactId && artifactDef.artifactType === GitArtifactType.Application) { + if (!!artifact?.gitApplicationMetadata?.remoteUrl) { + yield put(gitArtifactActions.fetchMetadataInit({ artifactDef })); yield take(gitArtifactActions.fetchMetadataSuccess.type); yield put( - gitArtifactActions.triggerAutocommitInit({ - ...basePayload, - artifactId: artifact.id, - }), + gitArtifactActions.triggerAutocommitInit({ artifactDef, artifactId }), + ); + yield put( + gitArtifactActions.fetchBranchesInit({ artifactDef, artifactId }), + ); + yield put(gitArtifactActions.fetchProtectedBranchesInit({ artifactDef })); + yield put( + gitArtifactActions.fetchStatusInit({ artifactDef, artifactId }), ); - yield put(gitArtifactActions.fetchBranchesInit(basePayload)); - yield put(gitArtifactActions.fetchProtectedBranchesInit(basePayload)); - yield put(gitArtifactActions.fetchStatusInit(basePayload)); } } } diff --git a/app/client/src/git/sagas/pullSaga.ts b/app/client/src/git/sagas/pullSaga.ts index eafb4a5c098b..07347326e3e0 100644 --- a/app/client/src/git/sagas/pullSaga.ts +++ b/app/client/src/git/sagas/pullSaga.ts @@ -4,7 +4,7 @@ import type { PullResponse } from "git/requests/pullRequest.types"; import type { PullInitPayload } from "git/store/actions/pullActions"; import { gitArtifactActions } from "git/store/gitArtifactSlice"; import type { GitArtifactPayloadAction } from "git/store/types"; -import { selectCurrentBranch } from "git/store/selectors/gitSingleArtifactSelectors"; +import { selectCurrentBranch } from "git/store/selectors/gitArtifactSelectors"; // internal dependencies import { validateResponse } from "sagas/ErrorSagas"; @@ -17,8 +17,7 @@ import { captureException } from "@sentry/react"; export default function* pullSaga( action: GitArtifactPayloadAction<PullInitPayload>, ) { - const { artifactId, artifactType, baseArtifactId } = action.payload; - const basePayload = { artifactType, baseArtifactId }; + const { artifactDef, artifactId } = action.payload; let response: PullResponse | undefined; try { @@ -26,12 +25,12 @@ export default function* pullSaga( const isValidResponse: boolean = yield validateResponse(response); if (response && isValidResponse) { - yield put(gitArtifactActions.pullSuccess(basePayload)); + yield put(gitArtifactActions.pullSuccess({ artifactDef })); const currentBasePageId: string = yield select(getCurrentBasePageId); const currentBranch: string = yield select( selectCurrentBranch, - basePayload, + artifactDef, ); yield put( @@ -51,7 +50,7 @@ export default function* pullSaga( // yield put(setIsGitErrorPopupVisible({ isVisible: true })); // } - yield put(gitArtifactActions.pullError({ ...basePayload, error })); + yield put(gitArtifactActions.pullError({ artifactDef, error })); } else { log.error(e); captureException(e); diff --git a/app/client/src/git/sagas/toggleAutocommitSaga.ts b/app/client/src/git/sagas/toggleAutocommitSaga.ts index cf8b0e923c67..4f97d0289543 100644 --- a/app/client/src/git/sagas/toggleAutocommitSaga.ts +++ b/app/client/src/git/sagas/toggleAutocommitSaga.ts @@ -10,24 +10,23 @@ import { validateResponse } from "sagas/ErrorSagas"; export default function* toggleAutocommitSaga( action: GitArtifactPayloadAction, ) { - const { artifactType, baseArtifactId } = action.payload; - const artifactDef = { artifactType, baseArtifactId }; + const { artifactDef } = action.payload; let response: ToggleAutocommitResponse | undefined; try { - response = yield call(toggleAutocommitRequest, baseArtifactId); + response = yield call(toggleAutocommitRequest, artifactDef.baseArtifactId); const isValidResponse: boolean = yield validateResponse(response); if (isValidResponse) { - yield put(gitArtifactActions.toggleAutocommitSuccess(artifactDef)); - yield put(gitArtifactActions.fetchMetadataInit(artifactDef)); + yield put(gitArtifactActions.toggleAutocommitSuccess({ artifactDef })); + yield put(gitArtifactActions.fetchMetadataInit({ artifactDef })); } } catch (e) { if (response && response.responseMeta.error) { const { error } = response.responseMeta; yield put( - gitArtifactActions.toggleAutocommitError({ ...artifactDef, error }), + gitArtifactActions.toggleAutocommitError({ artifactDef, error }), ); } else { log.error(e); diff --git a/app/client/src/git/sagas/triggerAutocommitSaga.ts b/app/client/src/git/sagas/triggerAutocommitSaga.ts index d0b316f594ec..6725fb0d59f9 100644 --- a/app/client/src/git/sagas/triggerAutocommitSaga.ts +++ b/app/client/src/git/sagas/triggerAutocommitSaga.ts @@ -1,8 +1,5 @@ import { triggerAutocommitSuccessAction } from "actions/gitSyncActions"; -import { - AutocommitStatusState, - type GitArtifactType, -} from "git/constants/enums"; +import { AutocommitStatusState } from "git/constants/enums"; import fetchAutocommitProgressRequest from "git/requests/fetchAutocommitProgressRequest"; import type { FetchAutocommitProgressResponse, @@ -15,8 +12,8 @@ import type { } from "git/requests/triggerAutocommitRequest.types"; import type { TriggerAutocommitInitPayload } from "git/store/actions/triggerAutocommitActions"; import { gitArtifactActions } from "git/store/gitArtifactSlice"; -import { selectAutocommitEnabled } from "git/store/selectors/gitSingleArtifactSelectors"; -import type { GitArtifactPayloadAction } from "git/store/types"; +import { selectAutocommitEnabled } from "git/store/selectors/gitArtifactSelectors"; +import type { GitArtifactDef, GitArtifactPayloadAction } from "git/store/types"; import { call, cancel, @@ -39,8 +36,7 @@ const AUTOCOMMIT_WHITELISTED_STATES = [ ]; interface PollAutocommitProgressParams { - artifactType: keyof typeof GitArtifactType; - baseArtifactId: string; + artifactDef: GitArtifactDef; artifactId: string; } @@ -57,8 +53,7 @@ function isAutocommitHappening( } function* pollAutocommitProgressSaga(params: PollAutocommitProgressParams) { - const { artifactId, artifactType, baseArtifactId } = params; - const basePayload = { artifactType, baseArtifactId }; + const { artifactDef, artifactId } = params; let triggerResponse: TriggerAutocommitResponse | undefined; try { @@ -66,14 +61,14 @@ function* pollAutocommitProgressSaga(params: PollAutocommitProgressParams) { const isValidResponse: boolean = yield validateResponse(triggerResponse); if (triggerResponse && isValidResponse) { - yield put(gitArtifactActions.triggerAutocommitSuccess(basePayload)); + yield put(gitArtifactActions.triggerAutocommitSuccess({ artifactDef })); } } catch (e) { if (triggerResponse && triggerResponse.responseMeta.error) { const { error } = triggerResponse.responseMeta; yield put( - gitArtifactActions.triggerAutocommitError({ ...basePayload, error }), + gitArtifactActions.triggerAutocommitError({ artifactDef, error }), ); } else { log.error(e); @@ -85,39 +80,47 @@ function* pollAutocommitProgressSaga(params: PollAutocommitProgressParams) { try { if (isAutocommitHappening(triggerResponse?.data)) { - yield put(gitArtifactActions.pollAutocommitProgressStart(basePayload)); + yield put( + gitArtifactActions.pollAutocommitProgressStart({ artifactDef }), + ); while (true) { - yield put(gitArtifactActions.fetchAutocommitProgressInit(basePayload)); + yield put( + gitArtifactActions.fetchAutocommitProgressInit({ artifactDef }), + ); progressResponse = yield call( fetchAutocommitProgressRequest, - baseArtifactId, + artifactDef.baseArtifactId, ); const isValidResponse: boolean = yield validateResponse(progressResponse); if (isValidResponse && !isAutocommitHappening(progressResponse?.data)) { - yield put(gitArtifactActions.pollAutocommitProgressStop(basePayload)); + yield put( + gitArtifactActions.pollAutocommitProgressStop({ artifactDef }), + ); } if (!isValidResponse) { - yield put(gitArtifactActions.pollAutocommitProgressStop(basePayload)); + yield put( + gitArtifactActions.pollAutocommitProgressStop({ artifactDef }), + ); } yield delay(AUTOCOMMIT_POLL_DELAY); } } else { - yield put(gitArtifactActions.pollAutocommitProgressStop(basePayload)); + yield put(gitArtifactActions.pollAutocommitProgressStop({ artifactDef })); } } catch (e) { - yield put(gitArtifactActions.pollAutocommitProgressStop(basePayload)); + yield put(gitArtifactActions.pollAutocommitProgressStop({ artifactDef })); if (progressResponse && progressResponse.responseMeta.error) { const { error } = progressResponse.responseMeta; yield put( gitArtifactActions.fetchAutocommitProgressError({ - ...basePayload, + artifactDef, error, }), ); @@ -131,15 +134,14 @@ function* pollAutocommitProgressSaga(params: PollAutocommitProgressParams) { export default function* triggerAutocommitSaga( action: GitArtifactPayloadAction<TriggerAutocommitInitPayload>, ) { - const { artifactId, artifactType, baseArtifactId } = action.payload; - const basePayload = { artifactType, baseArtifactId }; + const { artifactDef, artifactId } = action.payload; const isAutocommitEnabled: boolean = yield select( selectAutocommitEnabled, - basePayload, + artifactDef, ); if (isAutocommitEnabled) { - const params = { artifactType, baseArtifactId, artifactId }; + const params = { artifactDef, artifactId }; const pollTask: Task = yield fork(pollAutocommitProgressSaga, params); yield take(gitArtifactActions.pollAutocommitProgressStop.type); diff --git a/app/client/src/git/sagas/updateGlobalProfileSaga.ts b/app/client/src/git/sagas/updateGlobalProfileSaga.ts index 2ce98fe47fb4..d7466b1ed007 100644 --- a/app/client/src/git/sagas/updateGlobalProfileSaga.ts +++ b/app/client/src/git/sagas/updateGlobalProfileSaga.ts @@ -6,12 +6,12 @@ import type { UpdateGlobalProfileRequestParams, UpdateGlobalProfileResponse, } from "../requests/updateGlobalProfileRequest.types"; -import { gitConfigActions } from "../store/gitConfigSlice"; // internal dependencies import { validateResponse } from "sagas/ErrorSagas"; import log from "loglevel"; import { captureException } from "@sentry/react"; +import { gitGlobalActions } from "git/store/gitGlobalSlice"; export default function* updateGlobalProfileSaga( action: PayloadAction<UpdateGlobalProfileInitPayload>, @@ -29,14 +29,14 @@ export default function* updateGlobalProfileSaga( const isValidResponse: boolean = yield validateResponse(response, true); if (response && isValidResponse) { - yield put(gitConfigActions.updateGlobalProfileSuccess()); - yield put(gitConfigActions.fetchGlobalProfileInit()); + yield put(gitGlobalActions.updateGlobalProfileSuccess()); + yield put(gitGlobalActions.fetchGlobalProfileInit()); } } catch (e) { if (response && response.responseMeta.error) { const { error } = response.responseMeta; - yield put(gitConfigActions.updateGlobalProfileError({ error })); + yield put(gitGlobalActions.updateGlobalProfileError({ error })); } else { log.error(e); captureException(e); diff --git a/app/client/src/git/sagas/updateLocalProfileSaga.ts b/app/client/src/git/sagas/updateLocalProfileSaga.ts index 74579562b058..3b7253a391fe 100644 --- a/app/client/src/git/sagas/updateLocalProfileSaga.ts +++ b/app/client/src/git/sagas/updateLocalProfileSaga.ts @@ -14,8 +14,7 @@ import { captureException } from "@sentry/react"; export default function* updateLocalProfileSaga( action: GitArtifactPayloadAction<UpdateLocalProfileInitPayload>, ) { - const { artifactType, baseArtifactId } = action.payload; - const basePayload = { artifactType, baseArtifactId }; + const { artifactDef } = action.payload; let response: UpdateLocalProfileResponse | undefined; try { @@ -25,20 +24,24 @@ export default function* updateLocalProfileSaga( useGlobalProfile: action.payload.useGlobalProfile, }; - response = yield call(updateLocalProfileRequest, baseArtifactId, params); + response = yield call( + updateLocalProfileRequest, + artifactDef.baseArtifactId, + params, + ); const isValidResponse: boolean = yield validateResponse(response); if (isValidResponse) { - yield put(gitArtifactActions.updateLocalProfileSuccess(basePayload)); - yield put(gitArtifactActions.fetchLocalProfileInit(basePayload)); + yield put(gitArtifactActions.updateLocalProfileSuccess({ artifactDef })); + yield put(gitArtifactActions.fetchLocalProfileInit({ artifactDef })); } } catch (e) { if (response && response.responseMeta.error) { const { error } = response.responseMeta; yield put( - gitArtifactActions.updateLocalProfileError({ ...basePayload, error }), + gitArtifactActions.updateLocalProfileError({ artifactDef, error }), ); } else { log.error(e); diff --git a/app/client/src/git/sagas/updateProtectedBranchesSaga.ts b/app/client/src/git/sagas/updateProtectedBranchesSaga.ts index 3f7bd121270e..f24b20ee9290 100644 --- a/app/client/src/git/sagas/updateProtectedBranchesSaga.ts +++ b/app/client/src/git/sagas/updateProtectedBranchesSaga.ts @@ -14,8 +14,7 @@ import { validateResponse } from "sagas/ErrorSagas"; export default function* updateProtectedBranchesSaga( action: GitArtifactPayloadAction<UpdateProtectedBranchesInitPayload>, ) { - const { artifactType, baseArtifactId } = action.payload; - const artifactDef = { artifactType, baseArtifactId }; + const { artifactDef } = action.payload; let response: UpdateProtectedBranchesResponse | undefined; try { @@ -25,14 +24,16 @@ export default function* updateProtectedBranchesSaga( response = yield call( updateProtectedBranchesRequest, - baseArtifactId, + artifactDef.baseArtifactId, params, ); const isValidResponse: boolean = yield validateResponse(response); if (response && isValidResponse) { - yield put(gitArtifactActions.updateProtectedBranchesSuccess(artifactDef)); - yield put(gitArtifactActions.fetchProtectedBranchesInit(artifactDef)); + yield put( + gitArtifactActions.updateProtectedBranchesSuccess({ artifactDef }), + ); + yield put(gitArtifactActions.fetchProtectedBranchesInit({ artifactDef })); } } catch (e) { if (response && response.responseMeta.error) { @@ -40,7 +41,7 @@ export default function* updateProtectedBranchesSaga( yield put( gitArtifactActions.updateProtectedBranchesError({ - ...artifactDef, + artifactDef, error, }), ); diff --git a/app/client/src/git/store/actions/checkoutBranchActions.ts b/app/client/src/git/store/actions/checkoutBranchActions.ts index c771d1887e34..e9451a614d7f 100644 --- a/app/client/src/git/store/actions/checkoutBranchActions.ts +++ b/app/client/src/git/store/actions/checkoutBranchActions.ts @@ -1,12 +1,13 @@ -import { createSingleArtifactAction } from "../helpers/createSingleArtifactAction"; +import { createArtifactAction } from "../helpers/createArtifactAction"; import type { GitAsyncErrorPayload } from "../types"; import type { CheckoutBranchRequestParams } from "git/requests/checkoutBranchRequest.types"; -export interface CheckoutBranchInitPayload - extends CheckoutBranchRequestParams {} +export interface CheckoutBranchInitPayload extends CheckoutBranchRequestParams { + artifactId: string; +} export const checkoutBranchInitAction = - createSingleArtifactAction<CheckoutBranchInitPayload>((state, action) => { + createArtifactAction<CheckoutBranchInitPayload>((state, action) => { state.apiResponses.checkoutBranch.loading = true; state.apiResponses.checkoutBranch.error = null; state.ui.checkoutDestBranch = action.payload.branchName; @@ -14,18 +15,16 @@ export const checkoutBranchInitAction = return state; }); -export const checkoutBranchSuccessAction = createSingleArtifactAction( - (state) => { - state.apiResponses.checkoutBranch.loading = false; - state.apiResponses.checkoutBranch.error = null; - state.ui.checkoutDestBranch = null; +export const checkoutBranchSuccessAction = createArtifactAction((state) => { + state.apiResponses.checkoutBranch.loading = false; + state.apiResponses.checkoutBranch.error = null; + state.ui.checkoutDestBranch = null; - return state; - }, -); + return state; +}); export const checkoutBranchErrorAction = - createSingleArtifactAction<GitAsyncErrorPayload>((state, action) => { + createArtifactAction<GitAsyncErrorPayload>((state, action) => { const { error } = action.payload; state.apiResponses.checkoutBranch.loading = false; diff --git a/app/client/src/git/store/actions/commitActions.ts b/app/client/src/git/store/actions/commitActions.ts index 9ebb8d37db60..876463e803a9 100644 --- a/app/client/src/git/store/actions/commitActions.ts +++ b/app/client/src/git/store/actions/commitActions.ts @@ -1,10 +1,12 @@ -import { createSingleArtifactAction } from "../helpers/createSingleArtifactAction"; +import { createArtifactAction } from "../helpers/createArtifactAction"; import type { GitAsyncErrorPayload } from "../types"; import type { CommitRequestParams } from "git/requests/commitRequest.types"; -export interface CommitInitPayload extends CommitRequestParams {} +export interface CommitInitPayload extends CommitRequestParams { + artifactId: string; +} -export const commitInitAction = createSingleArtifactAction<CommitInitPayload>( +export const commitInitAction = createArtifactAction<CommitInitPayload>( (state) => { state.apiResponses.commit.loading = true; state.apiResponses.commit.error = null; @@ -13,23 +15,24 @@ export const commitInitAction = createSingleArtifactAction<CommitInitPayload>( }, ); -export const commitSuccessAction = createSingleArtifactAction((state) => { +export const commitSuccessAction = createArtifactAction((state) => { state.apiResponses.commit.loading = false; return state; }); -export const commitErrorAction = - createSingleArtifactAction<GitAsyncErrorPayload>((state, action) => { +export const commitErrorAction = createArtifactAction<GitAsyncErrorPayload>( + (state, action) => { const { error } = action.payload; state.apiResponses.commit.loading = false; state.apiResponses.commit.error = error; return state; - }); + }, +); -export const clearCommitErrorAction = createSingleArtifactAction((state) => { +export const clearCommitErrorAction = createArtifactAction((state) => { state.apiResponses.commit.error = null; return state; diff --git a/app/client/src/git/store/actions/connectActions.ts b/app/client/src/git/store/actions/connectActions.ts index 7fed98500000..9e5e2bcf10b1 100644 --- a/app/client/src/git/store/actions/connectActions.ts +++ b/app/client/src/git/store/actions/connectActions.ts @@ -1,12 +1,13 @@ -import { createSingleArtifactAction } from "../helpers/createSingleArtifactAction"; -import type { GitAsyncErrorPayload } from "../types"; -import type { ConnectRequestParams } from "git/requests/connectRequest.types"; +import { createArtifactAction } from "../helpers/createArtifactAction"; +import type { GitAsyncErrorPayload, GitAsyncSuccessPayload } from "../types"; +import type { + ConnectRequestParams, + ConnectResponseData, +} from "git/requests/connectRequest.types"; -export interface ConnectInitPayload extends ConnectRequestParams { - branchedPageId?: string; -} +export interface ConnectInitPayload extends ConnectRequestParams {} -export const connectInitAction = createSingleArtifactAction<ConnectInitPayload>( +export const connectInitAction = createArtifactAction<ConnectInitPayload>( (state) => { state.apiResponses.connect.loading = true; state.apiResponses.connect.error = null; @@ -15,18 +16,24 @@ export const connectInitAction = createSingleArtifactAction<ConnectInitPayload>( }, ); -export const connectSuccessAction = createSingleArtifactAction((state) => { - state.apiResponses.connect.loading = false; +export interface ConnectSuccessPayload + extends GitAsyncSuccessPayload<ConnectResponseData> {} - return state; -}); +export const connectSuccessAction = createArtifactAction<ConnectSuccessPayload>( + (state) => { + state.apiResponses.connect.loading = false; + + return state; + }, +); -export const connectErrorAction = - createSingleArtifactAction<GitAsyncErrorPayload>((state, action) => { +export const connectErrorAction = createArtifactAction<GitAsyncErrorPayload>( + (state, action) => { const { error } = action.payload; state.apiResponses.connect.loading = false; state.apiResponses.connect.error = error; return state; - }); + }, +); diff --git a/app/client/src/git/store/actions/createBranchActions.ts b/app/client/src/git/store/actions/createBranchActions.ts index be0e08445de2..010a7550888f 100644 --- a/app/client/src/git/store/actions/createBranchActions.ts +++ b/app/client/src/git/store/actions/createBranchActions.ts @@ -1,25 +1,27 @@ -import { createSingleArtifactAction } from "../helpers/createSingleArtifactAction"; +import { createArtifactAction } from "../helpers/createArtifactAction"; import type { GitAsyncErrorPayload } from "../types"; import type { CreateBranchRequestParams } from "git/requests/createBranchRequest.types"; -export interface CreateBranchInitPayload extends CreateBranchRequestParams {} +export interface CreateBranchInitPayload extends CreateBranchRequestParams { + artifactId: string; +} export const createBranchInitAction = - createSingleArtifactAction<CreateBranchInitPayload>((state) => { + createArtifactAction<CreateBranchInitPayload>((state) => { state.apiResponses.createBranch.loading = true; state.apiResponses.createBranch.error = null; return state; }); -export const createBranchSuccessAction = createSingleArtifactAction((state) => { +export const createBranchSuccessAction = createArtifactAction((state) => { state.apiResponses.createBranch.loading = false; return state; }); export const createBranchErrorAction = - createSingleArtifactAction<GitAsyncErrorPayload>((state, action) => { + createArtifactAction<GitAsyncErrorPayload>((state, action) => { const { error } = action.payload; state.apiResponses.createBranch.loading = false; diff --git a/app/client/src/git/store/actions/deleteBranchActions.ts b/app/client/src/git/store/actions/deleteBranchActions.ts index 09296625f0d6..0656886f39d4 100644 --- a/app/client/src/git/store/actions/deleteBranchActions.ts +++ b/app/client/src/git/store/actions/deleteBranchActions.ts @@ -1,25 +1,27 @@ -import { createSingleArtifactAction } from "../helpers/createSingleArtifactAction"; +import { createArtifactAction } from "../helpers/createArtifactAction"; import type { GitAsyncErrorPayload } from "../types"; import type { DeleteBranchRequestParams } from "../../requests/deleteBranchRequest.types"; -export interface DeleteBranchInitPayload extends DeleteBranchRequestParams {} +export interface DeleteBranchInitPayload extends DeleteBranchRequestParams { + artifactId: string; +} export const deleteBranchInitAction = - createSingleArtifactAction<DeleteBranchInitPayload>((state) => { + createArtifactAction<DeleteBranchInitPayload>((state) => { state.apiResponses.deleteBranch.loading = true; state.apiResponses.deleteBranch.error = null; return state; }); -export const deleteBranchSuccessAction = createSingleArtifactAction((state) => { +export const deleteBranchSuccessAction = createArtifactAction((state) => { state.apiResponses.deleteBranch.loading = false; return state; }); export const deleteBranchErrorAction = - createSingleArtifactAction<GitAsyncErrorPayload>((state, action) => { + createArtifactAction<GitAsyncErrorPayload>((state, action) => { const { error } = action.payload; state.apiResponses.deleteBranch.loading = false; diff --git a/app/client/src/git/store/actions/discardActions.ts b/app/client/src/git/store/actions/discardActions.ts index 35d37c0a6d0e..0f514cd0e585 100644 --- a/app/client/src/git/store/actions/discardActions.ts +++ b/app/client/src/git/store/actions/discardActions.ts @@ -1,20 +1,20 @@ -import { createSingleArtifactAction } from "../helpers/createSingleArtifactAction"; +import { createArtifactAction } from "../helpers/createArtifactAction"; import type { GitArtifactErrorPayloadAction } from "../types"; -export const discardInitAction = createSingleArtifactAction((state) => { +export const discardInitAction = createArtifactAction((state) => { state.apiResponses.discard.loading = true; state.apiResponses.discard.error = null; return state; }); -export const discardSuccessAction = createSingleArtifactAction((state) => { +export const discardSuccessAction = createArtifactAction((state) => { state.apiResponses.discard.loading = false; return state; }); -export const discardErrorAction = createSingleArtifactAction( +export const discardErrorAction = createArtifactAction( (state, action: GitArtifactErrorPayloadAction) => { const { error } = action.payload; @@ -25,7 +25,7 @@ export const discardErrorAction = createSingleArtifactAction( }, ); -export const clearDiscardErrorAction = createSingleArtifactAction((state) => { +export const clearDiscardErrorAction = createArtifactAction((state) => { state.apiResponses.discard.error = null; return state; diff --git a/app/client/src/git/store/actions/disconnectActions.ts b/app/client/src/git/store/actions/disconnectActions.ts index dba26c0de629..082aa91b7970 100644 --- a/app/client/src/git/store/actions/disconnectActions.ts +++ b/app/client/src/git/store/actions/disconnectActions.ts @@ -1,20 +1,20 @@ -import { createSingleArtifactAction } from "../helpers/createSingleArtifactAction"; +import { createArtifactAction } from "../helpers/createArtifactAction"; import type { GitArtifactErrorPayloadAction } from "../types"; -export const disconnectInitAction = createSingleArtifactAction((state) => { +export const disconnectInitAction = createArtifactAction((state) => { state.apiResponses.disconnect.loading = true; state.apiResponses.disconnect.error = null; return state; }); -export const disconnectSuccessAction = createSingleArtifactAction((state) => { +export const disconnectSuccessAction = createArtifactAction((state) => { state.apiResponses.disconnect.loading = false; return state; }); -export const disconnectErrorAction = createSingleArtifactAction( +export const disconnectErrorAction = createArtifactAction( (state, action: GitArtifactErrorPayloadAction) => { const { error } = action.payload; diff --git a/app/client/src/git/store/actions/fetchAutocommitProgressActions.ts b/app/client/src/git/store/actions/fetchAutocommitProgressActions.ts index a7d92793e4aa..bbde6e4dd649 100644 --- a/app/client/src/git/store/actions/fetchAutocommitProgressActions.ts +++ b/app/client/src/git/store/actions/fetchAutocommitProgressActions.ts @@ -1,7 +1,7 @@ import type { GitAsyncErrorPayload } from "../types"; -import { createSingleArtifactAction } from "../helpers/createSingleArtifactAction"; +import { createArtifactAction } from "../helpers/createArtifactAction"; -export const fetchAutocommitProgressInitAction = createSingleArtifactAction( +export const fetchAutocommitProgressInitAction = createArtifactAction( (state) => { state.apiResponses.autocommitProgress.loading = true; state.apiResponses.autocommitProgress.error = null; @@ -10,7 +10,7 @@ export const fetchAutocommitProgressInitAction = createSingleArtifactAction( }, ); -export const fetchAutocommitProgressSuccessAction = createSingleArtifactAction( +export const fetchAutocommitProgressSuccessAction = createArtifactAction( (state) => { state.apiResponses.autocommitProgress.loading = false; @@ -19,7 +19,7 @@ export const fetchAutocommitProgressSuccessAction = createSingleArtifactAction( ); export const fetchAutocommitProgressErrorAction = - createSingleArtifactAction<GitAsyncErrorPayload>((state, action) => { + createArtifactAction<GitAsyncErrorPayload>((state, action) => { const { error } = action.payload; state.apiResponses.autocommitProgress.loading = false; diff --git a/app/client/src/git/store/actions/fetchBranchesActions.ts b/app/client/src/git/store/actions/fetchBranchesActions.ts index e83ce0325e59..6758ad918eb0 100644 --- a/app/client/src/git/store/actions/fetchBranchesActions.ts +++ b/app/client/src/git/store/actions/fetchBranchesActions.ts @@ -3,19 +3,21 @@ import type { FetchBranchesResponseData, } from "../../requests/fetchBranchesRequest.types"; import type { GitAsyncErrorPayload, GitAsyncSuccessPayload } from "../types"; -import { createSingleArtifactAction } from "../helpers/createSingleArtifactAction"; +import { createArtifactAction } from "../helpers/createArtifactAction"; -export interface FetchBranchesInitPayload extends FetchBranchesRequestParams {} +export interface FetchBranchesInitPayload extends FetchBranchesRequestParams { + artifactId: string; +} export const fetchBranchesInitAction = - createSingleArtifactAction<FetchBranchesInitPayload>((state) => { + createArtifactAction<FetchBranchesInitPayload>((state) => { state.apiResponses.branches.loading = true; state.apiResponses.branches.error = null; return state; }); -export const fetchBranchesSuccessAction = createSingleArtifactAction< +export const fetchBranchesSuccessAction = createArtifactAction< GitAsyncSuccessPayload<FetchBranchesResponseData> >((state, action) => { state.apiResponses.branches.loading = false; @@ -25,7 +27,7 @@ export const fetchBranchesSuccessAction = createSingleArtifactAction< }); export const fetchBranchesErrorAction = - createSingleArtifactAction<GitAsyncErrorPayload>((state, action) => { + createArtifactAction<GitAsyncErrorPayload>((state, action) => { const { error } = action.payload; state.apiResponses.branches.loading = false; diff --git a/app/client/src/git/store/actions/fetchGlobalProfileActions.ts b/app/client/src/git/store/actions/fetchGlobalProfileActions.ts index 7cfb2390b021..bc2d0b6b92a3 100644 --- a/app/client/src/git/store/actions/fetchGlobalProfileActions.ts +++ b/app/client/src/git/store/actions/fetchGlobalProfileActions.ts @@ -2,11 +2,11 @@ import type { FetchGlobalProfileResponseData } from "git/requests/fetchGlobalPro import type { GitAsyncSuccessPayload, GitAsyncErrorPayload, - GitConfigReduxState, + GitGlobalReduxState, } from "../types"; import type { PayloadAction } from "@reduxjs/toolkit"; -export const fetchGlobalProfileInitAction = (state: GitConfigReduxState) => { +export const fetchGlobalProfileInitAction = (state: GitGlobalReduxState) => { state.globalProfile.loading = true; state.globalProfile.error = null; @@ -14,7 +14,7 @@ export const fetchGlobalProfileInitAction = (state: GitConfigReduxState) => { }; export const fetchGlobalProfileSuccessAction = ( - state: GitConfigReduxState, + state: GitGlobalReduxState, action: PayloadAction<GitAsyncSuccessPayload<FetchGlobalProfileResponseData>>, ) => { state.globalProfile.loading = false; @@ -24,7 +24,7 @@ export const fetchGlobalProfileSuccessAction = ( }; export const fetchGlobalProfileErrorAction = ( - state: GitConfigReduxState, + state: GitGlobalReduxState, action: PayloadAction<GitAsyncErrorPayload>, ) => { const { error } = action.payload; diff --git a/app/client/src/git/store/actions/fetchGlobalSSHKeyActions.ts b/app/client/src/git/store/actions/fetchGlobalSSHKeyActions.ts new file mode 100644 index 000000000000..de9add1c5ee0 --- /dev/null +++ b/app/client/src/git/store/actions/fetchGlobalSSHKeyActions.ts @@ -0,0 +1,55 @@ +import type { + FetchGlobalSSHKeyRequestParams, + FetchGlobalSSHKeyResponseData, +} from "git/requests/fetchGlobalSSHKeyRequest.types"; +import type { + GitAsyncSuccessPayload, + GitAsyncErrorPayload, + GitGlobalReduxState, +} from "../types"; +import type { PayloadAction } from "@reduxjs/toolkit"; + +export interface FetchGlobalSSHKeyInitPayload + extends FetchGlobalSSHKeyRequestParams {} + +export const fetchGlobalSSHKeyInitAction = ( + state: GitGlobalReduxState, + // need action to better define action type + // eslint-disable-next-line @typescript-eslint/no-unused-vars + action: PayloadAction<FetchGlobalSSHKeyInitPayload>, +) => { + state.globalSSHKey.loading = true; + state.globalSSHKey.error = null; + + return state; +}; + +export const fetchGlobalSSHKeySuccessAction = ( + state: GitGlobalReduxState, + action: PayloadAction<GitAsyncSuccessPayload<FetchGlobalSSHKeyResponseData>>, +) => { + state.globalSSHKey.loading = false; + state.globalSSHKey.value = action.payload.responseData; + + return state; +}; + +export const fetchGlobalSSHKeyErrorAction = ( + state: GitGlobalReduxState, + action: PayloadAction<GitAsyncErrorPayload>, +) => { + const { error } = action.payload; + + state.globalSSHKey.loading = false; + state.globalSSHKey.error = error; + + return state; +}; + +export const resetGlobalSSHKeyAction = (state: GitGlobalReduxState) => { + state.globalSSHKey.loading = false; + state.globalSSHKey.value = null; + state.globalSSHKey.error = null; + + return state; +}; diff --git a/app/client/src/git/store/actions/fetchLocalProfileActions.ts b/app/client/src/git/store/actions/fetchLocalProfileActions.ts index 3559a2814c35..33a62514f44c 100644 --- a/app/client/src/git/store/actions/fetchLocalProfileActions.ts +++ b/app/client/src/git/store/actions/fetchLocalProfileActions.ts @@ -3,18 +3,16 @@ import type { GitArtifactErrorPayloadAction, GitAsyncSuccessPayload, } from "../types"; -import { createSingleArtifactAction } from "../helpers/createSingleArtifactAction"; +import { createArtifactAction } from "../helpers/createArtifactAction"; -export const fetchLocalProfileInitAction = createSingleArtifactAction( - (state) => { - state.apiResponses.localProfile.loading = true; - state.apiResponses.localProfile.error = null; +export const fetchLocalProfileInitAction = createArtifactAction((state) => { + state.apiResponses.localProfile.loading = true; + state.apiResponses.localProfile.error = null; - return state; - }, -); + return state; +}); -export const fetchLocalProfileSuccessAction = createSingleArtifactAction< +export const fetchLocalProfileSuccessAction = createArtifactAction< GitAsyncSuccessPayload<FetchLocalProfileResponseData> >((state, action) => { state.apiResponses.localProfile.loading = false; @@ -23,7 +21,7 @@ export const fetchLocalProfileSuccessAction = createSingleArtifactAction< return state; }); -export const fetchLocalProfileErrorAction = createSingleArtifactAction( +export const fetchLocalProfileErrorAction = createArtifactAction( (state, action: GitArtifactErrorPayloadAction) => { const { error } = action.payload; diff --git a/app/client/src/git/store/actions/fetchMergeStatusActions.ts b/app/client/src/git/store/actions/fetchMergeStatusActions.ts index 65ed313114cb..26b72829fadd 100644 --- a/app/client/src/git/store/actions/fetchMergeStatusActions.ts +++ b/app/client/src/git/store/actions/fetchMergeStatusActions.ts @@ -1,5 +1,5 @@ import type { GitAsyncSuccessPayload, GitAsyncErrorPayload } from "../types"; -import { createSingleArtifactAction } from "../helpers/createSingleArtifactAction"; +import { createArtifactAction } from "../helpers/createArtifactAction"; import type { FetchMergeStatusRequestParams, FetchMergeStatusResponseData, @@ -11,14 +11,14 @@ export interface FetchMergeStatusInitPayload } export const fetchMergeStatusInitAction = - createSingleArtifactAction<FetchMergeStatusInitPayload>((state) => { + createArtifactAction<FetchMergeStatusInitPayload>((state) => { state.apiResponses.mergeStatus.loading = true; state.apiResponses.mergeStatus.error = null; return state; }); -export const fetchMergeStatusSuccessAction = createSingleArtifactAction< +export const fetchMergeStatusSuccessAction = createArtifactAction< GitAsyncSuccessPayload<FetchMergeStatusResponseData> >((state, action) => { state.apiResponses.mergeStatus.loading = false; @@ -28,7 +28,7 @@ export const fetchMergeStatusSuccessAction = createSingleArtifactAction< }); export const fetchMergeStatusErrorAction = - createSingleArtifactAction<GitAsyncErrorPayload>((state, action) => { + createArtifactAction<GitAsyncErrorPayload>((state, action) => { const { error } = action.payload; state.apiResponses.mergeStatus.loading = false; @@ -37,7 +37,7 @@ export const fetchMergeStatusErrorAction = return state; }); -export const clearMergeStatusAction = createSingleArtifactAction((state) => { +export const clearMergeStatusAction = createArtifactAction((state) => { state.apiResponses.mergeStatus.loading = false; state.apiResponses.mergeStatus.error = null; state.apiResponses.mergeStatus.value = null; diff --git a/app/client/src/git/store/actions/fetchMetadataActions.ts b/app/client/src/git/store/actions/fetchMetadataActions.ts index 176413dfbaaa..6e7a9f2f1e3d 100644 --- a/app/client/src/git/store/actions/fetchMetadataActions.ts +++ b/app/client/src/git/store/actions/fetchMetadataActions.ts @@ -1,15 +1,15 @@ import type { GitAsyncErrorPayload, GitAsyncSuccessPayload } from "../types"; -import { createSingleArtifactAction } from "../helpers/createSingleArtifactAction"; +import { createArtifactAction } from "../helpers/createArtifactAction"; import type { FetchMetadataResponseData } from "git/requests/fetchMetadataRequest.types"; -export const fetchMetadataInitAction = createSingleArtifactAction((state) => { +export const fetchMetadataInitAction = createArtifactAction((state) => { state.apiResponses.metadata.loading = true; state.apiResponses.metadata.error = null; return state; }); -export const fetchMetadataSuccessAction = createSingleArtifactAction< +export const fetchMetadataSuccessAction = createArtifactAction< GitAsyncSuccessPayload<FetchMetadataResponseData> >((state, action) => { state.apiResponses.metadata.loading = false; @@ -19,7 +19,7 @@ export const fetchMetadataSuccessAction = createSingleArtifactAction< }); export const fetchMetadataErrorAction = - createSingleArtifactAction<GitAsyncErrorPayload>((state, action) => { + createArtifactAction<GitAsyncErrorPayload>((state, action) => { const { error } = action.payload; state.apiResponses.metadata.loading = false; diff --git a/app/client/src/git/store/actions/fetchProtectedBranchesActions.ts b/app/client/src/git/store/actions/fetchProtectedBranchesActions.ts index dc66ff2290c0..1ad38bf4096c 100644 --- a/app/client/src/git/store/actions/fetchProtectedBranchesActions.ts +++ b/app/client/src/git/store/actions/fetchProtectedBranchesActions.ts @@ -1,8 +1,8 @@ import type { GitAsyncSuccessPayload, GitAsyncErrorPayload } from "../types"; -import { createSingleArtifactAction } from "../helpers/createSingleArtifactAction"; +import { createArtifactAction } from "../helpers/createArtifactAction"; import type { FetchProtectedBranchesResponseData } from "git/requests/fetchProtectedBranchesRequest.types"; -export const fetchProtectedBranchesInitAction = createSingleArtifactAction( +export const fetchProtectedBranchesInitAction = createArtifactAction( (state) => { state.apiResponses.protectedBranches.loading = true; state.apiResponses.protectedBranches.error = null; @@ -11,7 +11,7 @@ export const fetchProtectedBranchesInitAction = createSingleArtifactAction( }, ); -export const fetchProtectedBranchesSuccessAction = createSingleArtifactAction< +export const fetchProtectedBranchesSuccessAction = createArtifactAction< GitAsyncSuccessPayload<FetchProtectedBranchesResponseData> >((state, action) => { state.apiResponses.protectedBranches.loading = false; @@ -21,7 +21,7 @@ export const fetchProtectedBranchesSuccessAction = createSingleArtifactAction< }); export const fetchProtectedBranchesErrorAction = - createSingleArtifactAction<GitAsyncErrorPayload>((state, action) => { + createArtifactAction<GitAsyncErrorPayload>((state, action) => { const { error } = action.payload; state.apiResponses.protectedBranches.loading = false; diff --git a/app/client/src/git/store/actions/fetchSSHKeyActions.ts b/app/client/src/git/store/actions/fetchSSHKeyActions.ts index 828cf6ebcb75..386dd4643411 100644 --- a/app/client/src/git/store/actions/fetchSSHKeyActions.ts +++ b/app/client/src/git/store/actions/fetchSSHKeyActions.ts @@ -1,15 +1,15 @@ import type { GitAsyncErrorPayload, GitAsyncSuccessPayload } from "../types"; -import { createSingleArtifactAction } from "../helpers/createSingleArtifactAction"; +import { createArtifactAction } from "../helpers/createArtifactAction"; import type { FetchSSHKeyResponseData } from "git/requests/fetchSSHKeyRequest.types"; -export const fetchSSHKeyInitAction = createSingleArtifactAction((state) => { +export const fetchSSHKeyInitAction = createArtifactAction((state) => { state.apiResponses.sshKey.loading = true; state.apiResponses.sshKey.error = null; return state; }); -export const fetchSSHKeySuccessAction = createSingleArtifactAction< +export const fetchSSHKeySuccessAction = createArtifactAction< GitAsyncSuccessPayload<FetchSSHKeyResponseData> >((state, action) => { state.apiResponses.sshKey.loading = false; @@ -20,7 +20,7 @@ export const fetchSSHKeySuccessAction = createSingleArtifactAction< }); export const fetchSSHKeyErrorAction = - createSingleArtifactAction<GitAsyncErrorPayload>((state, action) => { + createArtifactAction<GitAsyncErrorPayload>((state, action) => { const { error } = action.payload; state.apiResponses.sshKey.loading = false; @@ -29,7 +29,7 @@ export const fetchSSHKeyErrorAction = return state; }); -export const resetFetchSSHKeyAction = createSingleArtifactAction((state) => { +export const resetFetchSSHKeyAction = createArtifactAction((state) => { state.apiResponses.sshKey.loading = false; state.apiResponses.sshKey.error = null; state.apiResponses.sshKey.value = null; diff --git a/app/client/src/git/store/actions/fetchStatusActions.ts b/app/client/src/git/store/actions/fetchStatusActions.ts index 1121e368d012..47097593260b 100644 --- a/app/client/src/git/store/actions/fetchStatusActions.ts +++ b/app/client/src/git/store/actions/fetchStatusActions.ts @@ -3,19 +3,21 @@ import type { FetchStatusResponseData, } from "git/requests/fetchStatusRequest.types"; import type { GitAsyncErrorPayload, GitAsyncSuccessPayload } from "../types"; -import { createSingleArtifactAction } from "../helpers/createSingleArtifactAction"; +import { createArtifactAction } from "../helpers/createArtifactAction"; -export interface FetchStatusInitPayload extends FetchStatusRequestParams {} +export interface FetchStatusInitPayload extends FetchStatusRequestParams { + artifactId: string; +} export const fetchStatusInitAction = - createSingleArtifactAction<FetchStatusInitPayload>((state) => { + createArtifactAction<FetchStatusInitPayload>((state) => { state.apiResponses.status.loading = true; state.apiResponses.status.error = null; return state; }); -export const fetchStatusSuccessAction = createSingleArtifactAction< +export const fetchStatusSuccessAction = createArtifactAction< GitAsyncSuccessPayload<FetchStatusResponseData> >((state, action) => { state.apiResponses.status.loading = false; @@ -25,7 +27,7 @@ export const fetchStatusSuccessAction = createSingleArtifactAction< }); export const fetchStatusErrorAction = - createSingleArtifactAction<GitAsyncErrorPayload>((state, action) => { + createArtifactAction<GitAsyncErrorPayload>((state, action) => { const { error } = action.payload; state.apiResponses.status.loading = false; diff --git a/app/client/src/git/store/actions/generateSSHKeyActions.ts b/app/client/src/git/store/actions/generateSSHKeyActions.ts index fa70c3a1ba28..569d7d9995c2 100644 --- a/app/client/src/git/store/actions/generateSSHKeyActions.ts +++ b/app/client/src/git/store/actions/generateSSHKeyActions.ts @@ -2,21 +2,21 @@ import type { GenerateSSHKeyRequestParams, GenerateSSHKeyResponseData, } from "git/requests/generateSSHKeyRequest.types"; -import { createSingleArtifactAction } from "../helpers/createSingleArtifactAction"; +import { createArtifactAction } from "../helpers/createArtifactAction"; import type { GitAsyncErrorPayload, GitAsyncSuccessPayload } from "../types"; export interface GenerateSSHKeyInitPayload extends GenerateSSHKeyRequestParams {} export const generateSSHKeyInitAction = - createSingleArtifactAction<GenerateSSHKeyInitPayload>((state) => { + createArtifactAction<GenerateSSHKeyInitPayload>((state) => { state.apiResponses.generateSSHKey.loading = true; state.apiResponses.generateSSHKey.error = null; return state; }); -export const generateSSHKeySuccessAction = createSingleArtifactAction< +export const generateSSHKeySuccessAction = createArtifactAction< GitAsyncSuccessPayload<GenerateSSHKeyResponseData> >((state, action) => { state.apiResponses.generateSSHKey.loading = false; @@ -27,7 +27,7 @@ export const generateSSHKeySuccessAction = createSingleArtifactAction< }); export const generateSSHKeyErrorAction = - createSingleArtifactAction<GitAsyncErrorPayload>((state, action) => { + createArtifactAction<GitAsyncErrorPayload>((state, action) => { const { error } = action.payload; state.apiResponses.generateSSHKey.loading = false; @@ -36,7 +36,7 @@ export const generateSSHKeyErrorAction = return state; }); -export const resetGenerateSSHKeyAction = createSingleArtifactAction((state) => { +export const resetGenerateSSHKeyAction = createArtifactAction((state) => { state.apiResponses.generateSSHKey.loading = false; state.apiResponses.generateSSHKey.error = null; diff --git a/app/client/src/git/store/actions/gitImportActions.ts b/app/client/src/git/store/actions/gitImportActions.ts index 49411b55dd55..30e9c7417b2d 100644 --- a/app/client/src/git/store/actions/gitImportActions.ts +++ b/app/client/src/git/store/actions/gitImportActions.ts @@ -1,25 +1,35 @@ -import { createSingleArtifactAction } from "../helpers/createSingleArtifactAction"; -import type { GitAsyncErrorPayload } from "../types"; +import type { PayloadAction } from "@reduxjs/toolkit"; +import type { GitAsyncErrorPayload, GitGlobalReduxState } from "../types"; +import type { GitImportRequestParams } from "git/requests/gitImportRequest.types"; -export const gitImportInitAction = createSingleArtifactAction((state) => { - state.apiResponses.gitImport.loading = true; - state.apiResponses.gitImport.error = null; +export interface GitImportInitPayload extends GitImportRequestParams {} + +export const gitImportInitAction = ( + state: GitGlobalReduxState, + // need type for better import + // eslint-disable-next-line @typescript-eslint/no-unused-vars + action: PayloadAction<GitImportInitPayload>, +) => { + state.gitImport.loading = true; + state.gitImport.error = null; return state; -}); +}; -export const gitImportSuccessAction = createSingleArtifactAction((state) => { - state.apiResponses.gitImport.loading = false; +export const gitImportSuccessAction = (state: GitGlobalReduxState) => { + state.gitImport.loading = false; return state; -}); +}; -export const gitImportErrorAction = - createSingleArtifactAction<GitAsyncErrorPayload>((state, action) => { - const { error } = action.payload; +export const gitImportErrorAction = ( + state: GitGlobalReduxState, + action: PayloadAction<GitAsyncErrorPayload>, +) => { + const { error } = action.payload; - state.apiResponses.gitImport.loading = false; - state.apiResponses.gitImport.error = error; + state.gitImport.loading = false; + state.gitImport.error = error; - return state; - }); + return state; +}; diff --git a/app/client/src/git/store/actions/initGitActions.ts b/app/client/src/git/store/actions/initGitActions.ts index d93cf955eeec..ebe588555a24 100644 --- a/app/client/src/git/store/actions/initGitActions.ts +++ b/app/client/src/git/store/actions/initGitActions.ts @@ -1,15 +1,11 @@ -import type { FetchMetadataResponseData } from "git/requests/fetchMetadataRequest.types"; -import { createSingleArtifactAction } from "../helpers/createSingleArtifactAction"; +import { createArtifactAction } from "../helpers/createArtifactAction"; +import type { ApplicationPayload } from "entities/Application"; export interface InitGitForEditorPayload { - artifact: { - id: string; - baseId: string; - gitApplicationMetadata?: Partial<FetchMetadataResponseData>; - }; + artifact: ApplicationPayload | null; } export const initGitForEditorAction = - createSingleArtifactAction<InitGitForEditorPayload>((state) => { + createArtifactAction<InitGitForEditorPayload>((state) => { return state; }); diff --git a/app/client/src/git/store/actions/mergeActions.ts b/app/client/src/git/store/actions/mergeActions.ts index 5bb17a351ce6..0d4e67eea8fe 100644 --- a/app/client/src/git/store/actions/mergeActions.ts +++ b/app/client/src/git/store/actions/mergeActions.ts @@ -1,20 +1,20 @@ -import { createSingleArtifactAction } from "../helpers/createSingleArtifactAction"; +import { createArtifactAction } from "../helpers/createArtifactAction"; import type { GitArtifactErrorPayloadAction } from "../types"; -export const mergeInitAction = createSingleArtifactAction((state) => { +export const mergeInitAction = createArtifactAction((state) => { state.apiResponses.merge.loading = true; state.apiResponses.merge.error = null; return state; }); -export const mergeSuccessAction = createSingleArtifactAction((state) => { +export const mergeSuccessAction = createArtifactAction((state) => { state.apiResponses.merge.loading = false; return state; }); -export const mergeErrorAction = createSingleArtifactAction( +export const mergeErrorAction = createArtifactAction( (state, action: GitArtifactErrorPayloadAction) => { const { error } = action.payload; diff --git a/app/client/src/git/store/actions/mountActions.ts b/app/client/src/git/store/actions/mountActions.ts index 07a08ee2b566..8d35126d9502 100644 --- a/app/client/src/git/store/actions/mountActions.ts +++ b/app/client/src/git/store/actions/mountActions.ts @@ -1,26 +1,31 @@ import type { PayloadAction } from "@reduxjs/toolkit"; -import type { GitArtifactBasePayload, GitArtifactReduxState } from "../types"; -import { gitSingleArtifactInitialState } from "../helpers/gitSingleArtifactInitialState"; +import type { + GitArtifactBasePayload, + GitArtifactRootReduxState, +} from "../types"; +import { gitArtifactInitialState } from "../helpers/initialState"; // ! This might be removed later export const mountAction = ( - state: GitArtifactReduxState, + state: GitArtifactRootReduxState, action: PayloadAction<GitArtifactBasePayload>, ) => { - const { artifactType, baseArtifactId } = action.payload; + const { artifactDef } = action.payload; + const { artifactType, baseArtifactId } = artifactDef; state[artifactType] ??= {}; - state[artifactType][baseArtifactId] ??= gitSingleArtifactInitialState; + state[artifactType][baseArtifactId] ??= gitArtifactInitialState; return state; }; export const unmountAction = ( - state: GitArtifactReduxState, + state: GitArtifactRootReduxState, action: PayloadAction<GitArtifactBasePayload>, ) => { - const { artifactType, baseArtifactId } = action.payload; + const { artifactDef } = action.payload; + const { artifactType, baseArtifactId } = artifactDef; delete state?.[artifactType]?.[baseArtifactId]; diff --git a/app/client/src/git/store/actions/pullActions.ts b/app/client/src/git/store/actions/pullActions.ts index 00a0d00f2033..48d3398e18c6 100644 --- a/app/client/src/git/store/actions/pullActions.ts +++ b/app/client/src/git/store/actions/pullActions.ts @@ -1,26 +1,24 @@ -import { createSingleArtifactAction } from "../helpers/createSingleArtifactAction"; +import { createArtifactAction } from "../helpers/createArtifactAction"; import type { GitAsyncErrorPayload } from "../types"; export interface PullInitPayload { artifactId: string; } -export const pullInitAction = createSingleArtifactAction<PullInitPayload>( - (state) => { - state.apiResponses.pull.loading = true; - state.apiResponses.pull.error = null; +export const pullInitAction = createArtifactAction<PullInitPayload>((state) => { + state.apiResponses.pull.loading = true; + state.apiResponses.pull.error = null; - return state; - }, -); + return state; +}); -export const pullSuccessAction = createSingleArtifactAction((state) => { +export const pullSuccessAction = createArtifactAction((state) => { state.apiResponses.pull.loading = false; return state; }); -export const pullErrorAction = createSingleArtifactAction<GitAsyncErrorPayload>( +export const pullErrorAction = createArtifactAction<GitAsyncErrorPayload>( (state, action) => { const { error } = action.payload; diff --git a/app/client/src/git/store/actions/repoLimitErrorModalActions.ts b/app/client/src/git/store/actions/repoLimitErrorModalActions.ts index b1867c1d5926..a2c96bac7721 100644 --- a/app/client/src/git/store/actions/repoLimitErrorModalActions.ts +++ b/app/client/src/git/store/actions/repoLimitErrorModalActions.ts @@ -1,16 +1,14 @@ -import { createSingleArtifactAction } from "../helpers/createSingleArtifactAction"; +import { createArtifactAction } from "../helpers/createArtifactAction"; interface ToggleRepoLimitModalActionPayload { open: boolean; } export const toggleRepoLimitErrorModalAction = - createSingleArtifactAction<ToggleRepoLimitModalActionPayload>( - (state, action) => { - const { open } = action.payload; + createArtifactAction<ToggleRepoLimitModalActionPayload>((state, action) => { + const { open } = action.payload; - state.ui.repoLimitErrorModalOpen = open; + state.ui.repoLimitErrorModalOpen = open; - return state; - }, - ); + return state; + }); diff --git a/app/client/src/git/store/actions/toggleAutocommitActions.ts b/app/client/src/git/store/actions/toggleAutocommitActions.ts index 96721698196f..d9c700cbb457 100644 --- a/app/client/src/git/store/actions/toggleAutocommitActions.ts +++ b/app/client/src/git/store/actions/toggleAutocommitActions.ts @@ -1,24 +1,20 @@ -import { createSingleArtifactAction } from "../helpers/createSingleArtifactAction"; +import { createArtifactAction } from "../helpers/createArtifactAction"; import type { GitArtifactErrorPayloadAction } from "../types"; -export const toggleAutocommitInitAction = createSingleArtifactAction( - (state) => { - state.apiResponses.toggleAutocommit.loading = true; - state.apiResponses.toggleAutocommit.error = null; +export const toggleAutocommitInitAction = createArtifactAction((state) => { + state.apiResponses.toggleAutocommit.loading = true; + state.apiResponses.toggleAutocommit.error = null; - return state; - }, -); + return state; +}); -export const toggleAutocommitSuccessAction = createSingleArtifactAction( - (state) => { - state.apiResponses.toggleAutocommit.loading = false; +export const toggleAutocommitSuccessAction = createArtifactAction((state) => { + state.apiResponses.toggleAutocommit.loading = false; - return state; - }, -); + return state; +}); -export const toggleAutocommitErrorAction = createSingleArtifactAction( +export const toggleAutocommitErrorAction = createArtifactAction( (state, action: GitArtifactErrorPayloadAction) => { const { error } = action.payload; diff --git a/app/client/src/git/store/actions/triggerAutocommitActions.ts b/app/client/src/git/store/actions/triggerAutocommitActions.ts index 28e88ecd2f16..da8075bc347f 100644 --- a/app/client/src/git/store/actions/triggerAutocommitActions.ts +++ b/app/client/src/git/store/actions/triggerAutocommitActions.ts @@ -1,4 +1,4 @@ -import { createSingleArtifactAction } from "../helpers/createSingleArtifactAction"; +import { createArtifactAction } from "../helpers/createArtifactAction"; import type { GitAsyncErrorPayload } from "../types"; export interface TriggerAutocommitInitPayload { @@ -6,23 +6,21 @@ export interface TriggerAutocommitInitPayload { } export const triggerAutocommitInitAction = - createSingleArtifactAction<TriggerAutocommitInitPayload>((state) => { + createArtifactAction<TriggerAutocommitInitPayload>((state) => { state.apiResponses.triggerAutocommit.loading = true; state.apiResponses.triggerAutocommit.error = null; return state; }); -export const triggerAutocommitSuccessAction = createSingleArtifactAction( - (state) => { - state.apiResponses.triggerAutocommit.loading = false; +export const triggerAutocommitSuccessAction = createArtifactAction((state) => { + state.apiResponses.triggerAutocommit.loading = false; - return state; - }, -); + return state; +}); export const triggerAutocommitErrorAction = - createSingleArtifactAction<GitAsyncErrorPayload>((state, action) => { + createArtifactAction<GitAsyncErrorPayload>((state, action) => { const { error } = action.payload; state.apiResponses.triggerAutocommit.loading = false; @@ -31,7 +29,7 @@ export const triggerAutocommitErrorAction = return state; }); -export const pollAutocommitProgressStartAction = createSingleArtifactAction( +export const pollAutocommitProgressStartAction = createArtifactAction( (state) => { state.ui.autocommitPolling = true; @@ -39,7 +37,7 @@ export const pollAutocommitProgressStartAction = createSingleArtifactAction( }, ); -export const pollAutocommitProgressStopAction = createSingleArtifactAction( +export const pollAutocommitProgressStopAction = createArtifactAction( (state) => { state.ui.autocommitPolling = false; diff --git a/app/client/src/git/store/actions/uiActions.ts b/app/client/src/git/store/actions/uiActions.ts index 577d1dfa3d10..162382c3b876 100644 --- a/app/client/src/git/store/actions/uiActions.ts +++ b/app/client/src/git/store/actions/uiActions.ts @@ -1,5 +1,7 @@ import type { GitOpsTab, GitSettingsTab } from "git/constants/enums"; -import { createSingleArtifactAction } from "../helpers/createSingleArtifactAction"; +import { createArtifactAction } from "../helpers/createArtifactAction"; +import type { GitGlobalReduxState } from "../types"; +import type { PayloadAction } from "@reduxjs/toolkit"; // connect modal export interface ToggleConnectModalPayload { @@ -7,7 +9,7 @@ export interface ToggleConnectModalPayload { } export const toggleConnectModalAction = - createSingleArtifactAction<ToggleConnectModalPayload>((state, action) => { + createArtifactAction<ToggleConnectModalPayload>((state, action) => { const { open } = action.payload; state.ui.connectModalOpen = open; @@ -15,27 +17,54 @@ export const toggleConnectModalAction = return state; }); +export interface ToggleConnectSuccessModalPayload { + open: boolean; +} + +export const toggleConnectSuccessModalAction = + createArtifactAction<ToggleConnectSuccessModalPayload>((state, action) => { + const { open } = action.payload; + + state.ui.connectSuccessModalOpen = open; + + return state; + }); + +export interface ToggleImportModalPayload { + open: boolean; +} + +export const toggleImportModalAction = ( + state: GitGlobalReduxState, + action: PayloadAction<ToggleImportModalPayload>, +) => { + const { open } = action.payload; + + state.isImportModalOpen = open; + + return state; +}; + // disconnect modal export interface OpenDisconnectModalPayload { artifactName: string; } export const openDisconnectModalAction = - createSingleArtifactAction<OpenDisconnectModalPayload>((state, action) => { - state.ui.disconnectBaseArtifactId = action.payload.baseArtifactId; + createArtifactAction<OpenDisconnectModalPayload>((state, action) => { + state.ui.disconnectBaseArtifactId = + action.payload.artifactDef.baseArtifactId; state.ui.disconnectArtifactName = action.payload.artifactName; return state; }); -export const closeDisconnectModalAction = createSingleArtifactAction( - (state) => { - state.ui.disconnectBaseArtifactId = null; - state.ui.disconnectArtifactName = null; +export const closeDisconnectModalAction = createArtifactAction((state) => { + state.ui.disconnectBaseArtifactId = null; + state.ui.disconnectArtifactName = null; - return state; - }, -); + return state; +}); // ops modal @@ -44,15 +73,16 @@ export interface ToggleOpsModalPayload { tab: keyof typeof GitOpsTab; } -export const toggleOpsModalAction = - createSingleArtifactAction<ToggleOpsModalPayload>((state, action) => { +export const toggleOpsModalAction = createArtifactAction<ToggleOpsModalPayload>( + (state, action) => { const { open, tab } = action.payload; state.ui.opsModalOpen = open; state.ui.opsModalTab = tab; return state; - }); + }, +); // settings modal export interface ToggleSettingsModalPayload { @@ -61,7 +91,7 @@ export interface ToggleSettingsModalPayload { } export const toggleSettingsModalAction = - createSingleArtifactAction<ToggleSettingsModalPayload>((state, action) => { + createArtifactAction<ToggleSettingsModalPayload>((state, action) => { const { open, tab } = action.payload; state.ui.settingsModalOpen = open; @@ -76,29 +106,28 @@ interface ToggleAutocommitDisableModalPayload { } export const toggleAutocommitDisableModalAction = - createSingleArtifactAction<ToggleAutocommitDisableModalPayload>( - (state, action) => { - const { open } = action.payload; + createArtifactAction<ToggleAutocommitDisableModalPayload>((state, action) => { + const { open } = action.payload; - state.ui.autocommitDisableModalOpen = open; + state.ui.autocommitDisableModalOpen = open; - return state; - }, - ); + return state; + }); // branch popup interface BranchPopupPayload { open: boolean; } -export const toggleBranchPopupAction = - createSingleArtifactAction<BranchPopupPayload>((state, action) => { +export const toggleBranchPopupAction = createArtifactAction<BranchPopupPayload>( + (state, action) => { const { open } = action.payload; state.ui.branchPopupOpen = open; return state; - }); + }, +); // error modals interface ToggleRepoLimitModalPayload { @@ -106,7 +135,7 @@ interface ToggleRepoLimitModalPayload { } export const toggleRepoLimitErrorModalAction = - createSingleArtifactAction<ToggleRepoLimitModalPayload>((state, action) => { + createArtifactAction<ToggleRepoLimitModalPayload>((state, action) => { const { open } = action.payload; state.ui.repoLimitErrorModalOpen = open; @@ -119,12 +148,10 @@ interface ToggleConflictErrorModalPayload { } export const toggleConflictErrorModalAction = - createSingleArtifactAction<ToggleConflictErrorModalPayload>( - (state, action) => { - const { open } = action.payload; + createArtifactAction<ToggleConflictErrorModalPayload>((state, action) => { + const { open } = action.payload; - state.ui.conflictErrorModalOpen = open; + state.ui.conflictErrorModalOpen = open; - return state; - }, - ); + return state; + }); diff --git a/app/client/src/git/store/actions/updateGlobalProfileActions.ts b/app/client/src/git/store/actions/updateGlobalProfileActions.ts index b4d25b0b57d7..3549672deb56 100644 --- a/app/client/src/git/store/actions/updateGlobalProfileActions.ts +++ b/app/client/src/git/store/actions/updateGlobalProfileActions.ts @@ -1,14 +1,14 @@ import type { UpdateGlobalProfileRequestParams } from "git/requests/updateGlobalProfileRequest.types"; -import type { GitAsyncErrorPayload, GitConfigReduxState } from "../types"; +import type { GitAsyncErrorPayload, GitGlobalReduxState } from "../types"; import type { PayloadAction } from "@reduxjs/toolkit"; export interface UpdateGlobalProfileInitPayload extends UpdateGlobalProfileRequestParams {} type UpdateGlobalProfileInitAction = ( - state: GitConfigReduxState, + state: GitGlobalReduxState, action: PayloadAction<UpdateGlobalProfileInitPayload>, -) => GitConfigReduxState; +) => GitGlobalReduxState; export const updateGlobalProfileInitAction: UpdateGlobalProfileInitAction = ( state, @@ -20,7 +20,7 @@ export const updateGlobalProfileInitAction: UpdateGlobalProfileInitAction = ( }; export const updateGlobalProfileSuccessAction = ( - state: GitConfigReduxState, + state: GitGlobalReduxState, ) => { state.updateGlobalProfile.loading = false; @@ -28,7 +28,7 @@ export const updateGlobalProfileSuccessAction = ( }; export const updateGlobalProfileErrorAction = ( - state: GitConfigReduxState, + state: GitGlobalReduxState, action: PayloadAction<GitAsyncErrorPayload>, ) => { const { error } = action.payload; diff --git a/app/client/src/git/store/actions/updateLocalProfileActions.ts b/app/client/src/git/store/actions/updateLocalProfileActions.ts index 717bb388cb9b..84ac561a5026 100644 --- a/app/client/src/git/store/actions/updateLocalProfileActions.ts +++ b/app/client/src/git/store/actions/updateLocalProfileActions.ts @@ -1,4 +1,4 @@ -import { createSingleArtifactAction } from "../helpers/createSingleArtifactAction"; +import { createArtifactAction } from "../helpers/createArtifactAction"; import type { GitAsyncErrorPayload } from "../types"; import type { UpdateLocalProfileRequestParams } from "git/requests/updateLocalProfileRequest.types"; @@ -6,23 +6,21 @@ export interface UpdateLocalProfileInitPayload extends UpdateLocalProfileRequestParams {} export const updateLocalProfileInitAction = - createSingleArtifactAction<UpdateLocalProfileInitPayload>((state) => { + createArtifactAction<UpdateLocalProfileInitPayload>((state) => { state.apiResponses.updateLocalProfile.loading = true; state.apiResponses.updateLocalProfile.error = null; return state; }); -export const updateLocalProfileSuccessAction = createSingleArtifactAction( - (state) => { - state.apiResponses.updateLocalProfile.loading = false; +export const updateLocalProfileSuccessAction = createArtifactAction((state) => { + state.apiResponses.updateLocalProfile.loading = false; - return state; - }, -); + return state; +}); export const updateLocalProfileErrorAction = - createSingleArtifactAction<GitAsyncErrorPayload>((state, action) => { + createArtifactAction<GitAsyncErrorPayload>((state, action) => { const { error } = action.payload; state.apiResponses.updateLocalProfile.loading = false; diff --git a/app/client/src/git/store/actions/updateProtectedBranchesActions.ts b/app/client/src/git/store/actions/updateProtectedBranchesActions.ts index 6e45bf0dcca5..a19926b673f9 100644 --- a/app/client/src/git/store/actions/updateProtectedBranchesActions.ts +++ b/app/client/src/git/store/actions/updateProtectedBranchesActions.ts @@ -1,19 +1,19 @@ import type { UpdateProtectedBranchesRequestParams } from "git/requests/updateProtectedBranchesRequest.types"; -import { createSingleArtifactAction } from "../helpers/createSingleArtifactAction"; +import { createArtifactAction } from "../helpers/createArtifactAction"; import type { GitArtifactErrorPayloadAction } from "../types"; export interface UpdateProtectedBranchesInitPayload extends UpdateProtectedBranchesRequestParams {} export const updateProtectedBranchesInitAction = - createSingleArtifactAction<UpdateProtectedBranchesInitPayload>((state) => { + createArtifactAction<UpdateProtectedBranchesInitPayload>((state) => { state.apiResponses.updateProtectedBranches.loading = true; state.apiResponses.updateProtectedBranches.error = null; return state; }); -export const updateProtectedBranchesSuccessAction = createSingleArtifactAction( +export const updateProtectedBranchesSuccessAction = createArtifactAction( (state) => { state.apiResponses.updateProtectedBranches.loading = false; @@ -21,7 +21,7 @@ export const updateProtectedBranchesSuccessAction = createSingleArtifactAction( }, ); -export const updateProtectedBranchesErrorAction = createSingleArtifactAction( +export const updateProtectedBranchesErrorAction = createArtifactAction( (state, action: GitArtifactErrorPayloadAction) => { const { error } = action.payload; diff --git a/app/client/src/git/store/gitArtifactSlice.ts b/app/client/src/git/store/gitArtifactSlice.ts index 924785f80c76..15bbb4de65d2 100644 --- a/app/client/src/git/store/gitArtifactSlice.ts +++ b/app/client/src/git/store/gitArtifactSlice.ts @@ -1,5 +1,5 @@ import { createSlice } from "@reduxjs/toolkit"; -import type { GitArtifactReduxState } from "./types"; +import type { GitArtifactRootReduxState } from "./types"; import { mountAction, unmountAction } from "./actions/mountActions"; import { connectErrorAction, @@ -62,6 +62,7 @@ import { openDisconnectModalAction, closeDisconnectModalAction, toggleAutocommitDisableModalAction, + toggleConnectSuccessModalAction, } from "./actions/uiActions"; import { checkoutBranchErrorAction, @@ -119,11 +120,6 @@ import { disconnectInitAction, disconnectSuccessAction, } from "./actions/disconnectActions"; -import { - gitImportErrorAction, - gitImportInitAction, - gitImportSuccessAction, -} from "./actions/gitImportActions"; import { fetchSSHKeyErrorAction, fetchSSHKeyInitAction, @@ -137,7 +133,7 @@ import { resetGenerateSSHKeyAction, } from "./actions/generateSSHKeyActions"; -const initialState: GitArtifactReduxState = {}; +const initialState: GitArtifactRootReduxState = {}; export const gitArtifactSlice = createSlice({ name: "git/artifact", @@ -156,9 +152,6 @@ export const gitArtifactSlice = createSlice({ connectInit: connectInitAction, connectSuccess: connectSuccessAction, connectError: connectErrorAction, - gitImportInit: gitImportInitAction, - gitImportSuccess: gitImportSuccessAction, - gitImportError: gitImportErrorAction, fetchSSHKeyInit: fetchSSHKeyInitAction, fetchSSHKeySuccess: fetchSSHKeySuccessAction, fetchSSHKeyError: fetchSSHKeyErrorAction, @@ -171,6 +164,7 @@ export const gitArtifactSlice = createSlice({ disconnectSuccess: disconnectSuccessAction, disconnectError: disconnectErrorAction, toggleConnectModal: toggleConnectModalAction, + toggleConnectSuccessModal: toggleConnectSuccessModalAction, openDisconnectModal: openDisconnectModalAction, closeDisconnectModal: closeDisconnectModalAction, toggleRepoLimitErrorModal: toggleRepoLimitErrorModalAction, diff --git a/app/client/src/git/store/gitConfigSlice.ts b/app/client/src/git/store/gitConfigSlice.ts deleted file mode 100644 index a07a45d9730b..000000000000 --- a/app/client/src/git/store/gitConfigSlice.ts +++ /dev/null @@ -1,29 +0,0 @@ -import { createSlice } from "@reduxjs/toolkit"; -import { - fetchGlobalProfileErrorAction, - fetchGlobalProfileInitAction, - fetchGlobalProfileSuccessAction, -} from "./actions/fetchGlobalProfileActions"; -import { - updateGlobalProfileErrorAction, - updateGlobalProfileInitAction, - updateGlobalProfileSuccessAction, -} from "./actions/updateGlobalProfileActions"; -import { gitConfigInitialState } from "./helpers/gitConfigInitialState"; - -export const gitConfigSlice = createSlice({ - name: "git/config", - initialState: gitConfigInitialState, - reducers: { - fetchGlobalProfileInit: fetchGlobalProfileInitAction, - fetchGlobalProfileSuccess: fetchGlobalProfileSuccessAction, - fetchGlobalProfileError: fetchGlobalProfileErrorAction, - updateGlobalProfileInit: updateGlobalProfileInitAction, - updateGlobalProfileSuccess: updateGlobalProfileSuccessAction, - updateGlobalProfileError: updateGlobalProfileErrorAction, - }, -}); - -export const gitConfigActions = gitConfigSlice.actions; - -export const gitConfigReducer = gitConfigSlice.reducer; diff --git a/app/client/src/git/store/gitGlobalSlice.ts b/app/client/src/git/store/gitGlobalSlice.ts new file mode 100644 index 000000000000..4a26f5d6132f --- /dev/null +++ b/app/client/src/git/store/gitGlobalSlice.ts @@ -0,0 +1,49 @@ +import { createSlice } from "@reduxjs/toolkit"; +import { + fetchGlobalProfileErrorAction, + fetchGlobalProfileInitAction, + fetchGlobalProfileSuccessAction, +} from "./actions/fetchGlobalProfileActions"; +import { + updateGlobalProfileErrorAction, + updateGlobalProfileInitAction, + updateGlobalProfileSuccessAction, +} from "./actions/updateGlobalProfileActions"; +import { gitGlobalInitialState } from "./helpers/initialState"; +import { toggleImportModalAction } from "./actions/uiActions"; +import { + gitImportErrorAction, + gitImportInitAction, + gitImportSuccessAction, +} from "./actions/gitImportActions"; +import { + fetchGlobalSSHKeyErrorAction, + fetchGlobalSSHKeyInitAction, + fetchGlobalSSHKeySuccessAction, + resetGlobalSSHKeyAction, +} from "./actions/fetchGlobalSSHKeyActions"; + +export const gitGlobalSlice = createSlice({ + name: "git/config", + initialState: gitGlobalInitialState, + reducers: { + fetchGlobalProfileInit: fetchGlobalProfileInitAction, + fetchGlobalProfileSuccess: fetchGlobalProfileSuccessAction, + fetchGlobalProfileError: fetchGlobalProfileErrorAction, + updateGlobalProfileInit: updateGlobalProfileInitAction, + updateGlobalProfileSuccess: updateGlobalProfileSuccessAction, + updateGlobalProfileError: updateGlobalProfileErrorAction, + fetchGlobalSSHKeyInit: fetchGlobalSSHKeyInitAction, + fetchGlobalSSHKeySuccess: fetchGlobalSSHKeySuccessAction, + fetchGlobalSSHKeyError: fetchGlobalSSHKeyErrorAction, + resetGlobalSSHKey: resetGlobalSSHKeyAction, + gitImportInit: gitImportInitAction, + gitImportSuccess: gitImportSuccessAction, + gitImportError: gitImportErrorAction, + toggleImportModal: toggleImportModalAction, + }, +}); + +export const gitGlobalActions = gitGlobalSlice.actions; + +export const gitGlobalReducer = gitGlobalSlice.reducer; diff --git a/app/client/src/git/store/helpers/createArtifactAction.ts b/app/client/src/git/store/helpers/createArtifactAction.ts new file mode 100644 index 000000000000..c138af710d53 --- /dev/null +++ b/app/client/src/git/store/helpers/createArtifactAction.ts @@ -0,0 +1,35 @@ +import type { + GitArtifactBasePayload, + GitArtifactPayloadAction, + GitArtifactReduxState, + GitArtifactRootReduxState, +} from "../types"; +import { gitArtifactInitialState } from "./initialState"; + +type ArtifactStateCb<T> = ( + artifactState: GitArtifactReduxState, + action: GitArtifactPayloadAction<T>, +) => GitArtifactReduxState; + +export const createArtifactAction = <T = GitArtifactBasePayload>( + artifactStateCb: ArtifactStateCb<T>, +) => { + return ( + state: GitArtifactRootReduxState, + action: GitArtifactPayloadAction<T>, + ) => { + const { artifactType, baseArtifactId } = action.payload.artifactDef; + + state[artifactType] ??= {}; + state[artifactType][baseArtifactId] ??= gitArtifactInitialState; + + const artifactState = state[artifactType][baseArtifactId]; + + state[artifactType][baseArtifactId] = artifactStateCb( + artifactState, + action, + ); + + return state; + }; +}; diff --git a/app/client/src/git/store/helpers/createSingleArtifactAction.ts b/app/client/src/git/store/helpers/createSingleArtifactAction.ts deleted file mode 100644 index 2e0642959be8..000000000000 --- a/app/client/src/git/store/helpers/createSingleArtifactAction.ts +++ /dev/null @@ -1,35 +0,0 @@ -import type { - GitArtifactBasePayload, - GitArtifactPayloadAction, - GitArtifactReduxState, - GitSingleArtifactReduxState, -} from "../types"; -import { gitSingleArtifactInitialState } from "./gitSingleArtifactInitialState"; - -type SingleArtifactStateCb<T> = ( - singleArtifactState: GitSingleArtifactReduxState, - action: GitArtifactPayloadAction<T>, -) => GitSingleArtifactReduxState; - -export const createSingleArtifactAction = <T = GitArtifactBasePayload>( - singleArtifactStateCb: SingleArtifactStateCb<T>, -) => { - return ( - state: GitArtifactReduxState, - action: GitArtifactPayloadAction<T>, - ) => { - const { artifactType, baseArtifactId } = action.payload; - - state[artifactType] ??= {}; - state[artifactType][baseArtifactId] ??= gitSingleArtifactInitialState; - - const singleArtifactState = state[artifactType][baseArtifactId]; - - state[artifactType][baseArtifactId] = singleArtifactStateCb( - singleArtifactState, - action, - ); - - return state; - }; -}; diff --git a/app/client/src/git/store/helpers/gitConfigInitialState.ts b/app/client/src/git/store/helpers/gitConfigInitialState.ts deleted file mode 100644 index 7017399dfb16..000000000000 --- a/app/client/src/git/store/helpers/gitConfigInitialState.ts +++ /dev/null @@ -1,13 +0,0 @@ -import type { GitConfigReduxState } from "../types"; - -export const gitConfigInitialState: GitConfigReduxState = { - globalProfile: { - value: null, - loading: false, - error: null, - }, - updateGlobalProfile: { - loading: false, - error: null, - }, -}; diff --git a/app/client/src/git/store/helpers/gitSingleArtifactInitialState.ts b/app/client/src/git/store/helpers/gitSingleArtifactInitialState.ts deleted file mode 100644 index b17c93a126cb..000000000000 --- a/app/client/src/git/store/helpers/gitSingleArtifactInitialState.ts +++ /dev/null @@ -1,138 +0,0 @@ -import { - gitArtifactAPIResponsesInitialState as gitArtifactAPIResponsesInitialStateExtended, - gitArtifactUIInitialState as gitArtifactUIInitialStateExtended, -} from "git/ee/store/helpers/initialState"; -import { GitOpsTab, GitSettingsTab } from "../../constants/enums"; -import type { - GitSingleArtifactAPIResponsesReduxState, - GitSingleArtifactUIReduxState, - GitSingleArtifactReduxState, -} from "../types"; - -const gitSingleArtifactInitialUIState: GitSingleArtifactUIReduxState = { - connectModalOpen: false, - disconnectBaseArtifactId: null, - disconnectArtifactName: null, - branchPopupOpen: false, - checkoutDestBranch: null, - opsModalOpen: false, - opsModalTab: GitOpsTab.Deploy, - settingsModalOpen: false, - settingsModalTab: GitSettingsTab.General, - autocommitDisableModalOpen: false, - autocommitPolling: false, - conflictErrorModalOpen: false, - repoLimitErrorModalOpen: false, - // EE - ...gitArtifactUIInitialStateExtended, -}; - -const gitSingleArtifactInitialAPIResponses: GitSingleArtifactAPIResponsesReduxState = - { - metadata: { - value: null, - loading: false, - error: null, - }, - connect: { - loading: false, - error: null, - }, - gitImport: { - loading: false, - error: null, - }, - status: { - value: null, - loading: false, - error: null, - }, - commit: { - loading: false, - error: null, - }, - pull: { - loading: false, - error: null, - }, - discard: { - loading: false, - error: null, - }, - mergeStatus: { - value: null, - loading: false, - error: null, - }, - merge: { - loading: false, - error: null, - }, - branches: { - value: null, - loading: false, - error: null, - }, - checkoutBranch: { - loading: false, - error: null, - }, - createBranch: { - loading: false, - error: null, - }, - deleteBranch: { - loading: false, - error: null, - }, - localProfile: { - value: null, - loading: false, - error: null, - }, - updateLocalProfile: { - loading: false, - error: null, - }, - disconnect: { - loading: false, - error: null, - }, - protectedBranches: { - value: null, - loading: false, - error: null, - }, - updateProtectedBranches: { - loading: false, - error: null, - }, - autocommitProgress: { - loading: false, - error: null, - }, - toggleAutocommit: { - loading: false, - error: null, - }, - triggerAutocommit: { - loading: false, - error: null, - }, - generateSSHKey: { - loading: false, - error: null, - }, - sshKey: { - value: null, - loading: false, - error: null, - }, - // EE - ...gitArtifactAPIResponsesInitialStateExtended, - }; - -export const gitSingleArtifactInitialState: GitSingleArtifactReduxState = { - ui: gitSingleArtifactInitialUIState, - apiResponses: gitSingleArtifactInitialAPIResponses, -}; diff --git a/app/client/src/git/store/helpers/initialState.ts b/app/client/src/git/store/helpers/initialState.ts new file mode 100644 index 000000000000..382833be2782 --- /dev/null +++ b/app/client/src/git/store/helpers/initialState.ts @@ -0,0 +1,157 @@ +import { + gitArtifactAPIResponsesInitialState as gitArtifactAPIResponsesInitialStateExtended, + gitArtifactUIInitialState as gitArtifactUIInitialStateExtended, +} from "git/ee/store/helpers/initialState"; +import { GitOpsTab, GitSettingsTab } from "../../constants/enums"; +import type { + GitArtifactAPIResponsesReduxState, + GitArtifactUIReduxState, + GitArtifactReduxState, + GitGlobalReduxState, +} from "../types"; + +const gitArtifactInitialUIState: GitArtifactUIReduxState = { + connectModalOpen: false, + connectSuccessModalOpen: false, + disconnectBaseArtifactId: null, + disconnectArtifactName: null, + branchPopupOpen: false, + checkoutDestBranch: null, + opsModalOpen: false, + opsModalTab: GitOpsTab.Deploy, + settingsModalOpen: false, + settingsModalTab: GitSettingsTab.General, + autocommitDisableModalOpen: false, + autocommitPolling: false, + conflictErrorModalOpen: false, + repoLimitErrorModalOpen: false, + // EE + ...gitArtifactUIInitialStateExtended, +}; + +const gitArtifactInitialAPIResponses: GitArtifactAPIResponsesReduxState = { + metadata: { + value: null, + loading: false, + error: null, + }, + connect: { + loading: false, + error: null, + }, + status: { + value: null, + loading: false, + error: null, + }, + commit: { + loading: false, + error: null, + }, + pull: { + loading: false, + error: null, + }, + discard: { + loading: false, + error: null, + }, + mergeStatus: { + value: null, + loading: false, + error: null, + }, + merge: { + loading: false, + error: null, + }, + branches: { + value: null, + loading: false, + error: null, + }, + checkoutBranch: { + loading: false, + error: null, + }, + createBranch: { + loading: false, + error: null, + }, + deleteBranch: { + loading: false, + error: null, + }, + localProfile: { + value: null, + loading: false, + error: null, + }, + updateLocalProfile: { + loading: false, + error: null, + }, + disconnect: { + loading: false, + error: null, + }, + protectedBranches: { + value: null, + loading: false, + error: null, + }, + updateProtectedBranches: { + loading: false, + error: null, + }, + autocommitProgress: { + loading: false, + error: null, + }, + toggleAutocommit: { + loading: false, + error: null, + }, + triggerAutocommit: { + loading: false, + error: null, + }, + generateSSHKey: { + loading: false, + error: null, + }, + sshKey: { + value: null, + loading: false, + error: null, + }, + // EE + ...gitArtifactAPIResponsesInitialStateExtended, +}; + +export const gitArtifactInitialState: GitArtifactReduxState = { + ui: gitArtifactInitialUIState, + apiResponses: gitArtifactInitialAPIResponses, +}; + +export const gitGlobalInitialState: GitGlobalReduxState = { + globalProfile: { + value: null, + loading: false, + error: null, + }, + updateGlobalProfile: { + loading: false, + error: null, + }, + globalSSHKey: { + value: null, + loading: false, + error: null, + }, + gitImport: { + loading: false, + error: null, + }, + isImportModalOpen: false, +}; diff --git a/app/client/src/git/store/index.ts b/app/client/src/git/store/index.ts index f5337e564f97..6d210139ada4 100644 --- a/app/client/src/git/store/index.ts +++ b/app/client/src/git/store/index.ts @@ -1,8 +1,8 @@ import { combineReducers } from "@reduxjs/toolkit"; import { gitArtifactReducer } from "./gitArtifactSlice"; -import { gitConfigReducer } from "./gitConfigSlice"; +import { gitGlobalReducer } from "./gitGlobalSlice"; export const gitReducer = combineReducers({ artifacts: gitArtifactReducer, - config: gitConfigReducer, + global: gitGlobalReducer, }); diff --git a/app/client/src/git/store/selectors/gitSingleArtifactSelectors.ts b/app/client/src/git/store/selectors/gitArtifactSelectors.ts similarity index 92% rename from app/client/src/git/store/selectors/gitSingleArtifactSelectors.ts rename to app/client/src/git/store/selectors/gitArtifactSelectors.ts index 845a2cfe41fe..5bf8267df889 100644 --- a/app/client/src/git/store/selectors/gitSingleArtifactSelectors.ts +++ b/app/client/src/git/store/selectors/gitArtifactSelectors.ts @@ -1,10 +1,4 @@ -import type { GitArtifactType } from "git/constants/enums"; -import type { GitRootState } from "../types"; - -export interface GitArtifactDef { - artifactType: keyof typeof GitArtifactType; - baseArtifactId: string; -} +import type { GitArtifactDef, GitRootState } from "../types"; export const selectGitArtifact = ( state: GitRootState, @@ -21,7 +15,7 @@ export const selectMetadataState = ( artifactDef: GitArtifactDef, ) => selectGitArtifact(state, artifactDef)?.apiResponses.metadata; -export const selectGitConnected = ( +export const selectConnected = ( state: GitRootState, artifactDef: GitArtifactDef, ) => !!selectMetadataState(state, artifactDef)?.value; @@ -32,11 +26,6 @@ export const selectConnectState = ( artifactDef: GitArtifactDef, ) => selectGitArtifact(state, artifactDef)?.apiResponses.connect; -export const selectGitImportState = ( - state: GitRootState, - artifactDef: GitArtifactDef, -) => selectGitArtifact(state, artifactDef)?.apiResponses.gitImport; - export const selectFetchSSHKeysState = ( state: GitRootState, artifactDef: GitArtifactDef, @@ -52,6 +41,11 @@ export const selectConnectModalOpen = ( artifactDef: GitArtifactDef, ) => selectGitArtifact(state, artifactDef)?.ui.connectModalOpen; +export const selectConnectSuccessModalOpen = ( + state: GitRootState, + artifactDef: GitArtifactDef, +) => selectGitArtifact(state, artifactDef)?.ui.connectSuccessModalOpen; + export const selectDisconnectState = ( state: GitRootState, artifactDef: GitArtifactDef, @@ -117,11 +111,14 @@ export const selectConflictErrorModalOpen = ( export const selectCurrentBranch = ( state: GitRootState, + // need this to preserve interface + // eslint-disable-next-line @typescript-eslint/no-unused-vars artifactDef: GitArtifactDef, ) => { - const gitMetadataState = selectMetadataState(state, artifactDef).value; - - return gitMetadataState?.branchName; + return ( + state?.ui?.applications?.currentApplication?.gitApplicationMetadata + ?.branchName ?? null + ); }; export const selectFetchBranchesState = ( @@ -220,10 +217,8 @@ export const selectProtectedMode = ( artifactDef: GitArtifactDef, ) => { const currentBranch = selectCurrentBranch(state, artifactDef); - const protectedBranches = selectFetchProtectedBranchesState( - state, - artifactDef, - ).value; + const protectedBranches = + selectFetchProtectedBranchesState(state, artifactDef)?.value ?? []; return protectedBranches?.includes(currentBranch ?? "") ?? false; }; diff --git a/app/client/src/git/store/selectors/gitConfigSelectors.ts b/app/client/src/git/store/selectors/gitConfigSelectors.ts deleted file mode 100644 index be31a23cda5e..000000000000 --- a/app/client/src/git/store/selectors/gitConfigSelectors.ts +++ /dev/null @@ -1,12 +0,0 @@ -import type { GitRootState } from "../types"; - -export const selectGitConfig = (state: GitRootState) => { - return state.git.config; -}; - -// global profile -export const selectFetchGlobalProfileState = (state: GitRootState) => - selectGitConfig(state).globalProfile; - -export const selectUpdateGlobalProfileState = (state: GitRootState) => - selectGitConfig(state).updateGlobalProfile; diff --git a/app/client/src/git/store/selectors/gitGlobalSelectors.ts b/app/client/src/git/store/selectors/gitGlobalSelectors.ts new file mode 100644 index 000000000000..1d1fdb555d0c --- /dev/null +++ b/app/client/src/git/store/selectors/gitGlobalSelectors.ts @@ -0,0 +1,21 @@ +import type { GitRootState } from "../types"; + +export const selectGitGlobal = (state: GitRootState) => { + return state.git.global; +}; + +// global profile +export const selectFetchGlobalProfileState = (state: GitRootState) => + selectGitGlobal(state).globalProfile; + +export const selectUpdateGlobalProfileState = (state: GitRootState) => + selectGitGlobal(state).updateGlobalProfile; + +export const selectImportModalOpen = (state: GitRootState) => + selectGitGlobal(state).isImportModalOpen; + +export const selectGitImportState = (state: GitRootState) => + selectGitGlobal(state).gitImport; + +export const selectFetchGlobalSSHKeyState = (state: GitRootState) => + selectGitGlobal(state).globalSSHKey; diff --git a/app/client/src/git/store/types.ts b/app/client/src/git/store/types.ts index ccb67a2e7a8b..90a2e72998a5 100644 --- a/app/client/src/git/store/types.ts +++ b/app/client/src/git/store/types.ts @@ -17,6 +17,7 @@ import type { GitArtifactAPIResponsesReduxState as GitArtifactAPIResponsesReduxStateExtended, GitArtifactUIReduxState as GitArtifactUIReduxStateExtended, } from "git/ee/store/types"; +import type { FetchGlobalSSHKeyResponseData } from "git/requests/fetchGlobalSSHKeyRequest.types"; export interface GitApiError extends ApiResponseError { errorType?: string; @@ -33,11 +34,10 @@ export interface GitAsyncStateWithoutValue { loading: boolean; error: GitApiError | null; } -export interface GitSingleArtifactAPIResponsesReduxState +export interface GitArtifactAPIResponsesReduxState extends GitArtifactAPIResponsesReduxStateExtended { metadata: GitAsyncState<FetchMetadataResponseData>; connect: GitAsyncStateWithoutValue; - gitImport: GitAsyncStateWithoutValue; status: GitAsyncState<FetchStatusResponseData>; commit: GitAsyncStateWithoutValue; pull: GitAsyncStateWithoutValue; @@ -60,9 +60,10 @@ export interface GitSingleArtifactAPIResponsesReduxState generateSSHKey: GitAsyncStateWithoutValue; } -export interface GitSingleArtifactUIReduxState +export interface GitArtifactUIReduxState extends GitArtifactUIReduxStateExtended { connectModalOpen: boolean; + connectSuccessModalOpen: boolean; disconnectBaseArtifactId: string | null; disconnectArtifactName: string | null; branchPopupOpen: boolean; @@ -76,30 +77,51 @@ export interface GitSingleArtifactUIReduxState conflictErrorModalOpen: boolean; repoLimitErrorModalOpen: boolean; } -export interface GitSingleArtifactReduxState { - ui: GitSingleArtifactUIReduxState; - apiResponses: GitSingleArtifactAPIResponsesReduxState; -} +export interface GitArtifactDef { + artifactType: keyof typeof GitArtifactType; + baseArtifactId: string; +} export interface GitArtifactReduxState { - [key: string]: Record<string, GitSingleArtifactReduxState>; + ui: GitArtifactUIReduxState; + apiResponses: GitArtifactAPIResponsesReduxState; } -export interface GitConfigReduxState { +export interface GitGlobalReduxState { globalProfile: GitAsyncState<FetchGlobalProfileResponseData>; updateGlobalProfile: GitAsyncStateWithoutValue; + gitImport: GitAsyncStateWithoutValue; + globalSSHKey: GitAsyncState<FetchGlobalSSHKeyResponseData>; + // ui + isImportModalOpen: boolean; +} + +export type GitArtifactRootReduxState = Record< + string, + Record<string, GitArtifactReduxState> +>; + +export interface GitReduxState { + artifacts: GitArtifactRootReduxState; + global: GitGlobalReduxState; } export interface GitRootState { - git: { - artifacts: GitArtifactReduxState; - config: GitConfigReduxState; + // will have to remove this later, once metadata is fixed + ui: { + applications: { + currentApplication?: { + gitApplicationMetadata?: { + branchName: string; + }; + }; + }; }; + git: GitReduxState; } export interface GitArtifactBasePayload { - artifactType: keyof typeof GitArtifactType; - baseArtifactId: string; + artifactDef: GitArtifactDef; } export interface GitAsyncErrorPayload { diff --git a/app/client/src/layoutSystems/anvil/common/hooks/detachedWidgetHooks.ts b/app/client/src/layoutSystems/anvil/common/hooks/detachedWidgetHooks.ts index c3ad4a82bd8d..6bf86d26a55d 100644 --- a/app/client/src/layoutSystems/anvil/common/hooks/detachedWidgetHooks.ts +++ b/app/client/src/layoutSystems/anvil/common/hooks/detachedWidgetHooks.ts @@ -1,7 +1,6 @@ import { useWidgetBorderStyles } from "./useWidgetBorderStyles"; import { useDispatch, useSelector } from "react-redux"; import { useWidgetSelection } from "utils/hooks/useWidgetSelection"; -import { combinedPreviewModeSelector } from "selectors/editorSelectors"; import { SELECT_ANVIL_WIDGET_CUSTOM_EVENT } from "layoutSystems/anvil/utils/constants"; import log from "loglevel"; import { useEffect, useMemo } from "react"; @@ -9,6 +8,7 @@ import { getAnvilWidgetDOMId } from "layoutSystems/common/utils/LayoutElementPos import { getCurrentlyOpenAnvilDetachedWidgets } from "layoutSystems/anvil/integrations/modalSelectors"; import { getCanvasWidgetsStructure } from "ee/selectors/entitiesSelector"; import type { CanvasWidgetStructure } from "WidgetProvider/constants"; +import { selectCombinedPreviewMode } from "selectors/gitModSelectors"; /** * This hook is used to select and focus on a detached widget * As detached widgets are outside of the layout flow, we need to access the correct element in the DOM @@ -17,7 +17,7 @@ import type { CanvasWidgetStructure } from "WidgetProvider/constants"; */ export function useHandleDetachedWidgetSelect(widgetId: string) { const dispatch = useDispatch(); - const isPreviewMode = useSelector(combinedPreviewModeSelector); + const isPreviewMode = useSelector(selectCombinedPreviewMode); const className = getAnvilWidgetDOMId(widgetId); const element = document.querySelector(`.${className}`); diff --git a/app/client/src/layoutSystems/anvil/common/hooks/useWidgetBorderStyles.ts b/app/client/src/layoutSystems/anvil/common/hooks/useWidgetBorderStyles.ts index fea0cc19424c..1213f9134b3a 100644 --- a/app/client/src/layoutSystems/anvil/common/hooks/useWidgetBorderStyles.ts +++ b/app/client/src/layoutSystems/anvil/common/hooks/useWidgetBorderStyles.ts @@ -7,8 +7,8 @@ import { getWidgetsDistributingSpace, } from "layoutSystems/anvil/integrations/selectors"; import { useSelector } from "react-redux"; -import { combinedPreviewModeSelector } from "selectors/editorSelectors"; import { isWidgetFocused, isWidgetSelected } from "selectors/widgetSelectors"; +import { selectCombinedPreviewMode } from "selectors/gitModSelectors"; export function useWidgetBorderStyles(widgetId: string, widgetType: string) { /** Selectors */ @@ -32,7 +32,7 @@ export function useWidgetBorderStyles(widgetId: string, widgetType: string) { const widgetsEffectedBySpaceDistribution = useSelector( getWidgetsDistributingSpace, ); - const isPreviewMode = useSelector(combinedPreviewModeSelector); + const isPreviewMode = useSelector(selectCombinedPreviewMode); /** EO selectors */ diff --git a/app/client/src/layoutSystems/anvil/editor/AnvilEditorWidgetOnion.tsx b/app/client/src/layoutSystems/anvil/editor/AnvilEditorWidgetOnion.tsx index f5a6505a2be2..839c055f0f40 100644 --- a/app/client/src/layoutSystems/anvil/editor/AnvilEditorWidgetOnion.tsx +++ b/app/client/src/layoutSystems/anvil/editor/AnvilEditorWidgetOnion.tsx @@ -4,7 +4,7 @@ import type { BaseWidgetProps } from "widgets/BaseWidgetHOC/withBaseWidgetHOC"; import { AnvilWidgetComponent } from "../common/widgetComponent/AnvilWidgetComponent"; import { getWidgetSizeConfiguration } from "../utils/widgetUtils"; import { useSelector } from "react-redux"; -import { combinedPreviewModeSelector } from "selectors/editorSelectors"; +import { selectCombinedPreviewMode } from "selectors/gitModSelectors"; import { AnvilEditorFlexComponent } from "./AnvilEditorFlexComponent"; import { AnvilFlexComponent } from "../common/AnvilFlexComponent"; import { SKELETON_WIDGET_TYPE } from "constants/WidgetConstants"; @@ -25,7 +25,7 @@ import { SKELETON_WIDGET_TYPE } from "constants/WidgetConstants"; * @returns Enhanced Widget */ export const AnvilEditorWidgetOnion = (props: BaseWidgetProps) => { - const isPreviewMode = useSelector(combinedPreviewModeSelector); + const isPreviewMode = useSelector(selectCombinedPreviewMode); const { widgetSize, WidgetWrapper } = useMemo(() => { return { widgetSize: getWidgetSizeConfiguration(props.type, props, isPreviewMode), diff --git a/app/client/src/layoutSystems/anvil/editor/hooks/useAnvilWidgetHover.ts b/app/client/src/layoutSystems/anvil/editor/hooks/useAnvilWidgetHover.ts index abdb88561f68..e51d921bf1bd 100644 --- a/app/client/src/layoutSystems/anvil/editor/hooks/useAnvilWidgetHover.ts +++ b/app/client/src/layoutSystems/anvil/editor/hooks/useAnvilWidgetHover.ts @@ -2,7 +2,7 @@ import type { AppState } from "ee/reducers"; import { getAnvilSpaceDistributionStatus } from "layoutSystems/anvil/integrations/selectors"; import { useCallback, useEffect } from "react"; import { useSelector } from "react-redux"; -import { combinedPreviewModeSelector } from "selectors/editorSelectors"; +import { selectCombinedPreviewMode } from "selectors/gitModSelectors"; import { isWidgetFocused } from "selectors/widgetSelectors"; import { useWidgetSelection } from "utils/hooks/useWidgetSelection"; @@ -12,7 +12,7 @@ export const useAnvilWidgetHover = ( ) => { // Retrieve state from the Redux store const isFocused = useSelector(isWidgetFocused(widgetId)); - const isPreviewMode = useSelector(combinedPreviewModeSelector); + const isPreviewMode = useSelector(selectCombinedPreviewMode); const isDistributingSpace = useSelector(getAnvilSpaceDistributionStatus); const isDragging = useSelector( (state: AppState) => state.ui.widgetDragResize.isDragging, diff --git a/app/client/src/layoutSystems/anvil/integrations/sagas/LayoutElementPositionsSaga.ts b/app/client/src/layoutSystems/anvil/integrations/sagas/LayoutElementPositionsSaga.ts index a882919710b1..2cddcc974bc8 100644 --- a/app/client/src/layoutSystems/anvil/integrations/sagas/LayoutElementPositionsSaga.ts +++ b/app/client/src/layoutSystems/anvil/integrations/sagas/LayoutElementPositionsSaga.ts @@ -8,7 +8,7 @@ import log from "loglevel"; import type { AppState } from "ee/reducers"; import { ReduxActionTypes } from "ee/constants/ReduxActionConstants"; import { APP_MODE } from "entities/App"; -import { combinedPreviewModeSelector } from "selectors/editorSelectors"; +import { selectCombinedPreviewMode } from "selectors/gitModSelectors"; import { getAppMode } from "ee/selectors/entitiesSelector"; import type { RefObject } from "react"; import { getAnvilSpaceDistributionStatus } from "../selectors"; @@ -87,7 +87,7 @@ function* readAndUpdateLayoutElementPositions() { // The positions are used only in the editor, so we should not be running this saga // in the viewer or the preview mode. - const isPreviewMode: boolean = yield select(combinedPreviewModeSelector); + const isPreviewMode: boolean = yield select(selectCombinedPreviewMode); const appMode: APP_MODE = yield select(getAppMode); if (isPreviewMode || appMode === APP_MODE.PUBLISHED) { diff --git a/app/client/src/layoutSystems/anvil/layoutComponents/components/zone/useZoneMinWidth.ts b/app/client/src/layoutSystems/anvil/layoutComponents/components/zone/useZoneMinWidth.ts index fe49ee655230..c8ba600c5fb6 100644 --- a/app/client/src/layoutSystems/anvil/layoutComponents/components/zone/useZoneMinWidth.ts +++ b/app/client/src/layoutSystems/anvil/layoutComponents/components/zone/useZoneMinWidth.ts @@ -3,22 +3,20 @@ import { ChildrenMapContext } from "layoutSystems/anvil/context/childrenMapConte import type { WidgetProps } from "widgets/BaseWidget"; import { RenderModes } from "constants/WidgetConstants"; import { useSelector } from "react-redux"; -import { - combinedPreviewModeSelector, - getRenderMode, -} from "selectors/editorSelectors"; +import { getRenderMode } from "selectors/editorSelectors"; import type { SizeConfig } from "WidgetProvider/constants"; import { getWidgetSizeConfiguration } from "layoutSystems/anvil/utils/widgetUtils"; import type { CanvasWidgetsReduxState } from "reducers/entityReducers/canvasWidgetsReducer"; import { getWidgets } from "sagas/selectors"; import isObject from "lodash/isObject"; +import { selectCombinedPreviewMode } from "selectors/gitModSelectors"; export function useZoneMinWidth() { const childrenMap: Record<string, WidgetProps> = useContext(ChildrenMapContext); const widgets: CanvasWidgetsReduxState = useSelector(getWidgets); const renderMode: RenderModes = useSelector(getRenderMode); - const isPreviewMode: boolean = useSelector(combinedPreviewModeSelector); + const isPreviewMode: boolean = useSelector(selectCombinedPreviewMode); if (renderMode === RenderModes.CANVAS && !isPreviewMode) return "auto"; diff --git a/app/client/src/layoutSystems/anvil/sectionSpaceDistributor/SectionSpaceDistributor.tsx b/app/client/src/layoutSystems/anvil/sectionSpaceDistributor/SectionSpaceDistributor.tsx index fd719bfd1f6f..25e94d38d9e8 100644 --- a/app/client/src/layoutSystems/anvil/sectionSpaceDistributor/SectionSpaceDistributor.tsx +++ b/app/client/src/layoutSystems/anvil/sectionSpaceDistributor/SectionSpaceDistributor.tsx @@ -2,7 +2,7 @@ import { getLayoutElementPositions } from "layoutSystems/common/selectors"; import type { LayoutElementPosition } from "layoutSystems/common/types"; import React, { useMemo } from "react"; import { useSelector } from "react-redux"; -import { combinedPreviewModeSelector } from "selectors/editorSelectors"; +import { selectCombinedPreviewMode } from "selectors/gitModSelectors"; import type { WidgetLayoutProps } from "../utils/anvilTypes"; import { getWidgetByID } from "sagas/selectors"; import { getDefaultSpaceDistributed } from "./utils/spaceRedistributionSagaUtils"; @@ -113,7 +113,7 @@ export const SectionSpaceDistributor = ( props: SectionSpaceDistributorProps, ) => { const { zones } = props; - const isPreviewMode = useSelector(combinedPreviewModeSelector); + const isPreviewMode = useSelector(selectCombinedPreviewMode); const isWidgetSelectionBlocked = useSelector(getWidgetSelectionBlock); const isDragging = useSelector( (state) => state.ui.widgetDragResize.isDragging, diff --git a/app/client/src/layoutSystems/anvil/viewer/AnvilViewerWidgetOnion.tsx b/app/client/src/layoutSystems/anvil/viewer/AnvilViewerWidgetOnion.tsx index 99ca7dddf492..763785755918 100644 --- a/app/client/src/layoutSystems/anvil/viewer/AnvilViewerWidgetOnion.tsx +++ b/app/client/src/layoutSystems/anvil/viewer/AnvilViewerWidgetOnion.tsx @@ -5,7 +5,7 @@ import { AnvilWidgetComponent } from "../common/widgetComponent/AnvilWidgetCompo import type { SizeConfig } from "WidgetProvider/constants"; import { getWidgetSizeConfiguration } from "../utils/widgetUtils"; import { useSelector } from "react-redux"; -import { combinedPreviewModeSelector } from "selectors/editorSelectors"; +import { selectCombinedPreviewMode } from "selectors/gitModSelectors"; /** * AnvilViewerWidgetOnion @@ -20,7 +20,7 @@ import { combinedPreviewModeSelector } from "selectors/editorSelectors"; * @returns Enhanced Widget */ export const AnvilViewerWidgetOnion = (props: BaseWidgetProps) => { - const isPreviewMode = useSelector(combinedPreviewModeSelector); + const isPreviewMode = useSelector(selectCombinedPreviewMode); const widgetSize: SizeConfig = useMemo( () => getWidgetSizeConfiguration(props.type, props, isPreviewMode), [isPreviewMode, props.type], diff --git a/app/client/src/layoutSystems/autolayout/common/FlexComponent.tsx b/app/client/src/layoutSystems/autolayout/common/FlexComponent.tsx index 20edbf4ce0d8..334ca9fd95ec 100644 --- a/app/client/src/layoutSystems/autolayout/common/FlexComponent.tsx +++ b/app/client/src/layoutSystems/autolayout/common/FlexComponent.tsx @@ -4,10 +4,7 @@ import styled from "styled-components"; import { WIDGET_PADDING } from "constants/WidgetConstants"; import { useSelector } from "react-redux"; -import { - combinedPreviewModeSelector, - snipingModeSelector, -} from "selectors/editorSelectors"; +import { snipingModeSelector } from "selectors/editorSelectors"; import { getIsResizing } from "selectors/widgetSelectors"; import { useClickToSelectWidget } from "utils/hooks/useClickToSelectWidget"; import { usePositionedContainerZIndex } from "utils/hooks/usePositionedContainerZIndex"; @@ -16,6 +13,7 @@ import { RESIZE_BORDER_BUFFER } from "layoutSystems/common/resizer/common"; import { checkIsDropTarget } from "WidgetProvider/factory/helpers"; import type { FlexComponentProps } from "../../autolayout/utils/types"; import { useHoverToFocusWidget } from "utils/hooks/useHoverToFocusWidget"; +import { selectCombinedPreviewMode } from "selectors/gitModSelectors"; const FlexWidget = styled.div` position: relative; @@ -58,7 +56,7 @@ export function FlexComponent(props: FlexComponentProps) { )} t--widget-${props.widgetName.toLowerCase()}`, [props.parentId, props.widgetId, props.widgetType, props.widgetName], ); - const isPreviewMode = useSelector(combinedPreviewModeSelector); + const isPreviewMode = useSelector(selectCombinedPreviewMode); const isResizing = useSelector(getIsResizing); const widgetDimensionsViewCss = { diff --git a/app/client/src/layoutSystems/common/dropTarget/DropTargetComponent.tsx b/app/client/src/layoutSystems/common/dropTarget/DropTargetComponent.tsx index d1df63825448..fcb93c9205a6 100644 --- a/app/client/src/layoutSystems/common/dropTarget/DropTargetComponent.tsx +++ b/app/client/src/layoutSystems/common/dropTarget/DropTargetComponent.tsx @@ -21,10 +21,7 @@ import { } from "actions/autoHeightActions"; import { useDispatch } from "react-redux"; import { getDragDetails } from "sagas/selectors"; -import { - combinedPreviewModeSelector, - getOccupiedSpacesSelectorForContainer, -} from "selectors/editorSelectors"; +import { getOccupiedSpacesSelectorForContainer } from "selectors/editorSelectors"; import { getCanvasSnapRows } from "utils/WidgetPropsUtils"; import { useAutoHeightUIState } from "utils/hooks/autoHeightUIHooks"; import { useShowPropertyPane } from "utils/hooks/dragResizeHooks"; @@ -42,6 +39,7 @@ import { import DragLayerComponent from "./DragLayerComponent"; import Onboarding from "./OnBoarding"; import { isDraggingBuildingBlockToCanvas } from "selectors/buildingBlocksSelectors"; +import { selectCombinedPreviewMode } from "selectors/gitModSelectors"; export type DropTargetComponentProps = PropsWithChildren<{ snapColumnSpace: number; @@ -196,7 +194,7 @@ function useUpdateRows( export function DropTargetComponent(props: DropTargetComponentProps) { // Get if this is in preview mode. - const isPreviewMode = useSelector(combinedPreviewModeSelector); + const isPreviewMode = useSelector(selectCombinedPreviewMode); const isAppSettingsPaneWithNavigationTabOpen = useSelector( getIsAppSettingsPaneWithNavigationTabOpen, ); diff --git a/app/client/src/layoutSystems/common/resizer/ModalResizableLayer.tsx b/app/client/src/layoutSystems/common/resizer/ModalResizableLayer.tsx index 559556bbbf42..1a516b9623fe 100644 --- a/app/client/src/layoutSystems/common/resizer/ModalResizableLayer.tsx +++ b/app/client/src/layoutSystems/common/resizer/ModalResizableLayer.tsx @@ -19,11 +19,9 @@ import { } from "./ResizeStyledComponents"; import type { UIElementSize } from "./ResizableUtils"; import { useModalWidth } from "widgets/ModalWidget/component/useModalWidth"; -import { - combinedPreviewModeSelector, - snipingModeSelector, -} from "selectors/editorSelectors"; +import { snipingModeSelector } from "selectors/editorSelectors"; import { getWidgetSelectionBlock } from "../../../selectors/ui"; +import { selectCombinedPreviewMode } from "selectors/gitModSelectors"; const minSize = 100; /** @@ -101,7 +99,7 @@ export const ModalResizableLayer = ({ widgetType: "MODAL_WIDGET", }); }; - const isPreviewMode = useSelector(combinedPreviewModeSelector); + const isPreviewMode = useSelector(selectCombinedPreviewMode); const isSnipingMode = useSelector(snipingModeSelector); const isWidgetSelectionBlocked = useSelector(getWidgetSelectionBlock); const enableResizing = diff --git a/app/client/src/layoutSystems/common/resizer/ResizableComponent.tsx b/app/client/src/layoutSystems/common/resizer/ResizableComponent.tsx index f0336f382b87..fb5aca05d16f 100644 --- a/app/client/src/layoutSystems/common/resizer/ResizableComponent.tsx +++ b/app/client/src/layoutSystems/common/resizer/ResizableComponent.tsx @@ -17,10 +17,7 @@ import { FixedLayoutResizable } from "layoutSystems/fixedlayout/common/resizer/F import { SelectionRequestType } from "sagas/WidgetSelectUtils"; import { getIsAutoLayout } from "selectors/canvasSelectors"; import { getIsAppSettingsPaneWithNavigationTabOpen } from "selectors/appSettingsPaneSelectors"; -import { - combinedPreviewModeSelector, - snipingModeSelector, -} from "selectors/editorSelectors"; +import { snipingModeSelector } from "selectors/editorSelectors"; import { getParentToOpenSelector, isWidgetFocused, @@ -69,6 +66,7 @@ import { getAltBlockWidgetSelection, getWidgetSelectionBlock, } from "selectors/ui"; +import { selectCombinedPreviewMode } from "selectors/gitModSelectors"; export type ResizableComponentProps = WidgetProps & { paddingOffset: number; @@ -83,7 +81,7 @@ export const ResizableComponent = memo(function ResizableComponent( const isAutoLayout = useSelector(getIsAutoLayout); const Resizable = isAutoLayout ? AutoLayoutResizable : FixedLayoutResizable; const isSnipingMode = useSelector(snipingModeSelector); - const isPreviewMode = useSelector(combinedPreviewModeSelector); + const isPreviewMode = useSelector(selectCombinedPreviewMode); const isWidgetSelectionBlock = useSelector(getWidgetSelectionBlock); const isAltWidgetSelectionBlock = useSelector(getAltBlockWidgetSelection); const isAppSettingsPaneWithNavigationTabOpen: boolean = useSelector( diff --git a/app/client/src/layoutSystems/common/utils/LayoutElementPositionsObserver/usePositionObserver.ts b/app/client/src/layoutSystems/common/utils/LayoutElementPositionsObserver/usePositionObserver.ts index 1d5a9c38f354..9c981c66f397 100644 --- a/app/client/src/layoutSystems/common/utils/LayoutElementPositionsObserver/usePositionObserver.ts +++ b/app/client/src/layoutSystems/common/utils/LayoutElementPositionsObserver/usePositionObserver.ts @@ -3,7 +3,7 @@ import { useEffect } from "react"; import { positionObserver } from "."; import { APP_MODE } from "entities/App"; import { useSelector } from "react-redux"; -import { combinedPreviewModeSelector } from "selectors/editorSelectors"; +import { selectCombinedPreviewMode } from "selectors/gitModSelectors"; import { getAppMode } from "ee/selectors/entitiesSelector"; import { getAnvilLayoutDOMId, getAnvilWidgetDOMId } from "./utils"; import { LayoutComponentTypes } from "layoutSystems/anvil/utils/anvilTypes"; @@ -13,7 +13,7 @@ export function useObserveDetachedWidget(widgetId: string) { // We don't need the observer in preview mode or the published app // This is because the positions need to be observed only to enable // editor features - const isPreviewMode = useSelector(combinedPreviewModeSelector); + const isPreviewMode = useSelector(selectCombinedPreviewMode); const appMode = useSelector(getAppMode); if (isPreviewMode || appMode === APP_MODE.PUBLISHED) { @@ -54,7 +54,7 @@ export function usePositionObserver( }, ref: RefObject<HTMLDivElement>, ) { - const isPreviewMode = useSelector(combinedPreviewModeSelector); + const isPreviewMode = useSelector(selectCombinedPreviewMode); const appMode = useSelector(getAppMode); useEffect(() => { diff --git a/app/client/src/layoutSystems/common/widgetName/index.tsx b/app/client/src/layoutSystems/common/widgetName/index.tsx index bb8c265946e5..8d5770b995a0 100644 --- a/app/client/src/layoutSystems/common/widgetName/index.tsx +++ b/app/client/src/layoutSystems/common/widgetName/index.tsx @@ -8,7 +8,6 @@ import { SelectionRequestType } from "sagas/WidgetSelectUtils"; import { getIsAppSettingsPaneWithNavigationTabOpen } from "selectors/appSettingsPaneSelectors"; import { hideErrors } from "selectors/debuggerSelectors"; import { - combinedPreviewModeSelector, getIsAutoLayout, snipingModeSelector, } from "selectors/editorSelectors"; @@ -31,6 +30,7 @@ import { RESIZE_BORDER_BUFFER } from "layoutSystems/common/resizer/common"; import { Layers } from "constants/Layers"; import memoize from "micro-memoize"; import { NavigationMethod } from "utils/history"; +import { selectCombinedPreviewMode } from "selectors/gitModSelectors"; const WidgetTypes = WidgetFactory.widgetTypes; @@ -78,7 +78,7 @@ interface WidgetNameComponentProps { export function WidgetNameComponent(props: WidgetNameComponentProps) { const dispatch = useDispatch(); const isSnipingMode = useSelector(snipingModeSelector); - const isPreviewMode = useSelector(combinedPreviewModeSelector); + const isPreviewMode = useSelector(selectCombinedPreviewMode); const isAppSettingsPaneWithNavigationTabOpen = useSelector( getIsAppSettingsPaneWithNavigationTabOpen, ); diff --git a/app/client/src/layoutSystems/fixedlayout/common/autoHeightOverlay/index.tsx b/app/client/src/layoutSystems/fixedlayout/common/autoHeightOverlay/index.tsx index 89519283f7cb..48015d2efff1 100644 --- a/app/client/src/layoutSystems/fixedlayout/common/autoHeightOverlay/index.tsx +++ b/app/client/src/layoutSystems/fixedlayout/common/autoHeightOverlay/index.tsx @@ -3,7 +3,7 @@ import type { CSSProperties } from "react"; import React, { memo } from "react"; import { useSelector } from "react-redux"; import { getIsAppSettingsPaneWithNavigationTabOpen } from "selectors/appSettingsPaneSelectors"; -import { combinedPreviewModeSelector } from "selectors/editorSelectors"; +import { selectCombinedPreviewMode } from "selectors/gitModSelectors"; import type { WidgetProps } from "widgets/BaseWidget"; import AutoHeightOverlayWithStateContext from "./AutoHeightOverlayWithStateContext"; @@ -31,7 +31,7 @@ const AutoHeightOverlayContainer: React.FC<AutoHeightOverlayContainerProps> = selectedWidgets, } = useSelector((state: AppState) => state.ui.widgetDragResize); - const isPreviewMode = useSelector(combinedPreviewModeSelector); + const isPreviewMode = useSelector(selectCombinedPreviewMode); const isAppSettingsPaneWithNavigationTabOpen = useSelector( getIsAppSettingsPaneWithNavigationTabOpen, ); diff --git a/app/client/src/layoutSystems/fixedlayout/editor/FixedLayoutCanvasArenas/CanvasSelectionArena.tsx b/app/client/src/layoutSystems/fixedlayout/editor/FixedLayoutCanvasArenas/CanvasSelectionArena.tsx index c0cf29167981..c299eaef18db 100644 --- a/app/client/src/layoutSystems/fixedlayout/editor/FixedLayoutCanvasArenas/CanvasSelectionArena.tsx +++ b/app/client/src/layoutSystems/fixedlayout/editor/FixedLayoutCanvasArenas/CanvasSelectionArena.tsx @@ -21,7 +21,6 @@ import { getIsDraggingForSelection, } from "selectors/canvasSelectors"; import { - combinedPreviewModeSelector, getCurrentApplicationLayout, getCurrentPageId, } from "selectors/editorSelectors"; @@ -31,6 +30,7 @@ import type { XYCord } from "layoutSystems/common/canvasArenas/ArenaTypes"; import { useCanvasDragToScroll } from "layoutSystems/common/canvasArenas/useCanvasDragToScroll"; import { StickyCanvasArena } from "layoutSystems/common/canvasArenas/StickyCanvasArena"; import { getWidgetSelectionBlock } from "../../../../selectors/ui"; +import { selectCombinedPreviewMode } from "selectors/gitModSelectors"; export interface SelectedArenaDimensions { top: number; @@ -71,7 +71,7 @@ export function CanvasSelectionArena({ (parentWidget && parentWidget.detachFromLayout) ); const appMode = useSelector(getAppMode); - const isPreviewMode = useSelector(combinedPreviewModeSelector); + const isPreviewMode = useSelector(selectCombinedPreviewMode); const isWidgetSelectionBlocked = useSelector(getWidgetSelectionBlock); const isAppSettingsPaneWithNavigationTabOpen = useSelector( getIsAppSettingsPaneWithNavigationTabOpen, diff --git a/app/client/src/pages/AppViewer/Navigation/Sidebar.tsx b/app/client/src/pages/AppViewer/Navigation/Sidebar.tsx index 3b6b80aa7328..5ad23ff2e567 100644 --- a/app/client/src/pages/AppViewer/Navigation/Sidebar.tsx +++ b/app/client/src/pages/AppViewer/Navigation/Sidebar.tsx @@ -12,10 +12,7 @@ import ShareButton from "./components/ShareButton"; import PrimaryCTA from "../PrimaryCTA"; import { useHref } from "pages/Editor/utils"; import { builderURL } from "ee/RouteBuilder"; -import { - combinedPreviewModeSelector, - getCurrentBasePageId, -} from "selectors/editorSelectors"; +import { getCurrentBasePageId } from "selectors/editorSelectors"; import type { User } from "constants/userConstants"; import SidebarProfileComponent from "./components/SidebarProfileComponent"; import CollapseButton from "./components/CollapseButton"; @@ -36,6 +33,7 @@ import MenuItemContainer from "./components/MenuItemContainer"; import BackToAppsButton from "./components/BackToAppsButton"; import { IDE_HEADER_HEIGHT } from "@appsmith/ads"; import { BOTTOM_BAR_HEIGHT } from "components/BottomBar/constants"; +import { selectCombinedPreviewMode } from "selectors/gitModSelectors"; interface SidebarProps { currentApplicationDetails?: ApplicationPayload; @@ -81,7 +79,7 @@ export function Sidebar(props: SidebarProps) { const isPinned = useSelector(getAppSidebarPinned); const [isOpen, setIsOpen] = useState(true); const { x } = useMouse(); - const isPreviewMode = useSelector(combinedPreviewModeSelector); + const isPreviewMode = useSelector(selectCombinedPreviewMode); const isAppSettingsPaneWithNavigationTabOpen = useSelector( getIsAppSettingsPaneWithNavigationTabOpen, ); diff --git a/app/client/src/pages/AppViewer/Navigation/TopInline.tsx b/app/client/src/pages/AppViewer/Navigation/TopInline.tsx index f15dd093ff21..af09e8497fd1 100644 --- a/app/client/src/pages/AppViewer/Navigation/TopInline.tsx +++ b/app/client/src/pages/AppViewer/Navigation/TopInline.tsx @@ -5,14 +5,12 @@ import MenuItem from "./components/MenuItem"; import { Container } from "./TopInline.styled"; import MenuItemContainer from "./components/MenuItemContainer"; import MoreDropdownButton from "./components/MoreDropdownButton"; -import { - combinedPreviewModeSelector, - getCanvasWidth, -} from "selectors/editorSelectors"; +import { getCanvasWidth } from "selectors/editorSelectors"; import { useSelector } from "react-redux"; import { getIsAppSettingsPaneWithNavigationTabOpen } from "selectors/appSettingsPaneSelectors"; import { throttle } from "lodash"; import type { NavigationProps } from "./constants"; +import { selectCombinedPreviewMode } from "selectors/gitModSelectors"; export function TopInline(props: NavigationProps) { const { currentApplicationDetails, pages } = props; @@ -23,7 +21,7 @@ export function TopInline(props: NavigationProps) { const maxMenuItemWidth = 220; const [maxMenuItemsThatCanFit, setMaxMenuItemsThatCanFit] = useState(0); const { width: screenWidth } = useWindowSizeHooks(); - const isPreviewMode = useSelector(combinedPreviewModeSelector); + const isPreviewMode = useSelector(selectCombinedPreviewMode); const isAppSettingsPaneWithNavigationTabOpen = useSelector( getIsAppSettingsPaneWithNavigationTabOpen, ); diff --git a/app/client/src/pages/AppViewer/PrimaryCTA.test.tsx b/app/client/src/pages/AppViewer/PrimaryCTA.test.tsx index 3b03a559fbfb..63b76d0e0fcc 100644 --- a/app/client/src/pages/AppViewer/PrimaryCTA.test.tsx +++ b/app/client/src/pages/AppViewer/PrimaryCTA.test.tsx @@ -7,6 +7,11 @@ import { lightTheme } from "selectors/themeSelectors"; import PrimaryCTA from "./PrimaryCTA"; import configureStore from "redux-mock-store"; +jest.mock("pages/Editor/gitSync/hooks/modHooks", () => ({ + ...jest.requireActual("pages/Editor/gitSync/hooks/modHooks"), + useGitProtectedMode: jest.fn(() => false), +})); + jest.mock("react-router", () => ({ ...jest.requireActual("react-router"), useHistory: () => ({ push: jest.fn() }), diff --git a/app/client/src/pages/AppViewer/PrimaryCTA.tsx b/app/client/src/pages/AppViewer/PrimaryCTA.tsx index 9e2816166454..97d0363bbf5f 100644 --- a/app/client/src/pages/AppViewer/PrimaryCTA.tsx +++ b/app/client/src/pages/AppViewer/PrimaryCTA.tsx @@ -25,8 +25,8 @@ import { Icon, Tooltip } from "@appsmith/ads"; import { getApplicationNameTextColor } from "./utils"; import { ButtonVariantTypes } from "components/constants"; import { setPreviewModeInitAction } from "actions/editorActions"; -import { protectedModeSelector } from "selectors/gitSyncSelectors"; import { getCurrentApplication } from "ee/selectors/applicationSelectors"; +import { useGitProtectedMode } from "pages/Editor/gitSync/hooks/modHooks"; /** * --------------------------------------------------------------------------------------------------- @@ -67,7 +67,7 @@ function PrimaryCTA(props: Props) { const canEdit = isPermitted(userPermissions, permissionRequired); const [isForkModalOpen, setIsForkModalOpen] = useState(false); const isPreviewMode = useSelector(previewModeSelector); - const isProtectedMode = useSelector(protectedModeSelector); + const isProtectedMode = useGitProtectedMode(); const dispatch = useDispatch(); const location = useLocation(); const queryParams = new URLSearchParams(location.search); diff --git a/app/client/src/pages/Editor/AppSettingsPane/AppSettings/ImportAppSettings.tsx b/app/client/src/pages/Editor/AppSettingsPane/AppSettings/ImportAppSettings.tsx index 8da3b25343c3..b721e7c5c7af 100644 --- a/app/client/src/pages/Editor/AppSettingsPane/AppSettings/ImportAppSettings.tsx +++ b/app/client/src/pages/Editor/AppSettingsPane/AppSettings/ImportAppSettings.tsx @@ -8,8 +8,8 @@ import ImportModal from "pages/common/ImportModal"; import React from "react"; import { useSelector } from "react-redux"; import { getCurrentApplicationId } from "selectors/editorSelectors"; -import { getIsGitConnected } from "selectors/gitSyncSelectors"; import styled from "styled-components"; +import { useGitConnected } from "pages/Editor/gitSync/hooks/modHooks"; const SettingWrapper = styled.div` display: flex; @@ -21,7 +21,7 @@ const SettingWrapper = styled.div` export function ImportAppSettings() { const appId = useSelector(getCurrentApplicationId); const workspace = useSelector(getCurrentAppWorkspace); - const isGitConnected = useSelector(getIsGitConnected); + const isGitConnected = useGitConnected(); const [isModalOpen, setIsModalOpen] = React.useState(false); function handleClose() { diff --git a/app/client/src/pages/Editor/Canvas.tsx b/app/client/src/pages/Editor/Canvas.tsx index 742e6d8a74b1..c34f2fc358c8 100644 --- a/app/client/src/pages/Editor/Canvas.tsx +++ b/app/client/src/pages/Editor/Canvas.tsx @@ -5,7 +5,7 @@ import * as Sentry from "@sentry/react"; import { useDispatch, useSelector } from "react-redux"; import type { CanvasWidgetStructure } from "WidgetProvider/constants"; import useWidgetFocus from "utils/hooks/useWidgetFocus"; -import { combinedPreviewModeSelector } from "selectors/editorSelectors"; +import { selectCombinedPreviewMode } from "selectors/gitModSelectors"; import { getSelectedAppTheme } from "selectors/appThemingSelectors"; import { getViewportClassName } from "layoutSystems/autolayout/utils/AutoLayoutUtils"; import { @@ -44,7 +44,7 @@ const Wrapper = styled.section<{ `; const Canvas = (props: CanvasProps) => { const { canvasWidth } = props; - const isPreviewMode = useSelector(combinedPreviewModeSelector); + const isPreviewMode = useSelector(selectCombinedPreviewMode); const isAppSettingsPaneWithNavigationTabOpen = useSelector( getIsAppSettingsPaneWithNavigationTabOpen, ); diff --git a/app/client/src/pages/Editor/GlobalHotKeys/GlobalHotKeys.tsx b/app/client/src/pages/Editor/GlobalHotKeys/GlobalHotKeys.tsx index 651f57e792c0..1e01349df831 100644 --- a/app/client/src/pages/Editor/GlobalHotKeys/GlobalHotKeys.tsx +++ b/app/client/src/pages/Editor/GlobalHotKeys/GlobalHotKeys.tsx @@ -45,8 +45,8 @@ import { toast } from "@appsmith/ads"; import { showDebuggerFlag } from "selectors/debuggerSelectors"; import { getIsFirstTimeUserOnboardingEnabled } from "selectors/onboardingSelectors"; import WalkthroughContext from "components/featureWalkthrough/walkthroughContext"; -import { protectedModeSelector } from "selectors/gitSyncSelectors"; import { setPreviewModeInitAction } from "actions/editorActions"; +import { selectGitApplicationProtectedMode } from "selectors/gitModSelectors"; interface Props { copySelectedWidget: () => void; @@ -372,15 +372,17 @@ class GlobalHotKeys extends React.Component<Props> { } } -const mapStateToProps = (state: AppState) => ({ - selectedWidget: getLastSelectedWidget(state), - selectedWidgets: getSelectedWidgets(state), - isDebuggerOpen: showDebuggerFlag(state), - appMode: getAppMode(state), - isPreviewMode: previewModeSelector(state), - isProtectedMode: protectedModeSelector(state), - isSignpostingEnabled: getIsFirstTimeUserOnboardingEnabled(state), -}); +const mapStateToProps = (state: AppState) => { + return { + selectedWidget: getLastSelectedWidget(state), + selectedWidgets: getSelectedWidgets(state), + isDebuggerOpen: showDebuggerFlag(state), + appMode: getAppMode(state), + isPreviewMode: previewModeSelector(state), + isProtectedMode: selectGitApplicationProtectedMode(state), + isSignpostingEnabled: getIsFirstTimeUserOnboardingEnabled(state), + }; +}; // TODO: Fix this the next time the file is edited // eslint-disable-next-line @typescript-eslint/no-explicit-any diff --git a/app/client/src/pages/Editor/IDE/Header/DeployButton.tsx b/app/client/src/pages/Editor/IDE/Header/DeployButton.tsx new file mode 100644 index 000000000000..843da728dddf --- /dev/null +++ b/app/client/src/pages/Editor/IDE/Header/DeployButton.tsx @@ -0,0 +1,131 @@ +import { Button, Tooltip } from "@appsmith/ads"; +import { objectKeys } from "@appsmith/utils"; +import { showConnectGitModal } from "actions/gitSyncActions"; +import { publishApplication } from "ee/actions/applicationActions"; +import { getCurrentApplication } from "ee/selectors/applicationSelectors"; +import type { NavigationSetting } from "constants/AppConstants"; +import { + createMessage, + DEPLOY_BUTTON_TOOLTIP, + DEPLOY_MENU_OPTION, + PACKAGE_UPGRADING_ACTION_STATUS, +} from "ee/constants/messages"; +import { getIsPackageUpgrading } from "ee/selectors/packageSelectors"; +import AnalyticsUtil from "ee/utils/AnalyticsUtil"; +import { useGitOps, useGitProtectedMode } from "git"; +import { + useGitConnected, + useGitModEnabled, +} from "pages/Editor/gitSync/hooks/modHooks"; +import React, { useCallback } from "react"; +import { useDispatch, useSelector } from "react-redux"; +import { + getCurrentApplicationId, + getIsPublishingApplication, +} from "selectors/editorSelectors"; +import styled from "styled-components"; + +// This wrapper maintains pointer events for tooltips when the child button is disabled. +// Without this, disabled buttons won't trigger tooltips because they have pointer-events: none +const StyledTooltipTarget = styled.span` + display: inline-block; +`; + +function DeployButton() { + const applicationId = useSelector(getCurrentApplicationId); + const currentApplication = useSelector(getCurrentApplication); + const isPackageUpgrading = useSelector(getIsPackageUpgrading); + const isProtectedMode = useGitProtectedMode(); + const isDeployDisabled = isPackageUpgrading || isProtectedMode; + const isPublishing = useSelector(getIsPublishingApplication); + const isGitConnected = useGitConnected(); + const isGitModEnabled = useGitModEnabled(); + const { toggleOpsModal } = useGitOps(); + + const deployTooltipText = isPackageUpgrading + ? createMessage(PACKAGE_UPGRADING_ACTION_STATUS, "deploy this app") + : createMessage(DEPLOY_BUTTON_TOOLTIP); + + const dispatch = useDispatch(); + + const handlePublish = useCallback(() => { + if (applicationId) { + dispatch(publishApplication(applicationId)); + + const appName = currentApplication ? currentApplication.name : ""; + const pageCount = currentApplication?.pages?.length; + const navigationSettingsWithPrefix: Record< + string, + NavigationSetting[keyof NavigationSetting] + > = {}; + + if (currentApplication?.applicationDetail?.navigationSetting) { + const settingKeys = objectKeys( + currentApplication.applicationDetail.navigationSetting, + ) as Array<keyof NavigationSetting>; + + settingKeys.map((key: keyof NavigationSetting) => { + if (currentApplication?.applicationDetail?.navigationSetting?.[key]) { + const value: NavigationSetting[keyof NavigationSetting] = + currentApplication.applicationDetail.navigationSetting[key]; + + navigationSettingsWithPrefix[`navigationSetting_${key}`] = value; + } + }); + } + + AnalyticsUtil.logEvent("PUBLISH_APP", { + appId: applicationId, + appName, + pageCount, + ...navigationSettingsWithPrefix, + isPublic: !!currentApplication?.isPublic, + templateTitle: currentApplication?.forkedFromTemplateTitle, + }); + } + }, [applicationId, currentApplication, dispatch]); + + const handleClickDeploy = useCallback(() => { + if (isGitConnected) { + if (isGitModEnabled) { + toggleOpsModal(true); + } else { + dispatch(showConnectGitModal()); + } + + AnalyticsUtil.logEvent("GS_DEPLOY_GIT_CLICK", { + source: "Deploy button", + }); + } else { + handlePublish(); + } + }, [ + dispatch, + handlePublish, + isGitConnected, + isGitModEnabled, + toggleOpsModal, + ]); + + return ( + <Tooltip content={deployTooltipText} placement="bottomRight"> + <StyledTooltipTarget> + <Button + className="t--application-publish-btn" + data-guided-tour-iid="deploy" + id={"application-publish-btn"} + isDisabled={isDeployDisabled} + isLoading={isPublishing} + kind="tertiary" + onClick={handleClickDeploy} + size="md" + startIcon={"rocket"} + > + {createMessage(DEPLOY_MENU_OPTION)} + </Button> + </StyledTooltipTarget> + </Tooltip> + ); +} + +export default DeployButton; diff --git a/app/client/src/pages/Editor/IDE/Header/index.tsx b/app/client/src/pages/Editor/IDE/Header/index.tsx index f8e75cda9db7..c26b641ba40d 100644 --- a/app/client/src/pages/Editor/IDE/Header/index.tsx +++ b/app/client/src/pages/Editor/IDE/Header/index.tsx @@ -1,7 +1,6 @@ -import React, { useCallback, useState } from "react"; +import React, { useState } from "react"; import { Flex, - Tooltip, Divider, Modal, ModalContent, @@ -11,7 +10,6 @@ import { TabsList, Tab, TabPanel, - Button, Link, IDEHeader, IDEHeaderTitle, @@ -24,19 +22,15 @@ import { APPLICATION_INVITE, COMMUNITY_TEMPLATES, createMessage, - DEPLOY_BUTTON_TOOLTIP, - DEPLOY_MENU_OPTION, IN_APP_EMBED_SETTING, INVITE_TAB, HEADER_TITLES, - PACKAGE_UPGRADING_ACTION_STATUS, } from "ee/constants/messages"; import EditorName from "pages/Editor/EditorName"; import { getCurrentApplicationId, getCurrentPageId, getIsPageSaving, - getIsPublishingApplication, getPageById, getPageSavingError, } from "selectors/editorSelectors"; @@ -46,10 +40,7 @@ import { getIsErroredSavingAppName, getIsSavingAppName, } from "ee/selectors/applicationSelectors"; -import { - publishApplication, - updateApplication, -} from "ee/actions/applicationActions"; +import { updateApplication } from "ee/actions/applicationActions"; import { getCurrentAppWorkspace } from "ee/selectors/selectedWorkspaceSelectors"; import { Omnibar } from "pages/Editor/commons/Omnibar"; import ToggleModeButton from "pages/Editor/ToggleModeButton"; @@ -62,13 +53,6 @@ import DeployLinkButtonDialog from "components/designSystems/appsmith/header/Dep import { useFeatureFlag } from "utils/hooks/useFeatureFlag"; import { FEATURE_FLAG } from "ee/entities/FeatureFlag"; import { getAppsmithConfigs } from "ee/configs"; -import { - getIsGitConnected, - protectedModeSelector, -} from "selectors/gitSyncSelectors"; -import { showConnectGitModal } from "actions/gitSyncActions"; -import AnalyticsUtil from "ee/utils/AnalyticsUtil"; -import type { NavigationSetting } from "constants/AppConstants"; import { useHref } from "pages/Editor/utils"; import { viewerURL } from "ee/RouteBuilder"; import HelpBar from "components/editorComponents/GlobalSearch/HelpBar"; @@ -80,7 +64,8 @@ import { APPLICATIONS_URL } from "constants/routes"; import { useNavigationMenuData } from "../../EditorName/useNavigationMenuData"; import useLibraryHeaderTitle from "ee/pages/Editor/IDE/Header/useLibraryHeaderTitle"; import { AppsmithLink } from "pages/Editor/AppsmithLink"; -import { getIsPackageUpgrading } from "ee/selectors/packageSelectors"; +import DeployButton from "./DeployButton"; +import GitApplicationContextProvider from "components/gitContexts/GitApplicationContextProvider"; const StyledDivider = styled(Divider)` height: 50%; @@ -88,12 +73,6 @@ const StyledDivider = styled(Divider)` margin-right: 8px; `; -// This wrapper maintains pointer events for tooltips when the child button is disabled. -// Without this, disabled buttons won't trigger tooltips because they have pointer-events: none -const StyledTooltipTarget = styled.span` - display: inline-block; -`; - const { cloudHosting } = getAppsmithConfigs(); interface HeaderTitleProps { @@ -137,19 +116,11 @@ const Header = () => { const currentApplication = useSelector(getCurrentApplication); const isErroredSavingName = useSelector(getIsErroredSavingAppName); const applicationList = useSelector(getApplicationList); - const isProtectedMode = useSelector(protectedModeSelector); - const isPackageUpgrading = useSelector(getIsPackageUpgrading); - const isPublishing = useSelector(getIsPublishingApplication); - const isGitConnected = useSelector(getIsGitConnected); const pageId = useSelector(getCurrentPageId) as string; const currentPage = useSelector(getPageById(pageId)); const appState = useCurrentAppState(); const isSaving = useSelector(getIsPageSaving); const pageSaveError = useSelector(getPageSavingError); - const isDeployDisabled = isPackageUpgrading || isProtectedMode; - const deployTooltipText = isPackageUpgrading - ? createMessage(PACKAGE_UPGRADING_ACTION_STATUS, "deploy this app") - : createMessage(DEPLOY_BUTTON_TOOLTIP); // states const [isPopoverOpen, setIsPopoverOpen] = useState<boolean>(false); const [showModal, setShowModal] = useState<boolean>(false); @@ -179,56 +150,8 @@ const Header = () => { dispatch(updateApplication(id, data)); }; - const handlePublish = useCallback(() => { - if (applicationId) { - dispatch(publishApplication(applicationId)); - - const appName = currentApplication ? currentApplication.name : ""; - const pageCount = currentApplication?.pages?.length; - const navigationSettingsWithPrefix: Record< - string, - NavigationSetting[keyof NavigationSetting] - > = {}; - - if (currentApplication?.applicationDetail?.navigationSetting) { - const settingKeys = Object.keys( - currentApplication.applicationDetail.navigationSetting, - ) as Array<keyof NavigationSetting>; - - settingKeys.map((key: keyof NavigationSetting) => { - if (currentApplication?.applicationDetail?.navigationSetting?.[key]) { - const value: NavigationSetting[keyof NavigationSetting] = - currentApplication.applicationDetail.navigationSetting[key]; - - navigationSettingsWithPrefix[`navigationSetting_${key}`] = value; - } - }); - } - - AnalyticsUtil.logEvent("PUBLISH_APP", { - appId: applicationId, - appName, - pageCount, - ...navigationSettingsWithPrefix, - isPublic: !!currentApplication?.isPublic, - templateTitle: currentApplication?.forkedFromTemplateTitle, - }); - } - }, [applicationId, currentApplication, dispatch]); - - const handleClickDeploy = useCallback(() => { - if (isGitConnected) { - dispatch(showConnectGitModal()); - AnalyticsUtil.logEvent("GS_DEPLOY_GIT_CLICK", { - source: "Deploy button", - }); - } else { - handlePublish(); - } - }, [dispatch, handlePublish, isGitConnected]); - return ( - <> + <GitApplicationContextProvider> <IDEHeader> <IDEHeader.Left logo={<AppsmithLink />}> <HeaderTitleComponent appState={appState} /> @@ -338,30 +261,13 @@ const Header = () => { showModal={showPublishCommunityTemplateModal} /> <div className="flex items-center"> - <Tooltip content={deployTooltipText} placement="bottomRight"> - <StyledTooltipTarget> - <Button - className="t--application-publish-btn" - data-guided-tour-iid="deploy" - id={"application-publish-btn"} - isDisabled={isDeployDisabled} - isLoading={isPublishing} - kind="tertiary" - onClick={handleClickDeploy} - size="md" - startIcon={"rocket"} - > - {DEPLOY_MENU_OPTION()} - </Button> - </StyledTooltipTarget> - </Tooltip> - + <DeployButton /> <DeployLinkButtonDialog link={deployLink} trigger="" /> </div> </IDEHeader.Right> </IDEHeader> <Omnibar /> - </> + </GitApplicationContextProvider> ); }; diff --git a/app/client/src/pages/Editor/IDE/Layout/AnimatedLayout.tsx b/app/client/src/pages/Editor/IDE/Layout/AnimatedLayout.tsx index 952b3542c3f8..d58e70910a3f 100644 --- a/app/client/src/pages/Editor/IDE/Layout/AnimatedLayout.tsx +++ b/app/client/src/pages/Editor/IDE/Layout/AnimatedLayout.tsx @@ -2,7 +2,6 @@ import React from "react"; import { useGridLayoutTemplate } from "./hooks/useGridLayoutTemplate"; import EditorWrapperContainer from "pages/Editor/commons/EditorWrapperContainer"; import { AnimatedGridLayout, LayoutArea } from "components/AnimatedGridLayout"; -import { useSelector } from "react-redux"; import BottomBar from "components/BottomBar"; import Sidebar from "../Sidebar"; import LeftPane from "../LeftPane"; @@ -10,10 +9,28 @@ import MainPane from "../MainPane"; import RightPane from "../RightPane"; import { Areas } from "./constants"; import ProtectedCallout from "../ProtectedCallout"; -import { protectedModeSelector } from "selectors/gitSyncSelectors"; +import { useGitModEnabled } from "pages/Editor/gitSync/hooks/modHooks"; +import { + GitProtectedBranchCallout as GitProtectedBranchCalloutNew, + useGitProtectedMode, +} from "git"; + +function GitProtectedBranchCallout() { + const isGitModEnabled = useGitModEnabled(); + const isProtectedMode = useGitProtectedMode(); + + if (isGitModEnabled) { + return <GitProtectedBranchCalloutNew />; + } + + if (isProtectedMode) { + return <ProtectedCallout />; + } + + return null; +} function AnimatedLayout() { - const isProtectedMode = useSelector(protectedModeSelector); const { areas, columns, rows } = useGridLayoutTemplate(); if (columns.length === 0) { @@ -22,7 +39,7 @@ function AnimatedLayout() { return ( <> - {isProtectedMode && <ProtectedCallout />} + <GitProtectedBranchCallout /> <EditorWrapperContainer> <AnimatedGridLayout areas={areas} diff --git a/app/client/src/pages/Editor/IDE/Layout/StaticLayout.tsx b/app/client/src/pages/Editor/IDE/Layout/StaticLayout.tsx index 57e2fd104fe7..56fab76ff3d6 100644 --- a/app/client/src/pages/Editor/IDE/Layout/StaticLayout.tsx +++ b/app/client/src/pages/Editor/IDE/Layout/StaticLayout.tsx @@ -1,5 +1,4 @@ import React from "react"; -import { useSelector } from "react-redux"; import BottomBar from "components/BottomBar"; import EditorWrapperContainer from "../../commons/EditorWrapperContainer"; @@ -7,11 +6,30 @@ import Sidebar from "pages/Editor/IDE/Sidebar"; import LeftPane from "../LeftPane"; import MainPane from "../MainPane"; import RightPane from "../RightPane"; -import { protectedModeSelector } from "selectors/gitSyncSelectors"; import ProtectedCallout from "../ProtectedCallout"; import { useGridLayoutTemplate } from "./hooks/useGridLayoutTemplate"; import styled from "styled-components"; import { Areas } from "./constants"; +import { useGitModEnabled } from "pages/Editor/gitSync/hooks/modHooks"; +import { + GitProtectedBranchCallout as GitProtectedBranchCalloutNew, + useGitProtectedMode, +} from "git"; + +function GitProtectedBranchCallout() { + const isGitModEnabled = useGitModEnabled(); + const isProtectedMode = useGitProtectedMode(); + + if (isGitModEnabled) { + return <GitProtectedBranchCalloutNew />; + } + + if (isProtectedMode) { + return <ProtectedCallout />; + } + + return null; +} const GridContainer = styled.div` display: grid; @@ -26,14 +44,13 @@ const LayoutContainer = styled.div<{ name: string }>` `; export const StaticLayout = React.memo(() => { - const isProtectedMode = useSelector(protectedModeSelector); const { areas, columns } = useGridLayoutTemplate(); const isSidebarVisible = columns[0] !== "0px"; return ( <> - {isProtectedMode && <ProtectedCallout />} + <GitProtectedBranchCallout /> <EditorWrapperContainer> <GridContainer style={{ diff --git a/app/client/src/pages/Editor/IDE/Layout/hooks/useEditorStateLeftPaneWidth.ts b/app/client/src/pages/Editor/IDE/Layout/hooks/useEditorStateLeftPaneWidth.ts index ace70208b26d..fe8dfd7e8a6a 100644 --- a/app/client/src/pages/Editor/IDE/Layout/hooks/useEditorStateLeftPaneWidth.ts +++ b/app/client/src/pages/Editor/IDE/Layout/hooks/useEditorStateLeftPaneWidth.ts @@ -11,7 +11,7 @@ import { getPropertyPaneWidth } from "selectors/propertyPaneSelectors"; import { EditorEntityTab, EditorViewMode } from "ee/entities/IDE/constants"; import { useCurrentEditorState } from "../../hooks"; import { previewModeSelector } from "selectors/editorSelectors"; -import { protectedModeSelector } from "selectors/gitSyncSelectors"; +import { useGitProtectedMode } from "pages/Editor/gitSync/hooks/modHooks"; export const useEditorStateLeftPaneWidth = (): number => { const [windowWidth] = useWindowDimensions(); @@ -20,7 +20,7 @@ export const useEditorStateLeftPaneWidth = (): number => { const { segment } = useCurrentEditorState(); const propertyPaneWidth = useSelector(getPropertyPaneWidth); const isPreviewMode = useSelector(previewModeSelector); - const isProtectedMode = useSelector(protectedModeSelector); + const isProtectedMode = useGitProtectedMode(); useEffect( function updateWidth() { diff --git a/app/client/src/pages/Editor/IDE/Layout/hooks/useGridLayoutTemplate.ts b/app/client/src/pages/Editor/IDE/Layout/hooks/useGridLayoutTemplate.ts index b2dc0558af59..bf97ce71790b 100644 --- a/app/client/src/pages/Editor/IDE/Layout/hooks/useGridLayoutTemplate.ts +++ b/app/client/src/pages/Editor/IDE/Layout/hooks/useGridLayoutTemplate.ts @@ -7,7 +7,6 @@ import { useCurrentAppState } from "../../hooks/useCurrentAppState"; import { getPropertyPaneWidth } from "selectors/propertyPaneSelectors"; import { previewModeSelector } from "selectors/editorSelectors"; import { getIDEViewMode } from "selectors/ideSelectors"; -import { protectedModeSelector } from "selectors/gitSyncSelectors"; import { EditorEntityTab, EditorState, @@ -20,6 +19,7 @@ import { } from "constants/AppConstants"; import { useEditorStateLeftPaneWidth } from "./useEditorStateLeftPaneWidth"; import { type Area, Areas, SIDEBAR_WIDTH } from "../constants"; +import { useGitProtectedMode } from "pages/Editor/gitSync/hooks/modHooks"; interface ReturnValue { areas: Area[][]; @@ -43,7 +43,7 @@ function useGridLayoutTemplate(): ReturnValue { const appState = useCurrentAppState(); const isPreviewMode = useSelector(previewModeSelector); const editorMode = useSelector(getIDEViewMode); - const isProtectedMode = useSelector(protectedModeSelector); + const isProtectedMode = useGitProtectedMode(); React.useEffect( function updateIDEColumns() { diff --git a/app/client/src/pages/Editor/IDE/ProtectedCallout.test.tsx b/app/client/src/pages/Editor/IDE/ProtectedCallout.test.tsx index 2a60c70f3f86..d735d5663d88 100644 --- a/app/client/src/pages/Editor/IDE/ProtectedCallout.test.tsx +++ b/app/client/src/pages/Editor/IDE/ProtectedCallout.test.tsx @@ -3,11 +3,11 @@ import { render } from "@testing-library/react"; import { merge } from "lodash"; import { Provider } from "react-redux"; import configureStore from "redux-mock-store"; -import IDE from "."; import { BrowserRouter } from "react-router-dom"; import "@testing-library/jest-dom"; import { ReduxActionTypes } from "ee/constants/ReduxActionConstants"; import store from "store"; +import ProtectedCallout from "./ProtectedCallout"; // TODO: Fix this the next time the file is edited // eslint-disable-next-line @typescript-eslint/no-explicit-any @@ -64,7 +64,7 @@ describe("Protected callout test cases", () => { const { getByTestId } = render( <Provider store={store}> <BrowserRouter> - <IDE /> + <ProtectedCallout /> </BrowserRouter> </Provider>, ); @@ -72,33 +72,6 @@ describe("Protected callout test cases", () => { expect(getByTestId("t--git-protected-branch-callout")).toBeInTheDocument(); }); - it("should not render the protected view if branch is not protected", () => { - const store = getMockStore({ - ui: { - applications: { - currentApplication: { - gitApplicationMetadata: { - branchName: "branch-1", - }, - }, - }, - gitSync: { - protectedBranches: ["main"], - }, - }, - }); - const { queryByTestId } = render( - <Provider store={store}> - <BrowserRouter> - <IDE /> - </BrowserRouter> - </Provider>, - ); - - expect( - queryByTestId("t--git-protected-branch-callout"), - ).not.toBeInTheDocument(); - }); it("should unprotect only the current branch if clicked on unprotect cta", () => { const store = getMockStore({ ui: { @@ -117,7 +90,7 @@ describe("Protected callout test cases", () => { const { queryByTestId } = render( <Provider store={store}> <BrowserRouter> - <IDE /> + <ProtectedCallout /> </BrowserRouter> </Provider>, ); diff --git a/app/client/src/pages/Editor/IDE/hooks.test.tsx b/app/client/src/pages/Editor/IDE/hooks.test.tsx index 0a12538bf260..9e5e40d6e98f 100644 --- a/app/client/src/pages/Editor/IDE/hooks.test.tsx +++ b/app/client/src/pages/Editor/IDE/hooks.test.tsx @@ -6,6 +6,12 @@ import { useGetPageFocusUrl } from "./hooks"; // eslint-disable-next-line @typescript-eslint/no-restricted-imports import { createEditorFocusInfo } from "../../../ce/navigation/FocusStrategy/AppIDEFocusStrategy"; +const mockUseGitCurrentBranch = jest.fn<string | null, []>(() => null); + +jest.mock("../gitSync/hooks/modHooks", () => ({ + useGitCurrentBranch: () => mockUseGitCurrentBranch(), +})); + describe("useGetPageFocusUrl", () => { const pages = PageFactory.buildList(4); @@ -42,6 +48,7 @@ describe("useGetPageFocusUrl", () => { const wrapper = hookWrapper({ initialState: state }); it("works for JS focus history", () => { + mockUseGitCurrentBranch.mockReturnValue(null); const { result } = renderHook(() => useGetPageFocusUrl(pages[0].pageId), { wrapper, }); @@ -83,10 +90,13 @@ describe("useGetPageFocusUrl", () => { it("returns correct state when branches exist", () => { const branch = "featureBranch"; + + mockUseGitCurrentBranch.mockReturnValue(branch); const page1FocusHistoryWithBranch = createEditorFocusInfo( pages[0].pageId, branch, ); + const state = getIDETestState({ pages, focusHistory: { diff --git a/app/client/src/pages/Editor/IDE/hooks.ts b/app/client/src/pages/Editor/IDE/hooks.ts index 178a02e94222..6d356af8626b 100644 --- a/app/client/src/pages/Editor/IDE/hooks.ts +++ b/app/client/src/pages/Editor/IDE/hooks.ts @@ -15,7 +15,6 @@ import { widgetListURL, } from "ee/RouteBuilder"; import { getCurrentFocusInfo } from "selectors/focusHistorySelectors"; -import { getCurrentGitBranch } from "selectors/gitSyncSelectors"; import { getIsAltFocusWidget, getWidgetSelectionBlock } from "selectors/ui"; import { altFocusWidget, setWidgetSelectionBlock } from "actions/widgetActions"; import { useJSAdd } from "ee/pages/Editor/IDE/EditorPane/JS/hooks"; @@ -27,6 +26,7 @@ import { closeJSActionTab } from "actions/jsActionActions"; import { closeQueryActionTab } from "actions/pluginActionActions"; import { getCurrentBasePageId } from "selectors/editorSelectors"; import { getCurrentEntityInfo } from "../utils"; +import { useGitCurrentBranch } from "../gitSync/hooks/modHooks"; import { useEditorType } from "ee/hooks"; import { useParentEntityInfo } from "ee/hooks/datasourceEditorHooks"; import { useBoolean } from "usehooks-ts"; @@ -102,7 +102,8 @@ export const useSegmentNavigation = (): { export const useGetPageFocusUrl = (basePageId: string): string => { const [focusPageUrl, setFocusPageUrl] = useState(builderURL({ basePageId })); - const branch = useSelector(getCurrentGitBranch); + const branch = useGitCurrentBranch(); + const editorStateFocusInfo = useSelector((appState) => getCurrentFocusInfo(appState, createEditorFocusInfoKey(basePageId, branch)), ); diff --git a/app/client/src/pages/Editor/WidgetsEditor/components/LayoutSystemBasedPageViewer.tsx b/app/client/src/pages/Editor/WidgetsEditor/components/LayoutSystemBasedPageViewer.tsx index a430ed2fd02e..935e67cd90f0 100644 --- a/app/client/src/pages/Editor/WidgetsEditor/components/LayoutSystemBasedPageViewer.tsx +++ b/app/client/src/pages/Editor/WidgetsEditor/components/LayoutSystemBasedPageViewer.tsx @@ -8,9 +8,9 @@ import { getCurrentPageId, previewModeSelector, } from "selectors/editorSelectors"; -import { protectedModeSelector } from "selectors/gitSyncSelectors"; import { getAppSettingsPaneContext } from "selectors/appSettingsPaneSelectors"; import { useShowSnapShotBanner } from "pages/Editor/CanvasLayoutConversion/hooks/useShowSnapShotBanner"; +import { useGitProtectedMode } from "pages/Editor/gitSync/hooks/modHooks"; /** * LayoutSystemBasedPageViewer @@ -25,7 +25,7 @@ export const LayoutSystemBasedPageViewer = ({ }) => { const currentPageId = useSelector(getCurrentPageId); const isPreviewMode = useSelector(previewModeSelector); - const isProtectedMode = useSelector(protectedModeSelector); + const isProtectedMode = useGitProtectedMode(); const appSettingsPaneContext = useSelector(getAppSettingsPaneContext); const canvasWidth = useSelector(getCanvasWidth); const shouldShowSnapShotBanner = useShowSnapShotBanner( diff --git a/app/client/src/pages/Editor/WidgetsEditor/components/NavigationAdjustedPageViewer.tsx b/app/client/src/pages/Editor/WidgetsEditor/components/NavigationAdjustedPageViewer.tsx index 7ec7cdd62ec4..6eb0f1ff10a6 100644 --- a/app/client/src/pages/Editor/WidgetsEditor/components/NavigationAdjustedPageViewer.tsx +++ b/app/client/src/pages/Editor/WidgetsEditor/components/NavigationAdjustedPageViewer.tsx @@ -4,7 +4,7 @@ import { EditorState } from "ee/entities/IDE/constants"; import { useCurrentAppState } from "pages/Editor/IDE/hooks/useCurrentAppState"; import { getIsAppSettingsPaneWithNavigationTabOpen } from "selectors/appSettingsPaneSelectors"; import { useSelector } from "react-redux"; -import { combinedPreviewModeSelector } from "selectors/editorSelectors"; +import { selectCombinedPreviewMode } from "selectors/gitModSelectors"; import { PageViewWrapper } from "pages/AppViewer/AppPage"; import classNames from "classnames"; import { APP_MODE } from "entities/App"; @@ -27,7 +27,7 @@ import { getIsAnvilLayout } from "layoutSystems/anvil/integrations/selectors"; export const NavigationAdjustedPageViewer = (props: { children: ReactNode; }) => { - const isPreview = useSelector(combinedPreviewModeSelector); + const isPreview = useSelector(selectCombinedPreviewMode); const currentApplicationDetails = useSelector(getCurrentApplication); const isAppSidebarPinned = useSelector(getAppSidebarPinned); const sidebarWidth = useSelector(getSidebarWidth); diff --git a/app/client/src/pages/Editor/WidgetsEditor/components/NavigationPreview.tsx b/app/client/src/pages/Editor/WidgetsEditor/components/NavigationPreview.tsx index 0478d6f63439..8f2aa0e23c24 100644 --- a/app/client/src/pages/Editor/WidgetsEditor/components/NavigationPreview.tsx +++ b/app/client/src/pages/Editor/WidgetsEditor/components/NavigationPreview.tsx @@ -2,7 +2,7 @@ import type { LegacyRef } from "react"; import React, { forwardRef } from "react"; import classNames from "classnames"; import { useSelector } from "react-redux"; -import { combinedPreviewModeSelector } from "selectors/editorSelectors"; +import { selectCombinedPreviewMode } from "selectors/gitModSelectors"; import { Navigation } from "pages/AppViewer/Navigation"; import { useCurrentAppState } from "pages/Editor/IDE/hooks/useCurrentAppState"; import { EditorState } from "ee/entities/IDE/constants"; @@ -22,7 +22,7 @@ const NavigationPreview = forwardRef( const appState = useCurrentAppState(); const isAppSettingsPaneWithNavigationTabOpen = appState === EditorState.SETTINGS && isNavigationSelectedInSettings; - const isPreviewMode = useSelector(combinedPreviewModeSelector); + const isPreviewMode = useSelector(selectCombinedPreviewMode); return ( <div diff --git a/app/client/src/pages/Editor/WidgetsEditor/components/WidgetEditorContentWrapper.tsx b/app/client/src/pages/Editor/WidgetsEditor/components/WidgetEditorContentWrapper.tsx index 517413ff0274..1f6cc4985526 100644 --- a/app/client/src/pages/Editor/WidgetsEditor/components/WidgetEditorContentWrapper.tsx +++ b/app/client/src/pages/Editor/WidgetsEditor/components/WidgetEditorContentWrapper.tsx @@ -1,19 +1,17 @@ import React, { type ReactNode, useCallback, useMemo } from "react"; import { useDispatch, useSelector } from "react-redux"; -import { - combinedPreviewModeSelector, - getIsAutoLayout, -} from "selectors/editorSelectors"; +import { getIsAutoLayout } from "selectors/editorSelectors"; import { setCanvasSelectionFromEditor } from "actions/canvasSelectionActions"; import { useAllowEditorDragToSelect } from "utils/hooks/useAllowEditorDragToSelect"; import { useAutoHeightUIState } from "utils/hooks/autoHeightUIHooks"; import { getSelectedAppTheme } from "selectors/appThemingSelectors"; +import { selectCombinedPreviewMode } from "selectors/gitModSelectors"; export const WidgetEditorContentWrapper = (props: { children: ReactNode }) => { const allowDragToSelect = useAllowEditorDragToSelect(); const { isAutoHeightWithLimitsChanging } = useAutoHeightUIState(); const dispatch = useDispatch(); - const isCombinedPreviewMode = useSelector(combinedPreviewModeSelector); + const isCombinedPreviewMode = useSelector(selectCombinedPreviewMode); const handleWrapperClick = useCallback( (e) => { diff --git a/app/client/src/pages/Editor/WidgetsEditor/components/WidgetEditorNavigation.tsx b/app/client/src/pages/Editor/WidgetsEditor/components/WidgetEditorNavigation.tsx index 852c210685ee..d7b7d2869271 100644 --- a/app/client/src/pages/Editor/WidgetsEditor/components/WidgetEditorNavigation.tsx +++ b/app/client/src/pages/Editor/WidgetsEditor/components/WidgetEditorNavigation.tsx @@ -7,7 +7,7 @@ import { getIsAppSettingsPaneWithNavigationTabOpen, } from "selectors/appSettingsPaneSelectors"; import { useSelector } from "react-redux"; -import { combinedPreviewModeSelector } from "selectors/editorSelectors"; +import { selectCombinedPreviewMode } from "selectors/gitModSelectors"; import { getCurrentApplication } from "ee/selectors/applicationSelectors"; /** @@ -20,7 +20,7 @@ import { getCurrentApplication } from "ee/selectors/applicationSelectors"; export const useNavigationPreviewHeight = () => { const [navigationHeight, setNavigationHeight] = useState(0); const navigationPreviewRef = useRef(null); - const isPreviewMode = useSelector(combinedPreviewModeSelector); + const isPreviewMode = useSelector(selectCombinedPreviewMode); const appSettingsPaneContext = useSelector(getAppSettingsPaneContext); const currentApplicationDetails = useSelector(getCurrentApplication); @@ -54,7 +54,7 @@ type DivRef = React.Ref<HTMLDivElement>; */ export const WidgetEditorNavigation = forwardRef( (props, navigationPreviewRef: DivRef) => { - const isPreviewMode = useSelector(combinedPreviewModeSelector); + const isPreviewMode = useSelector(selectCombinedPreviewMode); const isNavigationSelectedInSettings = useSelector( getIsAppSettingsPaneWithNavigationTabOpen, ); diff --git a/app/client/src/pages/Editor/commons/EditorWrapperContainer.tsx b/app/client/src/pages/Editor/commons/EditorWrapperContainer.tsx index 990004cbbec5..3b34d1beecd4 100644 --- a/app/client/src/pages/Editor/commons/EditorWrapperContainer.tsx +++ b/app/client/src/pages/Editor/commons/EditorWrapperContainer.tsx @@ -2,11 +2,11 @@ import React from "react"; import styled from "styled-components"; import classNames from "classnames"; import { useSelector } from "react-redux"; -import { combinedPreviewModeSelector } from "../../../selectors/editorSelectors"; -import { protectedModeSelector } from "selectors/gitSyncSelectors"; import { IDE_HEADER_HEIGHT } from "@appsmith/ads"; import { BOTTOM_BAR_HEIGHT } from "../../../components/BottomBar/constants"; import { PROTECTED_CALLOUT_HEIGHT } from "../IDE/ProtectedCallout"; +import { useGitProtectedMode } from "../gitSync/hooks/modHooks"; +import { selectCombinedPreviewMode } from "selectors/gitModSelectors"; interface EditorWrapperContainerProps { children: React.ReactNode; @@ -25,8 +25,8 @@ const Wrapper = styled.div<{ `; function EditorWrapperContainer({ children }: EditorWrapperContainerProps) { - const isCombinedPreviewMode = useSelector(combinedPreviewModeSelector); - const isProtectedMode = useSelector(protectedModeSelector); + const isCombinedPreviewMode = useSelector(selectCombinedPreviewMode); + const isProtectedMode = useGitProtectedMode(); return ( <Wrapper diff --git a/app/client/src/pages/Editor/gitSync/components/DeployPreview.tsx b/app/client/src/pages/Editor/gitSync/components/DeployPreview.tsx index 68c5d609429b..9ead5d9d65c9 100644 --- a/app/client/src/pages/Editor/gitSync/components/DeployPreview.tsx +++ b/app/client/src/pages/Editor/gitSync/components/DeployPreview.tsx @@ -58,7 +58,6 @@ export default function DeployPreview(props: { showSuccess: boolean }) { : ""; return lastDeployedAt ? ( - // ! case: can use flex? <Container className="t--git-deploy-preview"> <div> {props.showSuccess ? ( diff --git a/app/client/src/pages/Editor/gitSync/hooks/modHooks.ts b/app/client/src/pages/Editor/gitSync/hooks/modHooks.ts new file mode 100644 index 000000000000..e4d4b7fb4b7a --- /dev/null +++ b/app/client/src/pages/Editor/gitSync/hooks/modHooks.ts @@ -0,0 +1,44 @@ +// temp file will be removed after git mod is fully rolled out + +import { useSelector } from "react-redux"; +import { + getCurrentGitBranch, + getIsGitConnected, + protectedModeSelector, +} from "selectors/gitSyncSelectors"; +import { + useGitProtectedMode as useGitProtectedModeNew, + useGitCurrentBranch as useGitCurrentBranchNew, + useGitConnected as useGitConnectedNew, +} from "git"; +import { selectGitModEnabled } from "selectors/gitModSelectors"; + +export function useGitModEnabled() { + const isGitModEnabled = useSelector(selectGitModEnabled); + + return isGitModEnabled; +} + +export function useGitCurrentBranch() { + const isGitModEnabled = useGitModEnabled(); + const currentBranchOld = useSelector(getCurrentGitBranch) ?? null; + const currentBranchNew = useGitCurrentBranchNew(); + + return isGitModEnabled ? currentBranchNew : currentBranchOld; +} + +export function useGitProtectedMode() { + const isGitModEnabled = useGitModEnabled(); + const isProtectedModeOld = useSelector(protectedModeSelector); + const isProtectedModeNew = useGitProtectedModeNew(); + + return isGitModEnabled ? isProtectedModeNew : isProtectedModeOld; +} + +export function useGitConnected() { + const isGitModEnabled = useGitModEnabled(); + const isGitConnectedOld = useSelector(getIsGitConnected); + const isGitConnectedNew = useGitConnectedNew(); + + return isGitModEnabled ? isGitConnectedNew : isGitConnectedOld; +} diff --git a/app/client/src/pages/Editor/index.tsx b/app/client/src/pages/Editor/index.tsx index a7bfff34f2cb..746b7ca56733 100644 --- a/app/client/src/pages/Editor/index.tsx +++ b/app/client/src/pages/Editor/index.tsx @@ -25,12 +25,9 @@ import { getTheme, ThemeMode } from "selectors/themeSelectors"; import { ThemeProvider } from "styled-components"; import type { Theme } from "constants/DefaultTheme"; import GlobalHotKeys from "./GlobalHotKeys"; -import GitSyncModal from "pages/Editor/gitSync/GitSyncModal"; -import DisconnectGitModal from "pages/Editor/gitSync/DisconnectGitModal"; import { setupPageAction, updateCurrentPage } from "actions/pageActions"; import { getCurrentPageId } from "selectors/editorSelectors"; import { getSearchQuery } from "utils/helpers"; -import RepoLimitExceededErrorModal from "./gitSync/RepoLimitExceededErrorModal"; import ImportedApplicationSuccessModal from "./gitSync/ImportSuccessModal"; import { getIsBranchUpdated } from "../utils"; import { APP_MODE } from "entities/App"; @@ -42,16 +39,40 @@ import SignpostingOverlay from "pages/Editor/FirstTimeUserOnboarding/Overlay"; import { editorInitializer } from "../../utils/editor/EditorUtils"; import { widgetInitialisationSuccess } from "../../actions/widgetActions"; import urlBuilder from "ee/entities/URLRedirect/URLAssembly"; -import DisableAutocommitModal from "./gitSync/DisableAutocommitModal"; -import GitSettingsModal from "./gitSync/GitSettingsModal"; -import ReconfigureCDKeyModal from "ee/components/gitComponents/ReconfigureCDKeyModal"; -import DisableCDModal from "ee/components/gitComponents/DisableCDModal"; import { PartialExportModal } from "components/editorComponents/PartialImportExport/PartialExportModal"; import { PartialImportModal } from "components/editorComponents/PartialImportExport/PartialImportModal"; import type { Page } from "entities/Page"; import { AppCURLImportModal } from "ee/pages/Editor/CurlImport"; import { IDE_HEADER_HEIGHT } from "@appsmith/ads"; import GeneratePageModal from "./GeneratePage"; +import { GitModals as NewGitModals } from "git"; +import GitSyncModal from "./gitSync/GitSyncModal"; +import GitSettingsModal from "./gitSync/GitSettingsModal"; +import DisconnectGitModal from "./gitSync/DisconnectGitModal"; +import DisableAutocommitModal from "./gitSync/DisableAutocommitModal"; +import ReconfigureCDKeyModal from "ee/components/gitComponents/ReconfigureCDKeyModal"; +import DisableCDModal from "ee/components/gitComponents/DisableCDModal"; +import RepoLimitExceededErrorModal from "./gitSync/RepoLimitExceededErrorModal"; +import { useGitModEnabled } from "./gitSync/hooks/modHooks"; +import GitApplicationContextProvider from "components/gitContexts/GitApplicationContextProvider"; + +function GitModals() { + const isGitModEnabled = useGitModEnabled(); + + return isGitModEnabled ? ( + <NewGitModals /> + ) : ( + <> + <GitSyncModal /> + <GitSettingsModal /> + <DisableCDModal /> + <ReconfigureCDKeyModal /> + <DisconnectGitModal /> + <DisableAutocommitModal /> + <RepoLimitExceededErrorModal /> + </> + ); +} interface EditorProps { currentApplicationId?: string; @@ -195,24 +216,20 @@ class Editor extends Component<Props> { {`${this.props.currentApplicationName} | Editor | Appsmith`} </title> </Helmet> - <GlobalHotKeys> - <IDE /> - <GitSyncModal /> - <GitSettingsModal /> - <DisableCDModal /> - <ReconfigureCDKeyModal /> - <DisconnectGitModal /> - <DisableAutocommitModal /> - <RepoLimitExceededErrorModal /> - <TemplatesModal /> - <ImportedApplicationSuccessModal /> - <ReconnectDatasourceModal /> - <SignpostingOverlay /> - <PartialExportModal /> - <PartialImportModal /> - <AppCURLImportModal /> - <GeneratePageModal /> - </GlobalHotKeys> + <GitApplicationContextProvider> + <GlobalHotKeys> + <IDE /> + <GitModals /> + <TemplatesModal /> + <ImportedApplicationSuccessModal /> + <ReconnectDatasourceModal /> + <SignpostingOverlay /> + <PartialExportModal /> + <PartialImportModal /> + <AppCURLImportModal /> + <GeneratePageModal /> + </GlobalHotKeys> + </GitApplicationContextProvider> </div> <RequestConfirmationModal /> </ThemeProvider> diff --git a/app/client/src/pages/UserProfile/index.tsx b/app/client/src/pages/UserProfile/index.tsx index a715171bc31d..f77d74fedb50 100644 --- a/app/client/src/pages/UserProfile/index.tsx +++ b/app/client/src/pages/UserProfile/index.tsx @@ -3,12 +3,23 @@ import PageWrapper from "pages/common/PageWrapper"; import styled from "styled-components"; import { Tabs, Tab, TabsList, TabPanel } from "@appsmith/ads"; import General from "./General"; -import GitConfig from "./GitConfig"; +import OldGitConfig from "./GitConfig"; import { useLocation } from "react-router"; import { GIT_PROFILE_ROUTE } from "constants/routes"; import { BackButton } from "components/utils/helperComponents"; import { useDispatch } from "react-redux"; import { fetchGlobalGitConfigInit } from "actions/gitSyncActions"; +import { useGitModEnabled } from "pages/Editor/gitSync/hooks/modHooks"; +import { + fetchGitGlobalProfile, + GitGlobalProfile as GitGlobalProfileNew, +} from "git"; + +function GitGlobalProfile() { + const isGitModEnabled = useGitModEnabled(); + + return isGitModEnabled ? <GitGlobalProfileNew /> : <OldGitConfig />; +} const ProfileWrapper = styled.div` width: 978px; @@ -25,6 +36,7 @@ const ProfileWrapper = styled.div` function UserProfile() { const location = useLocation(); const dispatch = useDispatch(); + const isGitModEnabled = useGitModEnabled(); let initialTab = "general"; const tabs = [ @@ -39,7 +51,7 @@ function UserProfile() { tabs.push({ key: "gitConfig", title: "Git user config", - panelComponent: <GitConfig />, + panelComponent: <GitGlobalProfile />, icon: "git-branch", }); @@ -49,10 +61,16 @@ function UserProfile() { const [selectedTab, setSelectedTab] = useState(initialTab); - useEffect(() => { - // onMount Fetch Global config - dispatch(fetchGlobalGitConfigInit()); - }, []); + useEffect( + function fetchGlobalGitConfigOnInitEffect() { + if (isGitModEnabled) { + dispatch(fetchGitGlobalProfile()); + } else { + dispatch(fetchGlobalGitConfigInit()); + } + }, + [dispatch, isGitModEnabled], + ); return ( <PageWrapper displayName={"Profile"}> diff --git a/app/client/src/pages/common/ImportModal.tsx b/app/client/src/pages/common/ImportModal.tsx index b19974788529..12cefc5dec8c 100644 --- a/app/client/src/pages/common/ImportModal.tsx +++ b/app/client/src/pages/common/ImportModal.tsx @@ -30,6 +30,8 @@ import { import useMessages from "ee/hooks/importModal/useMessages"; import useMethods from "ee/hooks/importModal/useMethods"; import { getIsAnvilLayoutEnabled } from "layoutSystems/anvil/integrations/selectors"; +import { useGitModEnabled } from "pages/Editor/gitSync/hooks/modHooks"; +import { toggleGitImportModal } from "git"; const TextWrapper = styled.div` padding: 0; @@ -203,6 +205,7 @@ function ImportModal(props: ImportModalProps) { toEditor = false, workspaceId, } = props; + const isGitModEnabled = useGitModEnabled(); const { mainDescription, title } = useMessages(); const { appFileToBeUploaded, @@ -223,15 +226,21 @@ function ImportModal(props: ImportModalProps) { setWorkspaceIdForImport({ editorId: editorId || "", workspaceId }), ); - dispatch( - setIsGitSyncModalOpen({ - isOpen: true, - tab: GitSyncModalTab.GIT_CONNECTION, - }), - ); - - // dispatch(setIsReconnectingDatasourcesModalOpen({ isOpen: true })); - }, []); + if (isGitModEnabled) { + dispatch( + toggleGitImportModal({ + open: true, + }), + ); + } else { + dispatch( + setIsGitSyncModalOpen({ + isOpen: true, + tab: GitSyncModalTab.GIT_CONNECTION, + }), + ); + } + }, [dispatch, editorId, isGitModEnabled, onClose, workspaceId]); useEffect(() => { // finished of importing application diff --git a/app/client/src/sagas/ActionExecution/StoreActionSaga.ts b/app/client/src/sagas/ActionExecution/StoreActionSaga.ts index 4bcd909aabf0..ee6d99630ffd 100644 --- a/app/client/src/sagas/ActionExecution/StoreActionSaga.ts +++ b/app/client/src/sagas/ActionExecution/StoreActionSaga.ts @@ -4,7 +4,6 @@ import localStorage from "utils/localStorage"; import { updateAppStore } from "actions/pageActions"; import AppsmithConsole from "utils/AppsmithConsole"; import { getAppStoreData } from "ee/selectors/entitiesSelector"; -import { getCurrentGitBranch } from "selectors/gitSyncSelectors"; import { getCurrentApplicationId } from "selectors/editorSelectors"; import type { AppStoreState } from "reducers/entityReducers/appReducer"; import { Severity, LOG_CATEGORY } from "entities/AppsmithConsole"; @@ -13,6 +12,7 @@ import type { TRemoveValueDescription, TStoreValueDescription, } from "workers/Evaluation/fns/storeFns"; +import { selectGitApplicationCurrentBranch } from "selectors/gitModSelectors"; type StoreOperation = | TStoreValueDescription @@ -21,7 +21,9 @@ type StoreOperation = export function* handleStoreOperations(triggers: StoreOperation[]) { const applicationId: string = yield select(getCurrentApplicationId); - const branch: string | undefined = yield select(getCurrentGitBranch); + const branch: string | undefined = yield select( + selectGitApplicationCurrentBranch, + ); const appStoreName = getAppStoreName(applicationId, branch); const existingLocalStore = localStorage.getItem(appStoreName) || "{}"; let parsedLocalStore = JSON.parse(existingLocalStore); diff --git a/app/client/src/sagas/DatasourcesSagas.ts b/app/client/src/sagas/DatasourcesSagas.ts index 189fe5b80bc4..841be4eae950 100644 --- a/app/client/src/sagas/DatasourcesSagas.ts +++ b/app/client/src/sagas/DatasourcesSagas.ts @@ -714,6 +714,7 @@ function* redirectAuthorizationCodeSaga( const { contextId, contextType, datasourceId, pluginType } = actionPayload.payload; const isImport: string = yield select(getWorkspaceIdForImport); + // ! git mod - not sure how to handle this, there is no definition for the artifact used here const branchName: string | undefined = yield select(getCurrentGitBranch); if (pluginType === PluginType.API) { diff --git a/app/client/src/sagas/FocusRetentionSaga.ts b/app/client/src/sagas/FocusRetentionSaga.ts index 45232d9560dc..e92be7bae11b 100644 --- a/app/client/src/sagas/FocusRetentionSaga.ts +++ b/app/client/src/sagas/FocusRetentionSaga.ts @@ -18,10 +18,10 @@ import type { AppsmithLocationState } from "utils/history"; import type { Action } from "entities/Action"; import { getAction, getPlugin } from "ee/selectors/entitiesSelector"; import type { Plugin } from "api/PluginApi"; -import { getCurrentGitBranch } from "selectors/gitSyncSelectors"; import { getIDETypeByUrl } from "ee/entities/IDE/utils"; import { getIDEFocusStrategy } from "ee/navigation/FocusStrategy"; import { IDE_TYPE } from "ee/entities/IDE/constants"; +import { selectGitApplicationCurrentBranch } from "selectors/gitModSelectors"; export interface FocusPath { key: string; @@ -123,7 +123,9 @@ class FocusRetention { } public *handleRemoveFocusHistory(url: string) { - const branch: string | undefined = yield select(getCurrentGitBranch); + const branch: string | undefined = yield select( + selectGitApplicationCurrentBranch, + ); const removeKeys: string[] = []; const focusEntityInfo = identifyEntityFromPath(url); diff --git a/app/client/src/sagas/GlobalSearchSagas.ts b/app/client/src/sagas/GlobalSearchSagas.ts index 17cf81e719b3..93e29c0b29dc 100644 --- a/app/client/src/sagas/GlobalSearchSagas.ts +++ b/app/client/src/sagas/GlobalSearchSagas.ts @@ -21,19 +21,21 @@ import { } from "selectors/editorSelectors"; import type { RecentEntity } from "components/editorComponents/GlobalSearch/utils"; import log from "loglevel"; -import { getCurrentGitBranch } from "selectors/gitSyncSelectors"; import type { FocusEntity, FocusEntityInfo } from "navigation/FocusEntity"; import { convertToPageIdSelector } from "selectors/pageListSelectors"; +import { selectGitApplicationCurrentBranch } from "selectors/gitModSelectors"; const getRecentEntitiesKey = (applicationId: string, branch?: string) => branch ? `${applicationId}-${branch}` : applicationId; export function* updateRecentEntitySaga(entityInfo: FocusEntityInfo) { try { - const branch: string | undefined = yield select(getCurrentGitBranch); - const applicationId: string = yield select(getCurrentApplicationId); + const branch: string | undefined = yield select( + selectGitApplicationCurrentBranch, + ); + const recentEntitiesRestored: boolean = yield select( (state: AppState) => state.ui.globalSearch.recentEntitiesRestored, ); diff --git a/app/client/src/sagas/autoHeightSagas/helpers.ts b/app/client/src/sagas/autoHeightSagas/helpers.ts index da276f65d769..3ac3086a9d53 100644 --- a/app/client/src/sagas/autoHeightSagas/helpers.ts +++ b/app/client/src/sagas/autoHeightSagas/helpers.ts @@ -11,7 +11,7 @@ import type { } from "reducers/entityReducers/canvasWidgetsReducer"; import { select } from "redux-saga/effects"; import { getWidgetMetaProps, getWidgets } from "sagas/selectors"; -import { combinedPreviewModeSelector } from "selectors/editorSelectors"; +import { selectCombinedPreviewMode } from "selectors/gitModSelectors"; import { getAppMode } from "ee/selectors/entitiesSelector"; import { isAutoHeightEnabledForWidget } from "widgets/WidgetUtils"; import { getCanvasHeightOffset } from "utils/WidgetSizeUtils"; @@ -20,7 +20,7 @@ import type { DataTree } from "entities/DataTree/dataTreeTypes"; import { getDataTree } from "selectors/dataTreeSelectors"; export function* shouldWidgetsCollapse() { - const isPreviewMode: boolean = yield select(combinedPreviewModeSelector); + const isPreviewMode: boolean = yield select(selectCombinedPreviewMode); const appMode: APP_MODE = yield select(getAppMode); return isPreviewMode || appMode === APP_MODE.PUBLISHED; diff --git a/app/client/src/selectors/debuggerSelectors.tsx b/app/client/src/selectors/debuggerSelectors.tsx index 89c2c46df479..624fae4f290f 100644 --- a/app/client/src/selectors/debuggerSelectors.tsx +++ b/app/client/src/selectors/debuggerSelectors.tsx @@ -11,8 +11,8 @@ import { isWidget, } from "ee/workers/Evaluation/evaluationUtils"; import { getDataTree } from "./dataTreeSelectors"; -import { combinedPreviewModeSelector } from "./editorSelectors"; import type { CanvasDebuggerState } from "reducers/uiReducers/debuggerReducer"; +import { selectCombinedPreviewMode } from "./gitModSelectors"; interface ErrorObejct { [k: string]: Log; @@ -169,7 +169,7 @@ export const getDebuggerOpen = (state: AppState) => state.ui.debugger.isOpen; export const showDebuggerFlag = createSelector( getDebuggerOpen, - combinedPreviewModeSelector, + selectCombinedPreviewMode, (isOpen, isPreview) => isOpen && !isPreview, ); diff --git a/app/client/src/selectors/editorSelectors.tsx b/app/client/src/selectors/editorSelectors.tsx index ee3560dd5034..39bd1d46c1b6 100644 --- a/app/client/src/selectors/editorSelectors.tsx +++ b/app/client/src/selectors/editorSelectors.tsx @@ -990,9 +990,3 @@ export const getGsheetToken = (state: AppState) => export const getGsheetProjectID = (state: AppState) => state.entities.datasources.gsheetProjectID; - -export const combinedPreviewModeSelector = createSelector( - previewModeSelector, - protectedModeSelector, - (isPreviewMode, isProtectedMode) => isPreviewMode || isProtectedMode, -); diff --git a/app/client/src/selectors/gitModSelectors.ts b/app/client/src/selectors/gitModSelectors.ts new file mode 100644 index 000000000000..35fe32fbbff7 --- /dev/null +++ b/app/client/src/selectors/gitModSelectors.ts @@ -0,0 +1,50 @@ +// temp file will be removed after git mod is fully rolled out + +import { selectFeatureFlags } from "ee/selectors/featureFlagsSelectors"; +import { createSelector } from "reselect"; +import { getCurrentGitBranch, protectedModeSelector } from "./gitSyncSelectors"; +import { + selectGitCurrentBranch as selectGitCurrentBranchNew, + selectGitProtectedMode as selectGitProtectedModeNew, +} from "git"; +import { + getCurrentBaseApplicationId, + previewModeSelector, +} from "./editorSelectors"; +import { applicationArtifact } from "git/artifact-helpers/application"; + +export const selectGitModEnabled = createSelector( + selectFeatureFlags, + (featureFlags) => featureFlags.release_git_modularisation_enabled ?? false, +); + +export const selectGitApplicationArtifactDef = createSelector( + getCurrentBaseApplicationId, + (baseApplicationId) => applicationArtifact(baseApplicationId), +); + +export const selectGitApplicationCurrentBranch = createSelector( + selectGitModEnabled, + getCurrentGitBranch, + (state) => + selectGitCurrentBranchNew(state, selectGitApplicationArtifactDef(state)), + (isGitModEnabled, currentBranchOld, currentBranchNew) => { + return isGitModEnabled ? currentBranchNew : currentBranchOld; + }, +); + +export const selectGitApplicationProtectedMode = createSelector( + selectGitModEnabled, + protectedModeSelector, + (state) => + selectGitProtectedModeNew(state, selectGitApplicationArtifactDef(state)), + (isGitModEnabled, protectedModeOld, protectedModeNew) => { + return isGitModEnabled ? protectedModeNew : protectedModeOld; + }, +); + +export const selectCombinedPreviewMode = createSelector( + previewModeSelector, + selectGitApplicationProtectedMode, + (isPreviewMode, isProtectedMode) => isPreviewMode || isProtectedMode, +); diff --git a/app/client/src/selectors/widgetDragSelectors.ts b/app/client/src/selectors/widgetDragSelectors.ts index 0a2b35eb7e1f..21d5848d5175 100644 --- a/app/client/src/selectors/widgetDragSelectors.ts +++ b/app/client/src/selectors/widgetDragSelectors.ts @@ -1,11 +1,9 @@ import type { AppState } from "ee/reducers"; import { createSelector } from "reselect"; import { getIsAppSettingsPaneWithNavigationTabOpen } from "./appSettingsPaneSelectors"; -import { - combinedPreviewModeSelector, - snipingModeSelector, -} from "./editorSelectors"; +import { snipingModeSelector } from "./editorSelectors"; import { getWidgetSelectionBlock } from "./ui"; +import { selectCombinedPreviewMode } from "./gitModSelectors"; export const getIsDragging = (state: AppState) => state.ui.widgetDragResize.isDragging; @@ -23,7 +21,7 @@ export const getShouldAllowDrag = createSelector( getIsResizing, getIsDragging, getIsDraggingDisabledInEditor, - combinedPreviewModeSelector, + selectCombinedPreviewMode, snipingModeSelector, getIsAppSettingsPaneWithNavigationTabOpen, getWidgetSelectionBlock, diff --git a/app/client/src/selectors/widgetSelectors.ts b/app/client/src/selectors/widgetSelectors.ts index 4d45777ef4c9..35d648da50bf 100644 --- a/app/client/src/selectors/widgetSelectors.ts +++ b/app/client/src/selectors/widgetSelectors.ts @@ -21,8 +21,8 @@ import { APP_MODE } from "entities/App"; import { getIsTableFilterPaneVisible } from "selectors/tableFilterSelectors"; import { getIsAutoHeightWithLimitsChanging } from "utils/hooks/autoHeightUIHooks"; import { getIsPropertyPaneVisible } from "./propertyPaneSelectors"; -import { combinedPreviewModeSelector } from "./editorSelectors"; import { getIsAnvilLayout } from "layoutSystems/anvil/integrations/selectors"; +import { selectCombinedPreviewMode } from "./gitModSelectors"; export const getIsDraggingOrResizing = (state: AppState) => state.ui.widgetDragResize.isResizing || state.ui.widgetDragResize.isDragging; @@ -186,7 +186,7 @@ export const shouldWidgetIgnoreClicksSelector = (widgetId: string) => { (state: AppState) => state.ui.widgetDragResize.isDragging, (state: AppState) => state.ui.canvasSelection.isDraggingForSelection, getAppMode, - combinedPreviewModeSelector, + selectCombinedPreviewMode, getIsAutoHeightWithLimitsChanging, getAltBlockWidgetSelection, ( diff --git a/app/client/src/utils/hooks/useAllowEditorDragToSelect.ts b/app/client/src/utils/hooks/useAllowEditorDragToSelect.ts index e074a099ac70..a09f5492d648 100644 --- a/app/client/src/utils/hooks/useAllowEditorDragToSelect.ts +++ b/app/client/src/utils/hooks/useAllowEditorDragToSelect.ts @@ -1,13 +1,11 @@ import type { AppState } from "ee/reducers"; -import { - snipingModeSelector, - combinedPreviewModeSelector, -} from "selectors/editorSelectors"; +import { snipingModeSelector } from "selectors/editorSelectors"; import { useSelector } from "react-redux"; import { getIsAppSettingsPaneWithNavigationTabOpen } from "selectors/appSettingsPaneSelectors"; import { getLayoutSystemType } from "selectors/layoutSystemSelectors"; import { LayoutSystemTypes } from "layoutSystems/types"; import { getWidgetSelectionBlock } from "../../selectors/ui"; +import { selectCombinedPreviewMode } from "selectors/gitModSelectors"; export const useAllowEditorDragToSelect = () => { // This state tells us whether a `ResizableComponent` is resizing @@ -42,7 +40,7 @@ export const useAllowEditorDragToSelect = () => { // True when any widget is dragging or resizing, including this one const isResizingOrDragging = !!isResizing || !!isDragging || !!isSelecting; const isSnipingMode = useSelector(snipingModeSelector); - const isPreviewMode = useSelector(combinedPreviewModeSelector); + const isPreviewMode = useSelector(selectCombinedPreviewMode); const isAppSettingsPaneWithNavigationTabOpen = useSelector( getIsAppSettingsPaneWithNavigationTabOpen, ); diff --git a/app/client/src/utils/hooks/useHoverToFocusWidget.ts b/app/client/src/utils/hooks/useHoverToFocusWidget.ts index 10e5f764f06e..a6cf7962de9a 100644 --- a/app/client/src/utils/hooks/useHoverToFocusWidget.ts +++ b/app/client/src/utils/hooks/useHoverToFocusWidget.ts @@ -2,7 +2,7 @@ import { useWidgetSelection } from "./useWidgetSelection"; import { useSelector } from "react-redux"; import { isWidgetFocused } from "selectors/widgetSelectors"; import { getAnvilSpaceDistributionStatus } from "layoutSystems/anvil/integrations/selectors"; -import { combinedPreviewModeSelector } from "selectors/editorSelectors"; +import { selectCombinedPreviewMode } from "selectors/gitModSelectors"; import type { AppState } from "ee/reducers"; import type React from "react"; import { useCurrentAppState } from "pages/Editor/IDE/hooks/useCurrentAppState"; @@ -35,7 +35,7 @@ export const useHoverToFocusWidget = ( const isResizingOrDragging = isResizing || isDragging; // This state tells us whether space redistribution is in process const isDistributingSpace = useSelector(getAnvilSpaceDistributionStatus); - const isPreviewMode = useSelector(combinedPreviewModeSelector); + const isPreviewMode = useSelector(selectCombinedPreviewMode); // When mouse is over this draggable const handleMouseOver = (e: React.MouseEvent) => { focusWidget && diff --git a/app/client/src/widgets/ChartWidget/component/index.test.tsx b/app/client/src/widgets/ChartWidget/component/index.test.tsx index 8c043acb36a3..ee53792993a8 100644 --- a/app/client/src/widgets/ChartWidget/component/index.test.tsx +++ b/app/client/src/widgets/ChartWidget/component/index.test.tsx @@ -22,6 +22,11 @@ import { APP_MODE } from "entities/App"; // eslint-disable-next-line @typescript-eslint/no-explicit-any let container: any; +jest.mock("selectors/gitModSelectors", () => ({ + ...jest.requireActual("selectors/gitModSelectors"), + selectCombinedPreviewMode: jest.fn(() => false), +})); + describe("Chart Widget", () => { const seriesData1: ChartData = { seriesName: "series1", diff --git a/app/client/src/widgets/ChartWidget/component/index.tsx b/app/client/src/widgets/ChartWidget/component/index.tsx index 4ed693b142c3..f2a3280bd7a1 100644 --- a/app/client/src/widgets/ChartWidget/component/index.tsx +++ b/app/client/src/widgets/ChartWidget/component/index.tsx @@ -28,7 +28,7 @@ import { CustomEChartIFrameComponent } from "./CustomEChartIFrameComponent"; import type { AppState } from "ee/reducers"; import { connect } from "react-redux"; import { getWidgetPropsForPropertyPane } from "selectors/propertyPaneSelectors"; -import { combinedPreviewModeSelector } from "selectors/editorSelectors"; +import { selectCombinedPreviewMode } from "selectors/gitModSelectors"; import { getAppMode } from "ee/selectors/applicationSelectors"; import { APP_MODE } from "entities/App"; // Leaving this require here. Ref: https://stackoverflow.com/questions/41292559/could-not-find-a-declaration-file-for-module-module-name-path-to-module-nam/42505940#42505940 @@ -406,7 +406,7 @@ export const mapStateToProps = ( state: AppState, ownProps: ChartComponentProps, ) => { - const isPreviewMode = combinedPreviewModeSelector(state); + const isPreviewMode = selectCombinedPreviewMode(state); const appMode = getAppMode(state); return { diff --git a/app/client/src/widgets/CustomWidget/component/index.tsx b/app/client/src/widgets/CustomWidget/component/index.tsx index eb6740b48cd0..a3cf98d4afbb 100644 --- a/app/client/src/widgets/CustomWidget/component/index.tsx +++ b/app/client/src/widgets/CustomWidget/component/index.tsx @@ -19,7 +19,7 @@ import type { BoxShadow } from "components/designSystems/appsmith/WidgetStyleCon import type { Color } from "constants/Colors"; import { connect } from "react-redux"; import type { AppState } from "ee/reducers"; -import { combinedPreviewModeSelector } from "selectors/editorSelectors"; +import { selectCombinedPreviewMode } from "selectors/gitModSelectors"; import { getWidgetPropsForPropertyPane } from "selectors/propertyPaneSelectors"; import AnalyticsUtil from "ee/utils/AnalyticsUtil"; import { EVENTS } from "./customWidgetscript"; @@ -311,7 +311,7 @@ export const mapStateToProps = ( state: AppState, ownProps: CustomComponentProps, ) => { - const isPreviewMode = combinedPreviewModeSelector(state); + const isPreviewMode = selectCombinedPreviewMode(state); return { needsOverlay: diff --git a/app/client/src/widgets/IframeWidget/component/index.tsx b/app/client/src/widgets/IframeWidget/component/index.tsx index 1958ebd55e36..b16f5bdb2fcb 100644 --- a/app/client/src/widgets/IframeWidget/component/index.tsx +++ b/app/client/src/widgets/IframeWidget/component/index.tsx @@ -9,7 +9,7 @@ import { getAppMode } from "ee/selectors/applicationSelectors"; import { APP_MODE } from "entities/App"; import type { RenderMode } from "constants/WidgetConstants"; import { getAppsmithConfigs } from "ee/configs"; -import { combinedPreviewModeSelector } from "selectors/editorSelectors"; +import { selectCombinedPreviewMode } from "selectors/gitModSelectors"; interface IframeContainerProps { borderColor?: string; @@ -145,7 +145,7 @@ function IframeComponent(props: IframeComponentProps) { }, [srcDoc]); const appMode = useSelector(getAppMode); - const isPreviewMode = useSelector(combinedPreviewModeSelector); + const isPreviewMode = useSelector(selectCombinedPreviewMode); const selectedWidget = useSelector(getWidgetPropsForPropertyPane); return ( diff --git a/app/client/src/widgets/withWidgetProps.tsx b/app/client/src/widgets/withWidgetProps.tsx index 73dfd519687b..5a0f13d6c19d 100644 --- a/app/client/src/widgets/withWidgetProps.tsx +++ b/app/client/src/widgets/withWidgetProps.tsx @@ -25,7 +25,6 @@ import { getMetaWidget, getIsAutoLayoutMobileBreakPoint, getCanvasWidth, - combinedPreviewModeSelector, } from "selectors/editorSelectors"; import { createCanvasWidget, @@ -50,6 +49,7 @@ import { isWidgetSelectedForPropertyPane } from "selectors/propertyPaneSelectors import WidgetFactory from "WidgetProvider/factory"; import { getIsAnvilLayout } from "layoutSystems/anvil/integrations/selectors"; import { endSpan, startRootSpan } from "instrumentation/generateTraces"; +import { selectCombinedPreviewMode } from "selectors/gitModSelectors"; const WIDGETS_WITH_CHILD_WIDGETS = ["LIST_WIDGET", "FORM_WIDGET"]; const WIDGETS_REQUIRING_SELECTED_ANCESTRY = ["MODAL_WIDGET", "TABS_WIDGET"]; @@ -69,7 +69,7 @@ function withWidgetProps(WrappedWidget: typeof BaseWidget) { } = props; const span = startRootSpan("withWidgetProps", { widgetType: type }); - const isPreviewMode = useSelector(combinedPreviewModeSelector); + const isPreviewMode = useSelector(selectCombinedPreviewMode); const canvasWidget = useSelector((state: AppState) => getWidget(state, widgetId), diff --git a/app/client/test/testUtils.tsx b/app/client/test/testUtils.tsx index 9b99d698bb90..0d57bddfc09a 100644 --- a/app/client/test/testUtils.tsx +++ b/app/client/test/testUtils.tsx @@ -49,9 +49,12 @@ interface State { } const setupState = (state?: State) => { let reduxStore = store; + window.history.pushState({}, "Appsmith", state?.url || "/"); + if (state && (state.initialState || state.featureFlags)) { reduxStore = testStore(state.initialState || {}); + if (state.featureFlags) { reduxStore.dispatch( fetchFeatureFlagsSuccess({ @@ -61,10 +64,12 @@ const setupState = (state?: State) => { ); } } + if (state && state.sagasToRun) { reduxStore = testStoreWithTestMiddleWare(reduxStore.getState()); testSagaMiddleware.run(() => rootSaga(state.sagasToRun)); } + const defaultTheme = getCurrentThemeDetails(reduxStore.getState()); return { reduxStore, defaultTheme }; @@ -76,6 +81,7 @@ const customRender = ( options?: Omit<RenderOptions, "queries">, ) => { const { defaultTheme, reduxStore } = setupState(state); + return render( <BrowserRouter> <Provider store={reduxStore}> @@ -92,6 +98,7 @@ const customRender = ( const hookWrapper = (state: State) => { return ({ children }: { children: ReactElement }) => { const { defaultTheme, reduxStore } = setupState(state); + return ( <BrowserRouter> <Provider store={reduxStore}>
f898461f07c8a1324491741925ac43f26e3aa733
2023-07-07 12:16:48
Keyur Paralkar
fix: prevent click event on disabled next page button of table widget (#25119)
false
prevent click event on disabled next page button of table widget (#25119)
fix
diff --git a/app/client/cypress/e2e/Regression/ClientSide/Binding/TableV2_Widget_API_Pagination_spec.js b/app/client/cypress/e2e/Regression/ClientSide/Binding/TableV2_Widget_API_Pagination_spec.js index 8892bd9a4bec..6cc8330afd84 100644 --- a/app/client/cypress/e2e/Regression/ClientSide/Binding/TableV2_Widget_API_Pagination_spec.js +++ b/app/client/cypress/e2e/Regression/ClientSide/Binding/TableV2_Widget_API_Pagination_spec.js @@ -4,6 +4,7 @@ import { entityExplorer, propPane, apiPage, + table, } from "../../../../support/Objects/ObjectsCore"; describe("Test Create Api and Bind to Table widget V2", function () { @@ -34,4 +35,18 @@ describe("Test Create Api and Bind to Table widget V2", function () { .first() .should("contain", "2"); }); + + it("2. Bug #22477: should check whether the next page button is disabled and not clickable when last page is reached", () => { + /** + * Flow: + * Update total records count to 20 + * Click next page + */ + + propPane.UpdatePropertyFieldValue("Total Records", "20"); + agHelper.GetNClick(table._nextPage("v2")); + + agHelper.AssertAttribute(table._nextPage("v2"), "disabled", "disabled"); + agHelper.AssertElementAbsence(commonlocators._toastMsg); + }); }); diff --git a/app/client/src/widgets/TableWidgetV2/component/header/actions/index.tsx b/app/client/src/widgets/TableWidgetV2/component/header/actions/index.tsx index a68eda52cdda..98233cae1319 100644 --- a/app/client/src/widgets/TableWidgetV2/component/header/actions/index.tsx +++ b/app/client/src/widgets/TableWidgetV2/component/header/actions/index.tsx @@ -237,7 +237,13 @@ function Actions(props: ActionsPropsType) { props.pageNo === props.pageCount - 1 } onClick={() => { - props.nextPageClick(); + if ( + !( + !!props.totalRecordsCount && + props.pageNo === props.pageCount - 1 + ) + ) + props.nextPageClick(); }} > <Icon
6343e568dfc54ab44aff36f98fc76b206ff366d2
2023-12-13 18:20:37
Aishwarya-U-R
test: Cypress | Replace static with Dynamic waits - Part II (#29557)
false
Cypress | Replace static with Dynamic waits - Part II (#29557)
test
diff --git a/app/client/cypress/e2e/Regression/Apps/CommunityIssues_Spec.ts b/app/client/cypress/e2e/Regression/Apps/CommunityIssues_Spec.ts index b71a1ac9a79c..97f2d07f675d 100644 --- a/app/client/cypress/e2e/Regression/Apps/CommunityIssues_Spec.ts +++ b/app/client/cypress/e2e/Regression/Apps/CommunityIssues_Spec.ts @@ -6,7 +6,6 @@ import { agHelper, deployMode, propPane, - entityExplorer, locators, assertHelper, draggableWidgets, @@ -38,7 +37,6 @@ describe( assertHelper .WaitForNetworkCall("importNewApplication") .then((response: any) => { - agHelper.Sleep(); const { isPartialImport } = response.body.data; if (isPartialImport) { // should reconnect modal @@ -97,20 +95,16 @@ describe( table.AssertPageNumber(1, "On", "v2"); table.NavigateToNextPage(true, "v2"); //page 2 - agHelper.Sleep(3000); //wait for table navigation to take effect! table.WaitUntilTableLoad(0, 0, "v2"); table.AssertSelectedRow(selectedRow); table.NavigateToNextPage(true, "v2"); //page 3 - agHelper.Sleep(3000); //wait for table navigation to take effect! table.WaitForTableEmpty("v2"); //page 3 table.NavigateToPreviousPage(true, "v2"); //page 2 - agHelper.Sleep(3000); //wait for table navigation to take effect! table.WaitUntilTableLoad(0, 0, "v2"); table.AssertSelectedRow(selectedRow); table.NavigateToPreviousPage(true, "v2"); //page 1 - agHelper.Sleep(3000); //wait for table navigation to take effect! table.WaitUntilTableLoad(0, 0, "v2"); table.AssertSelectedRow(selectedRow); table.AssertPageNumber(1, "On", "v2"); @@ -146,7 +140,6 @@ describe( it("5. Verify Default search text in table as per 'Default search text' property set + Bug 12228", () => { EditorNavigation.SelectEntityByName("Table1", EntityType.Widget); - //propPane.EnterJSContext("Default search text", "Bug", false); propPane.TypeTextIntoField("Default search text", "Bug"); deployMode.DeployApp(); table.AssertSearchText("Bug"); @@ -155,7 +148,6 @@ describe( deployMode.NavigateBacktoEditor(); EditorNavigation.SelectEntityByName("Table1", EntityType.Widget); - //propPane.EnterJSContext("Default search text", "Question", false); propPane.TypeTextIntoField("Default search text", "Quest", true, false); deployMode.DeployApp(); @@ -165,7 +157,6 @@ describe( table.WaitUntilTableLoad(0, 0, "v2"); EditorNavigation.SelectEntityByName("Table1", EntityType.Widget); - //propPane.EnterJSContext("Default search text", "Epic", false); propPane.TypeTextIntoField("Default search text", "Epic"); //Bug 12228 - Searching based on hidden column value should not be allowed deployMode.DeployApp(); table.AssertSearchText("Epic"); @@ -335,7 +326,6 @@ describe( agHelper.ClickButton("Confirm"); agHelper.AssertElementAbsence(locators._toastMsg); //Making sure internal api doesnt throw error - agHelper.Sleep(3000); table.SearchTable("Suggestion"); table.WaitUntilTableLoad(0, 0, "v2"); @@ -349,14 +339,11 @@ describe( }); it("9. Validate Updating issue from Details tab & Verify multiselect widget selected values", () => { - agHelper.Sleep(2000); agHelper.AssertElementAbsence(locators._widgetInDeployed("tabswidget")); - agHelper.Sleep(2000); table.SelectTableRow(0, 1, true, "v2"); agHelper.AssertElementVisibility( locators._widgetInDeployed("tabswidget"), ); - agHelper.Sleep(2000); agHelper .GetNClick(locators._inputWidgetv1InDeployed, 0, true, 0) .type("-updating title"); @@ -388,7 +375,6 @@ describe( // key: 'Enter', // }) - //agHelper.Sleep(2000) //cy.get("body").type("{enter}") // Multiselect check is to verify bug #13588. // Currently, we have commented it. @@ -403,7 +389,6 @@ describe( "multiselectwidget", ); agHelper.ClickButton("Save"); - agHelper.Sleep(2000); table.ReadTableRowColumnData(0, 0, "v2", 2000).then((cellData) => { expect(cellData).to.be.equal("Troubleshooting"); }); @@ -413,18 +398,14 @@ describe( "Adding Title Suggestion via script-updating title", ); }); - - agHelper.Sleep(2000); //allowing time to save! }); it("10. Validate Deleting the newly created issue", () => { - agHelper.Sleep(2000); agHelper.AssertElementAbsence(locators._widgetInDeployed("tabswidget")); table.SelectTableRow(0, 0, true, "v2"); agHelper.AssertElementVisibility( locators._widgetInDeployed("tabswidget"), ); - agHelper.Sleep(); cy.get(table._trashIcon).closest("div").click({ force: true }); agHelper.WaitUntilEleDisappear(locators._widgetInDeployed("tabswidget")); agHelper.AssertElementAbsence(locators._widgetInDeployed("tabswidget")); diff --git a/app/client/cypress/e2e/Regression/Apps/EchoApiCMS_spec.js b/app/client/cypress/e2e/Regression/Apps/EchoApiCMS_spec.js index 6c3713ed9561..75944c8b19c4 100644 --- a/app/client/cypress/e2e/Regression/Apps/EchoApiCMS_spec.js +++ b/app/client/cypress/e2e/Regression/Apps/EchoApiCMS_spec.js @@ -123,7 +123,6 @@ describe( repoName = repName; cy.latestDeployPreview(); - cy.wait(2000); cy.xpath("//span[text()='[email protected]']") .should("be.visible") .click({ force: true }); diff --git a/app/client/cypress/e2e/Regression/Apps/ImportExportForkApplication_spec.js b/app/client/cypress/e2e/Regression/Apps/ImportExportForkApplication_spec.js index c7558dbe9abc..562acb3da965 100644 --- a/app/client/cypress/e2e/Regression/Apps/ImportExportForkApplication_spec.js +++ b/app/client/cypress/e2e/Regression/Apps/ImportExportForkApplication_spec.js @@ -27,14 +27,12 @@ describe( cy.get(homePageLocatores.importAppProgressWrapper).should("be.visible"); cy.wait("@importNewApplication").then((interception) => { - cy.wait(100); // should check reconnect modal openning const { isPartialImport } = interception.response.body.data; if (isPartialImport) { // should reconnect button dataSources.ReconnectSingleDSNAssert("mockdata", "PostgreSQL"); homePage.AssertNCloseImport(); - cy.wait(2000); } else { cy.get(homePageLocatores.toastMessage).should( "contain", @@ -48,7 +46,6 @@ describe( cy.get(homePageLocatores.portalMenuItem) .contains("Rename", { matchCase: false }) .click({ force: true }); - cy.wait(2000); cy.get(homePageLocatores.applicationName + " input").type(appName, { force: true, }); @@ -56,10 +53,8 @@ describe( cy.wait("@updateApplication") .its("response.body.responseMeta.status") .should("eq", 200); - cy.wait(2000); cy.wrap(appName).as("appname"); }); - cy.wait(3000); // validating data binding for the imported application cy.xpath("//input[@value='Submit']").should("be.visible"); cy.xpath("//span[text()='schema_name']").should("be.visible"); @@ -73,12 +68,10 @@ describe( // fork application homePage.NavigateToHome(); cy.get(homePageLocatores.searchInput).type(`${appName}`); - cy.wait(3000); // cy.get(homePage.applicationCard).first().trigger("mouseover"); cy.get(homePageLocatores.appMoreIcon).first().click({ force: true }); cy.get(homePageLocatores.forkAppFromMenu).click({ force: true }); cy.get(homePageLocatores.forkAppWorkspaceButton).click({ force: true }); - cy.wait(4000); // validating data binding for the forked application cy.xpath("//input[@value='Submit']").should("be.visible"); cy.xpath("//span[text()='schema_name']").should("be.visible"); @@ -90,7 +83,6 @@ describe( it("3. Export and import application and validate data binding for the widgets", function () { homePage.NavigateToHome(); cy.get(homePageLocatores.searchInput).clear().type(`${appName}`); - cy.wait(2000); //cy.get(homePageLocatores.applicationCard).first().trigger("mouseover"); cy.get(homePageLocatores.appMoreIcon).first().click({ force: true }); // export application @@ -103,7 +95,8 @@ describe( expect(headers) .to.have.property("content-disposition") .that.includes("attachment;") - .and.includes(`filename*=UTF-8''${appName}.json`); + .and.includes(`filename*=UTF-8''${appName}`) + .and.includes(`.json`); cy.writeFile("cypress/fixtures/exportedApp.json", body, "utf-8"); agHelper.AssertContains("Successfully exported"); agHelper.WaitUntilAllToastsDisappear(); @@ -122,11 +115,8 @@ describe( "cypress/fixtures/exportedApp.json", { force: true }, ); - if (!Cypress.env("AIRGAPPED")) { + if (!Cypress.env("AIRGAPPED")) assertHelper.AssertNetworkStatus("@getReleaseItems"); - } else { - agHelper.Sleep(2000); - } // import exported application in new workspace // cy.get(homePageLocatores.workspaceImportAppButton).click({ force: true }); @@ -138,7 +128,6 @@ describe( cy.get(reconnectDatasourceModal.SkipToAppBtn).click({ force: true, }); - cy.wait(2000); } else { cy.get(homePageLocatores.toastMessage).should( "contain", diff --git a/app/client/cypress/e2e/Regression/Apps/MongoDBShoppingCart_spec.ts b/app/client/cypress/e2e/Regression/Apps/MongoDBShoppingCart_spec.ts index 629837f64abb..c0354fc7ced0 100644 --- a/app/client/cypress/e2e/Regression/Apps/MongoDBShoppingCart_spec.ts +++ b/app/client/cypress/e2e/Regression/Apps/MongoDBShoppingCart_spec.ts @@ -115,7 +115,6 @@ describe("Shopping cart App", { tags: ["@tag.Datasource"] }, function () { // Adding the books to the Add cart form agHelper.GetNClick(appPage.bookname); //Wait for element to be in DOM - agHelper.Sleep(3000); agHelper.AssertElementLength(appPage.inputValues, 9); agHelper.ClearNType( appPage.bookname + "//" + locators._inputField, @@ -170,11 +169,9 @@ describe("Shopping cart App", { tags: ["@tag.Datasource"] }, function () { ); agHelper.GetNClick(appPage.addButton, 0, true); assertHelper.AssertNetworkStatus("@postExecute"); - agHelper.Sleep(3000); // Deleting the book from the cart agHelper.GetNClick(appPage.deleteButton, 1, false); assertHelper.AssertNetworkStatus("@postExecute"); - agHelper.Sleep(3000); assertHelper.AssertNetworkStatus("@postExecute"); // validating that the book is deleted @@ -189,7 +186,6 @@ describe("Shopping cart App", { tags: ["@tag.Datasource"] }, function () { agHelper.GetNClick(appPage.editButton, 0, true); //Wait for all post execute calls to finish - agHelper.Sleep(3000); assertHelper.AssertNetworkExecutionSuccess("@postExecute"); // validating updated value in the cart agHelper diff --git a/app/client/cypress/e2e/Regression/Apps/PgAdmin_spec.js b/app/client/cypress/e2e/Regression/Apps/PgAdmin_spec.js index cf6287a1d7a9..2569414d1873 100644 --- a/app/client/cypress/e2e/Regression/Apps/PgAdmin_spec.js +++ b/app/client/cypress/e2e/Regression/Apps/PgAdmin_spec.js @@ -65,8 +65,7 @@ describe("PgAdmin Clone App", { tags: ["@tag.Datasource"] }, function () { it("2. Add new table from app page, View and Delete table", function () { deployMode.DeployApp(locators._widgetInDeployed(draggableWidgets.BUTTON)); // adding new table - cy.xpath(appPage.addNewtable).click({ force: true }); - cy.wait(2000); + agHelper.GetNClick(appPage.addNewtable, 0, true); agHelper.AssertElementAbsence(appPage.loadButton, 40000); //for CI agHelper.WaitUntilEleAppear(appPage.addTablename); cy.generateUUID().then((UUID) => { @@ -85,8 +84,7 @@ describe("PgAdmin Clone App", { tags: ["@tag.Datasource"] }, function () { // switching on the Not Null toggle cy.get(widgetsPage.switchWidgetInactive).last().click(); cy.xpath(appPage.submitButton).click({ force: true }); - cy.xpath(appPage.addColumn).should("be.visible"); - cy.wait(500); + agHelper.AssertElementVisibility(appPage.addColumn); cy.xpath(appPage.submitButton).first().click({ force: true }); cy.xpath(appPage.closeButton).click({ force: true }); cy.xpath(appPage.addNewtable).should("be.visible"); diff --git a/app/client/cypress/e2e/Regression/Apps/PromisesApp_spec.js b/app/client/cypress/e2e/Regression/Apps/PromisesApp_spec.js index 1036f7bcc6e3..3c38edea9cdf 100644 --- a/app/client/cypress/e2e/Regression/Apps/PromisesApp_spec.js +++ b/app/client/cypress/e2e/Regression/Apps/PromisesApp_spec.js @@ -11,19 +11,22 @@ import EditorNavigation, { } from "../../../support/Pages/EditorNavigation"; const commonlocators = require("../../../locators/commonlocators.json"); -describe("JSEditor tests", { tags: ["@tag.Widget", "@tag.JS"] }, function () { - before(() => { - agHelper.AddDsl("promisesStoreValueDsl"); - }); +describe( + "Promises App tests", + { tags: ["@tag.Widget", "@tag.JS"] }, + function () { + before(() => { + agHelper.AddDsl("promisesStoreValueDsl"); + }); - it("1. Testing promises with resetWidget, storeValue action and API call", () => { - apiPage.CreateAndFillApi( - dataManager.dsValues[dataManager.defaultEnviorment].mockApiUrl, - "TC1api", - ); - apiPage.RunAPI(); - jsEditor.CreateJSObject( - `export default { + it("1. Testing promises with resetWidget, storeValue action and API call", () => { + apiPage.CreateAndFillApi( + dataManager.dsValues[dataManager.defaultEnviorment].mockApiUrl, + "TC1api", + ); + apiPage.RunAPI(); + jsEditor.CreateJSObject( + `export default { myFun1: async () => { //comment await this.clearStore() //clear store value before running the case return resetWidget('Switch1') @@ -50,84 +53,81 @@ describe("JSEditor tests", { tags: ["@tag.Widget", "@tag.JS"] }, function () { }) } }`, - { - paste: true, - completeReplace: true, - toRun: false, - shouldCreateNewJSObj: true, - }, - ); - EditorNavigation.SelectEntityByName("Page1", EntityType.Page); - cy.wait(2000); - // verify text in the text widget - cy.get(".t--draggable-textwidget span") - .eq(5) - .invoke("text") - .then((text) => { - expect(text).to.equal( - "Step 4: Value is Green and will default to undefined", - ); + { + paste: true, + completeReplace: true, + toRun: false, + shouldCreateNewJSObj: true, + }, + ); + EditorNavigation.SelectEntityByName("Page1", EntityType.Page); + cy.wait("@getPage"); + // verify text in the text widget + + agHelper.AssertText( + ".t--draggable-textwidget span", + "text", + "Step 4: Value is Green and will default to undefined", + 5, + ); + // toggle off the switch + cy.get(".t--switch-widget-active .bp3-control-indicator").click({ + force: true, }); - // toggle off the switch - cy.get(".t--switch-widget-active .bp3-control-indicator").click({ - force: true, - }); - agHelper.AssertContains("Switch widget has changed"); + agHelper.AssertContains("Switch widget has changed"); + + // select an option from select widget + cy.get(".bp3-button.select-button").click({ force: true }); + cy.get(".menu-item-text").eq(2).click({ force: true }); + // verify text in the text widget - // select an option from select widget - cy.get(".bp3-button.select-button").click({ force: true }); - cy.get(".menu-item-text").eq(2).click({ force: true }); - cy.wait(2000); - // verify text in the text widget - cy.get(".t--draggable-textwidget span") - .eq(5) - .invoke("text") - .then((text) => { - expect(text).to.equal( - "Step 4: Value is Red and will default to undefined", - ); + agHelper.AssertText( + ".t--draggable-textwidget span", + "text", + "Step 4: Value is Red and will default to undefined", + 5, + ); + // move to page 2 on table widget + agHelper.GetNClick(commonlocators.tableNextPage); + cy.get(".t--table-widget-page-input").within(() => { + cy.get("input.bp3-input").should("have.value", "2"); }); - // move to page 2 on table widget - agHelper.GetNClick(commonlocators.tableNextPage); - cy.get(".t--table-widget-page-input").within(() => { - cy.get("input.bp3-input").should("have.value", "2"); - }); - cy.wait(1000); - // hit audio play button and trigger actions - EditorNavigation.SelectEntityByName("Audio1", EntityType.Widget); - agHelper.GetElement("audio").then(($audio) => { - $audio[0].play(); - }); - assertHelper.AssertNetworkStatus("@postExecute"); - // verify text is visible - agHelper.AssertContains( - "Step 4: Value is Green and will default to GREEN", - "be.visible", - ".t--draggable-textwidget span", - ); + // hit audio play button and trigger actions + EditorNavigation.SelectEntityByName("Audio1", EntityType.Widget); + agHelper.GetElement("audio").then(($audio) => { + $audio[0].play(); + }); + assertHelper.AssertNetworkStatus("@postExecute"); + // verify text is visible + agHelper.AssertContains( + "Step 4: Value is Green and will default to GREEN", + "be.visible", + ".t--draggable-textwidget span", + ); - agHelper.GetNClick(commonlocators.tableNextPage); - agHelper.ValidateToastMessage("Success running API query"); - agHelper.ValidateToastMessage("GREEN"); - agHelper.GetElement(".t--table-widget-page-input").within(() => { - agHelper.ValidateFieldInputValue("input.bp3-input", "2"); + agHelper.GetNClick(commonlocators.tableNextPage); + agHelper.ValidateToastMessage("Success running API query"); + agHelper.ValidateToastMessage("GREEN"); + agHelper.GetElement(".t--table-widget-page-input").within(() => { + agHelper.ValidateFieldInputValue("input.bp3-input", "2"); + }); }); - }); - it("2. Testing dynamic widgets display using consecutive storeValue calls", () => { - EditorNavigation.SelectEntityByName("JSObject1", EntityType.JSObject); - jsEditor.SelectFunctionDropdown("clearStore"); - jsEditor.RunJSObj(); - EditorNavigation.SelectEntityByName("Page1", EntityType.Page); - cy.xpath("//span[text()='Clear store']").click({ force: true }); - cy.get(".t--draggable-textwidget span") - .eq(5) - .invoke("text") - .then((text) => { - expect(text).to.equal( - "Step 4: Value is Green and will default to undefined", - ); - }); - }); -}); + it("2. Testing dynamic widgets display using consecutive storeValue calls", () => { + EditorNavigation.SelectEntityByName("JSObject1", EntityType.JSObject); + jsEditor.SelectFunctionDropdown("clearStore"); + jsEditor.RunJSObj(); + EditorNavigation.SelectEntityByName("Page1", EntityType.Page); + cy.xpath("//span[text()='Clear store']").click({ force: true }); + cy.get(".t--draggable-textwidget span") + .eq(5) + .invoke("text") + .then((text) => { + expect(text).to.equal( + "Step 4: Value is Green and will default to undefined", + ); + }); + }); + }, +); diff --git a/app/client/cypress/e2e/Regression/ClientSide/Widgets/ListV2/ListV2_PageNo_PageSize_spec.js b/app/client/cypress/e2e/Regression/ClientSide/Widgets/ListV2/ListV2_PageNo_PageSize_spec.js index 4ba8e32845b8..c8338b170b63 100644 --- a/app/client/cypress/e2e/Regression/ClientSide/Widgets/ListV2/ListV2_PageNo_PageSize_spec.js +++ b/app/client/cypress/e2e/Regression/ClientSide/Widgets/ListV2/ListV2_PageNo_PageSize_spec.js @@ -157,90 +157,46 @@ describe("List widget V2 page number and page size", () => { .should("have.text", "PageSize 2"); }); - it( - "excludeForAirgap", - "3. should reset page no if higher than max when switched from server side to client side", - () => { - cy.addDsl(dslWithServerSide); - // Open Datasource editor - cy.wait(2000); - _.dataSources.CreateMockDB("Users").then(() => { - _.dataSources.CreateQueryAfterDSSaved(); - _.dataSources.ToggleUsePreparedStatement(false); - }); - // writing query to get the schema - _.dataSources.EnterQuery( - "SELECT * FROM users OFFSET {{List1.pageNo * List1.pageSize}} LIMIT {{List1.pageSize}};", - ); - - cy.WaitAutoSave(); - - cy.runQuery(); - - EditorNavigation.SelectEntityByName("Page1", EntityType.Page); - - cy.wait(1000); - - // Click next page in list widget - cy.get(".t--list-widget-next-page") - .find("button") - .click({ force: true }) - .wait(1000); - - // Change to client side pagination - cy.openPropertyPane("listwidgetv2"); - cy.togglebarDisable(".t--property-control-serversidepagination input"); - - cy.wait(2000); - - cy.get(".t--widget-containerwidget").should("have.length", 3); - }, - ); - - it( - "airgap", - "3. should reset page no if higher than max when switched from server side to client side - airgap", - () => { - cy.addDsl(dslWithServerSide); - // Open Datasource editor - cy.wait(2000); - _.dataSources.CreateDataSource("Postgres"); - _.dataSources.CreateQueryAfterDSSaved(); + it("3. should reset page no if higher than max when switched from server side to client side", () => { + cy.addDsl(dslWithServerSide); + // Open Datasource editor + cy.wait(2000); + _.dataSources.CreateDataSource("Postgres"); + _.dataSources.CreateQueryAfterDSSaved(); - // Click the editing field - cy.get(".t--action-name-edit-field").click({ force: true }); + // Click the editing field + cy.get(".t--action-name-edit-field").click({ force: true }); - // Click the editing field - cy.get(queryLocators.queryNameField).type("Query1"); + // Click the editing field + cy.get(queryLocators.queryNameField).type("Query1"); - // switching off Use Prepared Statement toggle - cy.get(queryLocators.switch).last().click({ force: true }); + // switching off Use Prepared Statement toggle + cy.get(queryLocators.switch).last().click({ force: true }); - _.dataSources.EnterQuery( - "SELECT * FROM users OFFSET {{List1.pageNo * 1}} LIMIT {{List1.pageSize}};", - ); + _.dataSources.EnterQuery( + "SELECT * FROM users OFFSET {{List1.pageNo * 1}} LIMIT {{List1.pageSize}};", + ); - cy.WaitAutoSave(); + cy.WaitAutoSave(); - cy.runQuery(); + cy.runQuery(); - EditorNavigation.SelectEntityByName("Page1", EntityType.Page); + EditorNavigation.SelectEntityByName("Page1", EntityType.Page); - cy.wait(1000); + cy.wait(1000); - // Click next page in list widget - cy.get(".t--list-widget-next-page") - .find("button") - .click({ force: true }) - .wait(1000); + // Click next page in list widget + cy.get(".t--list-widget-next-page") + .find("button") + .click({ force: true }) + .wait(1000); - // Change to client side pagination - cy.openPropertyPane("listwidgetv2"); - cy.togglebarDisable(".t--property-control-serversidepagination input"); + // Change to client side pagination + cy.openPropertyPane("listwidgetv2"); + cy.togglebarDisable(".t--property-control-serversidepagination input"); - cy.wait(2000); + cy.wait(2000); - cy.get(".t--widget-containerwidget").should("have.length", 2); - }, - ); + cy.get(".t--widget-containerwidget").should("have.length", 2); + }); }); diff --git a/app/client/cypress/e2e/Regression/ClientSide/Widgets/ListV2/Listv2_BasicServerSideData_spec.js b/app/client/cypress/e2e/Regression/ClientSide/Widgets/ListV2/Listv2_BasicServerSideData_spec.js index 58bfb57a9666..e2fc2be8f872 100644 --- a/app/client/cypress/e2e/Regression/ClientSide/Widgets/ListV2/Listv2_BasicServerSideData_spec.js +++ b/app/client/cypress/e2e/Regression/ClientSide/Widgets/ListV2/Listv2_BasicServerSideData_spec.js @@ -3,134 +3,58 @@ import EditorNavigation, { } from "../../../../../support/Pages/EditorNavigation"; const publishLocators = require("../../../../../locators/publishWidgetspage.json"); -const datasource = require("../../../../../locators/DatasourcesEditor.json"); const queryLocators = require("../../../../../locators/QueryEditor.json"); const commonlocators = require("../../../../../locators/commonlocators.json"); import * as _ from "../../../../../support/Objects/ObjectsCore"; - const toggleJSButton = (name) => `.t--property-control-${name} .t--js-toggle`; describe("List widget v2 - Basic server side data tests", () => { before(() => { _.agHelper.AddDsl("Listv2/listWithServerSideData"); // Open Datasource editor - if (!Cypress.env("AIRGAPPED")) { - cy.wait(2000); - // Create sample(mock) user database. - _.dataSources.CreateMockDB("Users").then(() => { - _.dataSources.CreateQueryAfterDSSaved(); - _.dataSources.ToggleUsePreparedStatement(false); - _.dataSources.EnterQuery( - "SELECT * FROM users OFFSET {{List1.pageNo * List1.pageSize}} LIMIT {{List1.pageSize}};", - ); - _.dataSources.RunQuery(); - }); - EditorNavigation.SelectEntityByName("Page1", EntityType.Page); - } else { - cy.wait(2000); - _.dataSources.CreateDataSource("Postgres"); - cy.get("@dsName").then(() => { - _.dataSources.CreateQueryAfterDSSaved( - "SELECT * FROM users OFFSET {{List1.pageNo * 1}} LIMIT {{List1.pageSize}};", - ); - _.dataSources.ToggleUsePreparedStatement(false); - _.dataSources.RunQuery(); - }); - EditorNavigation.SelectEntityByName("Page1", EntityType.Page); - } + _.dataSources.CreateDataSource("Postgres"); + cy.get("@dsName").then(() => { + _.dataSources.CreateQueryAfterDSSaved( + "SELECT * FROM users OFFSET {{List1.pageNo * 1}} LIMIT {{List1.pageSize}};", + ); + _.dataSources.ToggleUsePreparedStatement(false); + _.dataSources.RunQuery(); + }); + EditorNavigation.SelectEntityByName("Page1", EntityType.Page); }); - it( - "excludeForAirgap", - "1. shows correct number of items and binding texts", - () => { - cy.wait(2000); - cy.get(publishLocators.containerWidget).should("have.length", 3); - cy.get(publishLocators.imageWidget).should("have.length", 3); - cy.get(publishLocators.textWidget).should("have.length", 6); - - cy.get(publishLocators.containerWidget).each(($containerEl) => { - cy.wrap($containerEl) - .get(publishLocators.textWidget) - .eq(1) - .find("span") - .invoke("text") - .should("have.length.gt", 0); - }); - }, - ); - it( - "airgap", - "1. shows correct number of items and binding texts - airgap", - () => { - cy.wait(2000); - cy.get(publishLocators.containerWidget).should("have.length", 2); - cy.get(publishLocators.imageWidget).should("have.length", 2); - cy.get(publishLocators.textWidget).should("have.length", 4); - - cy.get(publishLocators.containerWidget).each(($containerEl) => { - cy.wrap($containerEl) - .get(publishLocators.textWidget) - .eq(1) - .find("span") - .invoke("text") - .should("have.length.gt", 0); - }); - }, - ); - - it( - "excludeForAirgap", - "2. next page shows correct number of items and binding text", - () => { - cy.get(".t--list-widget-next-page.rc-pagination-next") - .find("button") - .click({ force: true }); - - cy.get(".rc-pagination-item").contains(2); - - /** - * isLoading of the widget does not work properly so for a moment - * the previous data are visible which can cause the test to pass/fail. - * Adding a wait makes sure the next page data is loaded. - */ - cy.wait(3000); - - cy.get(publishLocators.containerWidget).should("have.length", 3); - cy.get(publishLocators.imageWidget).should("have.length", 3); - cy.get(publishLocators.textWidget).should("have.length", 6); - - cy.get(publishLocators.containerWidget).each(($containerEl) => { - cy.wrap($containerEl) - .get(publishLocators.textWidget) - .eq(1) - .find("span") - .invoke("text") - .should("have.length.gt", 0); - }); - }, - ); - - it( - "airgap", - "2. next page shows correct number of items and binding text - airgap", - () => { - cy.get(".t--list-widget-next-page.rc-pagination-next") - .find("button") - .click({ force: true }); - - cy.get(".rc-pagination-item").contains(2); - cy.get(publishLocators.containerWidget).should("have.length", 2); - cy.get(publishLocators.imageWidget).should("have.length", 2); - cy.get(publishLocators.textWidget).should("have.length", 4); - /** - * isLoading of the widget does not work properly so for a moment - * the previous data are visible which can cause the test to pass/fail. - * Adding a wait makes sure the next page data is loaded. - */ - cy.wait(3000); - }, - ); + it("1. shows correct number of items and binding texts", () => { + cy.wait(2000); + cy.get(publishLocators.containerWidget).should("have.length", 2); + cy.get(publishLocators.imageWidget).should("have.length", 2); + cy.get(publishLocators.textWidget).should("have.length", 4); + + cy.get(publishLocators.containerWidget).each(($containerEl) => { + cy.wrap($containerEl) + .get(publishLocators.textWidget) + .eq(1) + .find("span") + .invoke("text") + .should("have.length.gt", 0); + }); + }); + + it("2. next page shows correct number of items and binding text", () => { + cy.get(".t--list-widget-next-page.rc-pagination-next") + .find("button") + .click({ force: true }); + + cy.get(".rc-pagination-item").contains(2); + cy.get(publishLocators.containerWidget).should("have.length", 2); + cy.get(publishLocators.imageWidget).should("have.length", 2); + cy.get(publishLocators.textWidget).should("have.length", 4); + /** + * isLoading of the widget does not work properly so for a moment + * the previous data are visible which can cause the test to pass/fail. + * Adding a wait makes sure the next page data is loaded. + */ + cy.wait(3000); + }); it("3. re-runs query of page 1 when reset", () => { // Modify onPageChange @@ -178,116 +102,50 @@ describe("List widget v2 - Basic server side data tests", () => { cy.get(commonlocators.toastmsg).should("exist").should("have.length", 1); }); - it( - "excludeForAirgap", - "4. retains input values when pages are switched", - () => { - // Type a number in each of the item's input widget - cy.get(".t--draggable-inputwidgetv2").each(($inputWidget, index) => { - cy.wrap($inputWidget) - .find("input") - .type(index + 1); - }); - - // Verify the typed value - cy.get(".t--draggable-inputwidgetv2").each(($inputWidget, index) => { - cy.wrap($inputWidget) - .find("input") - .should("have.value", index + 1); - }); - - // Go to page 2 - cy.get(".t--list-widget-next-page.rc-pagination-next") - .find("button") - .click({ force: true }); - - cy.get(".rc-pagination-item").contains(2); - - /** - * isLoading of the widget does not work properly so for a moment - * the previous data are visible which can cause the test to pass/fail. - * Adding a wait makes sure the next page data is loaded. - */ - cy.wait(5000); - - // Type a number in each of the item's input widget - cy.get(".t--draggable-inputwidgetv2").each(($inputWidget, index) => { - cy.wrap($inputWidget) - .find("input") - .type(index + 4); - }); - - // Verify the typed value - cy.get(".t--draggable-inputwidgetv2").each(($inputWidget, index) => { - cy.wrap($inputWidget) - .find("input") - .should("have.value", index + 4); - }); - - // Go to page 1 - cy.get(".t--list-widget-prev-page.rc-pagination-prev") - .find("button") - .click({ force: true }); - - cy.get(".rc-pagination-item").contains(1).wait(5000); - - // Verify if previously the typed values are retained - cy.get(".t--draggable-inputwidgetv2").each(($inputWidget, index) => { - cy.wrap($inputWidget) - .find("input") - .should("have.value", index + 1); - }); - }, - ); - - it( - "airgap", - "4. retains input values when pages are switched - airgap", - () => { - // Type a number in each of the item's input widget - cy.get(".t--draggable-inputwidgetv2").each(($inputWidget, index) => { - cy.wrap($inputWidget) - .find("input") - .clear() - .type(index + 1); - }); - - // Verify the typed value - cy.get(".t--draggable-inputwidgetv2").each(($inputWidget, index) => { - cy.wrap($inputWidget) - .find("input") - .should("have.value", index + 1); - }); - - // Go to page 2 - cy.get(".t--list-widget-next-page.rc-pagination-next") - .find("button") - .click({ force: true }); - - cy.get(".rc-pagination-item").contains(2); - - /** - * isLoading of the widget does not work properly so for a moment - * the previous data are visible which can cause the test to pass/fail. - * Adding a wait makes sure the next page data is loaded. - */ - cy.wait(5000); - - // Go to page 1 - cy.get(".t--list-widget-prev-page.rc-pagination-prev") - .find("button") - .click({ force: true }); - - cy.get(".rc-pagination-item").contains(1).wait(5000); - - // Verify if previously the typed values are retained - cy.get(".t--draggable-inputwidgetv2").each(($inputWidget, index) => { - cy.wrap($inputWidget) - .find("input") - .should("have.value", index + 1); - }); - }, - ); + it("4. retains input values when pages are switched", () => { + // Type a number in each of the item's input widget + cy.get(".t--draggable-inputwidgetv2").each(($inputWidget, index) => { + cy.wrap($inputWidget) + .find("input") + .clear() + .type(index + 1); + }); + + // Verify the typed value + cy.get(".t--draggable-inputwidgetv2").each(($inputWidget, index) => { + cy.wrap($inputWidget) + .find("input") + .should("have.value", index + 1); + }); + + // Go to page 2 + cy.get(".t--list-widget-next-page.rc-pagination-next") + .find("button") + .click({ force: true }); + + cy.get(".rc-pagination-item").contains(2); + + /** + * isLoading of the widget does not work properly so for a moment + * the previous data are visible which can cause the test to pass/fail. + * Adding a wait makes sure the next page data is loaded. + */ + cy.wait(5000); + + // Go to page 1 + cy.get(".t--list-widget-prev-page.rc-pagination-prev") + .find("button") + .click({ force: true }); + + cy.get(".rc-pagination-item").contains(1).wait(5000); + + // Verify if previously the typed values are retained + cy.get(".t--draggable-inputwidgetv2").each(($inputWidget, index) => { + cy.wrap($inputWidget) + .find("input") + .should("have.value", index + 1); + }); + }); it("5. Total Record Count", () => { cy.openPropertyPane("listwidgetv2"); @@ -322,92 +180,41 @@ describe("List widget v2 - Basic server side data tests", () => { cy.get(commonlocators.toastmsg).should("exist"); }); - it( - "excludeForAirgap", - "6. no of items rendered should be equal to page size", - () => { - cy.NavigateToDatasourceEditor(); - - // Click on sample(mock) user database. - // Choose the first data source which consists of users keyword & Click on the "New query +"" button - cy.get(datasource.mockUserDatabase).click(); - - _.dataSources.CreateQueryAfterDSSaved(); - - // Click the editing field - cy.get(".t--action-name-edit-field").click({ - force: true, - }); - - // Click the editing field - cy.get(queryLocators.queryNameField).type("Query2"); - - // switching off Use Prepared Statement toggle - cy.get(queryLocators.switch).last().click({ - force: true, - }); - - //.1: Click on Write query area - - _.dataSources.EnterQuery("SELECT * FROM users LIMIT 20;"); + it("6. no of items rendered should be equal to page size", () => { + _.dataSources.CreateDataSource("Postgres"); + cy.wait(1000); + _.dataSources.CreateQueryAfterDSSaved(); + // Click the editing field + cy.get(".t--action-name-edit-field").click({ + force: true, + }); - cy.WaitAutoSave(); + // Click the editing field + cy.get(queryLocators.queryNameField).type("Query2"); - cy.runQuery(); + // switching off Use Prepared Statement toggle + cy.get(queryLocators.switch).last().click({ + force: true, + }); - EditorNavigation.SelectEntityByName("Page1", EntityType.Page); + //.1: Click on Write query area + _.dataSources.EnterQuery("SELECT * FROM users LIMIT 20;"); - cy.wait(1000); + cy.WaitAutoSave(); - cy.openPropertyPane("listwidgetv2"); + cy.runQuery(); - cy.testJsontext("items", "{{Query2.data}}"); + EditorNavigation.SelectEntityByName("Page1", EntityType.Page); - cy.wait(1000); + cy.wait(1000); - // Check if container no of containers are still 3 - cy.get(publishLocators.containerWidget).should("have.length", 3); - }, - ); - it( - "airgap", - "7. no of items rendered should be equal to page size - airgap", - () => { - _.dataSources.CreateDataSource("Postgres"); - cy.wait(1000); - _.dataSources.CreateQueryAfterDSSaved(); - // Click the editing field - cy.get(".t--action-name-edit-field").click({ - force: true, - }); - - // Click the editing field - cy.get(queryLocators.queryNameField).type("Query2"); - - // switching off Use Prepared Statement toggle - cy.get(queryLocators.switch).last().click({ - force: true, - }); - - //.1: Click on Write query area - _.dataSources.EnterQuery("SELECT * FROM users LIMIT 20;"); - - cy.WaitAutoSave(); - - cy.runQuery(); - - EditorNavigation.SelectEntityByName("Page1", EntityType.Page); - - cy.wait(1000); - - cy.openPropertyPane("listwidgetv2"); + cy.openPropertyPane("listwidgetv2"); - cy.testJsontext("items", "{{Query2.data}}"); + cy.testJsontext("items", "{{Query2.data}}"); - cy.wait(1000); + cy.wait(1000); - // Check if container no of containers are still 3 - cy.get(publishLocators.containerWidget).should("have.length", 3); - }, - ); + // Check if container no of containers are still 3 + cy.get(publishLocators.containerWidget).should("have.length", 3); + }); }); diff --git a/app/client/cypress/e2e/Sanity/Datasources/MockDBs_Spec.ts b/app/client/cypress/e2e/Sanity/Datasources/MockDBs_Spec.ts index bc274799c6bc..66961040916a 100644 --- a/app/client/cypress/e2e/Sanity/Datasources/MockDBs_Spec.ts +++ b/app/client/cypress/e2e/Sanity/Datasources/MockDBs_Spec.ts @@ -34,7 +34,7 @@ describe( 'SELECT * FROM public."users" LIMIT 10;', ); - dataSources.RunQueryNVerifyResponseViews(5); //minimum 5 rows are expected + dataSources.RunQueryNVerifyResponseViews(); //minimum 1 rows are expected AppSidebar.navigate(AppSidebarButton.Data); dataSources .getDatasourceListItemDescription(mockDBName) @@ -43,7 +43,7 @@ describe( ); entityExplorer.CreateNewDsQuery(mockDBName); - dataSources.RunQueryNVerifyResponseViews(10, true); + dataSources.RunQueryNVerifyResponseViews(); //minimum 1 rows are expected AppSidebar.navigate(AppSidebarButton.Data); dataSources .getDatasourceListItemDescription(mockDBName)
3df028d5a49913accd46de1c9eec77ab100b70cc
2025-02-27 15:17:38
Ankita Kinger
chore: Removing cyclic dependencies due to Sentry route (#39471)
false
Removing cyclic dependencies due to Sentry route (#39471)
chore
diff --git a/app/client/src/ce/AppRouter.tsx b/app/client/src/ce/AppRouter.tsx index 6d4f72eea78c..90e30f8001dc 100644 --- a/app/client/src/ce/AppRouter.tsx +++ b/app/client/src/ce/AppRouter.tsx @@ -1,7 +1,7 @@ import React, { Suspense, useEffect } from "react"; import history from "utils/history"; import AppHeader from "ee/pages/common/AppHeader"; -import { Redirect, Route, Router, Switch } from "react-router-dom"; +import { Redirect, Router, Switch } from "react-router-dom"; import { ADMIN_SETTINGS_CATEGORY_PATH, ADMIN_SETTINGS_PATH, @@ -43,7 +43,6 @@ import PageLoadingBar from "pages/common/PageLoadingBar"; import ErrorPageHeader from "pages/common/ErrorPageHeader"; import { useDispatch, useSelector } from "react-redux"; -import * as Sentry from "@sentry/react"; import { getSafeCrash, getSafeCrashCode } from "selectors/errorSelectors"; import UserProfile from "pages/UserProfile"; import Setup from "pages/setup"; @@ -64,8 +63,7 @@ import { FEATURE_FLAG } from "ee/entities/FeatureFlag"; import CustomWidgetBuilderLoader from "pages/Editor/CustomWidgetBuilder/loader"; import { getIsConsolidatedPageLoading } from "selectors/ui"; import { useFeatureFlagOverride } from "utils/hooks/useFeatureFlagOverride"; - -export const SentryRoute = Sentry.withSentryRouting(Route); +import { SentryRoute } from "components/SentryRoute"; export const loadingIndicator = <PageLoadingBar />; diff --git a/app/client/src/ce/components/WorkspaceSettingsTabs/index.tsx b/app/client/src/ce/components/WorkspaceSettingsTabs/index.tsx index da68513cda89..2f80611cec0c 100644 --- a/app/client/src/ce/components/WorkspaceSettingsTabs/index.tsx +++ b/app/client/src/ce/components/WorkspaceSettingsTabs/index.tsx @@ -1,19 +1,13 @@ import React, { useCallback, useEffect, useMemo } from "react"; -import { - useRouteMatch, - Route, - useLocation, - useHistory, -} from "react-router-dom"; +import { useRouteMatch, useLocation, useHistory } from "react-router-dom"; import MemberSettings from "ee/pages/workspace/Members"; import { GeneralSettings } from "pages/workspace/General"; import { Tabs, Tab, TabsList, TabPanel } from "@appsmith/ads"; import { navigateToTab } from "ee/pages/workspace/helpers"; import styled from "styled-components"; -import * as Sentry from "@sentry/react"; import { APPLICATIONS_URL } from "constants/routes/baseRoutes"; -export const SentryRoute = Sentry.withSentryRouting(Route); +import { SentryRoute } from "components/SentryRoute"; export const TabsWrapper = styled.div` padding-top: var(--ads-v2-spaces-4); diff --git a/app/client/src/components/SentryRoute.tsx b/app/client/src/components/SentryRoute.tsx new file mode 100644 index 000000000000..a5cac6a7f9d8 --- /dev/null +++ b/app/client/src/components/SentryRoute.tsx @@ -0,0 +1,4 @@ +import * as Sentry from "@sentry/react"; +import { Route } from "react-router"; + +export const SentryRoute = Sentry.withSentryRouting(Route); diff --git a/app/client/src/pages/AppIDE/layouts/components/Editor.tsx b/app/client/src/pages/AppIDE/layouts/components/Editor.tsx index 5b8bab55c841..136bdb581196 100644 --- a/app/client/src/pages/AppIDE/layouts/components/Editor.tsx +++ b/app/client/src/pages/AppIDE/layouts/components/Editor.tsx @@ -1,7 +1,6 @@ import React from "react"; import { Flex } from "@appsmith/ads"; import { Switch, useRouteMatch } from "react-router"; -import { SentryRoute } from "ee/AppRouter"; import { jsSegmentRoutes, querySegmentRoutes, @@ -12,6 +11,7 @@ import EditorTabs from "./EditorTabs"; import { useCurrentEditorState } from "../../hooks/useCurrentEditorState"; import { EditorEntityTab } from "IDE/Interfaces/EditorTypes"; import styled from "styled-components"; +import { SentryRoute } from "components/SentryRoute"; const Container = styled(Flex)` // Animating using https://developer.mozilla.org/en-US/docs/Web/API/View_Transitions_API diff --git a/app/client/src/pages/AppIDE/layouts/components/Explorer.tsx b/app/client/src/pages/AppIDE/layouts/components/Explorer.tsx index 2a714bb15c2c..98fd20865f22 100644 --- a/app/client/src/pages/AppIDE/layouts/components/Explorer.tsx +++ b/app/client/src/pages/AppIDE/layouts/components/Explorer.tsx @@ -1,7 +1,6 @@ import React, { useMemo } from "react"; import { ExplorerContainer } from "@appsmith/ads"; import { Switch, useRouteMatch } from "react-router"; -import { SentryRoute } from "ee/AppRouter"; import { jsSegmentRoutes, querySegmentRoutes, @@ -21,6 +20,7 @@ import { getIDEViewMode } from "selectors/ideSelectors"; import { EditorEntityTab, EditorViewMode } from "IDE/Interfaces/EditorTypes"; import { DEFAULT_EXPLORER_PANE_WIDTH } from "constants/AppConstants"; import { useCurrentEditorState } from "../../hooks/useCurrentEditorState"; +import { SentryRoute } from "components/SentryRoute"; const EditorPaneExplorer = () => { const { path } = useRouteMatch(); diff --git a/app/client/src/pages/AppIDE/layouts/routers/JSEditor/JSEditor.tsx b/app/client/src/pages/AppIDE/layouts/routers/JSEditor/JSEditor.tsx index f9d316a1f13a..3c00fa89ead8 100644 --- a/app/client/src/pages/AppIDE/layouts/routers/JSEditor/JSEditor.tsx +++ b/app/client/src/pages/AppIDE/layouts/routers/JSEditor/JSEditor.tsx @@ -1,7 +1,7 @@ import React from "react"; import { Switch, useRouteMatch } from "react-router"; import { JSEditorRoutes } from "ee/pages/AppIDE/layouts/routers/JSEditor/constants"; -import { SentryRoute } from "ee/AppRouter"; +import { SentryRoute } from "components/SentryRoute"; const JSEditorPane = () => { const { path } = useRouteMatch(); diff --git a/app/client/src/pages/AppIDE/layouts/routers/LeftPane.tsx b/app/client/src/pages/AppIDE/layouts/routers/LeftPane.tsx index 039d834e8c36..51ee61ef97f9 100644 --- a/app/client/src/pages/AppIDE/layouts/routers/LeftPane.tsx +++ b/app/client/src/pages/AppIDE/layouts/routers/LeftPane.tsx @@ -1,7 +1,6 @@ import React, { useMemo } from "react"; import { useSelector } from "react-redux"; import { Switch, useRouteMatch } from "react-router"; -import { SentryRoute } from "ee/AppRouter"; import { APP_LIBRARIES_EDITOR_PATH, APP_PACKAGES_EDITOR_PATH, @@ -18,6 +17,7 @@ import LibrarySidePane from "ee/pages/AppIDE/components/LibrariesList/LibrarySid import { getDatasourceUsageCountForApp } from "ee/selectors/entitiesSelector"; import { IDE_TYPE } from "ee/IDE/Interfaces/IDETypes"; import { Flex } from "@appsmith/ads"; +import { SentryRoute } from "components/SentryRoute"; const LeftPane = () => { const { path } = useRouteMatch(); diff --git a/app/client/src/pages/AppIDE/layouts/routers/MainPane/MainPane.tsx b/app/client/src/pages/AppIDE/layouts/routers/MainPane/MainPane.tsx index 2b5dc9bc106b..5f8c9ec4c49a 100644 --- a/app/client/src/pages/AppIDE/layouts/routers/MainPane/MainPane.tsx +++ b/app/client/src/pages/AppIDE/layouts/routers/MainPane/MainPane.tsx @@ -1,13 +1,11 @@ import React from "react"; -import { Route, Switch, useRouteMatch } from "react-router"; -import * as Sentry from "@sentry/react"; +import { Switch, useRouteMatch } from "react-router"; import { MainPaneRoutes } from "ee/pages/AppIDE/layouts/routers/MainPane/constants"; import { useSelector } from "react-redux"; import { selectCombinedPreviewMode } from "selectors/gitModSelectors"; import WidgetsEditor from "pages/Editor/WidgetsEditor"; import { useWidgetSelectionBlockListener } from "../../hooks/useWidgetSelectionBlockListener"; - -const SentryRoute = Sentry.withSentryRouting(Route); +import { SentryRoute } from "components/SentryRoute"; export const MainPane = (props: { id: string }) => { const { path } = useRouteMatch(); diff --git a/app/client/src/pages/AppIDE/layouts/routers/QueryEditor/Editor.tsx b/app/client/src/pages/AppIDE/layouts/routers/QueryEditor/Editor.tsx index 08d371d5ac1e..b19758a21fdc 100644 --- a/app/client/src/pages/AppIDE/layouts/routers/QueryEditor/Editor.tsx +++ b/app/client/src/pages/AppIDE/layouts/routers/QueryEditor/Editor.tsx @@ -2,7 +2,7 @@ import React from "react"; import { useRouteMatch } from "react-router"; import { Switch } from "react-router-dom"; import { QueryEditorRoutes } from "ee/pages/AppIDE/layouts/routers/QueryEditor/constants"; -import { SentryRoute } from "ee/AppRouter"; +import { SentryRoute } from "components/SentryRoute"; const QueryEditor = () => { const { path } = useRouteMatch(); diff --git a/app/client/src/pages/AppIDE/layouts/routers/RightPane.tsx b/app/client/src/pages/AppIDE/layouts/routers/RightPane.tsx index 6c185c3645c8..740440968f71 100644 --- a/app/client/src/pages/AppIDE/layouts/routers/RightPane.tsx +++ b/app/client/src/pages/AppIDE/layouts/routers/RightPane.tsx @@ -9,7 +9,7 @@ import { WIDGETS_EDITOR_ID_PATH, } from "constants/routes"; import { useRouteMatch } from "react-router"; -import { SentryRoute } from "ee/AppRouter"; +import { SentryRoute } from "components/SentryRoute"; const RightPane = () => { const { path } = useRouteMatch(); diff --git a/app/client/src/pages/AppIDE/layouts/routers/UISegmentLeftPane/UISegmentLeftPane.tsx b/app/client/src/pages/AppIDE/layouts/routers/UISegmentLeftPane/UISegmentLeftPane.tsx index 32bb42133d37..5b117e701998 100644 --- a/app/client/src/pages/AppIDE/layouts/routers/UISegmentLeftPane/UISegmentLeftPane.tsx +++ b/app/client/src/pages/AppIDE/layouts/routers/UISegmentLeftPane/UISegmentLeftPane.tsx @@ -1,8 +1,6 @@ import React from "react"; import { Flex } from "@appsmith/ads"; import { Switch, useRouteMatch } from "react-router"; - -import { SentryRoute } from "ee/AppRouter"; import { ADD_PATH, BUILDER_CUSTOM_PATH, @@ -19,6 +17,7 @@ import { useFeatureFlag } from "utils/hooks/useFeatureFlag"; import { FEATURE_FLAG } from "ee/entities/FeatureFlag"; import { getHasManagePagePermission } from "ee/utils/BusinessFeatures/permissionPageHelpers"; import { DEFAULT_EXPLORER_PANE_WIDTH } from "constants/AppConstants"; +import { SentryRoute } from "components/SentryRoute"; const UISegment = () => { const { path } = useRouteMatch(); diff --git a/app/client/src/pages/Templates/index.tsx b/app/client/src/pages/Templates/index.tsx index ce56f23d3037..a1cae7b92263 100644 --- a/app/client/src/pages/Templates/index.tsx +++ b/app/client/src/pages/Templates/index.tsx @@ -1,5 +1,4 @@ import type { AppState } from "ee/reducers"; -import * as Sentry from "@sentry/react"; import { fetchDefaultPlugins } from "actions/pluginActions"; import { getAllTemplates, getTemplateFilters } from "actions/templateActions"; import { setHeaderMeta } from "actions/themeActions"; @@ -8,7 +7,7 @@ import { isEmpty } from "lodash"; import ReconnectDatasourceModal from "pages/Editor/gitSync/ReconnectDatasourceModal"; import React, { useEffect } from "react"; import { useDispatch, useSelector } from "react-redux"; -import { Route, Switch, useRouteMatch } from "react-router-dom"; +import { Switch, useRouteMatch } from "react-router-dom"; import { allTemplatesFiltersSelector, getForkableWorkspaces, @@ -21,8 +20,7 @@ import TemplateFilters from "./TemplateFilters"; import { TemplateContent } from "./TemplateContent"; import TemplateView from "./TemplateView"; import { getFetchedWorkspaces } from "ee/selectors/workspaceSelectors"; - -const SentryRoute = Sentry.withSentryRouting(Route); +import { SentryRoute } from "components/SentryRoute"; const PageWrapper = styled.div` margin-top: ${(props) => props.theme.homePage.header}px; diff --git a/app/client/src/pages/UserAuth/index.tsx b/app/client/src/pages/UserAuth/index.tsx index f7d948ef3a0b..f6d2e20c1ef5 100644 --- a/app/client/src/pages/UserAuth/index.tsx +++ b/app/client/src/pages/UserAuth/index.tsx @@ -1,11 +1,10 @@ import React from "react"; -import { Route, Switch, useLocation, useRouteMatch } from "react-router-dom"; +import { Switch, useLocation, useRouteMatch } from "react-router-dom"; import Login from "pages/UserAuth/Login"; import SignUp from "pages/UserAuth/SignUp"; import ForgotPassword from "./ForgotPassword"; import ResetPassword from "./ResetPassword"; import PageNotFound from "pages/common/ErrorPages/PageNotFound"; -import * as Sentry from "@sentry/react"; import { requiresUnauth } from "./requiresAuthHOC"; import { useSelector } from "react-redux"; import { getThemeDetails, ThemeMode } from "selectors/themeSelectors"; @@ -19,8 +18,7 @@ import { useIsMobileDevice } from "utils/hooks/useDeviceDetect"; import { getAssetUrl } from "ee/utils/airgapHelpers"; import { getOrganizationConfig } from "ee/selectors/organizationSelectors"; import { getAppsmithConfigs } from "ee/configs"; - -const SentryRoute = Sentry.withSentryRouting(Route); +import { SentryRoute } from "components/SentryRoute"; export function UserAuth() { const { path } = useRouteMatch(); diff --git a/app/client/src/pages/workspace/index.tsx b/app/client/src/pages/workspace/index.tsx index 65ca0c24ac1b..04537f9e8fc2 100644 --- a/app/client/src/pages/workspace/index.tsx +++ b/app/client/src/pages/workspace/index.tsx @@ -1,10 +1,9 @@ import React from "react"; -import { Switch, useRouteMatch, useLocation, Route } from "react-router-dom"; +import { Switch, useRouteMatch, useLocation } from "react-router-dom"; import PageWrapper from "pages/common/PageWrapper"; import DefaultWorkspacePage from "./defaultWorkspacePage"; import Settings from "./settings"; -import * as Sentry from "@sentry/react"; -const SentryRoute = Sentry.withSentryRouting(Route); +import { SentryRoute } from "components/SentryRoute"; export function Workspace() { const { path } = useRouteMatch();
59e2daf96dce47ddff0c7c8be5af55fa0981b4ca
2024-09-12 11:58:33
Apeksha Bhosale
fix: 503 error recovery (#36252)
false
503 error recovery (#36252)
fix
diff --git a/app/client/src/reducers/uiReducers/errorReducer.tsx b/app/client/src/reducers/uiReducers/errorReducer.tsx index 2cf0535ea4ce..2832193e2dcf 100644 --- a/app/client/src/reducers/uiReducers/errorReducer.tsx +++ b/app/client/src/reducers/uiReducers/errorReducer.tsx @@ -38,6 +38,28 @@ const errorReducer = createReducer(initialState, { [ReduxActionTypes.FLUSH_ERRORS]: () => { return initialState; }, + [ReduxActionTypes.FETCH_CURRENT_TENANT_CONFIG_SUCCESS]: ( + state: ErrorReduxState, + ) => { + if ( + state?.currentError?.sourceAction === "FETCH_CURRENT_TENANT_CONFIG_ERROR" + ) { + return { + ...state, + ...initialState, + }; + } + return state; + }, + [ReduxActionTypes.UPDATE_TENANT_CONFIG_SUCCESS]: (state: ErrorReduxState) => { + if (state?.currentError?.sourceAction === "UPDATE_TENANT_CONFIG_ERROR") { + return { + ...state, + ...initialState, + }; + } + return state; + }, }); export interface ErrorReduxState {
990692cc814f442ff4e2a49f1b66bfab814489db
2022-09-02 12:32:51
sneha122
fix: gsheets insert command placeholder issue fixed (#16441)
false
gsheets insert command placeholder issue fixed (#16441)
fix
diff --git a/app/client/cypress/integration/Smoke_TestSuite/ServerSideTests/QueryPane/GoogleSheetsQuery_spec.js b/app/client/cypress/integration/Smoke_TestSuite/ServerSideTests/QueryPane/GoogleSheetsQuery_spec.js new file mode 100644 index 000000000000..a2106b49d9ba --- /dev/null +++ b/app/client/cypress/integration/Smoke_TestSuite/ServerSideTests/QueryPane/GoogleSheetsQuery_spec.js @@ -0,0 +1,44 @@ +import { ObjectsRegistry } from "../../../../support/Objects/Registry"; +const datasource = require("../../../../locators/DatasourcesEditor.json"); +const explorer = require("../../../../locators/explorerlocators.json"); + +let dataSources = ObjectsRegistry.DataSources; +let queryName; +let datasourceName; +let pluginName = "Google Sheets"; +let placeholderText = "{\n \"name\": {{nameInput.text}},\n \"dob\": {{dobPicker.formattedDate}},\n \"gender\": {{genderSelect.selectedOptionValue}} \n}" + +describe("Google Sheets datasource row objects placeholder", function() { + it("Bug: 16391 - Google Sheets DS, placeholder objects keys should have quotes", function() { + // create new Google Sheets datasource + dataSources.NavigateToDSCreateNew(); + dataSources.CreatePlugIn(pluginName); + + // navigate to create query tab and create a new query + cy.get("@createDatasource").then((httpResponse) => { + datasourceName = httpResponse.response.body.data.name; + // clicking on new query to write a query + cy.NavigateToQueryEditor(); + cy.get(explorer.createNew).click(); + cy.get("div:contains('" + datasourceName + " Query')").last().click(); + + // fill the create new api google sheets form + // and check for rowobject placeholder text + cy.get(datasource.gSheetsOperationDropdown).click(); + cy.get(datasource.gSheetsInsertOneOption).click(); + + cy.get(datasource.gSheetsEntityDropdown).click(); + cy.get(datasource.gSheetsSheetRowsOption).click(); + + cy.get(datasource.gSheetsCodeMirrorPlaceholder).should('have.text', placeholderText); + + // delete query and datasource after test is done + cy.get("@createNewApi").then((httpResponse) => { + queryName = httpResponse.response.body.data.name; + cy.deleteQueryUsingContext(); + cy.deleteDatasource(datasourceName); + }) + }); + }); + } +); diff --git a/app/client/cypress/locators/DatasourcesEditor.json b/app/client/cypress/locators/DatasourcesEditor.json index 1f1ee619de89..e1e2f8fbb7fe 100644 --- a/app/client/cypress/locators/DatasourcesEditor.json +++ b/app/client/cypress/locators/DatasourcesEditor.json @@ -73,5 +73,11 @@ "useSelfSignedCert": ".t--connection\\.ssl\\.authType", "useCertInAuth": "[data-cy='authentication.useSelfSignedCert'] input", "certificateDetails": "[data-cy='section-Certificate Details']", - "saveBtn": ".t--save-datasource" + "saveBtn": ".t--save-datasource", + "gSheetsOperationDropdown": "[data-cy='actionConfiguration.formData.command.data']", + "gSheetsEntityDropdown": "[data-cy='actionConfiguration.formData.entityType.data']", + "gSheetsInsertOneOption": ".t--dropdown-option:contains('Insert One')", + "gSheetsSheetRowsOption": ".t--dropdown-option:contains('Sheet Row(s)')", + "gSheetsCodeMirrorPlaceholder": ".CodeMirror-placeholder" + } diff --git a/app/server/appsmith-plugins/googleSheetsPlugin/src/main/resources/editor/insert.json b/app/server/appsmith-plugins/googleSheetsPlugin/src/main/resources/editor/insert.json index 5987f330f905..895c56b67224 100644 --- a/app/server/appsmith-plugins/googleSheetsPlugin/src/main/resources/editor/insert.json +++ b/app/server/appsmith-plugins/googleSheetsPlugin/src/main/resources/editor/insert.json @@ -36,7 +36,7 @@ "conditionals": { "show": "{{actionConfiguration.formData.smartSubstitution.data === true && actionConfiguration.formData.entityType.data === 'ROWS' && actionConfiguration.formData.command.data === 'INSERT_ONE'}}" }, - "placeholderText": "{\n name: {{nameInput.text}},\n dob: {{dobPicker.formattedDate}},\n gender: {{genderSelect.selectedOptionValue}} \n}" + "placeholderText": "{\n \"name\": {{nameInput.text}},\n \"dob\": {{dobPicker.formattedDate}},\n \"gender\": {{genderSelect.selectedOptionValue}} \n}" }, { "label": "Row Object", @@ -49,7 +49,7 @@ "conditionals": { "show": "{{actionConfiguration.formData.smartSubstitution.data === false && actionConfiguration.formData.entityType.data === 'ROWS' && actionConfiguration.formData.command.data === 'INSERT_ONE'}}" }, - "placeholderText": "{\n name: {{nameInput.text}},\n dob: {{dobPicker.formattedDate}},\n gender: {{genderSelect.selectedOptionValue}} \n}" + "placeholderText": "{\n \"name\": {{nameInput.text}},\n \"dob\": {{dobPicker.formattedDate}},\n \"gender\": {{genderSelect.selectedOptionValue}} \n}" }, { "label": "Row Object(s)", @@ -61,7 +61,7 @@ "conditionals": { "show": "{{actionConfiguration.formData.smartSubstitution.data === true && ((actionConfiguration.formData.entityType.data === 'ROWS' && actionConfiguration.formData.command.data === 'INSERT_MANY') || (actionConfiguration.formData.entityType.data === 'SPREADSHEET' && actionConfiguration.formData.command.data === 'INSERT_ONE'))}}" }, - "placeholderText": "[{\n name: {{nameInput.text}},\n dob: {{dobPicker.formattedDate}},\n gender: {{genderSelect.selectedOptionValue}} \n}]" + "placeholderText": "[{\n \"name\": {{nameInput.text}},\n \"dob\": {{dobPicker.formattedDate}},\n \"gender\": {{genderSelect.selectedOptionValue}} \n}]" }, { "label": "Row Object(s)", @@ -73,7 +73,7 @@ "conditionals": { "show": "{{actionConfiguration.formData.smartSubstitution.data === false && ((actionConfiguration.formData.entityType.data === 'ROWS' && actionConfiguration.formData.command.data === 'INSERT_MANY') || (actionConfiguration.formData.entityType.data === 'SPREADSHEET' && actionConfiguration.formData.command.data === 'INSERT_ONE'))}}" }, - "placeholderText": "[{\n name: {{nameInput.text}},\n dob: {{dobPicker.formattedDate}},\n gender: {{genderSelect.selectedOptionValue}} \n}]" + "placeholderText": "[{\n \"name\": {{nameInput.text}},\n \"dob\": {{dobPicker.formattedDate}},\n \"gender\": {{genderSelect.selectedOptionValue}} \n}]" } ] }
b24428be59a453fc4d79e6c8765a0e7802cf2d4f
2022-05-25 16:58:30
Chandan Balaji
fix: UI Inconsistencies in Datasource Card and Page
false
UI Inconsistencies in Datasource Card and Page
fix
diff --git a/app/client/src/components/ads/Tabs.tsx b/app/client/src/components/ads/Tabs.tsx index f6ab87175c00..67a5ed2c91e1 100644 --- a/app/client/src/components/ads/Tabs.tsx +++ b/app/client/src/components/ads/Tabs.tsx @@ -8,6 +8,7 @@ import { useEffect } from "react"; import { Indices } from "constants/Layers"; import { theme } from "constants/DefaultTheme"; import useResizeObserver from "utils/hooks/useResizeObserver"; +import { Colors } from "constants/Colors"; export const TAB_MIN_HEIGHT = `36px`; @@ -41,6 +42,8 @@ const TabsWrapper = styled.div<{ flex-direction: ${(props) => (!!props.vertical ? "column" : "row")}; align-items: ${(props) => (!!props.vertical ? "stretch" : "center")}; border-bottom: none; + gap: ${(props) => + !props.vertical ? `${props.theme.spaces[12] + 2}px` : 0}; color: ${(props) => props.theme.colors.tabs.normal}; path { fill: ${(props) => props.theme.colors.tabs.icon}; @@ -74,9 +77,7 @@ const TabsWrapper = styled.div<{ justify-content: center; border-color: transparent; position: relative; - padding: 0px 3px; - margin-right: ${(props) => - !props.vertical ? `${props.theme.spaces[12] - 3}px` : 0}; + padding: 0; ${(props) => props.responseViewer && @@ -134,10 +135,10 @@ const TabsWrapper = styled.div<{ `; export const TabTitle = styled.span<{ responseViewer?: boolean }>` - font-size: ${(props) => props.theme.typography.h5.fontSize}px; - font-weight: ${(props) => props.theme.typography.h5.fontWeight}; - line-height: ${(props) => props.theme.typography.h5.lineHeight - 3}px; - letter-spacing: ${(props) => props.theme.typography.h5.letterSpacing}px; + font-size: ${(props) => props.theme.typography.h4.fontSize}px; + font-weight: ${(props) => props.theme.typography.h4.fontWeight - 100}; + line-height: ${(props) => props.theme.typography.h4.lineHeight - 3}px; + letter-spacing: ${(props) => props.theme.typography.h4.letterSpacing}px; margin: 0; display: flex; align-items: center; @@ -215,18 +216,16 @@ const TabTitleWrapper = styled.div<{ props.selected ? ` background-color: transparent; - color: ${props.theme.colors.tabs.hover}; + color: ${Colors.GREY_900}; .${Classes.ICON} { svg { - fill: ${props.theme.colors.tabs.icon}; path { - fill: ${props.theme.colors.tabs.icon}; + fill: ${Colors.GREY_900}; } } } .tab-title { - font-weight: 700; ${props.responseViewer && ` font-weight: normal; diff --git a/app/client/src/components/utils/CollapseComponent.tsx b/app/client/src/components/utils/CollapseComponent.tsx index faecca39bb58..1e830416de3e 100644 --- a/app/client/src/components/utils/CollapseComponent.tsx +++ b/app/client/src/components/utils/CollapseComponent.tsx @@ -5,16 +5,16 @@ import { Collapse, Icon } from "@blueprintjs/core"; const CollapseWrapper = styled.div` position: relative; - margin-top: ${(props) => props.theme.spaces[3]}px; .collapse-title { - color: ${Colors.TROUT_DARK}; + color: ${Colors.GRAY_700}; letter-spacing: 0.04em; text-transform: uppercase; font-weight: 500; font-size: 12px; line-height: 16px; display: flex; - gap: 4px; + align-items: center; + gap: 8px; cursor: pointer; /* justify-content: space-between; */ .icon { @@ -55,9 +55,10 @@ function CollapseComponent(props: { > {props.title} <Icon - className={`icon ${!open ? "collapse" : ""}`} - icon="chevron-down" - iconSize={16} + className={`icon ${open ? "collapse" : ""}`} + color="#4B4848" + icon="arrow-right" + iconSize={12} /> </div> <Collapse isOpen={open} keepChildrenMounted> diff --git a/app/client/src/pages/Editor/DataSourceEditor/NewActionButton.tsx b/app/client/src/pages/Editor/DataSourceEditor/NewActionButton.tsx index ca590e711e50..4684459d7e40 100644 --- a/app/client/src/pages/Editor/DataSourceEditor/NewActionButton.tsx +++ b/app/client/src/pages/Editor/DataSourceEditor/NewActionButton.tsx @@ -1,7 +1,7 @@ import React, { useCallback, useState } from "react"; import { Action, ApiActionConfig, PluginType } from "entities/Action"; import styled from "styled-components"; -import Button from "components/ads/Button"; +import Button, { IconPositions } from "components/ads/Button"; import { createNewApiName, createNewQueryName } from "utils/AppsmithUtils"; import { Toaster } from "components/ads/Toast"; import { ERROR_ADD_API_INVALID_URL } from "@appsmith/constants/messages"; @@ -100,6 +100,7 @@ function NewActionButton(props: NewActionButtonProps) { <ActionButton className="t--create-query" icon="plus" + iconPosition={IconPositions.left} isLoading={isSelected || props.isLoading} onClick={createQueryAction} text={pluginType === PluginType.DB ? "New Query" : "New API"} diff --git a/app/client/src/pages/Editor/IntegrationEditor/ActiveDataSources.tsx b/app/client/src/pages/Editor/IntegrationEditor/ActiveDataSources.tsx index 323394b4014e..fdb0d5731f6a 100644 --- a/app/client/src/pages/Editor/IntegrationEditor/ActiveDataSources.tsx +++ b/app/client/src/pages/Editor/IntegrationEditor/ActiveDataSources.tsx @@ -15,7 +15,6 @@ import { const QueryHomePage = styled.div` ${thinScrollbar}; - padding: 5px; overflow: auto; display: flex; flex-direction: column; diff --git a/app/client/src/pages/Editor/IntegrationEditor/DatasourceCard.tsx b/app/client/src/pages/Editor/IntegrationEditor/DatasourceCard.tsx index 2cb2e8894a6b..a7c050e5f6d8 100644 --- a/app/client/src/pages/Editor/IntegrationEditor/DatasourceCard.tsx +++ b/app/client/src/pages/Editor/IntegrationEditor/DatasourceCard.tsx @@ -42,15 +42,15 @@ import { import { debounce } from "lodash"; const Wrapper = styled.div` - padding: 18px; + padding: 15px; /* margin-top: 18px; */ cursor: pointer; &:hover { - background: ${Colors.Gallery}; + background: ${Colors.GREY_1}; .bp3-collapse-body { - background: ${Colors.Gallery}; + background: ${Colors.GREY_1}; } } `; @@ -72,8 +72,19 @@ const MenuWrapper = styled.div` `; const DatasourceImage = styled.img` - height: 24px; + height: 18px; width: auto; + margin: 0 auto; + max-width: 100%; +`; + +const DatasourceIconWrapper = styled.div` + width: 34px; + height: 34px; + border-radius: 50%; + background: ${Colors.GREY_2}; + display: flex; + align-items: center; `; const GenerateTemplateButton = styled(Button)` @@ -89,9 +100,8 @@ const GenerateTemplateButton = styled(Button)` `; const DatasourceName = styled.span` - margin-left: 10px; font-size: 16px; - font-weight: 500; + font-weight: 400; `; const DatasourceCardHeader = styled.div` @@ -105,6 +115,7 @@ const DatasourceNameWrapper = styled.div` flex-direction: row; align-items: center; display: flex; + gap: 13px; `; const DatasourceInfo = styled.div` @@ -114,13 +125,14 @@ const DatasourceInfo = styled.div` const Queries = styled.div` color: ${Colors.DOVE_GRAY}; font-size: 14px; - display: inline-block; - margin-top: 11px; + display: flex; + margin: 4px 0; `; const ButtonsWrapper = styled.div` display: flex; gap: 10px; + align-items: center; `; const MoreOptionsContainer = styled.div` @@ -251,11 +263,13 @@ function DatasourceCard(props: DatasourceCardProps) { <DatasourceCardHeader className="t--datasource-name"> <div style={{ flex: 1 }}> <DatasourceNameWrapper> - <DatasourceImage - alt="Datasource" - className="dataSourceImage" - src={pluginImages[datasource.pluginId]} - /> + <DatasourceIconWrapper> + <DatasourceImage + alt="Datasource" + className="dataSourceImage" + src={pluginImages[datasource.pluginId]} + /> + </DatasourceIconWrapper> <DatasourceName>{datasource.name}</DatasourceName> </DatasourceNameWrapper> <Queries className={`t--queries-for-${plugin.type}`}> @@ -293,7 +307,7 @@ function DatasourceCard(props: DatasourceCardProps) { target={ <MoreOptionsContainer> <Icon - fillColor={Colors.GRAY2} + fillColor={Colors.GREY_8} name="comment-context-menu" size={IconSize.XXXL} /> diff --git a/app/client/src/pages/Editor/IntegrationEditor/DatasourceHome.tsx b/app/client/src/pages/Editor/IntegrationEditor/DatasourceHome.tsx index 3f7f5d70f523..f11fe91f215b 100644 --- a/app/client/src/pages/Editor/IntegrationEditor/DatasourceHome.tsx +++ b/app/client/src/pages/Editor/IntegrationEditor/DatasourceHome.tsx @@ -37,17 +37,15 @@ const DatasourceHomePage = styled.div` .textBtn { justify-content: center; text-align: center; - color: #2e3d49; - font-weight: 500; + color: ${Colors.BLACK}; + font-weight: 400; text-decoration: none !important; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; - - font-weight: 500; font-size: 16px; line-height: 24px; - letter-spacing: -0.17px; + letter-spacing: -0.24px; margin: 0; } `; @@ -68,20 +66,17 @@ const DatasourceCard = styled.div` justify-content: space-between; height: 64px; &:hover { - background: ${Colors.Gallery}; + background: ${Colors.GREY_1}; cursor: pointer; } .dataSourceImageWrapper { - width: 40px; - height: 40px; - padding: 6px 0; - border-radius: 20px; - margin: 0 8px; - background: #f0f0f0; + width: 48px; + height: 48px; + border-radius: 50%; + background: ${Colors.GREY_2}; display: flex; align-items: center; - .dataSourceImage { height: 28px; width: auto; @@ -105,6 +100,8 @@ const DatasourceCard = styled.div` const DatasourceContentWrapper = styled.div` display: flex; align-items: center; + gap: 13px; + padding-left: 13.5px; `; interface DatasourceHomeScreenProps { diff --git a/app/client/src/pages/Editor/IntegrationEditor/IntegrationsHomeScreen.tsx b/app/client/src/pages/Editor/IntegrationEditor/IntegrationsHomeScreen.tsx index f28c0f6ba95a..0d528c4f2ba6 100644 --- a/app/client/src/pages/Editor/IntegrationEditor/IntegrationsHomeScreen.tsx +++ b/app/client/src/pages/Editor/IntegrationEditor/IntegrationsHomeScreen.tsx @@ -37,7 +37,7 @@ const ApiHomePage = styled.div` display: flex; flex-direction: column; - font-size: 20px; + font-size: 24px; padding: 20px 20px 0 20px; /* margin-left: 10px; */ flex: 1; diff --git a/app/client/src/pages/Editor/IntegrationEditor/MockDataSources.tsx b/app/client/src/pages/Editor/IntegrationEditor/MockDataSources.tsx index 5da57aa6283d..97c7ad6f1f8c 100644 --- a/app/client/src/pages/Editor/IntegrationEditor/MockDataSources.tsx +++ b/app/client/src/pages/Editor/IntegrationEditor/MockDataSources.tsx @@ -11,25 +11,22 @@ import { AppState } from "reducers"; import AnalyticsUtil from "utils/AnalyticsUtil"; const MockDataSourceWrapper = styled.div` - overflow: auto; display: grid; grid-template-columns: repeat(auto-fill, minmax(300px, 1fr)); gap: 16px; - flex: 1; - - .sectionHeader { - font-weight: ${(props) => props.theme.fontWeights[2]}; - font-size: ${(props) => props.theme.fontSizes[4]}px; - margin-top: 10px; - } + min-width: 150px; + border-radius: 4px; + align-items: center; + margin-top: 8px; `; const Description = styled.div` - color: ${Colors.DOVE_GRAY}; - font-size: 14px; - display: inline-block; - margin-top: 11px; + color: ${Colors.GREY_8}; + font-size: 13px; + line-height: 17px; + letter-spacing: -0.24px; `; + function MockDataSources(props: { mockDatasources: MockDatasource[] }) { const orgId = useSelector(getCurrentOrgId); return ( @@ -50,38 +47,51 @@ function MockDataSources(props: { mockDatasources: MockDatasource[] }) { export default MockDataSources; const CardWrapper = styled.div` - padding: 18px; - /* margin-top: 18px; */ - + display: flex; + align-items: center; + justify-content: space-between; + height: 64px; &:hover { - background: ${Colors.Gallery}; + background: ${Colors.GREY_1}; cursor: pointer; - .bp3-collapse-body { - background: ${Colors.Gallery}; - } + } } `; const DatasourceImage = styled.img` - height: 24px; + height: 28px; width: auto; + margin: 0 auto; + max-width: 100%; `; const DatasourceName = styled.span` - margin-left: 10px; font-size: 16px; - font-weight: 500; + font-weight: 400; + line-height: 24px; + letter-spacing: -0.24px; + color: ${Colors.BLACK}; `; const DatasourceCardHeader = styled.div` - justify-content: space-between; display: flex; + align-items: center; + gap: 13px; + padding-left: 13.5px; `; -const DatasourceNameWrapper = styled.div` - flex-direction: row; +const DatasourceIconWrapper = styled.div` + width: 48px; + height: 48px; + border-radius: 50%; + background: ${Colors.GREY_2}; + display: flex; align-items: center; +`; + +const DatasourceNameWrapper = styled.div` display: flex; + flex-direction: column; `; type MockDatasourceCardProps = { @@ -130,17 +140,16 @@ function MockDatasourceCard(props: MockDatasourceCardProps) { return ( <CardWrapper className="t--mock-datasource" onClick={addMockDataSource}> <DatasourceCardHeader className="t--datasource-name"> - <div style={{ flex: 1 }}> - <DatasourceNameWrapper> - <DatasourceImage - alt="Datasource" - className="dataSourceImage" - src={pluginImages[currentPlugin.id]} - /> - <DatasourceName>{datasource.name}</DatasourceName> - </DatasourceNameWrapper> + <DatasourceIconWrapper> + <DatasourceImage + alt="Datasource" + src={pluginImages[currentPlugin.id]} + /> + </DatasourceIconWrapper> + <DatasourceNameWrapper> + <DatasourceName>{datasource.name}</DatasourceName> <Description>{datasource.description}</Description> - </div> + </DatasourceNameWrapper> </DatasourceCardHeader> </CardWrapper> ); diff --git a/app/client/src/pages/Editor/IntegrationEditor/NewApi.tsx b/app/client/src/pages/Editor/IntegrationEditor/NewApi.tsx index c62c76a9c721..c061299fad7c 100644 --- a/app/client/src/pages/Editor/IntegrationEditor/NewApi.tsx +++ b/app/client/src/pages/Editor/IntegrationEditor/NewApi.tsx @@ -29,9 +29,9 @@ const StyledContainer = styled.div` margin: 0; justify-content: center; text-align: center; - letter-spacing: -0.17px; + letter-spacing: -0.24px; color: ${Colors.OXFORD_BLUE}; - font-weight: 500; + font-weight: 400; text-decoration: none !important; flex-wrap: wrap; white-space: nowrap; @@ -84,17 +84,15 @@ const ApiCard = styled.div` justify-content: space-between; height: 64px; &:hover { - background: ${Colors.Gallery}; + background: ${Colors.GREY_1}; cursor: pointer; } .content-icon-wrapper { - width: 40px; - height: 40px; - border-radius: 20px; - padding: 6px 0; - margin: 0 8px; - background: #f0f0f0; + width: 48px; + height: 48px; + border-radius: 50%; + background: ${Colors.GREY_2}; display: flex; align-items: center; @@ -121,6 +119,8 @@ const ApiCard = styled.div` const CardContentWrapper = styled.div` display: flex; align-items: center; + gap: 13px; + padding-left: 13.5px; `; type ApiHomeScreenProps = {
bb77c03ebb20b0e14dc1d49632e5448e48d0bccf
2021-10-26 15:26:02
Siddharth Mishra
fix: Fixed the broken links in CONTRIBUTING.md (#8815)
false
Fixed the broken links in CONTRIBUTING.md (#8815)
fix
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index aedff8985e2f..ef78d7888ea2 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -13,15 +13,15 @@ Read our [Code of Conduct](CODE_OF_CONDUCT.md) before contributing There are many ways in which you can contribute to Appsmith. #### 🐛 Report a bug -Report all issues through GitHub Issues using the [Report a Bug](https://github.com/appsmithorg/appsmith/issues/new?assignees=Nikhil-Nandagopal&labels=Bug%2C+High&template=---bug-report.md&title=%5BBug%5D) template. +Report all issues through GitHub Issues using the [Report a Bug](https://github.com/appsmithorg/appsmith/issues/new?assignees=Nikhil-Nandagopal&labels=Bug%2CNeeds+Triaging&template=--bug-report.yaml&title=%5BBug%5D%3A+) template. To help resolve your issue as quickly as possible, read the template and provide all the requested information. #### 🛠 File a feature request We welcome all feature requests, whether it's to add new functionality to an existing extension or to offer an idea for a brand new extension. -File your feature request through GitHub Issues using the [Feature Request](https://github.com/appsmithorg/appsmith/issues/new?assignees=Nikhil-Nandagopal&labels=&template=----feature-request.md&title=%5BFeature%5D) template. +File your feature request through GitHub Issues using the [Feature Request](https://github.com/appsmithorg/appsmith/issues/new?assignees=Nikhil-Nandagopal&labels=Enhancement&template=--feature-request.yaml&title=%5BFeature%5D%3A+) template. #### 📝 Improve the documentation -In the process of shipping features quickly, we may forget to keep our docs up to date. You can help by suggesting improvements to our documentation or dive right into our [Docs Contribution Guide](contributions/docs/CONTRIBUTING.md)! +In the process of shipping features quickly, we may forget to keep our docs up to date. You can help by suggesting improvements to our documentation using the [Documentation Improvement](https://github.com/appsmithorg/appsmith/issues/new?assignees=Nikhil-Nandagopal&labels=Documentation&template=--documentation-improvement.yaml&title=%5BDocs%5D%3A+) template or dive right into our [Docs Contribution Guide](contributions/docs/CONTRIBUTING.md)! #### ⚙️ Close a Bug / Feature issue We welcome contributions that help make appsmith bug free & improve the experience of our users. You can also find issues tagged [Good First Issues](https://github.com/appsmithorg/appsmith/issues?q=is%3Aopen+is%3Aissue+label%3A%22Good+First+Issue%22+bug). Check out our [Code Contribution Guide](contributions/CodeContributionsGuidelines.md) to begin.
3bd313864cf0a59e61143dd51dd40e22d7541eeb
2022-08-29 14:46:24
Ankita Kinger
fix: Hiding the add new button in new workspace created if user has app viewer access (#16363)
false
Hiding the add new button in new workspace created if user has app viewer access (#16363)
fix
diff --git a/app/client/src/pages/Applications/index.tsx b/app/client/src/pages/Applications/index.tsx index 5e90445ee672..f5a178f91cad 100644 --- a/app/client/src/pages/Applications/index.tsx +++ b/app/client/src/pages/Applications/index.tsx @@ -661,6 +661,27 @@ function ApplicationsSection(props: any) { workspace.userPermissions, PERMISSION_TYPE.MANAGE_WORKSPACE, ); + const hasCreateNewApplicationPermission = + isPermitted( + workspace.userPermissions, + PERMISSION_TYPE.CREATE_APPLICATION, + ) && !isMobile; + + const onClickAddNewButton = (workspaceId: string) => { + if ( + Object.entries(creatingApplicationMap).length === 0 || + (creatingApplicationMap && !creatingApplicationMap[workspaceId]) + ) { + createNewApplication( + getNextEntityName( + "Untitled application ", + applications.map((el: any) => el.name), + ), + workspaceId, + ); + } + }; + return ( <WorkspaceSection className="t--workspace-section" @@ -717,11 +738,7 @@ function ApplicationsSection(props: any) { workspaceId={workspace.id} /> )} - {isPermitted( - workspace.userPermissions, - PERMISSION_TYPE.CREATE_APPLICATION, - ) && - !isMobile && + {hasCreateNewApplicationPermission && !isFetchingApplications && applications.length !== 0 && ( <Button @@ -731,22 +748,7 @@ function ApplicationsSection(props: any) { creatingApplicationMap && creatingApplicationMap[workspace.id] } - onClick={() => { - if ( - Object.entries(creatingApplicationMap).length === - 0 || - (creatingApplicationMap && - !creatingApplicationMap[workspace.id]) - ) { - createNewApplication( - getNextEntityName( - "Untitled application ", - applications.map((el: any) => el.name), - ), - workspace.id, - ); - } - }} + onClick={() => onClickAddNewButton(workspace.id)} size={Size.medium} tag="button" text={"New"} @@ -911,7 +913,7 @@ function ApplicationsSection(props: any) { <NoAppsFoundIcon /> <span>There’s nothing inside this workspace</span> {/* below component is duplicate. This is because of cypress test were failing */} - {!isMobile && ( + {hasCreateNewApplicationPermission && ( <Button className="t--new-button createnew" icon={"plus"} @@ -919,21 +921,7 @@ function ApplicationsSection(props: any) { creatingApplicationMap && creatingApplicationMap[workspace.id] } - onClick={() => { - if ( - Object.entries(creatingApplicationMap).length === 0 || - (creatingApplicationMap && - !creatingApplicationMap[workspace.id]) - ) { - createNewApplication( - getNextEntityName( - "Untitled application ", - applications.map((el: any) => el.name), - ), - workspace.id, - ); - } - }} + onClick={() => onClickAddNewButton(workspace.id)} size={Size.medium} tag="button" text={"New"} diff --git a/app/client/src/pages/common/PageWrapper.tsx b/app/client/src/pages/common/PageWrapper.tsx index d64a0d70c812..bf9d3d2b8055 100644 --- a/app/client/src/pages/common/PageWrapper.tsx +++ b/app/client/src/pages/common/PageWrapper.tsx @@ -7,7 +7,7 @@ const Wrapper = styled.section<{ isFixed?: boolean }>` props.isFixed ? `margin: 0; position: fixed; - top: ${props.theme.homePage.header}px;; + top: ${props.theme.homePage.header}px; width: 100%;` : `margin-top: ${props.theme.homePage.header}px;`} && .fade {
807f5606f001bdbd86e2a14cb90d14db64f53ee5
2024-04-09 19:59:21
Manish Kumar
chore: Git spans changed from enum to string (#32454)
false
Git spans changed from enum to string (#32454)
chore
diff --git a/app/server/appsmith-git/src/main/java/com/appsmith/git/service/ce/GitExecutorCEImpl.java b/app/server/appsmith-git/src/main/java/com/appsmith/git/service/ce/GitExecutorCEImpl.java index 4ff073d07c04..9d4cfd00bfd2 100644 --- a/app/server/appsmith-git/src/main/java/com/appsmith/git/service/ce/GitExecutorCEImpl.java +++ b/app/server/appsmith-git/src/main/java/com/appsmith/git/service/ce/GitExecutorCEImpl.java @@ -7,7 +7,7 @@ import com.appsmith.external.dtos.GitStatusDTO; import com.appsmith.external.dtos.MergeStatusDTO; import com.appsmith.external.git.GitExecutor; -import com.appsmith.external.git.constants.GitSpans; +import com.appsmith.external.git.constants.GitSpan; import com.appsmith.external.helpers.Stopwatch; import com.appsmith.git.configurations.GitServiceConfig; import com.appsmith.git.constants.AppsmithBotAsset; @@ -139,7 +139,7 @@ public Mono<String> commitArtifact( } }) .timeout(Duration.ofMillis(Constraint.TIMEOUT_MILLIS)) - .name(GitSpans.FILE_SYSTEM_COMMIT.getEventName()) + .name(GitSpan.FS_COMMIT) .tap(Micrometer.observation(observationRegistry)) .subscribeOn(scheduler); } @@ -243,7 +243,7 @@ public Mono<String> pushApplication( } }) .timeout(Duration.ofMillis(Constraint.TIMEOUT_MILLIS)) - .name(GitSpans.FILE_SYSTEM_PUSH.getEventName()) + .name(GitSpan.FS_PUSH) .tap(Micrometer.observation(observationRegistry)) .subscribeOn(scheduler); } @@ -285,7 +285,7 @@ public Mono<String> cloneRemoteIntoArtifactRepo( return branchName; }) .timeout(Duration.ofMillis(Constraint.TIMEOUT_MILLIS)) - .name(GitSpans.FILE_SYSTEM_CLONE_REPO.getEventName()) + .name(GitSpan.FS_CLONE_REPO) .tap(Micrometer.observation(observationRegistry)) .subscribeOn(scheduler); } @@ -315,7 +315,7 @@ public Mono<String> createAndCheckoutToBranch(Path repoSuffix, String branchName } }) .timeout(Duration.ofMillis(Constraint.TIMEOUT_MILLIS)) - .name(GitSpans.FILE_SYSTEM_CREATE_BRANCH.getEventName()) + .name(GitSpan.FS_CREATE_BRANCH) .tap(Micrometer.observation(observationRegistry)) .subscribeOn(scheduler); } @@ -345,7 +345,7 @@ public Mono<Boolean> deleteBranch(Path repoSuffix, String branchName) { } }) .timeout(Duration.ofMillis(Constraint.TIMEOUT_MILLIS)) - .name(GitSpans.FILE_SYSTEM_DELETE_BRANCH.getEventName()) + .name(GitSpan.FS_DELETE_BRANCH) .tap(Micrometer.observation(observationRegistry)) .subscribeOn(scheduler); } @@ -381,7 +381,7 @@ public Mono<Boolean> checkoutToBranch(Path repoSuffix, String branchName) { }) .timeout(Duration.ofMillis(Constraint.TIMEOUT_MILLIS)) .tag(CHECKOUT_REMOTE, FALSE.toString()) - .name(GitSpans.FILE_SYSTEM_CHECKOUT_BRANCH.getEventName()) + .name(GitSpan.FS_CHECKOUT_BRANCH) .tap(Micrometer.observation(observationRegistry)) .subscribeOn(scheduler); } @@ -443,7 +443,7 @@ public Mono<MergeStatusDTO> pullApplication( } }) .timeout(Duration.ofMillis(Constraint.TIMEOUT_MILLIS)) - .name(GitSpans.FILE_SYSTEM_PULL.getEventName()) + .name(GitSpan.FS_PULL) .tap(Micrometer.observation(observationRegistry)) .subscribeOn(scheduler); } @@ -560,7 +560,7 @@ public Mono<GitStatusDTO> getStatus(Path repoPath, String branchName) { }) .timeout(Duration.ofMillis(Constraint.TIMEOUT_MILLIS)) .flatMap(response -> response) - .name(GitSpans.FILE_SYSTEM_STATUS.getEventName()) + .name(GitSpan.FS_STATUS) .tap(Micrometer.observation(observationRegistry)) .subscribeOn(scheduler); } @@ -682,7 +682,7 @@ public Mono<String> mergeBranch(Path repoSuffix, String sourceBranch, String des } }) .timeout(Duration.ofMillis(Constraint.TIMEOUT_MILLIS)) - .name(GitSpans.FILE_SYSTEM_MERGE.getEventName()) + .name(GitSpan.FS_MERGE) .tap(Micrometer.observation(observationRegistry)) .subscribeOn(scheduler); } @@ -727,7 +727,7 @@ public Mono<String> fetchRemote( return Mono.error(error); }) .timeout(Duration.ofMillis(Constraint.TIMEOUT_MILLIS)) - .name(GitSpans.FILE_SYSTEM_FETCH_REMOTE.getEventName()) + .name(GitSpan.FS_FETCH_REMOTE) .tap(Micrometer.observation(observationRegistry)) .subscribeOn(scheduler); } @@ -838,7 +838,7 @@ public Mono<String> checkoutRemoteBranch(Path repoSuffix, String branchName) { }) .timeout(Duration.ofMillis(Constraint.TIMEOUT_MILLIS)) .tag(CHECKOUT_REMOTE, TRUE.toString()) - .name(GitSpans.FILE_SYSTEM_CHECKOUT_BRANCH.getEventName()) + .name(GitSpan.FS_CHECKOUT_BRANCH) .tap(Micrometer.observation(observationRegistry)) .subscribeOn(scheduler); } @@ -873,7 +873,7 @@ private Mono<Ref> resetToLastCommit(Git git) throws GitAPIException { }) .timeout(Duration.ofMillis(Constraint.TIMEOUT_MILLIS)) .tag(HARD_RESET, Boolean.FALSE.toString()) - .name(GitSpans.FILE_SYSTEM_RESET.getEventName()) + .name(GitSpan.FS_RESET) .tap(Micrometer.observation(observationRegistry)) .subscribeOn(scheduler); } @@ -909,7 +909,7 @@ public Mono<Boolean> resetHard(Path repoSuffix, String branchName) { }) .timeout(Duration.ofMillis(Constraint.TIMEOUT_MILLIS)) .tag(HARD_RESET, TRUE.toString()) - .name(GitSpans.FILE_SYSTEM_RESET.getEventName()) + .name(GitSpan.FS_RESET) .tap(Micrometer.observation(observationRegistry)) .subscribeOn(scheduler); } @@ -940,7 +940,7 @@ public Mono<Boolean> rebaseBranch(Path repoSuffix, String branchName) { } }) .timeout(Duration.ofMillis(Constraint.TIMEOUT_MILLIS)) - .name(GitSpans.FILE_SYSTEM_REBASE.getEventName()) + .name(GitSpan.FS_REBASE) .tap(Micrometer.observation(observationRegistry)) .subscribeOn(scheduler); } @@ -953,7 +953,7 @@ public Mono<BranchTrackingStatus> getBranchTrackingStatus(Path repoPath, String } }) .timeout(Duration.ofMillis(Constraint.TIMEOUT_MILLIS)) - .name(GitSpans.FILE_SYSTEM_BRANCH_TRACK.getEventName()) + .name(GitSpan.FS_BRANCH_TRACK) .tap(Micrometer.observation(observationRegistry)) .subscribeOn(scheduler); } diff --git a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/constants/spans/BaseSpan.java b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/constants/spans/BaseSpan.java index 392f7586b022..b654c4847947 100644 --- a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/constants/spans/BaseSpan.java +++ b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/constants/spans/BaseSpan.java @@ -7,4 +7,6 @@ public class BaseSpan { * This prefix is for all the git flows */ public static final String GIT_SPAN_PREFIX = "git."; + + public static final String APPLICATION_SPAN_PREFIX = "application."; } diff --git a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/git/constants/GitSpan.java b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/git/constants/GitSpan.java new file mode 100644 index 000000000000..d72a6bc5d3e4 --- /dev/null +++ b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/git/constants/GitSpan.java @@ -0,0 +1,5 @@ +package com.appsmith.external.git.constants; + +import com.appsmith.external.git.constants.ce.GitSpanCE; + +public class GitSpan extends GitSpanCE {} diff --git a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/git/constants/GitSpans.java b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/git/constants/GitSpans.java deleted file mode 100644 index 20fe0cb7f310..000000000000 --- a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/git/constants/GitSpans.java +++ /dev/null @@ -1,36 +0,0 @@ -package com.appsmith.external.git.constants; - -import java.util.Locale; - -import static com.appsmith.external.constants.spans.BaseSpan.APPSMITH_SPAN_PREFIX; -import static com.appsmith.external.constants.spans.BaseSpan.GIT_SPAN_PREFIX; - -public enum GitSpans { - FILE_SYSTEM_CLONE_REPO, - FILE_SYSTEM_STATUS, - FILE_SYSTEM_PULL, - FILE_SYSTEM_BRANCH_TRACK, - ADD_FILE_LOCK, - RELEASE_FILE_LOCK, - FILE_SYSTEM_COMMIT, - FILE_SYSTEM_CHECKOUT_BRANCH, - FILE_SYSTEM_CREATE_BRANCH, - FILE_SYSTEM_DELETE_BRANCH, - FILE_SYSTEM_CREATE_REPO, - FILE_SYSTEM_RESET, - FILE_SYSTEM_MERGE, - FILE_SYSTEM_REBASE, - FILE_SYSTEM_PUSH, - FILE_SYSTEM_FETCH_REMOTE, - STATUS, - COMMIT; - private final String eventName; - - GitSpans() { - this.eventName = APPSMITH_SPAN_PREFIX + GIT_SPAN_PREFIX + name().toLowerCase(Locale.ROOT); - } - - public String getEventName() { - return this.eventName; - } -} diff --git a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/git/constants/ce/GitSpanCE.java b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/git/constants/ce/GitSpanCE.java new file mode 100644 index 000000000000..8fa9e59107fd --- /dev/null +++ b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/git/constants/ce/GitSpanCE.java @@ -0,0 +1,34 @@ +package com.appsmith.external.git.constants.ce; + +import static com.appsmith.external.constants.spans.BaseSpan.APPSMITH_SPAN_PREFIX; +import static com.appsmith.external.constants.spans.BaseSpan.GIT_SPAN_PREFIX; + +public class GitSpanCE { + + public static final String FS_CLONE_REPO = APPSMITH_SPAN_PREFIX + GIT_SPAN_PREFIX + "fs_clone_repo"; + public static final String FS_STATUS = APPSMITH_SPAN_PREFIX + GIT_SPAN_PREFIX + "fs_status"; + public static final String FS_PULL = APPSMITH_SPAN_PREFIX + GIT_SPAN_PREFIX + "fs_pull"; + public static final String FS_BRANCH_TRACK = APPSMITH_SPAN_PREFIX + GIT_SPAN_PREFIX + "fs_branch_track"; + public static final String ADD_FILE_LOCK = APPSMITH_SPAN_PREFIX + GIT_SPAN_PREFIX + "add_file_lock"; + public static final String RELEASE_FILE_LOCK = APPSMITH_SPAN_PREFIX + GIT_SPAN_PREFIX + "release_file_lock"; + public static final String FS_COMMIT = APPSMITH_SPAN_PREFIX + GIT_SPAN_PREFIX + "fs_commit"; + public static final String FS_CHECKOUT_BRANCH = APPSMITH_SPAN_PREFIX + GIT_SPAN_PREFIX + "fs_checkout_branch"; + public static final String FS_CREATE_BRANCH = APPSMITH_SPAN_PREFIX + GIT_SPAN_PREFIX + "fs_create_branch"; + public static final String FS_DELETE_BRANCH = APPSMITH_SPAN_PREFIX + GIT_SPAN_PREFIX + "fs_delete_branch"; + public static final String FS_CREATE_REPO = APPSMITH_SPAN_PREFIX + GIT_SPAN_PREFIX + "fs_create_repo"; + public static final String FS_RESET = APPSMITH_SPAN_PREFIX + GIT_SPAN_PREFIX + "fs_reset"; + public static final String FS_MERGE = APPSMITH_SPAN_PREFIX + GIT_SPAN_PREFIX + "fs_merge"; + public static final String FS_REBASE = APPSMITH_SPAN_PREFIX + GIT_SPAN_PREFIX + "fs_rebase"; + public static final String FS_PUSH = APPSMITH_SPAN_PREFIX + GIT_SPAN_PREFIX + "fs_push"; + public static final String FS_FETCH_REMOTE = APPSMITH_SPAN_PREFIX + GIT_SPAN_PREFIX + "fs_fetch_remote"; + public static final String OPS_STATUS = APPSMITH_SPAN_PREFIX + GIT_SPAN_PREFIX + "ops_status"; + public static final String OPS_COMMIT = APPSMITH_SPAN_PREFIX + GIT_SPAN_PREFIX + "ops_commit"; + public static final String OPS_PUSH = APPSMITH_SPAN_PREFIX + GIT_SPAN_PREFIX + "ops_push"; + public static final String OPS_PULL = APPSMITH_SPAN_PREFIX + GIT_SPAN_PREFIX + "ops_pull"; + public static final String OPS_CREATE_BRANCH = APPSMITH_SPAN_PREFIX + GIT_SPAN_PREFIX + "ops_create_branch"; + public static final String OPS_CHECKOUT_BRANCH = APPSMITH_SPAN_PREFIX + GIT_SPAN_PREFIX + "ops_checkout_branch"; + public static final String OPS_DELETE_BRANCH = APPSMITH_SPAN_PREFIX + GIT_SPAN_PREFIX + "ops_delete_branch"; + public static final String OPS_FETCH_REMOTE = APPSMITH_SPAN_PREFIX + GIT_SPAN_PREFIX + "ops_fetch_remote"; + public static final String OPS_DETACH_REMOTE = APPSMITH_SPAN_PREFIX + GIT_SPAN_PREFIX + "ops_detach_remote"; + public static final String OPS_DISCARD_CHANGES = APPSMITH_SPAN_PREFIX + GIT_SPAN_PREFIX + "ops_discard_changes"; +} diff --git a/app/server/appsmith-interfaces/src/test/java/com/appsmith/external/git/GitSpansTest.java b/app/server/appsmith-interfaces/src/test/java/com/appsmith/external/git/GitSpansTest.java new file mode 100644 index 000000000000..80c517301fcd --- /dev/null +++ b/app/server/appsmith-interfaces/src/test/java/com/appsmith/external/git/GitSpansTest.java @@ -0,0 +1,31 @@ +package com.appsmith.external.git; + +import com.appsmith.external.git.constants.ce.GitSpanCE; +import lombok.extern.slf4j.Slf4j; +import org.junit.jupiter.api.Test; + +import java.lang.reflect.Field; + +import static com.appsmith.external.constants.spans.BaseSpan.APPSMITH_SPAN_PREFIX; +import static com.appsmith.external.constants.spans.BaseSpan.GIT_SPAN_PREFIX; +import static org.assertj.core.api.Assertions.assertThat; + +@Slf4j +public class GitSpansTest { + + @Test + public void enforceCorrectNameUsage_InGitSpansCE() throws IllegalAccessException { + Class<?> gitSpansClass = GitSpanCE.class; + Field[] fields = gitSpansClass.getDeclaredFields(); + for (Field field : fields) { + if (java.lang.reflect.Modifier.isStatic(field.getModifiers())) { + // Allow access to private fields + field.setAccessible(true); + String prefix = APPSMITH_SPAN_PREFIX + GIT_SPAN_PREFIX; + String propertyName = field.getName(); + String propertyValue = (String) field.get(null); + assertThat(propertyValue).isEqualTo(prefix + propertyName.toLowerCase()); + } + } + } +} diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/GitServiceCEImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/GitServiceCEImpl.java index 6c4376869f9c..a964d78abb58 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/GitServiceCEImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/GitServiceCEImpl.java @@ -7,7 +7,8 @@ import com.appsmith.external.dtos.GitStatusDTO; import com.appsmith.external.dtos.MergeStatusDTO; import com.appsmith.external.git.GitExecutor; -import com.appsmith.external.git.constants.GitSpans; +import com.appsmith.external.git.constants.GitConstants; +import com.appsmith.external.git.constants.GitSpan; import com.appsmith.external.models.Datasource; import com.appsmith.external.models.DatasourceStorage; import com.appsmith.git.service.GitExecutorImpl; @@ -107,8 +108,8 @@ import static com.appsmith.external.git.constants.GitConstants.GIT_CONFIG_ERROR; import static com.appsmith.external.git.constants.GitConstants.GIT_PROFILE_ERROR; import static com.appsmith.external.git.constants.GitConstants.MERGE_CONFLICT_BRANCH_NAME; -import static com.appsmith.external.git.constants.GitSpans.COMMIT; -import static com.appsmith.external.git.constants.GitSpans.STATUS; +import static com.appsmith.external.git.constants.GitSpan.OPS_COMMIT; +import static com.appsmith.external.git.constants.GitSpan.OPS_STATUS; import static com.appsmith.git.constants.AppsmithBotAsset.APPSMITH_BOT_USERNAME; import static com.appsmith.server.constants.ArtifactType.APPLICATION; import static com.appsmith.server.constants.FieldName.DEFAULT; @@ -116,6 +117,7 @@ import static com.appsmith.server.helpers.DefaultResourcesUtils.createDefaultIdsOrUpdateWithGivenResourceIds; import static com.appsmith.server.helpers.GitUtils.MAX_RETRIES; import static com.appsmith.server.helpers.GitUtils.RETRY_DELAY; +import static java.lang.Boolean.FALSE; import static java.lang.Boolean.TRUE; import static org.apache.commons.lang.ObjectUtils.defaultIfNull; @@ -219,10 +221,10 @@ public Mono<Map<String, GitProfile>> updateOrCreateGitProfileForCurrentUser( // 2. Updating or creating repo specific profile and user want to use repo specific profile but provided empty // values for authorName and email - if ((DEFAULT.equals(defaultApplicationId) || Boolean.FALSE.equals(gitProfile.getUseGlobalProfile())) + if ((DEFAULT.equals(defaultApplicationId) || FALSE.equals(gitProfile.getUseGlobalProfile())) && StringUtils.isEmptyOrNull(gitProfile.getAuthorName())) { return Mono.error(new AppsmithException(AppsmithError.INVALID_PARAMETER, "Author Name")); - } else if ((DEFAULT.equals(defaultApplicationId) || Boolean.FALSE.equals(gitProfile.getUseGlobalProfile())) + } else if ((DEFAULT.equals(defaultApplicationId) || FALSE.equals(gitProfile.getUseGlobalProfile())) && StringUtils.isEmptyOrNull(gitProfile.getAuthorEmail())) { return Mono.error(new AppsmithException(AppsmithError.INVALID_PARAMETER, "Author Email")); } else if (StringUtils.isEmptyOrNull(defaultApplicationId)) { @@ -232,7 +234,7 @@ public Mono<Map<String, GitProfile>> updateOrCreateGitProfileForCurrentUser( if (DEFAULT.equals(defaultApplicationId)) { gitProfile.setUseGlobalProfile(null); } else if (!TRUE.equals(gitProfile.getUseGlobalProfile())) { - gitProfile.setUseGlobalProfile(Boolean.FALSE); + gitProfile.setUseGlobalProfile(FALSE); } return sessionUserService @@ -458,7 +460,7 @@ private Mono<String> commitApplication( .flatMap(application -> gitPrivateRepoHelper.isRepoLimitReached(workspaceId, false)) .flatMap(isRepoLimitReached -> { - if (Boolean.FALSE.equals(isRepoLimitReached)) { + if (FALSE.equals(isRepoLimitReached)) { return Mono.just(defaultApplication); } throw new AppsmithException(AppsmithError.GIT_APPLICATION_LIMIT_ERROR); @@ -625,7 +627,7 @@ private Mono<String> commitApplication( childApplication.getGitApplicationMetadata().getIsRepoPrivate(), isSystemGenerated)) .thenReturn(status) - .name(COMMIT.getEventName()) + .name(OPS_COMMIT) .tap(Micrometer.observation(observationRegistry)); }); @@ -738,7 +740,7 @@ public Mono<Application> connectApplicationToGit( return gitPrivateRepoHelper .isRepoLimitReached(application.getWorkspaceId(), true) .flatMap(isRepoLimitReached -> { - if (Boolean.FALSE.equals(isRepoLimitReached)) { + if (FALSE.equals(isRepoLimitReached)) { return Mono.just(application); } return addAnalyticsForGitOperation( @@ -1092,7 +1094,9 @@ private Mono<String> pushApplication(String applicationId, boolean doPublish, bo application, application.getGitApplicationMetadata().getIsRepoPrivate()) .thenReturn(pushStatus); - }); + }) + .name(GitSpan.OPS_PUSH) + .tap(Micrometer.observation(observationRegistry)); return Mono.create(sink -> pushStatusMono.subscribe(sink::success, sink::error, null, sink.currentContext())); } @@ -1236,7 +1240,9 @@ public Mono<Application> detachRemote(String defaultApplicationId) { .collectList() .flatMapMany(actionCollectionService::saveAll)) .then(addAnalyticsForGitOperation(AnalyticsEvents.GIT_DISCONNECT, application, false)) - .map(responseUtils::updateApplicationWithDefaultResources)); + .map(responseUtils::updateApplicationWithDefaultResources)) + .name(GitSpan.OPS_DETACH_REMOTE) + .tap(Micrometer.observation(observationRegistry)); return Mono.create(sink -> disconnectMono.subscribe(sink::success, sink::error, null, sink.currentContext())); } @@ -1377,7 +1383,9 @@ public Mono<Application> createBranch(String defaultApplicationId, GitBranchDTO AnalyticsEvents.GIT_CREATE_BRANCH, application, application.getGitApplicationMetadata().getIsRepoPrivate()))) - .map(responseUtils::updateApplicationWithDefaultResources); + .map(responseUtils::updateApplicationWithDefaultResources) + .name(GitSpan.OPS_CREATE_BRANCH) + .tap(Micrometer.observation(observationRegistry)); return Mono.create(sink -> createBranchMono.subscribe(sink::success, sink::error, null, sink.currentContext())); } @@ -1447,6 +1455,9 @@ public Mono<Application> checkoutBranch(String defaultApplicationId, String bran } return Mono.just(result); }) + .tag(GitConstants.GitMetricConstants.CHECKOUT_REMOTE, FALSE.toString()) + .name(GitSpan.OPS_CHECKOUT_BRANCH) + .tap(Micrometer.observation(observationRegistry)) .onErrorResume(throwable -> { return Mono.error(throwable); }); @@ -1559,7 +1570,10 @@ private Mono<Application> checkoutRemoteBranch(String defaultApplicationId, Stri .map(responseUtils::updateApplicationWithDefaultResources) .flatMap(application1 -> releaseFileLock(defaultApplicationId).then(Mono.just(application1))); - }); + }) + .tag(GitConstants.GitMetricConstants.CHECKOUT_REMOTE, TRUE.toString()) + .name(GitSpan.OPS_CHECKOUT_BRANCH) + .tap(Micrometer.observation(observationRegistry)); return Mono.create( sink -> checkoutRemoteBranchMono.subscribe(sink::success, sink::error, null, sink.currentContext())); @@ -1648,7 +1662,9 @@ public Mono<GitPullDTO> pullApplication(String defaultApplicationId, String bran // Release file lock after the pull operation .flatMap(gitPullDTO -> releaseFileLock(defaultApplicationId).then(Mono.just(gitPullDTO))); - }); + }) + .name(GitSpan.OPS_PULL) + .tap(Micrometer.observation(observationRegistry)); return Mono.create(sink -> pullMono.subscribe(sink::success, sink::error, null, sink.currentContext())); } @@ -1857,7 +1873,7 @@ private Mono<List<GitBranchDTO>> getBranchListWithDefaultBranchName( } return branchDTOList; }) - .flatMap(gitBranchDTOList -> Boolean.FALSE.equals(pruneBranches) + .flatMap(gitBranchDTOList -> FALSE.equals(pruneBranches) ? Mono.just(gitBranchDTOList) : addAnalyticsForGitOperation( AnalyticsEvents.GIT_PRUNE, @@ -2000,7 +2016,7 @@ private Mono<GitStatusDTO> getStatus( throwable); return Mono.error(new AppsmithException(AppsmithError.GIT_GENERIC_ERROR, throwable.getMessage())); }) - .name(STATUS.getEventName()) + .name(OPS_STATUS) .tap(Micrometer.observation(observationRegistry)); return Mono.zip(statusMono, sessionUserService.getCurrentUser(), branchedAppMono) @@ -2134,7 +2150,9 @@ public Mono<BranchTrackingStatus> fetchRemoteChanges( return sendUnitExecutionTimeAnalyticsEvent( AnalyticsEvents.GIT_FETCH.getEventName(), elapsedTime, currentUser, app) .thenReturn(branchTrackingStatus); - }); + }) + .name(GitSpan.OPS_FETCH_REMOTE) + .tap(Micrometer.observation(observationRegistry)); return Mono.create(sink -> { fetchRemoteStatusMono.subscribe(sink::success, sink::error, null, sink.currentContext()); @@ -2572,7 +2590,7 @@ public Mono<ApplicationImportDTO> importApplicationFromGit(String workspaceId, G return gitPrivateRepoHelper .isRepoLimitReached(workspaceId, true) .flatMap(isRepoLimitReached -> { - if (Boolean.FALSE.equals(isRepoLimitReached)) { + if (FALSE.equals(isRepoLimitReached)) { return Mono.just(gitAuth).zipWith(applicationMono); } return addAnalyticsForGitOperation( @@ -2853,7 +2871,7 @@ public Mono<Application> deleteBranch(String defaultApplicationId, String branch .flatMap(isBranchDeleted -> releaseFileLock(defaultApplicationId).map(status -> isBranchDeleted)) .flatMap(isBranchDeleted -> { - if (Boolean.FALSE.equals(isBranchDeleted)) { + if (FALSE.equals(isBranchDeleted)) { return Mono.error(new AppsmithException( AppsmithError.GIT_ACTION_FAILED, " delete branch. Branch does not exists in the repo")); @@ -2889,7 +2907,9 @@ public Mono<Application> deleteBranch(String defaultApplicationId, String branch AnalyticsEvents.GIT_DELETE_BRANCH, application, application.getGitApplicationMetadata().getIsRepoPrivate())) - .map(responseUtils::updateApplicationWithDefaultResources); + .map(responseUtils::updateApplicationWithDefaultResources) + .name(GitSpan.OPS_DELETE_BRANCH) + .tap(Micrometer.observation(observationRegistry)); return Mono.create(sink -> deleteBranchMono.subscribe(sink::success, sink::error, null, sink.currentContext())); } @@ -2952,7 +2972,9 @@ public Mono<Application> discardChanges(String defaultApplicationId, String bran }) .flatMap(application -> releaseFileLock(defaultApplicationId) .then(this.addAnalyticsForGitOperation(AnalyticsEvents.GIT_DISCARD_CHANGES, application, null))) - .map(responseUtils::updateApplicationWithDefaultResources); + .map(responseUtils::updateApplicationWithDefaultResources) + .name(GitSpan.OPS_DISCARD_CHANGES) + .tap(Micrometer.observation(observationRegistry)); return Mono.create( sink -> discardChangeMono.subscribe(sink::success, sink::error, null, sink.currentContext())); @@ -3279,14 +3301,14 @@ private Mono<Boolean> addFileLock(String defaultApplicationId) { .onRetryExhaustedThrow((retryBackoffSpec, retrySignal) -> { throw new AppsmithException(AppsmithError.GIT_FILE_IN_USE); })) - .name(GitSpans.ADD_FILE_LOCK.getEventName()) + .name(GitSpan.ADD_FILE_LOCK) .tap(Micrometer.observation(observationRegistry)); } private Mono<Boolean> releaseFileLock(String defaultApplicationId) { return redisUtils .releaseFileLock(defaultApplicationId) - .name(GitSpans.RELEASE_FILE_LOCK.getEventName()) + .name(GitSpan.RELEASE_FILE_LOCK) .tap(Micrometer.observation(observationRegistry)); } @@ -3364,7 +3386,7 @@ public Mono<Boolean> toggleAutoCommitEnabled(String defaultApplicationId) { AutoCommitConfig autoCommitConfig = gitArtifactMetadata.getAutoCommitConfig(); if (autoCommitConfig.getEnabled()) { - autoCommitConfig.setEnabled(Boolean.FALSE); + autoCommitConfig.setEnabled(FALSE); } else { autoCommitConfig.setEnabled(TRUE); }
261cf8bfe602d2277cf3eeb294e0c0d910bd2b0b
2025-02-13 15:28:25
Aman Agarwal
fix: loading indicator ui for infinite loading table (#39208)
false
loading indicator ui for infinite loading table (#39208)
fix
diff --git a/app/client/src/ce/constants/messages.ts b/app/client/src/ce/constants/messages.ts index 0171963ba53f..c6f5dbfd9afb 100644 --- a/app/client/src/ce/constants/messages.ts +++ b/app/client/src/ce/constants/messages.ts @@ -2626,3 +2626,5 @@ export const PREMIUM_DATASOURCES = { export const DATASOURCE_SECURE_TEXT = () => `When connecting datasources, your passwords are AES-256 encrypted and we never store any of your data.`; + +export const TABLE_LOADING_RECORDS = () => "loading records"; diff --git a/app/client/src/widgets/TableWidgetV2/component/LoadingIndicator.test.tsx b/app/client/src/widgets/TableWidgetV2/component/LoadingIndicator.test.tsx new file mode 100644 index 000000000000..183d5dd0c9a7 --- /dev/null +++ b/app/client/src/widgets/TableWidgetV2/component/LoadingIndicator.test.tsx @@ -0,0 +1,26 @@ +import React from "react"; +import "@testing-library/jest-dom"; +import { render, screen } from "@testing-library/react"; +import { LoadingIndicator } from "./LoadingIndicator"; + +describe("LoadingIndicator", () => { + it("renders a spinner and loading text", () => { + render(<LoadingIndicator />); + + // Check if the Flex container is rendered + const flexContainer = document.querySelector(".ads-v2-flex"); + + expect(flexContainer).toBeInTheDocument(); + + // Check if the spinner is rendered + const spinner = document.querySelector(".ads-v2-spinner"); + + expect(spinner).toBeInTheDocument(); + + // Check if the text is displayed correctly + const textElement = screen.getByText("loading records"); + + expect(textElement).toBeInTheDocument(); + expect(textElement).toHaveClass("ads-v2-text"); + }); +}); diff --git a/app/client/src/widgets/TableWidgetV2/component/LoadingIndicator.tsx b/app/client/src/widgets/TableWidgetV2/component/LoadingIndicator.tsx new file mode 100644 index 000000000000..8764aafe1b9d --- /dev/null +++ b/app/client/src/widgets/TableWidgetV2/component/LoadingIndicator.tsx @@ -0,0 +1,22 @@ +import { Flex, Spinner, Text } from "@appsmith/ads"; +import { createMessage, TABLE_LOADING_RECORDS } from "ee/constants/messages"; +import React from "react"; + +export const LoadingIndicator = () => ( + <Flex + alignItems="center" + background="var(--ads-v2-color-white)" + borderTop="1px solid var(--wds-color-border-onaccent)" + bottom="0" + gap="spaces-3" + left="0" + padding="spaces-3" + position="sticky" + right="0" + > + <Spinner iconProps={{ color: "var(--ads-v2-color-gray-400)" }} size="md" /> + <Text color="var(--ads-v2-color-gray-400)" kind="body-s"> + {createMessage(TABLE_LOADING_RECORDS)} + </Text> + </Flex> +);
c44a279f11798173c994de970a02fb269c9b47d9
2024-03-25 11:40:44
Shrikant Sharat Kandula
chore(deps): Update webpack-dev-middleware to 5.3.4 (#32036)
false
Update webpack-dev-middleware to 5.3.4 (#32036)
chore
diff --git a/app/client/yarn.lock b/app/client/yarn.lock index c455af185e74..1d1e8e39a473 100644 --- a/app/client/yarn.lock +++ b/app/client/yarn.lock @@ -34186,8 +34186,8 @@ __metadata: linkType: hard "webpack-dev-middleware@npm:^5.3.1": - version: 5.3.3 - resolution: "webpack-dev-middleware@npm:5.3.3" + version: 5.3.4 + resolution: "webpack-dev-middleware@npm:5.3.4" dependencies: colorette: ^2.0.10 memfs: ^3.4.3 @@ -34196,7 +34196,7 @@ __metadata: schema-utils: ^4.0.0 peerDependencies: webpack: ^4.0.0 || ^5.0.0 - checksum: dd332cc6da61222c43d25e5a2155e23147b777ff32fdf1f1a0a8777020c072fbcef7756360ce2a13939c3f534c06b4992a4d659318c4a7fe2c0530b52a8a6621 + checksum: 90cf3e27d0714c1a745454a1794f491b7076434939340605b9ee8718ba2b85385b120939754e9fdbd6569811e749dee53eec319e0d600e70e0b0baffd8e3fb13 languageName: node linkType: hard
1e50debe2a5471cd258509df8cfd8daf37b04be6
2024-01-17 12:43:51
Rahul Barwal
chore: Refactor widgetselectionSagas to extract PartialImportExportSagas (#30295)
false
Refactor widgetselectionSagas to extract PartialImportExportSagas (#30295)
chore
diff --git a/app/client/src/actions/widgetActions.tsx b/app/client/src/actions/widgetActions.tsx index 8527bd716a0c..b67ca7ef21a3 100644 --- a/app/client/src/actions/widgetActions.tsx +++ b/app/client/src/actions/widgetActions.tsx @@ -7,7 +7,7 @@ import type { ExecuteTriggerPayload } from "constants/AppsmithActionConstants/Ac import type { BatchAction } from "actions/batchActions"; import { batchAction } from "actions/batchActions"; import type { WidgetProps } from "widgets/BaseWidget"; -import type { PartialExportParams } from "sagas/WidgetSelectionSagas"; +import type { PartialExportParams } from "sagas/PartialImportExportSagas"; export const widgetInitialisationSuccess = () => { return { diff --git a/app/client/src/components/editorComponents/PartialImportExport/PartialExportModal/index.tsx b/app/client/src/components/editorComponents/PartialImportExport/PartialExportModal/index.tsx index 525c2067fcf6..d4ed147236b4 100644 --- a/app/client/src/components/editorComponents/PartialImportExport/PartialExportModal/index.tsx +++ b/app/client/src/components/editorComponents/PartialImportExport/PartialExportModal/index.tsx @@ -28,7 +28,7 @@ import { useAppWideAndOtherDatasource } from "@appsmith/pages/Editor/Explorer/ho import React, { useEffect, useMemo, useState } from "react"; import { useDispatch, useSelector } from "react-redux"; import type { CanvasStructure } from "reducers/uiReducers/pageCanvasStructureReducer"; -import type { PartialExportParams } from "sagas/WidgetSelectionSagas"; +import type { PartialExportParams } from "sagas/PartialImportExportSagas"; import { getCurrentPageName } from "selectors/editorSelectors"; import type { JSLibrary } from "workers/common/JSLibrary"; import EntityCheckboxSelector from "./EntityCheckboxSelector"; diff --git a/app/client/src/sagas/PartialImportExportSagas/PartialExportSagas.ts b/app/client/src/sagas/PartialImportExportSagas/PartialExportSagas.ts new file mode 100644 index 000000000000..5291ab088eee --- /dev/null +++ b/app/client/src/sagas/PartialImportExportSagas/PartialExportSagas.ts @@ -0,0 +1,117 @@ +import ApplicationApi, { + type exportApplicationRequest, +} from "@appsmith/api/ApplicationApi"; +import type { + ApplicationPayload, + ReduxAction, +} from "@appsmith/constants/ReduxActionConstants"; +import { + ReduxActionErrorTypes, + ReduxActionTypes, +} from "@appsmith/constants/ReduxActionConstants"; +import { getCurrentApplication } from "@appsmith/selectors/applicationSelectors"; +import { toast } from "design-system"; +import { getFlexLayersForSelectedWidgets } from "layoutSystems/autolayout/utils/AutoLayoutUtils"; +import type { FlexLayer } from "layoutSystems/autolayout/utils/types"; +import type { FlattenedWidgetProps } from "reducers/entityReducers/canvasWidgetsReducer"; +import { all, call, put, select } from "redux-saga/effects"; +import { + getCurrentApplicationId, + getCurrentPageId, +} from "selectors/editorSelectors"; +import { validateResponse } from "../ErrorSagas"; +import { createWidgetCopy } from "../WidgetOperationUtils"; +import { getWidgets } from "../selectors"; + +export interface PartialExportParams { + jsObjects: string[]; + datasources: string[]; + customJSLibs: string[]; + widgets: string[]; + queries: string[]; +} + +export function* partialExportSaga(action: ReduxAction<PartialExportParams>) { + try { + const canvasWidgets: unknown = yield partialExportWidgetSaga( + action.payload.widgets, + ); + const applicationId: string = yield select(getCurrentApplicationId); + const currentPageId: string = yield select(getCurrentPageId); + + const body: exportApplicationRequest = { + actionList: action.payload.queries, + actionCollectionList: action.payload.jsObjects, + datasourceList: action.payload.datasources, + customJsLib: action.payload.customJSLibs, + widget: JSON.stringify(canvasWidgets), + }; + + const response: unknown = yield call( + ApplicationApi.exportPartialApplication, + applicationId, + currentPageId, + body, + ); + const isValid: boolean = yield validateResponse(response); + if (isValid) { + const application: ApplicationPayload = yield select( + getCurrentApplication, + ); + + (function downloadJSON(response: unknown) { + const dataStr = + "data:text/json;charset=utf-8," + + encodeURIComponent(JSON.stringify(response)); + const downloadAnchorNode = document.createElement("a"); + downloadAnchorNode.setAttribute("href", dataStr); + downloadAnchorNode.setAttribute("download", `${application.name}.json`); + document.body.appendChild(downloadAnchorNode); // required for firefox + downloadAnchorNode.click(); + downloadAnchorNode.remove(); + })((response as { data: unknown }).data); + yield put({ + type: ReduxActionTypes.PARTIAL_EXPORT_SUCCESS, + }); + } + } catch (e) { + toast.show(`Error exporting application. Please try again.`, { + kind: "error", + }); + yield put({ + type: ReduxActionErrorTypes.PARTIAL_EXPORT_ERROR, + payload: { + error: "Error exporting application", + }, + }); + } +} + +export function* partialExportWidgetSaga(widgetIds: string[]) { + const canvasWidgets: { + [widgetId: string]: FlattenedWidgetProps; + } = yield select(getWidgets); + const selectedWidgets = widgetIds.map((each) => canvasWidgets[each]); + + if (!selectedWidgets || !selectedWidgets.length) return; + + const widgetListsToStore: { + widgetId: string; + parentId: string; + list: FlattenedWidgetProps[]; + }[] = yield all( + selectedWidgets.map((widget) => call(createWidgetCopy, widget)), + ); + + const canvasId = selectedWidgets?.[0]?.parentId || ""; + + const flexLayers: FlexLayer[] = getFlexLayersForSelectedWidgets( + widgetIds, + canvasId ? canvasWidgets[canvasId] : undefined, + ); + const widgetsDSL = { + widgets: widgetListsToStore, + flexLayers, + }; + return widgetsDSL; +} diff --git a/app/client/src/sagas/PartialImportExportSagas/PartialImportSagas.ts b/app/client/src/sagas/PartialImportExportSagas/PartialImportSagas.ts new file mode 100644 index 000000000000..e908bc3b1fc8 --- /dev/null +++ b/app/client/src/sagas/PartialImportExportSagas/PartialImportSagas.ts @@ -0,0 +1,111 @@ +import { + importPartialApplicationSuccess, + initDatasourceConnectionDuringImportRequest, +} from "@appsmith/actions/applicationActions"; +import ApplicationApi from "@appsmith/api/ApplicationApi"; +import type { ReduxAction } from "@appsmith/constants/ReduxActionConstants"; +import { ReduxActionErrorTypes } from "@appsmith/constants/ReduxActionConstants"; +import type { AppState } from "@appsmith/reducers"; +import { areEnvironmentsFetched } from "@appsmith/selectors/environmentSelectors"; +import { getCurrentWorkspaceId } from "@appsmith/selectors/workspaceSelectors"; +import { pasteWidget } from "actions/widgetActions"; +import { selectWidgetInitAction } from "actions/widgetSelectionActions"; +import type { ApiResponse } from "api/ApiResponses"; +import { toast } from "design-system"; +import { call, fork, put, select } from "redux-saga/effects"; +import { SelectionRequestType } from "sagas/WidgetSelectUtils"; +import { + getCurrentApplicationId, + getCurrentPageId, +} from "selectors/editorSelectors"; +import { getCopiedWidgets, saveCopiedWidgets } from "utils/storage"; +import { validateResponse } from "../ErrorSagas"; +import { postPageAdditionSaga } from "../TemplatesSagas"; + +async function readJSONFile(file: File) { + return new Promise((resolve, reject) => { + const reader = new FileReader(); + reader.onload = () => { + try { + const json = JSON.parse(reader.result as string); + resolve(json); + } catch (e) { + reject(e); + } + }; + reader.readAsText(file); + }); +} + +function* partialImportWidgetsSaga(file: File) { + const existingCopiedWidgets: unknown = yield call(getCopiedWidgets); + try { + // assume that action.payload.applicationFile is a JSON file. Parse it and extract widgets property + const userUploadedJSON: { widgets: string } = yield call( + readJSONFile, + file, + ); + if ("widgets" in userUploadedJSON && userUploadedJSON.widgets.length > 0) { + yield saveCopiedWidgets(userUploadedJSON.widgets); + yield put(selectWidgetInitAction(SelectionRequestType.Empty)); + yield put(pasteWidget(false, { x: 0, y: 0 })); + } + } finally { + if (existingCopiedWidgets) { + yield call(saveCopiedWidgets, JSON.stringify(existingCopiedWidgets)); + } + } +} + +export function* partialImportSaga( + action: ReduxAction<{ applicationFile: File }>, +) { + try { + // Step1: Import widgets from file, in parallel + yield fork(partialImportWidgetsSaga, action.payload.applicationFile); + // Step2: Send backend request to import pending items. + const workspaceId: string = yield select(getCurrentWorkspaceId); + const pageId: string = yield select(getCurrentPageId); + const applicationId: string = yield select(getCurrentApplicationId); + const response: ApiResponse = yield call( + ApplicationApi.importPartialApplication, + { + applicationFile: action.payload.applicationFile, + workspaceId, + pageId, + applicationId, + }, + ); + + const isValidResponse: boolean = yield validateResponse(response); + + if (isValidResponse) { + yield call(postPageAdditionSaga, applicationId); + toast.show("Partial Application imported successfully", { + kind: "success", + }); + + const environmentsFetched: boolean = yield select((state: AppState) => + areEnvironmentsFetched(state, workspaceId), + ); + + if (workspaceId && environmentsFetched) { + yield put( + initDatasourceConnectionDuringImportRequest({ + workspaceId: workspaceId as string, + isPartialImport: true, + }), + ); + } + + yield put(importPartialApplicationSuccess()); + } + } catch (error) { + yield put({ + type: ReduxActionErrorTypes.PARTIAL_IMPORT_ERROR, + payload: { + error, + }, + }); + } +} diff --git a/app/client/src/sagas/PartialImportExportSagas/index.ts b/app/client/src/sagas/PartialImportExportSagas/index.ts new file mode 100644 index 000000000000..55b89e7b47e7 --- /dev/null +++ b/app/client/src/sagas/PartialImportExportSagas/index.ts @@ -0,0 +1,2 @@ +export * from "./PartialExportSagas"; +export * from "./PartialImportSagas"; diff --git a/app/client/src/sagas/WidgetOperationSagas.tsx b/app/client/src/sagas/WidgetOperationSagas.tsx index 53869a27b21c..42b68a12e60a 100644 --- a/app/client/src/sagas/WidgetOperationSagas.tsx +++ b/app/client/src/sagas/WidgetOperationSagas.tsx @@ -136,11 +136,11 @@ import { mergeDynamicPropertyPaths, purgeOrphanedDynamicPaths, } from "./WidgetOperationUtils"; +import { widgetSelectionSagas } from "./WidgetSelectionSagas"; import { - partialImportSaga, partialExportSaga, - widgetSelectionSagas, -} from "./WidgetSelectionSagas"; + partialImportSaga, +} from "./PartialImportExportSagas"; import type { WidgetEntityConfig } from "@appsmith/entities/DataTree/types"; import type { DataTree, ConfigTree } from "entities/DataTree/dataTreeTypes"; import { getCanvasSizeAfterWidgetMove } from "./CanvasSagas/DraggingCanvasSagas"; diff --git a/app/client/src/sagas/WidgetSelectionSagas.ts b/app/client/src/sagas/WidgetSelectionSagas.ts index 483c78c2e6b5..715ee4a5f267 100644 --- a/app/client/src/sagas/WidgetSelectionSagas.ts +++ b/app/client/src/sagas/WidgetSelectionSagas.ts @@ -1,54 +1,27 @@ import { widgetURL } from "@appsmith/RouteBuilder"; -import { - importPartialApplicationSuccess, - initDatasourceConnectionDuringImportRequest, -} from "@appsmith/actions/applicationActions"; -import ApplicationApi, { - type exportApplicationRequest, -} from "@appsmith/api/ApplicationApi"; -import type { - ApplicationPayload, - ReduxAction, -} from "@appsmith/constants/ReduxActionConstants"; +import type { ReduxAction } from "@appsmith/constants/ReduxActionConstants"; import { ReduxActionErrorTypes, ReduxActionTypes, } from "@appsmith/constants/ReduxActionConstants"; -import { getCurrentApplication } from "@appsmith/selectors/applicationSelectors"; import { getAppMode, getCanvasWidgets, } from "@appsmith/selectors/entitiesSelector"; -import { pasteWidget, showModal } from "actions/widgetActions"; +import { showModal } from "actions/widgetActions"; import type { SetSelectedWidgetsPayload, WidgetSelectionRequestPayload, } from "actions/widgetSelectionActions"; import { - selectWidgetInitAction, setEntityExplorerAncestry, setSelectedWidgetAncestry, setSelectedWidgets, } from "actions/widgetSelectionActions"; -import type { ApiResponse } from "api/ApiResponses"; -import { getCurrentWorkspaceId } from "@appsmith/selectors/workspaceSelectors"; -import { toast } from "design-system"; +import { MAIN_CONTAINER_WIDGET_ID } from "constants/WidgetConstants"; import { APP_MODE } from "entities/App"; -import { getFlexLayersForSelectedWidgets } from "layoutSystems/autolayout/utils/AutoLayoutUtils"; -import type { FlexLayer } from "layoutSystems/autolayout/utils/types"; -import type { - CanvasWidgetsReduxState, - FlattenedWidgetProps, -} from "reducers/entityReducers/canvasWidgetsReducer"; -import { - all, - call, - fork, - put, - select, - take, - takeLatest, -} from "redux-saga/effects"; +import type { CanvasWidgetsReduxState } from "reducers/entityReducers/canvasWidgetsReducer"; +import { all, call, put, select, take, takeLatest } from "redux-saga/effects"; import type { SetSelectionResult } from "sagas/WidgetSelectUtils"; import { SelectionRequestType, @@ -63,7 +36,6 @@ import { unselectWidget, } from "sagas/WidgetSelectUtils"; import { - getCurrentApplicationId, getCurrentPageId, getIsEditorInitialized, getIsFetchingPage, @@ -73,18 +45,11 @@ import { getLastSelectedWidget, getSelectedWidgets } from "selectors/ui"; import { areArraysEqual } from "utils/AppsmithUtils"; import { quickScrollToWidget } from "utils/helpers"; import history, { NavigationMethod } from "utils/history"; -import { getCopiedWidgets, saveCopiedWidgets } from "utils/storage"; -import { validateResponse } from "./ErrorSagas"; -import { postPageAdditionSaga } from "./TemplatesSagas"; -import { createWidgetCopy } from "./WidgetOperationUtils"; import { getWidgetIdsByType, getWidgetImmediateChildren, getWidgets, } from "./selectors"; -import type { AppState } from "@appsmith/reducers"; -import { areEnvironmentsFetched } from "@appsmith/selectors/environmentSelectors"; -import { MAIN_CONTAINER_WIDGET_ID } from "constants/WidgetConstants"; // The following is computed to be used in the entity explorer // Every time a widget is selected, we need to expand widget entities @@ -365,184 +330,3 @@ export function* widgetSelectionSagas() { ), ]); } - -export interface PartialExportParams { - jsObjects: string[]; - datasources: string[]; - customJSLibs: string[]; - widgets: string[]; - queries: string[]; -} - -export function* partialExportSaga(action: ReduxAction<PartialExportParams>) { - try { - const canvasWidgets: unknown = yield partialExportWidgetSaga( - action.payload.widgets, - ); - const applicationId: string = yield select(getCurrentApplicationId); - const currentPageId: string = yield select(getCurrentPageId); - - const body: exportApplicationRequest = { - actionList: action.payload.queries, - actionCollectionList: action.payload.jsObjects, - datasourceList: action.payload.datasources, - customJsLib: action.payload.customJSLibs, - widget: JSON.stringify(canvasWidgets), - }; - - const response: unknown = yield call( - ApplicationApi.exportPartialApplication, - applicationId, - currentPageId, - body, - ); - const isValid: boolean = yield validateResponse(response); - if (isValid) { - const application: ApplicationPayload = yield select( - getCurrentApplication, - ); - - (function downloadJSON(response: unknown) { - const dataStr = - "data:text/json;charset=utf-8," + - encodeURIComponent(JSON.stringify(response)); - const downloadAnchorNode = document.createElement("a"); - downloadAnchorNode.setAttribute("href", dataStr); - downloadAnchorNode.setAttribute("download", `${application.name}.json`); - document.body.appendChild(downloadAnchorNode); // required for firefox - downloadAnchorNode.click(); - downloadAnchorNode.remove(); - })((response as { data: unknown }).data); - yield put({ - type: ReduxActionTypes.PARTIAL_EXPORT_SUCCESS, - }); - } - } catch (e) { - toast.show(`Error exporting application. Please try again.`, { - kind: "error", - }); - yield put({ - type: ReduxActionErrorTypes.PARTIAL_EXPORT_ERROR, - payload: { - error: "Error exporting application", - }, - }); - } -} - -export function* partialExportWidgetSaga(widgetIds: string[]) { - const canvasWidgets: { - [widgetId: string]: FlattenedWidgetProps; - } = yield select(getWidgets); - const selectedWidgets = widgetIds.map((each) => canvasWidgets[each]); - - if (!selectedWidgets || !selectedWidgets.length) return; - - const widgetListsToStore: { - widgetId: string; - parentId: string; - list: FlattenedWidgetProps[]; - }[] = yield all( - selectedWidgets.map((widget) => call(createWidgetCopy, widget)), - ); - - const canvasId = selectedWidgets?.[0]?.parentId || ""; - - const flexLayers: FlexLayer[] = getFlexLayersForSelectedWidgets( - widgetIds, - canvasId ? canvasWidgets[canvasId] : undefined, - ); - const widgetsDSL = { - widgets: widgetListsToStore, - flexLayers, - }; - return widgetsDSL; -} - -async function readJSONFile(file: File) { - return new Promise((resolve, reject) => { - const reader = new FileReader(); - reader.onload = () => { - try { - const json = JSON.parse(reader.result as string); - resolve(json); - } catch (e) { - reject(e); - } - }; - reader.readAsText(file); - }); -} - -function* partialImportWidgetsSaga(file: File) { - const existingCopiedWidgets: unknown = yield call(getCopiedWidgets); - try { - // assume that action.payload.applicationFile is a JSON file. Parse it and extract widgets property - const userUploadedJSON: { widgets: string } = yield call( - readJSONFile, - file, - ); - if ("widgets" in userUploadedJSON && userUploadedJSON.widgets.length > 0) { - yield saveCopiedWidgets(userUploadedJSON.widgets); - yield put(selectWidgetInitAction(SelectionRequestType.Empty)); - yield put(pasteWidget(false, { x: 0, y: 0 })); - } - } finally { - if (existingCopiedWidgets) { - yield call(saveCopiedWidgets, JSON.stringify(existingCopiedWidgets)); - } - } -} - -export function* partialImportSaga( - action: ReduxAction<{ applicationFile: File }>, -) { - try { - // Step1: Import widgets from file, in parallel - yield fork(partialImportWidgetsSaga, action.payload.applicationFile); - // Step2: Send backend request to import pending items. - const workspaceId: string = yield select(getCurrentWorkspaceId); - const pageId: string = yield select(getCurrentPageId); - const applicationId: string = yield select(getCurrentApplicationId); - const response: ApiResponse = yield call( - ApplicationApi.importPartialApplication, - { - applicationFile: action.payload.applicationFile, - workspaceId, - pageId, - applicationId, - }, - ); - - const isValidResponse: boolean = yield validateResponse(response); - - if (isValidResponse) { - yield call(postPageAdditionSaga, applicationId); - toast.show("Partial Application imported successfully", { - kind: "success", - }); - - const environmentsFetched: boolean = yield select((state: AppState) => - areEnvironmentsFetched(state, workspaceId), - ); - - if (workspaceId && environmentsFetched) { - yield put( - initDatasourceConnectionDuringImportRequest({ - workspaceId: workspaceId as string, - isPartialImport: true, - }), - ); - } - - yield put(importPartialApplicationSuccess()); - } - } catch (error) { - yield put({ - type: ReduxActionErrorTypes.PARTIAL_IMPORT_ERROR, - payload: { - error, - }, - }); - } -}
d8f843187ffea1ff84aef2ea35bd1c4758e90d88
2022-03-17 10:17:17
Bhavin K
fix: handle Centered component height (#11825)
false
handle Centered component height (#11825)
fix
diff --git a/app/client/src/components/designSystems/appsmith/CenteredWrapper.tsx b/app/client/src/components/designSystems/appsmith/CenteredWrapper.tsx index 6896dc350366..a419f34b74d2 100644 --- a/app/client/src/components/designSystems/appsmith/CenteredWrapper.tsx +++ b/app/client/src/components/designSystems/appsmith/CenteredWrapper.tsx @@ -1,7 +1,24 @@ import styled from "styled-components"; -export default styled.div` - height: ${(props) => `calc(100vh - ${props.theme.smallHeaderHeight})`}; +/** + * Common component, mostly use to show loader / message + * + * Used By: + * AppViewerPageContainer + * - parent component AppViewer -> AppViewerBody's height calculated good enough + * - inherited height works fine here. + * CanvasContainer + * - calculated height looks good + * DefaultOrgPage + * - calculated height looks good + */ +export default styled.div<{ + isInheritedHeight?: boolean; +}>` + height: ${(props) => + props.isInheritedHeight + ? "inherit" + : `calc(100vh - ${props.theme.smallHeaderHeight})`}; width: 100%; display: flex; justify-content: center; diff --git a/app/client/src/pages/AppViewer/AppViewerPageContainer.tsx b/app/client/src/pages/AppViewer/AppViewerPageContainer.tsx index 487b642b9d5f..ff5847f0a732 100644 --- a/app/client/src/pages/AppViewer/AppViewerPageContainer.tsx +++ b/app/client/src/pages/AppViewer/AppViewerPageContainer.tsx @@ -76,7 +76,7 @@ class AppViewerPageContainer extends Component<AppViewerPageContainerProps> { ); } const pageNotFound = ( - <Centered> + <Centered isInheritedHeight> <NonIdealState description={appsmithEditorLink} icon={ @@ -91,7 +91,7 @@ class AppViewerPageContainer extends Component<AppViewerPageContainerProps> { </Centered> ); const pageLoading = ( - <Centered> + <Centered isInheritedHeight> <Spinner /> </Centered> );
50014eef7857fb146b589db5cb0d4b08383ffa65
2022-08-16 16:44:44
Satish Gandham
ci: Update the access token in ci script (#16058)
false
Update the access token in ci script (#16058)
ci
diff --git a/.github/workflows/integration-tests-command.yml b/.github/workflows/integration-tests-command.yml index 4f97efd19775..e9460313845d 100644 --- a/.github/workflows/integration-tests-command.yml +++ b/.github/workflows/integration-tests-command.yml @@ -1355,7 +1355,7 @@ jobs: uses: actions/checkout@v3 with: repository: appsmithorg/performance-infra - token: ${{ secrets.CYPRESS_GITHUB_PERSONAL_ACCESS_TOKEN }} + token: ${{ secrets.APPSMITH_PERF_INFRA_REPO_PAT }} ref: main path: app/client/perf
7112f9d857be8c025343e4a0339df1c990d6fca5
2023-07-21 22:03:15
Ayush Pahwa
chore: update tests to include ts definitions (#25555)
false
update tests to include ts definitions (#25555)
chore
diff --git a/app/client/cypress/support/Pages/HomePage.ts b/app/client/cypress/support/Pages/HomePage.ts index d9781bc98dfd..02ffe8ead07d 100644 --- a/app/client/cypress/support/Pages/HomePage.ts +++ b/app/client/cypress/support/Pages/HomePage.ts @@ -325,15 +325,20 @@ export class HomePage { cy.window().its("store").invoke("dispatch", { type: "LOGOUT_USER_INIT" }); cy.wait("@postLogout"); this.agHelper.VisitNAssert("/user/login", "signUpLogin"); - cy.get(this._username).should("be.visible").type(uname); - cy.get(this._password).type(pswd, { log: false }); - cy.get(this._submitBtn).click(); - cy.wait("@getMe"); + this.agHelper.AssertElementVisible(this._username); + this.agHelper.TypeText(this._username, uname); + this.agHelper.TypeText(this._password, pswd); + this.agHelper.GetNClick(this._submitBtn); + this.assertHelper.AssertNetworkStatus("@getMe"); this.agHelper.Sleep(3000); - if (role != "App Viewer") - cy.get(this._homePageAppCreateBtn) - .should("be.visible") - .should("be.enabled"); + if (role != "App Viewer") { + this.agHelper.AssertElementVisible(this._homePageAppCreateBtn); + this.agHelper.AssertElementEnabledDisabled( + this._homePageAppCreateBtn, + undefined, + false, + ); + } } public SignUp(uname: string, pswd: string) { @@ -341,20 +346,21 @@ export class HomePage { cy.window().its("store").invoke("dispatch", { type: "LOGOUT_USER_INIT" }); cy.wait("@postLogout"); this.agHelper.VisitNAssert("/user/signup", "signUpLogin"); - cy.get(this.signupUsername).should("be.visible").type(uname); - cy.get(this._password).type(pswd, { log: false }); - cy.get(this._submitBtn).click(); - cy.wait(1000); + this.agHelper.AssertElementVisible(this.signupUsername); + this.agHelper.TypeText(this.signupUsername, uname); + this.agHelper.TypeText(this._password, pswd); + this.agHelper.GetNClick(this._submitBtn); + this.agHelper.Sleep(1000); cy.get("body").then(($body) => { if ($body.find(this.roleDropdown).length > 0) { - cy.get(this.roleDropdown).click(); - cy.get(this.dropdownOption).click(); - cy.get(this.useCaseDropdown).click(); - cy.get(this.dropdownOption).click(); - cy.get(this.roleUsecaseSubmit).click({ force: true }); + this.agHelper.GetNClick(this.roleDropdown); + this.agHelper.GetNClick(this.dropdownOption); + this.agHelper.GetNClick(this.useCaseDropdown); + this.agHelper.GetNClick(this.dropdownOption); + this.agHelper.GetNClick(this.roleUsecaseSubmit, undefined, true); } }); - cy.wait("@getMe"); + this.assertHelper.AssertNetworkStatus("@getMe"); this.agHelper.Sleep(3000); } diff --git a/app/client/src/ee/components/EnvConfigSection.tsx/index.tsx b/app/client/src/ee/components/EnvConfigSection/index.tsx similarity index 100% rename from app/client/src/ee/components/EnvConfigSection.tsx/index.tsx rename to app/client/src/ee/components/EnvConfigSection/index.tsx diff --git a/app/client/src/pages/Editor/DataSourceEditor/DatasourceSection.tsx b/app/client/src/pages/Editor/DataSourceEditor/DatasourceSection.tsx index 6aba69b0ec0f..af541950c1db 100644 --- a/app/client/src/pages/Editor/DataSourceEditor/DatasourceSection.tsx +++ b/app/client/src/pages/Editor/DataSourceEditor/DatasourceSection.tsx @@ -15,7 +15,7 @@ import { import { getPlugin } from "selectors/entitiesSelector"; import type { PluginType } from "entities/Action"; import { getDefaultEnvId } from "@appsmith/api/ApiUtils"; -import { EnvConfigSection } from "@appsmith/components/EnvConfigSection.tsx"; +import { EnvConfigSection } from "@appsmith/components/EnvConfigSection"; const Key = styled.div` color: var(--ads-v2-color-fg-muted);
74ef1c9976be90d21a2c72334ffde55dee322fde
2020-10-08 22:19:26
Hetu Nandu
ci: Fix build id step:
false
Fix build id step:
ci
diff --git a/.github/workflows/client.yml b/.github/workflows/client.yml index 0abb23aee400..9b050329dae5 100644 --- a/.github/workflows/client.yml +++ b/.github/workflows/client.yml @@ -17,6 +17,7 @@ defaults: jobs: build_id: + runs-on: ubuntu-latest steps: - name: 'Set build id' id: build_id
6587a1851244142d61aefb4c99d58c9b720afc4b
2023-04-13 20:58:29
ChandanBalajiBP
chore: Add telemetry for resolved error message (#22339)
false
Add telemetry for resolved error message (#22339)
chore
diff --git a/app/client/src/actions/debuggerActions.ts b/app/client/src/actions/debuggerActions.ts index e25b230c13f8..4c449caa705f 100644 --- a/app/client/src/actions/debuggerActions.ts +++ b/app/client/src/actions/debuggerActions.ts @@ -9,6 +9,7 @@ export interface LogDebuggerErrorAnalyticsPayload { entityType: ENTITY_TYPE; eventName: EventName; propertyPath: string; + errorId?: string; errorMessages?: Message[]; errorMessage?: Message["message"]; errorType?: Message["type"]; diff --git a/app/client/src/sagas/DebuggerSagas.ts b/app/client/src/sagas/DebuggerSagas.ts index 26d87de56af1..7121659248c4 100644 --- a/app/client/src/sagas/DebuggerSagas.ts +++ b/app/client/src/sagas/DebuggerSagas.ts @@ -392,6 +392,7 @@ function* logDebuggerErrorAnalyticsSaga( AnalyticsUtil.logEvent(payload.eventName, { entityType: widgetType, propertyPath, + errorId: payload.errorId, errorMessages: payload.errorMessages, pageId: currentPageId, errorMessage: payload.errorMessage, @@ -415,6 +416,7 @@ function* logDebuggerErrorAnalyticsSaga( AnalyticsUtil.logEvent(payload.eventName, { entityType: pluginName, propertyPath, + errorId: payload.errorId, errorMessages: payload.errorMessages, pageId: currentPageId, errorMessage: payload.errorMessage, @@ -433,6 +435,7 @@ function* logDebuggerErrorAnalyticsSaga( // Sending plugin name for actions AnalyticsUtil.logEvent(payload.eventName, { entityType: pluginName, + errorId: payload.errorId, propertyPath: payload.propertyPath, errorMessages: payload.errorMessages, pageId: currentPageId, @@ -535,6 +538,7 @@ function* addDebuggerErrorLogsSaga(action: ReduxAction<Log[]>) { payload: { ...analyticsPayload, eventName: "DEBUGGER_RESOLVED_ERROR_MESSAGE", + errorId: currentDebuggerErrors[id].id, errorMessage: existingErrorMessage.message, errorType: existingErrorMessage.type, errorSubType: existingErrorMessage.subType, @@ -588,10 +592,6 @@ function* deleteDebuggerErrorLogsSaga( }); if (errorMessages) { - const appsmithErrorCode = get( - error, - "pluginErrorDetails.appsmithErrorCode", - ); yield all( errorMessages.map((errorMessage) => { return put({ @@ -599,11 +599,10 @@ function* deleteDebuggerErrorLogsSaga( payload: { ...analyticsPayload, eventName: "DEBUGGER_RESOLVED_ERROR_MESSAGE", + errorId: error.id, errorMessage: errorMessage.message, errorType: errorMessage.type, errorSubType: errorMessage.subType, - appsmithErrorCode, - tat: Date.now() - new Date(parseInt(error.timestamp)).getTime(), }, }); }),
c7d1e87c0aefe631261bfc3ecc93c6310174e9ee
2022-01-26 19:02:48
Nidhi
fix: Removed tracking on Sentry for unsupported plugin operation (#10636)
false
Removed tracking on Sentry for unsupported plugin operation (#10636)
fix
diff --git a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/exceptions/pluginExceptions/AppsmithPluginError.java b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/exceptions/pluginExceptions/AppsmithPluginError.java index d7c8282b7e71..7ab99dde68af 100644 --- a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/exceptions/pluginExceptions/AppsmithPluginError.java +++ b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/exceptions/pluginExceptions/AppsmithPluginError.java @@ -37,6 +37,7 @@ public enum AppsmithPluginError { AppsmithErrorAction.LOG_EXTERNALLY, "Appsmith In Memory Filtering Failed", ErrorType.INTERNAL_ERROR), PLUGIN_UQI_WHERE_CONDITION_UNKNOWN(500, 5011, "{0} is not a known conditional operator. Please reach out to Appsmith customer support to report this", AppsmithErrorAction.LOG_EXTERNALLY, "Where condition could not be parsed", ErrorType.INTERNAL_ERROR), + UNSUPPORTED_PLUGIN_OPERATION(500, 5012, "Unsupported operation", AppsmithErrorAction.DEFAULT, null, ErrorType.INTERNAL_ERROR), ; private final Integer httpErrorCode; diff --git a/app/server/appsmith-plugins/saasPlugin/src/main/java/com/external/plugins/SaasPlugin.java b/app/server/appsmith-plugins/saasPlugin/src/main/java/com/external/plugins/SaasPlugin.java index 7076816b85c8..c9a74a0955b0 100644 --- a/app/server/appsmith-plugins/saasPlugin/src/main/java/com/external/plugins/SaasPlugin.java +++ b/app/server/appsmith-plugins/saasPlugin/src/main/java/com/external/plugins/SaasPlugin.java @@ -213,7 +213,7 @@ public Set<String> validateDatasource(DatasourceConfiguration datasourceConfigur @Override public Mono<DatasourceTestResult> testDatasource(DatasourceConfiguration datasourceConfiguration) { - return Mono.error(new AppsmithPluginException(AppsmithPluginError.PLUGIN_ERROR, "Unsupported Operation")); + return Mono.error(new AppsmithPluginException(AppsmithPluginError.UNSUPPORTED_PLUGIN_OPERATION)); } } } \ No newline at end of file
101d5724823dc6c199840dfc2e068fa4750e89d2
2023-07-17 12:16:55
Sangeeth Sivan
fix: auto expand data section in prop pane on connect data (#25297)
false
auto expand data section in prop pane on connect data (#25297)
fix
diff --git a/app/client/src/pages/Editor/PropertyPane/PropertySection.tsx b/app/client/src/pages/Editor/PropertyPane/PropertySection.tsx index 6c77906977db..3cdb3d7250ec 100644 --- a/app/client/src/pages/Editor/PropertyPane/PropertySection.tsx +++ b/app/client/src/pages/Editor/PropertyPane/PropertySection.tsx @@ -1,6 +1,12 @@ import { Classes } from "@blueprintjs/core"; import type { ReactNode, Context } from "react"; -import React, { memo, useState, createContext, useCallback } from "react"; +import React, { + memo, + useState, + useEffect, + createContext, + useCallback, +} from "react"; import { Collapse } from "@blueprintjs/core"; import styled from "styled-components"; import { Colors } from "constants/Colors"; @@ -10,6 +16,7 @@ import { useDispatch, useSelector } from "react-redux"; import { getPropertySectionState } from "selectors/editorContextSelectors"; import { getCurrentWidgetId } from "selectors/propertyPaneSelectors"; import { setPropertySectionState } from "actions/propertyPaneActions"; +import { getIsOneClickBindingOptionsVisibility } from "selectors/oneClickBindingSelectors"; const TagContainer = styled.div``; @@ -105,7 +112,17 @@ export const PropertySection = memo((props: PropertySectionProps) => { } else { initialIsOpenState = !!isDefaultOpen; } + + const className = props.name.split(" ").join("").toLowerCase(); + const [isOpen, setIsOpen] = useState(initialIsOpenState); + const connectDataClicked = useSelector(getIsOneClickBindingOptionsVisibility); + + useEffect(() => { + if (connectDataClicked && className === "data" && !isOpen) { + handleSectionTitleClick(); + } + }, [connectDataClicked]); const handleSectionTitleClick = useCallback(() => { if (props.collapsible) @@ -123,7 +140,6 @@ export const PropertySection = memo((props: PropertySectionProps) => { if (!currentWidgetId) return null; - const className = props.name.split(" ").join("").toLowerCase(); return ( <SectionWrapper className={`t--property-pane-section-wrapper ${props.className}`}
ac41ad250b3b75460adc54d64e9fbf8ea1b62ece
2025-02-07 16:45:55
Hetu Nandu
chore: Move entities/IDE/constants (#39064)
false
Move entities/IDE/constants (#39064)
chore
diff --git a/app/client/src/IDE/Interfaces/EditorTypes.ts b/app/client/src/IDE/Interfaces/EditorTypes.ts new file mode 100644 index 000000000000..c899c3bd02f0 --- /dev/null +++ b/app/client/src/IDE/Interfaces/EditorTypes.ts @@ -0,0 +1,16 @@ +export enum EditorEntityTab { + QUERIES = "queries", + JS = "js", + UI = "ui", +} + +export enum EditorEntityTabState { + List = "List", + Edit = "Edit", + Add = "Add", +} + +export enum EditorViewMode { + FullScreen = "FullScreen", + SplitScreen = "SplitScreen", +} diff --git a/app/client/src/IDE/Interfaces/UseRoutes.ts b/app/client/src/IDE/Interfaces/UseRoutes.ts new file mode 100644 index 000000000000..23744e49c3e1 --- /dev/null +++ b/app/client/src/IDE/Interfaces/UseRoutes.ts @@ -0,0 +1,8 @@ +import type { ComponentType } from "react"; + +export type UseRoutes = Array<{ + key: string; + component: ComponentType; + path: string[]; + exact: boolean; +}>; diff --git a/app/client/src/IDE/constants/SidebarButtons.ts b/app/client/src/IDE/constants/SidebarButtons.ts new file mode 100644 index 000000000000..2a57b14b3521 --- /dev/null +++ b/app/client/src/IDE/constants/SidebarButtons.ts @@ -0,0 +1,41 @@ +import type { IDESidebarButton } from "@appsmith/ads"; +import { EditorState } from "../enums"; + +const SidebarButtonTitles = { + EDITOR: "Editor", + DATA: "Datasources", + SETTINGS: "Settings", + LIBRARIES: "Libraries", +}; + +export const EditorButton = (urlSuffix: string): IDESidebarButton => ({ + state: EditorState.EDITOR, + icon: "editor-v3", + title: SidebarButtonTitles.EDITOR, + testId: SidebarButtonTitles.EDITOR, + urlSuffix, +}); + +export const DataButton = (urlSuffix: string): IDESidebarButton => ({ + state: EditorState.DATA, + icon: "datasource-v3", + tooltip: SidebarButtonTitles.DATA, + testId: SidebarButtonTitles.DATA, + urlSuffix, +}); + +export const LibrariesButton = (urlSuffix: string): IDESidebarButton => ({ + state: EditorState.LIBRARIES, + icon: "packages-v3", + tooltip: SidebarButtonTitles.LIBRARIES, + testId: SidebarButtonTitles.LIBRARIES, + urlSuffix, +}); + +export const SettingsButton = (urlSuffix: string): IDESidebarButton => ({ + state: EditorState.SETTINGS, + icon: "settings-v3", + tooltip: SidebarButtonTitles.SETTINGS, + testId: SidebarButtonTitles.SETTINGS, + urlSuffix, +}); diff --git a/app/client/src/IDE/enums.ts b/app/client/src/IDE/enums.ts index 2c62e72c91ad..b1fdd7489d8f 100644 --- a/app/client/src/IDE/enums.ts +++ b/app/client/src/IDE/enums.ts @@ -3,3 +3,10 @@ export enum Condition { // Error = "Error", // Success = "Success", } + +export enum EditorState { + DATA = "DATA", + EDITOR = "EDITOR", + SETTINGS = "SETTINGS", + LIBRARIES = "LIBRARIES", +} diff --git a/app/client/src/IDE/hooks/useIsInSideBySideEditor.test.tsx b/app/client/src/IDE/hooks/useIsInSideBySideEditor.test.tsx index 81cf7a8d802f..e19ee79c2b7f 100644 --- a/app/client/src/IDE/hooks/useIsInSideBySideEditor.test.tsx +++ b/app/client/src/IDE/hooks/useIsInSideBySideEditor.test.tsx @@ -1,7 +1,7 @@ import React from "react"; import { renderHook, act } from "@testing-library/react-hooks/dom"; import { Provider } from "react-redux"; -import { EditorViewMode } from "ee/entities/IDE/constants"; +import { EditorViewMode } from "IDE/Interfaces/EditorTypes"; import { useIsInSideBySideEditor } from "./useIsInSideBySideEditor"; import { getIDETestState } from "test/factories/AppIDEFactoryUtils"; import type { AppState } from "ee/reducers"; diff --git a/app/client/src/actions/ideActions.ts b/app/client/src/actions/ideActions.ts index 028fa36b18f3..c6f8b5ae385c 100644 --- a/app/client/src/actions/ideActions.ts +++ b/app/client/src/actions/ideActions.ts @@ -1,4 +1,4 @@ -import type { EditorViewMode } from "ee/entities/IDE/constants"; +import type { EditorViewMode } from "IDE/Interfaces/EditorTypes"; import { ReduxActionTypes } from "ee/constants/ReduxActionConstants"; import type { ParentEntityIDETabs } from "../reducers/uiReducers/ideReducer"; diff --git a/app/client/src/ce/IDE/Interfaces/EntityItem.ts b/app/client/src/ce/IDE/Interfaces/EntityItem.ts new file mode 100644 index 000000000000..d4c723e0533c --- /dev/null +++ b/app/client/src/ce/IDE/Interfaces/EntityItem.ts @@ -0,0 +1,13 @@ +import type { PluginType } from "../../../entities/Plugin"; +import type { ReactNode } from "react"; + +export interface EntityItem { + title: string; + type: PluginType; + key: string; + icon?: ReactNode; + group?: string; + userPermissions?: string[]; +} + +export interface GenericEntityItem extends Omit<EntityItem, "type"> {} diff --git a/app/client/src/ce/IDE/Interfaces/IDETypes.ts b/app/client/src/ce/IDE/Interfaces/IDETypes.ts new file mode 100644 index 000000000000..525d543603ce --- /dev/null +++ b/app/client/src/ce/IDE/Interfaces/IDETypes.ts @@ -0,0 +1,6 @@ +export const IDE_TYPE = { + None: "None", + App: "App", +} as const; + +export type IDEType = keyof typeof IDE_TYPE; diff --git a/app/client/src/ce/IDE/constants/routes.ts b/app/client/src/ce/IDE/constants/routes.ts new file mode 100644 index 000000000000..114075e8ac44 --- /dev/null +++ b/app/client/src/ce/IDE/constants/routes.ts @@ -0,0 +1,44 @@ +import { + ADD_PATH, + API_EDITOR_ID_ADD_PATH, + API_EDITOR_ID_PATH, + BUILDER_CUSTOM_PATH, + BUILDER_PATH, + BUILDER_PATH_DEPRECATED, + DATA_SOURCES_EDITOR_ID_PATH, + ENTITY_PATH, + INTEGRATION_EDITOR_PATH, + JS_COLLECTION_ID_ADD_PATH, + JS_COLLECTION_ID_PATH, + QUERIES_EDITOR_ID_ADD_PATH, + QUERIES_EDITOR_ID_PATH, + WIDGETS_EDITOR_ID_PATH, +} from "ee/constants/routes/appRoutes"; +import { + SAAS_EDITOR_API_ID_ADD_PATH, + SAAS_EDITOR_API_ID_PATH, + SAAS_EDITOR_DATASOURCE_ID_PATH, +} from "pages/Editor/SaaSEditor/constants"; + +import { IDE_TYPE, type IDEType } from "../Interfaces/IDETypes"; + +export const EntityPaths: string[] = [ + API_EDITOR_ID_ADD_PATH, + API_EDITOR_ID_PATH, + QUERIES_EDITOR_ID_ADD_PATH, + QUERIES_EDITOR_ID_PATH, + DATA_SOURCES_EDITOR_ID_PATH, + INTEGRATION_EDITOR_PATH, + SAAS_EDITOR_DATASOURCE_ID_PATH, + SAAS_EDITOR_API_ID_ADD_PATH, + SAAS_EDITOR_API_ID_PATH, + JS_COLLECTION_ID_PATH, + JS_COLLECTION_ID_ADD_PATH, + WIDGETS_EDITOR_ID_PATH, + WIDGETS_EDITOR_ID_PATH + ADD_PATH, + ENTITY_PATH, +]; +export const IDEBasePaths: Readonly<Record<IDEType, string[]>> = { + [IDE_TYPE.None]: [], + [IDE_TYPE.App]: [BUILDER_PATH, BUILDER_PATH_DEPRECATED, BUILDER_CUSTOM_PATH], +}; diff --git a/app/client/src/ce/IDE/hooks/useParentEntityInfo.ts b/app/client/src/ce/IDE/hooks/useParentEntityInfo.ts index 47a277a4cca8..8844342f74f5 100644 --- a/app/client/src/ce/IDE/hooks/useParentEntityInfo.ts +++ b/app/client/src/ce/IDE/hooks/useParentEntityInfo.ts @@ -1,5 +1,5 @@ import { ActionParentEntityType } from "ee/entities/Engine/actionHelpers"; -import type { IDEType } from "ee/entities/IDE/constants"; +import type { IDEType } from "ee/IDE/Interfaces/IDETypes"; import { useSelector } from "react-redux"; import { getCurrentApplicationId, diff --git a/app/client/src/ce/PluginActionEditor/components/PluginActionResponse/hooks/usePluginActionResponseTabs.tsx b/app/client/src/ce/PluginActionEditor/components/PluginActionResponse/hooks/usePluginActionResponseTabs.tsx index 6d6988b883f5..80563b6d3d89 100644 --- a/app/client/src/ce/PluginActionEditor/components/PluginActionResponse/hooks/usePluginActionResponseTabs.tsx +++ b/app/client/src/ce/PluginActionEditor/components/PluginActionResponse/hooks/usePluginActionResponseTabs.tsx @@ -3,7 +3,8 @@ import { usePluginActionContext } from "PluginActionEditor/PluginActionContext"; import type { BottomTab } from "components/editorComponents/EntityBottomTabs"; import { getIDEViewMode } from "selectors/ideSelectors"; import { useSelector } from "react-redux"; -import { EditorViewMode, IDE_TYPE } from "ee/entities/IDE/constants"; +import { EditorViewMode } from "IDE/Interfaces/EditorTypes"; +import { IDE_TYPE } from "ee/IDE/Interfaces/IDETypes"; import { DEBUGGER_TAB_KEYS } from "components/editorComponents/Debugger/constants"; import { createMessage, diff --git a/app/client/src/ce/actions/helpers.ts b/app/client/src/ce/actions/helpers.ts index f244ff7483d2..bc0c4d1621b8 100644 --- a/app/client/src/ce/actions/helpers.ts +++ b/app/client/src/ce/actions/helpers.ts @@ -10,7 +10,7 @@ import { saveActionName, } from "actions/pluginActionActions"; import { saveJSObjectName } from "actions/jsActionActions"; -import { IDE_TYPE, type IDEType } from "ee/entities/IDE/constants"; +import { IDE_TYPE, type IDEType } from "ee/IDE/Interfaces/IDETypes"; export const createNewQueryBasedOnParentEntity = ( entityId: string, diff --git a/app/client/src/ce/entities/IDE/constants.ts b/app/client/src/ce/entities/IDE/constants.ts deleted file mode 100644 index 7809cb7f47d6..000000000000 --- a/app/client/src/ce/entities/IDE/constants.ts +++ /dev/null @@ -1,141 +0,0 @@ -import { - ADD_PATH, - API_EDITOR_ID_ADD_PATH, - API_EDITOR_ID_PATH, - BUILDER_CUSTOM_PATH, - BUILDER_PATH, - BUILDER_PATH_DEPRECATED, - DATA_SOURCES_EDITOR_ID_PATH, - ENTITY_PATH, - INTEGRATION_EDITOR_PATH, - JS_COLLECTION_ID_ADD_PATH, - JS_COLLECTION_ID_PATH, - QUERIES_EDITOR_ID_ADD_PATH, - QUERIES_EDITOR_ID_PATH, - WIDGETS_EDITOR_ID_PATH, -} from "ee/constants/routes/appRoutes"; -import { - SAAS_EDITOR_API_ID_ADD_PATH, - SAAS_EDITOR_API_ID_PATH, - SAAS_EDITOR_DATASOURCE_ID_PATH, -} from "pages/Editor/SaaSEditor/constants"; -import type { PluginType } from "entities/Plugin"; -import type { ComponentType, ReactNode } from "react"; -import type { IDESidebarButton } from "@appsmith/ads"; - -export enum EditorState { - DATA = "DATA", - EDITOR = "EDITOR", - SETTINGS = "SETTINGS", - LIBRARIES = "LIBRARIES", -} - -export const SidebarTopButtonTitles = { - EDITOR: "Editor", -}; - -export const SidebarBottomButtonTitles = { - DATA: "Datasources", - SETTINGS: "Settings", - LIBRARIES: "Libraries", -}; - -export enum EditorEntityTab { - QUERIES = "queries", - JS = "js", - UI = "ui", -} - -export enum EditorEntityTabState { - List = "List", - Edit = "Edit", - Add = "Add", -} - -export enum EditorViewMode { - FullScreen = "FullScreen", - SplitScreen = "SplitScreen", -} - -export const TopButtons: IDESidebarButton[] = [ - { - state: EditorState.EDITOR, - icon: "editor-v3", - title: SidebarTopButtonTitles.EDITOR, - testId: SidebarTopButtonTitles.EDITOR, - urlSuffix: "", - }, -]; - -export const BottomButtons: IDESidebarButton[] = [ - { - state: EditorState.DATA, - icon: "datasource-v3", - tooltip: SidebarBottomButtonTitles.DATA, - testId: SidebarBottomButtonTitles.DATA, - urlSuffix: "datasource", - }, - { - state: EditorState.LIBRARIES, - icon: "packages-v3", - tooltip: SidebarBottomButtonTitles.LIBRARIES, - testId: SidebarBottomButtonTitles.LIBRARIES, - urlSuffix: "libraries", - }, - { - state: EditorState.SETTINGS, - icon: "settings-v3", - tooltip: SidebarBottomButtonTitles.SETTINGS, - testId: SidebarBottomButtonTitles.SETTINGS, - urlSuffix: "settings", - }, -]; - -export const IDE_TYPE = { - None: "None", - App: "App", -} as const; - -export type IDEType = keyof typeof IDE_TYPE; - -export const EntityPaths: string[] = [ - API_EDITOR_ID_ADD_PATH, - API_EDITOR_ID_PATH, - QUERIES_EDITOR_ID_ADD_PATH, - QUERIES_EDITOR_ID_PATH, - DATA_SOURCES_EDITOR_ID_PATH, - INTEGRATION_EDITOR_PATH, - SAAS_EDITOR_DATASOURCE_ID_PATH, - SAAS_EDITOR_API_ID_ADD_PATH, - SAAS_EDITOR_API_ID_PATH, - JS_COLLECTION_ID_PATH, - JS_COLLECTION_ID_ADD_PATH, - WIDGETS_EDITOR_ID_PATH, - WIDGETS_EDITOR_ID_PATH + ADD_PATH, - ENTITY_PATH, -]; - -export const IDEBasePaths: Readonly<Record<IDEType, string[]>> = { - [IDE_TYPE.None]: [], - [IDE_TYPE.App]: [BUILDER_PATH, BUILDER_PATH_DEPRECATED, BUILDER_CUSTOM_PATH], -}; - -export interface EntityItem { - title: string; - type: PluginType; - key: string; - icon?: ReactNode; - group?: string; - userPermissions?: string[]; -} - -export interface GenericEntityItem extends Omit<EntityItem, "type"> {} - -export type UseRoutes = Array<{ - key: string; - // TODO: Fix this the next time the file is edited - // eslint-disable-next-line @typescript-eslint/no-explicit-any - component: ComponentType<any>; - path: string[]; - exact: boolean; -}>; diff --git a/app/client/src/ce/entities/IDE/hooks/useCreateActionsPermissions.ts b/app/client/src/ce/entities/IDE/hooks/useCreateActionsPermissions.ts index c984e29bc061..25af291d792d 100644 --- a/app/client/src/ce/entities/IDE/hooks/useCreateActionsPermissions.ts +++ b/app/client/src/ce/entities/IDE/hooks/useCreateActionsPermissions.ts @@ -1,5 +1,5 @@ import { useFeatureFlag } from "utils/hooks/useFeatureFlag"; -import { IDE_TYPE, type IDEType } from "ee/entities/IDE/constants"; +import { IDE_TYPE, type IDEType } from "ee/IDE/Interfaces/IDETypes"; import { FEATURE_FLAG } from "ee/entities/FeatureFlag"; import { useSelector } from "react-redux"; import { getPagePermissions } from "selectors/editorSelectors"; diff --git a/app/client/src/ce/entities/IDE/utils.ts b/app/client/src/ce/entities/IDE/utils.ts index d119cac82369..02c6809e6015 100644 --- a/app/client/src/ce/entities/IDE/utils.ts +++ b/app/client/src/ce/entities/IDE/utils.ts @@ -1,5 +1,6 @@ -import type { IDEType, EditorState } from "ee/entities/IDE/constants"; -import { IDE_TYPE, IDEBasePaths } from "ee/entities/IDE/constants"; +import type { EditorState } from "IDE/enums"; +import { IDE_TYPE, type IDEType } from "ee/IDE/Interfaces/IDETypes"; +import { IDEBasePaths } from "ee/IDE/constants/routes"; import { matchPath } from "react-router"; import { identifyEntityFromPath } from "navigation/FocusEntity"; import { @@ -9,7 +10,8 @@ import { } from "ee/constants/routes/appRoutes"; import { saveActionName } from "actions/pluginActionActions"; import { saveJSObjectName } from "actions/jsActionActions"; -import { EditorEntityTab, type EntityItem } from "ee/entities/IDE/constants"; +import { EditorEntityTab } from "IDE/Interfaces/EditorTypes"; +import type { EntityItem } from "ee/IDE/Interfaces/EntityItem"; import { getHasManageActionPermission } from "ee/utils/BusinessFeatures/permissionPageHelpers"; export interface SaveEntityName { diff --git a/app/client/src/ce/hooks/datasourceEditorHooks.tsx b/app/client/src/ce/hooks/datasourceEditorHooks.tsx index db6730c1961d..0630e8db57d9 100644 --- a/app/client/src/ce/hooks/datasourceEditorHooks.tsx +++ b/app/client/src/ce/hooks/datasourceEditorHooks.tsx @@ -23,7 +23,7 @@ import { isEnabledForPreviewData } from "utils/editorContextUtils"; import { useFeatureFlag } from "utils/hooks/useFeatureFlag"; import { getCurrentApplication } from "ee/selectors/applicationSelectors"; import { openGeneratePageModal } from "pages/Editor/GeneratePage/store/generatePageActions"; -import { IDE_TYPE, type IDEType } from "ee/entities/IDE/constants"; +import { IDE_TYPE, type IDEType } from "ee/IDE/Interfaces/IDETypes"; export interface HeaderActionProps { datasource: Datasource | ApiDatasourceForm | undefined; diff --git a/app/client/src/ce/navigation/FocusStrategy/AppIDEFocusStrategy.ts b/app/client/src/ce/navigation/FocusStrategy/AppIDEFocusStrategy.ts index ea26fc3bf8d5..a358014d55ff 100644 --- a/app/client/src/ce/navigation/FocusStrategy/AppIDEFocusStrategy.ts +++ b/app/client/src/ce/navigation/FocusStrategy/AppIDEFocusStrategy.ts @@ -8,7 +8,7 @@ import { FocusStoreHierarchy, identifyEntityFromPath, } from "navigation/FocusEntity"; -import { EditorState } from "ee/entities/IDE/constants"; +import { EditorState } from "IDE/enums"; import { ReduxActionTypes } from "ee/constants/ReduxActionConstants"; import { datasourcesEditorURL, diff --git a/app/client/src/ce/navigation/FocusStrategy/index.ts b/app/client/src/ce/navigation/FocusStrategy/index.ts index 024a97de0c96..cbac41820fb2 100644 --- a/app/client/src/ce/navigation/FocusStrategy/index.ts +++ b/app/client/src/ce/navigation/FocusStrategy/index.ts @@ -1,5 +1,4 @@ -import type { IDEType } from "ee/entities/IDE/constants"; -import { IDE_TYPE } from "ee/entities/IDE/constants"; +import { IDE_TYPE, type IDEType } from "ee/IDE/Interfaces/IDETypes"; import { AppIDEFocusStrategy } from "./AppIDEFocusStrategy"; import { NoIDEFocusStrategy } from "./NoIDEFocusStrategy"; diff --git a/app/client/src/ce/pages/Editor/IDE/EditorPane/JS/ListItem.tsx b/app/client/src/ce/pages/Editor/IDE/EditorPane/JS/ListItem.tsx index 0aadd95aa31f..2edc10d68940 100644 --- a/app/client/src/ce/pages/Editor/IDE/EditorPane/JS/ListItem.tsx +++ b/app/client/src/ce/pages/Editor/IDE/EditorPane/JS/ListItem.tsx @@ -1,5 +1,5 @@ import React from "react"; -import type { EntityItem } from "ee/entities/IDE/constants"; +import type { EntityItem } from "ee/IDE/Interfaces/EntityItem"; import { JSEntityItem } from "pages/Editor/IDE/EditorPane/JS/EntityItem/JSEntityItem"; export const JSEntity = (props: { item: EntityItem }) => { diff --git a/app/client/src/ce/pages/Editor/IDE/EditorPane/JS/hooks.tsx b/app/client/src/ce/pages/Editor/IDE/EditorPane/JS/hooks.tsx index 9f71fb80b129..fbc198f2bd61 100644 --- a/app/client/src/ce/pages/Editor/IDE/EditorPane/JS/hooks.tsx +++ b/app/client/src/ce/pages/Editor/IDE/EditorPane/JS/hooks.tsx @@ -7,14 +7,14 @@ import type { GroupedAddOperations } from "ee/pages/Editor/IDE/EditorPane/Query/ import { createMessage, EDITOR_PANE_TEXTS } from "ee/constants/messages"; import { JsFileIconV2 } from "pages/Editor/Explorer/ExplorerIcons"; import { SEARCH_ITEM_TYPES } from "components/editorComponents/GlobalSearch/utils"; -import type { UseRoutes } from "ee/entities/IDE/constants"; +import type { UseRoutes } from "IDE/Interfaces/UseRoutes"; import { ADD_PATH } from "ee/constants/routes/appRoutes"; import history from "utils/history"; import { FocusEntity, identifyEntityFromPath } from "navigation/FocusEntity"; import { useModuleOptions } from "ee/utils/moduleInstanceHelpers"; import { getJSUrl } from "ee/pages/Editor/IDE/EditorPane/JS/utils/getJSUrl"; import { getIDEViewMode } from "selectors/ideSelectors"; -import { EditorViewMode } from "ee/entities/IDE/constants"; +import { EditorViewMode } from "IDE/Interfaces/EditorTypes"; import { setListViewActiveState } from "actions/ideActions"; import { retryPromise } from "utils/AppsmithUtils"; import Skeleton from "widgets/Skeleton"; diff --git a/app/client/src/ce/pages/Editor/IDE/EditorPane/JS/old/ListItem.tsx b/app/client/src/ce/pages/Editor/IDE/EditorPane/JS/old/ListItem.tsx index 65db9a369bd6..d1622c54e160 100644 --- a/app/client/src/ce/pages/Editor/IDE/EditorPane/JS/old/ListItem.tsx +++ b/app/client/src/ce/pages/Editor/IDE/EditorPane/JS/old/ListItem.tsx @@ -1,7 +1,7 @@ import React from "react"; import ExplorerJSCollectionEntity from "pages/Editor/Explorer/JSActions/JSActionEntity"; import { Flex } from "@appsmith/ads"; -import type { EntityItem } from "ee/entities/IDE/constants"; +import type { EntityItem } from "ee/IDE/Interfaces/EntityItem"; export interface JSListItemProps { item: EntityItem; diff --git a/app/client/src/ce/pages/Editor/IDE/EditorPane/JS/utils/getJSContextMenuByIdeType.tsx b/app/client/src/ce/pages/Editor/IDE/EditorPane/JS/utils/getJSContextMenuByIdeType.tsx index d56db7010543..5590b59650a8 100644 --- a/app/client/src/ce/pages/Editor/IDE/EditorPane/JS/utils/getJSContextMenuByIdeType.tsx +++ b/app/client/src/ce/pages/Editor/IDE/EditorPane/JS/utils/getJSContextMenuByIdeType.tsx @@ -1,5 +1,5 @@ import React from "react"; -import { IDE_TYPE, type IDEType } from "ee/entities/IDE/constants"; +import { IDE_TYPE, type IDEType } from "ee/IDE/Interfaces/IDETypes"; import EntityContextMenu from "pages/Editor/IDE/EditorPane/components/EntityContextMenu"; import { AppJSContextMenuItems } from "pages/Editor/IDE/EditorPane/JS/EntityItem/AppJSContextMenuItems"; import type { JSCollection } from "entities/JSCollection"; diff --git a/app/client/src/ce/pages/Editor/IDE/EditorPane/JS/utils/getJSEntityItemUrl.ts b/app/client/src/ce/pages/Editor/IDE/EditorPane/JS/utils/getJSEntityItemUrl.ts index e394f9db47fd..abc76193a611 100644 --- a/app/client/src/ce/pages/Editor/IDE/EditorPane/JS/utils/getJSEntityItemUrl.ts +++ b/app/client/src/ce/pages/Editor/IDE/EditorPane/JS/utils/getJSEntityItemUrl.ts @@ -1,4 +1,4 @@ -import type { EntityItem } from "ee/entities/IDE/constants"; +import type { EntityItem } from "ee/IDE/Interfaces/EntityItem"; import { jsCollectionIdURL } from "ee/RouteBuilder"; export const getJSEntityItemUrl = ( diff --git a/app/client/src/ce/pages/Editor/IDE/EditorPane/JS/utils/getJSUrl.test.ts b/app/client/src/ce/pages/Editor/IDE/EditorPane/JS/utils/getJSUrl.test.ts index d71b88d4f4bd..475734581638 100644 --- a/app/client/src/ce/pages/Editor/IDE/EditorPane/JS/utils/getJSUrl.test.ts +++ b/app/client/src/ce/pages/Editor/IDE/EditorPane/JS/utils/getJSUrl.test.ts @@ -2,7 +2,7 @@ import { getJSUrl } from "./getJSUrl"; import urlBuilder from "ee/entities/URLRedirect/URLAssembly"; import type { FocusEntityInfo } from "navigation/FocusEntity"; import { FocusEntity } from "navigation/FocusEntity"; -import { EditorState } from "ee/entities/IDE/constants"; +import { EditorState } from "IDE/enums"; describe("getJSUrl", () => { urlBuilder.setCurrentBasePageId("0123456789abcdef00000000"); diff --git a/app/client/src/ce/pages/Editor/IDE/EditorPane/Query/ListItem.tsx b/app/client/src/ce/pages/Editor/IDE/EditorPane/Query/ListItem.tsx index 201d728199f3..f877949a889a 100644 --- a/app/client/src/ce/pages/Editor/IDE/EditorPane/Query/ListItem.tsx +++ b/app/client/src/ce/pages/Editor/IDE/EditorPane/Query/ListItem.tsx @@ -1,6 +1,6 @@ import React from "react"; import { QueryEntityItem } from "pages/Editor/IDE/EditorPane/Query/EntityItem/QueryEntityItem"; -import type { EntityItem } from "ee/entities/IDE/constants"; +import type { EntityItem } from "ee/IDE/Interfaces/EntityItem"; export const ActionEntityItem = (props: { item: EntityItem }) => { return <QueryEntityItem {...props} />; diff --git a/app/client/src/ce/pages/Editor/IDE/EditorPane/Query/hooks.tsx b/app/client/src/ce/pages/Editor/IDE/EditorPane/Query/hooks.tsx index d7aacb7d649a..34bcdc29ea8b 100644 --- a/app/client/src/ce/pages/Editor/IDE/EditorPane/Query/hooks.tsx +++ b/app/client/src/ce/pages/Editor/IDE/EditorPane/Query/hooks.tsx @@ -24,7 +24,7 @@ import { BUILDER_PATH_DEPRECATED, } from "ee/constants/routes/appRoutes"; import { SAAS_EDITOR_API_ID_PATH } from "pages/Editor/SaaSEditor/constants"; -import type { UseRoutes } from "ee/entities/IDE/constants"; +import type { UseRoutes } from "IDE/Interfaces/UseRoutes"; import type { AppState } from "ee/reducers"; import keyBy from "lodash/keyBy"; import { getPluginEntityIcon } from "pages/Editor/Explorer/ExplorerIcons"; @@ -35,7 +35,7 @@ import { } from "@appsmith/ads"; import { createAddClassName } from "pages/Editor/IDE/EditorPane/utils"; import { getIDEViewMode } from "selectors/ideSelectors"; -import { EditorViewMode } from "ee/entities/IDE/constants"; +import { EditorViewMode } from "IDE/Interfaces/EditorTypes"; import { setListViewActiveState } from "actions/ideActions"; import { retryPromise } from "utils/AppsmithUtils"; import Skeleton from "widgets/Skeleton"; diff --git a/app/client/src/ce/pages/Editor/IDE/EditorPane/Query/old/ListItem.tsx b/app/client/src/ce/pages/Editor/IDE/EditorPane/Query/old/ListItem.tsx index 90db39393a2a..7a62dffb63ed 100644 --- a/app/client/src/ce/pages/Editor/IDE/EditorPane/Query/old/ListItem.tsx +++ b/app/client/src/ce/pages/Editor/IDE/EditorPane/Query/old/ListItem.tsx @@ -1,6 +1,6 @@ import React from "react"; import ExplorerActionEntity from "pages/Editor/Explorer/Actions/ActionEntity"; -import type { EntityItem } from "ee/entities/IDE/constants"; +import type { EntityItem } from "ee/IDE/Interfaces/EntityItem"; export interface QueryListItemProps { item: EntityItem; diff --git a/app/client/src/ce/pages/Editor/IDE/EditorPane/Query/utils/getQueryContextMenuByIdeType.tsx b/app/client/src/ce/pages/Editor/IDE/EditorPane/Query/utils/getQueryContextMenuByIdeType.tsx index 052d6825d145..179e6a3fb863 100644 --- a/app/client/src/ce/pages/Editor/IDE/EditorPane/Query/utils/getQueryContextMenuByIdeType.tsx +++ b/app/client/src/ce/pages/Editor/IDE/EditorPane/Query/utils/getQueryContextMenuByIdeType.tsx @@ -1,5 +1,5 @@ import React from "react"; -import { IDE_TYPE, type IDEType } from "ee/entities/IDE/constants"; +import { IDE_TYPE, type IDEType } from "ee/IDE/Interfaces/IDETypes"; import type { Action } from "entities/Action"; import { AppQueryContextMenuItems } from "pages/Editor/IDE/EditorPane/Query/EntityItem/AppQueryContextMenuItems"; import EntityContextMenu from "pages/Editor/IDE/EditorPane/components/EntityContextMenu"; diff --git a/app/client/src/ce/pages/Editor/IDE/EditorPane/Query/utils/getQueryEntityItemUrl.ts b/app/client/src/ce/pages/Editor/IDE/EditorPane/Query/utils/getQueryEntityItemUrl.ts index b8b7ae4112de..6437a897e639 100644 --- a/app/client/src/ce/pages/Editor/IDE/EditorPane/Query/utils/getQueryEntityItemUrl.ts +++ b/app/client/src/ce/pages/Editor/IDE/EditorPane/Query/utils/getQueryEntityItemUrl.ts @@ -1,4 +1,4 @@ -import type { EntityItem } from "ee/entities/IDE/constants"; +import type { EntityItem } from "ee/IDE/Interfaces/EntityItem"; import { getActionConfig } from "pages/Editor/Explorer/Actions/helpers"; export const getQueryEntityItemUrl = ( diff --git a/app/client/src/ce/pages/Editor/IDE/EditorPane/Query/utils/getQueryUrl.test.ts b/app/client/src/ce/pages/Editor/IDE/EditorPane/Query/utils/getQueryUrl.test.ts index aa5fee5925da..a835868204e4 100644 --- a/app/client/src/ce/pages/Editor/IDE/EditorPane/Query/utils/getQueryUrl.test.ts +++ b/app/client/src/ce/pages/Editor/IDE/EditorPane/Query/utils/getQueryUrl.test.ts @@ -1,7 +1,7 @@ import { getQueryUrl } from "./getQueryUrl"; import type { FocusEntityInfo } from "navigation/FocusEntity"; import { FocusEntity } from "navigation/FocusEntity"; -import { EditorState } from "ee/entities/IDE/constants"; +import { EditorState } from "IDE/enums"; import { PluginPackageName } from "entities/Plugin"; import urlBuilder from "ee/entities/URLRedirect/URLAssembly"; diff --git a/app/client/src/ce/pages/Editor/IDE/constants/SidebarButtons.ts b/app/client/src/ce/pages/Editor/IDE/constants/SidebarButtons.ts new file mode 100644 index 000000000000..51fbd654fe32 --- /dev/null +++ b/app/client/src/ce/pages/Editor/IDE/constants/SidebarButtons.ts @@ -0,0 +1,26 @@ +import { + DataButton, + EditorButton, + LibrariesButton, + SettingsButton, +} from "IDE/constants/SidebarButtons"; +import { Condition, type IDESidebarButton } from "@appsmith/ads"; +import { + createMessage, + EMPTY_DATASOURCE_TOOLTIP_SIDEBUTTON, +} from "ee/constants/messages"; + +const DataButtonWithWarning: IDESidebarButton = { + ...DataButton("datasource"), + condition: Condition.Warn, + tooltip: createMessage(EMPTY_DATASOURCE_TOOLTIP_SIDEBUTTON), +}; + +const DataButtonWithoutWarning = DataButton("datasource"); + +export const BottomButtons = (datasourcesExist: boolean) => [ + datasourcesExist ? DataButtonWithoutWarning : DataButtonWithWarning, + LibrariesButton("libraries"), + SettingsButton("settings"), +]; +export const TopButtons = [EditorButton("editor")]; diff --git a/app/client/src/ce/pages/Editor/gitSync/useReconnectModalData.ts b/app/client/src/ce/pages/Editor/gitSync/useReconnectModalData.ts index b8c012ee97d1..f2be964e6dbd 100644 --- a/app/client/src/ce/pages/Editor/gitSync/useReconnectModalData.ts +++ b/app/client/src/ce/pages/Editor/gitSync/useReconnectModalData.ts @@ -1,4 +1,4 @@ -import { IDE_TYPE } from "ee/entities/IDE/constants"; +import { IDE_TYPE } from "ee/IDE/Interfaces/IDETypes"; import { builderURL } from "ee/RouteBuilder"; import { RECONNECT_MISSING_DATASOURCE_CREDENTIALS_DESCRIPTION, diff --git a/app/client/src/ce/sagas/DatasourcesSagas.ts b/app/client/src/ce/sagas/DatasourcesSagas.ts index 30529b22f3a0..a3230c23cff5 100644 --- a/app/client/src/ce/sagas/DatasourcesSagas.ts +++ b/app/client/src/ce/sagas/DatasourcesSagas.ts @@ -87,7 +87,7 @@ import { } from "ee/constants/forms"; import type { ActionDataState } from "ee/reducers/entityReducers/actionsReducer"; import { setIdeEditorViewMode } from "../../actions/ideActions"; -import { EditorViewMode } from "ee/entities/IDE/constants"; +import { EditorViewMode } from "IDE/Interfaces/EditorTypes"; import { getIsAnvilEnabledInCurrentApplication } from "../../layoutSystems/anvil/integrations/selectors"; import { createActionRequestSaga } from "../../sagas/ActionSagas"; import { validateResponse } from "../../sagas/ErrorSagas"; diff --git a/app/client/src/ce/sagas/JSActionSagas.ts b/app/client/src/ce/sagas/JSActionSagas.ts index ada296297b95..5302d4c06c36 100644 --- a/app/client/src/ce/sagas/JSActionSagas.ts +++ b/app/client/src/ce/sagas/JSActionSagas.ts @@ -72,7 +72,7 @@ import { getWidgets } from "sagas/selectors"; import FocusRetention from "sagas/FocusRetentionSaga"; import { handleJSEntityRedirect } from "sagas/IDESaga"; import { getIDETypeByUrl } from "ee/entities/IDE/utils"; -import { IDE_TYPE } from "ee/entities/IDE/constants"; +import { IDE_TYPE } from "ee/IDE/Interfaces/IDETypes"; import { CreateNewActionKey } from "ee/entities/Engine/actionHelpers"; import { getAllActionTestPayloads } from "utils/storage"; import { convertToBasePageIdSelector } from "selectors/pageListSelectors"; diff --git a/app/client/src/ce/sagas/NavigationSagas.ts b/app/client/src/ce/sagas/NavigationSagas.ts index 88d84e26a4b6..ea8b37fc8d6c 100644 --- a/app/client/src/ce/sagas/NavigationSagas.ts +++ b/app/client/src/ce/sagas/NavigationSagas.ts @@ -21,8 +21,8 @@ import { flushErrors } from "actions/errorActions"; import type { NavigationMethod } from "utils/history"; import UsagePulse from "usagePulse"; import { getIDETypeByUrl } from "ee/entities/IDE/utils"; -import type { EditorViewMode } from "ee/entities/IDE/constants"; -import { IDE_TYPE } from "ee/entities/IDE/constants"; +import type { EditorViewMode } from "IDE/Interfaces/EditorTypes"; +import { IDE_TYPE } from "ee/IDE/Interfaces/IDETypes"; import { updateIDETabsOnRouteChangeSaga } from "sagas/IDESaga"; import { getIDEViewMode } from "selectors/ideSelectors"; diff --git a/app/client/src/ce/selectors/appIDESelectors.test.ts b/app/client/src/ce/selectors/appIDESelectors.test.ts index 43425a1490b6..e2fce1e4c4d6 100644 --- a/app/client/src/ce/selectors/appIDESelectors.test.ts +++ b/app/client/src/ce/selectors/appIDESelectors.test.ts @@ -1,4 +1,4 @@ -import type { EntityItem } from "ee/entities/IDE/constants"; +import type { EntityItem } from "ee/IDE/Interfaces/EntityItem"; import { groupAndSortEntitySegmentList } from "./appIDESelectors"; import { PluginType } from "entities/Plugin"; diff --git a/app/client/src/ce/selectors/appIDESelectors.ts b/app/client/src/ce/selectors/appIDESelectors.ts index 16fcca2e5e5f..73ada5de31ae 100644 --- a/app/client/src/ce/selectors/appIDESelectors.ts +++ b/app/client/src/ce/selectors/appIDESelectors.ts @@ -1,6 +1,6 @@ import { groupBy, keyBy, sortBy } from "lodash"; import { createSelector } from "reselect"; -import type { EntityItem } from "ee/entities/IDE/constants"; +import type { EntityItem } from "ee/IDE/Interfaces/EntityItem"; import { getJSSegmentItems, getQuerySegmentItems, diff --git a/app/client/src/ce/selectors/entitiesSelector.ts b/app/client/src/ce/selectors/entitiesSelector.ts index e49dcd57d530..582e3ac5fd13 100644 --- a/app/client/src/ce/selectors/entitiesSelector.ts +++ b/app/client/src/ce/selectors/entitiesSelector.ts @@ -57,12 +57,12 @@ import { import { MAX_DATASOURCE_SUGGESTIONS } from "constants/DatasourceEditorConstants"; import type { CreateNewActionKeyInterface } from "ee/entities/Engine/actionHelpers"; import { getNextEntityName } from "utils/AppsmithUtils"; -import { - EditorEntityTab, - type EntityItem, - type GenericEntityItem, - type IDEType, -} from "ee/entities/IDE/constants"; +import { EditorEntityTab } from "IDE/Interfaces/EditorTypes"; +import type { IDEType } from "ee/IDE/Interfaces/IDETypes"; +import type { + EntityItem, + GenericEntityItem, +} from "ee/IDE/Interfaces/EntityItem"; import { ActionUrlIcon, JsFileIconV2, diff --git a/app/client/src/ce/utils/BusinessFeatures/permissionPageHelpers.tsx b/app/client/src/ce/utils/BusinessFeatures/permissionPageHelpers.tsx index e882d308b893..14ba9b5d8607 100644 --- a/app/client/src/ce/utils/BusinessFeatures/permissionPageHelpers.tsx +++ b/app/client/src/ce/utils/BusinessFeatures/permissionPageHelpers.tsx @@ -43,7 +43,7 @@ import { hasExecuteActionPermission as hasExecuteActionPermission_EE } from "ee/ import { hasAuditLogsReadPermission as hasAuditLogsReadPermission_CE } from "ce/utils/permissionHelpers"; import { hasAuditLogsReadPermission as hasAuditLogsReadPermission_EE } from "ee/utils/permissionHelpers"; -import { IDE_TYPE, type IDEType } from "ee/entities/IDE/constants"; +import { IDE_TYPE, type IDEType } from "ee/IDE/Interfaces/IDETypes"; export const getHasCreateWorkspacePermission = ( isEnabled: boolean, diff --git a/app/client/src/ce/utils/lintRulesHelpers.ts b/app/client/src/ce/utils/lintRulesHelpers.ts index fe0c07471d15..f0aa216747a3 100644 --- a/app/client/src/ce/utils/lintRulesHelpers.ts +++ b/app/client/src/ce/utils/lintRulesHelpers.ts @@ -1,4 +1,4 @@ -import type { IDEType } from "ee/entities/IDE/constants"; +import type { IDEType } from "ee/IDE/Interfaces/IDETypes"; interface ContextType { ideType: IDEType; diff --git a/app/client/src/components/editorComponents/ApiResponseView.test.tsx b/app/client/src/components/editorComponents/ApiResponseView.test.tsx index 9ad68895e52f..d3a142c304de 100644 --- a/app/client/src/components/editorComponents/ApiResponseView.test.tsx +++ b/app/client/src/components/editorComponents/ApiResponseView.test.tsx @@ -7,7 +7,7 @@ import { ThemeProvider } from "styled-components"; import { unitTestBaseMockStore } from "layoutSystems/common/dropTarget/unitTestUtils"; import { lightTheme } from "selectors/themeSelectors"; import { BrowserRouter as Router } from "react-router-dom"; -import { EditorViewMode } from "ee/entities/IDE/constants"; +import { EditorViewMode } from "IDE/Interfaces/EditorTypes"; import "@testing-library/jest-dom/extend-expect"; import { APIFactory } from "test/factories/Actions/API"; import { noop } from "lodash"; diff --git a/app/client/src/components/editorComponents/ApiResponseView.tsx b/app/client/src/components/editorComponents/ApiResponseView.tsx index be02637831d4..8f359b7355d9 100644 --- a/app/client/src/components/editorComponents/ApiResponseView.tsx +++ b/app/client/src/components/editorComponents/ApiResponseView.tsx @@ -24,7 +24,7 @@ import { setPluginActionEditorDebuggerState, } from "PluginActionEditor/store"; import { getIDEViewMode } from "selectors/ideSelectors"; -import { EditorViewMode } from "ee/entities/IDE/constants"; +import { EditorViewMode } from "IDE/Interfaces/EditorTypes"; import useDebuggerTriggerClick from "./Debugger/hooks/useDebuggerTriggerClick"; import { IDEBottomView, ViewHideBehaviour } from "IDE"; import { Response } from "PluginActionEditor/components/PluginActionResponse/components/Response"; diff --git a/app/client/src/components/editorComponents/Debugger/DebuggerTabs.tsx b/app/client/src/components/editorComponents/Debugger/DebuggerTabs.tsx index 514423108f63..e172214f4e4f 100644 --- a/app/client/src/components/editorComponents/Debugger/DebuggerTabs.tsx +++ b/app/client/src/components/editorComponents/Debugger/DebuggerTabs.tsx @@ -26,7 +26,7 @@ import { IDEBottomView, ViewHideBehaviour, ViewDisplayMode } from "IDE"; import { StateInspector } from "./StateInspector"; import { getIDETypeByUrl } from "ee/entities/IDE/utils"; import { useLocation } from "react-router"; -import { IDE_TYPE } from "ee/entities/IDE/constants"; +import { IDE_TYPE } from "ee/IDE/Interfaces/IDETypes"; function DebuggerTabs() { const dispatch = useDispatch(); diff --git a/app/client/src/components/editorComponents/Debugger/StateInspector/hooks/useStateInspectorItems.ts b/app/client/src/components/editorComponents/Debugger/StateInspector/hooks/useStateInspectorItems.ts index 906984a16467..e9f8ff8dcd7a 100644 --- a/app/client/src/components/editorComponents/Debugger/StateInspector/hooks/useStateInspectorItems.ts +++ b/app/client/src/components/editorComponents/Debugger/StateInspector/hooks/useStateInspectorItems.ts @@ -6,7 +6,7 @@ import { useGetJSItemsForStateInspector } from "./useGetJSItemsForStateInspector import { useGetUIItemsForStateInspector } from "./useGetUIItemsForStateInspector"; import type { GroupedItems } from "../types"; import { enhanceItemForListItem } from "../utils"; -import type { GenericEntityItem } from "ee/entities/IDE/constants"; +import type { GenericEntityItem } from "ee/IDE/Interfaces/EntityItem"; export const useStateInspectorItems: () => [ GenericEntityItem | undefined, diff --git a/app/client/src/components/editorComponents/Debugger/hooks/useDebuggerTriggerClick.ts b/app/client/src/components/editorComponents/Debugger/hooks/useDebuggerTriggerClick.ts index d901f3702d53..2ebfbdf20dd4 100644 --- a/app/client/src/components/editorComponents/Debugger/hooks/useDebuggerTriggerClick.ts +++ b/app/client/src/components/editorComponents/Debugger/hooks/useDebuggerTriggerClick.ts @@ -13,7 +13,7 @@ import { import { getCanvasDebuggerState } from "selectors/debuggerSelectors"; import { getIDEViewMode } from "selectors/ideSelectors"; import { useDispatch, useSelector } from "react-redux"; -import { EditorViewMode } from "ee/entities/IDE/constants"; +import { EditorViewMode } from "IDE/Interfaces/EditorTypes"; import type { ReduxAction } from "actions/ReduxActionTypes"; import type { CanvasDebuggerState } from "reducers/uiReducers/debuggerReducer"; import type { AppState } from "ee/reducers"; diff --git a/app/client/src/components/editorComponents/JSResponseView.test.tsx b/app/client/src/components/editorComponents/JSResponseView.test.tsx index 74217d6ae49a..656c536cdee4 100644 --- a/app/client/src/components/editorComponents/JSResponseView.test.tsx +++ b/app/client/src/components/editorComponents/JSResponseView.test.tsx @@ -8,7 +8,7 @@ import { ThemeProvider } from "styled-components"; import { unitTestBaseMockStore } from "layoutSystems/common/dropTarget/unitTestUtils"; import { lightTheme } from "selectors/themeSelectors"; import { BrowserRouter as Router } from "react-router-dom"; -import { EditorViewMode } from "ee/entities/IDE/constants"; +import { EditorViewMode } from "IDE/Interfaces/EditorTypes"; import type { JSCollectionData } from "ee/reducers/entityReducers/jsActionsReducer"; import { PluginType } from "entities/Plugin"; import "@testing-library/jest-dom/extend-expect"; diff --git a/app/client/src/components/editorComponents/JSResponseView.tsx b/app/client/src/components/editorComponents/JSResponseView.tsx index 185d45408f9b..738112b34c0a 100644 --- a/app/client/src/components/editorComponents/JSResponseView.tsx +++ b/app/client/src/components/editorComponents/JSResponseView.tsx @@ -32,7 +32,8 @@ import { import { getJsPaneDebuggerState } from "selectors/jsPaneSelectors"; import { setJsPaneDebuggerState } from "actions/jsPaneActions"; import { getIDEViewMode } from "selectors/ideSelectors"; -import { EditorViewMode, IDE_TYPE } from "ee/entities/IDE/constants"; +import { EditorViewMode } from "IDE/Interfaces/EditorTypes"; +import { IDE_TYPE } from "ee/IDE/Interfaces/IDETypes"; import ErrorLogs from "./Debugger/Errors"; import { isBrowserExecutionAllowed } from "ee/utils/actionExecutionUtils"; import JSRemoteExecutionView from "ee/components/JSRemoteExecutionView"; diff --git a/app/client/src/ee/IDE/Interfaces/EntityItem.ts b/app/client/src/ee/IDE/Interfaces/EntityItem.ts new file mode 100644 index 000000000000..64d8614b5d1d --- /dev/null +++ b/app/client/src/ee/IDE/Interfaces/EntityItem.ts @@ -0,0 +1 @@ +export * from "ce/IDE/Interfaces/EntityItem"; diff --git a/app/client/src/ee/IDE/Interfaces/IDETypes.ts b/app/client/src/ee/IDE/Interfaces/IDETypes.ts new file mode 100644 index 000000000000..1e0b445528af --- /dev/null +++ b/app/client/src/ee/IDE/Interfaces/IDETypes.ts @@ -0,0 +1 @@ +export * from "ce/IDE/Interfaces/IDETypes"; diff --git a/app/client/src/ee/IDE/constants/routes.ts b/app/client/src/ee/IDE/constants/routes.ts new file mode 100644 index 000000000000..56054c42df2b --- /dev/null +++ b/app/client/src/ee/IDE/constants/routes.ts @@ -0,0 +1 @@ +export * from "ce/IDE/constants/routes"; diff --git a/app/client/src/ee/entities/IDE/constants.ts b/app/client/src/ee/entities/IDE/constants.ts deleted file mode 100644 index bad2f3dc193a..000000000000 --- a/app/client/src/ee/entities/IDE/constants.ts +++ /dev/null @@ -1 +0,0 @@ -export * from "ce/entities/IDE/constants"; diff --git a/app/client/src/ee/pages/Editor/IDE/constants/SidebarButtons.ts b/app/client/src/ee/pages/Editor/IDE/constants/SidebarButtons.ts new file mode 100644 index 000000000000..56e6a6d8fa98 --- /dev/null +++ b/app/client/src/ee/pages/Editor/IDE/constants/SidebarButtons.ts @@ -0,0 +1 @@ +export * from "ce/pages/Editor/IDE/constants/SidebarButtons"; diff --git a/app/client/src/layoutSystems/common/dropTarget/OnBoarding/OnBoarding.test.tsx b/app/client/src/layoutSystems/common/dropTarget/OnBoarding/OnBoarding.test.tsx index cb09b911afca..b07105cd2196 100644 --- a/app/client/src/layoutSystems/common/dropTarget/OnBoarding/OnBoarding.test.tsx +++ b/app/client/src/layoutSystems/common/dropTarget/OnBoarding/OnBoarding.test.tsx @@ -1,5 +1,6 @@ import { EMPTY_CANVAS_HINTS, createMessage } from "ee/constants/messages"; -import { EditorEntityTab, EditorState } from "ee/entities/IDE/constants"; +import { EditorState } from "IDE/enums"; +import { EditorEntityTab } from "IDE/Interfaces/EditorTypes"; import "@testing-library/jest-dom"; import { render, screen } from "@testing-library/react"; import "jest-styled-components"; diff --git a/app/client/src/navigation/FocusEntity.test.ts b/app/client/src/navigation/FocusEntity.test.ts index ee286285dc6d..69aa11d2e081 100644 --- a/app/client/src/navigation/FocusEntity.test.ts +++ b/app/client/src/navigation/FocusEntity.test.ts @@ -1,6 +1,6 @@ import type { FocusEntityInfo } from "navigation/FocusEntity"; import { FocusEntity, identifyEntityFromPath } from "navigation/FocusEntity"; -import { EditorState } from "ee/entities/IDE/constants"; +import { EditorState } from "IDE/enums"; interface TestCase { path: string; diff --git a/app/client/src/navigation/FocusEntity.ts b/app/client/src/navigation/FocusEntity.ts index 7b50baa57cb0..351ba0599a82 100644 --- a/app/client/src/navigation/FocusEntity.ts +++ b/app/client/src/navigation/FocusEntity.ts @@ -2,8 +2,9 @@ import type { match } from "react-router"; import { matchPath } from "react-router"; import { ADD_PATH } from "constants/routes"; import { TEMP_DATASOURCE_ID } from "constants/Datasource"; -import type { IDEType } from "ee/entities/IDE/constants"; -import { EditorState, EntityPaths } from "ee/entities/IDE/constants"; +import type { IDEType } from "ee/IDE/Interfaces/IDETypes"; +import { EditorState } from "IDE/enums"; +import { EntityPaths } from "ee/IDE/constants/routes"; import { getBaseUrlsForIDEType, getIDETypeByUrl } from "ee/entities/IDE/utils"; import { memoize } from "lodash"; import { MODULE_TYPE } from "ee/constants/ModuleConstants"; diff --git a/app/client/src/pages/Editor/CanvasLayoutConversion/hooks/useShowSnapShotBanner.ts b/app/client/src/pages/Editor/CanvasLayoutConversion/hooks/useShowSnapShotBanner.ts index ed09ba647cc4..59d12e965eba 100644 --- a/app/client/src/pages/Editor/CanvasLayoutConversion/hooks/useShowSnapShotBanner.ts +++ b/app/client/src/pages/Editor/CanvasLayoutConversion/hooks/useShowSnapShotBanner.ts @@ -1,5 +1,5 @@ import { FEATURE_FLAG } from "ee/entities/FeatureFlag"; -import { EditorState } from "ee/entities/IDE/constants"; +import { EditorState } from "IDE/enums"; import { getReadableSnapShotDetails } from "layoutSystems/autolayout/utils/AutoLayoutUtils"; import { useCurrentAppState } from "pages/Editor/IDE/hooks/useCurrentAppState"; import { useSelector } from "react-redux"; diff --git a/app/client/src/pages/Editor/DataSourceEditor/Debugger.test.tsx b/app/client/src/pages/Editor/DataSourceEditor/Debugger.test.tsx index 4a39ac05904d..5429ab626dc1 100644 --- a/app/client/src/pages/Editor/DataSourceEditor/Debugger.test.tsx +++ b/app/client/src/pages/Editor/DataSourceEditor/Debugger.test.tsx @@ -6,7 +6,7 @@ import { ThemeProvider } from "styled-components"; import { unitTestBaseMockStore } from "layoutSystems/common/dropTarget/unitTestUtils"; import { lightTheme } from "selectors/themeSelectors"; import { BrowserRouter as Router } from "react-router-dom"; -import { EditorViewMode } from "ee/entities/IDE/constants"; +import { EditorViewMode } from "IDE/Interfaces/EditorTypes"; import "@testing-library/jest-dom/extend-expect"; import Debugger from "./Debugger"; diff --git a/app/client/src/pages/Editor/Explorer/Entity/EntityProperties.tsx b/app/client/src/pages/Editor/Explorer/Entity/EntityProperties.tsx index 21846b52a95d..06293abfd904 100644 --- a/app/client/src/pages/Editor/Explorer/Entity/EntityProperties.tsx +++ b/app/client/src/pages/Editor/Explorer/Entity/EntityProperties.tsx @@ -14,7 +14,7 @@ import { getEntityProperties } from "ee/pages/Editor/Explorer/Entity/getEntityPr import store from "store"; import { ENTITY_TYPE } from "entities/DataTree/dataTreeFactory"; import { getIDEViewMode } from "selectors/ideSelectors"; -import { EditorViewMode } from "ee/entities/IDE/constants"; +import { EditorViewMode } from "IDE/Interfaces/EditorTypes"; import { DEFAULT_EXPLORER_PANE_WIDTH } from "constants/AppConstants"; import { BOTTOM_BAR_HEIGHT } from "components/BottomBar/constants"; diff --git a/app/client/src/pages/Editor/IDE/EditorPane/Editor.tsx b/app/client/src/pages/Editor/IDE/EditorPane/Editor.tsx index 1664df4ec4f0..9e5c1724c56c 100644 --- a/app/client/src/pages/Editor/IDE/EditorPane/Editor.tsx +++ b/app/client/src/pages/Editor/IDE/EditorPane/Editor.tsx @@ -10,7 +10,7 @@ import { JSEditorPane } from "./JS"; import { QueryEditor } from "./Query"; import EditorTabs from "../EditorTabs"; import { useCurrentEditorState } from "../hooks"; -import { EditorEntityTab } from "ee/entities/IDE/constants"; +import { EditorEntityTab } from "IDE/Interfaces/EditorTypes"; import styled from "styled-components"; const Container = styled(Flex)` diff --git a/app/client/src/pages/Editor/IDE/EditorPane/Explorer.tsx b/app/client/src/pages/Editor/IDE/EditorPane/Explorer.tsx index 8a4910e50818..0113d35dca14 100644 --- a/app/client/src/pages/Editor/IDE/EditorPane/Explorer.tsx +++ b/app/client/src/pages/Editor/IDE/EditorPane/Explorer.tsx @@ -18,7 +18,7 @@ import { import SegmentSwitcher from "./components/SegmentSwitcher"; import { useSelector } from "react-redux"; import { getIDEViewMode } from "selectors/ideSelectors"; -import { EditorEntityTab, EditorViewMode } from "ee/entities/IDE/constants"; +import { EditorEntityTab, EditorViewMode } from "IDE/Interfaces/EditorTypes"; import { DEFAULT_EXPLORER_PANE_WIDTH } from "constants/AppConstants"; import { useCurrentEditorState } from "../hooks"; diff --git a/app/client/src/pages/Editor/IDE/EditorPane/JS/Add.tsx b/app/client/src/pages/Editor/IDE/EditorPane/JS/Add.tsx index a15f59e6af92..65b1cf5531ff 100644 --- a/app/client/src/pages/Editor/IDE/EditorPane/JS/Add.tsx +++ b/app/client/src/pages/Editor/IDE/EditorPane/JS/Add.tsx @@ -19,7 +19,7 @@ import { createAddClassName } from "../utils"; import { FocusEntity } from "navigation/FocusEntity"; import { getIDEViewMode } from "selectors/ideSelectors"; import type { FlexProps } from "@appsmith/ads"; -import { EditorViewMode } from "ee/entities/IDE/constants"; +import { EditorViewMode } from "IDE/Interfaces/EditorTypes"; import { filterEntityGroupsBySearchTerm } from "IDE/utils"; import { DEFAULT_GROUP_LIST_SIZE } from "../../constants"; diff --git a/app/client/src/pages/Editor/IDE/EditorPane/JS/EntityItem/JSEntityItem.tsx b/app/client/src/pages/Editor/IDE/EditorPane/JS/EntityItem/JSEntityItem.tsx index 9a341d91324a..07f2ae1e8c56 100644 --- a/app/client/src/pages/Editor/IDE/EditorPane/JS/EntityItem/JSEntityItem.tsx +++ b/app/client/src/pages/Editor/IDE/EditorPane/JS/EntityItem/JSEntityItem.tsx @@ -1,6 +1,5 @@ import React, { useCallback, useMemo } from "react"; import { EntityItem } from "@appsmith/ads"; -import type { EntityItem as EntityItemProps } from "ee/entities/IDE/constants"; import type { AppState } from "ee/reducers"; import { getJsCollectionByBaseId } from "ee/selectors/entitiesSelector"; import { useDispatch, useSelector } from "react-redux"; @@ -20,6 +19,7 @@ import type { JSCollection } from "entities/JSCollection"; import { jsCollectionIdURL } from "ee/RouteBuilder"; import { JsFileIconV2 } from "pages/Editor/Explorer/ExplorerIcons"; import { getJSContextMenuByIdeType } from "ee/pages/Editor/IDE/EditorPane/JS/utils/getJSContextMenuByIdeType"; +import type { EntityItem as EntityItemProps } from "ee/IDE/Interfaces/EntityItem"; export const JSEntityItem = ({ item }: { item: EntityItemProps }) => { const jsAction = useSelector((state: AppState) => diff --git a/app/client/src/pages/Editor/IDE/EditorPane/JS/Explorer.tsx b/app/client/src/pages/Editor/IDE/EditorPane/JS/Explorer.tsx index cd2fe71fd280..f568223ac4e1 100644 --- a/app/client/src/pages/Editor/IDE/EditorPane/JS/Explorer.tsx +++ b/app/client/src/pages/Editor/IDE/EditorPane/JS/Explorer.tsx @@ -2,7 +2,7 @@ import React from "react"; import List from "./List"; import { useSelector } from "react-redux"; import { getIDEViewMode } from "selectors/ideSelectors"; -import { EditorViewMode } from "ee/entities/IDE/constants"; +import { EditorViewMode } from "IDE/Interfaces/EditorTypes"; const JSExplorer = () => { const ideViewMode = useSelector(getIDEViewMode); diff --git a/app/client/src/pages/Editor/IDE/EditorPane/JS/JSRender.test.tsx b/app/client/src/pages/Editor/IDE/EditorPane/JS/JSRender.test.tsx index 5e1b2cf1d6e7..dac2b145eff5 100644 --- a/app/client/src/pages/Editor/IDE/EditorPane/JS/JSRender.test.tsx +++ b/app/client/src/pages/Editor/IDE/EditorPane/JS/JSRender.test.tsx @@ -5,7 +5,7 @@ import IDE from "pages/Editor/IDE/index"; import React from "react"; import { createMessage, EDITOR_PANE_TEXTS } from "ee/constants/messages"; import { getIDETestState } from "test/factories/AppIDEFactoryUtils"; -import { EditorEntityTab, EditorViewMode } from "ee/entities/IDE/constants"; +import { EditorEntityTab, EditorViewMode } from "IDE/Interfaces/EditorTypes"; import { PageFactory } from "test/factories/PageFactory"; import { JSObjectFactory } from "test/factories/Actions/JSObject"; diff --git a/app/client/src/pages/Editor/IDE/EditorPane/JS/List.tsx b/app/client/src/pages/Editor/IDE/EditorPane/JS/List.tsx index 992afea302bd..8be64a119f55 100644 --- a/app/client/src/pages/Editor/IDE/EditorPane/JS/List.tsx +++ b/app/client/src/pages/Editor/IDE/EditorPane/JS/List.tsx @@ -24,8 +24,8 @@ import { useLocation } from "react-router"; import { getIDETypeByUrl } from "ee/entities/IDE/utils"; import { useParentEntityInfo } from "ee/IDE/hooks/useParentEntityInfo"; import { useCreateActionsPermissions } from "ee/entities/IDE/hooks/useCreateActionsPermissions"; -import type { EntityItem } from "ee/entities/IDE/constants"; import { JSEntity } from "ee/pages/Editor/IDE/EditorPane/JS/ListItem"; +import type { EntityItem } from "ee/IDE/Interfaces/EntityItem"; const JSContainer = styled(Flex)` & .t--entity-item { diff --git a/app/client/src/pages/Editor/IDE/EditorPane/Query/Add.tsx b/app/client/src/pages/Editor/IDE/EditorPane/Query/Add.tsx index a19e3c3f50cc..36fef60ce41e 100644 --- a/app/client/src/pages/Editor/IDE/EditorPane/Query/Add.tsx +++ b/app/client/src/pages/Editor/IDE/EditorPane/Query/Add.tsx @@ -16,7 +16,7 @@ import { } from "ee/pages/Editor/IDE/EditorPane/Query/hooks"; import { useSelector } from "react-redux"; import { getIDEViewMode } from "selectors/ideSelectors"; -import { EditorViewMode } from "ee/entities/IDE/constants"; +import { EditorViewMode } from "IDE/Interfaces/EditorTypes"; import { filterEntityGroupsBySearchTerm } from "IDE/utils"; import { DEFAULT_GROUP_LIST_SIZE } from "../../constants"; diff --git a/app/client/src/pages/Editor/IDE/EditorPane/Query/EntityItem/QueryEntityItem.tsx b/app/client/src/pages/Editor/IDE/EditorPane/Query/EntityItem/QueryEntityItem.tsx index f74f53d02d28..9b045f6be8b8 100644 --- a/app/client/src/pages/Editor/IDE/EditorPane/Query/EntityItem/QueryEntityItem.tsx +++ b/app/client/src/pages/Editor/IDE/EditorPane/Query/EntityItem/QueryEntityItem.tsx @@ -1,6 +1,5 @@ import React, { useCallback, useMemo } from "react"; import { EntityItem } from "@appsmith/ads"; -import type { EntityItem as EntityItemProps } from "ee/entities/IDE/constants"; import type { AppState } from "ee/reducers"; import { getActionByBaseId, @@ -26,6 +25,7 @@ import { useActiveActionBaseId } from "ee/pages/Editor/Explorer/hooks"; import { PluginType } from "entities/Plugin"; import { useParentEntityInfo } from "ee/IDE/hooks/useParentEntityInfo"; import { getQueryContextMenuByIdeType } from "ee/pages/Editor/IDE/EditorPane/Query/utils/getQueryContextMenuByIdeType"; +import type { EntityItem as EntityItemProps } from "ee/IDE/Interfaces/EntityItem"; export const QueryEntityItem = ({ item }: { item: EntityItemProps }) => { const action = useSelector((state: AppState) => diff --git a/app/client/src/pages/Editor/IDE/EditorPane/Query/Explorer.tsx b/app/client/src/pages/Editor/IDE/EditorPane/Query/Explorer.tsx index 587da0cd88ad..64720ed10089 100644 --- a/app/client/src/pages/Editor/IDE/EditorPane/Query/Explorer.tsx +++ b/app/client/src/pages/Editor/IDE/EditorPane/Query/Explorer.tsx @@ -4,7 +4,7 @@ import styled from "styled-components"; import { Flex } from "@appsmith/ads"; import { useSelector } from "react-redux"; import { getIDEViewMode } from "selectors/ideSelectors"; -import { EditorViewMode } from "ee/entities/IDE/constants"; +import { EditorViewMode } from "IDE/Interfaces/EditorTypes"; const QueriesContainer = styled(Flex)` & .t--entity-item { diff --git a/app/client/src/pages/Editor/IDE/EditorPane/Query/List.tsx b/app/client/src/pages/Editor/IDE/EditorPane/Query/List.tsx index a919ad44ad75..66683f461bc7 100644 --- a/app/client/src/pages/Editor/IDE/EditorPane/Query/List.tsx +++ b/app/client/src/pages/Editor/IDE/EditorPane/Query/List.tsx @@ -20,13 +20,13 @@ import { getShowWorkflowFeature } from "ee/selectors/workflowSelectors"; import { BlankState } from "./BlankState"; import { EDITOR_PANE_TEXTS, createMessage } from "ee/constants/messages"; import { filterEntityGroupsBySearchTerm } from "IDE/utils"; -import type { EntityItem } from "ee/entities/IDE/constants"; import { ActionEntityItem } from "ee/pages/Editor/IDE/EditorPane/Query/ListItem"; import { useLocation } from "react-router"; import { getIDETypeByUrl } from "ee/entities/IDE/utils"; import { useParentEntityInfo } from "ee/IDE/hooks/useParentEntityInfo"; import { useCreateActionsPermissions } from "ee/entities/IDE/hooks/useCreateActionsPermissions"; import { objectKeys } from "@appsmith/utils"; +import type { EntityItem } from "ee/IDE/Interfaces/EntityItem"; const ListQuery = () => { const [searchTerm, setSearchTerm] = useState(""); diff --git a/app/client/src/pages/Editor/IDE/EditorPane/Query/QueryRender.test.tsx b/app/client/src/pages/Editor/IDE/EditorPane/Query/QueryRender.test.tsx index 97ac93702354..66292912e196 100644 --- a/app/client/src/pages/Editor/IDE/EditorPane/Query/QueryRender.test.tsx +++ b/app/client/src/pages/Editor/IDE/EditorPane/Query/QueryRender.test.tsx @@ -4,7 +4,7 @@ import { render } from "test/testUtils"; import IDE from "pages/Editor/IDE/index"; import { createMessage, EDITOR_PANE_TEXTS } from "ee/constants/messages"; import { BUILDER_PATH } from "ee/constants/routes/appRoutes"; -import { EditorEntityTab, EditorViewMode } from "ee/entities/IDE/constants"; +import { EditorEntityTab, EditorViewMode } from "IDE/Interfaces/EditorTypes"; import { APIFactory } from "test/factories/Actions/API"; import { PostgresFactory } from "test/factories/Actions/Postgres"; import { sagasToRunForTests } from "test/sagas"; diff --git a/app/client/src/pages/Editor/IDE/EditorPane/UI/UIRender.test.tsx b/app/client/src/pages/Editor/IDE/EditorPane/UI/UIRender.test.tsx index ebea1b837310..015ffa44c55a 100644 --- a/app/client/src/pages/Editor/IDE/EditorPane/UI/UIRender.test.tsx +++ b/app/client/src/pages/Editor/IDE/EditorPane/UI/UIRender.test.tsx @@ -11,7 +11,7 @@ import { buildChildren, widgetCanvasFactory, } from "test/factories/WidgetFactoryUtils"; -import { EditorViewMode } from "ee/entities/IDE/constants"; +import { EditorViewMode } from "IDE/Interfaces/EditorTypes"; const pageId = "0123456789abcdef00000000"; diff --git a/app/client/src/pages/Editor/IDE/EditorPane/components/SegmentSwitcher.tsx b/app/client/src/pages/Editor/IDE/EditorPane/components/SegmentSwitcher.tsx index fa0df5e105c7..e8c48fcde922 100644 --- a/app/client/src/pages/Editor/IDE/EditorPane/components/SegmentSwitcher.tsx +++ b/app/client/src/pages/Editor/IDE/EditorPane/components/SegmentSwitcher.tsx @@ -1,6 +1,6 @@ import React, { useMemo } from "react"; import { createMessage, EDITOR_PANE_TEXTS } from "ee/constants/messages"; -import { EditorEntityTab } from "ee/entities/IDE/constants"; +import { EditorEntityTab } from "IDE/Interfaces/EditorTypes"; import { useCurrentEditorState, useSegmentNavigation } from "../../hooks"; import { EditorSegments } from "@appsmith/ads"; diff --git a/app/client/src/pages/Editor/IDE/EditorPane/index.tsx b/app/client/src/pages/Editor/IDE/EditorPane/index.tsx index 2c6c166a3d04..a5363bda9f52 100644 --- a/app/client/src/pages/Editor/IDE/EditorPane/index.tsx +++ b/app/client/src/pages/Editor/IDE/EditorPane/index.tsx @@ -4,7 +4,7 @@ import EditorPaneExplorer from "./Explorer"; import Editor from "./Editor"; import { useSelector } from "react-redux"; import { getIDEViewMode } from "selectors/ideSelectors"; -import { EditorViewMode } from "ee/entities/IDE/constants"; +import { EditorViewMode } from "IDE/Interfaces/EditorTypes"; import EntityProperties from "pages/Editor/Explorer/Entity/EntityProperties"; const EditorPane = () => { diff --git a/app/client/src/pages/Editor/IDE/EditorTabs/AddTab.tsx b/app/client/src/pages/Editor/IDE/EditorTabs/AddTab.tsx index 48581c848f7e..2ff7276bb464 100644 --- a/app/client/src/pages/Editor/IDE/EditorTabs/AddTab.tsx +++ b/app/client/src/pages/Editor/IDE/EditorTabs/AddTab.tsx @@ -6,7 +6,7 @@ import { DismissibleTab, Text } from "@appsmith/ads"; import { EditorEntityTab, EditorEntityTabState, -} from "ee/entities/IDE/constants"; +} from "IDE/Interfaces/EditorTypes"; import { useCurrentEditorState } from "../hooks"; diff --git a/app/client/src/pages/Editor/IDE/EditorTabs/EditableTab.tsx b/app/client/src/pages/Editor/IDE/EditorTabs/EditableTab.tsx index d523b0a6f84f..3515400dffc0 100644 --- a/app/client/src/pages/Editor/IDE/EditorTabs/EditableTab.tsx +++ b/app/client/src/pages/Editor/IDE/EditorTabs/EditableTab.tsx @@ -4,7 +4,7 @@ import { useEventCallback } from "usehooks-ts"; import { EditableDismissibleTab } from "@appsmith/ads"; -import { type EntityItem } from "ee/entities/IDE/constants"; +import { type EntityItem } from "ee/IDE/Interfaces/EntityItem"; import { FEATURE_FLAG } from "ee/entities/FeatureFlag"; import { getIsSavingEntityName } from "ee/selectors/entitiesSelector"; diff --git a/app/client/src/pages/Editor/IDE/EditorTabs/Editortabs.test.tsx b/app/client/src/pages/Editor/IDE/EditorTabs/Editortabs.test.tsx index a59dc63aecb6..1ea582539b14 100644 --- a/app/client/src/pages/Editor/IDE/EditorTabs/Editortabs.test.tsx +++ b/app/client/src/pages/Editor/IDE/EditorTabs/Editortabs.test.tsx @@ -2,7 +2,7 @@ import React from "react"; import { fireEvent, render } from "test/testUtils"; import EditorTabs from "."; import { getIDETestState } from "test/factories/AppIDEFactoryUtils"; -import { EditorEntityTab, EditorViewMode } from "ee/entities/IDE/constants"; +import { EditorEntityTab, EditorViewMode } from "IDE/Interfaces/EditorTypes"; import { Route } from "react-router-dom"; import { BUILDER_PATH } from "ee/constants/routes/appRoutes"; import "@testing-library/jest-dom"; diff --git a/app/client/src/pages/Editor/IDE/EditorTabs/List.tsx b/app/client/src/pages/Editor/IDE/EditorTabs/List.tsx index bab1f62c42c4..0960d23cf99d 100644 --- a/app/client/src/pages/Editor/IDE/EditorTabs/List.tsx +++ b/app/client/src/pages/Editor/IDE/EditorTabs/List.tsx @@ -3,7 +3,7 @@ import styled from "styled-components"; import { Flex } from "@appsmith/ads"; import { useCurrentEditorState } from "../hooks"; -import { EditorEntityTab } from "ee/entities/IDE/constants"; +import { EditorEntityTab } from "IDE/Interfaces/EditorTypes"; import ListQuery from "../EditorPane/Query/List"; import ListJSObjects from "../EditorPane/JS/List"; diff --git a/app/client/src/pages/Editor/IDE/EditorTabs/ScreenModeToggle.tsx b/app/client/src/pages/Editor/IDE/EditorTabs/ScreenModeToggle.tsx index aa5b78a10ac8..e51bb3df56c4 100644 --- a/app/client/src/pages/Editor/IDE/EditorTabs/ScreenModeToggle.tsx +++ b/app/client/src/pages/Editor/IDE/EditorTabs/ScreenModeToggle.tsx @@ -3,7 +3,7 @@ import { useDispatch, useSelector } from "react-redux"; import { Button, Tooltip } from "@appsmith/ads"; import { getIDEViewMode } from "selectors/ideSelectors"; -import { EditorViewMode } from "ee/entities/IDE/constants"; +import { EditorViewMode } from "IDE/Interfaces/EditorTypes"; import AnalyticsUtil from "ee/utils/AnalyticsUtil"; import { MAXIMIZE_BUTTON_TOOLTIP, diff --git a/app/client/src/pages/Editor/IDE/EditorTabs/constants.ts b/app/client/src/pages/Editor/IDE/EditorTabs/constants.ts index 97d228b0fe04..04e87813d3bd 100644 --- a/app/client/src/pages/Editor/IDE/EditorTabs/constants.ts +++ b/app/client/src/pages/Editor/IDE/EditorTabs/constants.ts @@ -1,5 +1,4 @@ -import type { EntityItem } from "ee/entities/IDE/constants"; -import { EditorEntityTab } from "ee/entities/IDE/constants"; +import { EditorEntityTab } from "IDE/Interfaces/EditorTypes"; import type { AppState } from "ee/reducers"; import { selectJSSegmentEditorTabs, @@ -11,6 +10,7 @@ import { } from "ee/selectors/entitiesSelector"; import { getJSEntityItemUrl } from "ee/pages/Editor/IDE/EditorPane/JS/utils/getJSEntityItemUrl"; import { getQueryEntityItemUrl } from "ee/pages/Editor/IDE/EditorPane/Query/utils/getQueryEntityItemUrl"; +import type { EntityItem } from "ee/IDE/Interfaces/EntityItem"; export const TabSelectors: Record< EditorEntityTab, diff --git a/app/client/src/pages/Editor/IDE/EditorTabs/index.tsx b/app/client/src/pages/Editor/IDE/EditorTabs/index.tsx index 71878f335edd..29bc483fb961 100644 --- a/app/client/src/pages/Editor/IDE/EditorTabs/index.tsx +++ b/app/client/src/pages/Editor/IDE/EditorTabs/index.tsx @@ -10,12 +10,12 @@ import { } from "@appsmith/ads"; import { getIDEViewMode, getListViewActiveState } from "selectors/ideSelectors"; -import type { EntityItem } from "ee/entities/IDE/constants"; +import type { EntityItem } from "ee/IDE/Interfaces/EntityItem"; import { EditorEntityTab, EditorEntityTabState, EditorViewMode, -} from "ee/entities/IDE/constants"; +} from "IDE/Interfaces/EditorTypes"; import { useIsJSAddLoading } from "ee/pages/Editor/IDE/EditorPane/JS/hooks"; import { identifyEntityFromPath } from "navigation/FocusEntity"; diff --git a/app/client/src/pages/Editor/IDE/Header/index.tsx b/app/client/src/pages/Editor/IDE/Header/index.tsx index 66b1b86cf722..0d3962f6b55c 100644 --- a/app/client/src/pages/Editor/IDE/Header/index.tsx +++ b/app/client/src/pages/Editor/IDE/Header/index.tsx @@ -57,7 +57,7 @@ import { viewerURL } from "ee/RouteBuilder"; import HelpBar from "components/editorComponents/GlobalSearch/HelpBar"; import { EditorTitle } from "./EditorTitle"; import { useCurrentAppState } from "../hooks/useCurrentAppState"; -import { EditorState } from "ee/entities/IDE/constants"; +import { EditorState } from "IDE/enums"; import { EditorSaveIndicator } from "pages/Editor/EditorSaveIndicator"; import { APPLICATIONS_URL } from "constants/routes"; import { useNavigationMenuData } from "../../EditorName/useNavigationMenuData"; diff --git a/app/client/src/pages/Editor/IDE/Layout/hooks/useEditorStateLeftPaneWidth.ts b/app/client/src/pages/Editor/IDE/Layout/hooks/useEditorStateLeftPaneWidth.ts index fe8dfd7e8a6a..97801344b8b4 100644 --- a/app/client/src/pages/Editor/IDE/Layout/hooks/useEditorStateLeftPaneWidth.ts +++ b/app/client/src/pages/Editor/IDE/Layout/hooks/useEditorStateLeftPaneWidth.ts @@ -8,7 +8,7 @@ import { import { useSelector } from "react-redux"; import { getIDEViewMode } from "selectors/ideSelectors"; import { getPropertyPaneWidth } from "selectors/propertyPaneSelectors"; -import { EditorEntityTab, EditorViewMode } from "ee/entities/IDE/constants"; +import { EditorEntityTab, EditorViewMode } from "IDE/Interfaces/EditorTypes"; import { useCurrentEditorState } from "../../hooks"; import { previewModeSelector } from "selectors/editorSelectors"; import { useGitProtectedMode } from "pages/Editor/gitSync/hooks/modHooks"; diff --git a/app/client/src/pages/Editor/IDE/Layout/hooks/useGridLayoutTemplate.ts b/app/client/src/pages/Editor/IDE/Layout/hooks/useGridLayoutTemplate.ts index bf97ce71790b..c58548156633 100644 --- a/app/client/src/pages/Editor/IDE/Layout/hooks/useGridLayoutTemplate.ts +++ b/app/client/src/pages/Editor/IDE/Layout/hooks/useGridLayoutTemplate.ts @@ -7,11 +7,8 @@ import { useCurrentAppState } from "../../hooks/useCurrentAppState"; import { getPropertyPaneWidth } from "selectors/propertyPaneSelectors"; import { previewModeSelector } from "selectors/editorSelectors"; import { getIDEViewMode } from "selectors/ideSelectors"; -import { - EditorEntityTab, - EditorState, - EditorViewMode, -} from "ee/entities/IDE/constants"; +import { EditorState } from "IDE/enums"; +import { EditorEntityTab, EditorViewMode } from "IDE/Interfaces/EditorTypes"; import { APP_SETTINGS_PANE_WIDTH, APP_SIDEBAR_WIDTH, diff --git a/app/client/src/pages/Editor/IDE/LeftPane/DataSidePane.test.tsx b/app/client/src/pages/Editor/IDE/LeftPane/DataSidePane.test.tsx index 6d040c9a2fc5..65a75ae14534 100644 --- a/app/client/src/pages/Editor/IDE/LeftPane/DataSidePane.test.tsx +++ b/app/client/src/pages/Editor/IDE/LeftPane/DataSidePane.test.tsx @@ -8,7 +8,7 @@ import { PostgresFactory } from "test/factories/Actions/Postgres"; import type { AppState } from "ee/reducers"; import { render } from "test/testUtils"; import { getDatasourceUsageCountForApp } from "ee/selectors/entitiesSelector"; -import { IDE_TYPE } from "ee/entities/IDE/constants"; +import { IDE_TYPE } from "ee/IDE/Interfaces/IDETypes"; const productsDS = datasourceFactory().build({ name: "Products", diff --git a/app/client/src/pages/Editor/IDE/LeftPane/index.tsx b/app/client/src/pages/Editor/IDE/LeftPane/index.tsx index a8b152005e73..2c855e8e3d79 100644 --- a/app/client/src/pages/Editor/IDE/LeftPane/index.tsx +++ b/app/client/src/pages/Editor/IDE/LeftPane/index.tsx @@ -17,7 +17,7 @@ import DataSidePane from "./DataSidePane"; import EditorPane from "../EditorPane"; import LibrarySidePane from "ee/pages/Editor/IDE/LeftPane/LibrarySidePane"; import { getDatasourceUsageCountForApp } from "ee/selectors/entitiesSelector"; -import { IDE_TYPE } from "ee/entities/IDE/constants"; +import { IDE_TYPE } from "ee/IDE/Interfaces/IDETypes"; export const LeftPaneContainer = styled.div` height: 100%; diff --git a/app/client/src/pages/Editor/IDE/Sidebar.tsx b/app/client/src/pages/Editor/IDE/Sidebar.tsx index 8e8fb55a03f0..eb711ddb35e3 100644 --- a/app/client/src/pages/Editor/IDE/Sidebar.tsx +++ b/app/client/src/pages/Editor/IDE/Sidebar.tsx @@ -6,17 +6,12 @@ import history, { NavigationMethod } from "utils/history"; import { useCurrentAppState } from "./hooks/useCurrentAppState"; import { getCurrentWorkspaceId } from "ee/selectors/selectedWorkspaceSelectors"; import { fetchWorkspace } from "ee/actions/workspaceActions"; -import { IDESidebar, Condition } from "@appsmith/ads"; +import { IDESidebar } from "@appsmith/ads"; +import { getDatasources } from "ee/selectors/entitiesSelector"; import { BottomButtons, - EditorState, TopButtons, -} from "ee/entities/IDE/constants"; -import { getDatasources } from "ee/selectors/entitiesSelector"; -import { - createMessage, - EMPTY_DATASOURCE_TOOLTIP_SIDEBUTTON, -} from "ee/constants/messages"; +} from "ee/pages/Editor/IDE/constants/SidebarButtons"; function Sidebar() { const dispatch = useDispatch(); @@ -28,19 +23,7 @@ function Sidebar() { // Updates the bottom button config based on datasource existence const bottomButtons = React.useMemo(() => { - return datasourcesExist - ? BottomButtons - : BottomButtons.map((button) => { - if (button.state === EditorState.DATA) { - return { - ...button, - condition: Condition.Warn, - tooltip: createMessage(EMPTY_DATASOURCE_TOOLTIP_SIDEBUTTON), - }; - } - - return button; - }); + return BottomButtons(datasourcesExist); }, [datasourcesExist]); useEffect(() => { diff --git a/app/client/src/pages/Editor/IDE/hooks.ts b/app/client/src/pages/Editor/IDE/hooks.ts index d48defeba1aa..5c525622eb39 100644 --- a/app/client/src/pages/Editor/IDE/hooks.ts +++ b/app/client/src/pages/Editor/IDE/hooks.ts @@ -1,9 +1,8 @@ import { useCallback, useEffect, useState } from "react"; -import type { EntityItem } from "ee/entities/IDE/constants"; import { EditorEntityTab, EditorEntityTabState, -} from "ee/entities/IDE/constants"; +} from "IDE/Interfaces/EditorTypes"; import { useLocation } from "react-router"; import { FocusEntity, identifyEntityFromPath } from "navigation/FocusEntity"; import { useDispatch, useSelector } from "react-redux"; @@ -32,6 +31,7 @@ import { useBoolean } from "usehooks-ts"; import { isWidgetActionConnectionPresent } from "selectors/onboardingSelectors"; import localStorage, { LOCAL_STORAGE_KEYS } from "utils/localStorage"; import { getIDETypeByUrl } from "ee/entities/IDE/utils"; +import type { EntityItem } from "ee/IDE/Interfaces/EntityItem"; export const useCurrentEditorState = () => { const [selectedSegment, setSelectedSegment] = useState<EditorEntityTab>( diff --git a/app/client/src/pages/Editor/IDE/hooks/useCurrentAppState.ts b/app/client/src/pages/Editor/IDE/hooks/useCurrentAppState.ts index db1061cdc149..9d36e085644a 100644 --- a/app/client/src/pages/Editor/IDE/hooks/useCurrentAppState.ts +++ b/app/client/src/pages/Editor/IDE/hooks/useCurrentAppState.ts @@ -1,5 +1,5 @@ import { useEffect, useState } from "react"; -import { EditorState } from "ee/entities/IDE/constants"; +import { EditorState } from "IDE/enums"; import { useLocation } from "react-router"; import { identifyEntityFromPath } from "navigation/FocusEntity"; diff --git a/app/client/src/pages/Editor/IntegrationEditor/APIOrSaasPlugins.tsx b/app/client/src/pages/Editor/IntegrationEditor/APIOrSaasPlugins.tsx index ad05e166cb1b..8d47abbd36da 100644 --- a/app/client/src/pages/Editor/IntegrationEditor/APIOrSaasPlugins.tsx +++ b/app/client/src/pages/Editor/IntegrationEditor/APIOrSaasPlugins.tsx @@ -48,7 +48,7 @@ import { } from "./PremiumDatasources/Constants"; import { getDatasourcesLoadingState } from "selectors/datasourceSelectors"; import { getIDETypeByUrl } from "ee/entities/IDE/utils"; -import type { IDEType } from "ee/entities/IDE/constants"; +import type { IDEType } from "ee/IDE/Interfaces/IDETypes"; import { filterSearch } from "./util"; import { selectFeatureFlagCheck } from "ee/selectors/featureFlagsSelectors"; import { FEATURE_FLAG } from "ee/entities/FeatureFlag"; diff --git a/app/client/src/pages/Editor/IntegrationEditor/DBOrMostPopularPlugins.tsx b/app/client/src/pages/Editor/IntegrationEditor/DBOrMostPopularPlugins.tsx index 590a04f8d6c3..83a17d71485e 100644 --- a/app/client/src/pages/Editor/IntegrationEditor/DBOrMostPopularPlugins.tsx +++ b/app/client/src/pages/Editor/IntegrationEditor/DBOrMostPopularPlugins.tsx @@ -51,7 +51,7 @@ import { PluginType, } from "entities/Plugin"; import { getIDETypeByUrl } from "ee/entities/IDE/utils"; -import type { IDEType } from "ee/entities/IDE/constants"; +import type { IDEType } from "ee/IDE/Interfaces/IDETypes"; import { filterSearch } from "./util"; // This function remove the given key from queryParams and return string diff --git a/app/client/src/pages/Editor/QueryEditor/QueryDebuggerTabs.tsx b/app/client/src/pages/Editor/QueryEditor/QueryDebuggerTabs.tsx index 6481edfc4d25..19afb1f4a8ef 100644 --- a/app/client/src/pages/Editor/QueryEditor/QueryDebuggerTabs.tsx +++ b/app/client/src/pages/Editor/QueryEditor/QueryDebuggerTabs.tsx @@ -31,7 +31,7 @@ import { } from "PluginActionEditor/store"; import { actionResponseDisplayDataFormats } from "../utils"; import { getIDEViewMode } from "selectors/ideSelectors"; -import { EditorViewMode } from "ee/entities/IDE/constants"; +import { EditorViewMode } from "IDE/Interfaces/EditorTypes"; import { IDEBottomView, ViewHideBehaviour } from "IDE"; import { EditorTheme } from "components/editorComponents/CodeEditor/EditorConfig"; diff --git a/app/client/src/pages/Editor/WidgetsEditor/WidgetEditorContainer.tsx b/app/client/src/pages/Editor/WidgetsEditor/WidgetEditorContainer.tsx index cad110052fd0..16e668ae3b50 100644 --- a/app/client/src/pages/Editor/WidgetsEditor/WidgetEditorContainer.tsx +++ b/app/client/src/pages/Editor/WidgetsEditor/WidgetEditorContainer.tsx @@ -5,7 +5,7 @@ import classNames from "classnames"; import { useCurrentAppState } from "pages/Editor/IDE/hooks/useCurrentAppState"; import { useSelector } from "react-redux"; import { getIsAppSettingsPaneWithNavigationTabOpen } from "selectors/appSettingsPaneSelectors"; -import { EditorState } from "ee/entities/IDE/constants"; +import { EditorState } from "IDE/enums"; import { RenderModes } from "constants/WidgetConstants"; import styled from "styled-components"; import { IDE_HEADER_HEIGHT } from "@appsmith/ads"; diff --git a/app/client/src/pages/Editor/WidgetsEditor/components/CodeModeTooltip.tsx b/app/client/src/pages/Editor/WidgetsEditor/components/CodeModeTooltip.tsx index c39b9b648343..62c12f752fe8 100644 --- a/app/client/src/pages/Editor/WidgetsEditor/components/CodeModeTooltip.tsx +++ b/app/client/src/pages/Editor/WidgetsEditor/components/CodeModeTooltip.tsx @@ -6,7 +6,7 @@ import { getWidgetSelectionBlock } from "selectors/ui"; import { retrieveCodeWidgetNavigationUsed } from "utils/storage"; import { CANVAS_VIEW_MODE_TOOLTIP, createMessage } from "ee/constants/messages"; import { useCurrentAppState } from "pages/Editor/IDE/hooks/useCurrentAppState"; -import { EditorState } from "ee/entities/IDE/constants"; +import { EditorState } from "IDE/enums"; /** * CodeModeTooltip diff --git a/app/client/src/pages/Editor/WidgetsEditor/components/NavigationAdjustedPageViewer.tsx b/app/client/src/pages/Editor/WidgetsEditor/components/NavigationAdjustedPageViewer.tsx index 6eb0f1ff10a6..c9e079795ad7 100644 --- a/app/client/src/pages/Editor/WidgetsEditor/components/NavigationAdjustedPageViewer.tsx +++ b/app/client/src/pages/Editor/WidgetsEditor/components/NavigationAdjustedPageViewer.tsx @@ -1,6 +1,6 @@ import type { ReactNode } from "react"; import React from "react"; -import { EditorState } from "ee/entities/IDE/constants"; +import { EditorState } from "IDE/enums"; import { useCurrentAppState } from "pages/Editor/IDE/hooks/useCurrentAppState"; import { getIsAppSettingsPaneWithNavigationTabOpen } from "selectors/appSettingsPaneSelectors"; import { useSelector } from "react-redux"; diff --git a/app/client/src/pages/Editor/WidgetsEditor/components/NavigationPreview.tsx b/app/client/src/pages/Editor/WidgetsEditor/components/NavigationPreview.tsx index 8f2aa0e23c24..ff8ce07de230 100644 --- a/app/client/src/pages/Editor/WidgetsEditor/components/NavigationPreview.tsx +++ b/app/client/src/pages/Editor/WidgetsEditor/components/NavigationPreview.tsx @@ -5,7 +5,7 @@ import { useSelector } from "react-redux"; import { selectCombinedPreviewMode } from "selectors/gitModSelectors"; import { Navigation } from "pages/AppViewer/Navigation"; import { useCurrentAppState } from "pages/Editor/IDE/hooks/useCurrentAppState"; -import { EditorState } from "ee/entities/IDE/constants"; +import { EditorState } from "IDE/enums"; import { getIsAppSettingsPaneWithNavigationTabOpen } from "selectors/appSettingsPaneSelectors"; /** diff --git a/app/client/src/pages/Editor/WidgetsEditor/components/WidgetEditorNavigation.tsx b/app/client/src/pages/Editor/WidgetsEditor/components/WidgetEditorNavigation.tsx index d7b7d2869271..2876bfcfce71 100644 --- a/app/client/src/pages/Editor/WidgetsEditor/components/WidgetEditorNavigation.tsx +++ b/app/client/src/pages/Editor/WidgetsEditor/components/WidgetEditorNavigation.tsx @@ -1,6 +1,6 @@ import React, { forwardRef, useEffect, useRef, useState } from "react"; import NavigationPreview from "./NavigationPreview"; -import { EditorState } from "ee/entities/IDE/constants"; +import { EditorState } from "IDE/enums"; import { useCurrentAppState } from "pages/Editor/IDE/hooks/useCurrentAppState"; import { getAppSettingsPaneContext, diff --git a/app/client/src/pages/Editor/utils.tsx b/app/client/src/pages/Editor/utils.tsx index f9b42347b8d8..02fcd76893ac 100644 --- a/app/client/src/pages/Editor/utils.tsx +++ b/app/client/src/pages/Editor/utils.tsx @@ -35,9 +35,9 @@ import { Icon } from "@appsmith/ads"; import { EditorEntityTab, EditorEntityTabState, - EditorState, EditorViewMode, -} from "ee/entities/IDE/constants"; +} from "IDE/Interfaces/EditorTypes"; +import { EditorState } from "IDE/enums"; import { FocusEntity } from "navigation/FocusEntity"; import { objectKeys } from "@appsmith/utils"; diff --git a/app/client/src/plugins/Linting/constants.ts b/app/client/src/plugins/Linting/constants.ts index 63acf26cfbd6..c7a7f9955eaa 100644 --- a/app/client/src/plugins/Linting/constants.ts +++ b/app/client/src/plugins/Linting/constants.ts @@ -3,7 +3,8 @@ import type { LintOptions } from "jshint"; import isEntityFunction from "./utils/isEntityFunction"; import { noFloatingPromisesLintRule } from "./customRules/no-floating-promises"; import { getLintRulesBasedOnContext } from "ee/utils/lintRulesHelpers"; -import type { IDEType } from "ee/entities/IDE/constants"; + +import type { IDEType } from "ee/IDE/Interfaces/IDETypes"; export enum LINTER_TYPE { "JSHINT" = "JSHint", diff --git a/app/client/src/plugins/Linting/utils/getLintingErrors.ts b/app/client/src/plugins/Linting/utils/getLintingErrors.ts index bfbc61d13f02..850d54415e5e 100644 --- a/app/client/src/plugins/Linting/utils/getLintingErrors.ts +++ b/app/client/src/plugins/Linting/utils/getLintingErrors.ts @@ -45,8 +45,8 @@ import { Linter } from "eslint-linter-browserify"; import { ENTITY_TYPE } from "entities/DataTree/dataTreeFactory"; import type { DataTreeEntity } from "entities/DataTree/dataTreeTypes"; import type { AppsmithEntity } from "ee/entities/DataTree/types"; -import { IDE_TYPE, type IDEType } from "ee/entities/IDE/constants"; import { getIDETypeByUrl } from "ee/entities/IDE/utils"; +import { IDE_TYPE, type IDEType } from "ee/IDE/Interfaces/IDETypes"; const EvaluationScriptPositions: Record<string, Position> = {}; diff --git a/app/client/src/reducers/uiReducers/ideReducer.ts b/app/client/src/reducers/uiReducers/ideReducer.ts index 19f1456d0a40..69624a49c4f9 100644 --- a/app/client/src/reducers/uiReducers/ideReducer.ts +++ b/app/client/src/reducers/uiReducers/ideReducer.ts @@ -1,7 +1,7 @@ import { createImmerReducer } from "utils/ReducerUtils"; import type { ReduxAction } from "actions/ReduxActionTypes"; import { ReduxActionTypes } from "ee/constants/ReduxActionConstants"; -import { EditorEntityTab, EditorViewMode } from "ee/entities/IDE/constants"; +import { EditorEntityTab, EditorViewMode } from "IDE/Interfaces/EditorTypes"; import { klona } from "klona"; import { get, remove, set } from "lodash"; diff --git a/app/client/src/sagas/ActionSagas.ts b/app/client/src/sagas/ActionSagas.ts index 274faa639cc6..b6ea24423b9e 100644 --- a/app/client/src/sagas/ActionSagas.ts +++ b/app/client/src/sagas/ActionSagas.ts @@ -58,7 +58,7 @@ import { } from "ee/constants/ReduxActionConstants"; import { ENTITY_TYPE } from "ee/entities/AppsmithConsole/utils"; import { CreateNewActionKey } from "ee/entities/Engine/actionHelpers"; -import { EditorViewMode, IDE_TYPE } from "ee/entities/IDE/constants"; +import { EditorViewMode } from "IDE/Interfaces/EditorTypes"; import { getIDETypeByUrl } from "ee/entities/IDE/utils"; import type { ActionData } from "ee/reducers/entityReducers/actionsReducer"; import { @@ -143,6 +143,7 @@ import { } from "./helper"; import { handleQueryEntityRedirect } from "./IDESaga"; import type { EvaluationReduxAction } from "actions/EvaluationReduxActionTypes"; +import { IDE_TYPE } from "ee/IDE/Interfaces/IDETypes"; export const DEFAULT_PREFIX = { QUERY: "Query", diff --git a/app/client/src/sagas/AnalyticsSaga.ts b/app/client/src/sagas/AnalyticsSaga.ts index 87477f4407a1..25ada435aa70 100644 --- a/app/client/src/sagas/AnalyticsSaga.ts +++ b/app/client/src/sagas/AnalyticsSaga.ts @@ -12,7 +12,7 @@ import log from "loglevel"; import { all, put, select, takeEvery } from "redux-saga/effects"; import { getIdeCanvasSideBySideHoverState } from "selectors/ideSelectors"; -import { EditorViewMode } from "ee/entities/IDE/constants"; +import { EditorViewMode } from "IDE/Interfaces/EditorTypes"; import { recordAnalyticsForSideBySideNavigation, recordAnalyticsForSideBySideWidgetHover, diff --git a/app/client/src/sagas/DebuggerSagas.ts b/app/client/src/sagas/DebuggerSagas.ts index dfa17ffe92a7..d91842067bd9 100644 --- a/app/client/src/sagas/DebuggerSagas.ts +++ b/app/client/src/sagas/DebuggerSagas.ts @@ -57,7 +57,7 @@ import { } from "ee/sagas/helpers"; import { identifyEntityFromPath } from "../navigation/FocusEntity"; import { getIDEViewMode } from "../selectors/ideSelectors"; -import type { EditorViewMode } from "ee/entities/IDE/constants"; +import type { EditorViewMode } from "IDE/Interfaces/EditorTypes"; import { getDebuggerPaneConfig } from "../components/editorComponents/Debugger/hooks/useDebuggerTriggerClick"; import { DEBUGGER_TAB_KEYS } from "../components/editorComponents/Debugger/constants"; diff --git a/app/client/src/sagas/FocusRetentionSaga.ts b/app/client/src/sagas/FocusRetentionSaga.ts index 19e3b3c45b23..5a2470347937 100644 --- a/app/client/src/sagas/FocusRetentionSaga.ts +++ b/app/client/src/sagas/FocusRetentionSaga.ts @@ -20,7 +20,7 @@ import { getAction, getPlugin } from "ee/selectors/entitiesSelector"; import type { Plugin } from "entities/Plugin"; import { getIDETypeByUrl } from "ee/entities/IDE/utils"; import { getIDEFocusStrategy } from "ee/navigation/FocusStrategy"; -import { IDE_TYPE } from "ee/entities/IDE/constants"; +import { IDE_TYPE } from "ee/IDE/Interfaces/IDETypes"; import { selectGitApplicationCurrentBranch } from "selectors/gitModSelectors"; export interface FocusPath { diff --git a/app/client/src/sagas/IDESaga.tsx b/app/client/src/sagas/IDESaga.tsx index e6adeafa8e3d..ced295c54dab 100644 --- a/app/client/src/sagas/IDESaga.tsx +++ b/app/client/src/sagas/IDESaga.tsx @@ -14,13 +14,13 @@ import { queryAddURL, queryListURL, } from "ee/RouteBuilder"; -import type { EntityItem } from "ee/entities/IDE/constants"; +import type { EntityItem } from "ee/IDE/Interfaces/EntityItem"; import { getQueryEntityItemUrl } from "ee/pages/Editor/IDE/EditorPane/Query/utils/getQueryEntityItemUrl"; import { getJSEntityItemUrl } from "ee/pages/Editor/IDE/EditorPane/JS/utils/getJSEntityItemUrl"; import log from "loglevel"; import type { ReduxAction } from "actions/ReduxActionTypes"; import { ReduxActionTypes } from "ee/constants/ReduxActionConstants"; -import type { EditorViewMode } from "ee/entities/IDE/constants"; +import type { EditorViewMode } from "IDE/Interfaces/EditorTypes"; import { retrieveIDEViewMode, storeIDEViewMode } from "utils/storage"; import { selectJSSegmentEditorTabs, diff --git a/app/client/src/sagas/JSPaneSagas.ts b/app/client/src/sagas/JSPaneSagas.ts index 5e49d43b0808..2434dff1b86c 100644 --- a/app/client/src/sagas/JSPaneSagas.ts +++ b/app/client/src/sagas/JSPaneSagas.ts @@ -96,7 +96,7 @@ import { getJsPaneDebuggerState } from "selectors/jsPaneSelectors"; import { logMainJsActionExecution } from "ee/utils/analyticsHelpers"; import { getFocusablePropertyPaneField } from "selectors/propertyPaneSelectors"; import { setIdeEditorViewMode } from "actions/ideActions"; -import { EditorViewMode } from "ee/entities/IDE/constants"; +import { EditorViewMode } from "IDE/Interfaces/EditorTypes"; import { updateJSCollectionAPICall } from "ee/sagas/ApiCallerSagas"; import { convertToBasePageIdSelector } from "selectors/pageListSelectors"; diff --git a/app/client/src/sagas/getNextEntityAfterRemove.test.ts b/app/client/src/sagas/getNextEntityAfterRemove.test.ts index daf7565eb4e4..77ad93bfd417 100644 --- a/app/client/src/sagas/getNextEntityAfterRemove.test.ts +++ b/app/client/src/sagas/getNextEntityAfterRemove.test.ts @@ -1,8 +1,9 @@ -import { EditorState, type EntityItem } from "ee/entities/IDE/constants"; +import { EditorState } from "IDE/enums"; import { PluginType } from "entities/Plugin"; import * as FocusEntityObj from "navigation/FocusEntity"; import { RedirectAction, getNextEntityAfterRemove } from "./IDESaga"; import { FocusEntity } from "navigation/FocusEntity"; +import type { EntityItem } from "ee/IDE/Interfaces/EntityItem"; describe("getNextEntityAfterRemove function", () => { const items: EntityItem[] = [ diff --git a/app/client/src/selectors/ideSelectors.tsx b/app/client/src/selectors/ideSelectors.tsx index f3c0499779b0..18f926994f42 100644 --- a/app/client/src/selectors/ideSelectors.tsx +++ b/app/client/src/selectors/ideSelectors.tsx @@ -1,7 +1,7 @@ import { createSelector } from "reselect"; import type { AppState } from "ee/reducers"; import { getPageActions } from "ee/selectors/entitiesSelector"; -import { EditorEntityTab } from "ee/entities/IDE/constants"; +import { EditorEntityTab } from "IDE/Interfaces/EditorTypes"; import { getCurrentBasePageId } from "./editorSelectors"; import type { ParentEntityIDETabs } from "../reducers/uiReducers/ideReducer"; import { get } from "lodash"; diff --git a/app/client/src/utils/hooks/useHoverToFocusWidget.ts b/app/client/src/utils/hooks/useHoverToFocusWidget.ts index a6cf7962de9a..176192674a8c 100644 --- a/app/client/src/utils/hooks/useHoverToFocusWidget.ts +++ b/app/client/src/utils/hooks/useHoverToFocusWidget.ts @@ -6,7 +6,7 @@ import { selectCombinedPreviewMode } from "selectors/gitModSelectors"; import type { AppState } from "ee/reducers"; import type React from "react"; import { useCurrentAppState } from "pages/Editor/IDE/hooks/useCurrentAppState"; -import { EditorState } from "ee/entities/IDE/constants"; +import { EditorState } from "IDE/enums"; export const useHoverToFocusWidget = ( widgetId: string, diff --git a/app/client/src/utils/storage.ts b/app/client/src/utils/storage.ts index 8893261bb190..eefd22ee09ff 100644 --- a/app/client/src/utils/storage.ts +++ b/app/client/src/utils/storage.ts @@ -3,7 +3,7 @@ import moment from "moment"; import localforage from "localforage"; import { isNumber } from "lodash"; import { EditorModes } from "components/editorComponents/CodeEditor/EditorConfig"; -import type { EditorViewMode } from "ee/entities/IDE/constants"; +import type { EditorViewMode } from "IDE/Interfaces/EditorTypes"; import type { OverriddenFeatureFlags } from "./hooks/useFeatureFlagOverride"; import { AvailableFeaturesToOverride } from "./hooks/useFeatureFlagOverride"; diff --git a/app/client/test/factories/AppIDEFactoryUtils.ts b/app/client/test/factories/AppIDEFactoryUtils.ts index 5eccc699e189..b91938136412 100644 --- a/app/client/test/factories/AppIDEFactoryUtils.ts +++ b/app/client/test/factories/AppIDEFactoryUtils.ts @@ -1,5 +1,5 @@ import store from "store"; -import { EditorViewMode } from "ee/entities/IDE/constants"; +import { EditorViewMode } from "IDE/Interfaces/EditorTypes"; import type { AppState } from "ee/reducers"; import MockPluginsState from "test/factories/MockPluginsState"; import type { Action } from "entities/Action";
a8afe98a160cac46a3d2e6ec62adc3d5604d4402
2021-11-05 12:53:46
haojin111
fix: member setting page issues (#8816)
false
member setting page issues (#8816)
fix
diff --git a/app/client/src/components/ads/DialogComponent.tsx b/app/client/src/components/ads/DialogComponent.tsx index 6d4246327641..b9e5f2c26d48 100644 --- a/app/client/src/components/ads/DialogComponent.tsx +++ b/app/client/src/components/ads/DialogComponent.tsx @@ -2,6 +2,7 @@ import React, { ReactNode, useState, useEffect } from "react"; import styled from "styled-components"; import { Dialog, Classes } from "@blueprintjs/core"; import { Colors } from "constants/Colors"; +import Icon, { IconName, IconSize } from "./Icon"; const StyledDialog = styled(Dialog)<{ setMaxWidth?: boolean; @@ -86,6 +87,13 @@ const StyledDialog = styled(Dialog)<{ } `; +const HeaderIconWrapper = styled.div` + padding: 5px; + border-radius: 50%; + margin-right: 10px; + background: ${(props) => props.theme.colors.modal.iconBg}; +`; + const TriggerWrapper = styled.div` margin-right: 4px; `; @@ -94,6 +102,11 @@ type DialogComponentProps = { isOpen?: boolean; canOutsideClickClose?: boolean; title?: string; + headerIcon?: { + name: IconName; + fillColor?: string; + hoverColor?: string; + }; trigger?: ReactNode; setMaxWidth?: boolean; children: ReactNode; @@ -125,6 +138,16 @@ export function DialogComponent(props: DialogComponentProps) { }, [props.isOpen]); const getHeader = props.getHeader; + const headerIcon = props.headerIcon ? ( + <HeaderIconWrapper> + <Icon + fillColor={props.headerIcon.fillColor} + hoverFillColor={props.headerIcon.hoverColor} + name={props.headerIcon.name} + size={IconSize.XL} + /> + </HeaderIconWrapper> + ) : null; return ( <> @@ -143,6 +166,7 @@ export function DialogComponent(props: DialogComponentProps) { canEscapeKeyClose={!!props.canEscapeKeyClose} canOutsideClickClose={!!props.canOutsideClickClose} className={props.className} + icon={headerIcon} isOpen={isOpen} maxHeight={props.maxHeight} maxWidth={props.maxWidth} diff --git a/app/client/src/components/ads/Dropdown.tsx b/app/client/src/components/ads/Dropdown.tsx index f89e0e2bb21c..57088371d83a 100644 --- a/app/client/src/components/ads/Dropdown.tsx +++ b/app/client/src/components/ads/Dropdown.tsx @@ -79,6 +79,7 @@ export type DropdownProps = CommonComponentProps & dontUsePortal?: boolean; hideSubText?: boolean; boundary?: PopperBoundary; + defaultIcon?: IconName; }; export interface DefaultDropDownValueNodeProps { selected: DropdownOption; @@ -685,7 +686,7 @@ export default function Dropdown(props: DropdownProps) { <DropdownIcon fillColor={downIconColor} hoverFillColor={downIconColor} - name="expand-more" + name={props.defaultIcon || "expand-more"} size={IconSize.XXL} /> ) diff --git a/app/client/src/components/ads/Text.tsx b/app/client/src/components/ads/Text.tsx index f49b5fc210cd..182d06d16d51 100644 --- a/app/client/src/components/ads/Text.tsx +++ b/app/client/src/components/ads/Text.tsx @@ -82,7 +82,9 @@ const getFontWeight = ({ }; const Text = styled.span.attrs((props: TextProps) => ({ - className: props.className ? props.className + Classes.TEXT : Classes.TEXT, + className: props.className + ? `${props.className} ${Classes.TEXT}` + : Classes.TEXT, "data-cy": props.cypressSelector, }))<TextProps>` text-decoration: ${(props) => (props.underline ? "underline" : "unset")}; diff --git a/app/client/src/constants/DefaultTheme.tsx b/app/client/src/constants/DefaultTheme.tsx index d82a394abb26..fc8451bb6a8a 100644 --- a/app/client/src/constants/DefaultTheme.tsx +++ b/app/client/src/constants/DefaultTheme.tsx @@ -567,6 +567,7 @@ const darkShades = [ "#FFFFFF", "#157A96", "#090707", + "#FFDEDE", ] as const; const lightShades = [ @@ -588,6 +589,7 @@ const lightShades = [ "#858282", "#000000", "#F86A2B", + "#FFDEDE", ] as const; type ShadeColor = typeof darkShades[number] | typeof lightShades[number]; @@ -898,6 +900,7 @@ type ColorType = { bg: ShadeColor; headerText: ShadeColor; iconColor: string; + iconBg: ShadeColor; user: { textColor: ShadeColor; }; @@ -1864,6 +1867,7 @@ export const dark: ColorType = { bg: darkShades[1], headerText: darkShades[9], iconColor: "#6D6D6D", + iconBg: darkShades[12], user: { textColor: darkShades[7], }, @@ -2502,6 +2506,7 @@ export const light: ColorType = { bg: lightShades[11], headerText: lightShades[10], iconColor: lightShades[5], + iconBg: lightShades[18], user: { textColor: lightShades[9], }, diff --git a/app/client/src/constants/ReduxActionConstants.tsx b/app/client/src/constants/ReduxActionConstants.tsx index df62ff7e697d..9bf9f0fe0872 100644 --- a/app/client/src/constants/ReduxActionConstants.tsx +++ b/app/client/src/constants/ReduxActionConstants.tsx @@ -324,9 +324,9 @@ export const ReduxActionTypes = { INITIALIZE_PAGE_VIEWER_SUCCESS: "INITIALIZE_PAGE_VIEWER_SUCCESS", FETCH_APPLICATION_INIT: "FETCH_APPLICATION_INIT", FETCH_APPLICATION_SUCCESS: "FETCH_APPLICATION_SUCCESS", + INVITED_USERS_TO_ORGANIZATION: "INVITED_USERS_TO_ORGANIZATION", CREATE_APPLICATION_INIT: "CREATE_APPLICATION_INIT", CREATE_APPLICATION_SUCCESS: "CREATE_APPLICATION_SUCCESS", - INVITED_USERS_TO_ORGANIZATION: "INVITED_USERS_TO_ORGANIZATION", UPDATE_WIDGET_PROPERTY_VALIDATION: "UPDATE_WIDGET_PROPERTY_VALIDATION", HIDE_PROPERTY_PANE: "HIDE_PROPERTY_PANE", INIT_DATASOURCE_PANE: "INIT_DATASOURCE_PANE", diff --git a/app/client/src/pages/organization/DeleteConfirmationModal.tsx b/app/client/src/pages/organization/DeleteConfirmationModal.tsx index a8f3176b9bc9..a8e6d78cd9ae 100644 --- a/app/client/src/pages/organization/DeleteConfirmationModal.tsx +++ b/app/client/src/pages/organization/DeleteConfirmationModal.tsx @@ -9,6 +9,7 @@ import { } from "constants/messages"; import Dialog from "components/ads/DialogComponent"; import { Classes } from "@blueprintjs/core"; +import { Colors } from "constants/Colors"; const StyledDialog = styled(Dialog)` && .${Classes.DIALOG_BODY} { @@ -16,8 +17,8 @@ const StyledDialog = styled(Dialog)` } `; -const CenteredContainer = styled.div` - text-align: center; +const LeftContainer = styled.div` + text-align: left; `; const ImportButton = styled(Button)<{ disabled?: boolean }>` @@ -28,7 +29,7 @@ const ImportButton = styled(Button)<{ disabled?: boolean }>` const ButtonWrapper = styled.div` display: flex; - justify-content: center; + justify-content: end; margin-top: 20px; & > a { @@ -52,12 +53,17 @@ function DeleteConfirmationModal(props: DeleteConfirmationProps) { <StyledDialog canOutsideClickClose className={"t--member-delete-confirmation-modal"} + headerIcon={{ + name: "delete", + fillColor: Colors.DANGER_SOLID, + hoverColor: Colors.DANGER_SOLID_HOVER, + }} isOpen={isOpen} maxHeight={"540px"} setModalClose={onClose} title={DELETE_CONFIRMATION_MODAL_TITLE()} > - <CenteredContainer> + <LeftContainer> <Text textAlign="center" type={TextType.P1}> {DELETE_CONFIRMATION_MODAL_SUBTITLE(name || username)} </Text> @@ -80,7 +86,7 @@ function DeleteConfirmationModal(props: DeleteConfirmationProps) { variant={Variant.danger} /> </ButtonWrapper> - </CenteredContainer> + </LeftContainer> </StyledDialog> ); } diff --git a/app/client/src/pages/organization/Members.tsx b/app/client/src/pages/organization/Members.tsx index c15bf13e8a3d..846c4c3a7012 100644 --- a/app/client/src/pages/organization/Members.tsx +++ b/app/client/src/pages/organization/Members.tsx @@ -20,7 +20,7 @@ import { changeOrgUserRole, deleteOrgUser, } from "actions/orgActions"; -import Button, { Size } from "components/ads/Button"; +import Button, { Size, Category } from "components/ads/Button"; import TableDropdown from "components/ads/TableDropdown"; import Dropdown from "components/ads/Dropdown"; import Text, { TextType } from "components/ads/Text"; @@ -34,6 +34,7 @@ import { useMediaQuery } from "react-responsive"; import { Card } from "@blueprintjs/core"; import ProfileImage from "pages/common/ProfileImage"; import { USER_PHOTO_URL } from "constants/userConstants"; +import { Colors } from "constants/Colors"; export type PageProps = RouteComponentProps<{ orgId: string; @@ -81,28 +82,60 @@ const UserCardContainer = styled.div` const UserCard = styled(Card)` display: flex; flex-direction: column; - background-color: #ebebeb; - padding: ${(props) => props.theme.spaces[15]}px 64px; - width: 345px; + box-shadow: none; + background-color: ${Colors.GREY_1}; + border: 1px solid ${Colors.GREY_3}; + border-radius: 0px; + padding: ${(props) => + `${props.theme.spaces[15]}px ${props.theme.spaces[7] * 4}px;`} + width: 343px; height: 201px; margin: auto; - margin-bottom: 15px; + margin-bottom: ${(props) => props.theme.spaces[7] - 1}px; align-items: center; justify-content: center; + position: relative; .avatar { min-height: 71px; + + .${AppClass.TEXT} { + margin: auto; + } } .${AppClass.TEXT} { - color: #090707; - &.email { - color: #858282; + color: ${Colors.GREY_10}; + margin-top: ${(props) => props.theme.spaces[1]}px; + &.user-name { + margin-top: ${(props) => props.theme.spaces[4]}px; + } + &.user-email { + color: ${Colors.GREY_7}; + } + &.user-role { + margin-bottom: ${(props) => props.theme.spaces[3]}px; } } .approve-btn { - background: #f86a2b; + padding: ${(props) => + `${props.theme.spaces[1]}px ${props.theme.spaces[3]}px`}; + } + .delete-btn { + position: absolute; + } + + .t--user-status { + background: transparent; + border: 0px; + width: fit-content; + margin: auto; + .${AppClass.TEXT} { + width: fit-content; + margin-top: 0px; + color: ${Colors.GREY_10}; + } } `; @@ -118,6 +151,12 @@ const TableWrapper = styled(Table)` } `; +const DeleteIcon = styled(Icon)` + position: absolute; + top: ${(props) => props.theme.spaces[9]}px; + right: ${(props) => props.theme.spaces[7]}px; +`; + export default function MemberSettings(props: PageProps) { const { match: { @@ -222,10 +261,7 @@ export default function MemberSettings(props: PageProps) { (role: { name: string; desc: string }) => role.name === cellProps.cell.value, ); - if ( - cellProps.cell.row.values.username === - useSelector(getCurrentUser)?.username - ) { + if (cellProps.cell.row.values.username === currentUser?.username) { return cellProps.cell.value; } return ( @@ -333,32 +369,61 @@ export default function MemberSettings(props: PageProps) { const role = roles.find((role) => role.value === user.roleName) || roles[0]; + const isOwner = user.username === currentUser?.username; return ( <UserCard key={index}> <ProfileImage className="avatar" side={71} source={`/api/${USER_PHOTO_URL}/${user.username}`} - userName={"Test User"} + userName={user.name || user.username} /> - <Text type={TextType.P1}>{user.name || user.username}</Text> - <Text className="email" type={TextType.P1}> + <Text className="user-name" type={TextType.P1}> + {user.name || user.username} + </Text> + <Text className="user-email" type={TextType.P1}> {user.username} </Text> - <Dropdown - height="31px" - onSelect={(value) => { - selectRole(value, user.username); - }} - options={roles} - selected={role} - width="140px" - /> + {isOwner && ( + <Text className="user-role" type={TextType.P1}> + {user.roleName} + </Text> + )} + {!isOwner && ( + <Dropdown + boundary="viewport" + className="t--user-status" + defaultIcon="downArrow" + height="31px" + onSelect={(value) => { + selectRole(value, user.username); + }} + options={roles} + selected={role} + width="140px" + /> + )} <Button + category={Category.primary} className="approve-btn" size={Size.xxs} text="Approve" /> + <DeleteIcon + className="t--deleteUser" + cypressSelector="t--deleteUser" + fillColor={Colors.DANGER_SOLID} + hoverFillColor={Colors.DANGER_SOLID_HOVER} + name="trash-outline" + onClick={() => { + onConfirmMemberDeletion( + user.username, + user.username, + orgId, + ); + }} + size={IconSize.LARGE} + /> </UserCard> ); })}
6225aca0466230a1c73e6d342c2fde3c1236a9b6
2021-10-18 11:48:27
Rishabh Saxena
chore: conditionally load plausible on Appsmith cloud (#8477)
false
conditionally load plausible on Appsmith cloud (#8477)
chore
diff --git a/app/client/public/index.html b/app/client/public/index.html index 6041467fa5cb..47c232e73c33 100755 --- a/app/client/public/index.html +++ b/app/client/public/index.html @@ -24,6 +24,33 @@ 'https://www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f); })(window,document,'script','dataLayer','%REACT_APP_GOOGLE_ANALYTICS_ID%');</script> <!-- End Google Tag Manager --> + <script> + // '' (empty strings), 'false' are falsy + // could return either boolean or string based on value + const parseConfig = (config) => { + if (config.indexOf("__") === 0 || config.indexOf("$") === 0 || config.indexOf("%") === 0) + return ""; + + const result = config.trim(); + if (result.toLowerCase() === "false" || result === "") { + return false; + } else if (result.toLowerCase() === "true") { + return true; + } + + return result; + } + const CLOUD_HOSTING = parseConfig("__APPSMITH_CLOUD_HOSTING__"); + + // Initialize plausible + if (CLOUD_HOSTING) { + const script = document.createElement('script'); + script.defer = true; + script.dataset.domain = location.hostname; + script.src = "https://plausible.io/js/plausible.js"; + document.getElementsByTagName('head')[0].appendChild(script); + } + </script> </head> <body> @@ -139,26 +166,10 @@ registerPageServiceWorker(); </script> <script type="text/javascript"> - // '' (empty strings), 'false' are falsy - // could return either boolean or string based on value - const parseConfig = (config) => { - if (config.indexOf("__") === 0 || config.indexOf("$") === 0 || config.indexOf("%") === 0) - return ""; - - const result = config.trim(); - if (result.toLowerCase() === "false" || result === "") { - return false; - } else if (result.toLowerCase() === "true") { - return true; - } - - return result; - } const LOG_LEVELS = ["debug", "error"]; const CONFIG_LOG_LEVEL_INDEX = LOG_LEVELS.indexOf(parseConfig("__APPSMITH_CLIENT_LOG_LEVEL__")); const INTERCOM_APP_ID = parseConfig("%REACT_APP_INTERCOM_APP_ID%") || parseConfig("__APPSMITH_INTERCOM_APP_ID__"); - const CLOUD_HOSTING = parseConfig("__APPSMITH_CLOUD_HOSTING__"); const DISABLE_TELEMETRY = parseConfig("__APPSMITH_DISABLE_TELEMETRY__"); const DISABLE_INTERCOM = parseConfig("__APPSMITH_DISABLE_INTERCOM__"); @@ -208,7 +219,6 @@ cloudServicesBaseUrl: parseConfig("__APPSMITH_CLOUD_SERVICES_BASE_URL__") || "https://cs.appsmith.com", googleRecaptchaSiteKey: parseConfig("__APPSMITH_RECAPTCHA_SITE_KEY__"), }; - </script> </body>
4d33d6b0333793c95ca931db672726d1819373de
2024-06-18 15:57:27
Manish Kumar
chore: annotate serializable attributes with git annotation (#34273)
false
annotate serializable attributes with git annotation (#34273)
chore
diff --git a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/Datasource.java b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/Datasource.java index c7748bd047fc..e70dc8a0d3de 100644 --- a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/Datasource.java +++ b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/Datasource.java @@ -50,7 +50,7 @@ public class Datasource extends BranchAwareDomain { @JsonView({Views.Public.class, FromRequest.class}) String workspaceId; - @JsonView(Views.Public.class) + @JsonView({Views.Public.class, Git.class}) String templateName; // This is only kept public for embedded datasource diff --git a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/DatasourceStorage.java b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/DatasourceStorage.java index ccd3cb1234ac..da83038dcc62 100644 --- a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/DatasourceStorage.java +++ b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/DatasourceStorage.java @@ -1,5 +1,6 @@ package com.appsmith.external.models; +import com.appsmith.external.views.Git; import com.appsmith.external.views.Views; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonView; @@ -49,9 +50,11 @@ public class DatasourceStorage extends BaseDomain { Set<String> invalids = new HashSet<>(); @Transient + @JsonView({Views.Public.class, Git.class}) String name; @Transient + @JsonView({Views.Public.class, Git.class}) String pluginId; /* @@ -70,9 +73,11 @@ public class DatasourceStorage extends BaseDomain { String workspaceId; @Transient + @JsonView({Views.Public.class, Git.class}) String templateName; @Transient + @JsonView({Views.Public.class, Git.class}) Boolean isAutoGenerated; @Transient diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/domains/ce/ApplicationDetailCE.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/domains/ce/ApplicationDetailCE.java index db1618d943a1..0409752683b0 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/domains/ce/ApplicationDetailCE.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/domains/ce/ApplicationDetailCE.java @@ -1,6 +1,9 @@ package com.appsmith.server.domains.ce; +import com.appsmith.external.views.Git; +import com.appsmith.external.views.Views; import com.appsmith.server.domains.Application; +import com.fasterxml.jackson.annotation.JsonView; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.Setter; @@ -11,8 +14,13 @@ @ToString @EqualsAndHashCode public class ApplicationDetailCE { + @JsonView({Views.Public.class, Git.class}) Application.AppPositioning appPositioning; + + @JsonView({Views.Public.class, Git.class}) Application.NavigationSetting navigationSetting; + + @JsonView({Views.Public.class, Git.class}) Application.ThemeSetting themeSetting; public ApplicationDetailCE() { diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/dtos/PageDTO.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/dtos/PageDTO.java index 4afd5f4e1f81..fccb245d80ea 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/dtos/PageDTO.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/dtos/PageDTO.java @@ -43,7 +43,7 @@ public class PageDTO { @JsonView({Views.Public.class, Views.Export.class, Git.class}) String slug; - @JsonView(Views.Public.class) + @JsonView({Views.Public.class, Git.class}) String customSlug; @Transient @@ -65,7 +65,7 @@ public class PageDTO { @JsonView(Views.Public.class) Instant deletedAt = null; - @JsonView(Views.Public.class) + @JsonView({Views.Public.class, Git.class}) Boolean isHidden; @Transient @@ -78,7 +78,8 @@ public class PageDTO { @JsonView(Views.Public.class) DefaultResources defaultResources; - @JsonView(Views.Public.class) + // TODO: get this clarified for GIT annotation + @JsonView({Views.Public.class, Git.class}) Map<String, List<String>> dependencyMap; public void sanitiseToExportDBObject() {
c3a29b2c2f63a8f0ab883bff50244ee6d77f16e3
2023-05-03 12:28:53
Druthi Polisetty
chore: Removing the old BINDING_SUCCESS event (#22908)
false
Removing the old BINDING_SUCCESS event (#22908)
chore
diff --git a/app/client/src/sagas/PostEvaluationSagas.ts b/app/client/src/sagas/PostEvaluationSagas.ts index 06ae93a00c8c..e11c1aa4fc84 100644 --- a/app/client/src/sagas/PostEvaluationSagas.ts +++ b/app/client/src/sagas/PostEvaluationSagas.ts @@ -382,14 +382,6 @@ export function* logSuccessfulBindings( const hasErrors = errors.length > 0; if (!hasErrors) { if (!isCreateFirstTree) { - // we only aim to log binding success which were added by user - // for first evaluation, bindings are not added by user hence skipping it. - AnalyticsUtil.logEvent("BINDING_SUCCESS", { - unevalValue, - entityType, - propertyPath, - }); - /**Log the binding only if it doesn't already exist */ if ( !successfulBindingPaths[evaluatedPath] || diff --git a/app/client/src/utils/AnalyticsUtil.tsx b/app/client/src/utils/AnalyticsUtil.tsx index 1d9ed17997d0..98cbb3f7e995 100644 --- a/app/client/src/utils/AnalyticsUtil.tsx +++ b/app/client/src/utils/AnalyticsUtil.tsx @@ -134,7 +134,6 @@ export type EventName = | "CYCLICAL_DEPENDENCY_ERROR" | "DISCORD_LINK_CLICK" | "INTERCOM_CLICK" - | "BINDING_SUCCESS" | "ENTITY_BINDING_SUCCESS" | "APP_MENU_OPTION_CLICK" | "SLASH_COMMAND"
813279bfc2d6fbfb64c0091bb423d173af300e5b
2024-12-13 22:21:40
Manish Kumar
chore: Added changes for discard (#38152)
false
Added changes for discard (#38152)
chore
diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/git/GitRedisUtils.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/git/GitRedisUtils.java index 6c27759f3ea3..e0d61cdc192b 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/git/GitRedisUtils.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/git/GitRedisUtils.java @@ -69,7 +69,7 @@ public Mono<Boolean> releaseFileLock(String defaultApplicationId) { * @return : Boolean for whether the lock is acquired */ // TODO @Manish add artifactType reference in incoming prs. - public Mono<Boolean> acquireGitLock(String baseArtifactId, String commandName, boolean isLockRequired) { + public Mono<Boolean> acquireGitLock(String baseArtifactId, String commandName, Boolean isLockRequired) { if (!Boolean.TRUE.equals(isLockRequired)) { return Mono.just(Boolean.TRUE); } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/git/central/CentralGitServiceCE.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/git/central/CentralGitServiceCE.java index 576a7fb99cd3..4254b5d4dd2a 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/git/central/CentralGitServiceCE.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/git/central/CentralGitServiceCE.java @@ -31,4 +31,6 @@ Mono<String> fetchRemoteChanges( ArtifactType artifactType, GitType gitType, RefType refType); + + Mono<? extends Artifact> discardChanges(String branchedArtifactId, ArtifactType artifactType, GitType gitType); } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/git/central/CentralGitServiceCEImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/git/central/CentralGitServiceCEImpl.java index 7a15b41f63c6..55e1692b816e 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/git/central/CentralGitServiceCEImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/git/central/CentralGitServiceCEImpl.java @@ -1112,4 +1112,84 @@ private Mono<? extends Artifact> updateArtifactWithGitMetadataGivenPermission( .getArtifactHelper(artifact.getArtifactType()) .saveArtifact(artifact); } + + /** + * Resets the artifact to last commit, all uncommitted changes are lost in the process. + * @param branchedArtifactId : id of the branchedArtifact + * @param artifactType type of the artifact + * @param gitType what is the intended implementation type + * @return : a publisher of an artifact. + */ + @Override + public Mono<? extends Artifact> discardChanges( + String branchedArtifactId, ArtifactType artifactType, GitType gitType) { + + if (!hasText(branchedArtifactId)) { + return Mono.error(new AppsmithException(AppsmithError.INVALID_PARAMETER, FieldName.ARTIFACT_ID)); + } + + GitArtifactHelper<?> gitArtifactHelper = gitArtifactHelperResolver.getArtifactHelper(artifactType); + AclPermission artifactEditPermission = gitArtifactHelper.getArtifactEditPermission(); + + Mono<? extends Artifact> branchedArtifactMonoCached = + gitArtifactHelper.getArtifactById(branchedArtifactId, artifactEditPermission); + + Mono<? extends Artifact> recreatedArtifactFromLastCommit; + + // Rehydrate the artifact from local file system + recreatedArtifactFromLastCommit = branchedArtifactMonoCached + .flatMap(branchedArtifact -> { + GitArtifactMetadata branchedGitData = branchedArtifact.getGitArtifactMetadata(); + if (branchedGitData == null || !hasText(branchedGitData.getDefaultArtifactId())) { + return Mono.error( + new AppsmithException(AppsmithError.INVALID_GIT_CONFIGURATION, GIT_CONFIG_ERROR)); + } + + return Mono.just(branchedArtifact) + .doFinally(signalType -> gitRedisUtils.acquireGitLock( + branchedGitData.getDefaultArtifactId(), + GitConstants.GitCommandConstants.DISCARD, + TRUE)); + }) + .flatMap(branchedArtifact -> { + GitArtifactMetadata branchedGitData = branchedArtifact.getGitArtifactMetadata(); + ArtifactJsonTransformationDTO jsonTransformationDTO = new ArtifactJsonTransformationDTO(); + // Because this operation is only valid for branches + jsonTransformationDTO.setArtifactType(artifactType); + jsonTransformationDTO.setRefType(RefType.BRANCH); + jsonTransformationDTO.setWorkspaceId(branchedArtifact.getWorkspaceId()); + jsonTransformationDTO.setBaseArtifactId(branchedGitData.getDefaultArtifactId()); + jsonTransformationDTO.setRefName(branchedGitData.getRefName()); + jsonTransformationDTO.setRepoName(branchedGitData.getRepoName()); + + GitHandlingService gitHandlingService = gitHandlingServiceResolver.getGitHandlingService(gitType); + + return gitHandlingService + .recreateArtifactJsonFromLastCommit(jsonTransformationDTO) + .onErrorResume(throwable -> { + log.error("Git recreate ArtifactJsonFailed : {}", throwable.getMessage()); + return Mono.error( + new AppsmithException( + AppsmithError.GIT_ACTION_FAILED, + "discard changes", + "Please create a new branch and resolve conflicts in the remote repository before proceeding.")); + }) + .flatMap(artifactExchangeJson -> importService.importArtifactInWorkspaceFromGit( + branchedArtifact.getWorkspaceId(), + branchedArtifact.getId(), + artifactExchangeJson, + branchedGitData.getBranchName())) + // Update the last deployed status after the rebase + .flatMap(importedArtifact -> gitArtifactHelper.publishArtifact(importedArtifact, true)); + }) + .flatMap(branchedArtifact -> gitAnalyticsUtils + .addAnalyticsForGitOperation(AnalyticsEvents.GIT_DISCARD_CHANGES, branchedArtifact, null) + .doFinally(signalType -> gitRedisUtils.releaseFileLock( + branchedArtifact.getGitArtifactMetadata().getDefaultArtifactId(), TRUE))) + .name(GitSpan.OPS_DISCARD_CHANGES) + .tap(Micrometer.observation(observationRegistry)); + + return Mono.create(sink -> + recreatedArtifactFromLastCommit.subscribe(sink::success, sink::error, null, sink.currentContext())); + } } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/git/central/GitHandlingServiceCE.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/git/central/GitHandlingServiceCE.java index 5b9551ffa675..de387a9e75ee 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/git/central/GitHandlingServiceCE.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/git/central/GitHandlingServiceCE.java @@ -58,4 +58,7 @@ Mono<Tuple2<? extends Artifact, String>> commitArtifact( Artifact branchedArtifact, CommitDTO commitDTO, ArtifactJsonTransformationDTO jsonTransformationDTO); Mono<String> fetchRemoteChanges(ArtifactJsonTransformationDTO jsonTransformationDTO, GitAuth gitAuth); + + Mono<? extends ArtifactExchangeJson> recreateArtifactJsonFromLastCommit( + ArtifactJsonTransformationDTO jsonTransformationDTO); } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/git/fs/GitFSServiceCEImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/git/fs/GitFSServiceCEImpl.java index e84ecd9f7a49..27dc09fde456 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/git/fs/GitFSServiceCEImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/git/fs/GitFSServiceCEImpl.java @@ -598,4 +598,23 @@ public Mono<String> fetchRemoteChanges(ArtifactJsonTransformationDTO jsonTransfo return checkoutBranchMono.then(Mono.defer(() -> fetchRemoteMono)); } + + @Override + public Mono<? extends ArtifactExchangeJson> recreateArtifactJsonFromLastCommit( + ArtifactJsonTransformationDTO jsonTransformationDTO) { + + String workspaceId = jsonTransformationDTO.getWorkspaceId(); + String baseArtifactId = jsonTransformationDTO.getBaseArtifactId(); + String repoName = jsonTransformationDTO.getRepoName(); + String refName = jsonTransformationDTO.getRefName(); + + ArtifactType artifactType = jsonTransformationDTO.getArtifactType(); + GitArtifactHelper<?> gitArtifactHelper = gitArtifactHelperResolver.getArtifactHelper(artifactType); + Path repoSuffix = gitArtifactHelper.getRepoSuffixPath(workspaceId, baseArtifactId, repoName); + + return fsGitHandler.rebaseBranch(repoSuffix, refName).flatMap(rebaseStatus -> { + return commonGitFileUtils.reconstructArtifactExchangeJsonFromGitRepoWithAnalytics( + workspaceId, baseArtifactId, repoName, refName, artifactType); + }); + } }
5eae03d2f0996df585b8f75f88d469ea755f0a1b
2024-04-04 11:30:42
Abhijeet
chore: Remove Mongo BSON dependency for mssql plugin testcase (#32355)
false
Remove Mongo BSON dependency for mssql plugin testcase (#32355)
chore
diff --git a/app/server/appsmith-plugins/mssqlPlugin/src/test/java/com/external/plugins/MssqlPluginTest.java b/app/server/appsmith-plugins/mssqlPlugin/src/test/java/com/external/plugins/MssqlPluginTest.java index 9443afcff118..7be16681867a 100755 --- a/app/server/appsmith-plugins/mssqlPlugin/src/test/java/com/external/plugins/MssqlPluginTest.java +++ b/app/server/appsmith-plugins/mssqlPlugin/src/test/java/com/external/plugins/MssqlPluginTest.java @@ -21,7 +21,6 @@ import com.fasterxml.jackson.databind.node.ArrayNode; import com.fasterxml.jackson.databind.node.JsonNodeType; import com.zaxxer.hikari.HikariDataSource; -import org.bson.types.ObjectId; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; @@ -40,6 +39,7 @@ import java.util.List; import java.util.Map; import java.util.Set; +import java.util.UUID; import java.util.stream.Collectors; import java.util.stream.Stream; @@ -221,8 +221,8 @@ public void invalidTestConnectMsSqlContainer() { DatasourceConfiguration dsConfig = createDatasourceConfiguration(container); // Set up random username and password and try to connect DBAuth auth = (DBAuth) dsConfig.getAuthentication(); - auth.setUsername(new ObjectId().toString()); - auth.setPassword(new ObjectId().toString()); + auth.setUsername(UUID.randomUUID().toString()); + auth.setPassword(UUID.randomUUID().toString()); Mono<HikariDataSource> dsConnectionMono = mssqlPluginExecutor.datasourceCreate(dsConfig);
c41236845c0a4a34975d07c34fe898a6bad2edfd
2024-05-02 17:48:53
Aman Agarwal
feat: added modal name, lint warning for string, action selector modal (#32893)
false
added modal name, lint warning for string, action selector modal (#32893)
feat
diff --git a/app/client/cypress/e2e/Regression/ClientSide/ActionExecution/ActionSelector_JsToNonJSMode_1_spec.ts b/app/client/cypress/e2e/Regression/ClientSide/ActionExecution/ActionSelector_JsToNonJSMode_1_spec.ts index 6a292e4a7495..8b739f964cc3 100644 --- a/app/client/cypress/e2e/Regression/ClientSide/ActionExecution/ActionSelector_JsToNonJSMode_1_spec.ts +++ b/app/client/cypress/e2e/Regression/ClientSide/ActionExecution/ActionSelector_JsToNonJSMode_1_spec.ts @@ -92,7 +92,7 @@ describe("JS to non-JS mode in Action Selector", { tags: ["@tag.JS"] }, () => { EditorNavigation.SelectEntityByName("Button1", EntityType.Widget); propPane.EnterJSContext( "onClick", - `{{Api1.run().then(() => { showAlert('Hello world!', 'info'); storeValue('a', 18); }).catch(() => { showModal('Modal1'); });}}`, + `{{Api1.run().then(() => { showAlert('Hello world!', 'info'); storeValue('a', 18); }).catch(() => { showModal(Modal1.name); });}}`, true, false, ); diff --git a/app/client/cypress/e2e/Regression/ClientSide/ActionExecution/ActionSelector_JsToNonJSMode_2_spec.ts b/app/client/cypress/e2e/Regression/ClientSide/ActionExecution/ActionSelector_JsToNonJSMode_2_spec.ts index 6c135176f910..f51ad098c736 100644 --- a/app/client/cypress/e2e/Regression/ClientSide/ActionExecution/ActionSelector_JsToNonJSMode_2_spec.ts +++ b/app/client/cypress/e2e/Regression/ClientSide/ActionExecution/ActionSelector_JsToNonJSMode_2_spec.ts @@ -212,7 +212,12 @@ describe("JS to non-JS mode in Action Selector", { tags: ["@tag.JS"] }, () => { 0, ); - propPane.EnterJSContext("onClick", "{{showModal('Modal1')}}", true, false); + propPane.EnterJSContext( + "onClick", + "{{showModal(Modal1.name)}}", + true, + false, + ); propPane.ToggleJSMode("onClick", false); agHelper.GetNAssertElementText( @@ -253,7 +258,12 @@ describe("JS to non-JS mode in Action Selector", { tags: ["@tag.JS"] }, () => { 0, ); - propPane.EnterJSContext("onClick", "{{closeModal('Modal1')}}", true, false); + propPane.EnterJSContext( + "onClick", + "{{closeModal(Modal1.name)}}", + true, + false, + ); propPane.ToggleJSMode("onClick", false); agHelper.GetNAssertElementText( diff --git a/app/client/cypress/e2e/Regression/ClientSide/Widgets/Button/ButtonGroup2_spec.ts b/app/client/cypress/e2e/Regression/ClientSide/Widgets/Button/ButtonGroup2_spec.ts index 83991240db1f..16665e914480 100644 --- a/app/client/cypress/e2e/Regression/ClientSide/Widgets/Button/ButtonGroup2_spec.ts +++ b/app/client/cypress/e2e/Regression/ClientSide/Widgets/Button/ButtonGroup2_spec.ts @@ -163,7 +163,7 @@ describe( agHelper.ClickButton("Close"); EditorNavigation.SelectEntityByName("ButtonGroup1", EntityType.Widget); agHelper.GetNClick(buttongroupwidgetlocators.buttonSettingInPropPane, 0); - propPane.EnterJSContext("onClick", "{{showModal('Modal1')}}"); + propPane.EnterJSContext("onClick", "{{showModal(Modal1.name)}}"); deployMode.DeployApp(); agHelper.ClickButton("Favorite"); agHelper.AssertElementExist(locators._modal); diff --git a/app/client/cypress/e2e/Regression/ClientSide/Widgets/Modal/Modal_focus_spec.js b/app/client/cypress/e2e/Regression/ClientSide/Widgets/Modal/Modal_focus_spec.js index 146c30d153b0..8d774a60f021 100644 --- a/app/client/cypress/e2e/Regression/ClientSide/Widgets/Modal/Modal_focus_spec.js +++ b/app/client/cypress/e2e/Regression/ClientSide/Widgets/Modal/Modal_focus_spec.js @@ -17,7 +17,7 @@ describe("Modal focus", { tags: ["@tag.Widget", "@tag.Modal"] }, function () { cy.updateCodeInput( ".t--property-control-onclick", - `{{showModal('Modal1')}}`, + `{{showModal(Modal1.name)}}`, ); //add modal EditorNavigation.SelectEntityByName("Modal1", EntityType.Widget); diff --git a/app/client/cypress/e2e/Regression/ClientSide/Widgets/Modal/Modal_spec.ts b/app/client/cypress/e2e/Regression/ClientSide/Widgets/Modal/Modal_spec.ts index 8fc623d5cdda..86cad0ac3623 100644 --- a/app/client/cypress/e2e/Regression/ClientSide/Widgets/Modal/Modal_spec.ts +++ b/app/client/cypress/e2e/Regression/ClientSide/Widgets/Modal/Modal_spec.ts @@ -26,7 +26,7 @@ describe( entityExplorer.DragDropWidgetNVerify(draggableWidgets.BUTTON); entityExplorer.DragDropWidgetNVerify(draggableWidgets.MODAL, 300, 300); EditorNavigation.SelectEntityByName("Button1", EntityType.Widget); - propPane.EnterJSContext("onClick", "{{showModal('Modal1');}}"); + propPane.EnterJSContext("onClick", "{{showModal(Modal1.name);}}"); deployMode.DeployApp(locators._widgetInDeployed(draggableWidgets.BUTTON)); agHelper.WaitUntilEleAppear( locators._widgetInDeployed(draggableWidgets.BUTTON), diff --git a/app/client/cypress/fixtures/CMSdsl.json b/app/client/cypress/fixtures/CMSdsl.json index a370880f2111..9ed61d63dcb2 100644 --- a/app/client/cypress/fixtures/CMSdsl.json +++ b/app/client/cypress/fixtures/CMSdsl.json @@ -252,7 +252,7 @@ { "resetFormOnClick": true, "widgetName": "FormButton1", - "onClick": "{{showModal('Modal1')}}", + "onClick": "{{showModal(Modal1.name)}}", "buttonColor": "#03B365", "dynamicPropertyPathList": [{ "key": "onClick" }], "displayName": "FormButton", @@ -609,7 +609,7 @@ }, { "widgetName": "Button4", - "onClick": "{{showModal('Modal2')}}", + "onClick": "{{showModal(Modal2.name)}}", "buttonColor": "#03B365", "dynamicPropertyPathList": [{ "key": "onClick" }], "displayName": "Button", @@ -821,7 +821,7 @@ { "widgetName": "Icon1", "rightColumn": 64, - "onClick": "{{closeModal('Modal1')}}", + "onClick": "{{closeModal(Modal1.name)}}", "color": "#040627", "iconName": "cross", "displayName": "Icon", @@ -867,7 +867,7 @@ }, { "widgetName": "Button2", - "onClick": "{{closeModal('Modal1')}}", + "onClick": "{{closeModal(Modal1.name)}}", "buttonColor": "#03B365", "displayName": "Button", "iconSVG": "/static/media/icon.cca02633.svg", diff --git a/app/client/cypress/fixtures/CommunityIssuesExport.json b/app/client/cypress/fixtures/CommunityIssuesExport.json index 332863ac1c7b..81fc5e39b0cd 100644 --- a/app/client/cypress/fixtures/CommunityIssuesExport.json +++ b/app/client/cypress/fixtures/CommunityIssuesExport.json @@ -215,7 +215,7 @@ { "boxShadow": "none", "widgetName": "Icon2", - "onClick": "{{closeModal('upvote_modal')}}", + "onClick": "{{closeModal(upvote_modal.name)}}", "buttonColor": "#2E3D49", "displayName": "Icon", "iconSVG": "/static/media/icon.31d6cfe0.svg", @@ -277,7 +277,7 @@ { "boxShadow": "none", "widgetName": "Button5", - "onClick": "{{closeModal('upvote_modal')}}", + "onClick": "{{closeModal(upvote_modal.name)}}", "buttonColor": "#2E3D49", "displayName": "Button", "iconSVG": "/static/media/icon.cca02633.svg", @@ -2362,7 +2362,7 @@ { "boxShadow": "none", "widgetName": "AddIssue", - "onClick": "{{showModal('add_issue_modal')}}", + "onClick": "{{showModal(add_issue_modal.name)}}", "buttonColor": "#2E3D49", "displayName": "Icon Button", "iconSVG": "/static/media/icon.1a0c634a.svg", @@ -2929,7 +2929,7 @@ { "boxShadow": "none", "widgetName": "Button2", - "onClick": "{{closeModal('add_issue_modal')}}", + "onClick": "{{closeModal(add_issue_modal.name)}}", "buttonColor": "#2E3D49", "displayName": "Button", "iconSVG": "/static/media/icon.cca02633.svg", @@ -2997,7 +2997,7 @@ { "boxShadow": "none", "widgetName": "IconButton5", - "onClick": "{{closeModal('add_issue_modal')}}", + "onClick": "{{closeModal(add_issue_modal.name)}}", "buttonColor": "#2E3D49", "dynamicPropertyPathList": [ { "key": "borderRadius" } @@ -4127,7 +4127,7 @@ "boxShadow": "none", "customAlias": "", "iconName": "caret-up", - "onClick": "{{showModal('upvote_modal');}}", + "onClick": "{{showModal(upvote_modal.name);}}", "buttonVariant": "SECONDARY" } }, @@ -4387,7 +4387,7 @@ { "widgetName": "Icon2", "rightColumn": 64.0, - "onClick": "{{closeModal('upvote_modal')}}", + "onClick": "{{closeModal(upvote_modal.name)}}", "iconName": "cross", "buttonColor": "#2E3D49", "displayName": "Icon", @@ -4437,7 +4437,7 @@ }, { "widgetName": "Button5", - "onClick": "{{closeModal('upvote_modal')}}", + "onClick": "{{closeModal(upvote_modal.name)}}", "buttonColor": "#2E3D49", "displayName": "Button", "iconSVG": "/static/media/icon.cca02633.svg", @@ -6281,7 +6281,7 @@ { "boxShadow": "NONE", "widgetName": "AddIssue", - "onClick": "{{showModal('add_issue_modal')}}", + "onClick": "{{showModal(add_issue_modal.name)}}", "buttonColor": "#2E3D49", "displayName": "Icon Button", "iconSVG": "/static/media/icon.1a0c634a.svg", @@ -6751,7 +6751,7 @@ }, { "widgetName": "Button2", - "onClick": "{{closeModal('add_issue_modal')}}", + "onClick": "{{closeModal(add_issue_modal.name)}}", "buttonColor": "#2E3D49", "displayName": "Button", "iconSVG": "/static/media/icon.cca02633.svg", @@ -6814,7 +6814,7 @@ { "boxShadow": "NONE", "widgetName": "IconButton5", - "onClick": "{{closeModal('add_issue_modal')}}", + "onClick": "{{closeModal(add_issue_modal.name)}}", "buttonColor": "#2E3D49", "displayName": "Icon Button", "iconSVG": "/static/media/icon.1a0c634a.svg", @@ -7280,7 +7280,7 @@ "iconName": "caret-up", "borderRadius": "ROUNDED", "buttonVariant": "SECONDARY", - "onClick": "{{showModal('upvote_modal')}}", + "onClick": "{{showModal(upvote_modal.name)}}", "horizontalAlignment": "LEFT", "textSize": "PARAGRAPH" }, @@ -8518,7 +8518,7 @@ "timeoutInMillisecond": 10000.0, "paginationType": "NONE", "encodeParamsToggle": true, - "body": "() => {\n const labels = IssueManager.getAssignedLabels(label_select.selectedOptionValues);\n add_new_issue.run(() => {\n fetch_issues.run(() => {\n resetWidget('add_issue_modal', true);\n closeModal('add_issue_modal');\n });\n }, undefined, {\n labels: labels\n });\n}", + "body": "() => {\n const labels = IssueManager.getAssignedLabels(label_select.selectedOptionValues);\n add_new_issue.run(() => {\n fetch_issues.run(() => {\n resetWidget('add_issue_modal', true);\n closeModal(add_issue_modal.name);\n });\n }, undefined, {\n labels: labels\n });\n}", "selfReferencingDataPaths": [], "jsArguments": [], "isAsync": false @@ -8529,7 +8529,7 @@ "invalids": [], "messages": [], "jsonPathKeys": [ - "() => {\n const labels = IssueManager.getAssignedLabels(label_select.selectedOptionValues);\n add_new_issue.run(() => {\n fetch_issues.run(() => {\n resetWidget('add_issue_modal', true);\n closeModal('add_issue_modal');\n });\n }, undefined, {\n labels: labels\n });\n}" + "() => {\n const labels = IssueManager.getAssignedLabels(label_select.selectedOptionValues);\n add_new_issue.run(() => {\n fetch_issues.run(() => {\n resetWidget('add_issue_modal', true);\n closeModal(add_issue_modal.name);\n });\n }, undefined, {\n labels: labels\n });\n}" ], "userSetOnLoad": false, "confirmBeforeExecute": false, @@ -8554,7 +8554,7 @@ "timeoutInMillisecond": 10000.0, "paginationType": "NONE", "encodeParamsToggle": true, - "body": "() => {\n\t\tconst labels = IssueManager.getAssignedLabels(label_select.selectedOptionValues);\n\t\tadd_new_issue.run(() => {\n\t\t\t\tfetch_issues.run(() => {\n\t\t\t\t\tresetWidget('add_issue_modal', true);\n\t\t\t\t\tcloseModal('add_issue_modal');\n\t\t\t\t});\n\t\t}, undefined, { labels: labels })\n\t}", + "body": "() => {\n\t\tconst labels = IssueManager.getAssignedLabels(label_select.selectedOptionValues);\n\t\tadd_new_issue.run(() => {\n\t\t\t\tfetch_issues.run(() => {\n\t\t\t\t\tresetWidget('add_issue_modal', true);\n\t\t\t\t\tcloseModal(add_issue_modal.name);\n\t\t\t\t});\n\t\t}, undefined, { labels: labels })\n\t}", "selfReferencingDataPaths": [], "jsArguments": [], "isAsync": false @@ -8565,7 +8565,7 @@ "invalids": [], "messages": [], "jsonPathKeys": [ - "() => {\n\t\tconst labels = IssueManager.getAssignedLabels(label_select.selectedOptionValues);\n\t\tadd_new_issue.run(() => {\n\t\t\t\tfetch_issues.run(() => {\n\t\t\t\t\tresetWidget('add_issue_modal', true);\n\t\t\t\t\tcloseModal('add_issue_modal');\n\t\t\t\t});\n\t\t}, undefined, { labels: labels })\n\t}" + "() => {\n\t\tconst labels = IssueManager.getAssignedLabels(label_select.selectedOptionValues);\n\t\tadd_new_issue.run(() => {\n\t\t\t\tfetch_issues.run(() => {\n\t\t\t\t\tresetWidget('add_issue_modal', true);\n\t\t\t\t\tcloseModal(add_issue_modal.name);\n\t\t\t\t});\n\t\t}, undefined, { labels: labels })\n\t}" ], "userSetOnLoad": false, "confirmBeforeExecute": false, @@ -9632,7 +9632,7 @@ "timeoutInMillisecond": 10000.0, "paginationType": "NONE", "encodeParamsToggle": true, - "body": "() => {\n add_new_comment.run(() => {\n fetch_comments.run();\n update_issue_labels.run(() => fetch_issues.run());\n closeModal('upvote_modal');\n resetWidget('upvote_modal', true);\n });\n}", + "body": "() => {\n add_new_comment.run(() => {\n fetch_comments.run();\n update_issue_labels.run(() => fetch_issues.run());\n closeModal(upvote_modal.name);\n resetWidget('upvote_modal', true);\n });\n}", "selfReferencingDataPaths": [], "jsArguments": [], "isAsync": true @@ -9643,7 +9643,7 @@ "invalids": [], "messages": [], "jsonPathKeys": [ - "() => {\n add_new_comment.run(() => {\n fetch_comments.run();\n update_issue_labels.run(() => fetch_issues.run());\n closeModal('upvote_modal');\n resetWidget('upvote_modal', true);\n });\n}" + "() => {\n add_new_comment.run(() => {\n fetch_comments.run();\n update_issue_labels.run(() => fetch_issues.run());\n closeModal(upvote_modal.name);\n resetWidget('upvote_modal', true);\n });\n}" ], "userSetOnLoad": false, "confirmBeforeExecute": false, @@ -9668,7 +9668,7 @@ "timeoutInMillisecond": 10000.0, "paginationType": "NONE", "encodeParamsToggle": true, - "body": "() => {\n\t\tadd_new_comment.run(() => {\n\t\t\tfetch_comments.run();\n\t\t\tupdate_issue_labels.run(() => \n\t\t\t\tfetch_issues.run());\n\t\t\tcloseModal('upvote_modal');\n\t\t\tresetWidget('upvote_modal', true);\n\t\t});\n\t}", + "body": "() => {\n\t\tadd_new_comment.run(() => {\n\t\t\tfetch_comments.run();\n\t\t\tupdate_issue_labels.run(() => \n\t\t\t\tfetch_issues.run());\n\t\t\tcloseModal(upvote_modal.name);\n\t\t\tresetWidget('upvote_modal', true);\n\t\t});\n\t}", "selfReferencingDataPaths": [], "jsArguments": [], "isAsync": true @@ -9679,7 +9679,7 @@ "invalids": [], "messages": [], "jsonPathKeys": [ - "() => {\n\t\tadd_new_comment.run(() => {\n\t\t\tfetch_comments.run();\n\t\t\tupdate_issue_labels.run(() => \n\t\t\t\tfetch_issues.run());\n\t\t\tcloseModal('upvote_modal');\n\t\t\tresetWidget('upvote_modal', true);\n\t\t});\n\t}" + "() => {\n\t\tadd_new_comment.run(() => {\n\t\t\tfetch_comments.run();\n\t\t\tupdate_issue_labels.run(() => \n\t\t\t\tfetch_issues.run());\n\t\t\tcloseModal(upvote_modal.name);\n\t\t\tresetWidget('upvote_modal', true);\n\t\t});\n\t}" ], "userSetOnLoad": false, "confirmBeforeExecute": false, @@ -9975,7 +9975,7 @@ "pluginType": "JS", "actions": [], "archivedActions": [], - "body": "export default {\n\tgetAssignedLabels: (allLabels = label_select.selectedOptionValues) => {\n\t\tconst labels = allLabels.filter((label) => {\n\t\t\treturn Utils.checkIsPod(label) !== true;\n\t\t}); \n\t\tconst podMap = {};\n\t\tlabels.map((label) => {\n\t\t\tconst pod = Utils.getPodForLabel(label);\n\t\t\tif (pod)\n\t\t\t\tpodMap[pod] = true;\n\t\t});\n\t\treturn [...Object.keys(podMap), ...labels];\n\t}, \n\tcreate_issue: () => {\n\t\tconst labels = this.getAssignedLabels(label_select.selectedOptionValues);\n\t\tadd_new_issue.run(() => {\n\t\t\t\tfetch_issues.run(() => {\n\t\t\t\t\tresetWidget('add_issue_modal', true);\n\t\t\t\t\tcloseModal('add_issue_modal');\n\t\t\t\t});\n\t\t}, undefined, { labels: labels })\n\t},\n\tfetchIssues: () => {\n\t\tfetch_issues.run();\n\t},\n\tgetIssueData: () => {\n\t\treturn fetch_issues.data.map((issue) => {\n\t\t\tif (issue.upvote_id > 0)\n\t\t\t\tissue.count = issue.count + 1;\n\t\t\treturn { type: issue.type, title: issue.title, total_reactions: issue.total_reactions, unique_commentors: issue.unique_commentors, upvote_id: issue.upvote_id ,...issue};\n\t\t});\n\t},\n\taddComment: () => {\n\t\tadd_new_comment.run(() => {\n\t\t\tfetch_comments.run();\n\t\t\tupdate_issue_labels.run(() => \n\t\t\t\tfetch_issues.run());\n\t\t\tcloseModal('upvote_modal');\n\t\t\tresetWidget('upvote_modal', true);\n\t\t});\n\t},\n\tupdate: async () => {\n\t\tconst labels = this.getAssignedLabels(edit_label_select.selectedOptionValues);\n\t\tawait update_issue.run({ labels: labels });\n\t\tawait fetch_issues.run();\n\t},\n\tdelete: async () => {\n\t\tawait delete_issue.run(() => fetch_issues.run());\n\t}\n}", + "body": "export default {\n\tgetAssignedLabels: (allLabels = label_select.selectedOptionValues) => {\n\t\tconst labels = allLabels.filter((label) => {\n\t\t\treturn Utils.checkIsPod(label) !== true;\n\t\t}); \n\t\tconst podMap = {};\n\t\tlabels.map((label) => {\n\t\t\tconst pod = Utils.getPodForLabel(label);\n\t\t\tif (pod)\n\t\t\t\tpodMap[pod] = true;\n\t\t});\n\t\treturn [...Object.keys(podMap), ...labels];\n\t}, \n\tcreate_issue: () => {\n\t\tconst labels = this.getAssignedLabels(label_select.selectedOptionValues);\n\t\tadd_new_issue.run(() => {\n\t\t\t\tfetch_issues.run(() => {\n\t\t\t\t\tresetWidget('add_issue_modal', true);\n\t\t\t\t\tcloseModal(add_issue_modal.name);\n\t\t\t\t});\n\t\t}, undefined, { labels: labels })\n\t},\n\tfetchIssues: () => {\n\t\tfetch_issues.run();\n\t},\n\tgetIssueData: () => {\n\t\treturn fetch_issues.data.map((issue) => {\n\t\t\tif (issue.upvote_id > 0)\n\t\t\t\tissue.count = issue.count + 1;\n\t\t\treturn { type: issue.type, title: issue.title, total_reactions: issue.total_reactions, unique_commentors: issue.unique_commentors, upvote_id: issue.upvote_id ,...issue};\n\t\t});\n\t},\n\taddComment: () => {\n\t\tadd_new_comment.run(() => {\n\t\t\tfetch_comments.run();\n\t\t\tupdate_issue_labels.run(() => \n\t\t\t\tfetch_issues.run());\n\t\t\tcloseModal(upvote_modal.name);\n\t\t\tresetWidget('upvote_modal', true);\n\t\t});\n\t},\n\tupdate: async () => {\n\t\tconst labels = this.getAssignedLabels(edit_label_select.selectedOptionValues);\n\t\tawait update_issue.run({ labels: labels });\n\t\tawait fetch_issues.run();\n\t},\n\tdelete: async () => {\n\t\tawait delete_issue.run(() => fetch_issues.run());\n\t}\n}", "variables": [], "userPermissions": [] }, @@ -9986,7 +9986,7 @@ "pluginType": "JS", "actions": [], "archivedActions": [], - "body": "export default {\n\tgetAssignedLabels: (allLabels = label_select.selectedOptionValues) => {\n\t\tconst labels = allLabels.filter((label) => {\n\t\t\treturn Utils.checkIsPod(label) !== true;\n\t\t}); \n\t\tconst podMap = {};\n\t\tlabels.map((label) => {\n\t\t\tconst pod = Utils.getPodForLabel(label);\n\t\t\tif (pod)\n\t\t\t\tpodMap[pod] = true;\n\t\t});\n\t\treturn [...Object.keys(podMap), ...labels];\n\t}, \n\tcreate_issue: () => {\n\t\tconst labels = this.getAssignedLabels(label_select.selectedOptionValues);\n\t\tadd_new_issue.run(() => {\n\t\t\t\tfetch_issues.run(() => {\n\t\t\t\t\tresetWidget('add_issue_modal', true);\n\t\t\t\t\tcloseModal('add_issue_modal');\n\t\t\t\t});\n\t\t}, undefined, { labels: labels })\n\t},\n\tfetchIssues: () => {\n\t\tfetch_issues.run();\n\t},\n\tgetIssueData: () => {\n\t\treturn fetch_issues.data.map((issue) => {\n\t\t\tif (issue.upvote_id > 0)\n\t\t\t\tissue.count = issue.count + 1;\n\t\t\treturn { type: issue.type, title: issue.title, total_reactions: issue.total_reactions, unique_commentors: issue.unique_commentors, upvote_id: issue.upvote_id ,...issue};\n\t\t});\n\t},\n\taddComment: () => {\n\t\tadd_new_comment.run(() => {\n\t\t\tfetch_comments.run();\n\t\t\tupdate_issue_labels.run(() => \n\t\t\t\tfetch_issues.run());\n\t\t\tcloseModal('upvote_modal');\n\t\t\tresetWidget('upvote_modal', true);\n\t\t});\n\t},\n\tupdate: async () => {\n\t\tconst labels = this.getAssignedLabels(edit_label_select.selectedOptionValues);\n\t\tawait update_issue.run({ labels: labels });\n\t\tawait fetch_issues.run();\n\t},\n\tdelete: async () => {\n\t\tawait delete_issue.run(() => fetch_issues.run());\n\t}\n}", + "body": "export default {\n\tgetAssignedLabels: (allLabels = label_select.selectedOptionValues) => {\n\t\tconst labels = allLabels.filter((label) => {\n\t\t\treturn Utils.checkIsPod(label) !== true;\n\t\t}); \n\t\tconst podMap = {};\n\t\tlabels.map((label) => {\n\t\t\tconst pod = Utils.getPodForLabel(label);\n\t\t\tif (pod)\n\t\t\t\tpodMap[pod] = true;\n\t\t});\n\t\treturn [...Object.keys(podMap), ...labels];\n\t}, \n\tcreate_issue: () => {\n\t\tconst labels = this.getAssignedLabels(label_select.selectedOptionValues);\n\t\tadd_new_issue.run(() => {\n\t\t\t\tfetch_issues.run(() => {\n\t\t\t\t\tresetWidget('add_issue_modal', true);\n\t\t\t\t\tcloseModal(add_issue_modal.name);\n\t\t\t\t});\n\t\t}, undefined, { labels: labels })\n\t},\n\tfetchIssues: () => {\n\t\tfetch_issues.run();\n\t},\n\tgetIssueData: () => {\n\t\treturn fetch_issues.data.map((issue) => {\n\t\t\tif (issue.upvote_id > 0)\n\t\t\t\tissue.count = issue.count + 1;\n\t\t\treturn { type: issue.type, title: issue.title, total_reactions: issue.total_reactions, unique_commentors: issue.unique_commentors, upvote_id: issue.upvote_id ,...issue};\n\t\t});\n\t},\n\taddComment: () => {\n\t\tadd_new_comment.run(() => {\n\t\t\tfetch_comments.run();\n\t\t\tupdate_issue_labels.run(() => \n\t\t\t\tfetch_issues.run());\n\t\t\tcloseModal(upvote_modal.name);\n\t\t\tresetWidget('upvote_modal', true);\n\t\t});\n\t},\n\tupdate: async () => {\n\t\tconst labels = this.getAssignedLabels(edit_label_select.selectedOptionValues);\n\t\tawait update_issue.run({ labels: labels });\n\t\tawait fetch_issues.run();\n\t},\n\tdelete: async () => {\n\t\tawait delete_issue.run(() => fetch_issues.run());\n\t}\n}", "variables": [], "userPermissions": [] }, diff --git a/app/client/cypress/fixtures/ContextSwitching.json b/app/client/cypress/fixtures/ContextSwitching.json index 8b9b734bfc7e..2a78e803b5e2 100644 --- a/app/client/cypress/fixtures/ContextSwitching.json +++ b/app/client/cypress/fixtures/ContextSwitching.json @@ -497,7 +497,7 @@ { "boxShadow": "none", "widgetName": "IconButton1", - "onClick": "{{closeModal('Modal1')}}", + "onClick": "{{closeModal(Modal1.name)}}", "buttonColor": "{{appsmith.theme.colors.primaryColor}}", "displayName": "Icon button", "iconSVG": "/static/media/icon.1a0c634ac75f9fa6b6ae7a8df882a3ba.svg", @@ -580,7 +580,7 @@ "resetFormOnClick": false, "boxShadow": "none", "widgetName": "Button2", - "onClick": "{{closeModal('Modal1')}}", + "onClick": "{{closeModal(Modal1.name)}}", "buttonColor": "{{appsmith.theme.colors.primaryColor}}", "displayName": "Button", "iconSVG": "/static/media/icon.cca026338f1c8eb6df8ba03d084c2fca.svg", diff --git a/app/client/cypress/fixtures/Datatypes/ArrayDTdsl.json b/app/client/cypress/fixtures/Datatypes/ArrayDTdsl.json index 14d73e8922dc..b45e387de0f0 100644 --- a/app/client/cypress/fixtures/Datatypes/ArrayDTdsl.json +++ b/app/client/cypress/fixtures/Datatypes/ArrayDTdsl.json @@ -234,7 +234,7 @@ { "boxShadow": "none", "widgetName": "IconButton1Copy", - "onClick": "{{closeModal('UpdateModal')}}", + "onClick": "{{closeModal(UpdateModal.name)}}", "buttonColor": "{{appsmith.theme.colors.primaryColor}}", "displayName": "Icon button", "iconSVG": "/static/media/icon.1a0c634a.svg", @@ -317,7 +317,7 @@ { "boxShadow": "none", "widgetName": "runUpdateQuery", - "onClick": "{{updateRecord.run(() => {closeModal('UpdateModal'), () => {};selectRecords.run() })}}", + "onClick": "{{updateRecord.run(() => {closeModal(UpdateModal.name), () => {};selectRecords.run() })}}", "buttonColor": "{{appsmith.theme.colors.primaryColor}}", "dynamicPropertyPathList": [ { @@ -678,7 +678,7 @@ { "boxShadow": "none", "widgetName": "InsertButton", - "onClick": "{{showModal('InsertModal')}}", + "onClick": "{{showModal(InsertModal.name)}}", "buttonColor": "{{appsmith.theme.colors.primaryColor}}", "dynamicPropertyPathList": [ { @@ -728,7 +728,7 @@ { "boxShadow": "none", "widgetName": "UpdateButton", - "onClick": "{{showModal('UpdateModal')}}", + "onClick": "{{showModal(UpdateModal.name)}}", "buttonColor": "{{appsmith.theme.colors.primaryColor}}", "dynamicPropertyPathList": [], "displayName": "Button", @@ -926,7 +926,7 @@ { "boxShadow": "none", "widgetName": "IconButton1", - "onClick": "{{closeModal('InsertModal')}}", + "onClick": "{{closeModal(InsertModal.name)}}", "buttonColor": "{{appsmith.theme.colors.primaryColor}}", "displayName": "Icon button", "iconSVG": "/static/media/icon.1a0c634a.svg", @@ -1057,7 +1057,7 @@ { "boxShadow": "none", "widgetName": "runInsertQuery", - "onClick": "{{insertRecord.run(() => {selectRecords.run();resetWidget('InsertModal', true);closeModal('InsertModal'), () => {};})}}", + "onClick": "{{insertRecord.run(() => {selectRecords.run();resetWidget('InsertModal', true);closeModal(InsertModal.name), () => {};})}}", "buttonColor": "{{appsmith.theme.colors.primaryColor}}", "dynamicPropertyPathList": [ { diff --git a/app/client/cypress/fixtures/Datatypes/BinaryDTdsl.json b/app/client/cypress/fixtures/Datatypes/BinaryDTdsl.json index 60cac4dd932b..5d70884c16f1 100644 --- a/app/client/cypress/fixtures/Datatypes/BinaryDTdsl.json +++ b/app/client/cypress/fixtures/Datatypes/BinaryDTdsl.json @@ -179,7 +179,7 @@ { "boxShadow": "none", "widgetName": "IconButton1Copy", - "onClick": "{{closeModal('UpdateModal')}}", + "onClick": "{{closeModal(UpdateModal.name)}}", "buttonColor": "{{appsmith.theme.colors.primaryColor}}", "displayName": "Icon button", "iconSVG": "/static/media/icon.1a0c634a.svg", @@ -262,7 +262,7 @@ { "boxShadow": "none", "widgetName": "runUpdateQuery", - "onClick": "{{updateRecord.run(() => {closeModal('UpdateModal'), () => {};selectRecords.run() })}}", + "onClick": "{{updateRecord.run(() => {closeModal(UpdateModal.name), () => {};selectRecords.run() })}}", "buttonColor": "{{appsmith.theme.colors.primaryColor}}", "dynamicPropertyPathList": [ { @@ -833,7 +833,7 @@ { "boxShadow": "none", "widgetName": "InsertButton", - "onClick": "{{showModal('InsertModal')}}", + "onClick": "{{showModal(InsertModal.name)}}", "buttonColor": "{{appsmith.theme.colors.primaryColor}}", "dynamicPropertyPathList": [ { @@ -883,7 +883,7 @@ { "boxShadow": "none", "widgetName": "UpdateButton", - "onClick": "{{showModal('UpdateModal')}}", + "onClick": "{{showModal(UpdateModal.name)}}", "buttonColor": "{{appsmith.theme.colors.primaryColor}}", "dynamicPropertyPathList": [], "displayName": "Button", @@ -975,7 +975,7 @@ { "boxShadow": "none", "widgetName": "IconButton1", - "onClick": "{{closeModal('InsertModal')}}", + "onClick": "{{closeModal(InsertModal.name)}}", "buttonColor": "{{appsmith.theme.colors.primaryColor}}", "displayName": "Icon button", "iconSVG": "/static/media/icon.1a0c634a.svg", @@ -1109,7 +1109,7 @@ { "boxShadow": "none", "widgetName": "runInsertQuery", - "onClick": "{{insertRecord.run(() => {selectRecords.run();resetWidget('InsertModal', true);closeModal('InsertModal'), () => {};})}}", + "onClick": "{{insertRecord.run(() => {selectRecords.run();resetWidget('InsertModal', true);closeModal(InsertModal.name), () => {};})}}", "buttonColor": "{{appsmith.theme.colors.backgroundColor}}", "dynamicPropertyPathList": [ { diff --git a/app/client/cypress/fixtures/Datatypes/BooleanEnumDTdsl.json b/app/client/cypress/fixtures/Datatypes/BooleanEnumDTdsl.json index 4f5466f552ad..98f6e6c48200 100644 --- a/app/client/cypress/fixtures/Datatypes/BooleanEnumDTdsl.json +++ b/app/client/cypress/fixtures/Datatypes/BooleanEnumDTdsl.json @@ -67,7 +67,7 @@ { "boxShadow": "none", "widgetName": "IconButton1Copy", - "onClick": "{{closeModal('InsertModal')}}", + "onClick": "{{closeModal(InsertModal.name)}}", "buttonColor": "{{appsmith.theme.colors.primaryColor}}", "displayName": "Icon button", "iconSVG": "/static/media/icon.1a0c634a.svg", @@ -145,7 +145,7 @@ { "boxShadow": "none", "widgetName": "Button5Copy", - "onClick": "{{closeModal('UpdateModal')}}", + "onClick": "{{closeModal(UpdateModal.name)}}", "buttonColor": "{{appsmith.theme.colors.primaryColor}}", "displayName": "Button", "iconSVG": "/static/media/icon.cca02633.svg", @@ -184,7 +184,7 @@ { "boxShadow": "none", "widgetName": "runUpdateQuery", - "onClick": "{{updateRecord.run(() => {closeModal('UpdateModal'), () => {};\nselectRecords.run()\t\t\t\t\t\t\t\t\t\t\t\t })}}", + "onClick": "{{updateRecord.run(() => {closeModal(UpdateModal.name), () => {};\nselectRecords.run()\t\t\t\t\t\t\t\t\t\t\t\t })}}", "buttonColor": "{{appsmith.theme.colors.primaryColor}}", "dynamicPropertyPathList": [ { @@ -615,7 +615,7 @@ { "boxShadow": "none", "widgetName": "InsertButton", - "onClick": "{{showModal('InsertModal')}}", + "onClick": "{{showModal(InsertModal.name)}}", "buttonColor": "{{appsmith.theme.colors.primaryColor}}", "dynamicPropertyPathList": [ { @@ -665,7 +665,7 @@ { "boxShadow": "none", "widgetName": "UpdateButton", - "onClick": "{{showModal('UpdateModal')}}", + "onClick": "{{showModal(UpdateModal.name)}}", "buttonColor": "{{appsmith.theme.colors.primaryColor}}", "dynamicPropertyPathList": [], "displayName": "Button", @@ -755,7 +755,7 @@ { "boxShadow": "none", "widgetName": "IconButton1", - "onClick": "{{closeModal('InsertModal')}}", + "onClick": "{{closeModal(InsertModal.name)}}", "buttonColor": "{{appsmith.theme.colors.primaryColor}}", "displayName": "Icon button", "iconSVG": "/static/media/icon.1a0c634a.svg", @@ -830,7 +830,7 @@ { "boxShadow": "none", "widgetName": "Button5", - "onClick": "{{closeModal('InsertModal')}}", + "onClick": "{{closeModal(InsertModal.name)}}", "buttonColor": "{{appsmith.theme.colors.primaryColor}}", "displayName": "Button", "iconSVG": "/static/media/icon.cca02633.svg", @@ -869,7 +869,7 @@ { "boxShadow": "none", "widgetName": "runInsertQuery", - "onClick": "{{insertRecord.run(() => {\nselectRecords.run();\t\t\t\tresetWidget('InsertModal', true);\ncloseModal('InsertModal'), () => {};})}}", + "onClick": "{{insertRecord.run(() => {\nselectRecords.run();\t\t\t\tresetWidget('InsertModal', true);\ncloseModal(InsertModal.name), () => {};})}}", "buttonColor": "{{appsmith.theme.colors.primaryColor}}", "dynamicPropertyPathList": [ { diff --git a/app/client/cypress/fixtures/Datatypes/CharacterDTdsl.json b/app/client/cypress/fixtures/Datatypes/CharacterDTdsl.json index 6794dc58650a..82229f2e78c2 100644 --- a/app/client/cypress/fixtures/Datatypes/CharacterDTdsl.json +++ b/app/client/cypress/fixtures/Datatypes/CharacterDTdsl.json @@ -174,7 +174,7 @@ { "boxShadow": "none", "widgetName": "IconButton1Copy", - "onClick": "{{closeModal('InsertModal')}}", + "onClick": "{{closeModal(InsertModal.name)}}", "buttonColor": "{{appsmith.theme.colors.primaryColor}}", "displayName": "Icon button", "iconSVG": "/static/media/icon.1a0c634a.svg", @@ -252,7 +252,7 @@ { "boxShadow": "none", "widgetName": "Button5Copy", - "onClick": "{{closeModal('UpdateModal')}}", + "onClick": "{{closeModal(UpdateModal.name)}}", "buttonColor": "{{appsmith.theme.colors.primaryColor}}", "displayName": "Button", "iconSVG": "/static/media/icon.cca02633.svg", @@ -291,7 +291,7 @@ { "boxShadow": "none", "widgetName": "runUpdateQuery", - "onClick": "{{updateRecord.run(() => {closeModal('UpdateModal'), () => {};\nselectRecords.run()\t\t\t\t\t\t\t\t\t\t\t\t })}}", + "onClick": "{{updateRecord.run(() => {closeModal(UpdateModal.name), () => {};\nselectRecords.run()\t\t\t\t\t\t\t\t\t\t\t\t })}}", "buttonColor": "{{appsmith.theme.colors.primaryColor}}", "dynamicPropertyPathList": [ { @@ -817,7 +817,7 @@ { "boxShadow": "none", "widgetName": "InsertButton", - "onClick": "{{showModal('InsertModal')}}", + "onClick": "{{showModal(InsertModal.name)}}", "buttonColor": "{{appsmith.theme.colors.primaryColor}}", "dynamicPropertyPathList": [ { @@ -867,7 +867,7 @@ { "boxShadow": "none", "widgetName": "UpdateButton", - "onClick": "{{showModal('UpdateModal')}}", + "onClick": "{{showModal(UpdateModal.name)}}", "buttonColor": "{{appsmith.theme.colors.primaryColor}}", "dynamicPropertyPathList": [], "displayName": "Button", @@ -1059,7 +1059,7 @@ { "boxShadow": "none", "widgetName": "IconButton1", - "onClick": "{{closeModal('InsertModal')}}", + "onClick": "{{closeModal(InsertModal.name)}}", "buttonColor": "{{appsmith.theme.colors.primaryColor}}", "displayName": "Icon button", "iconSVG": "/static/media/icon.1a0c634a.svg", @@ -1134,7 +1134,7 @@ { "boxShadow": "none", "widgetName": "Button5", - "onClick": "{{closeModal('InsertModal')}}", + "onClick": "{{closeModal(InsertModal.name)}}", "buttonColor": "{{appsmith.theme.colors.primaryColor}}", "displayName": "Button", "iconSVG": "/static/media/icon.cca02633.svg", @@ -1173,7 +1173,7 @@ { "boxShadow": "none", "widgetName": "runInsertQuery", - "onClick": "{{insertRecord.run(() => {\nselectRecords.run();\t\t\t\tresetWidget('InsertModal', true);\ncloseModal('InsertModal'), () => {};})}}", + "onClick": "{{insertRecord.run(() => {\nselectRecords.run();\t\t\t\tresetWidget('InsertModal', true);\ncloseModal(InsertModal.name), () => {};})}}", "buttonColor": "{{appsmith.theme.colors.primaryColor}}", "dynamicPropertyPathList": [ { diff --git a/app/client/cypress/fixtures/Datatypes/DateTimeDTdsl.json b/app/client/cypress/fixtures/Datatypes/DateTimeDTdsl.json index 23cd8084ef17..c869d8abbfa5 100644 --- a/app/client/cypress/fixtures/Datatypes/DateTimeDTdsl.json +++ b/app/client/cypress/fixtures/Datatypes/DateTimeDTdsl.json @@ -173,7 +173,7 @@ { "boxShadow": "none", "widgetName": "IconButton1Copy", - "onClick": "{{closeModal('InsertModal')}}", + "onClick": "{{closeModal(InsertModal.name)}}", "buttonColor": "{{appsmith.theme.colors.primaryColor}}", "displayName": "Icon button", "iconSVG": "/static/media/icon.1a0c634a.svg", @@ -251,7 +251,7 @@ { "boxShadow": "none", "widgetName": "Button5Copy", - "onClick": "{{closeModal('UpdateModal')}}", + "onClick": "{{closeModal(UpdateModal.name)}}", "buttonColor": "{{appsmith.theme.colors.primaryColor}}", "displayName": "Button", "iconSVG": "/static/media/icon.cca02633.svg", @@ -290,7 +290,7 @@ { "boxShadow": "none", "widgetName": "runUpdateQuery", - "onClick": "{{updateRecord.run(() => {closeModal('UpdateModal'), () => {};\nselectRecords.run()\t\t\t\t\t\t\t\t\t\t\t\t })}}", + "onClick": "{{updateRecord.run(() => {closeModal(UpdateModal.name), () => {};\nselectRecords.run()\t\t\t\t\t\t\t\t\t\t\t\t })}}", "buttonColor": "{{appsmith.theme.colors.primaryColor}}", "dynamicPropertyPathList": [ { @@ -872,7 +872,7 @@ { "boxShadow": "none", "widgetName": "InsertButton", - "onClick": "{{showModal('InsertModal')}}", + "onClick": "{{showModal(InsertModal.name)}}", "buttonColor": "{{appsmith.theme.colors.primaryColor}}", "dynamicPropertyPathList": [ { @@ -922,7 +922,7 @@ { "boxShadow": "none", "widgetName": "UpdateButton", - "onClick": "{{showModal('UpdateModal')}}", + "onClick": "{{showModal(UpdateModal.name)}}", "buttonColor": "{{appsmith.theme.colors.primaryColor}}", "dynamicPropertyPathList": [], "displayName": "Button", @@ -1113,7 +1113,7 @@ { "boxShadow": "none", "widgetName": "IconButton1", - "onClick": "{{closeModal('InsertModal')}}", + "onClick": "{{closeModal(InsertModal.name)}}", "buttonColor": "{{appsmith.theme.colors.primaryColor}}", "displayName": "Icon button", "iconSVG": "/static/media/icon.1a0c634a.svg", @@ -1188,7 +1188,7 @@ { "boxShadow": "none", "widgetName": "Button5", - "onClick": "{{closeModal('InsertModal')}}", + "onClick": "{{closeModal(InsertModal.name)}}", "buttonColor": "{{appsmith.theme.colors.primaryColor}}", "displayName": "Button", "iconSVG": "/static/media/icon.cca02633.svg", @@ -1227,7 +1227,7 @@ { "boxShadow": "none", "widgetName": "runInsertQuery", - "onClick": "{{insertRecord.run(() => {\nselectRecords.run();\t\t\t\tresetWidget('InsertModal', true);\ncloseModal('InsertModal'), () => {};})}}", + "onClick": "{{insertRecord.run(() => {\nselectRecords.run();\t\t\t\tresetWidget('InsertModal', true);\ncloseModal(InsertModal.name), () => {};})}}", "buttonColor": "{{appsmith.theme.colors.primaryColor}}", "dynamicPropertyPathList": [ { diff --git a/app/client/cypress/fixtures/Datatypes/JsonBDTdsl.json b/app/client/cypress/fixtures/Datatypes/JsonBDTdsl.json index 58eb6d1866c3..dacd5d5145a3 100644 --- a/app/client/cypress/fixtures/Datatypes/JsonBDTdsl.json +++ b/app/client/cypress/fixtures/Datatypes/JsonBDTdsl.json @@ -240,7 +240,7 @@ ], "displayName": "JSON Form", "iconSVG": "/static/media/icon.5b428de12db9ad6a591955ead07f86e9.svg", - "onSubmit": "{{updateRecord.run(() => {closeModal('UpdateModal'), () => {};\nselectRecords.run()})}}", + "onSubmit": "{{updateRecord.run(() => {closeModal(UpdateModal.name), () => {};\nselectRecords.run()})}}", "topRow": 8, "bottomRow": 60, "fieldLimitExceeded": false, @@ -439,7 +439,7 @@ { "boxShadow": "none", "widgetName": "IconButton1Copy", - "onClick": "{{closeModal('UpdateModal')}}", + "onClick": "{{closeModal(UpdateModal.name)}}", "buttonColor": "{{appsmith.theme.colors.primaryColor}}", "displayName": "Icon button", "iconSVG": "/static/media/icon.1a0c634a.svg", @@ -746,7 +746,7 @@ { "boxShadow": "none", "widgetName": "InsertButton", - "onClick": "{{showModal('InsertModal')}}", + "onClick": "{{showModal(InsertModal.name)}}", "buttonColor": "{{appsmith.theme.colors.primaryColor}}", "dynamicPropertyPathList": [ { @@ -796,7 +796,7 @@ { "boxShadow": "none", "widgetName": "UpdateButton", - "onClick": "{{showModal('UpdateModal')}}", + "onClick": "{{showModal(UpdateModal.name)}}", "buttonColor": "{{appsmith.theme.colors.primaryColor}}", "dynamicPropertyPathList": [], "displayName": "Button", @@ -880,7 +880,7 @@ { "boxShadow": "none", "widgetName": "IconButton1", - "onClick": "{{closeModal('InsertModal')}}", + "onClick": "{{closeModal(InsertModal.name)}}", "buttonColor": "{{appsmith.theme.colors.primaryColor}}", "displayName": "Icon button", "iconSVG": "/static/media/icon.1a0c634a.svg", @@ -1130,7 +1130,7 @@ ], "displayName": "JSON Form", "iconSVG": "/static/media/icon.5b428de12db9ad6a591955ead07f86e9.svg", - "onSubmit": "{{insertRecord.run(() => {\nselectRecords.run();\t\t\t\tresetWidget('InsertModal', true);\ncloseModal('InsertModal'), () => {};})}}", + "onSubmit": "{{insertRecord.run(() => {\nselectRecords.run();\t\t\t\tresetWidget('InsertModal', true);\ncloseModal(InsertModal.name), () => {};})}}", "topRow": 6, "bottomRow": 58, "fieldLimitExceeded": false, diff --git a/app/client/cypress/fixtures/Datatypes/JsonDTdsl.json b/app/client/cypress/fixtures/Datatypes/JsonDTdsl.json index 434c27789920..35fd0739e7da 100644 --- a/app/client/cypress/fixtures/Datatypes/JsonDTdsl.json +++ b/app/client/cypress/fixtures/Datatypes/JsonDTdsl.json @@ -266,7 +266,7 @@ ], "displayName": "JSON Form", "iconSVG": "/static/media/icon.5b428de12db9ad6a591955ead07f86e9.svg", - "onSubmit": "{{updateRecord.run(() => {closeModal('UpdateModal'), () => {};\nselectRecords.run()})}}", + "onSubmit": "{{updateRecord.run(() => {closeModal(UpdateModal.name), () => {};\nselectRecords.run()})}}", "topRow": 8, "bottomRow": 60, "fieldLimitExceeded": false, @@ -561,7 +561,7 @@ { "boxShadow": "none", "widgetName": "IconButton1Copy", - "onClick": "{{closeModal('UpdateModal')}}", + "onClick": "{{closeModal(UpdateModal.name)}}", "buttonColor": "{{appsmith.theme.colors.primaryColor}}", "displayName": "Icon button", "iconSVG": "/static/media/icon.1a0c634a.svg", @@ -902,7 +902,7 @@ { "boxShadow": "none", "widgetName": "InsertButton", - "onClick": "{{showModal('InsertModal')}}", + "onClick": "{{showModal(InsertModal.name)}}", "buttonColor": "{{appsmith.theme.colors.primaryColor}}", "dynamicPropertyPathList": [ { @@ -952,7 +952,7 @@ { "boxShadow": "none", "widgetName": "UpdateButton", - "onClick": "{{showModal('UpdateModal')}}", + "onClick": "{{showModal(UpdateModal.name)}}", "buttonColor": "{{appsmith.theme.colors.primaryColor}}", "dynamicPropertyPathList": [], "displayName": "Button", @@ -1043,7 +1043,7 @@ { "boxShadow": "none", "widgetName": "IconButton1", - "onClick": "{{closeModal('InsertModal')}}", + "onClick": "{{closeModal(InsertModal.name)}}", "buttonColor": "{{appsmith.theme.colors.primaryColor}}", "displayName": "Icon button", "iconSVG": "/static/media/icon.1a0c634a.svg", @@ -1319,7 +1319,7 @@ ], "displayName": "JSON Form", "iconSVG": "/static/media/icon.5b428de12db9ad6a591955ead07f86e9.svg", - "onSubmit": "{{insertRecord.run(() => {\nselectRecords.run();\t\t\t\tresetWidget('InsertModal', true);\ncloseModal('InsertModal'), () => {};})}}", + "onSubmit": "{{insertRecord.run(() => {\nselectRecords.run();\t\t\t\tresetWidget('InsertModal', true);\ncloseModal(InsertModal.name), () => {};})}}", "topRow": 6, "bottomRow": 58, "fieldLimitExceeded": false, diff --git a/app/client/cypress/fixtures/Datatypes/NumericDTdsl.json b/app/client/cypress/fixtures/Datatypes/NumericDTdsl.json index edb6ec38e09e..f5c6999faff8 100644 --- a/app/client/cypress/fixtures/Datatypes/NumericDTdsl.json +++ b/app/client/cypress/fixtures/Datatypes/NumericDTdsl.json @@ -173,7 +173,7 @@ { "boxShadow": "none", "widgetName": "IconButton1Copy", - "onClick": "{{closeModal('InsertModal')}}", + "onClick": "{{closeModal(InsertModal.name)}}", "buttonColor": "{{appsmith.theme.colors.primaryColor}}", "displayName": "Icon button", "iconSVG": "/static/media/icon.1a0c634a.svg", @@ -251,7 +251,7 @@ { "boxShadow": "none", "widgetName": "Button5Copy", - "onClick": "{{closeModal('UpdateModal')}}", + "onClick": "{{closeModal(UpdateModal.name)}}", "buttonColor": "{{appsmith.theme.colors.primaryColor}}", "displayName": "Button", "iconSVG": "/static/media/icon.cca02633.svg", @@ -290,7 +290,7 @@ { "boxShadow": "none", "widgetName": "runUpdateQuery", - "onClick": "{{updateRecord.run(() => {closeModal('UpdateModal'), () => {};\nselectRecords.run()\t\t\t\t\t\t\t\t\t\t\t\t })}}", + "onClick": "{{updateRecord.run(() => {closeModal(UpdateModal.name), () => {};\nselectRecords.run()\t\t\t\t\t\t\t\t\t\t\t\t })}}", "buttonColor": "{{appsmith.theme.colors.primaryColor}}", "dynamicPropertyPathList": [ { @@ -690,7 +690,7 @@ { "boxShadow": "none", "widgetName": "InsertButton", - "onClick": "{{showModal('InsertModal')}}", + "onClick": "{{showModal(InsertModal.name)}}", "buttonColor": "{{appsmith.theme.colors.primaryColor}}", "dynamicPropertyPathList": [ { @@ -740,7 +740,7 @@ { "boxShadow": "none", "widgetName": "UpdateButton", - "onClick": "{{showModal('UpdateModal')}}", + "onClick": "{{showModal(UpdateModal.name)}}", "buttonColor": "{{appsmith.theme.colors.primaryColor}}", "dynamicPropertyPathList": [], "displayName": "Button", @@ -930,7 +930,7 @@ { "boxShadow": "none", "widgetName": "IconButton1", - "onClick": "{{closeModal('InsertModal')}}", + "onClick": "{{closeModal(InsertModal.name)}}", "buttonColor": "{{appsmith.theme.colors.primaryColor}}", "displayName": "Icon button", "iconSVG": "/static/media/icon.1a0c634a.svg", @@ -1005,7 +1005,7 @@ { "boxShadow": "none", "widgetName": "Button5", - "onClick": "{{closeModal('InsertModal')}}", + "onClick": "{{closeModal(InsertModal.name)}}", "buttonColor": "{{appsmith.theme.colors.primaryColor}}", "displayName": "Button", "iconSVG": "/static/media/icon.cca02633.svg", @@ -1044,7 +1044,7 @@ { "boxShadow": "none", "widgetName": "runInsertQuery", - "onClick": "{{insertRecord.run(() => {\nselectRecords.run();\t\t\t\tresetWidget('InsertModal', true);\ncloseModal('InsertModal'), () => {};})}}", + "onClick": "{{insertRecord.run(() => {\nselectRecords.run();\t\t\t\tresetWidget('InsertModal', true);\ncloseModal(InsertModal.name), () => {};})}}", "buttonColor": "{{appsmith.theme.colors.primaryColor}}", "dynamicPropertyPathList": [ { diff --git a/app/client/cypress/fixtures/Datatypes/UUIDDTdsl.json b/app/client/cypress/fixtures/Datatypes/UUIDDTdsl.json index db65a3665a0c..999e9497d7d5 100644 --- a/app/client/cypress/fixtures/Datatypes/UUIDDTdsl.json +++ b/app/client/cypress/fixtures/Datatypes/UUIDDTdsl.json @@ -69,7 +69,7 @@ { "boxShadow": "none", "widgetName": "IconButton1Copy", - "onClick": "{{closeModal('UpdateModal')}}", + "onClick": "{{closeModal(UpdateModal.name)}}", "buttonColor": "{{appsmith.theme.colors.primaryColor}}", "displayName": "Icon button", "iconSVG": "/static/media/icon.1a0c634a.svg", @@ -345,7 +345,7 @@ "resetFormOnClick": false, "boxShadow": "none", "widgetName": "runUpdateQuery", - "onClick": "{{updateRecord.run(() => {closeModal('UpdateModal'), () => {};selectRecords.run() })}}", + "onClick": "{{updateRecord.run(() => {closeModal(UpdateModal.name), () => {};selectRecords.run() })}}", "buttonColor": "#c084fc", "dynamicPropertyPathList": [ { @@ -730,7 +730,7 @@ { "boxShadow": "none", "widgetName": "InsertButton", - "onClick": "{{showModal('InsertModal')}}", + "onClick": "{{showModal(InsertModal.name)}}", "buttonColor": "{{appsmith.theme.colors.primaryColor}}", "dynamicPropertyPathList": [ { @@ -780,7 +780,7 @@ { "boxShadow": "none", "widgetName": "UpdateButton", - "onClick": "{{showModal('UpdateModal')}}", + "onClick": "{{showModal(UpdateModal.name)}}", "buttonColor": "{{appsmith.theme.colors.primaryColor}}", "dynamicPropertyPathList": [], "displayName": "Button", @@ -872,7 +872,7 @@ { "boxShadow": "none", "widgetName": "IconButton1", - "onClick": "{{closeModal('InsertModal')}}", + "onClick": "{{closeModal(InsertModal.name)}}", "buttonColor": "{{appsmith.theme.colors.primaryColor}}", "displayName": "Icon button", "iconSVG": "/static/media/icon.1a0c634a.svg", @@ -947,7 +947,7 @@ { "boxShadow": "none", "widgetName": "runInsertQuery", - "onClick": "{{insertRecord.run(() => {selectRecords.run();resetWidget('InsertModal', true);closeModal('InsertModal'), () => {};})}}", + "onClick": "{{insertRecord.run(() => {selectRecords.run();resetWidget('InsertModal', true);closeModal(InsertModal.name), () => {};})}}", "buttonColor": "#c084fc", "dynamicPropertyPathList": [ { diff --git a/app/client/cypress/fixtures/Datatypes/mySQLdsl.json b/app/client/cypress/fixtures/Datatypes/mySQLdsl.json index 5790d38b7fdc..01930867261b 100644 --- a/app/client/cypress/fixtures/Datatypes/mySQLdsl.json +++ b/app/client/cypress/fixtures/Datatypes/mySQLdsl.json @@ -1897,7 +1897,7 @@ { "boxShadow": "none", "widgetName": "runUpdateQuery", - "onClick": "{{updateRecord.run(() => {closeModal('UpdateModal'), () => {};\nselectRecords.run()\t\t\t\t\t\t\t\t\t\t\t\t })}}", + "onClick": "{{updateRecord.run(() => {closeModal(UpdateModal.name), () => {};\nselectRecords.run()\t\t\t\t\t\t\t\t\t\t\t\t })}}", "buttonColor": "{{appsmith.theme.colors.primaryColor}}", "dynamicPropertyPathList": [ { @@ -1948,7 +1948,7 @@ { "boxShadow": "none", "widgetName": "Button5Copy", - "onClick": "{{closeModal('UpdateModal')}}", + "onClick": "{{closeModal(UpdateModal.name)}}", "buttonColor": "{{appsmith.theme.colors.primaryColor}}", "displayName": "Button", "iconSVG": "/static/media/icon.cca02633.svg", @@ -2005,7 +2005,7 @@ { "boxShadow": "none", "widgetName": "IconButton1Copy", - "onClick": "{{closeModal('InsertModal')}}", + "onClick": "{{closeModal(InsertModal.name)}}", "buttonColor": "{{appsmith.theme.colors.primaryColor}}", "displayName": "Icon button", "iconSVG": "/static/media/icon.1a0c634a.svg", @@ -2824,7 +2824,7 @@ { "boxShadow": "none", "widgetName": "InsertButton", - "onClick": "{{showModal('InsertModal')}}", + "onClick": "{{showModal(InsertModal.name)}}", "buttonColor": "{{appsmith.theme.colors.primaryColor}}", "dynamicPropertyPathList": [ { @@ -2874,7 +2874,7 @@ { "boxShadow": "none", "widgetName": "UpdateButton", - "onClick": "{{showModal('UpdateModal')}}", + "onClick": "{{showModal(UpdateModal.name)}}", "buttonColor": "{{appsmith.theme.colors.primaryColor}}", "dynamicPropertyPathList": [], "displayName": "Button", @@ -4590,7 +4590,7 @@ { "boxShadow": "none", "widgetName": "Button5", - "onClick": "{{closeModal('InsertModal')}}", + "onClick": "{{closeModal(InsertModal.name)}}", "buttonColor": "{{appsmith.theme.colors.primaryColor}}", "displayName": "Button", "iconSVG": "/static/media/icon.cca02633.svg", @@ -4631,7 +4631,7 @@ { "boxShadow": "none", "widgetName": "runInsertQuery", - "onClick": "{{insertRecord.run(() => {\nselectRecords.run();\t\t\t\tresetWidget('InsertModal', true);\ncloseModal('InsertModal'), () => {};})}}", + "onClick": "{{insertRecord.run(() => {\nselectRecords.run();\t\t\t\tresetWidget('InsertModal', true);\ncloseModal(InsertModal.name), () => {};})}}", "buttonColor": "{{appsmith.theme.colors.primaryColor}}", "dynamicPropertyPathList": [ { @@ -4698,7 +4698,7 @@ { "boxShadow": "none", "widgetName": "IconButton1", - "onClick": "{{closeModal('InsertModal')}}", + "onClick": "{{closeModal(InsertModal.name)}}", "buttonColor": "{{appsmith.theme.colors.primaryColor}}", "displayName": "Icon button", "iconSVG": "/static/media/icon.1a0c634a.svg", diff --git a/app/client/cypress/fixtures/DynamicHeightModalDsl.json b/app/client/cypress/fixtures/DynamicHeightModalDsl.json index 8166882c652f..4cd9bd1006a8 100644 --- a/app/client/cypress/fixtures/DynamicHeightModalDsl.json +++ b/app/client/cypress/fixtures/DynamicHeightModalDsl.json @@ -80,7 +80,7 @@ "key": "borderRadius" } ], - "onClick": "{{closeModal('Modal1')}}" + "onClick": "{{closeModal(Modal1.name)}}" }, { "isVisible": true, @@ -170,7 +170,7 @@ "key": "borderRadius" } ], - "onClick": "{{closeModal('Modal1')}}", + "onClick": "{{closeModal(Modal1.name)}}", "originalTopRow": 18, "originalBottomRow": 22 }, diff --git a/app/client/cypress/fixtures/ListVulnerabilityDSL.json b/app/client/cypress/fixtures/ListVulnerabilityDSL.json index 018f78b25cd5..147c1d7d7b73 100644 --- a/app/client/cypress/fixtures/ListVulnerabilityDSL.json +++ b/app/client/cypress/fixtures/ListVulnerabilityDSL.json @@ -798,7 +798,7 @@ { "boxShadow": "none", "widgetName": "IconButton1", - "onClick": "{{closeModal('Modal1')}}", + "onClick": "{{closeModal(Modal1.name)}}", "buttonColor": "{{appsmith.theme.colors.primaryColor}}", "displayName": "Icon button", "iconSVG": "/static/media/icon.1a0c634ac75f9fa6b6ae7a8df882a3ba.svg", @@ -876,7 +876,7 @@ "resetFormOnClick": false, "boxShadow": "none", "widgetName": "Button3", - "onClick": "{{closeModal('Modal1')}}", + "onClick": "{{closeModal(Modal1.name)}}", "buttonColor": "{{appsmith.theme.colors.primaryColor}}", "displayName": "Button", "iconSVG": "/static/media/icon.cca026338f1c8eb6df8ba03d084c2fca.svg", diff --git a/app/client/cypress/fixtures/Listv2/ListWithModalStatCheckboxAndRadio.json b/app/client/cypress/fixtures/Listv2/ListWithModalStatCheckboxAndRadio.json index c56e74a8ad1d..d65aa35bc7fb 100644 --- a/app/client/cypress/fixtures/Listv2/ListWithModalStatCheckboxAndRadio.json +++ b/app/client/cypress/fixtures/Listv2/ListWithModalStatCheckboxAndRadio.json @@ -291,7 +291,7 @@ { "boxShadow": "none", "widgetName": "IconButton1", - "onClick": "{{showModal('Modal1')}}", + "onClick": "{{showModal(Modal1.name)}}", "buttonColor": "{{appsmith.theme.colors.primaryColor}}", "displayName": "Icon button", "iconSVG": "/static/media/icon.1a0c634ac75f9fa6b6ae7a8df882a3ba.svg", @@ -484,7 +484,7 @@ } ], "labelPosition": "Top", - "onSelectionChange": "{{showModal('Modal2')}}", + "onSelectionChange": "{{showModal(Modal2.name)}}", "options": [ { "label": "Yes", @@ -544,7 +544,7 @@ } ], "labelPosition": "Top", - "onSelectionChange": "{{showModal('Modal2')}}", + "onSelectionChange": "{{showModal(Modal2.name)}}", "options": [ { "label": "Blue", @@ -704,7 +704,7 @@ { "boxShadow": "none", "widgetName": "IconButton2", - "onClick": "{{closeModal('Modal1')}}", + "onClick": "{{closeModal(Modal1.name)}}", "buttonColor": "{{appsmith.theme.colors.primaryColor}}", "displayName": "Icon button", "iconSVG": "/static/media/icon.1a0c634ac75f9fa6b6ae7a8df882a3ba.svg", @@ -793,7 +793,7 @@ "resetFormOnClick": false, "boxShadow": "none", "widgetName": "Button1", - "onClick": "{{closeModal('Modal1')}}", + "onClick": "{{closeModal(Modal1.name)}}", "buttonColor": "{{appsmith.theme.colors.primaryColor}}", "displayName": "Button", "iconSVG": "/static/media/icon.cca026338f1c8eb6df8ba03d084c2fca.svg", @@ -998,7 +998,7 @@ { "boxShadow": "none", "widgetName": "IconButton4", - "onClick": "{{closeModal('Modal2')}}", + "onClick": "{{closeModal(Modal2.name)}}", "buttonColor": "{{appsmith.theme.colors.primaryColor}}", "displayName": "Icon button", "iconSVG": "/static/media/icon.1a0c634ac75f9fa6b6ae7a8df882a3ba.svg", @@ -1087,7 +1087,7 @@ "resetFormOnClick": false, "boxShadow": "none", "widgetName": "Button3", - "onClick": "{{closeModal('Modal2')}}", + "onClick": "{{closeModal(Modal2.name)}}", "buttonColor": "{{appsmith.theme.colors.primaryColor}}", "displayName": "Button", "iconSVG": "/static/media/icon.cca026338f1c8eb6df8ba03d084c2fca.svg", diff --git a/app/client/cypress/fixtures/ModalDsl.json b/app/client/cypress/fixtures/ModalDsl.json index b7f974d98125..4aac3a1d3e2a 100644 --- a/app/client/cypress/fixtures/ModalDsl.json +++ b/app/client/cypress/fixtures/ModalDsl.json @@ -50,7 +50,7 @@ "bottomRow": 1, "parentId": "yyyrxs383y", "widgetId": "kxdvolusyp", - "onClick": "{{closeModal('Modal1')}}" + "onClick": "{{closeModal(Modal1.name)}}" }, { "isVisible": true, diff --git a/app/client/cypress/fixtures/PartialImportExport/PartialImportExportSampleApp.json b/app/client/cypress/fixtures/PartialImportExport/PartialImportExportSampleApp.json index 7ce106360bb9..17317c2c8a1b 100644 --- a/app/client/cypress/fixtures/PartialImportExport/PartialImportExportSampleApp.json +++ b/app/client/cypress/fixtures/PartialImportExport/PartialImportExportSampleApp.json @@ -249,7 +249,7 @@ "boxShadow": "none", "isDerived": true, "computedValue": "", - "onClick": "{{showModal('Delete_Modal')}}", + "onClick": "{{showModal(Delete_Modal.name)}}", "buttonColor": "#DD4B34", "buttonStyle": "rgb(3, 179, 101)", "index": 5.0, @@ -684,7 +684,7 @@ "boxShadow": "none", "isDerived": true, "computedValue": "", - "onClick": "{{showModal('Delete_Modal')}}", + "onClick": "{{showModal(Delete_Modal.name)}}", "buttonColor": "#DD4B34", "buttonStyle": "rgb(3, 179, 101)", "index": 5.0, @@ -786,7 +786,7 @@ "boxShadow": "none", "widgetName": "add_btn", "rightColumn": 59.0, - "onClick": "{{showModal('Insert_Modal')}}", + "onClick": "{{showModal(Insert_Modal.name)}}", "iconName": "add", "buttonColor": "{{appsmith.theme.colors.primaryColor}}", "widgetId": "nh3cu4lb1g", @@ -887,7 +887,7 @@ { "boxShadow": "none", "widgetName": "Button1", - "onClick": "{{closeModal('Delete_Modal')}}", + "onClick": "{{closeModal(Delete_Modal.name)}}", "dynamicPropertyPathList": [], "buttonColor": "#2E3D49", "topRow": 17.0, @@ -913,7 +913,7 @@ { "boxShadow": "none", "widgetName": "Delete_Button", - "onClick": "{{DeleteQuery.run(() => SelectQuery.run(() => closeModal('Delete_Modal')), () => {})}}", + "onClick": "{{DeleteQuery.run(() => SelectQuery.run(() => closeModal(Delete_Modal.name)), () => {})}}", "dynamicPropertyPathList": [{ "key": "onClick" }], "buttonColor": "#DD4B34", "topRow": 17.0, @@ -1350,7 +1350,7 @@ ], "displayName": "JSON Form", "iconSVG": "/static/media/icon.6bacf7df.svg", - "onSubmit": "{{InsertQuery.run(\n\t() => SelectQuery.run()\n\t\t\t\t\t.then(() => closeModal('Insert_Modal')), \n\t(error) => showAlert(`Error while inserting resource!\\n ${error}`,'error'))\n}}", + "onSubmit": "{{InsertQuery.run(\n\t() => SelectQuery.run()\n\t\t\t\t\t.then(() => closeModal(Insert_Modal.name)), \n\t(error) => showAlert(`Error while inserting resource!\\n ${error}`,'error'))\n}}", "topRow": 0.0, "bottomRow": 81.0, "fieldLimitExceeded": false, diff --git a/app/client/cypress/fixtures/PartialImportExport/WidgetsExportedOnly.json b/app/client/cypress/fixtures/PartialImportExport/WidgetsExportedOnly.json index cbcee49d64fd..286b43c9a18e 100644 --- a/app/client/cypress/fixtures/PartialImportExport/WidgetsExportedOnly.json +++ b/app/client/cypress/fixtures/PartialImportExport/WidgetsExportedOnly.json @@ -1 +1 @@ -{"clientSchemaVersion":1,"serverSchemaVersion":7,"widgets":"{\"widgets\":[{\"widgetId\":\"hpy3pb4xft\",\"list\":[{\"boxShadow\":\"{{appsmith.theme.boxShadow.appBoxShadow}}\",\"onSort\":\"{{SelectQuery.run()}}\",\"isVisibleDownload\":true,\"iconSVG\":\"/static/media/icon.db8a9cbd.svg\",\"topRow\":6,\"isSortable\":true,\"onPageChange\":\"{{SelectQuery.run()}}\",\"type\":\"TABLE_WIDGET_V2\",\"animateLoading\":true,\"dynamicBindingPathList\":[{\"key\":\"tableData\"},{\"key\":\"derivedColumns.customColumn1.buttonLabel\"},{\"key\":\"primaryColumns.customColumn1.buttonLabel\"},{\"key\":\"accentColor\"},{\"key\":\"borderRadius\"},{\"key\":\"boxShadow\"},{\"key\":\"primaryColumns.customColumn1.borderRadius\"},{\"key\":\"primaryColumns.id.computedValue\"},{\"key\":\"primaryColumns.gender.computedValue\"},{\"key\":\"primaryColumns.latitude.computedValue\"},{\"key\":\"primaryColumns.longitude.computedValue\"},{\"key\":\"primaryColumns.dob.computedValue\"},{\"key\":\"primaryColumns.phone.computedValue\"},{\"key\":\"primaryColumns.email.computedValue\"},{\"key\":\"primaryColumns.image.computedValue\"},{\"key\":\"primaryColumns.country.computedValue\"},{\"key\":\"primaryColumns.name.computedValue\"},{\"key\":\"primaryColumns.created_at.computedValue\"},{\"key\":\"primaryColumns.updated_at.computedValue\"}],\"leftColumn\":0,\"delimiter\":\",\",\"defaultSelectedRowIndex\":\"0\",\"accentColor\":\"{{appsmith.theme.colors.primaryColor}}\",\"isVisibleFilters\":true,\"isVisible\":\"true\",\"enableClientSideSearch\":true,\"version\":3,\"totalRecordsCount\":0,\"isLoading\":false,\"onSearchTextChanged\":\"{{SelectQuery.run()}}\",\"childStylesheet\":{\"button\":{\"boxShadow\":\"none\",\"borderRadius\":\"{{appsmith.theme.borderRadius.appBorderRadius}}\",\"buttonColor\":\"{{appsmith.theme.colors.primaryColor}}\"},\"iconButton\":{\"boxShadow\":\"none\",\"borderRadius\":\"{{appsmith.theme.borderRadius.appBorderRadius}}\",\"menuColor\":\"{{appsmith.theme.colors.primaryColor}}\"},\"menuButton\":{\"boxShadow\":\"none\",\"borderRadius\":\"{{appsmith.theme.borderRadius.appBorderRadius}}\",\"menuColor\":\"{{appsmith.theme.colors.primaryColor}}\"}},\"borderRadius\":\"{{appsmith.theme.borderRadius.appBorderRadius}}\",\"columnUpdatedAt\":1704697943255,\"primaryColumnId\":\"id\",\"columnSizeMap\":{\"task\":245,\"step\":62,\"status\":75},\"widgetName\":\"data_table\",\"defaultPageSize\":0,\"columnOrder\":[\"id\",\"gender\",\"latitude\",\"longitude\",\"dob\",\"phone\",\"email\",\"image\",\"country\",\"name\",\"created_at\",\"updated_at\",\"customColumn1\"],\"dynamicPropertyPathList\":[{\"key\":\"primaryColumns.customColumn1.borderRadius\"},{\"key\":\"tableData\"}],\"displayName\":\"Table\",\"bottomRow\":85,\"parentRowSpace\":10,\"hideCard\":false,\"parentColumnSpace\":16.3125,\"dynamicTriggerPathList\":[{\"key\":\"primaryColumns.customColumn1.onClick\"},{\"key\":\"onPageChange\"},{\"key\":\"onSearchTextChanged\"},{\"key\":\"onSort\"}],\"primaryColumns\":{\"customColumn1\":{\"isCellVisible\":true,\"boxShadow\":\"none\",\"isDerived\":true,\"computedValue\":\"\",\"onClick\":\"{{showModal('Delete_Modal')}}\",\"buttonColor\":\"#DD4B34\",\"buttonStyle\":\"rgb(3, 179, 101)\",\"index\":5,\"isVisible\":true,\"label\":\"Delete\",\"labelColor\":\"#FFFFFF\",\"buttonLabel\":\"{{data_table.processedTableData.map((currentRow, currentIndex) => ( 'Delete'))}}\",\"columnType\":\"button\",\"borderRadius\":\"{{data_table.processedTableData.map((currentRow, currentIndex) => ( appsmith.theme.borderRadius.appBorderRadius))}}\",\"menuColor\":\"#03B365\",\"width\":150,\"enableFilter\":true,\"enableSort\":true,\"id\":\"customColumn1\",\"isDisabled\":false,\"buttonLabelColor\":\"#FFFFFF\",\"sticky\":\"right\"},\"id\":{\"allowCellWrapping\":false,\"allowSameOptionsInNewRow\":true,\"index\":0,\"width\":150,\"originalId\":\"id\",\"id\":\"id\",\"alias\":\"id\",\"horizontalAlignment\":\"LEFT\",\"verticalAlignment\":\"CENTER\",\"columnType\":\"number\",\"textColor\":\"\",\"textSize\":\"0.875rem\",\"fontStyle\":\"\",\"enableFilter\":true,\"enableSort\":true,\"isVisible\":true,\"isDisabled\":false,\"isCellEditable\":false,\"isEditable\":false,\"isCellVisible\":true,\"isDerived\":false,\"label\":\"id\",\"isSaveVisible\":true,\"isDiscardVisible\":true,\"computedValue\":\"{{data_table.processedTableData.map((currentRow, currentIndex) => ( currentRow[\\\"id\\\"]))}}\",\"sticky\":\"\",\"validation\":{},\"currencyCode\":\"USD\",\"decimals\":0,\"thousandSeparator\":true,\"notation\":\"standard\",\"cellBackground\":\"\"},\"gender\":{\"allowCellWrapping\":false,\"allowSameOptionsInNewRow\":true,\"index\":1,\"width\":150,\"originalId\":\"gender\",\"id\":\"gender\",\"alias\":\"gender\",\"horizontalAlignment\":\"LEFT\",\"verticalAlignment\":\"CENTER\",\"columnType\":\"text\",\"textColor\":\"\",\"textSize\":\"0.875rem\",\"fontStyle\":\"\",\"enableFilter\":true,\"enableSort\":true,\"isVisible\":true,\"isDisabled\":false,\"isCellEditable\":false,\"isEditable\":false,\"isCellVisible\":true,\"isDerived\":false,\"label\":\"gender\",\"isSaveVisible\":true,\"isDiscardVisible\":true,\"computedValue\":\"{{data_table.processedTableData.map((currentRow, currentIndex) => ( currentRow[\\\"gender\\\"]))}}\",\"sticky\":\"\",\"validation\":{},\"currencyCode\":\"USD\",\"decimals\":0,\"thousandSeparator\":true,\"notation\":\"standard\",\"cellBackground\":\"\"},\"latitude\":{\"allowCellWrapping\":false,\"allowSameOptionsInNewRow\":true,\"index\":2,\"width\":150,\"originalId\":\"latitude\",\"id\":\"latitude\",\"alias\":\"latitude\",\"horizontalAlignment\":\"LEFT\",\"verticalAlignment\":\"CENTER\",\"columnType\":\"text\",\"textColor\":\"\",\"textSize\":\"0.875rem\",\"fontStyle\":\"\",\"enableFilter\":true,\"enableSort\":true,\"isVisible\":true,\"isDisabled\":false,\"isCellEditable\":false,\"isEditable\":false,\"isCellVisible\":true,\"isDerived\":false,\"label\":\"latitude\",\"isSaveVisible\":true,\"isDiscardVisible\":true,\"computedValue\":\"{{data_table.processedTableData.map((currentRow, currentIndex) => ( currentRow[\\\"latitude\\\"]))}}\",\"sticky\":\"\",\"validation\":{},\"currencyCode\":\"USD\",\"decimals\":0,\"thousandSeparator\":true,\"notation\":\"standard\",\"cellBackground\":\"\"},\"longitude\":{\"allowCellWrapping\":false,\"allowSameOptionsInNewRow\":true,\"index\":3,\"width\":150,\"originalId\":\"longitude\",\"id\":\"longitude\",\"alias\":\"longitude\",\"horizontalAlignment\":\"LEFT\",\"verticalAlignment\":\"CENTER\",\"columnType\":\"text\",\"textColor\":\"\",\"textSize\":\"0.875rem\",\"fontStyle\":\"\",\"enableFilter\":true,\"enableSort\":true,\"isVisible\":true,\"isDisabled\":false,\"isCellEditable\":false,\"isEditable\":false,\"isCellVisible\":true,\"isDerived\":false,\"label\":\"longitude\",\"isSaveVisible\":true,\"isDiscardVisible\":true,\"computedValue\":\"{{data_table.processedTableData.map((currentRow, currentIndex) => ( currentRow[\\\"longitude\\\"]))}}\",\"sticky\":\"\",\"validation\":{},\"currencyCode\":\"USD\",\"decimals\":0,\"thousandSeparator\":true,\"notation\":\"standard\",\"cellBackground\":\"\"},\"dob\":{\"allowCellWrapping\":false,\"allowSameOptionsInNewRow\":true,\"index\":4,\"width\":150,\"originalId\":\"dob\",\"id\":\"dob\",\"alias\":\"dob\",\"horizontalAlignment\":\"LEFT\",\"verticalAlignment\":\"CENTER\",\"columnType\":\"date\",\"textColor\":\"\",\"textSize\":\"0.875rem\",\"fontStyle\":\"\",\"enableFilter\":true,\"enableSort\":true,\"isVisible\":true,\"isDisabled\":false,\"isCellEditable\":false,\"isEditable\":false,\"isCellVisible\":true,\"isDerived\":false,\"label\":\"dob\",\"isSaveVisible\":true,\"isDiscardVisible\":true,\"computedValue\":\"{{data_table.processedTableData.map((currentRow, currentIndex) => ( currentRow[\\\"dob\\\"]))}}\",\"sticky\":\"\",\"validation\":{},\"currencyCode\":\"USD\",\"decimals\":0,\"thousandSeparator\":true,\"notation\":\"standard\",\"cellBackground\":\"\"},\"phone\":{\"allowCellWrapping\":false,\"allowSameOptionsInNewRow\":true,\"index\":5,\"width\":150,\"originalId\":\"phone\",\"id\":\"phone\",\"alias\":\"phone\",\"horizontalAlignment\":\"LEFT\",\"verticalAlignment\":\"CENTER\",\"columnType\":\"text\",\"textColor\":\"\",\"textSize\":\"0.875rem\",\"fontStyle\":\"\",\"enableFilter\":true,\"enableSort\":true,\"isVisible\":true,\"isDisabled\":false,\"isCellEditable\":false,\"isEditable\":false,\"isCellVisible\":true,\"isDerived\":false,\"label\":\"phone\",\"isSaveVisible\":true,\"isDiscardVisible\":true,\"computedValue\":\"{{data_table.processedTableData.map((currentRow, currentIndex) => ( currentRow[\\\"phone\\\"]))}}\",\"sticky\":\"\",\"validation\":{},\"currencyCode\":\"USD\",\"decimals\":0,\"thousandSeparator\":true,\"notation\":\"standard\",\"cellBackground\":\"\"},\"email\":{\"allowCellWrapping\":false,\"allowSameOptionsInNewRow\":true,\"index\":6,\"width\":150,\"originalId\":\"email\",\"id\":\"email\",\"alias\":\"email\",\"horizontalAlignment\":\"LEFT\",\"verticalAlignment\":\"CENTER\",\"columnType\":\"text\",\"textColor\":\"\",\"textSize\":\"0.875rem\",\"fontStyle\":\"\",\"enableFilter\":true,\"enableSort\":true,\"isVisible\":true,\"isDisabled\":false,\"isCellEditable\":false,\"isEditable\":false,\"isCellVisible\":true,\"isDerived\":false,\"label\":\"email\",\"isSaveVisible\":true,\"isDiscardVisible\":true,\"computedValue\":\"{{data_table.processedTableData.map((currentRow, currentIndex) => ( currentRow[\\\"email\\\"]))}}\",\"sticky\":\"\",\"validation\":{},\"currencyCode\":\"USD\",\"decimals\":0,\"thousandSeparator\":true,\"notation\":\"standard\",\"cellBackground\":\"\"},\"image\":{\"allowCellWrapping\":false,\"allowSameOptionsInNewRow\":true,\"index\":7,\"width\":150,\"originalId\":\"image\",\"id\":\"image\",\"alias\":\"image\",\"horizontalAlignment\":\"LEFT\",\"verticalAlignment\":\"CENTER\",\"columnType\":\"text\",\"textColor\":\"\",\"textSize\":\"0.875rem\",\"fontStyle\":\"\",\"enableFilter\":true,\"enableSort\":true,\"isVisible\":true,\"isDisabled\":false,\"isCellEditable\":false,\"isEditable\":false,\"isCellVisible\":true,\"isDerived\":false,\"label\":\"image\",\"isSaveVisible\":true,\"isDiscardVisible\":true,\"computedValue\":\"{{data_table.processedTableData.map((currentRow, currentIndex) => ( currentRow[\\\"image\\\"]))}}\",\"sticky\":\"\",\"validation\":{},\"currencyCode\":\"USD\",\"decimals\":0,\"thousandSeparator\":true,\"notation\":\"standard\",\"cellBackground\":\"\"},\"country\":{\"allowCellWrapping\":false,\"allowSameOptionsInNewRow\":true,\"index\":8,\"width\":150,\"originalId\":\"country\",\"id\":\"country\",\"alias\":\"country\",\"horizontalAlignment\":\"LEFT\",\"verticalAlignment\":\"CENTER\",\"columnType\":\"text\",\"textColor\":\"\",\"textSize\":\"0.875rem\",\"fontStyle\":\"\",\"enableFilter\":true,\"enableSort\":true,\"isVisible\":true,\"isDisabled\":false,\"isCellEditable\":false,\"isEditable\":false,\"isCellVisible\":true,\"isDerived\":false,\"label\":\"country\",\"isSaveVisible\":true,\"isDiscardVisible\":true,\"computedValue\":\"{{data_table.processedTableData.map((currentRow, currentIndex) => ( currentRow[\\\"country\\\"]))}}\",\"sticky\":\"\",\"validation\":{},\"currencyCode\":\"USD\",\"decimals\":0,\"thousandSeparator\":true,\"notation\":\"standard\",\"cellBackground\":\"\"},\"name\":{\"allowCellWrapping\":false,\"allowSameOptionsInNewRow\":true,\"index\":9,\"width\":150,\"originalId\":\"name\",\"id\":\"name\",\"alias\":\"name\",\"horizontalAlignment\":\"LEFT\",\"verticalAlignment\":\"CENTER\",\"columnType\":\"text\",\"textColor\":\"\",\"textSize\":\"0.875rem\",\"fontStyle\":\"\",\"enableFilter\":true,\"enableSort\":true,\"isVisible\":true,\"isDisabled\":false,\"isCellEditable\":false,\"isEditable\":false,\"isCellVisible\":true,\"isDerived\":false,\"label\":\"name\",\"isSaveVisible\":true,\"isDiscardVisible\":true,\"computedValue\":\"{{data_table.processedTableData.map((currentRow, currentIndex) => ( currentRow[\\\"name\\\"]))}}\",\"sticky\":\"\",\"validation\":{},\"currencyCode\":\"USD\",\"decimals\":0,\"thousandSeparator\":true,\"notation\":\"standard\",\"cellBackground\":\"\"},\"created_at\":{\"allowCellWrapping\":false,\"allowSameOptionsInNewRow\":true,\"index\":10,\"width\":150,\"originalId\":\"created_at\",\"id\":\"created_at\",\"alias\":\"created_at\",\"horizontalAlignment\":\"LEFT\",\"verticalAlignment\":\"CENTER\",\"columnType\":\"text\",\"textColor\":\"\",\"textSize\":\"0.875rem\",\"fontStyle\":\"\",\"enableFilter\":true,\"enableSort\":true,\"isVisible\":true,\"isDisabled\":false,\"isCellEditable\":false,\"isEditable\":false,\"isCellVisible\":true,\"isDerived\":false,\"label\":\"created_at\",\"isSaveVisible\":true,\"isDiscardVisible\":true,\"computedValue\":\"{{data_table.processedTableData.map((currentRow, currentIndex) => ( currentRow[\\\"created_at\\\"]))}}\",\"sticky\":\"\",\"validation\":{},\"currencyCode\":\"USD\",\"decimals\":0,\"thousandSeparator\":true,\"notation\":\"standard\",\"cellBackground\":\"\"},\"updated_at\":{\"allowCellWrapping\":false,\"allowSameOptionsInNewRow\":true,\"index\":11,\"width\":150,\"originalId\":\"updated_at\",\"id\":\"updated_at\",\"alias\":\"updated_at\",\"horizontalAlignment\":\"LEFT\",\"verticalAlignment\":\"CENTER\",\"columnType\":\"text\",\"textColor\":\"\",\"textSize\":\"0.875rem\",\"fontStyle\":\"\",\"enableFilter\":true,\"enableSort\":true,\"isVisible\":true,\"isDisabled\":false,\"isCellEditable\":false,\"isEditable\":false,\"isCellVisible\":true,\"isDerived\":false,\"label\":\"updated_at\",\"isSaveVisible\":true,\"isDiscardVisible\":true,\"computedValue\":\"{{data_table.processedTableData.map((currentRow, currentIndex) => ( currentRow[\\\"updated_at\\\"]))}}\",\"sticky\":\"\",\"validation\":{},\"currencyCode\":\"USD\",\"decimals\":0,\"thousandSeparator\":true,\"notation\":\"standard\",\"cellBackground\":\"\"}},\"key\":\"zba5qel0au\",\"derivedColumns\":{\"customColumn1\":{\"isCellVisible\":true,\"boxShadow\":\"none\",\"isDerived\":true,\"computedValue\":\"\",\"onClick\":\"{{showModal('Delete_Modal')}}\",\"buttonColor\":\"#DD4B34\",\"buttonStyle\":\"rgb(3, 179, 101)\",\"index\":5,\"isVisible\":true,\"label\":\"Delete\",\"labelColor\":\"#FFFFFF\",\"buttonLabel\":\"{{data_table.processedTableData.map((currentRow, currentIndex) => ( 'Delete'))}}\",\"columnType\":\"button\",\"borderRadius\":\"0px\",\"menuColor\":\"#03B365\",\"width\":150,\"enableFilter\":true,\"enableSort\":true,\"id\":\"customColumn1\",\"isDisabled\":false,\"buttonLabelColor\":\"#FFFFFF\"}},\"labelTextSize\":\"0.875rem\",\"rightColumn\":64,\"textSize\":\"0.875rem\",\"widgetId\":\"hpy3pb4xft\",\"enableServerSideFiltering\":false,\"tableData\":\"{{SelectQuery.data}}\",\"label\":\"Data\",\"searchKey\":\"\",\"parentId\":\"59rw5mx0bq\",\"serverSidePaginationEnabled\":true,\"renderMode\":\"CANVAS\",\"horizontalAlignment\":\"LEFT\",\"isVisibleSearch\":true,\"isVisiblePagination\":true,\"verticalAlignment\":\"CENTER\"}],\"parentId\":\"59rw5mx0bq\"},{\"widgetId\":\"urzv99hdc8\",\"list\":[{\"boxShadow\":\"none\",\"widgetName\":\"Text16\",\"dynamicPropertyPathList\":[{\"key\":\"fontSize\"}],\"topRow\":1,\"bottomRow\":5,\"parentRowSpace\":10,\"type\":\"TEXT_WIDGET\",\"parentColumnSpace\":11.78515625,\"dynamicTriggerPathList\":[],\"overflow\":\"NONE\",\"fontFamily\":\"{{appsmith.theme.fontFamily.appFont}}\",\"leftColumn\":0,\"dynamicBindingPathList\":[{\"key\":\"fontFamily\"},{\"key\":\"text\"}],\"text\":\"public_users Data + {{JSObject1.addNumbers(3,7)}}\",\"labelTextSize\":\"0.875rem\",\"rightColumn\":54,\"textAlign\":\"LEFT\",\"dynamicHeight\":\"FIXED\",\"widgetId\":\"urzv99hdc8\",\"isVisible\":\"true\",\"fontStyle\":\"BOLD\",\"textColor\":\"#231F20\",\"version\":1,\"parentId\":\"59rw5mx0bq\",\"isLoading\":false,\"borderRadius\":\"0px\",\"maxDynamicHeight\":9000,\"fontSize\":\"1.5rem\",\"minDynamicHeight\":4}],\"parentId\":\"59rw5mx0bq\"},{\"widgetId\":\"xp5u9a9nzq\",\"list\":[{\"labelTextSize\":\"0.875rem\",\"boxShadow\":\"none\",\"widgetName\":\"refresh_btn\",\"rightColumn\":64,\"onClick\":\"{{SelectQuery.run()}}\",\"iconName\":\"refresh\",\"buttonColor\":\"{{appsmith.theme.colors.primaryColor}}\",\"widgetId\":\"xp5u9a9nzq\",\"topRow\":1,\"bottomRow\":5,\"parentRowSpace\":10,\"isVisible\":\"true\",\"type\":\"ICON_BUTTON_WIDGET\",\"version\":1,\"parentId\":\"59rw5mx0bq\",\"isLoading\":false,\"parentColumnSpace\":12.0703125,\"dynamicTriggerPathList\":[{\"key\":\"onClick\"}],\"borderRadius\":\"{{appsmith.theme.borderRadius.appBorderRadius}}\",\"leftColumn\":60,\"dynamicBindingPathList\":[{\"key\":\"buttonColor\"},{\"key\":\"borderRadius\"}],\"buttonVariant\":\"PRIMARY\",\"isDisabled\":false}],\"parentId\":\"59rw5mx0bq\"},{\"widgetId\":\"nh3cu4lb1g\",\"list\":[{\"labelTextSize\":\"0.875rem\",\"boxShadow\":\"none\",\"widgetName\":\"add_btn\",\"rightColumn\":59,\"onClick\":\"{{showModal('Insert_Modal')}}\",\"iconName\":\"add\",\"buttonColor\":\"{{appsmith.theme.colors.primaryColor}}\",\"widgetId\":\"nh3cu4lb1g\",\"topRow\":1,\"bottomRow\":5,\"parentRowSpace\":10,\"isVisible\":\"true\",\"type\":\"ICON_BUTTON_WIDGET\",\"version\":1,\"parentId\":\"59rw5mx0bq\",\"isLoading\":false,\"parentColumnSpace\":12.0703125,\"dynamicTriggerPathList\":[{\"key\":\"onClick\"}],\"borderRadius\":\"{{appsmith.theme.borderRadius.appBorderRadius}}\",\"leftColumn\":55,\"dynamicBindingPathList\":[{\"key\":\"buttonColor\"},{\"key\":\"borderRadius\"}],\"buttonVariant\":\"PRIMARY\",\"isDisabled\":false}],\"parentId\":\"59rw5mx0bq\"},{\"widgetId\":\"35yoxo4oec\",\"list\":[{\"boxShadow\":\"none\",\"widgetName\":\"Alert_text\",\"dynamicPropertyPathList\":[{\"key\":\"fontSize\"}],\"topRow\":1,\"bottomRow\":5,\"type\":\"TEXT_WIDGET\",\"dynamicTriggerPathList\":[],\"overflow\":\"NONE\",\"fontFamily\":\"System Default\",\"leftColumn\":1,\"dynamicBindingPathList\":[],\"text\":\"Delete Row\",\"labelTextSize\":\"0.875rem\",\"rightColumn\":41,\"textAlign\":\"LEFT\",\"dynamicHeight\":\"FIXED\",\"widgetId\":\"35yoxo4oec\",\"isVisible\":\"true\",\"fontStyle\":\"BOLD\",\"textColor\":\"#231F20\",\"version\":1,\"parentId\":\"zi8fjakv8o\",\"isLoading\":false,\"borderRadius\":\"0px\",\"maxDynamicHeight\":9000,\"fontSize\":\"1.5rem\",\"minDynamicHeight\":4}],\"parentId\":\"zi8fjakv8o\"},{\"widgetId\":\"lryg8kw537\",\"list\":[{\"boxShadow\":\"none\",\"widgetName\":\"Button1\",\"onClick\":\"{{closeModal('Delete_Modal')}}\",\"dynamicPropertyPathList\":[],\"buttonColor\":\"#2E3D49\",\"topRow\":17,\"bottomRow\":21,\"type\":\"BUTTON_WIDGET\",\"dynamicTriggerPathList\":[{\"key\":\"onClick\"}],\"leftColumn\":34,\"dynamicBindingPathList\":[{\"key\":\"borderRadius\"}],\"text\":\"Cancel\",\"isDisabled\":false,\"labelTextSize\":\"0.875rem\",\"rightColumn\":46,\"isDefaultClickDisabled\":true,\"widgetId\":\"lryg8kw537\",\"isVisible\":\"true\",\"version\":1,\"recaptchaType\":\"V3\",\"parentId\":\"zi8fjakv8o\",\"isLoading\":false,\"borderRadius\":\"{{appsmith.theme.borderRadius.appBorderRadius}}\",\"buttonVariant\":\"TERTIARY\"}],\"parentId\":\"zi8fjakv8o\"},{\"widgetId\":\"qq02lh7ust\",\"list\":[{\"boxShadow\":\"none\",\"widgetName\":\"Delete_Button\",\"onClick\":\"{{DeleteQuery.run(() => SelectQuery.run(() => closeModal('Delete_Modal')), () => {})}}\",\"dynamicPropertyPathList\":[{\"key\":\"onClick\"}],\"buttonColor\":\"#DD4B34\",\"topRow\":17,\"bottomRow\":21,\"type\":\"BUTTON_WIDGET\",\"dynamicTriggerPathList\":[{\"key\":\"onClick\"}],\"leftColumn\":46,\"dynamicBindingPathList\":[{\"key\":\"borderRadius\"}],\"text\":\"Confirm\",\"isDisabled\":false,\"labelTextSize\":\"0.875rem\",\"rightColumn\":64,\"isDefaultClickDisabled\":true,\"widgetId\":\"qq02lh7ust\",\"isVisible\":\"true\",\"version\":1,\"recaptchaType\":\"V3\",\"parentId\":\"zi8fjakv8o\",\"isLoading\":false,\"borderRadius\":\"{{appsmith.theme.borderRadius.appBorderRadius}}\",\"buttonVariant\":\"PRIMARY\"}],\"parentId\":\"zi8fjakv8o\"},{\"widgetId\":\"48uac29g6e\",\"list\":[{\"boxShadow\":\"none\",\"widgetName\":\"Text12\",\"topRow\":8,\"bottomRow\":12,\"parentRowSpace\":10,\"type\":\"TEXT_WIDGET\",\"parentColumnSpace\":6.875,\"dynamicTriggerPathList\":[],\"overflow\":\"NONE\",\"fontFamily\":\"System Default\",\"leftColumn\":1,\"dynamicBindingPathList\":[],\"text\":\"Are you sure you want to delete this item?\",\"labelTextSize\":\"0.875rem\",\"rightColumn\":63,\"textAlign\":\"LEFT\",\"dynamicHeight\":\"FIXED\",\"widgetId\":\"48uac29g6e\",\"isVisible\":\"true\",\"fontStyle\":\"\",\"textColor\":\"#231F20\",\"version\":1,\"parentId\":\"zi8fjakv8o\",\"isLoading\":false,\"borderRadius\":\"0px\",\"maxDynamicHeight\":9000,\"fontSize\":\"1rem\",\"minDynamicHeight\":4}],\"parentId\":\"zi8fjakv8o\"},{\"widgetId\":\"o8oiq6vwkk\",\"list\":[{\"schema\":{\"__root_schema__\":{\"labelTextSize\":\"0.875rem\",\"identifier\":\"__root_schema__\",\"boxShadow\":\"none\",\"isRequired\":false,\"isCustomField\":false,\"defaultValue\":\"{{((sourceData, formData, fieldState) => (sourceData))(insert_form.sourceData, insert_form.formData, insert_form.fieldState)}}\",\"dataType\":\"object\",\"cellBorderRadius\":\"{{appsmith.theme.borderRadius.appBorderRadius}}\",\"accessor\":\"__root_schema__\",\"isVisible\":true,\"label\":\"\",\"originalIdentifier\":\"__root_schema__\",\"borderRadius\":\"{{appsmith.theme.borderRadius.appBorderRadius}}\",\"children\":{\"col8\":{\"labelTextSize\":\"0.875rem\",\"identifier\":\"col8\",\"isRequired\":false,\"boxShadow\":\"none\",\"isCustomField\":false,\"defaultValue\":\"{{((sourceData, formData, fieldState) => (sourceData.col8))(insert_form.sourceData, insert_form.formData, insert_form.fieldState)}}\",\"accentColor\":\"{{appsmith.theme.colors.primaryColor}}\",\"dataType\":\"null\",\"cellBorderRadius\":\"0px\",\"accessor\":\"col8\",\"isVisible\":true,\"label\":\"Col 8\",\"originalIdentifier\":\"col8\",\"borderRadius\":\"{{appsmith.theme.borderRadius.appBorderRadius}}\",\"children\":{},\"isSpellCheck\":false,\"iconAlign\":\"left\",\"position\":7,\"isDisabled\":false,\"cellBoxShadow\":\"none\",\"fieldType\":\"Text Input\"},\"col12\":{\"labelTextSize\":\"0.875rem\",\"identifier\":\"col12\",\"isRequired\":false,\"boxShadow\":\"none\",\"isCustomField\":false,\"defaultValue\":\"{{((sourceData, formData, fieldState) => (sourceData.col12))(insert_form.sourceData, insert_form.formData, insert_form.fieldState)}}\",\"accentColor\":\"{{appsmith.theme.colors.primaryColor}}\",\"dataType\":\"null\",\"cellBorderRadius\":\"0px\",\"accessor\":\"col12\",\"isVisible\":true,\"label\":\"Col 12\",\"originalIdentifier\":\"col12\",\"borderRadius\":\"{{appsmith.theme.borderRadius.appBorderRadius}}\",\"children\":{},\"isSpellCheck\":false,\"iconAlign\":\"left\",\"position\":11,\"isDisabled\":false,\"cellBoxShadow\":\"none\",\"fieldType\":\"Text Input\"},\"col9\":{\"labelTextSize\":\"0.875rem\",\"identifier\":\"col9\",\"isRequired\":false,\"boxShadow\":\"none\",\"isCustomField\":false,\"defaultValue\":\"{{((sourceData, formData, fieldState) => (sourceData.col9))(insert_form.sourceData, insert_form.formData, insert_form.fieldState)}}\",\"accentColor\":\"{{appsmith.theme.colors.primaryColor}}\",\"dataType\":\"null\",\"cellBorderRadius\":\"0px\",\"accessor\":\"col9\",\"isVisible\":true,\"label\":\"Col 9\",\"originalIdentifier\":\"col9\",\"borderRadius\":\"{{appsmith.theme.borderRadius.appBorderRadius}}\",\"children\":{},\"isSpellCheck\":false,\"iconAlign\":\"left\",\"position\":8,\"isDisabled\":false,\"cellBoxShadow\":\"none\",\"fieldType\":\"Text Input\"},\"col11\":{\"labelTextSize\":\"0.875rem\",\"identifier\":\"col11\",\"isRequired\":false,\"boxShadow\":\"none\",\"isCustomField\":false,\"defaultValue\":\"{{((sourceData, formData, fieldState) => (sourceData.col11))(insert_form.sourceData, insert_form.formData, insert_form.fieldState)}}\",\"accentColor\":\"{{appsmith.theme.colors.primaryColor}}\",\"dataType\":\"null\",\"cellBorderRadius\":\"0px\",\"accessor\":\"col11\",\"isVisible\":true,\"label\":\"Col 11\",\"originalIdentifier\":\"col11\",\"borderRadius\":\"{{appsmith.theme.borderRadius.appBorderRadius}}\",\"children\":{},\"isSpellCheck\":false,\"iconAlign\":\"left\",\"position\":10,\"isDisabled\":false,\"cellBoxShadow\":\"none\",\"fieldType\":\"Text Input\"},\"col6\":{\"labelTextSize\":\"0.875rem\",\"identifier\":\"col6\",\"isRequired\":false,\"boxShadow\":\"none\",\"isCustomField\":false,\"defaultValue\":\"{{((sourceData, formData, fieldState) => (sourceData.col6))(insert_form.sourceData, insert_form.formData, insert_form.fieldState)}}\",\"accentColor\":\"{{appsmith.theme.colors.primaryColor}}\",\"dataType\":\"null\",\"cellBorderRadius\":\"0px\",\"accessor\":\"col6\",\"isVisible\":true,\"label\":\"Col 6\",\"originalIdentifier\":\"col6\",\"borderRadius\":\"{{appsmith.theme.borderRadius.appBorderRadius}}\",\"children\":{},\"isSpellCheck\":false,\"iconAlign\":\"left\",\"position\":5,\"isDisabled\":false,\"cellBoxShadow\":\"none\",\"fieldType\":\"Text Input\"},\"col10\":{\"labelTextSize\":\"0.875rem\",\"identifier\":\"col10\",\"isRequired\":false,\"boxShadow\":\"none\",\"isCustomField\":false,\"defaultValue\":\"{{((sourceData, formData, fieldState) => (sourceData.col10))(insert_form.sourceData, insert_form.formData, insert_form.fieldState)}}\",\"accentColor\":\"{{appsmith.theme.colors.primaryColor}}\",\"dataType\":\"null\",\"cellBorderRadius\":\"0px\",\"accessor\":\"col10\",\"isVisible\":true,\"label\":\"Col 10\",\"originalIdentifier\":\"col10\",\"borderRadius\":\"{{appsmith.theme.borderRadius.appBorderRadius}}\",\"children\":{},\"isSpellCheck\":false,\"iconAlign\":\"left\",\"position\":9,\"isDisabled\":false,\"cellBoxShadow\":\"none\",\"fieldType\":\"Text Input\"},\"col7\":{\"labelTextSize\":\"0.875rem\",\"identifier\":\"col7\",\"isRequired\":false,\"boxShadow\":\"none\",\"isCustomField\":false,\"defaultValue\":\"{{((sourceData, formData, fieldState) => (sourceData.col7))(insert_form.sourceData, insert_form.formData, insert_form.fieldState)}}\",\"accentColor\":\"{{appsmith.theme.colors.primaryColor}}\",\"dataType\":\"null\",\"cellBorderRadius\":\"0px\",\"accessor\":\"col7\",\"isVisible\":true,\"label\":\"Col 7\",\"originalIdentifier\":\"col7\",\"borderRadius\":\"{{appsmith.theme.borderRadius.appBorderRadius}}\",\"children\":{},\"isSpellCheck\":false,\"iconAlign\":\"left\",\"position\":6,\"isDisabled\":false,\"cellBoxShadow\":\"none\",\"fieldType\":\"Text Input\"},\"col4\":{\"labelTextSize\":\"0.875rem\",\"identifier\":\"col4\",\"isRequired\":false,\"boxShadow\":\"none\",\"isCustomField\":false,\"defaultValue\":\"{{((sourceData, formData, fieldState) => (sourceData.col4))(insert_form.sourceData, insert_form.formData, insert_form.fieldState)}}\",\"accentColor\":\"{{appsmith.theme.colors.primaryColor}}\",\"dataType\":\"boolean\",\"cellBorderRadius\":\"0px\",\"accessor\":\"col4\",\"isVisible\":true,\"label\":\"Col 4\",\"alignWidget\":\"LEFT\",\"originalIdentifier\":\"col4\",\"borderRadius\":\"0px\",\"children\":{},\"position\":3,\"isDisabled\":false,\"sourceData\":true,\"cellBoxShadow\":\"none\",\"fieldType\":\"Switch\"},\"col5\":{\"labelTextSize\":\"0.875rem\",\"identifier\":\"col5\",\"boxShadow\":\"none\",\"isRequired\":false,\"isCustomField\":false,\"defaultValue\":\"{{((sourceData, formData, fieldState) => (sourceData.col5))(insert_form.sourceData, insert_form.formData, insert_form.fieldState)}}\",\"accentColor\":\"{{appsmith.theme.colors.primaryColor}}\",\"dataType\":\"number\",\"accessor\":\"col5\",\"isVisible\":true,\"label\":\"Col 5\",\"originalIdentifier\":\"col5\",\"borderRadius\":\"{{appsmith.theme.borderRadius.appBorderRadius}}\",\"children\":{},\"isSpellCheck\":false,\"iconAlign\":\"left\",\"position\":4,\"isDisabled\":false,\"fieldType\":\"Number Input\"},\"col2\":{\"labelTextSize\":\"0.875rem\",\"identifier\":\"col2\",\"isRequired\":false,\"boxShadow\":\"none\",\"isCustomField\":false,\"defaultValue\":\"{{((sourceData, formData, fieldState) => (sourceData.col2))(insert_form.sourceData, insert_form.formData, insert_form.fieldState)}}\",\"accentColor\":\"{{appsmith.theme.colors.primaryColor}}\",\"dataType\":\"string\",\"cellBorderRadius\":\"0px\",\"accessor\":\"col2\",\"isVisible\":true,\"label\":\"Col 2\",\"originalIdentifier\":\"col2\",\"borderRadius\":\"{{appsmith.theme.borderRadius.appBorderRadius}}\",\"children\":{},\"isSpellCheck\":false,\"iconAlign\":\"left\",\"position\":1,\"isDisabled\":false,\"sourceData\":\"skill B\",\"cellBoxShadow\":\"none\",\"fieldType\":\"Text Input\"},\"col3\":{\"labelTextSize\":\"0.875rem\",\"identifier\":\"col3\",\"isRequired\":false,\"boxShadow\":\"none\",\"isCustomField\":false,\"defaultValue\":\"{{((sourceData, formData, fieldState) => (sourceData.col3))(insert_form.sourceData, insert_form.formData, insert_form.fieldState)}}\",\"accentColor\":\"{{appsmith.theme.colors.primaryColor}}\",\"dataType\":\"number\",\"cellBorderRadius\":\"0px\",\"accessor\":\"col3\",\"isVisible\":true,\"label\":\"Col 3\",\"originalIdentifier\":\"col3\",\"borderRadius\":\"{{appsmith.theme.borderRadius.appBorderRadius}}\",\"children\":{},\"isSpellCheck\":false,\"iconAlign\":\"left\",\"position\":2,\"isDisabled\":false,\"sourceData\":9,\"cellBoxShadow\":\"none\",\"fieldType\":\"Number Input\"},\"col1\":{\"labelTextSize\":\"0.875rem\",\"identifier\":\"col1\",\"boxShadow\":\"none\",\"isRequired\":false,\"isCustomField\":false,\"defaultValue\":\"{{((sourceData, formData, fieldState) => (sourceData.col1))(insert_form.sourceData, insert_form.formData, insert_form.fieldState)}}\",\"accentColor\":\"{{appsmith.theme.colors.primaryColor}}\",\"dataType\":\"number\",\"accessor\":\"col1\",\"isVisible\":true,\"label\":\"Col 1\",\"originalIdentifier\":\"col1\",\"borderRadius\":\"{{appsmith.theme.borderRadius.appBorderRadius}}\",\"children\":{},\"isSpellCheck\":false,\"iconAlign\":\"left\",\"position\":0,\"isDisabled\":false,\"sourceData\":5,\"fieldType\":\"Number Input\"}},\"position\":-1,\"isDisabled\":false,\"sourceData\":{\"col4\":true,\"col2\":\"skill B\",\"col3\":9,\"col1\":5},\"cellBoxShadow\":\"none\",\"fieldType\":\"Object\"}},\"boxShadow\":\"none\",\"widgetName\":\"insert_form\",\"submitButtonStyles\":{\"boxShadow\":\"none\",\"borderRadius\":\"{{appsmith.theme.borderRadius.appBorderRadius}}\",\"buttonColor\":\"{{appsmith.theme.colors.primaryColor}}\",\"buttonVariant\":\"PRIMARY\"},\"dynamicPropertyPathList\":[{\"key\":\"schema.__root_schema__.children.date_of_birth.defaultValue\"},{\"key\":\"schema.__root_schema__.children.col5.defaultValue\"},{\"key\":\"schema.__root_schema__.children.col4.defaultValue\"},{\"key\":\"onSubmit\"}],\"displayName\":\"JSON Form\",\"iconSVG\":\"/static/media/icon.6bacf7df.svg\",\"onSubmit\":\"{{InsertQuery.run(\\n\\t() => SelectQuery.run()\\n\\t\\t\\t\\t\\t.then(() => closeModal('Insert_Modal')), \\n\\t(error) => showAlert(`Error while inserting resource!\\\\n ${error}`,'error'))\\n}}\",\"topRow\":0,\"bottomRow\":81,\"fieldLimitExceeded\":false,\"parentRowSpace\":10,\"title\":\"Insert Row\",\"type\":\"JSON_FORM_WIDGET\",\"hideCard\":false,\"animateLoading\":true,\"parentColumnSpace\":8.125,\"dynamicTriggerPathList\":[{\"key\":\"onSubmit\"}],\"leftColumn\":0,\"dynamicBindingPathList\":[{\"key\":\"schema.__root_schema__.defaultValue\"},{\"key\":\"sourceData\"},{\"key\":\"schema.__root_schema__.children.col3.defaultValue\"},{\"key\":\"schema.__root_schema__.children.col4.defaultValue\"},{\"key\":\"schema.__root_schema__.children.col5.defaultValue\"},{\"key\":\"schema.__root_schema__.children.col2.defaultValue\"},{\"key\":\"schema.__root_schema__.children.col6.defaultValue\"},{\"key\":\"schema.__root_schema__.children.col7.defaultValue\"},{\"key\":\"schema.__root_schema__.children.col8.defaultValue\"},{\"key\":\"schema.__root_schema__.children.col9.defaultValue\"},{\"key\":\"schema.__root_schema__.children.col10.defaultValue\"},{\"key\":\"schema.__root_schema__.children.col11.defaultValue\"},{\"key\":\"schema.__root_schema__.children.col12.defaultValue\"},{\"key\":\"schema.__root_schema__.children.col5.accentColor\"},{\"key\":\"schema.__root_schema__.children.col5.borderRadius\"},{\"key\":\"schema.__root_schema__.borderRadius\"},{\"key\":\"schema.__root_schema__.cellBorderRadius\"},{\"key\":\"schema.__root_schema__.children.col1.defaultValue\"},{\"key\":\"schema.__root_schema__.children.col1.accentColor\"},{\"key\":\"schema.__root_schema__.children.col1.borderRadius\"},{\"key\":\"borderRadius\"},{\"key\":\"submitButtonStyles.buttonColor\"},{\"key\":\"submitButtonStyles.borderRadius\"},{\"key\":\"resetButtonStyles.borderRadius\"},{\"key\":\"resetButtonStyles.buttonColor\"},{\"key\":\"schema.__root_schema__.children.col2.accentColor\"},{\"key\":\"schema.__root_schema__.children.col2.borderRadius\"},{\"key\":\"schema.__root_schema__.children.col3.accentColor\"},{\"key\":\"schema.__root_schema__.children.col3.borderRadius\"},{\"key\":\"schema.__root_schema__.children.col4.accentColor\"},{\"key\":\"schema.__root_schema__.children.col6.accentColor\"},{\"key\":\"schema.__root_schema__.children.col6.borderRadius\"},{\"key\":\"schema.__root_schema__.children.col7.accentColor\"},{\"key\":\"schema.__root_schema__.children.col7.borderRadius\"},{\"key\":\"schema.__root_schema__.children.col8.accentColor\"},{\"key\":\"schema.__root_schema__.children.col8.borderRadius\"},{\"key\":\"schema.__root_schema__.children.col9.accentColor\"},{\"key\":\"schema.__root_schema__.children.col9.borderRadius\"},{\"key\":\"schema.__root_schema__.children.col10.accentColor\"},{\"key\":\"schema.__root_schema__.children.col10.borderRadius\"},{\"key\":\"schema.__root_schema__.children.col11.accentColor\"},{\"key\":\"schema.__root_schema__.children.col11.borderRadius\"},{\"key\":\"schema.__root_schema__.children.col12.accentColor\"},{\"key\":\"schema.__root_schema__.children.col12.borderRadius\"}],\"sourceData\":\"{{_.omit(data_table.tableData[0], \\\"customColumn1\\\", \\\"id\\\")}}\",\"showReset\":true,\"resetButtonLabel\":\"Reset\",\"key\":\"h9l9ozr8op\",\"labelTextSize\":\"0.875rem\",\"backgroundColor\":\"#fff\",\"rightColumn\":64,\"dynamicHeight\":\"FIXED\",\"autoGenerateForm\":true,\"widgetId\":\"o8oiq6vwkk\",\"resetButtonStyles\":{\"boxShadow\":\"none\",\"borderRadius\":\"{{appsmith.theme.borderRadius.appBorderRadius}}\",\"buttonColor\":\"{{appsmith.theme.colors.primaryColor}}\",\"buttonVariant\":\"SECONDARY\"},\"isVisible\":\"true\",\"version\":1,\"parentId\":\"9rhv3ioohq\",\"renderMode\":\"CANVAS\",\"isLoading\":false,\"scrollContents\":true,\"fixedFooter\":true,\"submitButtonLabel\":\"Submit\",\"childStylesheet\":{\"CHECKBOX\":{\"borderRadius\":\"{{appsmith.theme.borderRadius.appBorderRadius}}\",\"accentColor\":\"{{appsmith.theme.colors.primaryColor}}\"},\"ARRAY\":{\"boxShadow\":\"none\",\"borderRadius\":\"{{appsmith.theme.borderRadius.appBorderRadius}}\",\"accentColor\":\"{{appsmith.theme.colors.primaryColor}}\",\"cellBorderRadius\":\"{{appsmith.theme.borderRadius.appBorderRadius}}\",\"cellBoxShadow\":\"none\"},\"CURRENCY_INPUT\":{\"boxShadow\":\"none\",\"borderRadius\":\"{{appsmith.theme.borderRadius.appBorderRadius}}\",\"accentColor\":\"{{appsmith.theme.colors.primaryColor}}\"},\"DATEPICKER\":{\"boxShadow\":\"none\",\"borderRadius\":\"{{appsmith.theme.borderRadius.appBorderRadius}}\",\"accentColor\":\"{{appsmith.theme.colors.primaryColor}}\"},\"PHONE_NUMBER_INPUT\":{\"boxShadow\":\"none\",\"borderRadius\":\"{{appsmith.theme.borderRadius.appBorderRadius}}\",\"accentColor\":\"{{appsmith.theme.colors.primaryColor}}\"},\"OBJECT\":{\"boxShadow\":\"none\",\"borderRadius\":\"{{appsmith.theme.borderRadius.appBorderRadius}}\",\"cellBorderRadius\":\"{{appsmith.theme.borderRadius.appBorderRadius}}\",\"cellBoxShadow\":\"none\"},\"MULTISELECT\":{\"boxShadow\":\"none\",\"borderRadius\":\"{{appsmith.theme.borderRadius.appBorderRadius}}\",\"accentColor\":\"{{appsmith.theme.colors.primaryColor}}\"},\"SELECT\":{\"boxShadow\":\"none\",\"borderRadius\":\"{{appsmith.theme.borderRadius.appBorderRadius}}\",\"accentColor\":\"{{appsmith.theme.colors.primaryColor}}\"},\"NUMBER_INPUT\":{\"boxShadow\":\"none\",\"borderRadius\":\"{{appsmith.theme.borderRadius.appBorderRadius}}\",\"accentColor\":\"{{appsmith.theme.colors.primaryColor}}\"},\"PASSWORD_INPUT\":{\"boxShadow\":\"none\",\"borderRadius\":\"{{appsmith.theme.borderRadius.appBorderRadius}}\",\"accentColor\":\"{{appsmith.theme.colors.primaryColor}}\"},\"EMAIL_INPUT\":{\"boxShadow\":\"none\",\"borderRadius\":\"{{appsmith.theme.borderRadius.appBorderRadius}}\",\"accentColor\":\"{{appsmith.theme.colors.primaryColor}}\"},\"RADIO_GROUP\":{\"boxShadow\":\"none\",\"accentColor\":\"{{appsmith.theme.colors.primaryColor}}\"},\"SWITCH\":{\"boxShadow\":\"none\",\"accentColor\":\"{{appsmith.theme.colors.primaryColor}}\"},\"TEXT_INPUT\":{\"boxShadow\":\"none\",\"borderRadius\":\"{{appsmith.theme.borderRadius.appBorderRadius}}\",\"accentColor\":\"{{appsmith.theme.colors.primaryColor}}\"},\"MULTILINE_TEXT_INPUT\":{\"boxShadow\":\"none\",\"borderRadius\":\"{{appsmith.theme.borderRadius.appBorderRadius}}\",\"accentColor\":\"{{appsmith.theme.colors.primaryColor}}\"}},\"disabledWhenInvalid\":true,\"borderRadius\":\"{{appsmith.theme.borderRadius.appBorderRadius}}\",\"maxDynamicHeight\":9000,\"minDynamicHeight\":4}],\"parentId\":\"9rhv3ioohq\"}],\"flexLayers\":[]}"} \ No newline at end of file +{"clientSchemaVersion":1,"serverSchemaVersion":7,"widgets":"{\"widgets\":[{\"widgetId\":\"hpy3pb4xft\",\"list\":[{\"boxShadow\":\"{{appsmith.theme.boxShadow.appBoxShadow}}\",\"onSort\":\"{{SelectQuery.run()}}\",\"isVisibleDownload\":true,\"iconSVG\":\"/static/media/icon.db8a9cbd.svg\",\"topRow\":6,\"isSortable\":true,\"onPageChange\":\"{{SelectQuery.run()}}\",\"type\":\"TABLE_WIDGET_V2\",\"animateLoading\":true,\"dynamicBindingPathList\":[{\"key\":\"tableData\"},{\"key\":\"derivedColumns.customColumn1.buttonLabel\"},{\"key\":\"primaryColumns.customColumn1.buttonLabel\"},{\"key\":\"accentColor\"},{\"key\":\"borderRadius\"},{\"key\":\"boxShadow\"},{\"key\":\"primaryColumns.customColumn1.borderRadius\"},{\"key\":\"primaryColumns.id.computedValue\"},{\"key\":\"primaryColumns.gender.computedValue\"},{\"key\":\"primaryColumns.latitude.computedValue\"},{\"key\":\"primaryColumns.longitude.computedValue\"},{\"key\":\"primaryColumns.dob.computedValue\"},{\"key\":\"primaryColumns.phone.computedValue\"},{\"key\":\"primaryColumns.email.computedValue\"},{\"key\":\"primaryColumns.image.computedValue\"},{\"key\":\"primaryColumns.country.computedValue\"},{\"key\":\"primaryColumns.name.computedValue\"},{\"key\":\"primaryColumns.created_at.computedValue\"},{\"key\":\"primaryColumns.updated_at.computedValue\"}],\"leftColumn\":0,\"delimiter\":\",\",\"defaultSelectedRowIndex\":\"0\",\"accentColor\":\"{{appsmith.theme.colors.primaryColor}}\",\"isVisibleFilters\":true,\"isVisible\":\"true\",\"enableClientSideSearch\":true,\"version\":3,\"totalRecordsCount\":0,\"isLoading\":false,\"onSearchTextChanged\":\"{{SelectQuery.run()}}\",\"childStylesheet\":{\"button\":{\"boxShadow\":\"none\",\"borderRadius\":\"{{appsmith.theme.borderRadius.appBorderRadius}}\",\"buttonColor\":\"{{appsmith.theme.colors.primaryColor}}\"},\"iconButton\":{\"boxShadow\":\"none\",\"borderRadius\":\"{{appsmith.theme.borderRadius.appBorderRadius}}\",\"menuColor\":\"{{appsmith.theme.colors.primaryColor}}\"},\"menuButton\":{\"boxShadow\":\"none\",\"borderRadius\":\"{{appsmith.theme.borderRadius.appBorderRadius}}\",\"menuColor\":\"{{appsmith.theme.colors.primaryColor}}\"}},\"borderRadius\":\"{{appsmith.theme.borderRadius.appBorderRadius}}\",\"columnUpdatedAt\":1704697943255,\"primaryColumnId\":\"id\",\"columnSizeMap\":{\"task\":245,\"step\":62,\"status\":75},\"widgetName\":\"data_table\",\"defaultPageSize\":0,\"columnOrder\":[\"id\",\"gender\",\"latitude\",\"longitude\",\"dob\",\"phone\",\"email\",\"image\",\"country\",\"name\",\"created_at\",\"updated_at\",\"customColumn1\"],\"dynamicPropertyPathList\":[{\"key\":\"primaryColumns.customColumn1.borderRadius\"},{\"key\":\"tableData\"}],\"displayName\":\"Table\",\"bottomRow\":85,\"parentRowSpace\":10,\"hideCard\":false,\"parentColumnSpace\":16.3125,\"dynamicTriggerPathList\":[{\"key\":\"primaryColumns.customColumn1.onClick\"},{\"key\":\"onPageChange\"},{\"key\":\"onSearchTextChanged\"},{\"key\":\"onSort\"}],\"primaryColumns\":{\"customColumn1\":{\"isCellVisible\":true,\"boxShadow\":\"none\",\"isDerived\":true,\"computedValue\":\"\",\"onClick\":\"{{showModal(Delete_Modal.name)}}\",\"buttonColor\":\"#DD4B34\",\"buttonStyle\":\"rgb(3, 179, 101)\",\"index\":5,\"isVisible\":true,\"label\":\"Delete\",\"labelColor\":\"#FFFFFF\",\"buttonLabel\":\"{{data_table.processedTableData.map((currentRow, currentIndex) => ( 'Delete'))}}\",\"columnType\":\"button\",\"borderRadius\":\"{{data_table.processedTableData.map((currentRow, currentIndex) => ( appsmith.theme.borderRadius.appBorderRadius))}}\",\"menuColor\":\"#03B365\",\"width\":150,\"enableFilter\":true,\"enableSort\":true,\"id\":\"customColumn1\",\"isDisabled\":false,\"buttonLabelColor\":\"#FFFFFF\",\"sticky\":\"right\"},\"id\":{\"allowCellWrapping\":false,\"allowSameOptionsInNewRow\":true,\"index\":0,\"width\":150,\"originalId\":\"id\",\"id\":\"id\",\"alias\":\"id\",\"horizontalAlignment\":\"LEFT\",\"verticalAlignment\":\"CENTER\",\"columnType\":\"number\",\"textColor\":\"\",\"textSize\":\"0.875rem\",\"fontStyle\":\"\",\"enableFilter\":true,\"enableSort\":true,\"isVisible\":true,\"isDisabled\":false,\"isCellEditable\":false,\"isEditable\":false,\"isCellVisible\":true,\"isDerived\":false,\"label\":\"id\",\"isSaveVisible\":true,\"isDiscardVisible\":true,\"computedValue\":\"{{data_table.processedTableData.map((currentRow, currentIndex) => ( currentRow[\\\"id\\\"]))}}\",\"sticky\":\"\",\"validation\":{},\"currencyCode\":\"USD\",\"decimals\":0,\"thousandSeparator\":true,\"notation\":\"standard\",\"cellBackground\":\"\"},\"gender\":{\"allowCellWrapping\":false,\"allowSameOptionsInNewRow\":true,\"index\":1,\"width\":150,\"originalId\":\"gender\",\"id\":\"gender\",\"alias\":\"gender\",\"horizontalAlignment\":\"LEFT\",\"verticalAlignment\":\"CENTER\",\"columnType\":\"text\",\"textColor\":\"\",\"textSize\":\"0.875rem\",\"fontStyle\":\"\",\"enableFilter\":true,\"enableSort\":true,\"isVisible\":true,\"isDisabled\":false,\"isCellEditable\":false,\"isEditable\":false,\"isCellVisible\":true,\"isDerived\":false,\"label\":\"gender\",\"isSaveVisible\":true,\"isDiscardVisible\":true,\"computedValue\":\"{{data_table.processedTableData.map((currentRow, currentIndex) => ( currentRow[\\\"gender\\\"]))}}\",\"sticky\":\"\",\"validation\":{},\"currencyCode\":\"USD\",\"decimals\":0,\"thousandSeparator\":true,\"notation\":\"standard\",\"cellBackground\":\"\"},\"latitude\":{\"allowCellWrapping\":false,\"allowSameOptionsInNewRow\":true,\"index\":2,\"width\":150,\"originalId\":\"latitude\",\"id\":\"latitude\",\"alias\":\"latitude\",\"horizontalAlignment\":\"LEFT\",\"verticalAlignment\":\"CENTER\",\"columnType\":\"text\",\"textColor\":\"\",\"textSize\":\"0.875rem\",\"fontStyle\":\"\",\"enableFilter\":true,\"enableSort\":true,\"isVisible\":true,\"isDisabled\":false,\"isCellEditable\":false,\"isEditable\":false,\"isCellVisible\":true,\"isDerived\":false,\"label\":\"latitude\",\"isSaveVisible\":true,\"isDiscardVisible\":true,\"computedValue\":\"{{data_table.processedTableData.map((currentRow, currentIndex) => ( currentRow[\\\"latitude\\\"]))}}\",\"sticky\":\"\",\"validation\":{},\"currencyCode\":\"USD\",\"decimals\":0,\"thousandSeparator\":true,\"notation\":\"standard\",\"cellBackground\":\"\"},\"longitude\":{\"allowCellWrapping\":false,\"allowSameOptionsInNewRow\":true,\"index\":3,\"width\":150,\"originalId\":\"longitude\",\"id\":\"longitude\",\"alias\":\"longitude\",\"horizontalAlignment\":\"LEFT\",\"verticalAlignment\":\"CENTER\",\"columnType\":\"text\",\"textColor\":\"\",\"textSize\":\"0.875rem\",\"fontStyle\":\"\",\"enableFilter\":true,\"enableSort\":true,\"isVisible\":true,\"isDisabled\":false,\"isCellEditable\":false,\"isEditable\":false,\"isCellVisible\":true,\"isDerived\":false,\"label\":\"longitude\",\"isSaveVisible\":true,\"isDiscardVisible\":true,\"computedValue\":\"{{data_table.processedTableData.map((currentRow, currentIndex) => ( currentRow[\\\"longitude\\\"]))}}\",\"sticky\":\"\",\"validation\":{},\"currencyCode\":\"USD\",\"decimals\":0,\"thousandSeparator\":true,\"notation\":\"standard\",\"cellBackground\":\"\"},\"dob\":{\"allowCellWrapping\":false,\"allowSameOptionsInNewRow\":true,\"index\":4,\"width\":150,\"originalId\":\"dob\",\"id\":\"dob\",\"alias\":\"dob\",\"horizontalAlignment\":\"LEFT\",\"verticalAlignment\":\"CENTER\",\"columnType\":\"date\",\"textColor\":\"\",\"textSize\":\"0.875rem\",\"fontStyle\":\"\",\"enableFilter\":true,\"enableSort\":true,\"isVisible\":true,\"isDisabled\":false,\"isCellEditable\":false,\"isEditable\":false,\"isCellVisible\":true,\"isDerived\":false,\"label\":\"dob\",\"isSaveVisible\":true,\"isDiscardVisible\":true,\"computedValue\":\"{{data_table.processedTableData.map((currentRow, currentIndex) => ( currentRow[\\\"dob\\\"]))}}\",\"sticky\":\"\",\"validation\":{},\"currencyCode\":\"USD\",\"decimals\":0,\"thousandSeparator\":true,\"notation\":\"standard\",\"cellBackground\":\"\"},\"phone\":{\"allowCellWrapping\":false,\"allowSameOptionsInNewRow\":true,\"index\":5,\"width\":150,\"originalId\":\"phone\",\"id\":\"phone\",\"alias\":\"phone\",\"horizontalAlignment\":\"LEFT\",\"verticalAlignment\":\"CENTER\",\"columnType\":\"text\",\"textColor\":\"\",\"textSize\":\"0.875rem\",\"fontStyle\":\"\",\"enableFilter\":true,\"enableSort\":true,\"isVisible\":true,\"isDisabled\":false,\"isCellEditable\":false,\"isEditable\":false,\"isCellVisible\":true,\"isDerived\":false,\"label\":\"phone\",\"isSaveVisible\":true,\"isDiscardVisible\":true,\"computedValue\":\"{{data_table.processedTableData.map((currentRow, currentIndex) => ( currentRow[\\\"phone\\\"]))}}\",\"sticky\":\"\",\"validation\":{},\"currencyCode\":\"USD\",\"decimals\":0,\"thousandSeparator\":true,\"notation\":\"standard\",\"cellBackground\":\"\"},\"email\":{\"allowCellWrapping\":false,\"allowSameOptionsInNewRow\":true,\"index\":6,\"width\":150,\"originalId\":\"email\",\"id\":\"email\",\"alias\":\"email\",\"horizontalAlignment\":\"LEFT\",\"verticalAlignment\":\"CENTER\",\"columnType\":\"text\",\"textColor\":\"\",\"textSize\":\"0.875rem\",\"fontStyle\":\"\",\"enableFilter\":true,\"enableSort\":true,\"isVisible\":true,\"isDisabled\":false,\"isCellEditable\":false,\"isEditable\":false,\"isCellVisible\":true,\"isDerived\":false,\"label\":\"email\",\"isSaveVisible\":true,\"isDiscardVisible\":true,\"computedValue\":\"{{data_table.processedTableData.map((currentRow, currentIndex) => ( currentRow[\\\"email\\\"]))}}\",\"sticky\":\"\",\"validation\":{},\"currencyCode\":\"USD\",\"decimals\":0,\"thousandSeparator\":true,\"notation\":\"standard\",\"cellBackground\":\"\"},\"image\":{\"allowCellWrapping\":false,\"allowSameOptionsInNewRow\":true,\"index\":7,\"width\":150,\"originalId\":\"image\",\"id\":\"image\",\"alias\":\"image\",\"horizontalAlignment\":\"LEFT\",\"verticalAlignment\":\"CENTER\",\"columnType\":\"text\",\"textColor\":\"\",\"textSize\":\"0.875rem\",\"fontStyle\":\"\",\"enableFilter\":true,\"enableSort\":true,\"isVisible\":true,\"isDisabled\":false,\"isCellEditable\":false,\"isEditable\":false,\"isCellVisible\":true,\"isDerived\":false,\"label\":\"image\",\"isSaveVisible\":true,\"isDiscardVisible\":true,\"computedValue\":\"{{data_table.processedTableData.map((currentRow, currentIndex) => ( currentRow[\\\"image\\\"]))}}\",\"sticky\":\"\",\"validation\":{},\"currencyCode\":\"USD\",\"decimals\":0,\"thousandSeparator\":true,\"notation\":\"standard\",\"cellBackground\":\"\"},\"country\":{\"allowCellWrapping\":false,\"allowSameOptionsInNewRow\":true,\"index\":8,\"width\":150,\"originalId\":\"country\",\"id\":\"country\",\"alias\":\"country\",\"horizontalAlignment\":\"LEFT\",\"verticalAlignment\":\"CENTER\",\"columnType\":\"text\",\"textColor\":\"\",\"textSize\":\"0.875rem\",\"fontStyle\":\"\",\"enableFilter\":true,\"enableSort\":true,\"isVisible\":true,\"isDisabled\":false,\"isCellEditable\":false,\"isEditable\":false,\"isCellVisible\":true,\"isDerived\":false,\"label\":\"country\",\"isSaveVisible\":true,\"isDiscardVisible\":true,\"computedValue\":\"{{data_table.processedTableData.map((currentRow, currentIndex) => ( currentRow[\\\"country\\\"]))}}\",\"sticky\":\"\",\"validation\":{},\"currencyCode\":\"USD\",\"decimals\":0,\"thousandSeparator\":true,\"notation\":\"standard\",\"cellBackground\":\"\"},\"name\":{\"allowCellWrapping\":false,\"allowSameOptionsInNewRow\":true,\"index\":9,\"width\":150,\"originalId\":\"name\",\"id\":\"name\",\"alias\":\"name\",\"horizontalAlignment\":\"LEFT\",\"verticalAlignment\":\"CENTER\",\"columnType\":\"text\",\"textColor\":\"\",\"textSize\":\"0.875rem\",\"fontStyle\":\"\",\"enableFilter\":true,\"enableSort\":true,\"isVisible\":true,\"isDisabled\":false,\"isCellEditable\":false,\"isEditable\":false,\"isCellVisible\":true,\"isDerived\":false,\"label\":\"name\",\"isSaveVisible\":true,\"isDiscardVisible\":true,\"computedValue\":\"{{data_table.processedTableData.map((currentRow, currentIndex) => ( currentRow[\\\"name\\\"]))}}\",\"sticky\":\"\",\"validation\":{},\"currencyCode\":\"USD\",\"decimals\":0,\"thousandSeparator\":true,\"notation\":\"standard\",\"cellBackground\":\"\"},\"created_at\":{\"allowCellWrapping\":false,\"allowSameOptionsInNewRow\":true,\"index\":10,\"width\":150,\"originalId\":\"created_at\",\"id\":\"created_at\",\"alias\":\"created_at\",\"horizontalAlignment\":\"LEFT\",\"verticalAlignment\":\"CENTER\",\"columnType\":\"text\",\"textColor\":\"\",\"textSize\":\"0.875rem\",\"fontStyle\":\"\",\"enableFilter\":true,\"enableSort\":true,\"isVisible\":true,\"isDisabled\":false,\"isCellEditable\":false,\"isEditable\":false,\"isCellVisible\":true,\"isDerived\":false,\"label\":\"created_at\",\"isSaveVisible\":true,\"isDiscardVisible\":true,\"computedValue\":\"{{data_table.processedTableData.map((currentRow, currentIndex) => ( currentRow[\\\"created_at\\\"]))}}\",\"sticky\":\"\",\"validation\":{},\"currencyCode\":\"USD\",\"decimals\":0,\"thousandSeparator\":true,\"notation\":\"standard\",\"cellBackground\":\"\"},\"updated_at\":{\"allowCellWrapping\":false,\"allowSameOptionsInNewRow\":true,\"index\":11,\"width\":150,\"originalId\":\"updated_at\",\"id\":\"updated_at\",\"alias\":\"updated_at\",\"horizontalAlignment\":\"LEFT\",\"verticalAlignment\":\"CENTER\",\"columnType\":\"text\",\"textColor\":\"\",\"textSize\":\"0.875rem\",\"fontStyle\":\"\",\"enableFilter\":true,\"enableSort\":true,\"isVisible\":true,\"isDisabled\":false,\"isCellEditable\":false,\"isEditable\":false,\"isCellVisible\":true,\"isDerived\":false,\"label\":\"updated_at\",\"isSaveVisible\":true,\"isDiscardVisible\":true,\"computedValue\":\"{{data_table.processedTableData.map((currentRow, currentIndex) => ( currentRow[\\\"updated_at\\\"]))}}\",\"sticky\":\"\",\"validation\":{},\"currencyCode\":\"USD\",\"decimals\":0,\"thousandSeparator\":true,\"notation\":\"standard\",\"cellBackground\":\"\"}},\"key\":\"zba5qel0au\",\"derivedColumns\":{\"customColumn1\":{\"isCellVisible\":true,\"boxShadow\":\"none\",\"isDerived\":true,\"computedValue\":\"\",\"onClick\":\"{{showModal(Delete_Modal.name)}}\",\"buttonColor\":\"#DD4B34\",\"buttonStyle\":\"rgb(3, 179, 101)\",\"index\":5,\"isVisible\":true,\"label\":\"Delete\",\"labelColor\":\"#FFFFFF\",\"buttonLabel\":\"{{data_table.processedTableData.map((currentRow, currentIndex) => ( 'Delete'))}}\",\"columnType\":\"button\",\"borderRadius\":\"0px\",\"menuColor\":\"#03B365\",\"width\":150,\"enableFilter\":true,\"enableSort\":true,\"id\":\"customColumn1\",\"isDisabled\":false,\"buttonLabelColor\":\"#FFFFFF\"}},\"labelTextSize\":\"0.875rem\",\"rightColumn\":64,\"textSize\":\"0.875rem\",\"widgetId\":\"hpy3pb4xft\",\"enableServerSideFiltering\":false,\"tableData\":\"{{SelectQuery.data}}\",\"label\":\"Data\",\"searchKey\":\"\",\"parentId\":\"59rw5mx0bq\",\"serverSidePaginationEnabled\":true,\"renderMode\":\"CANVAS\",\"horizontalAlignment\":\"LEFT\",\"isVisibleSearch\":true,\"isVisiblePagination\":true,\"verticalAlignment\":\"CENTER\"}],\"parentId\":\"59rw5mx0bq\"},{\"widgetId\":\"urzv99hdc8\",\"list\":[{\"boxShadow\":\"none\",\"widgetName\":\"Text16\",\"dynamicPropertyPathList\":[{\"key\":\"fontSize\"}],\"topRow\":1,\"bottomRow\":5,\"parentRowSpace\":10,\"type\":\"TEXT_WIDGET\",\"parentColumnSpace\":11.78515625,\"dynamicTriggerPathList\":[],\"overflow\":\"NONE\",\"fontFamily\":\"{{appsmith.theme.fontFamily.appFont}}\",\"leftColumn\":0,\"dynamicBindingPathList\":[{\"key\":\"fontFamily\"},{\"key\":\"text\"}],\"text\":\"public_users Data + {{JSObject1.addNumbers(3,7)}}\",\"labelTextSize\":\"0.875rem\",\"rightColumn\":54,\"textAlign\":\"LEFT\",\"dynamicHeight\":\"FIXED\",\"widgetId\":\"urzv99hdc8\",\"isVisible\":\"true\",\"fontStyle\":\"BOLD\",\"textColor\":\"#231F20\",\"version\":1,\"parentId\":\"59rw5mx0bq\",\"isLoading\":false,\"borderRadius\":\"0px\",\"maxDynamicHeight\":9000,\"fontSize\":\"1.5rem\",\"minDynamicHeight\":4}],\"parentId\":\"59rw5mx0bq\"},{\"widgetId\":\"xp5u9a9nzq\",\"list\":[{\"labelTextSize\":\"0.875rem\",\"boxShadow\":\"none\",\"widgetName\":\"refresh_btn\",\"rightColumn\":64,\"onClick\":\"{{SelectQuery.run()}}\",\"iconName\":\"refresh\",\"buttonColor\":\"{{appsmith.theme.colors.primaryColor}}\",\"widgetId\":\"xp5u9a9nzq\",\"topRow\":1,\"bottomRow\":5,\"parentRowSpace\":10,\"isVisible\":\"true\",\"type\":\"ICON_BUTTON_WIDGET\",\"version\":1,\"parentId\":\"59rw5mx0bq\",\"isLoading\":false,\"parentColumnSpace\":12.0703125,\"dynamicTriggerPathList\":[{\"key\":\"onClick\"}],\"borderRadius\":\"{{appsmith.theme.borderRadius.appBorderRadius}}\",\"leftColumn\":60,\"dynamicBindingPathList\":[{\"key\":\"buttonColor\"},{\"key\":\"borderRadius\"}],\"buttonVariant\":\"PRIMARY\",\"isDisabled\":false}],\"parentId\":\"59rw5mx0bq\"},{\"widgetId\":\"nh3cu4lb1g\",\"list\":[{\"labelTextSize\":\"0.875rem\",\"boxShadow\":\"none\",\"widgetName\":\"add_btn\",\"rightColumn\":59,\"onClick\":\"{{showModal(Insert_Modal.name)}}\",\"iconName\":\"add\",\"buttonColor\":\"{{appsmith.theme.colors.primaryColor}}\",\"widgetId\":\"nh3cu4lb1g\",\"topRow\":1,\"bottomRow\":5,\"parentRowSpace\":10,\"isVisible\":\"true\",\"type\":\"ICON_BUTTON_WIDGET\",\"version\":1,\"parentId\":\"59rw5mx0bq\",\"isLoading\":false,\"parentColumnSpace\":12.0703125,\"dynamicTriggerPathList\":[{\"key\":\"onClick\"}],\"borderRadius\":\"{{appsmith.theme.borderRadius.appBorderRadius}}\",\"leftColumn\":55,\"dynamicBindingPathList\":[{\"key\":\"buttonColor\"},{\"key\":\"borderRadius\"}],\"buttonVariant\":\"PRIMARY\",\"isDisabled\":false}],\"parentId\":\"59rw5mx0bq\"},{\"widgetId\":\"35yoxo4oec\",\"list\":[{\"boxShadow\":\"none\",\"widgetName\":\"Alert_text\",\"dynamicPropertyPathList\":[{\"key\":\"fontSize\"}],\"topRow\":1,\"bottomRow\":5,\"type\":\"TEXT_WIDGET\",\"dynamicTriggerPathList\":[],\"overflow\":\"NONE\",\"fontFamily\":\"System Default\",\"leftColumn\":1,\"dynamicBindingPathList\":[],\"text\":\"Delete Row\",\"labelTextSize\":\"0.875rem\",\"rightColumn\":41,\"textAlign\":\"LEFT\",\"dynamicHeight\":\"FIXED\",\"widgetId\":\"35yoxo4oec\",\"isVisible\":\"true\",\"fontStyle\":\"BOLD\",\"textColor\":\"#231F20\",\"version\":1,\"parentId\":\"zi8fjakv8o\",\"isLoading\":false,\"borderRadius\":\"0px\",\"maxDynamicHeight\":9000,\"fontSize\":\"1.5rem\",\"minDynamicHeight\":4}],\"parentId\":\"zi8fjakv8o\"},{\"widgetId\":\"lryg8kw537\",\"list\":[{\"boxShadow\":\"none\",\"widgetName\":\"Button1\",\"onClick\":\"{{closeModal(Delete_Modal.name)}}\",\"dynamicPropertyPathList\":[],\"buttonColor\":\"#2E3D49\",\"topRow\":17,\"bottomRow\":21,\"type\":\"BUTTON_WIDGET\",\"dynamicTriggerPathList\":[{\"key\":\"onClick\"}],\"leftColumn\":34,\"dynamicBindingPathList\":[{\"key\":\"borderRadius\"}],\"text\":\"Cancel\",\"isDisabled\":false,\"labelTextSize\":\"0.875rem\",\"rightColumn\":46,\"isDefaultClickDisabled\":true,\"widgetId\":\"lryg8kw537\",\"isVisible\":\"true\",\"version\":1,\"recaptchaType\":\"V3\",\"parentId\":\"zi8fjakv8o\",\"isLoading\":false,\"borderRadius\":\"{{appsmith.theme.borderRadius.appBorderRadius}}\",\"buttonVariant\":\"TERTIARY\"}],\"parentId\":\"zi8fjakv8o\"},{\"widgetId\":\"qq02lh7ust\",\"list\":[{\"boxShadow\":\"none\",\"widgetName\":\"Delete_Button\",\"onClick\":\"{{DeleteQuery.run(() => SelectQuery.run(() => closeModal(Delete_Modal.name)), () => {})}}\",\"dynamicPropertyPathList\":[{\"key\":\"onClick\"}],\"buttonColor\":\"#DD4B34\",\"topRow\":17,\"bottomRow\":21,\"type\":\"BUTTON_WIDGET\",\"dynamicTriggerPathList\":[{\"key\":\"onClick\"}],\"leftColumn\":46,\"dynamicBindingPathList\":[{\"key\":\"borderRadius\"}],\"text\":\"Confirm\",\"isDisabled\":false,\"labelTextSize\":\"0.875rem\",\"rightColumn\":64,\"isDefaultClickDisabled\":true,\"widgetId\":\"qq02lh7ust\",\"isVisible\":\"true\",\"version\":1,\"recaptchaType\":\"V3\",\"parentId\":\"zi8fjakv8o\",\"isLoading\":false,\"borderRadius\":\"{{appsmith.theme.borderRadius.appBorderRadius}}\",\"buttonVariant\":\"PRIMARY\"}],\"parentId\":\"zi8fjakv8o\"},{\"widgetId\":\"48uac29g6e\",\"list\":[{\"boxShadow\":\"none\",\"widgetName\":\"Text12\",\"topRow\":8,\"bottomRow\":12,\"parentRowSpace\":10,\"type\":\"TEXT_WIDGET\",\"parentColumnSpace\":6.875,\"dynamicTriggerPathList\":[],\"overflow\":\"NONE\",\"fontFamily\":\"System Default\",\"leftColumn\":1,\"dynamicBindingPathList\":[],\"text\":\"Are you sure you want to delete this item?\",\"labelTextSize\":\"0.875rem\",\"rightColumn\":63,\"textAlign\":\"LEFT\",\"dynamicHeight\":\"FIXED\",\"widgetId\":\"48uac29g6e\",\"isVisible\":\"true\",\"fontStyle\":\"\",\"textColor\":\"#231F20\",\"version\":1,\"parentId\":\"zi8fjakv8o\",\"isLoading\":false,\"borderRadius\":\"0px\",\"maxDynamicHeight\":9000,\"fontSize\":\"1rem\",\"minDynamicHeight\":4}],\"parentId\":\"zi8fjakv8o\"},{\"widgetId\":\"o8oiq6vwkk\",\"list\":[{\"schema\":{\"__root_schema__\":{\"labelTextSize\":\"0.875rem\",\"identifier\":\"__root_schema__\",\"boxShadow\":\"none\",\"isRequired\":false,\"isCustomField\":false,\"defaultValue\":\"{{((sourceData, formData, fieldState) => (sourceData))(insert_form.sourceData, insert_form.formData, insert_form.fieldState)}}\",\"dataType\":\"object\",\"cellBorderRadius\":\"{{appsmith.theme.borderRadius.appBorderRadius}}\",\"accessor\":\"__root_schema__\",\"isVisible\":true,\"label\":\"\",\"originalIdentifier\":\"__root_schema__\",\"borderRadius\":\"{{appsmith.theme.borderRadius.appBorderRadius}}\",\"children\":{\"col8\":{\"labelTextSize\":\"0.875rem\",\"identifier\":\"col8\",\"isRequired\":false,\"boxShadow\":\"none\",\"isCustomField\":false,\"defaultValue\":\"{{((sourceData, formData, fieldState) => (sourceData.col8))(insert_form.sourceData, insert_form.formData, insert_form.fieldState)}}\",\"accentColor\":\"{{appsmith.theme.colors.primaryColor}}\",\"dataType\":\"null\",\"cellBorderRadius\":\"0px\",\"accessor\":\"col8\",\"isVisible\":true,\"label\":\"Col 8\",\"originalIdentifier\":\"col8\",\"borderRadius\":\"{{appsmith.theme.borderRadius.appBorderRadius}}\",\"children\":{},\"isSpellCheck\":false,\"iconAlign\":\"left\",\"position\":7,\"isDisabled\":false,\"cellBoxShadow\":\"none\",\"fieldType\":\"Text Input\"},\"col12\":{\"labelTextSize\":\"0.875rem\",\"identifier\":\"col12\",\"isRequired\":false,\"boxShadow\":\"none\",\"isCustomField\":false,\"defaultValue\":\"{{((sourceData, formData, fieldState) => (sourceData.col12))(insert_form.sourceData, insert_form.formData, insert_form.fieldState)}}\",\"accentColor\":\"{{appsmith.theme.colors.primaryColor}}\",\"dataType\":\"null\",\"cellBorderRadius\":\"0px\",\"accessor\":\"col12\",\"isVisible\":true,\"label\":\"Col 12\",\"originalIdentifier\":\"col12\",\"borderRadius\":\"{{appsmith.theme.borderRadius.appBorderRadius}}\",\"children\":{},\"isSpellCheck\":false,\"iconAlign\":\"left\",\"position\":11,\"isDisabled\":false,\"cellBoxShadow\":\"none\",\"fieldType\":\"Text Input\"},\"col9\":{\"labelTextSize\":\"0.875rem\",\"identifier\":\"col9\",\"isRequired\":false,\"boxShadow\":\"none\",\"isCustomField\":false,\"defaultValue\":\"{{((sourceData, formData, fieldState) => (sourceData.col9))(insert_form.sourceData, insert_form.formData, insert_form.fieldState)}}\",\"accentColor\":\"{{appsmith.theme.colors.primaryColor}}\",\"dataType\":\"null\",\"cellBorderRadius\":\"0px\",\"accessor\":\"col9\",\"isVisible\":true,\"label\":\"Col 9\",\"originalIdentifier\":\"col9\",\"borderRadius\":\"{{appsmith.theme.borderRadius.appBorderRadius}}\",\"children\":{},\"isSpellCheck\":false,\"iconAlign\":\"left\",\"position\":8,\"isDisabled\":false,\"cellBoxShadow\":\"none\",\"fieldType\":\"Text Input\"},\"col11\":{\"labelTextSize\":\"0.875rem\",\"identifier\":\"col11\",\"isRequired\":false,\"boxShadow\":\"none\",\"isCustomField\":false,\"defaultValue\":\"{{((sourceData, formData, fieldState) => (sourceData.col11))(insert_form.sourceData, insert_form.formData, insert_form.fieldState)}}\",\"accentColor\":\"{{appsmith.theme.colors.primaryColor}}\",\"dataType\":\"null\",\"cellBorderRadius\":\"0px\",\"accessor\":\"col11\",\"isVisible\":true,\"label\":\"Col 11\",\"originalIdentifier\":\"col11\",\"borderRadius\":\"{{appsmith.theme.borderRadius.appBorderRadius}}\",\"children\":{},\"isSpellCheck\":false,\"iconAlign\":\"left\",\"position\":10,\"isDisabled\":false,\"cellBoxShadow\":\"none\",\"fieldType\":\"Text Input\"},\"col6\":{\"labelTextSize\":\"0.875rem\",\"identifier\":\"col6\",\"isRequired\":false,\"boxShadow\":\"none\",\"isCustomField\":false,\"defaultValue\":\"{{((sourceData, formData, fieldState) => (sourceData.col6))(insert_form.sourceData, insert_form.formData, insert_form.fieldState)}}\",\"accentColor\":\"{{appsmith.theme.colors.primaryColor}}\",\"dataType\":\"null\",\"cellBorderRadius\":\"0px\",\"accessor\":\"col6\",\"isVisible\":true,\"label\":\"Col 6\",\"originalIdentifier\":\"col6\",\"borderRadius\":\"{{appsmith.theme.borderRadius.appBorderRadius}}\",\"children\":{},\"isSpellCheck\":false,\"iconAlign\":\"left\",\"position\":5,\"isDisabled\":false,\"cellBoxShadow\":\"none\",\"fieldType\":\"Text Input\"},\"col10\":{\"labelTextSize\":\"0.875rem\",\"identifier\":\"col10\",\"isRequired\":false,\"boxShadow\":\"none\",\"isCustomField\":false,\"defaultValue\":\"{{((sourceData, formData, fieldState) => (sourceData.col10))(insert_form.sourceData, insert_form.formData, insert_form.fieldState)}}\",\"accentColor\":\"{{appsmith.theme.colors.primaryColor}}\",\"dataType\":\"null\",\"cellBorderRadius\":\"0px\",\"accessor\":\"col10\",\"isVisible\":true,\"label\":\"Col 10\",\"originalIdentifier\":\"col10\",\"borderRadius\":\"{{appsmith.theme.borderRadius.appBorderRadius}}\",\"children\":{},\"isSpellCheck\":false,\"iconAlign\":\"left\",\"position\":9,\"isDisabled\":false,\"cellBoxShadow\":\"none\",\"fieldType\":\"Text Input\"},\"col7\":{\"labelTextSize\":\"0.875rem\",\"identifier\":\"col7\",\"isRequired\":false,\"boxShadow\":\"none\",\"isCustomField\":false,\"defaultValue\":\"{{((sourceData, formData, fieldState) => (sourceData.col7))(insert_form.sourceData, insert_form.formData, insert_form.fieldState)}}\",\"accentColor\":\"{{appsmith.theme.colors.primaryColor}}\",\"dataType\":\"null\",\"cellBorderRadius\":\"0px\",\"accessor\":\"col7\",\"isVisible\":true,\"label\":\"Col 7\",\"originalIdentifier\":\"col7\",\"borderRadius\":\"{{appsmith.theme.borderRadius.appBorderRadius}}\",\"children\":{},\"isSpellCheck\":false,\"iconAlign\":\"left\",\"position\":6,\"isDisabled\":false,\"cellBoxShadow\":\"none\",\"fieldType\":\"Text Input\"},\"col4\":{\"labelTextSize\":\"0.875rem\",\"identifier\":\"col4\",\"isRequired\":false,\"boxShadow\":\"none\",\"isCustomField\":false,\"defaultValue\":\"{{((sourceData, formData, fieldState) => (sourceData.col4))(insert_form.sourceData, insert_form.formData, insert_form.fieldState)}}\",\"accentColor\":\"{{appsmith.theme.colors.primaryColor}}\",\"dataType\":\"boolean\",\"cellBorderRadius\":\"0px\",\"accessor\":\"col4\",\"isVisible\":true,\"label\":\"Col 4\",\"alignWidget\":\"LEFT\",\"originalIdentifier\":\"col4\",\"borderRadius\":\"0px\",\"children\":{},\"position\":3,\"isDisabled\":false,\"sourceData\":true,\"cellBoxShadow\":\"none\",\"fieldType\":\"Switch\"},\"col5\":{\"labelTextSize\":\"0.875rem\",\"identifier\":\"col5\",\"boxShadow\":\"none\",\"isRequired\":false,\"isCustomField\":false,\"defaultValue\":\"{{((sourceData, formData, fieldState) => (sourceData.col5))(insert_form.sourceData, insert_form.formData, insert_form.fieldState)}}\",\"accentColor\":\"{{appsmith.theme.colors.primaryColor}}\",\"dataType\":\"number\",\"accessor\":\"col5\",\"isVisible\":true,\"label\":\"Col 5\",\"originalIdentifier\":\"col5\",\"borderRadius\":\"{{appsmith.theme.borderRadius.appBorderRadius}}\",\"children\":{},\"isSpellCheck\":false,\"iconAlign\":\"left\",\"position\":4,\"isDisabled\":false,\"fieldType\":\"Number Input\"},\"col2\":{\"labelTextSize\":\"0.875rem\",\"identifier\":\"col2\",\"isRequired\":false,\"boxShadow\":\"none\",\"isCustomField\":false,\"defaultValue\":\"{{((sourceData, formData, fieldState) => (sourceData.col2))(insert_form.sourceData, insert_form.formData, insert_form.fieldState)}}\",\"accentColor\":\"{{appsmith.theme.colors.primaryColor}}\",\"dataType\":\"string\",\"cellBorderRadius\":\"0px\",\"accessor\":\"col2\",\"isVisible\":true,\"label\":\"Col 2\",\"originalIdentifier\":\"col2\",\"borderRadius\":\"{{appsmith.theme.borderRadius.appBorderRadius}}\",\"children\":{},\"isSpellCheck\":false,\"iconAlign\":\"left\",\"position\":1,\"isDisabled\":false,\"sourceData\":\"skill B\",\"cellBoxShadow\":\"none\",\"fieldType\":\"Text Input\"},\"col3\":{\"labelTextSize\":\"0.875rem\",\"identifier\":\"col3\",\"isRequired\":false,\"boxShadow\":\"none\",\"isCustomField\":false,\"defaultValue\":\"{{((sourceData, formData, fieldState) => (sourceData.col3))(insert_form.sourceData, insert_form.formData, insert_form.fieldState)}}\",\"accentColor\":\"{{appsmith.theme.colors.primaryColor}}\",\"dataType\":\"number\",\"cellBorderRadius\":\"0px\",\"accessor\":\"col3\",\"isVisible\":true,\"label\":\"Col 3\",\"originalIdentifier\":\"col3\",\"borderRadius\":\"{{appsmith.theme.borderRadius.appBorderRadius}}\",\"children\":{},\"isSpellCheck\":false,\"iconAlign\":\"left\",\"position\":2,\"isDisabled\":false,\"sourceData\":9,\"cellBoxShadow\":\"none\",\"fieldType\":\"Number Input\"},\"col1\":{\"labelTextSize\":\"0.875rem\",\"identifier\":\"col1\",\"boxShadow\":\"none\",\"isRequired\":false,\"isCustomField\":false,\"defaultValue\":\"{{((sourceData, formData, fieldState) => (sourceData.col1))(insert_form.sourceData, insert_form.formData, insert_form.fieldState)}}\",\"accentColor\":\"{{appsmith.theme.colors.primaryColor}}\",\"dataType\":\"number\",\"accessor\":\"col1\",\"isVisible\":true,\"label\":\"Col 1\",\"originalIdentifier\":\"col1\",\"borderRadius\":\"{{appsmith.theme.borderRadius.appBorderRadius}}\",\"children\":{},\"isSpellCheck\":false,\"iconAlign\":\"left\",\"position\":0,\"isDisabled\":false,\"sourceData\":5,\"fieldType\":\"Number Input\"}},\"position\":-1,\"isDisabled\":false,\"sourceData\":{\"col4\":true,\"col2\":\"skill B\",\"col3\":9,\"col1\":5},\"cellBoxShadow\":\"none\",\"fieldType\":\"Object\"}},\"boxShadow\":\"none\",\"widgetName\":\"insert_form\",\"submitButtonStyles\":{\"boxShadow\":\"none\",\"borderRadius\":\"{{appsmith.theme.borderRadius.appBorderRadius}}\",\"buttonColor\":\"{{appsmith.theme.colors.primaryColor}}\",\"buttonVariant\":\"PRIMARY\"},\"dynamicPropertyPathList\":[{\"key\":\"schema.__root_schema__.children.date_of_birth.defaultValue\"},{\"key\":\"schema.__root_schema__.children.col5.defaultValue\"},{\"key\":\"schema.__root_schema__.children.col4.defaultValue\"},{\"key\":\"onSubmit\"}],\"displayName\":\"JSON Form\",\"iconSVG\":\"/static/media/icon.6bacf7df.svg\",\"onSubmit\":\"{{InsertQuery.run(\\n\\t() => SelectQuery.run()\\n\\t\\t\\t\\t\\t.then(() => closeModal(Insert_Modal.name)), \\n\\t(error) => showAlert(`Error while inserting resource!\\\\n ${error}`,'error'))\\n}}\",\"topRow\":0,\"bottomRow\":81,\"fieldLimitExceeded\":false,\"parentRowSpace\":10,\"title\":\"Insert Row\",\"type\":\"JSON_FORM_WIDGET\",\"hideCard\":false,\"animateLoading\":true,\"parentColumnSpace\":8.125,\"dynamicTriggerPathList\":[{\"key\":\"onSubmit\"}],\"leftColumn\":0,\"dynamicBindingPathList\":[{\"key\":\"schema.__root_schema__.defaultValue\"},{\"key\":\"sourceData\"},{\"key\":\"schema.__root_schema__.children.col3.defaultValue\"},{\"key\":\"schema.__root_schema__.children.col4.defaultValue\"},{\"key\":\"schema.__root_schema__.children.col5.defaultValue\"},{\"key\":\"schema.__root_schema__.children.col2.defaultValue\"},{\"key\":\"schema.__root_schema__.children.col6.defaultValue\"},{\"key\":\"schema.__root_schema__.children.col7.defaultValue\"},{\"key\":\"schema.__root_schema__.children.col8.defaultValue\"},{\"key\":\"schema.__root_schema__.children.col9.defaultValue\"},{\"key\":\"schema.__root_schema__.children.col10.defaultValue\"},{\"key\":\"schema.__root_schema__.children.col11.defaultValue\"},{\"key\":\"schema.__root_schema__.children.col12.defaultValue\"},{\"key\":\"schema.__root_schema__.children.col5.accentColor\"},{\"key\":\"schema.__root_schema__.children.col5.borderRadius\"},{\"key\":\"schema.__root_schema__.borderRadius\"},{\"key\":\"schema.__root_schema__.cellBorderRadius\"},{\"key\":\"schema.__root_schema__.children.col1.defaultValue\"},{\"key\":\"schema.__root_schema__.children.col1.accentColor\"},{\"key\":\"schema.__root_schema__.children.col1.borderRadius\"},{\"key\":\"borderRadius\"},{\"key\":\"submitButtonStyles.buttonColor\"},{\"key\":\"submitButtonStyles.borderRadius\"},{\"key\":\"resetButtonStyles.borderRadius\"},{\"key\":\"resetButtonStyles.buttonColor\"},{\"key\":\"schema.__root_schema__.children.col2.accentColor\"},{\"key\":\"schema.__root_schema__.children.col2.borderRadius\"},{\"key\":\"schema.__root_schema__.children.col3.accentColor\"},{\"key\":\"schema.__root_schema__.children.col3.borderRadius\"},{\"key\":\"schema.__root_schema__.children.col4.accentColor\"},{\"key\":\"schema.__root_schema__.children.col6.accentColor\"},{\"key\":\"schema.__root_schema__.children.col6.borderRadius\"},{\"key\":\"schema.__root_schema__.children.col7.accentColor\"},{\"key\":\"schema.__root_schema__.children.col7.borderRadius\"},{\"key\":\"schema.__root_schema__.children.col8.accentColor\"},{\"key\":\"schema.__root_schema__.children.col8.borderRadius\"},{\"key\":\"schema.__root_schema__.children.col9.accentColor\"},{\"key\":\"schema.__root_schema__.children.col9.borderRadius\"},{\"key\":\"schema.__root_schema__.children.col10.accentColor\"},{\"key\":\"schema.__root_schema__.children.col10.borderRadius\"},{\"key\":\"schema.__root_schema__.children.col11.accentColor\"},{\"key\":\"schema.__root_schema__.children.col11.borderRadius\"},{\"key\":\"schema.__root_schema__.children.col12.accentColor\"},{\"key\":\"schema.__root_schema__.children.col12.borderRadius\"}],\"sourceData\":\"{{_.omit(data_table.tableData[0], \\\"customColumn1\\\", \\\"id\\\")}}\",\"showReset\":true,\"resetButtonLabel\":\"Reset\",\"key\":\"h9l9ozr8op\",\"labelTextSize\":\"0.875rem\",\"backgroundColor\":\"#fff\",\"rightColumn\":64,\"dynamicHeight\":\"FIXED\",\"autoGenerateForm\":true,\"widgetId\":\"o8oiq6vwkk\",\"resetButtonStyles\":{\"boxShadow\":\"none\",\"borderRadius\":\"{{appsmith.theme.borderRadius.appBorderRadius}}\",\"buttonColor\":\"{{appsmith.theme.colors.primaryColor}}\",\"buttonVariant\":\"SECONDARY\"},\"isVisible\":\"true\",\"version\":1,\"parentId\":\"9rhv3ioohq\",\"renderMode\":\"CANVAS\",\"isLoading\":false,\"scrollContents\":true,\"fixedFooter\":true,\"submitButtonLabel\":\"Submit\",\"childStylesheet\":{\"CHECKBOX\":{\"borderRadius\":\"{{appsmith.theme.borderRadius.appBorderRadius}}\",\"accentColor\":\"{{appsmith.theme.colors.primaryColor}}\"},\"ARRAY\":{\"boxShadow\":\"none\",\"borderRadius\":\"{{appsmith.theme.borderRadius.appBorderRadius}}\",\"accentColor\":\"{{appsmith.theme.colors.primaryColor}}\",\"cellBorderRadius\":\"{{appsmith.theme.borderRadius.appBorderRadius}}\",\"cellBoxShadow\":\"none\"},\"CURRENCY_INPUT\":{\"boxShadow\":\"none\",\"borderRadius\":\"{{appsmith.theme.borderRadius.appBorderRadius}}\",\"accentColor\":\"{{appsmith.theme.colors.primaryColor}}\"},\"DATEPICKER\":{\"boxShadow\":\"none\",\"borderRadius\":\"{{appsmith.theme.borderRadius.appBorderRadius}}\",\"accentColor\":\"{{appsmith.theme.colors.primaryColor}}\"},\"PHONE_NUMBER_INPUT\":{\"boxShadow\":\"none\",\"borderRadius\":\"{{appsmith.theme.borderRadius.appBorderRadius}}\",\"accentColor\":\"{{appsmith.theme.colors.primaryColor}}\"},\"OBJECT\":{\"boxShadow\":\"none\",\"borderRadius\":\"{{appsmith.theme.borderRadius.appBorderRadius}}\",\"cellBorderRadius\":\"{{appsmith.theme.borderRadius.appBorderRadius}}\",\"cellBoxShadow\":\"none\"},\"MULTISELECT\":{\"boxShadow\":\"none\",\"borderRadius\":\"{{appsmith.theme.borderRadius.appBorderRadius}}\",\"accentColor\":\"{{appsmith.theme.colors.primaryColor}}\"},\"SELECT\":{\"boxShadow\":\"none\",\"borderRadius\":\"{{appsmith.theme.borderRadius.appBorderRadius}}\",\"accentColor\":\"{{appsmith.theme.colors.primaryColor}}\"},\"NUMBER_INPUT\":{\"boxShadow\":\"none\",\"borderRadius\":\"{{appsmith.theme.borderRadius.appBorderRadius}}\",\"accentColor\":\"{{appsmith.theme.colors.primaryColor}}\"},\"PASSWORD_INPUT\":{\"boxShadow\":\"none\",\"borderRadius\":\"{{appsmith.theme.borderRadius.appBorderRadius}}\",\"accentColor\":\"{{appsmith.theme.colors.primaryColor}}\"},\"EMAIL_INPUT\":{\"boxShadow\":\"none\",\"borderRadius\":\"{{appsmith.theme.borderRadius.appBorderRadius}}\",\"accentColor\":\"{{appsmith.theme.colors.primaryColor}}\"},\"RADIO_GROUP\":{\"boxShadow\":\"none\",\"accentColor\":\"{{appsmith.theme.colors.primaryColor}}\"},\"SWITCH\":{\"boxShadow\":\"none\",\"accentColor\":\"{{appsmith.theme.colors.primaryColor}}\"},\"TEXT_INPUT\":{\"boxShadow\":\"none\",\"borderRadius\":\"{{appsmith.theme.borderRadius.appBorderRadius}}\",\"accentColor\":\"{{appsmith.theme.colors.primaryColor}}\"},\"MULTILINE_TEXT_INPUT\":{\"boxShadow\":\"none\",\"borderRadius\":\"{{appsmith.theme.borderRadius.appBorderRadius}}\",\"accentColor\":\"{{appsmith.theme.colors.primaryColor}}\"}},\"disabledWhenInvalid\":true,\"borderRadius\":\"{{appsmith.theme.borderRadius.appBorderRadius}}\",\"maxDynamicHeight\":9000,\"minDynamicHeight\":4}],\"parentId\":\"9rhv3ioohq\"}],\"flexLayers\":[]}"} \ No newline at end of file diff --git a/app/client/cypress/fixtures/PgAdmindsl.json b/app/client/cypress/fixtures/PgAdmindsl.json index c196bfcc72fa..e24e3aeaaac9 100644 --- a/app/client/cypress/fixtures/PgAdmindsl.json +++ b/app/client/cypress/fixtures/PgAdmindsl.json @@ -375,7 +375,7 @@ "bottomRow": true, "parentId": true }, - "onClick": "{{showModal('Modal1')}}" + "onClick": "{{showModal(Modal1.name)}}" } }, "widgetName": "List1", @@ -751,7 +751,7 @@ }, { "widgetName": "Button2", - "onClick": "{{showModal('Modal1')}}", + "onClick": "{{showModal(Modal1.name)}}", "buttonColor": "#DD4B34", "dynamicPropertyPathList": [ { "key": "onClick" } @@ -854,7 +854,7 @@ }, { "widgetName": "Button3", - "onClick": "{{showModal('nt_modal')}}", + "onClick": "{{showModal(nt_modal.name)}}", "buttonColor": "#03B365", "dynamicPropertyPathList": [], "displayName": "Button", @@ -1036,7 +1036,7 @@ "iconName": "pencil-fill-icon", "buttonVariant": "SECONDARY", "boxShadow": "NONE", - "onClick": "{{showModal('ec_modal')}}" + "onClick": "{{showModal(ec_modal.name)}}" }, "starelid": { "index": 0, @@ -1637,7 +1637,7 @@ }, { "widgetName": "Button6", - "onClick": "{{showModal('nc_modal')}}", + "onClick": "{{showModal(nc_modal.name)}}", "buttonColor": "#03B365", "dynamicPropertyPathList": [{ "key": "onClick" }], "displayName": "Button", @@ -1862,7 +1862,7 @@ { "resetFormOnClick": true, "widgetName": "FormButton2", - "onClick": "{{closeModal('nt_modal')}}", + "onClick": "{{closeModal(nt_modal.name)}}", "rightColumn": 17, "isDefaultClickDisabled": true, "buttonColor": "#03B365", @@ -2104,7 +2104,7 @@ }, { "widgetName": "Button5", - "onClick": "{{showModal('nt_col_modal')}}", + "onClick": "{{showModal(nt_col_modal.name)}}", "buttonColor": "#03B365", "displayName": "Button", "iconSVG": "/static/media/icon.cca02633.svg", @@ -2240,7 +2240,7 @@ { "resetFormOnClick": true, "widgetName": "FormButton3", - "onClick": "{{(()=>{\n\tconst nt_col = appsmith.store.nt_col ||[];\nnt_col.push({\n\t\tname:nt_col_name.text,\ndtype:nt_col_type.selectedOptionValue,\npkey:nt_col_pkey.isSwitchedOn,\nnnull:nt_col_nnull.isSwitchedOn});\nstoreValue('nt_col',nt_col)\n\tshowModal('nt_modal')\n})()}}", + "onClick": "{{(()=>{\n\tconst nt_col = appsmith.store.nt_col ||[];\nnt_col.push({\n\t\tname:nt_col_name.text,\ndtype:nt_col_type.selectedOptionValue,\npkey:nt_col_pkey.isSwitchedOn,\nnnull:nt_col_nnull.isSwitchedOn});\nstoreValue('nt_col',nt_col)\n\tshowModal(nt_modal.name)\n})()}}", "buttonColor": "#03B365", "dynamicPropertyPathList": [{ "key": "onClick" }], "displayName": "FormButton", @@ -2595,7 +2595,7 @@ { "resetFormOnClick": true, "widgetName": "FormButton5", - "onClick": "{{create_column.run(()=>{get_columns.run();\ncloseModal('nc_modal');\t\t})}}", + "onClick": "{{create_column.run(()=>{get_columns.run();\ncloseModal(nc_modal.name);\t\t})}}", "buttonColor": "#03B365", "dynamicPropertyPathList": [{ "key": "onClick" }], "displayName": "FormButton", @@ -3219,7 +3219,7 @@ { "widgetName": "Icon1", "rightColumn": 63, - "onClick": "{{closeModal('Modal1')}}", + "onClick": "{{closeModal(Modal1.name)}}", "color": "#040627", "iconName": "cross", "displayName": "Icon", @@ -3265,7 +3265,7 @@ }, { "widgetName": "Button7", - "onClick": "{{closeModal('Modal1')}}", + "onClick": "{{closeModal(Modal1.name)}}", "buttonColor": "#03B365", "displayName": "Button", "iconSVG": "/static/media/icon.cca02633.svg", diff --git a/app/client/cypress/fixtures/autocomp.json b/app/client/cypress/fixtures/autocomp.json index 39244e7bac37..b0d364a319b8 100644 --- a/app/client/cypress/fixtures/autocomp.json +++ b/app/client/cypress/fixtures/autocomp.json @@ -473,7 +473,7 @@ "isRequired": false, "widgetName": "Icon1", "rightColumn": 64, - "onClick": "{{closeModal('TestModal')}}", + "onClick": "{{closeModal(TestModal.name)}}", "color": "#040627", "iconName": "cross", "widgetId": "n5fc0ven2a", diff --git a/app/client/cypress/fixtures/commondsl.json b/app/client/cypress/fixtures/commondsl.json index b780924fa39a..6f8078dcdb36 100644 --- a/app/client/cypress/fixtures/commondsl.json +++ b/app/client/cypress/fixtures/commondsl.json @@ -436,7 +436,7 @@ { "widgetName": "Icon1", "rightColumn": 16, - "onClick": "{{closeModal('TestModal')}}", + "onClick": "{{closeModal(TestModal.name)}}", "color": "#040627", "iconName": "cross", "widgetId": "n5fc0ven2a", diff --git a/app/client/cypress/fixtures/defaultMetadataDsl.json b/app/client/cypress/fixtures/defaultMetadataDsl.json index 1ca1661dde79..51881f4dfdea 100644 --- a/app/client/cypress/fixtures/defaultMetadataDsl.json +++ b/app/client/cypress/fixtures/defaultMetadataDsl.json @@ -79,7 +79,7 @@ "key": "borderRadius" } ], - "onClick": "{{closeModal('Modal1')}}" + "onClick": "{{closeModal(Modal1.name)}}" }, { "isVisible": true, @@ -158,7 +158,7 @@ "key": "borderRadius" } ], - "onClick": "{{closeModal('Modal1')}}" + "onClick": "{{closeModal(Modal1.name)}}" }, { "isVisible": true, diff --git a/app/client/cypress/fixtures/dynamicHeightFormSwitchdsl.json b/app/client/cypress/fixtures/dynamicHeightFormSwitchdsl.json index dc490bab43e1..82440b610b8a 100644 --- a/app/client/cypress/fixtures/dynamicHeightFormSwitchdsl.json +++ b/app/client/cypress/fixtures/dynamicHeightFormSwitchdsl.json @@ -145,7 +145,7 @@ "key": "accentColor" } ], - "onSelectionChange": "{{showModal('Modal1')}}", + "onSelectionChange": "{{showModal(Modal1.name)}}", "dynamicTriggerPathList": [ { "key": "onSelectionChange" @@ -269,7 +269,7 @@ "key": "borderRadius" } ], - "onClick": "{{closeModal('Modal1')}}" + "onClick": "{{closeModal(Modal1.name)}}" }, { "isVisible": true, @@ -356,7 +356,7 @@ "key": "borderRadius" } ], - "onClick": "{{closeModal('Modal1')}}" + "onClick": "{{closeModal(Modal1.name)}}" }, { "isVisible": true, diff --git a/app/client/cypress/fixtures/editorContextdsl.json b/app/client/cypress/fixtures/editorContextdsl.json index 6aa427fae76f..de6270a7b6b1 100644 --- a/app/client/cypress/fixtures/editorContextdsl.json +++ b/app/client/cypress/fixtures/editorContextdsl.json @@ -149,7 +149,7 @@ { "boxShadow": "none", "widgetName": "IconButton1", - "onClick": "{{closeModal('Modal1')}}", + "onClick": "{{closeModal(Modal1.name)}}", "buttonColor": "{{appsmith.theme.colors.primaryColor}}", "displayName": "Icon button", "iconSVG": "/static/media/icon.1a0c634ac75f9fa6b6ae7a8df882a3ba.svg", @@ -229,7 +229,7 @@ "resetFormOnClick": false, "boxShadow": "none", "widgetName": "Button2", - "onClick": "{{closeModal('Modal1')}}", + "onClick": "{{closeModal(Modal1.name)}}", "buttonColor": "{{appsmith.theme.colors.primaryColor}}", "displayName": "Button", "iconSVG": "/static/media/icon.cca026338f1c8eb6df8ba03d084c2fca.svg", diff --git a/app/client/cypress/fixtures/explorerHiddenWidgets.json b/app/client/cypress/fixtures/explorerHiddenWidgets.json index 7f4851e0bb74..ad17b3e68963 100644 --- a/app/client/cypress/fixtures/explorerHiddenWidgets.json +++ b/app/client/cypress/fixtures/explorerHiddenWidgets.json @@ -723,7 +723,7 @@ { "boxShadow": "none", "widgetName": "IconButton2", - "onClick": "{{closeModal('SimpleModal')}}", + "onClick": "{{closeModal(SimpleModal.name)}}", "buttonColor": "{{appsmith.theme.colors.primaryColor}}", "displayName": "Icon button", "iconSVG": "/static/media/icon.1a0c634ac75f9fa6b6ae7a8df882a3ba.svg", @@ -810,7 +810,7 @@ "resetFormOnClick": false, "boxShadow": "none", "widgetName": "Button3", - "onClick": "{{closeModal('Modal2')}}", + "onClick": "{{closeModal(Modal2.name)}}", "buttonColor": "{{appsmith.theme.colors.primaryColor}}", "displayName": "Button", "iconSVG": "/static/media/icon.cca026338f1c8eb6df8ba03d084c2fca.svg", diff --git a/app/client/cypress/fixtures/filePickerV2WidgetReskinDsl.json b/app/client/cypress/fixtures/filePickerV2WidgetReskinDsl.json index 1b0bb7b2db7f..aa2f2a646b2d 100644 --- a/app/client/cypress/fixtures/filePickerV2WidgetReskinDsl.json +++ b/app/client/cypress/fixtures/filePickerV2WidgetReskinDsl.json @@ -112,7 +112,7 @@ { "boxShadow": "none", "widgetName": "IconButton1", - "onClick": "{{closeModal('Modal1')}}", + "onClick": "{{closeModal(Modal1.name)}}", "buttonColor": "{{appsmith.theme.colors.primaryColor}}", "displayName": "Icon button", "iconSVG": "/static/media/icon.1a0c634ac75f9fa6b6ae7a8df882a3ba.svg", @@ -188,7 +188,7 @@ { "boxShadow": "none", "widgetName": "Button1", - "onClick": "{{closeModal('Modal1')}}", + "onClick": "{{closeModal(Modal1.name)}}", "buttonColor": "{{appsmith.theme.colors.primaryColor}}", "displayName": "Button", "iconSVG": "/static/media/icon.cca026338f1c8eb6df8ba03d084c2fca.svg", diff --git a/app/client/cypress/fixtures/jsonFormDynamicHeightDsl.json b/app/client/cypress/fixtures/jsonFormDynamicHeightDsl.json index c0f2fd693514..43d2e43904db 100644 --- a/app/client/cypress/fixtures/jsonFormDynamicHeightDsl.json +++ b/app/client/cypress/fixtures/jsonFormDynamicHeightDsl.json @@ -69,7 +69,7 @@ { "boxShadow": "none", "widgetName": "IconButton1", - "onClick": "{{closeModal('Modal1')}}", + "onClick": "{{closeModal(Modal1.name)}}", "buttonColor": "{{appsmith.theme.colors.primaryColor}}", "displayName": "Icon button", "iconSVG": "/static/media/icon.1a0c634ac75f9fa6b6ae7a8df882a3ba.svg", @@ -152,7 +152,7 @@ "resetFormOnClick": false, "boxShadow": "none", "widgetName": "Button1", - "onClick": "{{closeModal('Modal1')}}", + "onClick": "{{closeModal(Modal1.name)}}", "buttonColor": "{{appsmith.theme.colors.primaryColor}}", "displayName": "Button", "iconSVG": "/static/media/icon.cca026338f1c8eb6df8ba03d084c2fca.svg", diff --git a/app/client/cypress/fixtures/jsonFormInModalDsl.json b/app/client/cypress/fixtures/jsonFormInModalDsl.json index 9afcd9273edb..3ec810021758 100644 --- a/app/client/cypress/fixtures/jsonFormInModalDsl.json +++ b/app/client/cypress/fixtures/jsonFormInModalDsl.json @@ -59,7 +59,7 @@ { "boxShadow": "NONE", "widgetName": "IconButton1", - "onClick": "{{closeModal('Modal1')}}", + "onClick": "{{closeModal(Modal1.name)}}", "buttonColor": "#2E3D49", "displayName": "Icon button", "iconSVG": "/static/media/icon.1a0c634a.svg", @@ -112,7 +112,7 @@ }, { "widgetName": "Button1", - "onClick": "{{closeModal('Modal1')}}", + "onClick": "{{closeModal(Modal1.name)}}", "buttonColor": "#03B365", "displayName": "Button", "iconSVG": "/static/media/icon.cca02633.svg", @@ -463,7 +463,7 @@ "isDisabled": false, "isDerived": false, "label": "action", - "onClick": "{{showModal('Modal1')}}", + "onClick": "{{showModal(Modal1.name)}}", "computedValue": "{{Table1.sanitizedTableData.map((currentRow) => ( currentRow.action))}}", "buttonColor": "#03B365", "menuColor": "#03B365", diff --git a/app/client/cypress/fixtures/lazyRender.json b/app/client/cypress/fixtures/lazyRender.json index 37d8cd4a433e..02bb7ba86dc3 100644 --- a/app/client/cypress/fixtures/lazyRender.json +++ b/app/client/cypress/fixtures/lazyRender.json @@ -1 +1 @@ -{"dsl":{"widgetName":"MainContainer","backgroundColor":"none","rightColumn":4896,"snapColumns":64,"detachFromLayout":true,"widgetId":"0","topRow":0,"bottomRow":1810,"containerStyle":"none","snapRows":125,"parentRowSpace":1,"type":"CANVAS_WIDGET","canExtend":true,"version":71,"minHeight":1292,"dynamicTriggerPathList":[],"parentColumnSpace":1,"dynamicBindingPathList":[],"leftColumn":0,"children":[{"isVisible":true,"label":"Label","labelPosition":"Top","labelAlignment":"left","labelTextSize":"0.875rem","labelWidth":5,"widgetName":"PhoneInput1","version":1,"defaultText":"","iconAlign":"left","autoFocus":false,"labelStyle":"","resetOnSubmit":true,"isRequired":false,"isDisabled":false,"animateLoading":true,"defaultDialCode":"+1","allowDialCodeChange":false,"allowFormatting":true,"minDynamicHeight":4,"maxDynamicHeight":9000,"dynamicHeight":"FIXED","searchTags":["call"],"type":"PHONE_INPUT_WIDGET","hideCard":false,"isDeprecated":false,"displayName":"Phone Input","key":"ljiw4y9d0k","iconSVG":"/static/media/icon.108789d7165de30306435ab3c24e6cad.svg","widgetId":"75v1xxqwnk","renderMode":"CANVAS","accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none","isLoading":false,"parentColumnSpace":20.0625,"parentRowSpace":10,"leftColumn":20,"rightColumn":40,"topRow":6,"bottomRow":13,"parentId":"0","dynamicBindingPathList":[{"key":"accentColor"},{"key":"borderRadius"}]},{"isVisible":true,"animateLoading":true,"defaultSelectedRowIndex":0,"defaultSelectedRowIndices":[0],"label":"Data","widgetName":"Table2","searchKey":"","textSize":"0.875rem","horizontalAlignment":"LEFT","verticalAlignment":"CENTER","totalRecordsCount":0,"defaultPageSize":0,"dynamicPropertyPathList":[],"borderColor":"#E0DEDE","borderWidth":"1","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"}],"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":"{{Table2.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":"{{Table2.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":"{{Table2.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":"{{Table2.processedTableData.map((currentRow, currentIndex) => ( currentRow[\"action\"]))}}","validation":{},"labelColor":"#FFFFFF","buttonColor":"{{Table2.processedTableData.map((currentRow, currentIndex) => ( appsmith.theme.colors.primaryColor))}}","borderRadius":"{{Table2.processedTableData.map((currentRow, currentIndex) => ( appsmith.theme.borderRadius.appBorderRadius))}}","boxShadow":"{{Table2.processedTableData.map((currentRow, currentIndex) => ( 'none'))}}"}},"tableData":"[\n {\n \"step\": \"#11\",\n \"task\": \"Drop a table\",\n \"status\": \"✅\",\n \"action\": \"\"\n },\n {\n \"step\": \"#2\",\n \"task\": \"Create a query fetch_users with the Mock DB\",\n \"status\": \"--\",\n \"action\": \"\"\n },\n {\n \"step\": \"#3\",\n \"task\": \"Bind the query using => fetch_users.data\",\n \"status\": \"--\",\n \"action\": \"\"\n }\n]","columnWidthMap":{"task":245,"step":62,"status":75},"columnOrder":["step","task","status","action"],"enableClientSideSearch":true,"isVisibleSearch":true,"isVisibleFilters":true,"isVisibleDownload":true,"isVisiblePagination":true,"isSortable":true,"delimiter":",","version":1,"inlineEditingSaveOption":"ROW_LEVEL","type":"TABLE_WIDGET_V2","hideCard":false,"isDeprecated":false,"displayName":"Table","key":"0ul35w2hry","iconSVG":"/static/media/icon.db8a9cbd2acd22a31ea91cc37ea2a46c.svg","widgetId":"ccrsdlbcvm","renderMode":"CANVAS","accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"{{appsmith.theme.boxShadow.appBoxShadow}}","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}}"}},"isLoading":false,"parentColumnSpace":20.0625,"parentRowSpace":10,"leftColumn":14,"rightColumn":48,"topRow":145,"bottomRow":173,"parentId":"0","dynamicTriggerPathList":[],"originalTopRow":145,"originalBottomRow":173},{"isVisible":true,"shouldScrollContents":true,"widgetName":"Tabs1","animateLoading":true,"borderWidth":1,"borderColor":"#E0DEDE","backgroundColor":"#FFFFFF","minDynamicHeight":15,"tabsObj":{"tab1":{"label":"Tab 1","id":"tab1","widgetId":"4zaewfci4y","isVisible":true,"index":0},"tab2":{"label":"Tab 2","id":"tab2","widgetId":"i6ac4w48hr","isVisible":true,"index":1}},"shouldShowTabs":true,"defaultTab":"Tab 1","version":3,"maxDynamicHeight":9000,"dynamicHeight":"FIXED","type":"TABS_WIDGET","hideCard":false,"isDeprecated":false,"displayName":"Tabs","key":"blrs9324u1","iconSVG":"/static/media/icon.74a6d653c8201e66f1cd367a3fba2657.svg","isCanvas":true,"widgetId":"576oct3f8g","renderMode":"CANVAS","accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"{{appsmith.theme.boxShadow.appBoxShadow}}","isLoading":false,"parentColumnSpace":20.046875,"parentRowSpace":10,"leftColumn":18,"rightColumn":42,"topRow":28,"bottomRow":57,"parentId":"0","dynamicBindingPathList":[{"key":"accentColor"},{"key":"borderRadius"},{"key":"boxShadow"}],"children":[{"isVisible":true,"widgetName":"Canvas2","version":1,"detachFromLayout":true,"type":"CANVAS_WIDGET","hideCard":true,"isDeprecated":false,"displayName":"Canvas","key":"c5q0qzphez","canExtend":true,"isDisabled":false,"shouldScrollContents":false,"tabId":"tab1","tabName":"Tab 1","children":[],"bottomRow":240,"minHeight":240,"widgetId":"4zaewfci4y","renderMode":"CANVAS","isLoading":false,"parentColumnSpace":1,"parentRowSpace":1,"leftColumn":0,"rightColumn":481.125,"topRow":0,"parentId":"576oct3f8g","dynamicBindingPathList":[]},{"isVisible":true,"widgetName":"Canvas3","version":1,"detachFromLayout":true,"type":"CANVAS_WIDGET","hideCard":true,"isDeprecated":false,"displayName":"Canvas","key":"c5q0qzphez","canExtend":true,"isDisabled":false,"shouldScrollContents":false,"tabId":"tab2","tabName":"Tab 2","children":[{"isVisible":true,"animateLoading":true,"maxCount":5,"defaultRate":3,"activeColor":"{{appsmith.theme.colors.primaryColor}}","inactiveColor":"#E0DEDE","size":"LARGE","isRequired":false,"isAllowHalf":false,"isDisabled":false,"isReadOnly":false,"tooltips":["Terrible","Bad","Neutral","Good","Great"],"widgetName":"Rating2","minDynamicHeight":4,"maxDynamicHeight":9000,"dynamicHeight":"AUTO_HEIGHT","searchTags":["stars"],"type":"RATE_WIDGET","hideCard":false,"isDeprecated":false,"displayName":"Rating","key":"w7tg0fyr4q","iconSVG":"/static/media/icon.914eb943f3f3762263872a333aff727d.svg","widgetId":"c9a0ev0knr","renderMode":"CANVAS","isLoading":false,"parentColumnSpace":7.205078125,"parentRowSpace":10,"leftColumn":22,"rightColumn":42,"topRow":8,"bottomRow":12,"parentId":"i6ac4w48hr","dynamicBindingPathList":[{"key":"activeColor"}]}],"bottomRow":240,"minHeight":240,"widgetId":"i6ac4w48hr","renderMode":"CANVAS","isLoading":false,"parentColumnSpace":1,"parentRowSpace":1,"leftColumn":0,"rightColumn":481.125,"topRow":0,"parentId":"576oct3f8g","dynamicBindingPathList":[]}],"dynamicTriggerPathList":[]},{"width":456,"height":240,"minDynamicHeight":24,"canEscapeKeyClose":true,"animateLoading":true,"detachFromLayout":true,"canOutsideClickClose":true,"shouldScrollContents":true,"widgetName":"Modal2","children":[{"isVisible":true,"widgetName":"Canvas4","version":1,"detachFromLayout":true,"type":"CANVAS_WIDGET","hideCard":true,"isDeprecated":false,"displayName":"Canvas","key":"c5q0qzphez","canExtend":true,"isDisabled":false,"shouldScrollContents":false,"children":[{"isVisible":true,"iconName":"cross","buttonVariant":"TERTIARY","isDisabled":false,"widgetName":"IconButton2","version":1,"animateLoading":true,"searchTags":["click","submit"],"type":"ICON_BUTTON_WIDGET","hideCard":false,"isDeprecated":false,"displayName":"Icon Button","key":"ym75a7w8rt","iconSVG":"/static/media/icon.1a0c634ac75f9fa6b6ae7a8df882a3ba.svg","buttonColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","iconSize":24,"widgetId":"19nbe63tb9","renderMode":"CANVAS","boxShadow":"none","isLoading":false,"leftColumn":58,"rightColumn":64,"topRow":0,"bottomRow":4,"parentId":"22b2arf9sr","dynamicBindingPathList":[{"key":"buttonColor"},{"key":"borderRadius"}],"onClick":"{{closeModal('Modal2')}}"},{"isVisible":true,"text":"Modal Title","fontSize":"1.25rem","fontStyle":"BOLD","textAlign":"LEFT","textColor":"#231F20","widgetName":"Text2","shouldTruncate":false,"overflow":"NONE","version":1,"animateLoading":true,"minDynamicHeight":4,"maxDynamicHeight":9000,"dynamicHeight":"AUTO_HEIGHT","searchTags":["typography","paragraph","label"],"type":"TEXT_WIDGET","hideCard":false,"isDeprecated":false,"displayName":"Text","key":"tutq05ktuy","iconSVG":"/static/media/icon.97c59b523e6f70ba6f40a10fc2c7c5b5.svg","widgetId":"gzae1zsezq","renderMode":"CANVAS","truncateButtonColor":"{{appsmith.theme.colors.primaryColor}}","fontFamily":"{{appsmith.theme.fontFamily.appFont}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","isLoading":false,"leftColumn":1,"rightColumn":41,"topRow":1,"bottomRow":5,"parentId":"22b2arf9sr","dynamicBindingPathList":[{"key":"truncateButtonColor"},{"key":"fontFamily"},{"key":"borderRadius"}]},{"isVisible":true,"animateLoading":true,"text":"Close","buttonVariant":"SECONDARY","placement":"CENTER","widgetName":"Button4","isDisabled":false,"isDefaultClickDisabled":true,"disabledWhenInvalid":false,"resetFormOnClick":false,"recaptchaType":"V3","version":1,"searchTags":["click","submit"],"type":"BUTTON_WIDGET","hideCard":false,"isDeprecated":false,"displayName":"Button","key":"2yyvxh8q6a","iconSVG":"/static/media/icon.cca026338f1c8eb6df8ba03d084c2fca.svg","buttonStyle":"PRIMARY","widgetId":"t0g3x74ibg","renderMode":"CANVAS","buttonColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none","isLoading":false,"leftColumn":31,"rightColumn":47,"topRow":18,"bottomRow":22,"parentId":"22b2arf9sr","dynamicBindingPathList":[{"key":"buttonColor"},{"key":"borderRadius"}],"onClick":"{{closeModal('Modal2')}}"},{"isVisible":true,"animateLoading":true,"text":"Confirm","buttonVariant":"PRIMARY","placement":"CENTER","widgetName":"Button5","isDisabled":false,"isDefaultClickDisabled":true,"disabledWhenInvalid":false,"resetFormOnClick":false,"recaptchaType":"V3","version":1,"searchTags":["click","submit"],"type":"BUTTON_WIDGET","hideCard":false,"isDeprecated":false,"displayName":"Button","key":"2yyvxh8q6a","iconSVG":"/static/media/icon.cca026338f1c8eb6df8ba03d084c2fca.svg","buttonStyle":"PRIMARY_BUTTON","widgetId":"8288muyiw3","renderMode":"CANVAS","buttonColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none","isLoading":false,"leftColumn":47,"rightColumn":63,"topRow":18,"bottomRow":22,"parentId":"22b2arf9sr","dynamicBindingPathList":[{"key":"buttonColor"},{"key":"borderRadius"}]},{"isVisible":true,"label":"Label","labelPosition":"Top","labelAlignment":"left","labelTextSize":"0.875rem","labelWidth":5,"widgetName":"Input1","version":2,"defaultText":"","iconAlign":"left","autoFocus":false,"labelStyle":"","resetOnSubmit":true,"isRequired":false,"isDisabled":false,"animateLoading":true,"inputType":"TEXT","minDynamicHeight":4,"maxDynamicHeight":9000,"dynamicHeight":"FIXED","searchTags":["form","text input","number","textarea"],"type":"INPUT_WIDGET_V2","hideCard":false,"isDeprecated":false,"displayName":"Input","key":"2r6vo22qxp","iconSVG":"/static/media/icon.9f505595da61a34f563dba82adeb06ec.svg","widgetId":"qmku1b7xmj","renderMode":"CANVAS","accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none","isLoading":false,"parentColumnSpace":6.9375,"parentRowSpace":10,"leftColumn":21,"rightColumn":41,"topRow":7,"bottomRow":14,"parentId":"22b2arf9sr","dynamicBindingPathList":[{"key":"accentColor"},{"key":"borderRadius"}]}],"minHeight":240,"widgetId":"22b2arf9sr","renderMode":"CANVAS","isLoading":false,"parentColumnSpace":1,"parentRowSpace":1,"leftColumn":0,"rightColumn":481.125,"topRow":0,"bottomRow":240,"parentId":"gicjvabcts","dynamicBindingPathList":[]}],"version":2,"maxDynamicHeight":9000,"dynamicHeight":"AUTO_HEIGHT","searchTags":["dialog","popup","notification"],"type":"MODAL_WIDGET","hideCard":false,"isDeprecated":false,"displayName":"Modal","key":"u8mxhf08ot","iconSVG":"/static/media/icon.4975978e9a961fb0bfb4e38de7ecc7c5.svg","isCanvas":true,"widgetId":"gicjvabcts","renderMode":"CANVAS","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none","isLoading":false,"parentColumnSpace":20.046875,"parentRowSpace":10,"leftColumn":7,"rightColumn":31,"topRow":17,"bottomRow":257,"parentId":"0","dynamicBindingPathList":[{"key":"borderRadius"}]},{"isVisible":true,"animateLoading":true,"text":"Submit","buttonVariant":"PRIMARY","placement":"CENTER","widgetName":"Button6","isDisabled":false,"isDefaultClickDisabled":true,"disabledWhenInvalid":false,"resetFormOnClick":false,"recaptchaType":"V3","version":1,"searchTags":["click","submit"],"type":"BUTTON_WIDGET","hideCard":false,"isDeprecated":false,"displayName":"Button","key":"2yyvxh8q6a","iconSVG":"/static/media/icon.cca026338f1c8eb6df8ba03d084c2fca.svg","widgetId":"wr1yquusjr","renderMode":"CANVAS","buttonColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none","isLoading":false,"parentColumnSpace":20.0625,"parentRowSpace":10,"leftColumn":22,"rightColumn":38,"topRow":20,"bottomRow":24,"parentId":"0","dynamicBindingPathList":[{"key":"buttonColor"},{"key":"borderRadius"}],"onClick":"{{showModal('Modal2')}}","dynamicTriggerPathList":[{"key":"onClick"}]}]}} \ No newline at end of file +{"dsl":{"widgetName":"MainContainer","backgroundColor":"none","rightColumn":4896,"snapColumns":64,"detachFromLayout":true,"widgetId":"0","topRow":0,"bottomRow":1810,"containerStyle":"none","snapRows":125,"parentRowSpace":1,"type":"CANVAS_WIDGET","canExtend":true,"version":71,"minHeight":1292,"dynamicTriggerPathList":[],"parentColumnSpace":1,"dynamicBindingPathList":[],"leftColumn":0,"children":[{"isVisible":true,"label":"Label","labelPosition":"Top","labelAlignment":"left","labelTextSize":"0.875rem","labelWidth":5,"widgetName":"PhoneInput1","version":1,"defaultText":"","iconAlign":"left","autoFocus":false,"labelStyle":"","resetOnSubmit":true,"isRequired":false,"isDisabled":false,"animateLoading":true,"defaultDialCode":"+1","allowDialCodeChange":false,"allowFormatting":true,"minDynamicHeight":4,"maxDynamicHeight":9000,"dynamicHeight":"FIXED","searchTags":["call"],"type":"PHONE_INPUT_WIDGET","hideCard":false,"isDeprecated":false,"displayName":"Phone Input","key":"ljiw4y9d0k","iconSVG":"/static/media/icon.108789d7165de30306435ab3c24e6cad.svg","widgetId":"75v1xxqwnk","renderMode":"CANVAS","accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none","isLoading":false,"parentColumnSpace":20.0625,"parentRowSpace":10,"leftColumn":20,"rightColumn":40,"topRow":6,"bottomRow":13,"parentId":"0","dynamicBindingPathList":[{"key":"accentColor"},{"key":"borderRadius"}]},{"isVisible":true,"animateLoading":true,"defaultSelectedRowIndex":0,"defaultSelectedRowIndices":[0],"label":"Data","widgetName":"Table2","searchKey":"","textSize":"0.875rem","horizontalAlignment":"LEFT","verticalAlignment":"CENTER","totalRecordsCount":0,"defaultPageSize":0,"dynamicPropertyPathList":[],"borderColor":"#E0DEDE","borderWidth":"1","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"}],"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":"{{Table2.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":"{{Table2.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":"{{Table2.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":"{{Table2.processedTableData.map((currentRow, currentIndex) => ( currentRow[\"action\"]))}}","validation":{},"labelColor":"#FFFFFF","buttonColor":"{{Table2.processedTableData.map((currentRow, currentIndex) => ( appsmith.theme.colors.primaryColor))}}","borderRadius":"{{Table2.processedTableData.map((currentRow, currentIndex) => ( appsmith.theme.borderRadius.appBorderRadius))}}","boxShadow":"{{Table2.processedTableData.map((currentRow, currentIndex) => ( 'none'))}}"}},"tableData":"[\n {\n \"step\": \"#11\",\n \"task\": \"Drop a table\",\n \"status\": \"✅\",\n \"action\": \"\"\n },\n {\n \"step\": \"#2\",\n \"task\": \"Create a query fetch_users with the Mock DB\",\n \"status\": \"--\",\n \"action\": \"\"\n },\n {\n \"step\": \"#3\",\n \"task\": \"Bind the query using => fetch_users.data\",\n \"status\": \"--\",\n \"action\": \"\"\n }\n]","columnWidthMap":{"task":245,"step":62,"status":75},"columnOrder":["step","task","status","action"],"enableClientSideSearch":true,"isVisibleSearch":true,"isVisibleFilters":true,"isVisibleDownload":true,"isVisiblePagination":true,"isSortable":true,"delimiter":",","version":1,"inlineEditingSaveOption":"ROW_LEVEL","type":"TABLE_WIDGET_V2","hideCard":false,"isDeprecated":false,"displayName":"Table","key":"0ul35w2hry","iconSVG":"/static/media/icon.db8a9cbd2acd22a31ea91cc37ea2a46c.svg","widgetId":"ccrsdlbcvm","renderMode":"CANVAS","accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"{{appsmith.theme.boxShadow.appBoxShadow}}","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}}"}},"isLoading":false,"parentColumnSpace":20.0625,"parentRowSpace":10,"leftColumn":14,"rightColumn":48,"topRow":145,"bottomRow":173,"parentId":"0","dynamicTriggerPathList":[],"originalTopRow":145,"originalBottomRow":173},{"isVisible":true,"shouldScrollContents":true,"widgetName":"Tabs1","animateLoading":true,"borderWidth":1,"borderColor":"#E0DEDE","backgroundColor":"#FFFFFF","minDynamicHeight":15,"tabsObj":{"tab1":{"label":"Tab 1","id":"tab1","widgetId":"4zaewfci4y","isVisible":true,"index":0},"tab2":{"label":"Tab 2","id":"tab2","widgetId":"i6ac4w48hr","isVisible":true,"index":1}},"shouldShowTabs":true,"defaultTab":"Tab 1","version":3,"maxDynamicHeight":9000,"dynamicHeight":"FIXED","type":"TABS_WIDGET","hideCard":false,"isDeprecated":false,"displayName":"Tabs","key":"blrs9324u1","iconSVG":"/static/media/icon.74a6d653c8201e66f1cd367a3fba2657.svg","isCanvas":true,"widgetId":"576oct3f8g","renderMode":"CANVAS","accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"{{appsmith.theme.boxShadow.appBoxShadow}}","isLoading":false,"parentColumnSpace":20.046875,"parentRowSpace":10,"leftColumn":18,"rightColumn":42,"topRow":28,"bottomRow":57,"parentId":"0","dynamicBindingPathList":[{"key":"accentColor"},{"key":"borderRadius"},{"key":"boxShadow"}],"children":[{"isVisible":true,"widgetName":"Canvas2","version":1,"detachFromLayout":true,"type":"CANVAS_WIDGET","hideCard":true,"isDeprecated":false,"displayName":"Canvas","key":"c5q0qzphez","canExtend":true,"isDisabled":false,"shouldScrollContents":false,"tabId":"tab1","tabName":"Tab 1","children":[],"bottomRow":240,"minHeight":240,"widgetId":"4zaewfci4y","renderMode":"CANVAS","isLoading":false,"parentColumnSpace":1,"parentRowSpace":1,"leftColumn":0,"rightColumn":481.125,"topRow":0,"parentId":"576oct3f8g","dynamicBindingPathList":[]},{"isVisible":true,"widgetName":"Canvas3","version":1,"detachFromLayout":true,"type":"CANVAS_WIDGET","hideCard":true,"isDeprecated":false,"displayName":"Canvas","key":"c5q0qzphez","canExtend":true,"isDisabled":false,"shouldScrollContents":false,"tabId":"tab2","tabName":"Tab 2","children":[{"isVisible":true,"animateLoading":true,"maxCount":5,"defaultRate":3,"activeColor":"{{appsmith.theme.colors.primaryColor}}","inactiveColor":"#E0DEDE","size":"LARGE","isRequired":false,"isAllowHalf":false,"isDisabled":false,"isReadOnly":false,"tooltips":["Terrible","Bad","Neutral","Good","Great"],"widgetName":"Rating2","minDynamicHeight":4,"maxDynamicHeight":9000,"dynamicHeight":"AUTO_HEIGHT","searchTags":["stars"],"type":"RATE_WIDGET","hideCard":false,"isDeprecated":false,"displayName":"Rating","key":"w7tg0fyr4q","iconSVG":"/static/media/icon.914eb943f3f3762263872a333aff727d.svg","widgetId":"c9a0ev0knr","renderMode":"CANVAS","isLoading":false,"parentColumnSpace":7.205078125,"parentRowSpace":10,"leftColumn":22,"rightColumn":42,"topRow":8,"bottomRow":12,"parentId":"i6ac4w48hr","dynamicBindingPathList":[{"key":"activeColor"}]}],"bottomRow":240,"minHeight":240,"widgetId":"i6ac4w48hr","renderMode":"CANVAS","isLoading":false,"parentColumnSpace":1,"parentRowSpace":1,"leftColumn":0,"rightColumn":481.125,"topRow":0,"parentId":"576oct3f8g","dynamicBindingPathList":[]}],"dynamicTriggerPathList":[]},{"width":456,"height":240,"minDynamicHeight":24,"canEscapeKeyClose":true,"animateLoading":true,"detachFromLayout":true,"canOutsideClickClose":true,"shouldScrollContents":true,"widgetName":"Modal2","children":[{"isVisible":true,"widgetName":"Canvas4","version":1,"detachFromLayout":true,"type":"CANVAS_WIDGET","hideCard":true,"isDeprecated":false,"displayName":"Canvas","key":"c5q0qzphez","canExtend":true,"isDisabled":false,"shouldScrollContents":false,"children":[{"isVisible":true,"iconName":"cross","buttonVariant":"TERTIARY","isDisabled":false,"widgetName":"IconButton2","version":1,"animateLoading":true,"searchTags":["click","submit"],"type":"ICON_BUTTON_WIDGET","hideCard":false,"isDeprecated":false,"displayName":"Icon Button","key":"ym75a7w8rt","iconSVG":"/static/media/icon.1a0c634ac75f9fa6b6ae7a8df882a3ba.svg","buttonColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","iconSize":24,"widgetId":"19nbe63tb9","renderMode":"CANVAS","boxShadow":"none","isLoading":false,"leftColumn":58,"rightColumn":64,"topRow":0,"bottomRow":4,"parentId":"22b2arf9sr","dynamicBindingPathList":[{"key":"buttonColor"},{"key":"borderRadius"}],"onClick":"{{closeModal(Modal2.name)}}"},{"isVisible":true,"text":"Modal Title","fontSize":"1.25rem","fontStyle":"BOLD","textAlign":"LEFT","textColor":"#231F20","widgetName":"Text2","shouldTruncate":false,"overflow":"NONE","version":1,"animateLoading":true,"minDynamicHeight":4,"maxDynamicHeight":9000,"dynamicHeight":"AUTO_HEIGHT","searchTags":["typography","paragraph","label"],"type":"TEXT_WIDGET","hideCard":false,"isDeprecated":false,"displayName":"Text","key":"tutq05ktuy","iconSVG":"/static/media/icon.97c59b523e6f70ba6f40a10fc2c7c5b5.svg","widgetId":"gzae1zsezq","renderMode":"CANVAS","truncateButtonColor":"{{appsmith.theme.colors.primaryColor}}","fontFamily":"{{appsmith.theme.fontFamily.appFont}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","isLoading":false,"leftColumn":1,"rightColumn":41,"topRow":1,"bottomRow":5,"parentId":"22b2arf9sr","dynamicBindingPathList":[{"key":"truncateButtonColor"},{"key":"fontFamily"},{"key":"borderRadius"}]},{"isVisible":true,"animateLoading":true,"text":"Close","buttonVariant":"SECONDARY","placement":"CENTER","widgetName":"Button4","isDisabled":false,"isDefaultClickDisabled":true,"disabledWhenInvalid":false,"resetFormOnClick":false,"recaptchaType":"V3","version":1,"searchTags":["click","submit"],"type":"BUTTON_WIDGET","hideCard":false,"isDeprecated":false,"displayName":"Button","key":"2yyvxh8q6a","iconSVG":"/static/media/icon.cca026338f1c8eb6df8ba03d084c2fca.svg","buttonStyle":"PRIMARY","widgetId":"t0g3x74ibg","renderMode":"CANVAS","buttonColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none","isLoading":false,"leftColumn":31,"rightColumn":47,"topRow":18,"bottomRow":22,"parentId":"22b2arf9sr","dynamicBindingPathList":[{"key":"buttonColor"},{"key":"borderRadius"}],"onClick":"{{closeModal(Modal2.name)}}"},{"isVisible":true,"animateLoading":true,"text":"Confirm","buttonVariant":"PRIMARY","placement":"CENTER","widgetName":"Button5","isDisabled":false,"isDefaultClickDisabled":true,"disabledWhenInvalid":false,"resetFormOnClick":false,"recaptchaType":"V3","version":1,"searchTags":["click","submit"],"type":"BUTTON_WIDGET","hideCard":false,"isDeprecated":false,"displayName":"Button","key":"2yyvxh8q6a","iconSVG":"/static/media/icon.cca026338f1c8eb6df8ba03d084c2fca.svg","buttonStyle":"PRIMARY_BUTTON","widgetId":"8288muyiw3","renderMode":"CANVAS","buttonColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none","isLoading":false,"leftColumn":47,"rightColumn":63,"topRow":18,"bottomRow":22,"parentId":"22b2arf9sr","dynamicBindingPathList":[{"key":"buttonColor"},{"key":"borderRadius"}]},{"isVisible":true,"label":"Label","labelPosition":"Top","labelAlignment":"left","labelTextSize":"0.875rem","labelWidth":5,"widgetName":"Input1","version":2,"defaultText":"","iconAlign":"left","autoFocus":false,"labelStyle":"","resetOnSubmit":true,"isRequired":false,"isDisabled":false,"animateLoading":true,"inputType":"TEXT","minDynamicHeight":4,"maxDynamicHeight":9000,"dynamicHeight":"FIXED","searchTags":["form","text input","number","textarea"],"type":"INPUT_WIDGET_V2","hideCard":false,"isDeprecated":false,"displayName":"Input","key":"2r6vo22qxp","iconSVG":"/static/media/icon.9f505595da61a34f563dba82adeb06ec.svg","widgetId":"qmku1b7xmj","renderMode":"CANVAS","accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none","isLoading":false,"parentColumnSpace":6.9375,"parentRowSpace":10,"leftColumn":21,"rightColumn":41,"topRow":7,"bottomRow":14,"parentId":"22b2arf9sr","dynamicBindingPathList":[{"key":"accentColor"},{"key":"borderRadius"}]}],"minHeight":240,"widgetId":"22b2arf9sr","renderMode":"CANVAS","isLoading":false,"parentColumnSpace":1,"parentRowSpace":1,"leftColumn":0,"rightColumn":481.125,"topRow":0,"bottomRow":240,"parentId":"gicjvabcts","dynamicBindingPathList":[]}],"version":2,"maxDynamicHeight":9000,"dynamicHeight":"AUTO_HEIGHT","searchTags":["dialog","popup","notification"],"type":"MODAL_WIDGET","hideCard":false,"isDeprecated":false,"displayName":"Modal","key":"u8mxhf08ot","iconSVG":"/static/media/icon.4975978e9a961fb0bfb4e38de7ecc7c5.svg","isCanvas":true,"widgetId":"gicjvabcts","renderMode":"CANVAS","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none","isLoading":false,"parentColumnSpace":20.046875,"parentRowSpace":10,"leftColumn":7,"rightColumn":31,"topRow":17,"bottomRow":257,"parentId":"0","dynamicBindingPathList":[{"key":"borderRadius"}]},{"isVisible":true,"animateLoading":true,"text":"Submit","buttonVariant":"PRIMARY","placement":"CENTER","widgetName":"Button6","isDisabled":false,"isDefaultClickDisabled":true,"disabledWhenInvalid":false,"resetFormOnClick":false,"recaptchaType":"V3","version":1,"searchTags":["click","submit"],"type":"BUTTON_WIDGET","hideCard":false,"isDeprecated":false,"displayName":"Button","key":"2yyvxh8q6a","iconSVG":"/static/media/icon.cca026338f1c8eb6df8ba03d084c2fca.svg","widgetId":"wr1yquusjr","renderMode":"CANVAS","buttonColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none","isLoading":false,"parentColumnSpace":20.0625,"parentRowSpace":10,"leftColumn":22,"rightColumn":38,"topRow":20,"bottomRow":24,"parentId":"0","dynamicBindingPathList":[{"key":"buttonColor"},{"key":"borderRadius"}],"onClick":"{{showModal(Modal2.name)}}","dynamicTriggerPathList":[{"key":"onClick"}]}]}} \ No newline at end of file diff --git a/app/client/cypress/fixtures/listwidgetData.json b/app/client/cypress/fixtures/listwidgetData.json index beb287ef1340..485941abdffd 100644 --- a/app/client/cypress/fixtures/listwidgetData.json +++ b/app/client/cypress/fixtures/listwidgetData.json @@ -1041,7 +1041,7 @@ "boxShadow": "none", "mobileBottomRow": 4, "widgetName": "IconButton1", - "onClick": "{{closeModal('Modal_1');}}", + "onClick": "{{closeModal(Modal_1.name);}}", "buttonColor": "{{appsmith.theme.colors.primaryColor}}", "displayName": "Icon button", "iconSVG": "/static/media/icon.b08054586989b185a0801e9a34f8ad49.svg", @@ -1155,7 +1155,7 @@ "boxShadow": "none", "mobileBottomRow": 22, "widgetName": "Button1", - "onClick": "{{closeModal('Modal1')}}", + "onClick": "{{closeModal(Modal1.name)}}", "buttonColor": "{{appsmith.theme.colors.primaryColor}}", "displayName": "Button", "iconSVG": "/static/media/icon.05d209fafeb13a8569e3b4e97069d9ee.svg", diff --git a/app/client/cypress/fixtures/modalOnTableFilterPaneDsl.json b/app/client/cypress/fixtures/modalOnTableFilterPaneDsl.json index a969c070b1f2..5bf41f9f89d2 100644 --- a/app/client/cypress/fixtures/modalOnTableFilterPaneDsl.json +++ b/app/client/cypress/fixtures/modalOnTableFilterPaneDsl.json @@ -58,7 +58,7 @@ { "widgetName": "Icon1", "rightColumn": 64, - "onClick": "{{closeModal('Modal1')}}", + "onClick": "{{closeModal(Modal1.name)}}", "color": "#040627", "iconName": "cross", "displayName": "Icon", @@ -102,7 +102,7 @@ }, { "widgetName": "Button1", - "onClick": "{{closeModal('Modal1')}}", + "onClick": "{{closeModal(Modal1.name)}}", "buttonColor": "#03B365", "displayName": "Button", "iconSVG": "/static/media/icon.cca02633.svg", @@ -171,7 +171,7 @@ }, { "widgetName": "Button3", - "onClick": "{{showModal('Modal1')}}", + "onClick": "{{showModal(Modal1.name)}}", "buttonColor": "#03B365", "displayName": "Button", "iconSVG": "/static/media/icon.cca02633.svg", diff --git a/app/client/cypress/fixtures/modalScroll.json b/app/client/cypress/fixtures/modalScroll.json index b8e66c7f4957..c705459650bb 100644 --- a/app/client/cypress/fixtures/modalScroll.json +++ b/app/client/cypress/fixtures/modalScroll.json @@ -59,7 +59,7 @@ { "widgetName": "Icon1", "rightColumn": 64, - "onClick": "{{closeModal('Modal1')}}", + "onClick": "{{closeModal(Modal1.name)}}", "color": "#040627", "iconName": "cross", "displayName": "Icon", @@ -107,7 +107,7 @@ }, { "widgetName": "Button1", - "onClick": "{{closeModal('Modal1')}}", + "onClick": "{{closeModal(Modal1.name)}}", "buttonColor": "#03B365", "displayName": "Button", "iconSVG": "/static/media/icon.cca02633.svg", @@ -342,7 +342,7 @@ }, { "widgetName": "Button3", - "onClick": "{{showModal('Modal1')}}", + "onClick": "{{showModal(Modal1.name)}}", "buttonColor": "#03B365", "displayName": "Button", "iconSVG": "/static/media/icon.cca02633.svg", diff --git a/app/client/cypress/fixtures/modalWidgetBGcolorDSL.json b/app/client/cypress/fixtures/modalWidgetBGcolorDSL.json index 034845ea20bf..87d2f440a2fe 100644 --- a/app/client/cypress/fixtures/modalWidgetBGcolorDSL.json +++ b/app/client/cypress/fixtures/modalWidgetBGcolorDSL.json @@ -24,7 +24,7 @@ "resetFormOnClick": false, "boxShadow": "none", "widgetName": "Button1", - "onClick": "{{showModal('Modal1')}}", + "onClick": "{{showModal(Modal1.name)}}", "buttonColor": "{{appsmith.theme.colors.primaryColor}}", "displayName": "Button", "iconSVG": "/static/media/icon.cca026338f1c8eb6df8ba03d084c2fca.svg", @@ -109,7 +109,7 @@ { "boxShadow": "none", "widgetName": "IconButton1", - "onClick": "{{closeModal('Modal1')}}", + "onClick": "{{closeModal(Modal1.name)}}", "buttonColor": "{{appsmith.theme.colors.primaryColor}}", "displayName": "Icon button", "iconSVG": "/static/media/icon.1a0c634ac75f9fa6b6ae7a8df882a3ba.svg", @@ -192,7 +192,7 @@ "resetFormOnClick": false, "boxShadow": "none", "widgetName": "Button2", - "onClick": "{{closeModal('Modal1')}}", + "onClick": "{{closeModal(Modal1.name)}}", "buttonColor": "{{appsmith.theme.colors.primaryColor}}", "displayName": "Button", "iconSVG": "/static/media/icon.cca026338f1c8eb6df8ba03d084c2fca.svg", diff --git a/app/client/cypress/fixtures/modalWidgetTestApp.json b/app/client/cypress/fixtures/modalWidgetTestApp.json index 388b7c8c1411..93186b6d0f2b 100644 --- a/app/client/cypress/fixtures/modalWidgetTestApp.json +++ b/app/client/cypress/fixtures/modalWidgetTestApp.json @@ -56,7 +56,7 @@ "boxShadow": "none", "mobileBottomRow": 12.0, "widgetName": "Button1", - "onClick": "{{showModal('Modal1');}}", + "onClick": "{{showModal(Modal1.name);}}", "buttonColor": "{{appsmith.theme.colors.primaryColor}}", "displayName": "Button", "iconSVG": "/static/media/icon.05d209fafeb13a8569e3b4e97069d9ee.svg", @@ -145,7 +145,7 @@ "boxShadow": "none", "mobileBottomRow": 4.0, "widgetName": "IconButton1", - "onClick": "{{closeModal('Modal1')}}", + "onClick": "{{closeModal(Modal1.name)}}", "buttonColor": "{{appsmith.theme.colors.primaryColor}}", "displayName": "Icon button", "iconSVG": "/static/media/icon.b08054586989b185a0801e9a34f8ad49.svg", @@ -1804,7 +1804,7 @@ "responsiveBehavior": "fill", "mobileLeftColumn": 7.0, "maxDynamicHeight": 9000.0, - "onOptionChange": "{{showModal('Modal2');}}", + "onOptionChange": "{{showModal(Modal2.name);}}", "minDynamicHeight": 4.0 }, { @@ -1852,7 +1852,7 @@ "boxShadow": "none", "mobileBottomRow": 4.0, "widgetName": "IconButton3", - "onClick": "{{closeModal('Modal2')}}", + "onClick": "{{closeModal(Modal2.name)}}", "buttonColor": "{{appsmith.theme.colors.primaryColor}}", "displayName": "Icon button", "iconSVG": "/static/media/icon.b08054586989b185a0801e9a34f8ad49.svg", @@ -2340,7 +2340,7 @@ "rightColumn": 59.0, "widgetId": "b7fjdn1ail", "minWidth": 450.0, - "onItemClick": "{{showModal('Modal3');}}", + "onItemClick": "{{showModal(Modal3.name);}}", "parentId": "0", "renderMode": "CANVAS", "mobileTopRow": 17.0, @@ -2393,7 +2393,7 @@ "boxShadow": "none", "mobileBottomRow": 4.0, "widgetName": "IconButton4", - "onClick": "{{closeModal('Modal3')}}", + "onClick": "{{closeModal(Modal3.name)}}", "buttonColor": "{{appsmith.theme.colors.primaryColor}}", "displayName": "Icon button", "iconSVG": "/static/media/icon.b08054586989b185a0801e9a34f8ad49.svg", @@ -2481,7 +2481,7 @@ "boxShadow": "none", "mobileBottomRow": 22.0, "widgetName": "Button2", - "onClick": "{{closeModal('Modal3')}}", + "onClick": "{{closeModal(Modal3.name)}}", "buttonColor": "{{appsmith.theme.colors.primaryColor}}", "displayName": "Button", "iconSVG": "/static/media/icon.05d209fafeb13a8569e3b4e97069d9ee.svg", @@ -2644,7 +2644,7 @@ "totalRecordsCount": 0.0, "tags": ["Suggested", "Display"], "isLoading": false, - "onSearchTextChanged": "{{showModal('Modal4');}}", + "onSearchTextChanged": "{{showModal(Modal4.name);}}", "childStylesheet": { "button": { "buttonColor": "{{appsmith.theme.colors.primaryColor}}", @@ -2950,7 +2950,7 @@ "boxShadow": "none", "mobileBottomRow": 4.0, "widgetName": "IconButton5", - "onClick": "{{closeModal('Modal4')}}", + "onClick": "{{closeModal(Modal4.name)}}", "buttonColor": "{{appsmith.theme.colors.primaryColor}}", "displayName": "Icon button", "iconSVG": "/static/media/icon.b08054586989b185a0801e9a34f8ad49.svg", @@ -3038,7 +3038,7 @@ "boxShadow": "none", "mobileBottomRow": 22.0, "widgetName": "Button4", - "onClick": "{{closeModal('Modal4')}}", + "onClick": "{{closeModal(Modal4.name)}}", "buttonColor": "{{appsmith.theme.colors.primaryColor}}", "displayName": "Button", "iconSVG": "/static/media/icon.05d209fafeb13a8569e3b4e97069d9ee.svg", @@ -3170,7 +3170,7 @@ "boxShadow": "{{appsmith.theme.boxShadow.appBoxShadow}}", "borderColor": "#E0DEDE", "iconSVG": "/static/media/icon.46adf7030d667f0ad9002aa31f997573.svg", - "onSubmit": "{{showModal('Modal5');}}", + "onSubmit": "{{showModal(Modal5.name);}}", "topRow": 61.0, "type": "JSON_FORM_WIDGET", "animateLoading": true, @@ -3498,7 +3498,7 @@ "boxShadow": "none", "mobileBottomRow": 4.0, "widgetName": "IconButton6", - "onClick": "{{closeModal('Modal5')}}", + "onClick": "{{closeModal(Modal5.name)}}", "buttonColor": "{{appsmith.theme.colors.primaryColor}}", "displayName": "Icon button", "iconSVG": "/static/media/icon.b08054586989b185a0801e9a34f8ad49.svg", @@ -3586,7 +3586,7 @@ "boxShadow": "none", "mobileBottomRow": 22.0, "widgetName": "Button6", - "onClick": "{{closeModal('Modal5')}}", + "onClick": "{{closeModal(Modal5.name)}}", "buttonColor": "{{appsmith.theme.colors.primaryColor}}", "displayName": "Button", "iconSVG": "/static/media/icon.05d209fafeb13a8569e3b4e97069d9ee.svg", @@ -3771,7 +3771,7 @@ "boxShadow": "none", "mobileBottomRow": 12.0, "widgetName": "Button1", - "onClick": "{{showModal('Modal1');}}", + "onClick": "{{showModal(Modal1.name);}}", "buttonColor": "{{appsmith.theme.colors.primaryColor}}", "displayName": "Button", "iconSVG": "/static/media/icon.05d209fafeb13a8569e3b4e97069d9ee.svg", @@ -3860,7 +3860,7 @@ "boxShadow": "none", "mobileBottomRow": 4.0, "widgetName": "IconButton1", - "onClick": "{{closeModal('Modal1')}}", + "onClick": "{{closeModal(Modal1.name)}}", "buttonColor": "{{appsmith.theme.colors.primaryColor}}", "displayName": "Icon button", "iconSVG": "/static/media/icon.b08054586989b185a0801e9a34f8ad49.svg", @@ -5519,7 +5519,7 @@ "responsiveBehavior": "fill", "mobileLeftColumn": 7.0, "maxDynamicHeight": 9000.0, - "onOptionChange": "{{showModal('Modal2');}}", + "onOptionChange": "{{showModal(Modal2.name);}}", "minDynamicHeight": 4.0 }, { @@ -5567,7 +5567,7 @@ "boxShadow": "none", "mobileBottomRow": 4.0, "widgetName": "IconButton3", - "onClick": "{{closeModal('Modal2')}}", + "onClick": "{{closeModal(Modal2.name)}}", "buttonColor": "{{appsmith.theme.colors.primaryColor}}", "displayName": "Icon button", "iconSVG": "/static/media/icon.b08054586989b185a0801e9a34f8ad49.svg", @@ -6055,7 +6055,7 @@ "rightColumn": 59.0, "widgetId": "b7fjdn1ail", "minWidth": 450.0, - "onItemClick": "{{showModal('Modal3');}}", + "onItemClick": "{{showModal(Modal3.name);}}", "parentId": "0", "renderMode": "CANVAS", "mobileTopRow": 17.0, @@ -6108,7 +6108,7 @@ "boxShadow": "none", "mobileBottomRow": 4.0, "widgetName": "IconButton4", - "onClick": "{{closeModal('Modal3')}}", + "onClick": "{{closeModal(Modal3.name)}}", "buttonColor": "{{appsmith.theme.colors.primaryColor}}", "displayName": "Icon button", "iconSVG": "/static/media/icon.b08054586989b185a0801e9a34f8ad49.svg", @@ -6196,7 +6196,7 @@ "boxShadow": "none", "mobileBottomRow": 22.0, "widgetName": "Button2", - "onClick": "{{closeModal('Modal3')}}", + "onClick": "{{closeModal(Modal3.name)}}", "buttonColor": "{{appsmith.theme.colors.primaryColor}}", "displayName": "Button", "iconSVG": "/static/media/icon.05d209fafeb13a8569e3b4e97069d9ee.svg", @@ -6359,7 +6359,7 @@ "totalRecordsCount": 0.0, "tags": ["Suggested", "Display"], "isLoading": false, - "onSearchTextChanged": "{{showModal('Modal4');}}", + "onSearchTextChanged": "{{showModal(Modal4.name);}}", "childStylesheet": { "button": { "buttonColor": "{{appsmith.theme.colors.primaryColor}}", @@ -6665,7 +6665,7 @@ "boxShadow": "none", "mobileBottomRow": 4.0, "widgetName": "IconButton5", - "onClick": "{{closeModal('Modal4')}}", + "onClick": "{{closeModal(Modal4.name)}}", "buttonColor": "{{appsmith.theme.colors.primaryColor}}", "displayName": "Icon button", "iconSVG": "/static/media/icon.b08054586989b185a0801e9a34f8ad49.svg", @@ -6753,7 +6753,7 @@ "boxShadow": "none", "mobileBottomRow": 22.0, "widgetName": "Button4", - "onClick": "{{closeModal('Modal4')}}", + "onClick": "{{closeModal(Modal4.name)}}", "buttonColor": "{{appsmith.theme.colors.primaryColor}}", "displayName": "Button", "iconSVG": "/static/media/icon.05d209fafeb13a8569e3b4e97069d9ee.svg", @@ -6885,7 +6885,7 @@ "boxShadow": "{{appsmith.theme.boxShadow.appBoxShadow}}", "borderColor": "#E0DEDE", "iconSVG": "/static/media/icon.46adf7030d667f0ad9002aa31f997573.svg", - "onSubmit": "{{showModal('Modal5');}}", + "onSubmit": "{{showModal(Modal5.name);}}", "topRow": 61.0, "type": "JSON_FORM_WIDGET", "animateLoading": true, @@ -7213,7 +7213,7 @@ "boxShadow": "none", "mobileBottomRow": 4.0, "widgetName": "IconButton6", - "onClick": "{{closeModal('Modal5')}}", + "onClick": "{{closeModal(Modal5.name)}}", "buttonColor": "{{appsmith.theme.colors.primaryColor}}", "displayName": "Icon button", "iconSVG": "/static/media/icon.b08054586989b185a0801e9a34f8ad49.svg", @@ -7301,7 +7301,7 @@ "boxShadow": "none", "mobileBottomRow": 22.0, "widgetName": "Button6", - "onClick": "{{closeModal('Modal5')}}", + "onClick": "{{closeModal(Modal5.name)}}", "buttonColor": "{{appsmith.theme.colors.primaryColor}}", "displayName": "Button", "iconSVG": "/static/media/icon.05d209fafeb13a8569e3b4e97069d9ee.svg", diff --git a/app/client/cypress/fixtures/mongo_PUT_replaceLayoutWithCRUD.json b/app/client/cypress/fixtures/mongo_PUT_replaceLayoutWithCRUD.json index 3f6918e32e76..7d72912ab9e2 100644 --- a/app/client/cypress/fixtures/mongo_PUT_replaceLayoutWithCRUD.json +++ b/app/client/cypress/fixtures/mongo_PUT_replaceLayoutWithCRUD.json @@ -1 +1 @@ -{"responseMeta":{"status":201,"success":true},"data":{"page":{"id":"616d7d4c9594b25adfa3e569","name":"Page3","applicationId":null,"layouts":[{"id":"616d7d4c9594b25adfa3e568","userPermissions":[],"dsl":{"widgetName":"MainContainer","backgroundColor":"none","rightColumn":1280,"snapColumns":64,"detachFromLayout":true,"widgetId":"0","topRow":0,"bottomRow":940,"containerStyle":"none","snapRows":125,"parentRowSpace":1,"type":"CANVAS_WIDGET","canExtend":true,"version":41,"minHeight":860,"parentColumnSpace":1,"dynamicTriggerPathList":[],"dynamicBindingPathList":[],"leftColumn":0,"children":[{"backgroundColor":"#FFFFFF","widgetName":"Container1","rightColumn":40,"widgetId":"mvubsemxfo","containerStyle":"card","topRow":0,"bottomRow":87,"parentRowSpace":10,"isVisible":"true","type":"CONTAINER_WIDGET","version":1,"parentId":"0","isLoading":false,"parentColumnSpace":19.75,"leftColumn":0,"children":[{"widgetName":"Canvas1","rightColumn":632,"detachFromLayout":true,"widgetId":"59rw5mx0bq","containerStyle":"none","topRow":0,"bottomRow":890,"parentRowSpace":1,"isVisible":"true","canExtend":false,"type":"CANVAS_WIDGET","version":1,"parentId":"mvubsemxfo","minHeight":870,"isLoading":false,"parentColumnSpace":1,"dynamicTriggerPathList":[],"leftColumn":0,"dynamicBindingPathList":[],"children":[{"widgetName":"data_table","columnOrder":["customColumn1","_id","col4","col2","col3","col1"],"dynamicPropertyPathList":[{"key":"onPageChange"}],"isVisibleDownload":true,"topRow":10,"bottomRow":86,"parentRowSpace":10,"onPageChange":"{{FindQuery.run()}}","type":"TABLE_WIDGET","defaultSelectedRow":"0","parentColumnSpace":1,"dynamicTriggerPathList":[{"key":"onPageChange"},{"key":"primaryColumns.customColumn1.onClick"},{"key":"onSearchTextChanged"}],"dynamicBindingPathList":[{"key":"primaryColumns.customColumn1.buttonLabel"},{"key":"tableData"},{"key":"primaryColumns.col1.computedValue"},{"key":"primaryColumns.col2.computedValue"},{"key":"primaryColumns.col3.computedValue"},{"key":"primaryColumns.col4.computedValue"},{"key":"primaryColumns._id.computedValue"}],"leftColumn":0,"primaryColumns":{"customColumn1":{"isCellVisible":true,"isDerived":true,"computedValue":"","onClick":"{{showModal('Delete_Modal')}}","textSize":"PARAGRAPH","buttonColor":"#DD4B34","index":7,"isVisible":true,"label":"Delete","buttonLabel":"{{data_table.sanitizedTableData.map((currentRow) => { return 'Delete'})}}","columnType":"button","horizontalAlignment":"LEFT","width":150,"enableFilter":true,"enableSort":true,"id":"customColumn1","isDisabled":false,"buttonLabelColor":"#FFFFFF","verticalAlignment":"CENTER"},"col4":{"isCellVisible":true,"isDerived":false,"computedValue":"{{data_table.sanitizedTableData.map((currentRow) => ( currentRow.col4))}}","textSize":"PARAGRAPH","index":3,"isVisible":true,"label":"col4","columnType":"text","horizontalAlignment":"LEFT","width":150,"enableFilter":true,"enableSort":true,"id":"col4","verticalAlignment":"CENTER"},"_id":{"isCellVisible":true,"isDerived":false,"computedValue":"{{data_table.sanitizedTableData.map((currentRow) => ( currentRow._id))}}","textSize":"PARAGRAPH","index":1,"isVisible":true,"label":"_id","columnType":"text","horizontalAlignment":"LEFT","width":150,"enableFilter":true,"enableSort":true,"id":"_id","verticalAlignment":"CENTER"},"col2":{"isCellVisible":true,"isDerived":false,"computedValue":"{{data_table.sanitizedTableData.map((currentRow) => ( currentRow.col2))}}","textSize":"PARAGRAPH","index":1,"isVisible":true,"label":"col2","columnType":"text","horizontalAlignment":"LEFT","width":150,"enableFilter":true,"enableSort":true,"id":"col2","verticalAlignment":"CENTER"},"col3":{"isCellVisible":true,"isDerived":false,"computedValue":"{{data_table.sanitizedTableData.map((currentRow) => ( currentRow.col3))}}","textSize":"PARAGRAPH","index":2,"isVisible":true,"label":"col3","columnType":"text","horizontalAlignment":"LEFT","width":150,"enableFilter":true,"enableSort":true,"id":"col3","verticalAlignment":"CENTER"},"col1":{"isCellVisible":true,"isDerived":false,"computedValue":"{{data_table.sanitizedTableData.map((currentRow) => ( currentRow.col1))}}","textSize":"PARAGRAPH","index":0,"isVisible":true,"label":"col1","columnType":"text","horizontalAlignment":"LEFT","width":150,"enableFilter":true,"enableSort":true,"id":"col1","verticalAlignment":"CENTER"}},"delimiter":",","derivedColumns":{"customColumn1":{"isDerived":true,"computedValue":"","onClick":"{{DeleteQuery.run()}}","textSize":"PARAGRAPH","buttonStyle":"#DD4B34","index":7,"isVisible":true,"label":"customColumn1","buttonLabel":"{{data_table.sanitizedTableData.map((currentRow) => { return 'Delete'})}}","columnType":"button","horizontalAlignment":"LEFT","width":150,"enableFilter":true,"enableSort":true,"id":"customColumn1","buttonLabelColor":"#FFFFFF","verticalAlignment":"CENTER"}},"rightColumn":64,"textSize":"PARAGRAPH","widgetId":"jabdu9f16g","isVisibleFilters":true,"tableData":"{{FindQuery.data}}","isVisible":"true","label":"Data","searchKey":"","version":3,"parentId":"59rw5mx0bq","serverSidePaginationEnabled":true,"isLoading":false,"isVisibleCompactMode":true,"onSearchTextChanged":"{{FindQuery.run()}}","horizontalAlignment":"LEFT","isVisibleSearch":true,"isVisiblePagination":true,"verticalAlignment":"CENTER","columnSizeMap":{"task":245,"deliveryAddress":170,"step":62,"id":228,"status":75}},{"isRequired":false,"widgetName":"key_select","isFilterable":true,"rightColumn":22,"dynamicPropertyPathList":[{"key":"isVisible"}],"widgetId":"asmgosgxjm","topRow":5,"bottomRow":9,"parentRowSpace":10,"isVisible":"{{FindQuery.data.length > 0}}","label":"","type":"DROP_DOWN_WIDGET","version":1,"parentId":"59rw5mx0bq","isLoading":false,"defaultOptionValue":"genres","parentColumnSpace":18.8828125,"dynamicTriggerPathList":[{"key":"onOptionChange"}],"leftColumn":7,"dynamicBindingPathList":[{"key":"isVisible"}],"options":"[\n{\n\t\"label\": \"poster_path\",\n\t\"value\": \"poster_path\"\n}, \n{\n\t\"label\": \"homepage\",\n\t\"value\": \"homepage\"\n}, \n{\n\t\"label\": \"imdb_id\",\n\t\"value\": \"imdb_id\"\n}, \n{\n\t\"label\": \"genres\",\n\t\"value\": \"genres\"\n}]","onOptionChange":"{{FindQuery.run()}}","isDisabled":false},{"widgetName":"Text15","rightColumn":7,"textAlign":"LEFT","widgetId":"l8pgl90klz","topRow":5,"bottomRow":9,"parentRowSpace":10,"isVisible":"true","fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"59rw5mx0bq","isLoading":false,"parentColumnSpace":19.75,"dynamicTriggerPathList":[],"leftColumn":0,"dynamicBindingPathList":[],"fontSize":"PARAGRAPH","text":"Order By :"},{"isRequired":false,"widgetName":"order_select","isFilterable":true,"rightColumn":30,"dynamicPropertyPathList":[{"key":"isVisible"}],"widgetId":"10v8a19m25","topRow":5,"bottomRow":9,"parentRowSpace":10,"isVisible":"{{FindQuery.data.length > 0}}","label":"","type":"DROP_DOWN_WIDGET","version":1,"parentId":"59rw5mx0bq","isLoading":false,"defaultOptionValue":"1","parentColumnSpace":19.75,"dynamicTriggerPathList":[{"key":"onOptionChange"}],"leftColumn":22,"dynamicBindingPathList":[{"key":"isVisible"}],"options":"[\n {\n \"label\": \"ASC\",\n \"value\": \"1\"\n },\n {\n \"label\": \"DESC\",\n \"value\": \"-1\"\n }\n]","onOptionChange":"{{FindQuery.run()}}","isDisabled":false},{"widgetName":"Text16","rightColumn":41,"textAlign":"LEFT","widgetId":"urzv99hdc8","topRow":0,"bottomRow":4,"parentRowSpace":10,"isVisible":"true","fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"59rw5mx0bq","isLoading":false,"parentColumnSpace":11.78515625,"dynamicTriggerPathList":[],"leftColumn":0,"dynamicBindingPathList":[],"fontSize":"HEADING1","text":"movies Data"},{"boxShadow":"NONE","widgetName":"refresh_btn","rightColumn":64,"onClick":"{{FindQuery.run()}}","iconName":"refresh","buttonColor":"#03B365","widgetId":"nj85l57r47","topRow":5,"bottomRow":9,"parentRowSpace":10,"isVisible":"true","type":"ICON_BUTTON_WIDGET","version":1,"parentId":"59rw5mx0bq","isLoading":false,"parentColumnSpace":12.0703125,"dynamicTriggerPathList":[{"key":"onClick"}],"borderRadius":"CIRCLE","leftColumn":60,"dynamicBindingPathList":[],"buttonVariant":"GHOST","isDisabled":false},{"boxShadow":"NONE","widgetName":"add_btn","rightColumn":60,"onClick":"{{showModal('Insert_Modal')}}","iconName":"add","buttonColor":"#03B365","widgetId":"atgojamsmw","topRow":5,"bottomRow":9,"parentRowSpace":10,"isVisible":"true","type":"ICON_BUTTON_WIDGET","version":1,"parentId":"59rw5mx0bq","isLoading":false,"parentColumnSpace":12.0703125,"dynamicTriggerPathList":[{"key":"onClick"}],"borderRadius":"CIRCLE","leftColumn":56,"dynamicBindingPathList":[],"buttonVariant":"GHOST","isDisabled":false}]}]},{"widgetName":"Delete_Modal","rightColumn":45,"detachFromLayout":true,"widgetId":"i3whp03wf0","topRow":13,"bottomRow":37,"parentRowSpace":10,"canOutsideClickClose":true,"type":"MODAL_WIDGET","canEscapeKeyClose":true,"version":2,"parentId":"0","shouldScrollContents":false,"isLoading":false,"parentColumnSpace":18.8828125,"dynamicTriggerPathList":[],"leftColumn":21,"dynamicBindingPathList":[],"children":[{"widgetName":"Canvas3","rightColumn":453.1875,"detachFromLayout":true,"widgetId":"zi8fjakv8o","topRow":0,"bottomRow":230,"parentRowSpace":1,"isVisible":"true","canExtend":true,"type":"CANVAS_WIDGET","version":1,"parentId":"i3whp03wf0","shouldScrollContents":false,"minHeight":240,"isLoading":false,"parentColumnSpace":1,"dynamicTriggerPathList":[],"leftColumn":0,"dynamicBindingPathList":[],"children":[{"widgetName":"Alert_text","rightColumn":41,"textAlign":"LEFT","widgetId":"35yoxo4oec","topRow":1,"bottomRow":5,"isVisible":"true","fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"zi8fjakv8o","isLoading":false,"dynamicTriggerPathList":[],"leftColumn":1,"dynamicBindingPathList":[],"fontSize":"HEADING1","text":"Delete Row"},{"widgetName":"Button1","rightColumn":46,"onClick":"{{closeModal('Delete_Modal')}}","isDefaultClickDisabled":true,"dynamicPropertyPathList":[],"buttonColor":"#03B365","widgetId":"lryg8kw537","topRow":17,"bottomRow":21,"isVisible":"true","type":"BUTTON_WIDGET","version":1,"parentId":"zi8fjakv8o","isLoading":false,"dynamicTriggerPathList":[{"key":"onClick"}],"leftColumn":34,"dynamicBindingPathList":[],"text":"Cancel","isDisabled":false},{"widgetName":"Delete_Button","rightColumn":64,"onClick":"{{DeleteQuery.run(() => FindQuery.run(() => closeModal('Delete_Modal')), () => {})}}","isDefaultClickDisabled":true,"dynamicPropertyPathList":[{"key":"onClick"}],"buttonColor":"#F22B2B","widgetId":"qq02lh7ust","topRow":17,"bottomRow":21,"isVisible":"true","type":"BUTTON_WIDGET","version":1,"parentId":"zi8fjakv8o","isLoading":false,"dynamicTriggerPathList":[{"key":"onClick"}],"leftColumn":48,"dynamicBindingPathList":[],"text":"Confirm","isDisabled":false},{"widgetName":"Text12","rightColumn":63,"textAlign":"LEFT","widgetId":"48uac29g6e","topRow":8,"bottomRow":12,"parentRowSpace":10,"isVisible":"true","fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"zi8fjakv8o","isLoading":false,"parentColumnSpace":6.875,"dynamicTriggerPathList":[],"leftColumn":1,"dynamicBindingPathList":[],"fontSize":"PARAGRAPH","text":"Are you sure you want to delete this item?"}],"isDisabled":false}],"width":456,"height":240},{"widgetName":"Insert_Modal","rightColumn":41,"detachFromLayout":true,"widgetId":"vmorzie6eq","topRow":16,"bottomRow":40,"parentRowSpace":10,"canOutsideClickClose":true,"type":"MODAL_WIDGET","canEscapeKeyClose":true,"version":2,"parentId":"0","shouldScrollContents":false,"isLoading":false,"parentColumnSpace":18.8828125,"dynamicTriggerPathList":[],"leftColumn":17,"dynamicBindingPathList":[],"children":[{"widgetName":"Canvas4","rightColumn":453.1875,"detachFromLayout":true,"widgetId":"9rhv3ioohq","topRow":0,"bottomRow":610,"parentRowSpace":1,"isVisible":"true","canExtend":true,"type":"CANVAS_WIDGET","version":1,"parentId":"vmorzie6eq","shouldScrollContents":false,"minHeight":600,"isLoading":false,"parentColumnSpace":1,"dynamicTriggerPathList":[],"leftColumn":0,"dynamicBindingPathList":[],"children":[{"widgetName":"Form2","backgroundColor":"#F6F7F8","rightColumn":64,"widgetId":"1ruewbc4ef","topRow":0,"bottomRow":58,"parentRowSpace":10,"isVisible":"true","type":"FORM_WIDGET","parentId":"9rhv3ioohq","isLoading":false,"shouldScrollContents":false,"parentColumnSpace":8,"dynamicTriggerPathList":[],"leftColumn":1,"dynamicBindingPathList":[],"children":[{"widgetName":"Canvas5","rightColumn":224,"detachFromLayout":true,"widgetId":"tp9pui0e6y","containerStyle":"none","topRow":0,"bottomRow":570,"parentRowSpace":1,"isVisible":"true","canExtend":false,"type":"CANVAS_WIDGET","version":1,"parentId":"1ruewbc4ef","minHeight":580,"isLoading":false,"parentColumnSpace":1,"dynamicTriggerPathList":[],"leftColumn":0,"dynamicBindingPathList":[],"children":[{"resetFormOnClick":true,"widgetName":"insert_button","rightColumn":62,"onClick":"{{InsertQuery.run(() => FindQuery.run(() => closeModal('Insert_Modal')))}}","isDefaultClickDisabled":true,"dynamicPropertyPathList":[{"key":"onClick"}],"buttonColor":"#03B365","widgetId":"h8vxf3oh4s","topRow":51,"bottomRow":55,"isVisible":"true","type":"FORM_BUTTON_WIDGET","version":1,"parentId":"tp9pui0e6y","isLoading":false,"dynamicTriggerPathList":[{"key":"onClick"}],"disabledWhenInvalid":true,"leftColumn":43,"dynamicBindingPathList":[],"googleRecaptchaKey":"","text":"Submit"},{"resetFormOnClick":true,"widgetName":"reset_button","rightColumn":42,"onClick":"{{closeModal('Insert_Modal')}}","isDefaultClickDisabled":true,"buttonColor":"#03B365","widgetId":"o23gs26wm5","topRow":51,"bottomRow":55,"isVisible":"true","type":"FORM_BUTTON_WIDGET","version":1,"parentId":"tp9pui0e6y","isLoading":false,"dynamicTriggerPathList":[{"key":"onClick"}],"disabledWhenInvalid":false,"leftColumn":29,"dynamicBindingPathList":[],"buttonVariant":"OUTLINE","text":"Close"},{"widgetName":"Text21","rightColumn":19,"textAlign":"RIGHT","widgetId":"cfmxebyn06","topRow":5,"bottomRow":9,"parentRowSpace":10,"isVisible":"true","fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"tp9pui0e6y","isLoading":false,"parentColumnSpace":7.6865234375,"dynamicTriggerPathList":[],"leftColumn":3,"dynamicBindingPathList":[],"fontSize":"PARAGRAPH","text":"genres:"},{"isRequired":true,"widgetName":"insert_col_input1","rightColumn":62,"widgetId":"h1wbbv7alb","topRow":5,"bottomRow":9,"parentRowSpace":10,"isVisible":"true","label":"","type":"INPUT_WIDGET_V2","version":1,"parentId":"tp9pui0e6y","isLoading":false,"parentColumnSpace":7.6865234375,"dynamicTriggerPathList":[],"resetOnSubmit":true,"leftColumn":21,"dynamicBindingPathList":[],"inputType":"TEXT","placeholderText":"genres","defaultText":"","isDisabled":false,"validation":"true"},{"widgetName":"Text22","rightColumn":19,"textAlign":"RIGHT","widgetId":"jsffaxrqhw","topRow":12,"bottomRow":16,"parentRowSpace":10,"isVisible":"true","fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"tp9pui0e6y","isLoading":false,"parentColumnSpace":7.6865234375,"dynamicTriggerPathList":[],"leftColumn":2,"dynamicBindingPathList":[],"fontSize":"PARAGRAPH","text":"homepage:"},{"isRequired":true,"widgetName":"insert_col_input2","rightColumn":62,"widgetId":"6enalyprua","topRow":12,"bottomRow":16,"parentRowSpace":10,"isVisible":"true","label":"","type":"INPUT_WIDGET_V2","version":1,"parentId":"tp9pui0e6y","isLoading":false,"parentColumnSpace":8.0625,"dynamicTriggerPathList":[],"resetOnSubmit":true,"leftColumn":21,"dynamicBindingPathList":[],"inputType":"TEXT","defaultText":"","placeholderText":"homepage","isDisabled":false,"validation":"true"},{"widgetName":"Text23","rightColumn":19,"textAlign":"RIGHT","widgetId":"btk60uozsm","topRow":19,"bottomRow":23,"parentRowSpace":10,"isVisible":"true","fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"tp9pui0e6y","isLoading":false,"parentColumnSpace":7.6865234375,"dynamicTriggerPathList":[],"leftColumn":3,"dynamicBindingPathList":[],"fontSize":"PARAGRAPH","text":"imdb_id:"},{"isRequired":true,"widgetName":"insert_col_input3","rightColumn":62,"widgetId":"e490gfts69","topRow":19,"bottomRow":23,"parentRowSpace":10,"isVisible":"true","label":"","type":"INPUT_WIDGET_V2","version":1,"parentId":"tp9pui0e6y","isLoading":false,"parentColumnSpace":8.0625,"dynamicTriggerPathList":[],"resetOnSubmit":true,"leftColumn":21,"dynamicBindingPathList":[],"inputType":"TEXT","placeholderText":"imdb_id","defaultText":"","isDisabled":false,"validation":"true"},{"widgetName":"Text14","rightColumn":19,"textAlign":"RIGHT","widgetId":"8fm60omwwv","topRow":26,"bottomRow":30,"parentRowSpace":10,"isVisible":"true","fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"tp9pui0e6y","isLoading":false,"parentColumnSpace":8.0625,"dynamicTriggerPathList":[],"leftColumn":3,"dynamicBindingPathList":[],"fontSize":"PARAGRAPH","text":"poster_path:"},{"isRequired":true,"widgetName":"insert_col_input4","rightColumn":62,"widgetId":"r55cydp0ao","topRow":26,"bottomRow":30,"parentRowSpace":10,"isVisible":"true","label":"","type":"INPUT_WIDGET_V2","version":1,"parentId":"tp9pui0e6y","isLoading":false,"parentColumnSpace":8.0625,"dynamicTriggerPathList":[],"resetOnSubmit":true,"leftColumn":21,"dynamicBindingPathList":[],"inputType":"TEXT","placeholderText":"poster_path","defaultText":"","isDisabled":false,"validation":"true"},{"widgetName":"Text13Copy","rightColumn":35,"textAlign":"LEFT","widgetId":"18x7vdv3gs","topRow":0,"bottomRow":4,"isVisible":"true","fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"shouldScroll":false,"parentId":"tp9pui0e6y","isLoading":false,"dynamicTriggerPathList":[],"leftColumn":0,"dynamicBindingPathList":[],"fontSize":"HEADING1","text":"Insert Row"}]}]}],"isDisabled":false}],"width":532,"height":600},{"widgetName":"Form1","backgroundColor":"white","rightColumn":64,"dynamicPropertyPathList":[{"key":"isVisible"}],"widgetId":"m7dvlazbn7","topRow":0,"bottomRow":46,"parentRowSpace":10,"isVisible":"{{!!data_table.selectedRow._id}}","type":"FORM_WIDGET","parentId":"0","isLoading":false,"shouldScrollContents":true,"parentColumnSpace":18.8828125,"dynamicTriggerPathList":[],"leftColumn":40,"dynamicBindingPathList":[{"key":"isVisible"}],"children":[{"widgetName":"Canvas2","rightColumn":528.71875,"detachFromLayout":true,"widgetId":"cicukwhp5j","containerStyle":"none","topRow":0,"bottomRow":450,"parentRowSpace":1,"isVisible":"true","canExtend":false,"type":"CANVAS_WIDGET","version":1,"parentId":"m7dvlazbn7","minHeight":460,"isLoading":false,"parentColumnSpace":1,"dynamicTriggerPathList":[],"leftColumn":0,"dynamicBindingPathList":[],"children":[{"resetFormOnClick":false,"widgetName":"update_button","rightColumn":63,"onClick":"{{UpdateQuery.run(() => FindQuery.run(), () => showAlert('Error while updating resource!','error'))}}","isDefaultClickDisabled":true,"dynamicPropertyPathList":[],"buttonColor":"#03B365","widgetId":"4gnygu5jew","topRow":39,"bottomRow":43,"isVisible":"true","type":"FORM_BUTTON_WIDGET","version":1,"parentId":"cicukwhp5j","isLoading":false,"dynamicTriggerPathList":[{"key":"onClick"}],"disabledWhenInvalid":true,"leftColumn":47,"dynamicBindingPathList":[],"text":"Update"},{"resetFormOnClick":true,"widgetName":"reset_update_button","rightColumn":46,"onClick":"","isDefaultClickDisabled":true,"dynamicPropertyPathList":[],"buttonColor":"#03B365","widgetId":"twwgpz5wfu","topRow":39,"bottomRow":43,"isVisible":"true","type":"FORM_BUTTON_WIDGET","version":1,"parentId":"cicukwhp5j","isLoading":false,"dynamicTriggerPathList":[{"key":"onClick"}],"disabledWhenInvalid":false,"leftColumn":28,"dynamicBindingPathList":[],"buttonVariant":"OUTLINE","text":"Reset"},{"isRequired":true,"widgetName":"update_col_1","rightColumn":63,"widgetId":"in8e51pg3y","topRow":8,"bottomRow":12,"parentRowSpace":10,"isVisible":"true","label":"","type":"INPUT_WIDGET_V2","version":1,"parentId":"cicukwhp5j","isLoading":false,"parentColumnSpace":8.8963623046875,"dynamicTriggerPathList":[],"resetOnSubmit":true,"leftColumn":19,"dynamicBindingPathList":[{"key":"defaultText"}],"inputType":"TEXT","defaultText":"{{data_table.selectedRow.genres}}","isDisabled":false,"validation":"true"},{"isRequired":true,"widgetName":"update_col_2","rightColumn":63,"widgetId":"mlhvfasf31","topRow":15,"bottomRow":19,"parentRowSpace":10,"isVisible":"true","label":"","type":"INPUT_WIDGET_V2","version":1,"parentId":"cicukwhp5j","isLoading":false,"parentColumnSpace":8.8963623046875,"dynamicTriggerPathList":[],"resetOnSubmit":true,"leftColumn":19,"dynamicBindingPathList":[{"key":"defaultText"}],"inputType":"TEXT","defaultText":"{{data_table.selectedRow.homepage}}","isDisabled":false,"validation":"true"},{"isRequired":true,"widgetName":"update_col_3","rightColumn":63,"widgetId":"0lz9vhcnr0","topRow":22,"bottomRow":26,"parentRowSpace":10,"isVisible":"true","label":"","type":"INPUT_WIDGET_V2","version":1,"parentId":"cicukwhp5j","isLoading":false,"parentColumnSpace":8.8963623046875,"dynamicTriggerPathList":[],"resetOnSubmit":true,"leftColumn":19,"dynamicBindingPathList":[{"key":"defaultText"}],"inputType":"TEXT","defaultText":"{{data_table.selectedRow.imdb_id}}","isDisabled":false,"validation":"true"},{"isRequired":true,"widgetName":"update_col_4","rightColumn":63,"widgetId":"m4esf7fww5","topRow":29,"bottomRow":33,"parentRowSpace":10,"isVisible":"true","label":"","type":"INPUT_WIDGET_V2","version":1,"parentId":"cicukwhp5j","isLoading":false,"parentColumnSpace":8.8963623046875,"dynamicTriggerPathList":[],"resetOnSubmit":true,"leftColumn":19,"dynamicBindingPathList":[{"key":"defaultText"}],"inputType":"TEXT","defaultText":"{{data_table.selectedRow.poster_path}}","isDisabled":false,"validation":"true"},{"widgetName":"Text9","rightColumn":63,"textAlign":"LEFT","widgetId":"4hnz8ktmz5","topRow":0,"bottomRow":6,"parentRowSpace":10,"isVisible":"true","fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"cicukwhp5j","isLoading":false,"parentColumnSpace":8.8963623046875,"dynamicTriggerPathList":[],"leftColumn":1,"dynamicBindingPathList":[],"fontSize":"HEADING1","text":"Update Selected Row"},{"widgetName":"Text17","rightColumn":18,"textAlign":"RIGHT","widgetId":"afzzc7q8af","topRow":8,"bottomRow":12,"parentRowSpace":10,"isVisible":"true","fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"cicukwhp5j","isLoading":false,"parentColumnSpace":7.15625,"dynamicTriggerPathList":[],"leftColumn":1,"dynamicBindingPathList":[],"fontSize":"PARAGRAPH","text":"genres:"},{"widgetName":"Text18","rightColumn":18,"textAlign":"RIGHT","widgetId":"xqcsd2e5dj","topRow":15,"bottomRow":19,"parentRowSpace":10,"isVisible":"true","fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"cicukwhp5j","isLoading":false,"parentColumnSpace":7.15625,"dynamicTriggerPathList":[],"leftColumn":1,"dynamicBindingPathList":[],"fontSize":"PARAGRAPH","text":"homepage:"},{"widgetName":"Text19","rightColumn":18,"textAlign":"RIGHT","widgetId":"l109ilp3vq","topRow":22,"bottomRow":26,"parentRowSpace":10,"isVisible":"true","fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"cicukwhp5j","isLoading":false,"parentColumnSpace":7.15625,"dynamicTriggerPathList":[],"leftColumn":1,"dynamicBindingPathList":[],"fontSize":"PARAGRAPH","text":"imdb_id:"},{"widgetName":"Text20","rightColumn":18,"textAlign":"RIGHT","widgetId":"gqpwf0yng6","topRow":29,"bottomRow":33,"parentRowSpace":10,"isVisible":"true","fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"cicukwhp5j","isLoading":false,"parentColumnSpace":7.15625,"dynamicTriggerPathList":[],"leftColumn":1,"dynamicBindingPathList":[],"fontSize":"PARAGRAPH","text":"poster_path:"}]}]}]},"layoutOnLoadActions":[[{"id":"616d7e429594b25adfa3e580","name":"FindQuery","pluginType":"DB","jsonPathKeys":["key_select.selectedOptionValue","data_table.pageSize","data_table.searchText||\"\"","(data_table.pageNo - 1) * data_table.pageSize","order_select.selectedOptionValue"],"timeoutInMillisecond":10000}]],"new":false}],"userPermissions":["read:pages","manage:pages"],"lastUpdatedTime":1634565699},"successMessage":"We have generated the <b>Table</b> from the <b>MongoDB datasource</b>. You can use the <b>Form</b> to modify it. Since all your data is already connected you can add more queries and modify the bindings","successImageUrl":"https://assets.appsmith.com/crud/working-flow-chart.png"}} \ No newline at end of file +{"responseMeta":{"status":201,"success":true},"data":{"page":{"id":"616d7d4c9594b25adfa3e569","name":"Page3","applicationId":null,"layouts":[{"id":"616d7d4c9594b25adfa3e568","userPermissions":[],"dsl":{"widgetName":"MainContainer","backgroundColor":"none","rightColumn":1280,"snapColumns":64,"detachFromLayout":true,"widgetId":"0","topRow":0,"bottomRow":940,"containerStyle":"none","snapRows":125,"parentRowSpace":1,"type":"CANVAS_WIDGET","canExtend":true,"version":41,"minHeight":860,"parentColumnSpace":1,"dynamicTriggerPathList":[],"dynamicBindingPathList":[],"leftColumn":0,"children":[{"backgroundColor":"#FFFFFF","widgetName":"Container1","rightColumn":40,"widgetId":"mvubsemxfo","containerStyle":"card","topRow":0,"bottomRow":87,"parentRowSpace":10,"isVisible":"true","type":"CONTAINER_WIDGET","version":1,"parentId":"0","isLoading":false,"parentColumnSpace":19.75,"leftColumn":0,"children":[{"widgetName":"Canvas1","rightColumn":632,"detachFromLayout":true,"widgetId":"59rw5mx0bq","containerStyle":"none","topRow":0,"bottomRow":890,"parentRowSpace":1,"isVisible":"true","canExtend":false,"type":"CANVAS_WIDGET","version":1,"parentId":"mvubsemxfo","minHeight":870,"isLoading":false,"parentColumnSpace":1,"dynamicTriggerPathList":[],"leftColumn":0,"dynamicBindingPathList":[],"children":[{"widgetName":"data_table","columnOrder":["customColumn1","_id","col4","col2","col3","col1"],"dynamicPropertyPathList":[{"key":"onPageChange"}],"isVisibleDownload":true,"topRow":10,"bottomRow":86,"parentRowSpace":10,"onPageChange":"{{FindQuery.run()}}","type":"TABLE_WIDGET","defaultSelectedRow":"0","parentColumnSpace":1,"dynamicTriggerPathList":[{"key":"onPageChange"},{"key":"primaryColumns.customColumn1.onClick"},{"key":"onSearchTextChanged"}],"dynamicBindingPathList":[{"key":"primaryColumns.customColumn1.buttonLabel"},{"key":"tableData"},{"key":"primaryColumns.col1.computedValue"},{"key":"primaryColumns.col2.computedValue"},{"key":"primaryColumns.col3.computedValue"},{"key":"primaryColumns.col4.computedValue"},{"key":"primaryColumns._id.computedValue"}],"leftColumn":0,"primaryColumns":{"customColumn1":{"isCellVisible":true,"isDerived":true,"computedValue":"","onClick":"{{showModal(Delete_Modal.name)}}","textSize":"PARAGRAPH","buttonColor":"#DD4B34","index":7,"isVisible":true,"label":"Delete","buttonLabel":"{{data_table.sanitizedTableData.map((currentRow) => { return 'Delete'})}}","columnType":"button","horizontalAlignment":"LEFT","width":150,"enableFilter":true,"enableSort":true,"id":"customColumn1","isDisabled":false,"buttonLabelColor":"#FFFFFF","verticalAlignment":"CENTER"},"col4":{"isCellVisible":true,"isDerived":false,"computedValue":"{{data_table.sanitizedTableData.map((currentRow) => ( currentRow.col4))}}","textSize":"PARAGRAPH","index":3,"isVisible":true,"label":"col4","columnType":"text","horizontalAlignment":"LEFT","width":150,"enableFilter":true,"enableSort":true,"id":"col4","verticalAlignment":"CENTER"},"_id":{"isCellVisible":true,"isDerived":false,"computedValue":"{{data_table.sanitizedTableData.map((currentRow) => ( currentRow._id))}}","textSize":"PARAGRAPH","index":1,"isVisible":true,"label":"_id","columnType":"text","horizontalAlignment":"LEFT","width":150,"enableFilter":true,"enableSort":true,"id":"_id","verticalAlignment":"CENTER"},"col2":{"isCellVisible":true,"isDerived":false,"computedValue":"{{data_table.sanitizedTableData.map((currentRow) => ( currentRow.col2))}}","textSize":"PARAGRAPH","index":1,"isVisible":true,"label":"col2","columnType":"text","horizontalAlignment":"LEFT","width":150,"enableFilter":true,"enableSort":true,"id":"col2","verticalAlignment":"CENTER"},"col3":{"isCellVisible":true,"isDerived":false,"computedValue":"{{data_table.sanitizedTableData.map((currentRow) => ( currentRow.col3))}}","textSize":"PARAGRAPH","index":2,"isVisible":true,"label":"col3","columnType":"text","horizontalAlignment":"LEFT","width":150,"enableFilter":true,"enableSort":true,"id":"col3","verticalAlignment":"CENTER"},"col1":{"isCellVisible":true,"isDerived":false,"computedValue":"{{data_table.sanitizedTableData.map((currentRow) => ( currentRow.col1))}}","textSize":"PARAGRAPH","index":0,"isVisible":true,"label":"col1","columnType":"text","horizontalAlignment":"LEFT","width":150,"enableFilter":true,"enableSort":true,"id":"col1","verticalAlignment":"CENTER"}},"delimiter":",","derivedColumns":{"customColumn1":{"isDerived":true,"computedValue":"","onClick":"{{DeleteQuery.run()}}","textSize":"PARAGRAPH","buttonStyle":"#DD4B34","index":7,"isVisible":true,"label":"customColumn1","buttonLabel":"{{data_table.sanitizedTableData.map((currentRow) => { return 'Delete'})}}","columnType":"button","horizontalAlignment":"LEFT","width":150,"enableFilter":true,"enableSort":true,"id":"customColumn1","buttonLabelColor":"#FFFFFF","verticalAlignment":"CENTER"}},"rightColumn":64,"textSize":"PARAGRAPH","widgetId":"jabdu9f16g","isVisibleFilters":true,"tableData":"{{FindQuery.data}}","isVisible":"true","label":"Data","searchKey":"","version":3,"parentId":"59rw5mx0bq","serverSidePaginationEnabled":true,"isLoading":false,"isVisibleCompactMode":true,"onSearchTextChanged":"{{FindQuery.run()}}","horizontalAlignment":"LEFT","isVisibleSearch":true,"isVisiblePagination":true,"verticalAlignment":"CENTER","columnSizeMap":{"task":245,"deliveryAddress":170,"step":62,"id":228,"status":75}},{"isRequired":false,"widgetName":"key_select","isFilterable":true,"rightColumn":22,"dynamicPropertyPathList":[{"key":"isVisible"}],"widgetId":"asmgosgxjm","topRow":5,"bottomRow":9,"parentRowSpace":10,"isVisible":"{{FindQuery.data.length > 0}}","label":"","type":"DROP_DOWN_WIDGET","version":1,"parentId":"59rw5mx0bq","isLoading":false,"defaultOptionValue":"genres","parentColumnSpace":18.8828125,"dynamicTriggerPathList":[{"key":"onOptionChange"}],"leftColumn":7,"dynamicBindingPathList":[{"key":"isVisible"}],"options":"[\n{\n\t\"label\": \"poster_path\",\n\t\"value\": \"poster_path\"\n}, \n{\n\t\"label\": \"homepage\",\n\t\"value\": \"homepage\"\n}, \n{\n\t\"label\": \"imdb_id\",\n\t\"value\": \"imdb_id\"\n}, \n{\n\t\"label\": \"genres\",\n\t\"value\": \"genres\"\n}]","onOptionChange":"{{FindQuery.run()}}","isDisabled":false},{"widgetName":"Text15","rightColumn":7,"textAlign":"LEFT","widgetId":"l8pgl90klz","topRow":5,"bottomRow":9,"parentRowSpace":10,"isVisible":"true","fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"59rw5mx0bq","isLoading":false,"parentColumnSpace":19.75,"dynamicTriggerPathList":[],"leftColumn":0,"dynamicBindingPathList":[],"fontSize":"PARAGRAPH","text":"Order By :"},{"isRequired":false,"widgetName":"order_select","isFilterable":true,"rightColumn":30,"dynamicPropertyPathList":[{"key":"isVisible"}],"widgetId":"10v8a19m25","topRow":5,"bottomRow":9,"parentRowSpace":10,"isVisible":"{{FindQuery.data.length > 0}}","label":"","type":"DROP_DOWN_WIDGET","version":1,"parentId":"59rw5mx0bq","isLoading":false,"defaultOptionValue":"1","parentColumnSpace":19.75,"dynamicTriggerPathList":[{"key":"onOptionChange"}],"leftColumn":22,"dynamicBindingPathList":[{"key":"isVisible"}],"options":"[\n {\n \"label\": \"ASC\",\n \"value\": \"1\"\n },\n {\n \"label\": \"DESC\",\n \"value\": \"-1\"\n }\n]","onOptionChange":"{{FindQuery.run()}}","isDisabled":false},{"widgetName":"Text16","rightColumn":41,"textAlign":"LEFT","widgetId":"urzv99hdc8","topRow":0,"bottomRow":4,"parentRowSpace":10,"isVisible":"true","fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"59rw5mx0bq","isLoading":false,"parentColumnSpace":11.78515625,"dynamicTriggerPathList":[],"leftColumn":0,"dynamicBindingPathList":[],"fontSize":"HEADING1","text":"movies Data"},{"boxShadow":"NONE","widgetName":"refresh_btn","rightColumn":64,"onClick":"{{FindQuery.run()}}","iconName":"refresh","buttonColor":"#03B365","widgetId":"nj85l57r47","topRow":5,"bottomRow":9,"parentRowSpace":10,"isVisible":"true","type":"ICON_BUTTON_WIDGET","version":1,"parentId":"59rw5mx0bq","isLoading":false,"parentColumnSpace":12.0703125,"dynamicTriggerPathList":[{"key":"onClick"}],"borderRadius":"CIRCLE","leftColumn":60,"dynamicBindingPathList":[],"buttonVariant":"GHOST","isDisabled":false},{"boxShadow":"NONE","widgetName":"add_btn","rightColumn":60,"onClick":"{{showModal(Insert_Modal.name)}}","iconName":"add","buttonColor":"#03B365","widgetId":"atgojamsmw","topRow":5,"bottomRow":9,"parentRowSpace":10,"isVisible":"true","type":"ICON_BUTTON_WIDGET","version":1,"parentId":"59rw5mx0bq","isLoading":false,"parentColumnSpace":12.0703125,"dynamicTriggerPathList":[{"key":"onClick"}],"borderRadius":"CIRCLE","leftColumn":56,"dynamicBindingPathList":[],"buttonVariant":"GHOST","isDisabled":false}]}]},{"widgetName":"Delete_Modal","rightColumn":45,"detachFromLayout":true,"widgetId":"i3whp03wf0","topRow":13,"bottomRow":37,"parentRowSpace":10,"canOutsideClickClose":true,"type":"MODAL_WIDGET","canEscapeKeyClose":true,"version":2,"parentId":"0","shouldScrollContents":false,"isLoading":false,"parentColumnSpace":18.8828125,"dynamicTriggerPathList":[],"leftColumn":21,"dynamicBindingPathList":[],"children":[{"widgetName":"Canvas3","rightColumn":453.1875,"detachFromLayout":true,"widgetId":"zi8fjakv8o","topRow":0,"bottomRow":230,"parentRowSpace":1,"isVisible":"true","canExtend":true,"type":"CANVAS_WIDGET","version":1,"parentId":"i3whp03wf0","shouldScrollContents":false,"minHeight":240,"isLoading":false,"parentColumnSpace":1,"dynamicTriggerPathList":[],"leftColumn":0,"dynamicBindingPathList":[],"children":[{"widgetName":"Alert_text","rightColumn":41,"textAlign":"LEFT","widgetId":"35yoxo4oec","topRow":1,"bottomRow":5,"isVisible":"true","fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"zi8fjakv8o","isLoading":false,"dynamicTriggerPathList":[],"leftColumn":1,"dynamicBindingPathList":[],"fontSize":"HEADING1","text":"Delete Row"},{"widgetName":"Button1","rightColumn":46,"onClick":"{{closeModal(Delete_Modal.name)}}","isDefaultClickDisabled":true,"dynamicPropertyPathList":[],"buttonColor":"#03B365","widgetId":"lryg8kw537","topRow":17,"bottomRow":21,"isVisible":"true","type":"BUTTON_WIDGET","version":1,"parentId":"zi8fjakv8o","isLoading":false,"dynamicTriggerPathList":[{"key":"onClick"}],"leftColumn":34,"dynamicBindingPathList":[],"text":"Cancel","isDisabled":false},{"widgetName":"Delete_Button","rightColumn":64,"onClick":"{{DeleteQuery.run(() => FindQuery.run(() => closeModal(Delete_Modal.name)), () => {})}}","isDefaultClickDisabled":true,"dynamicPropertyPathList":[{"key":"onClick"}],"buttonColor":"#F22B2B","widgetId":"qq02lh7ust","topRow":17,"bottomRow":21,"isVisible":"true","type":"BUTTON_WIDGET","version":1,"parentId":"zi8fjakv8o","isLoading":false,"dynamicTriggerPathList":[{"key":"onClick"}],"leftColumn":48,"dynamicBindingPathList":[],"text":"Confirm","isDisabled":false},{"widgetName":"Text12","rightColumn":63,"textAlign":"LEFT","widgetId":"48uac29g6e","topRow":8,"bottomRow":12,"parentRowSpace":10,"isVisible":"true","fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"zi8fjakv8o","isLoading":false,"parentColumnSpace":6.875,"dynamicTriggerPathList":[],"leftColumn":1,"dynamicBindingPathList":[],"fontSize":"PARAGRAPH","text":"Are you sure you want to delete this item?"}],"isDisabled":false}],"width":456,"height":240},{"widgetName":"Insert_Modal","rightColumn":41,"detachFromLayout":true,"widgetId":"vmorzie6eq","topRow":16,"bottomRow":40,"parentRowSpace":10,"canOutsideClickClose":true,"type":"MODAL_WIDGET","canEscapeKeyClose":true,"version":2,"parentId":"0","shouldScrollContents":false,"isLoading":false,"parentColumnSpace":18.8828125,"dynamicTriggerPathList":[],"leftColumn":17,"dynamicBindingPathList":[],"children":[{"widgetName":"Canvas4","rightColumn":453.1875,"detachFromLayout":true,"widgetId":"9rhv3ioohq","topRow":0,"bottomRow":610,"parentRowSpace":1,"isVisible":"true","canExtend":true,"type":"CANVAS_WIDGET","version":1,"parentId":"vmorzie6eq","shouldScrollContents":false,"minHeight":600,"isLoading":false,"parentColumnSpace":1,"dynamicTriggerPathList":[],"leftColumn":0,"dynamicBindingPathList":[],"children":[{"widgetName":"Form2","backgroundColor":"#F6F7F8","rightColumn":64,"widgetId":"1ruewbc4ef","topRow":0,"bottomRow":58,"parentRowSpace":10,"isVisible":"true","type":"FORM_WIDGET","parentId":"9rhv3ioohq","isLoading":false,"shouldScrollContents":false,"parentColumnSpace":8,"dynamicTriggerPathList":[],"leftColumn":1,"dynamicBindingPathList":[],"children":[{"widgetName":"Canvas5","rightColumn":224,"detachFromLayout":true,"widgetId":"tp9pui0e6y","containerStyle":"none","topRow":0,"bottomRow":570,"parentRowSpace":1,"isVisible":"true","canExtend":false,"type":"CANVAS_WIDGET","version":1,"parentId":"1ruewbc4ef","minHeight":580,"isLoading":false,"parentColumnSpace":1,"dynamicTriggerPathList":[],"leftColumn":0,"dynamicBindingPathList":[],"children":[{"resetFormOnClick":true,"widgetName":"insert_button","rightColumn":62,"onClick":"{{InsertQuery.run(() => FindQuery.run(() => closeModal(Insert_Modal.name)))}}","isDefaultClickDisabled":true,"dynamicPropertyPathList":[{"key":"onClick"}],"buttonColor":"#03B365","widgetId":"h8vxf3oh4s","topRow":51,"bottomRow":55,"isVisible":"true","type":"FORM_BUTTON_WIDGET","version":1,"parentId":"tp9pui0e6y","isLoading":false,"dynamicTriggerPathList":[{"key":"onClick"}],"disabledWhenInvalid":true,"leftColumn":43,"dynamicBindingPathList":[],"googleRecaptchaKey":"","text":"Submit"},{"resetFormOnClick":true,"widgetName":"reset_button","rightColumn":42,"onClick":"{{closeModal(Insert_Modal.name)}}","isDefaultClickDisabled":true,"buttonColor":"#03B365","widgetId":"o23gs26wm5","topRow":51,"bottomRow":55,"isVisible":"true","type":"FORM_BUTTON_WIDGET","version":1,"parentId":"tp9pui0e6y","isLoading":false,"dynamicTriggerPathList":[{"key":"onClick"}],"disabledWhenInvalid":false,"leftColumn":29,"dynamicBindingPathList":[],"buttonVariant":"OUTLINE","text":"Close"},{"widgetName":"Text21","rightColumn":19,"textAlign":"RIGHT","widgetId":"cfmxebyn06","topRow":5,"bottomRow":9,"parentRowSpace":10,"isVisible":"true","fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"tp9pui0e6y","isLoading":false,"parentColumnSpace":7.6865234375,"dynamicTriggerPathList":[],"leftColumn":3,"dynamicBindingPathList":[],"fontSize":"PARAGRAPH","text":"genres:"},{"isRequired":true,"widgetName":"insert_col_input1","rightColumn":62,"widgetId":"h1wbbv7alb","topRow":5,"bottomRow":9,"parentRowSpace":10,"isVisible":"true","label":"","type":"INPUT_WIDGET_V2","version":1,"parentId":"tp9pui0e6y","isLoading":false,"parentColumnSpace":7.6865234375,"dynamicTriggerPathList":[],"resetOnSubmit":true,"leftColumn":21,"dynamicBindingPathList":[],"inputType":"TEXT","placeholderText":"genres","defaultText":"","isDisabled":false,"validation":"true"},{"widgetName":"Text22","rightColumn":19,"textAlign":"RIGHT","widgetId":"jsffaxrqhw","topRow":12,"bottomRow":16,"parentRowSpace":10,"isVisible":"true","fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"tp9pui0e6y","isLoading":false,"parentColumnSpace":7.6865234375,"dynamicTriggerPathList":[],"leftColumn":2,"dynamicBindingPathList":[],"fontSize":"PARAGRAPH","text":"homepage:"},{"isRequired":true,"widgetName":"insert_col_input2","rightColumn":62,"widgetId":"6enalyprua","topRow":12,"bottomRow":16,"parentRowSpace":10,"isVisible":"true","label":"","type":"INPUT_WIDGET_V2","version":1,"parentId":"tp9pui0e6y","isLoading":false,"parentColumnSpace":8.0625,"dynamicTriggerPathList":[],"resetOnSubmit":true,"leftColumn":21,"dynamicBindingPathList":[],"inputType":"TEXT","defaultText":"","placeholderText":"homepage","isDisabled":false,"validation":"true"},{"widgetName":"Text23","rightColumn":19,"textAlign":"RIGHT","widgetId":"btk60uozsm","topRow":19,"bottomRow":23,"parentRowSpace":10,"isVisible":"true","fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"tp9pui0e6y","isLoading":false,"parentColumnSpace":7.6865234375,"dynamicTriggerPathList":[],"leftColumn":3,"dynamicBindingPathList":[],"fontSize":"PARAGRAPH","text":"imdb_id:"},{"isRequired":true,"widgetName":"insert_col_input3","rightColumn":62,"widgetId":"e490gfts69","topRow":19,"bottomRow":23,"parentRowSpace":10,"isVisible":"true","label":"","type":"INPUT_WIDGET_V2","version":1,"parentId":"tp9pui0e6y","isLoading":false,"parentColumnSpace":8.0625,"dynamicTriggerPathList":[],"resetOnSubmit":true,"leftColumn":21,"dynamicBindingPathList":[],"inputType":"TEXT","placeholderText":"imdb_id","defaultText":"","isDisabled":false,"validation":"true"},{"widgetName":"Text14","rightColumn":19,"textAlign":"RIGHT","widgetId":"8fm60omwwv","topRow":26,"bottomRow":30,"parentRowSpace":10,"isVisible":"true","fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"tp9pui0e6y","isLoading":false,"parentColumnSpace":8.0625,"dynamicTriggerPathList":[],"leftColumn":3,"dynamicBindingPathList":[],"fontSize":"PARAGRAPH","text":"poster_path:"},{"isRequired":true,"widgetName":"insert_col_input4","rightColumn":62,"widgetId":"r55cydp0ao","topRow":26,"bottomRow":30,"parentRowSpace":10,"isVisible":"true","label":"","type":"INPUT_WIDGET_V2","version":1,"parentId":"tp9pui0e6y","isLoading":false,"parentColumnSpace":8.0625,"dynamicTriggerPathList":[],"resetOnSubmit":true,"leftColumn":21,"dynamicBindingPathList":[],"inputType":"TEXT","placeholderText":"poster_path","defaultText":"","isDisabled":false,"validation":"true"},{"widgetName":"Text13Copy","rightColumn":35,"textAlign":"LEFT","widgetId":"18x7vdv3gs","topRow":0,"bottomRow":4,"isVisible":"true","fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"shouldScroll":false,"parentId":"tp9pui0e6y","isLoading":false,"dynamicTriggerPathList":[],"leftColumn":0,"dynamicBindingPathList":[],"fontSize":"HEADING1","text":"Insert Row"}]}]}],"isDisabled":false}],"width":532,"height":600},{"widgetName":"Form1","backgroundColor":"white","rightColumn":64,"dynamicPropertyPathList":[{"key":"isVisible"}],"widgetId":"m7dvlazbn7","topRow":0,"bottomRow":46,"parentRowSpace":10,"isVisible":"{{!!data_table.selectedRow._id}}","type":"FORM_WIDGET","parentId":"0","isLoading":false,"shouldScrollContents":true,"parentColumnSpace":18.8828125,"dynamicTriggerPathList":[],"leftColumn":40,"dynamicBindingPathList":[{"key":"isVisible"}],"children":[{"widgetName":"Canvas2","rightColumn":528.71875,"detachFromLayout":true,"widgetId":"cicukwhp5j","containerStyle":"none","topRow":0,"bottomRow":450,"parentRowSpace":1,"isVisible":"true","canExtend":false,"type":"CANVAS_WIDGET","version":1,"parentId":"m7dvlazbn7","minHeight":460,"isLoading":false,"parentColumnSpace":1,"dynamicTriggerPathList":[],"leftColumn":0,"dynamicBindingPathList":[],"children":[{"resetFormOnClick":false,"widgetName":"update_button","rightColumn":63,"onClick":"{{UpdateQuery.run(() => FindQuery.run(), () => showAlert('Error while updating resource!','error'))}}","isDefaultClickDisabled":true,"dynamicPropertyPathList":[],"buttonColor":"#03B365","widgetId":"4gnygu5jew","topRow":39,"bottomRow":43,"isVisible":"true","type":"FORM_BUTTON_WIDGET","version":1,"parentId":"cicukwhp5j","isLoading":false,"dynamicTriggerPathList":[{"key":"onClick"}],"disabledWhenInvalid":true,"leftColumn":47,"dynamicBindingPathList":[],"text":"Update"},{"resetFormOnClick":true,"widgetName":"reset_update_button","rightColumn":46,"onClick":"","isDefaultClickDisabled":true,"dynamicPropertyPathList":[],"buttonColor":"#03B365","widgetId":"twwgpz5wfu","topRow":39,"bottomRow":43,"isVisible":"true","type":"FORM_BUTTON_WIDGET","version":1,"parentId":"cicukwhp5j","isLoading":false,"dynamicTriggerPathList":[{"key":"onClick"}],"disabledWhenInvalid":false,"leftColumn":28,"dynamicBindingPathList":[],"buttonVariant":"OUTLINE","text":"Reset"},{"isRequired":true,"widgetName":"update_col_1","rightColumn":63,"widgetId":"in8e51pg3y","topRow":8,"bottomRow":12,"parentRowSpace":10,"isVisible":"true","label":"","type":"INPUT_WIDGET_V2","version":1,"parentId":"cicukwhp5j","isLoading":false,"parentColumnSpace":8.8963623046875,"dynamicTriggerPathList":[],"resetOnSubmit":true,"leftColumn":19,"dynamicBindingPathList":[{"key":"defaultText"}],"inputType":"TEXT","defaultText":"{{data_table.selectedRow.genres}}","isDisabled":false,"validation":"true"},{"isRequired":true,"widgetName":"update_col_2","rightColumn":63,"widgetId":"mlhvfasf31","topRow":15,"bottomRow":19,"parentRowSpace":10,"isVisible":"true","label":"","type":"INPUT_WIDGET_V2","version":1,"parentId":"cicukwhp5j","isLoading":false,"parentColumnSpace":8.8963623046875,"dynamicTriggerPathList":[],"resetOnSubmit":true,"leftColumn":19,"dynamicBindingPathList":[{"key":"defaultText"}],"inputType":"TEXT","defaultText":"{{data_table.selectedRow.homepage}}","isDisabled":false,"validation":"true"},{"isRequired":true,"widgetName":"update_col_3","rightColumn":63,"widgetId":"0lz9vhcnr0","topRow":22,"bottomRow":26,"parentRowSpace":10,"isVisible":"true","label":"","type":"INPUT_WIDGET_V2","version":1,"parentId":"cicukwhp5j","isLoading":false,"parentColumnSpace":8.8963623046875,"dynamicTriggerPathList":[],"resetOnSubmit":true,"leftColumn":19,"dynamicBindingPathList":[{"key":"defaultText"}],"inputType":"TEXT","defaultText":"{{data_table.selectedRow.imdb_id}}","isDisabled":false,"validation":"true"},{"isRequired":true,"widgetName":"update_col_4","rightColumn":63,"widgetId":"m4esf7fww5","topRow":29,"bottomRow":33,"parentRowSpace":10,"isVisible":"true","label":"","type":"INPUT_WIDGET_V2","version":1,"parentId":"cicukwhp5j","isLoading":false,"parentColumnSpace":8.8963623046875,"dynamicTriggerPathList":[],"resetOnSubmit":true,"leftColumn":19,"dynamicBindingPathList":[{"key":"defaultText"}],"inputType":"TEXT","defaultText":"{{data_table.selectedRow.poster_path}}","isDisabled":false,"validation":"true"},{"widgetName":"Text9","rightColumn":63,"textAlign":"LEFT","widgetId":"4hnz8ktmz5","topRow":0,"bottomRow":6,"parentRowSpace":10,"isVisible":"true","fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"cicukwhp5j","isLoading":false,"parentColumnSpace":8.8963623046875,"dynamicTriggerPathList":[],"leftColumn":1,"dynamicBindingPathList":[],"fontSize":"HEADING1","text":"Update Selected Row"},{"widgetName":"Text17","rightColumn":18,"textAlign":"RIGHT","widgetId":"afzzc7q8af","topRow":8,"bottomRow":12,"parentRowSpace":10,"isVisible":"true","fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"cicukwhp5j","isLoading":false,"parentColumnSpace":7.15625,"dynamicTriggerPathList":[],"leftColumn":1,"dynamicBindingPathList":[],"fontSize":"PARAGRAPH","text":"genres:"},{"widgetName":"Text18","rightColumn":18,"textAlign":"RIGHT","widgetId":"xqcsd2e5dj","topRow":15,"bottomRow":19,"parentRowSpace":10,"isVisible":"true","fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"cicukwhp5j","isLoading":false,"parentColumnSpace":7.15625,"dynamicTriggerPathList":[],"leftColumn":1,"dynamicBindingPathList":[],"fontSize":"PARAGRAPH","text":"homepage:"},{"widgetName":"Text19","rightColumn":18,"textAlign":"RIGHT","widgetId":"l109ilp3vq","topRow":22,"bottomRow":26,"parentRowSpace":10,"isVisible":"true","fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"cicukwhp5j","isLoading":false,"parentColumnSpace":7.15625,"dynamicTriggerPathList":[],"leftColumn":1,"dynamicBindingPathList":[],"fontSize":"PARAGRAPH","text":"imdb_id:"},{"widgetName":"Text20","rightColumn":18,"textAlign":"RIGHT","widgetId":"gqpwf0yng6","topRow":29,"bottomRow":33,"parentRowSpace":10,"isVisible":"true","fontStyle":"BOLD","type":"TEXT_WIDGET","textColor":"#231F20","version":1,"parentId":"cicukwhp5j","isLoading":false,"parentColumnSpace":7.15625,"dynamicTriggerPathList":[],"leftColumn":1,"dynamicBindingPathList":[],"fontSize":"PARAGRAPH","text":"poster_path:"}]}]}]},"layoutOnLoadActions":[[{"id":"616d7e429594b25adfa3e580","name":"FindQuery","pluginType":"DB","jsonPathKeys":["key_select.selectedOptionValue","data_table.pageSize","data_table.searchText||\"\"","(data_table.pageNo - 1) * data_table.pageSize","order_select.selectedOptionValue"],"timeoutInMillisecond":10000}]],"new":false}],"userPermissions":["read:pages","manage:pages"],"lastUpdatedTime":1634565699},"successMessage":"We have generated the <b>Table</b> from the <b>MongoDB datasource</b>. You can use the <b>Form</b> to modify it. Since all your data is already connected you can add more queries and modify the bindings","successImageUrl":"https://assets.appsmith.com/crud/working-flow-chart.png"}} \ No newline at end of file diff --git a/app/client/cypress/fixtures/mySQL_PUT_replaceLayoutWithCRUD.json b/app/client/cypress/fixtures/mySQL_PUT_replaceLayoutWithCRUD.json index 8972f6d52fc8..3003e41addf9 100644 --- a/app/client/cypress/fixtures/mySQL_PUT_replaceLayoutWithCRUD.json +++ b/app/client/cypress/fixtures/mySQL_PUT_replaceLayoutWithCRUD.json @@ -134,7 +134,7 @@ "isCellVisible": true, "isDerived": true, "computedValue": "", - "onClick": "{{showModal('Delete_Modal')}}", + "onClick": "{{showModal(Delete_Modal.name)}}", "textSize": "PARAGRAPH", "buttonColor": "#DD4B34", "index": 7.0, @@ -432,7 +432,7 @@ "boxShadow": "NONE", "widgetName": "add_btn", "rightColumn": 60.0, - "onClick": "{{showModal('Insert_Modal')}}", + "onClick": "{{showModal(Insert_Modal.name)}}", "iconName": "add", "buttonColor": "#03B365", "widgetId": "kby34l9nbb", @@ -524,7 +524,7 @@ { "widgetName": "Button1", "rightColumn": 46.0, - "onClick": "{{closeModal('Delete_Modal')}}", + "onClick": "{{closeModal(Delete_Modal.name)}}", "isDefaultClickDisabled": true, "dynamicPropertyPathList": [], "buttonColor": "#03B365", @@ -549,7 +549,7 @@ { "widgetName": "Delete_Button", "rightColumn": 64.0, - "onClick": "{{DeleteQuery.run(() => SelectQuery.run(() => closeModal('Delete_Modal')), () => {})}}", + "onClick": "{{DeleteQuery.run(() => SelectQuery.run(() => closeModal(Delete_Modal.name)), () => {})}}", "isDefaultClickDisabled": true, "dynamicPropertyPathList": [ { @@ -688,7 +688,7 @@ "resetFormOnClick": true, "widgetName": "insert_button", "rightColumn": 62.0, - "onClick": "{{InsertQuery.run(() => SelectQuery.run(() => closeModal('Insert_Modal')))}}", + "onClick": "{{InsertQuery.run(() => SelectQuery.run(() => closeModal(Insert_Modal.name)))}}", "isDefaultClickDisabled": true, "dynamicPropertyPathList": [ { @@ -719,7 +719,7 @@ "resetFormOnClick": true, "widgetName": "reset_button", "rightColumn": 42.0, - "onClick": "{{closeModal('Insert_Modal')}}", + "onClick": "{{closeModal(Insert_Modal.name)}}", "isDefaultClickDisabled": true, "buttonColor": "#03B365", "widgetId": "o23gs26wm5", diff --git a/app/client/cypress/fixtures/tableResizedColumnsDsl.json b/app/client/cypress/fixtures/tableResizedColumnsDsl.json index ead31f7a73ea..2ac1da30aeea 100644 --- a/app/client/cypress/fixtures/tableResizedColumnsDsl.json +++ b/app/client/cypress/fixtures/tableResizedColumnsDsl.json @@ -251,7 +251,7 @@ "customColumn2": { "isDerived": true, "computedValue": "", - "onClick": "{{showModal('Modal2')}}", + "onClick": "{{showModal(Modal2.name)}}", "textSize": "PARAGRAPH2", "buttonStyle": "#38AFF4", "index": 9, @@ -378,7 +378,7 @@ "customColumn2": { "isDerived": true, "computedValue": "", - "onClick": "{{showModal('Modal2')}}", + "onClick": "{{showModal(Modal2.name)}}", "textSize": "PARAGRAPH2", "buttonStyle": "#38AFF4", "index": 9, diff --git a/app/client/cypress/fixtures/tableV2ResizedColumnsDsl.json b/app/client/cypress/fixtures/tableV2ResizedColumnsDsl.json index 1e9bc9d942c9..1be715bfabb5 100644 --- a/app/client/cypress/fixtures/tableV2ResizedColumnsDsl.json +++ b/app/client/cypress/fixtures/tableV2ResizedColumnsDsl.json @@ -270,7 +270,7 @@ "customColumn2": { "isDerived": true, "computedValue": "", - "onClick": "{{showModal('Modal2')}}", + "onClick": "{{showModal(Modal2.name)}}", "textSize": "PARAGRAPH2", "buttonStyle": "#38AFF4", "index": 9, @@ -411,7 +411,7 @@ "customColumn2": { "isDerived": true, "computedValue": "", - "onClick": "{{showModal('Modal2')}}", + "onClick": "{{showModal(Modal2.name)}}", "textSize": "PARAGRAPH2", "buttonStyle": "#38AFF4", "index": 9, diff --git a/app/client/cypress/fixtures/uiBindDsl.json b/app/client/cypress/fixtures/uiBindDsl.json index 61780bdff08c..9d512c19977e 100644 --- a/app/client/cypress/fixtures/uiBindDsl.json +++ b/app/client/cypress/fixtures/uiBindDsl.json @@ -146,7 +146,7 @@ "bottomRow": 1, "parentId": "cwamdbv44c", "widgetId": "t3sjfihdb1", - "onClick": "{{closeModal('Modal1')}}" + "onClick": "{{closeModal(Modal1.name)}}" }, { "isVisible": true, diff --git a/app/client/packages/ast/index.ts b/app/client/packages/ast/index.ts index 60e86927a5a6..d5dfb3d1450d 100644 --- a/app/client/packages/ast/index.ts +++ b/app/client/packages/ast/index.ts @@ -4,6 +4,7 @@ import type { MemberExpressionData, IdentifierInfo, AssignmentExpressionData, + CallExpressionData, } from "./src"; import { isIdentifierNode, @@ -83,6 +84,7 @@ export type { AssignmentExpressionData, JSVarProperty, JSFunctionProperty, + CallExpressionData, }; export { diff --git a/app/client/packages/ast/src/actionCreator/index.ts b/app/client/packages/ast/src/actionCreator/index.ts index f3b89c53ff91..32b9c0c6c9df 100644 --- a/app/client/packages/ast/src/actionCreator/index.ts +++ b/app/client/packages/ast/src/actionCreator/index.ts @@ -466,6 +466,14 @@ export const getModalName = ( switch (argument?.type) { case NodeTypes.Literal: modalName = argument.value as string; + break; + case NodeTypes.MemberExpression: + // this is for cases where we have {{showModal(Modal1.name)}} or {{closeModal(Modal1.name)}} + // modalName = Modal1.name; + modalName = generate(argument, { + comments: true, + }).trim(); + break; } } @@ -509,7 +517,7 @@ export const setModalName = ( const newNode: LiteralNode = { type: NodeTypes.Literal, value: `${changeValue}`, - raw: String.raw`'${changeValue}'`, + raw: String.raw`${changeValue}`, start: startPosition, // add 2 for quotes end: startPosition + (changeValue.length + LENGTH_OF_QUOTES), diff --git a/app/client/packages/ast/src/index.ts b/app/client/packages/ast/src/index.ts index 9b88786a2e1b..da11d206e8b2 100644 --- a/app/client/packages/ast/src/index.ts +++ b/app/client/packages/ast/src/index.ts @@ -592,6 +592,11 @@ export interface AssignmentExpressionData { parentNode: NodeWithLocation<AssignmentExpressionNode>; } +export interface CallExpressionData { + property: NodeWithLocation<IdentifierNode>; + params: NodeWithLocation<MemberExpressionNode | LiteralNode>[]; +} + export interface AssignmentExpressionNode extends Node { operator: string; left: Expression; @@ -622,8 +627,10 @@ export const extractExpressionsFromCode = ( ): { invalidTopLevelMemberExpressionsArray: MemberExpressionData[]; assignmentExpressionsData: AssignmentExpressionData[]; + callExpressionsData: CallExpressionData[]; } => { const assignmentExpressionsData = new Set<AssignmentExpressionData>(); + const callExpressionsData = new Set<CallExpressionData>(); const invalidTopLevelMemberExpressions = new Set<MemberExpressionData>(); const variableDeclarations = new Set<string>(); let functionalParams = new Set<string>(); @@ -638,6 +645,7 @@ export const extractExpressionsFromCode = ( return { invalidTopLevelMemberExpressionsArray: [], assignmentExpressionsData: [], + callExpressionsData: [], }; } throw e; @@ -717,6 +725,14 @@ export const extractExpressionsFromCode = ( parentNode: node, } as AssignmentExpressionData); }, + CallExpression(node: Node) { + if (isCallExpressionNode(node) && isIdentifierNode(node.callee)) { + callExpressionsData.add({ + property: node.callee, + params: node.arguments, + } as CallExpressionData); + } + }, }); const invalidTopLevelMemberExpressionsArray = Array.from( @@ -731,6 +747,7 @@ export const extractExpressionsFromCode = ( return { invalidTopLevelMemberExpressionsArray, assignmentExpressionsData: [...assignmentExpressionsData], + callExpressionsData: [...callExpressionsData], }; }; diff --git a/app/client/src/ce/utils/autocomplete/EntityDefinitions.ts b/app/client/src/ce/utils/autocomplete/EntityDefinitions.ts index 81bfb9884a59..30a5c87ea5e6 100644 --- a/app/client/src/ce/utils/autocomplete/EntityDefinitions.ts +++ b/app/client/src/ce/utils/autocomplete/EntityDefinitions.ts @@ -286,10 +286,10 @@ export const ternDocsInfo: Record<string, any> = { ], }, showModal: { - exampleArgs: ["'Modal1'"], + exampleArgs: ["Modal1.name"], }, closeModal: { - exampleArgs: ["'Modal1'"], + exampleArgs: ["Modal1.name"], }, navigateTo: { exampleArgs: [ diff --git a/app/client/src/components/editorComponents/ActionCreator/Field/FieldConfig.ts b/app/client/src/components/editorComponents/ActionCreator/Field/FieldConfig.ts index 8e50e8d4e57d..162f1a190dfb 100644 --- a/app/client/src/components/editorComponents/ActionCreator/Field/FieldConfig.ts +++ b/app/client/src/components/editorComponents/ActionCreator/Field/FieldConfig.ts @@ -369,7 +369,7 @@ export const FIELD_CONFIG: AppsmithFunctionConfigType = { label: () => "Modal name", options: (props: FieldProps) => props.modalDropdownList, defaultText: "Select modal", - exampleText: "showModal('Modal1')", + exampleText: "showModal(Modal1.name)", getter: (value: any) => { return modalGetter(value); }, @@ -382,7 +382,7 @@ export const FIELD_CONFIG: AppsmithFunctionConfigType = { label: () => "Modal name", options: (props: FieldProps) => props.modalDropdownList, defaultText: "Select modal", - exampleText: "closeModal('Modal1')", + exampleText: "closeModal(Modal1.name)", getter: (value: any) => { return modalGetter(value); }, diff --git a/app/client/src/components/editorComponents/ActionCreator/FieldGroup/FieldGroupConfig.ts b/app/client/src/components/editorComponents/ActionCreator/FieldGroup/FieldGroupConfig.ts index 42924889ce84..477713add2ab 100644 --- a/app/client/src/components/editorComponents/ActionCreator/FieldGroup/FieldGroupConfig.ts +++ b/app/client/src/components/editorComponents/ActionCreator/FieldGroup/FieldGroupConfig.ts @@ -70,7 +70,7 @@ export const FIELD_GROUP_CONFIG: FieldGroupConfig = { [AppsmithFunction.showModal]: { label: createMessage(SHOW_MODAL), fields: [FieldType.SHOW_MODAL_FIELD], - defaultParams: `''`, + defaultParams: ``, icon: "show-modal", }, [AppsmithFunction.closeModal]: { diff --git a/app/client/src/components/editorComponents/ActionCreator/helpers.tsx b/app/client/src/components/editorComponents/ActionCreator/helpers.tsx index fe00c897ca5f..6f390850fb01 100644 --- a/app/client/src/components/editorComponents/ActionCreator/helpers.tsx +++ b/app/client/src/components/editorComponents/ActionCreator/helpers.tsx @@ -378,7 +378,7 @@ export function useModalDropdownList(handleClose: () => void) { const modalName = nextModalName; if (setter) { setter({ - value: `${modalName}`, + value: `${modalName}.name`, }); dispatch(createModalAction(modalName)); handleClose(); diff --git a/app/client/src/components/editorComponents/ActionCreator/utils.test.ts b/app/client/src/components/editorComponents/ActionCreator/utils.test.ts index 090215c9910f..e22362f4fe5a 100644 --- a/app/client/src/components/editorComponents/ActionCreator/utils.test.ts +++ b/app/client/src/components/editorComponents/ActionCreator/utils.test.ts @@ -246,26 +246,26 @@ describe("Test modalSetter", () => { { index: 1, input: "{{showModal('')}}", - expected: "{{showModal('Modal1');}}", - value: "Modal1", + expected: "{{showModal(Modal1.name);}}", + value: "Modal1.name", }, { index: 2, - input: "{{showModal('Modal1')}}", - expected: "{{showModal('Modal2');}}", - value: "Modal2", + input: "{{showModal(Modal1.name)}}", + expected: "{{showModal(Modal2.name);}}", + value: "Modal2.name", }, { index: 3, input: "{{closeModal('')}}", - expected: "{{closeModal('Modal1');}}", - value: "Modal1", + expected: "{{closeModal(Modal1.name);}}", + value: "Modal1.name", }, { index: 4, - input: "{{closeModal('Modal1')}}", - expected: "{{closeModal('Modal2');}}", - value: "Modal2", + input: "{{closeModal(Modal1.name)}}", + expected: "{{closeModal(Modal2.name);}}", + value: "Modal2.name", }, ]; test.each(cases.map((x) => [x.index, x.input, x.expected, x.value]))( @@ -286,17 +286,27 @@ describe("Test modalGetter", () => { }, { index: 2, - input: "{{showModal('Modal1')}}", - expected: "Modal1", + input: "{{showModal(Modal1.name)}}", + expected: "Modal1.name", }, { index: 3, + input: '{{showModal("Modal1")}}', + expected: "Modal1", + }, + { + index: 4, input: "{{closeModal('')}}", expected: "", }, { - index: 4, - input: "{{closeModal('Modal1')}}", + index: 5, + input: "{{closeModal(Modal1.name)}}", + expected: "Modal1.name", + }, + { + index: 6, + input: '{{closeModal("Modal1")}}', expected: "Modal1", }, ]; diff --git a/app/client/src/components/editorComponents/ActionCreator/viewComponents/ActionBlockTree/utils.tsx b/app/client/src/components/editorComponents/ActionCreator/viewComponents/ActionBlockTree/utils.tsx index 8e2193bd6e51..541fdd26daa0 100644 --- a/app/client/src/components/editorComponents/ActionCreator/viewComponents/ActionBlockTree/utils.tsx +++ b/app/client/src/components/editorComponents/ActionCreator/viewComponents/ActionBlockTree/utils.tsx @@ -149,12 +149,14 @@ function getActionHeading( case AppsmithFunction.showModal: return ( - FIELD_CONFIG[FieldType.SHOW_MODAL_FIELD].getter(code) || "Select modal" + FIELD_CONFIG[FieldType.SHOW_MODAL_FIELD].getter(code).split(".")[0] || + "Select modal" ); case AppsmithFunction.closeModal: return ( - FIELD_CONFIG[FieldType.CLOSE_MODAL_FIELD].getter(code) || "Select modal" + FIELD_CONFIG[FieldType.CLOSE_MODAL_FIELD].getter(code).split(".")[0] || + "Select modal" ); case AppsmithFunction.resetWidget: diff --git a/app/client/src/plugins/Linting/constants.ts b/app/client/src/plugins/Linting/constants.ts index 506fe6f567a5..e04d8e93f71e 100644 --- a/app/client/src/plugins/Linting/constants.ts +++ b/app/client/src/plugins/Linting/constants.ts @@ -42,6 +42,7 @@ export const WARNING_LINT_ERRORS = { W014: "Misleading line break before '{a}'; readers may interpret this as an expression boundary.", ASYNC_FUNCTION_BOUND_TO_SYNC_FIELD: "Cannot execute async code on functions bound to data fields", + ACTION_MODAL_STRING: 'Use Modal1.name instead of "Modal" as a string', }; export function asyncActionInSyncFieldLintMessage(isJsObject = false) { @@ -66,6 +67,8 @@ export enum CustomLintErrorCode { INVALID_WIDGET_PROPERTY_SETTER = "INVALID_WIDGET_PROPERTY_SETTER", // appsmith.store.value = "test" INVALID_APPSMITH_STORE_PROPERTY_SETTER = "INVALID_APPSMITH_STORE_PROPERTY_SETTER", + // showModal("Modal1") + ACTION_MODAL_STRING = "ACTION_MODAL_STRING", } export const CUSTOM_LINT_ERRORS: Record< @@ -115,4 +118,7 @@ export const CUSTOM_LINT_ERRORS: Record< [CustomLintErrorCode.INVALID_APPSMITH_STORE_PROPERTY_SETTER]: () => { return "Use storeValue() method to modify the store"; }, + [CustomLintErrorCode.ACTION_MODAL_STRING]: (modalName: string) => { + return `Use ${modalName}.name instead of "${modalName}" as a string`; + }, }; diff --git a/app/client/src/plugins/Linting/utils/getLintingErrors.ts b/app/client/src/plugins/Linting/utils/getLintingErrors.ts index abc7adfb0c56..4cacfcb92336 100644 --- a/app/client/src/plugins/Linting/utils/getLintingErrors.ts +++ b/app/client/src/plugins/Linting/utils/getLintingErrors.ts @@ -6,6 +6,7 @@ import { get, isEmpty, isNumber, keys } from "lodash"; import type { MemberExpressionData, AssignmentExpressionData, + CallExpressionData, } from "@shared/ast"; import { extractExpressionsFromCode, @@ -384,6 +385,7 @@ function getCustomErrorsFromScript( ): LintError[] { let invalidTopLevelMemberExpressions: MemberExpressionData[] = []; let assignmentExpressions: AssignmentExpressionData[] = []; + let callExpressions: CallExpressionData[] = []; try { const value = extractExpressionsFromCode( script, @@ -393,6 +395,7 @@ function getCustomErrorsFromScript( invalidTopLevelMemberExpressions = value.invalidTopLevelMemberExpressionsArray; assignmentExpressions = value.assignmentExpressionsData; + callExpressions = value.callExpressionsData; } catch (e) {} const invalidWidgetPropertySetterErrors = @@ -422,10 +425,18 @@ function getCustomErrorsFromScript( data, }); + const invalidActionModalErrors = getActionModalStringValueErrors({ + callExpressions, + script, + scriptPos, + originalBinding, + }); + return [ ...invalidPropertyErrors, ...invalidWidgetPropertySetterErrors, ...invalidAppsmithStorePropertyErrors, + ...invalidActionModalErrors, ]; } @@ -455,3 +466,57 @@ function getPositionInEvaluationScript(type: EvaluationScriptType): Position { return { line: lines.length, ch: lastLine.length }; } + +function getActionModalStringValueErrors({ + callExpressions, + originalBinding, + script, + scriptPos, +}: { + callExpressions: CallExpressionData[]; + scriptPos: Position; + originalBinding: string; + script: string; +}) { + const actionModalLintErrors: LintError[] = []; + + for (const { params, property } of callExpressions) { + if (property.name === "showModal" || property.name === "closeModal") { + if (params[0] && isLiteralNode(params[0])) { + const lintErrorMessage = CUSTOM_LINT_ERRORS[ + CustomLintErrorCode.ACTION_MODAL_STRING + ](params[0].value); + const callExpressionsString = generate(params[0]); + + // line position received after AST parsing is 1 more than the actual line of code, hence we subtract 1 to get the actual line number + const objectStartLine = params[0].loc.start.line - 1; + + // AST parsing start column position from index 0 whereas codemirror start ch position from index 1, hence we add 1 to get the actual ch position + const objectStartCol = params[0].loc.start.column + 1; + + actionModalLintErrors.push({ + errorType: PropertyEvaluationErrorType.LINT, + raw: script, + severity: getLintSeverity( + CustomLintErrorCode.ACTION_MODAL_STRING, + lintErrorMessage, + ), + errorMessage: { + name: "LintingError", + message: lintErrorMessage, + }, + errorSegment: callExpressionsString, + originalBinding, + variables: [callExpressionsString, null, null], + code: CustomLintErrorCode.ACTION_MODAL_STRING, + line: objectStartLine - scriptPos.line, + ch: + objectStartLine === scriptPos.line + ? objectStartCol - scriptPos.ch + : objectStartCol, + }); + } + } + } + return actionModalLintErrors; +} diff --git a/app/client/src/selectors/widgetSelectors.ts b/app/client/src/selectors/widgetSelectors.ts index ea276eaf47dd..f11d91f3fdd3 100644 --- a/app/client/src/selectors/widgetSelectors.ts +++ b/app/client/src/selectors/widgetSelectors.ts @@ -65,7 +65,7 @@ export const getModalDropdownList = createSelector( return modalWidgets.map((widget: FlattenedWidgetProps) => ({ id: widget.widgetId, label: widget.widgetName, - value: `${widget.widgetName}`, + value: `${widget.widgetName}.name`, })); }, ); diff --git a/app/client/src/utils/testDSLs.ts b/app/client/src/utils/testDSLs.ts index 1b49e7e5067e..02fb9a2debad 100644 --- a/app/client/src/utils/testDSLs.ts +++ b/app/client/src/utils/testDSLs.ts @@ -3532,7 +3532,7 @@ export const originalDSLForDSLMigrations = { { boxShadow: "none", widgetName: "IconButton6", - onClick: "{{closeModal('Modal1')}}", + onClick: "{{closeModal(Modal1.name)}}", buttonColor: "{{appsmith.theme.colors.primaryColor}}", displayName: "Icon button", iconSVG: "/static/media/icon.1a0c634a.svg", diff --git a/app/client/src/widgets/ModalWidget/widget/index.tsx b/app/client/src/widgets/ModalWidget/widget/index.tsx index ce4db6374be2..8aaebeb0c0a8 100644 --- a/app/client/src/widgets/ModalWidget/widget/index.tsx +++ b/app/client/src/widgets/ModalWidget/widget/index.tsx @@ -3,7 +3,7 @@ import { EventType } from "constants/AppsmithActionConstants/ActionConstants"; import type { RenderMode } from "constants/WidgetConstants"; import { GridDefaults } from "constants/WidgetConstants"; import { ValidationTypes } from "constants/WidgetValidation"; -import type { Stylesheet } from "entities/AppTheming"; +import type { SetterConfig, Stylesheet } from "entities/AppTheming"; import { SelectionRequestType } from "sagas/WidgetSelectUtils"; import { FlexLayerAlignment, @@ -178,7 +178,7 @@ export class ModalWidget extends BaseWidget<ModalWidgetProps, WidgetState> { { widgetId: iconChild.widgetId, propertyName: "onClick", - propertyValue: `{{closeModal('${parent.widgetName}')}}`, + propertyValue: `{{closeModal(${parent.widgetName}.name);}}`, }, ]; } @@ -204,7 +204,7 @@ export class ModalWidget extends BaseWidget<ModalWidgetProps, WidgetState> { { widgetId: cancelBtnChild.widgetId, propertyName: "onClick", - propertyValue: `{{closeModal('${parent.widgetName}')}}`, + propertyValue: `{{closeModal(${parent.widgetName}.name);}}`, }, ]; } @@ -359,6 +359,22 @@ export class ModalWidget extends BaseWidget<ModalWidgetProps, WidgetState> { static getAutocompleteDefinitions(): AutocompletionDefinitions { return { isVisible: DefaultAutocompleteDefinitions.isVisible, + name: { + "!type": "string", + "!doc": "Returns the modal name", + }, + }; + } + + static getDerivedPropertiesMap() { + return { + name: "{{this.widgetName}}", + }; + } + + static getSetterConfig(): SetterConfig { + return { + __setters: {}, }; } diff --git a/app/client/test/factories/Widgets/ModalFactory.ts b/app/client/test/factories/Widgets/ModalFactory.ts index 8deeb7071c89..4584f6085b51 100644 --- a/app/client/test/factories/Widgets/ModalFactory.ts +++ b/app/client/test/factories/Widgets/ModalFactory.ts @@ -199,7 +199,7 @@ export const ModalFactory = Factory.Sync.makeFactory<WidgetProps>({ { widgetName: "Icon1", rightColumn: 16, - onClick: "{{closeModal('TestModal')}}", + onClick: "{{closeModal(TestModal.name)}}", color: "#040627", iconName: "cross", widgetId: "n5fc0ven2a",
fa01d10bf51a53772513ff332679ee76ed3dbcaf
2023-12-01 16:24:37
Shrikant Sharat Kandula
chore: Install Caddy ahead of PR to enable Caddy support (#29256)
false
Install Caddy ahead of PR to enable Caddy support (#29256)
chore
diff --git a/deploy/docker/base.dockerfile b/deploy/docker/base.dockerfile index 072de958b6ad..4b3bed07fe3f 100644 --- a/deploy/docker/base.dockerfile +++ b/deploy/docker/base.dockerfile @@ -49,6 +49,13 @@ RUN set -o xtrace \ && file="$(curl -sS 'https://nodejs.org/dist/latest-v18.x/' | awk -F\" '$2 ~ /linux-'"$(uname -m | sed 's/x86_64/x64/; s/aarch64/arm64/')"'.tar.gz/ {print $2}')" \ && curl "https://nodejs.org/dist/latest-v18.x/$file" | tar -xz -C /opt/node --strip-components 1 +# Install Caddy +RUN set -o xtrace \ + && mkdir -p /opt/caddy \ + && version="$(curl --write-out '%{redirect_url}' 'https://github.com/caddyserver/caddy/releases/latest' | sed 's,.*/v,,')" \ + && curl --location "https://github.com/caddyserver/caddy/releases/download/v$version/caddy_${version}_linux_$(uname -m | sed 's/x86_64/amd64/; s/aarch64/arm64/').tar.gz" \ + | tar -xz -C /opt/caddy + # Clean up cache file - Service layer RUN rm -rf \ /root/.cache \
3b10f233cd7313ca67becfddc5d4965a9bf4647e
2024-03-09 09:55:50
Nidhi
ci: Make Cypress results show up in body as well (#31631)
false
Make Cypress results show up in body as well (#31631)
ci
diff --git a/.github/workflows/integration-tests-command-2.yml b/.github/workflows/integration-tests-command-2.yml index 7632128b086f..2153ea954802 100644 --- a/.github/workflows/integration-tests-command-2.yml +++ b/.github/workflows/integration-tests-command-2.yml @@ -170,109 +170,58 @@ jobs: echo "$new_failed_spec_env" >> $GITHUB_ENV echo "EOF" >> $GITHUB_ENV - - name: Add a comment on the PR with new CI failures + - name: Modify test response in the PR with new CI failures if: needs.ci-test.result != 'success' && steps.combine_ci.outputs.specs_failed == '1' - uses: peter-evans/create-or-update-comment@v3 + uses: nefrob/[email protected] with: - issue-number: ${{ github.event.number }} - body: | - Workflow run: <${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}>. - Commit: `${{ github.event.client_payload.slash_command.args.named.sha }}`. - Cypress dashboard: <a href="https://internal.appsmith.com/app/cypress-dashboard/rundetails-65890b3c81d7400d08fa9ee5?branch=master&workflowId=${{ github.run_id }}&attempt=${{ github.run_attempt }}&selectiontype=test&testsstatus=failed&specsstatus=fail" target="_blank"> Click here!</a> - The following are new failures, please fix them before merging the PR: ${{env.new_failed_spec_env}} - To know the list of identified flaky tests - <a href="https://internal.appsmith.com/app/cypress-dashboard/identified-flaky-tests-65890b3c81d7400d08fa9ee3?branch=master" target="_blank">Refer here</a> - - - name: Add a comment on the PR when ci-test is failed but no specs found + content: | + ################# _Do Not Edit This Area_ ################# + #### ok-to-test Response: + Workflow run: <${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}>. + Commit: `${{ github.event.pull_request.head.sha }}`. + Cypress dashboard: <a href="https://internal.appsmith.com/app/cypress-dashboard/rundetails-65890b3c81d7400d08fa9ee5?branch=master&workflowId=${{ github.run_id }}&attempt=${{ github.run_attempt }}&selectiontype=test&testsstatus=failed&specsstatus=fail" target="_blank"> Click here!</a> + The following are new failures, please fix them before merging the PR: ${{env.new_failed_spec_env}} + To know the list of identified flaky tests - <a href="https://internal.appsmith.com/app/cypress-dashboard/identified-flaky-tests-65890b3c81d7400d08fa9ee3?branch=master" target="_blank">Refer here</a> + + ################################################### + regex: "################# _Do Not Edit This Area_ #################.*?###################################################" + regexFlags: ims + token: ${{ secrets.GITHUB_TOKEN }} + + - name: Modify test response in the PR when ci-test is failed but no specs found if: needs.ci-test.result != 'success' && steps.combine_ci.outputs.specs_failed == '0' - uses: peter-evans/create-or-update-comment@v3 + uses: nefrob/[email protected] with: - issue-number: ${{ github.event.number }} - body: | - Workflow run: <${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}>. - Commit: `${{ github.event.client_payload.slash_command.args.named.sha }}`. - Cypress dashboard url: <a href="https://internal.appsmith.com/app/cypress-dashboard/rundetails-65890b3c81d7400d08fa9ee5?branch=master&workflowId=${{ github.run_id }}&attempt=${{ github.run_attempt }}" target="_blank">Click here!</a> - It seems like **no tests ran** 😔. We are not able to recognize it, please check workflow <a href="${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}" target="_blank">here.</a> - - - name: Add a comment on the PR when ci-test is success + content: | + ################# _Do Not Edit This Area_ ################# + #### ok-to-test Response: + Workflow run: <${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}>. + Commit: `${{ github.event.pull_request.head.sha }}`. + Cypress dashboard url: <a href="https://internal.appsmith.com/app/cypress-dashboard/rundetails-65890b3c81d7400d08fa9ee5?branch=master&workflowId=${{ github.run_id }}&attempt=${{ github.run_attempt }}" target="_blank">Click here!</a> + It seems like **no tests ran** 😔. We are not able to recognize it, please check workflow <a href="${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}" target="_blank">here.</a> + + ################################################### + regex: "################# _Do Not Edit This Area_ #################.*?###################################################" + regexFlags: ims + token: ${{ secrets.GITHUB_TOKEN }} + + - name: Modify test response in the PR when ci-test is success if: needs.ci-test.result == 'success' && steps.combine_ci.outputs.specs_failed == '0' - uses: peter-evans/create-or-update-comment@v3 + uses: nefrob/[email protected] with: - issue-number: ${{ github.event.number }} - body: | - Workflow run: <${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}>. - Commit: `${{ github.event.client_payload.slash_command.args.named.sha }}`. - Cypress dashboard url: <a href="https://internal.appsmith.com/app/cypress-dashboard/rundetails-65890b3c81d7400d08fa9ee5?branch=master&workflowId=${{ github.run_id }}&attempt=${{ github.run_attempt }}" target="_blank">Click here!</a> - All cypress tests have passed 🎉🎉🎉 + content: | + ################# _Do Not Edit This Area_ ################# + #### ok-to-test Response: + Workflow run: <${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}>. + Commit: `${{ github.event.pull_request.head.sha }}`. + Cypress dashboard url: <a href="https://internal.appsmith.com/app/cypress-dashboard/rundetails-65890b3c81d7400d08fa9ee5?branch=master&workflowId=${{ github.run_id }}&attempt=${{ github.run_attempt }}" target="_blank">Click here!</a> + All cypress tests have passed 🎉🎉🎉 + + ################################################### + regex: "################# _Do Not Edit This Area_ #################.*?###################################################" + regexFlags: ims + token: ${{ secrets.GITHUB_TOKEN }} - name: Check ci-test set status if: needs.ci-test.result != 'success' - run: exit 1 - - package: - needs: [ci-test] - runs-on: ubuntu-latest - defaults: - run: - working-directory: app/client - # Run this job only if all the previous steps are a success and the reference if the release or master branch - if: success() && (github.ref == 'refs/heads/release' || github.ref == 'refs/heads/master') - - steps: - # Update check run called "package" - - name: Mark package job as complete - uses: actions/github-script@v6 - id: update-check-run - if: ${{ always() }} - env: - run_id: ${{ github.run_id }} - repository: ${{ github.repository }} - number: ${{ github.event.number }} - job: ${{ github.job }} - # Conveniently, job.status maps to https://developer.github.com/v3/checks/runs/#update-a-check-run - conclusion: ${{ job.status }} - with: - github-token: ${{ secrets.GITHUB_TOKEN }} - script: | - const { data: pull } = await github.rest.pulls.get({ - ...context.repo, - pull_number: process.env.number - }); - const ref = pull.head.sha; - - const { data: checks } = await github.rest.checks.listForRef({ - ...context.repo, - ref - }); - - const check = checks.check_runs.filter(c => c.name === process.env.job); - - if(check.length == 0) { - const head_sha = pull.head.sha; - const { data: completed_at } = await github.rest.checks.create({ - owner: context.repo.owner, - repo: context.repo.repo, - head_sha: head_sha, - name: process.env.job, - status: 'completed', - conclusion: process.env.conclusion, - output: { - title: "Package result for ok to test", - summary: "https://github.com/" + process.env.repository + "/actions/runs/" + process.env.run_id - } - }); - - return completed_at; - } else { - const { data: result } = await github.rest.checks.update({ - ...context.repo, - check_run_id: check[0].id, - status: 'completed', - conclusion: process.env.conclusion, - output: { - title: "Package result for ok to test", - summary: "https://github.com/" + process.env.repository + "/actions/runs/" + process.env.run_id - } - }); - - return result; - } + run: exit 1 \ No newline at end of file diff --git a/.github/workflows/ok-to-test-2.yml b/.github/workflows/ok-to-test-2.yml index 3e1a9a17863c..07d26f21edfd 100644 --- a/.github/workflows/ok-to-test-2.yml +++ b/.github/workflows/ok-to-test-2.yml @@ -141,7 +141,6 @@ jobs: regex: "################# _Do Not Edit This Area_ #################.*?###################################################" regexFlags: ims token: ${{ secrets.GITHUB_TOKEN }} - uses: peter-evans/create-or-update-comment@v3 # Call the workflow to run Cypress tests perform-test:
a7bf302f9a523dce3e946b0b1980135e781a1e89
2024-10-14 11:20:21
Pawan Kumar
chore: Update markdown component + create avatar component + refactor (#36832)
false
Update markdown component + create avatar component + refactor (#36832)
chore
diff --git a/app/client/packages/design-system/widgets/jest.config.js b/app/client/packages/design-system/widgets/jest.config.js index 08272cd0c571..3043cc942948 100644 --- a/app/client/packages/design-system/widgets/jest.config.js +++ b/app/client/packages/design-system/widgets/jest.config.js @@ -1,3 +1,5 @@ +const esModules = ["remark-gfm"].join("|"); + module.exports = { preset: "ts-jest", roots: ["<rootDir>/src"], @@ -6,6 +8,9 @@ module.exports = { moduleNameMapper: { "\\.(css)$": "<rootDir>../../../test/__mocks__/styleMock.js", }, + transformIgnorePatterns: [ + `[/\\\\]node_modules[/\\\\](?!${esModules}).+\\.(js|jsx|mjs|cjs|ts|tsx)$`, + ], globals: { "ts-jest": { useESM: true, diff --git a/app/client/packages/design-system/widgets/package.json b/app/client/packages/design-system/widgets/package.json index 12607a4be39a..799d1e31679e 100644 --- a/app/client/packages/design-system/widgets/package.json +++ b/app/client/packages/design-system/widgets/package.json @@ -28,7 +28,8 @@ "lodash": "*", "react-aria-components": "^1.2.1", "react-markdown": "^9.0.1", - "react-syntax-highlighter": "^15.5.0" + "react-syntax-highlighter": "^15.5.0", + "remark-gfm": "^4.0.0" }, "devDependencies": { "@types/fs-extra": "^11.0.4", diff --git a/app/client/packages/design-system/widgets/src/components/AIChat/src/AIChat.tsx b/app/client/packages/design-system/widgets/src/components/AIChat/src/AIChat.tsx index 4fbadd4aaad5..f952bec2329f 100644 --- a/app/client/packages/design-system/widgets/src/components/AIChat/src/AIChat.tsx +++ b/app/client/packages/design-system/widgets/src/components/AIChat/src/AIChat.tsx @@ -1,14 +1,11 @@ -import { Button, Flex, Text, TextArea } from "@appsmith/wds"; -import type { FormEvent, ForwardedRef, KeyboardEvent } from "react"; -import React, { forwardRef, useCallback } from "react"; -import { ChatDescriptionModal } from "./ChatDescriptionModal"; -import { ChatTitle } from "./ChatTitle"; -import styles from "./styles.module.css"; -import { ThreadMessage } from "./ThreadMessage"; -import type { AIChatProps, ChatMessage } from "./types"; -import { UserAvatar } from "./UserAvatar"; +import type { ForwardedRef } from "react"; +import React, { forwardRef } from "react"; -const MIN_PROMPT_LENGTH = 3; +import styles from "./styles.module.css"; +import { ChatHeader } from "./ChatHeader"; +import { ChatThread } from "./ChatThread"; +import type { AIChatProps } from "./types"; +import { ChatInputSection } from "./ChatInputSection"; const _AIChat = (props: AIChatProps, ref: ForwardedRef<HTMLDivElement>) => { const { @@ -25,81 +22,28 @@ const _AIChat = (props: AIChatProps, ref: ForwardedRef<HTMLDivElement>) => { username, ...rest } = props; - const [isChatDescriptionModalOpen, setIsChatDescriptionModalOpen] = - React.useState(false); - - const handleFormSubmit = useCallback( - (event: FormEvent<HTMLFormElement>) => { - event.preventDefault(); - onSubmit?.(); - }, - [onSubmit], - ); - - const handlePromptInputKeyDown = useCallback( - (event: KeyboardEvent<HTMLTextAreaElement>) => { - if (event.key === "Enter" && event.shiftKey) { - event.preventDefault(); - onSubmit?.(); - } - }, - [onSubmit], - ); return ( <div className={styles.root} ref={ref} {...rest}> - <ChatDescriptionModal - isOpen={isChatDescriptionModalOpen} - setOpen={() => - setIsChatDescriptionModalOpen(!isChatDescriptionModalOpen) - } - > - {chatDescription} - </ChatDescriptionModal> - - <div className={styles.header}> - <Flex alignItems="center" gap="spacing-2"> - <ChatTitle title={chatTitle} /> - <Button - icon="info-square-rounded" - onPress={() => setIsChatDescriptionModalOpen(true)} - variant="ghost" - /> - </Flex> - - <Flex alignItems="center" gap="spacing-2"> - <UserAvatar username={username} /> - <Text data-testid="t--aichat-username" size="body"> - {username} - </Text> - </Flex> - </div> - - <ul className={styles.thread} data-testid="t--aichat-thread"> - {thread.map((message: ChatMessage) => ( - <ThreadMessage - {...message} - key={message.id} - onApplyAssistantSuggestion={onApplyAssistantSuggestion} - username={username} - /> - ))} - </ul> - - <form className={styles.promptForm} onSubmit={handleFormSubmit}> - <TextArea - // TODO: Handle isWaitingForResponse: true state - isDisabled={isWaitingForResponse} - name="prompt" - onChange={onPromptChange} - onKeyDown={handlePromptInputKeyDown} - placeholder={promptInputPlaceholder} - value={prompt} - /> - <Button isDisabled={prompt.length < MIN_PROMPT_LENGTH} type="submit"> - Send - </Button> - </form> + <ChatHeader + chatDescription={chatDescription} + chatTitle={chatTitle} + username={username} + /> + + <ChatThread + onApplyAssistantSuggestion={onApplyAssistantSuggestion} + thread={thread} + username={username} + /> + + <ChatInputSection + isWaitingForResponse={isWaitingForResponse} + onPromptChange={onPromptChange} + onSubmit={onSubmit} + prompt={prompt} + promptInputPlaceholder={promptInputPlaceholder} + /> </div> ); }; diff --git a/app/client/packages/design-system/widgets/src/components/AIChat/src/ChatDescriptionModal/ChatDescriptionModal.tsx b/app/client/packages/design-system/widgets/src/components/AIChat/src/ChatDescriptionModal/ChatDescriptionModal.tsx deleted file mode 100644 index 06b983a1e32f..000000000000 --- a/app/client/packages/design-system/widgets/src/components/AIChat/src/ChatDescriptionModal/ChatDescriptionModal.tsx +++ /dev/null @@ -1,17 +0,0 @@ -import { Modal, ModalBody, ModalContent, ModalHeader } from "@appsmith/wds"; -import React from "react"; -import type { ChatDescriptionModalProps } from "./types"; - -export const ChatDescriptionModal = ({ - children, - ...rest -}: ChatDescriptionModalProps) => { - return ( - <Modal {...rest}> - <ModalContent> - <ModalHeader title="Information about the bot" /> - <ModalBody>{children}</ModalBody> - </ModalContent> - </Modal> - ); -}; diff --git a/app/client/packages/design-system/widgets/src/components/AIChat/src/ChatDescriptionModal/index.ts b/app/client/packages/design-system/widgets/src/components/AIChat/src/ChatDescriptionModal/index.ts deleted file mode 100644 index e16a07a5b8f4..000000000000 --- a/app/client/packages/design-system/widgets/src/components/AIChat/src/ChatDescriptionModal/index.ts +++ /dev/null @@ -1,2 +0,0 @@ -export * from "./ChatDescriptionModal"; -export * from "./types"; diff --git a/app/client/packages/design-system/widgets/src/components/AIChat/src/ChatDescriptionModal/types.ts b/app/client/packages/design-system/widgets/src/components/AIChat/src/ChatDescriptionModal/types.ts deleted file mode 100644 index 41e2f9c04360..000000000000 --- a/app/client/packages/design-system/widgets/src/components/AIChat/src/ChatDescriptionModal/types.ts +++ /dev/null @@ -1,3 +0,0 @@ -import type { ModalProps } from "@appsmith/wds"; - -export interface ChatDescriptionModalProps extends ModalProps {} diff --git a/app/client/packages/design-system/widgets/src/components/AIChat/src/ChatHeader.tsx b/app/client/packages/design-system/widgets/src/components/AIChat/src/ChatHeader.tsx new file mode 100644 index 000000000000..b05f513782b6 --- /dev/null +++ b/app/client/packages/design-system/widgets/src/components/AIChat/src/ChatHeader.tsx @@ -0,0 +1,62 @@ +import React, { useState } from "react"; +import { + Avatar, + Button, + Flex, + Modal, + ModalBody, + ModalContent, + ModalHeader, + Text, +} from "@appsmith/wds"; + +import styles from "./styles.module.css"; + +// this value might come from props in future. So keeping a temporary value here. +const LOGO = + "https://app.appsmith.com/static/media/appsmith_logo_square.3867b1959653dabff8dc.png"; + +export const ChatHeader: React.FC<{ + chatTitle?: string; + username: string; + chatDescription?: string; +}> = ({ chatDescription, chatTitle, username }) => { + const [isChatDescriptionModalOpen, setIsChatDescriptionModalOpen] = + useState(false); + + return ( + <> + <div className={styles.header}> + <Flex alignItems="center" gap="spacing-2"> + <Flex alignItems="center" gap="spacing-3"> + <Avatar label="Appsmith AI" size="large" src={LOGO} /> + <Text fontWeight={600} size="subtitle"> + {chatTitle} + </Text> + </Flex> + <Button + icon="info-square-rounded" + onPress={() => setIsChatDescriptionModalOpen(true)} + variant="ghost" + /> + </Flex> + <Flex alignItems="center" gap="spacing-2"> + <Avatar label={username} /> + <Text data-testid="t--aichat-username" size="body"> + {username} + </Text> + </Flex> + </div> + + <Modal + isOpen={isChatDescriptionModalOpen} + setOpen={setIsChatDescriptionModalOpen} + > + <ModalContent> + <ModalHeader title="Information about the bot" /> + <ModalBody>{chatDescription}</ModalBody> + </ModalContent> + </Modal> + </> + ); +}; diff --git a/app/client/packages/design-system/widgets/src/components/AIChat/src/ChatInputSection.tsx b/app/client/packages/design-system/widgets/src/components/AIChat/src/ChatInputSection.tsx new file mode 100644 index 000000000000..fbc0183c1ce9 --- /dev/null +++ b/app/client/packages/design-system/widgets/src/components/AIChat/src/ChatInputSection.tsx @@ -0,0 +1,48 @@ +import React from "react"; +import { Flex, ChatInput, Icon, Text } from "@appsmith/wds"; + +const MIN_PROMPT_LENGTH = 3; + +export const ChatInputSection: React.FC<{ + isWaitingForResponse: boolean; + prompt: string; + promptInputPlaceholder?: string; + onPromptChange: (value: string) => void; + onSubmit?: () => void; +}> = ({ + isWaitingForResponse, + onPromptChange, + onSubmit, + prompt, + promptInputPlaceholder, +}) => ( + <Flex + direction="column" + gap="spacing-3" + paddingBottom="spacing-4" + paddingLeft="spacing-6" + paddingRight="spacing-6" + paddingTop="spacing-4" + > + <ChatInput + isLoading={isWaitingForResponse} + isSubmitDisabled={prompt.length < MIN_PROMPT_LENGTH} + onChange={onPromptChange} + onSubmit={onSubmit} + placeholder={promptInputPlaceholder} + value={prompt} + /> + <Flex + alignItems="center" + flexGrow={1} + gap="spacing-1" + justifyContent="center" + > + <Icon name="alert-circle" size="small" /> + <Text color="neutral" size="caption" textAlign="center"> + LLM assistant can make mistakes. Answers should be verified before they + are trusted. + </Text> + </Flex> + </Flex> +); diff --git a/app/client/packages/design-system/widgets/src/components/AIChat/src/ChatThread.tsx b/app/client/packages/design-system/widgets/src/components/AIChat/src/ChatThread.tsx new file mode 100644 index 000000000000..82ab94e2b0c4 --- /dev/null +++ b/app/client/packages/design-system/widgets/src/components/AIChat/src/ChatThread.tsx @@ -0,0 +1,53 @@ +import React from "react"; +import { Avatar, Flex, Markdown } from "@appsmith/wds"; + +import styles from "./styles.module.css"; +import type { ChatMessage } from "./types"; +import { AssistantSuggestionButton } from "./AssistantSuggestionButton"; + +export const ChatThread: React.FC<{ + thread: ChatMessage[]; + onApplyAssistantSuggestion?: (suggestion: string) => void; + username: string; +}> = ({ onApplyAssistantSuggestion, thread, username }) => ( + <Flex direction="column" gap="spacing-3" padding="spacing-6"> + {thread.map((message: ChatMessage) => { + const { content, isAssistant, promptSuggestions = [] } = message; + + return ( + <Flex direction={isAssistant ? "row" : "row-reverse"} key={message.id}> + {isAssistant && ( + <div> + <Markdown>{content}</Markdown> + + {promptSuggestions.length > 0 && ( + <Flex + className={styles.suggestions} + gap="spacing-5" + paddingTop="spacing-4" + wrap="wrap" + > + {promptSuggestions.map((suggestion) => ( + <AssistantSuggestionButton + key={suggestion} + // eslint-disable-next-line react-perf/jsx-no-new-function-as-prop + onPress={() => onApplyAssistantSuggestion?.(suggestion)} + > + {suggestion} + </AssistantSuggestionButton> + ))} + </Flex> + )} + </div> + )} + {!isAssistant && ( + <Flex direction="row-reverse" gap="spacing-3"> + <Avatar label={username} /> + <div>{content}</div> + </Flex> + )} + </Flex> + ); + })} + </Flex> +); diff --git a/app/client/packages/design-system/widgets/src/components/AIChat/src/ChatTitle/ChatTitle.tsx b/app/client/packages/design-system/widgets/src/components/AIChat/src/ChatTitle/ChatTitle.tsx deleted file mode 100644 index 2819d3523144..000000000000 --- a/app/client/packages/design-system/widgets/src/components/AIChat/src/ChatTitle/ChatTitle.tsx +++ /dev/null @@ -1,17 +0,0 @@ -import { clsx } from "clsx"; -import React from "react"; -import styles from "./styles.module.css"; -import type { ChatTitleProps } from "./types"; - -export const ChatTitle = ({ className, title, ...rest }: ChatTitleProps) => { - return ( - <div - className={clsx(styles.root, className)} - {...rest} - data-testid="t--aichat-chat-title" - > - <div className={styles.logo} /> - {title} - </div> - ); -}; diff --git a/app/client/packages/design-system/widgets/src/components/AIChat/src/ChatTitle/index.ts b/app/client/packages/design-system/widgets/src/components/AIChat/src/ChatTitle/index.ts deleted file mode 100644 index 78b61712de79..000000000000 --- a/app/client/packages/design-system/widgets/src/components/AIChat/src/ChatTitle/index.ts +++ /dev/null @@ -1,2 +0,0 @@ -export * from "./ChatTitle"; -export * from "./types"; diff --git a/app/client/packages/design-system/widgets/src/components/AIChat/src/ChatTitle/styles.module.css b/app/client/packages/design-system/widgets/src/components/AIChat/src/ChatTitle/styles.module.css deleted file mode 100644 index f231c0590300..000000000000 --- a/app/client/packages/design-system/widgets/src/components/AIChat/src/ChatTitle/styles.module.css +++ /dev/null @@ -1,22 +0,0 @@ -.root { - display: flex; - gap: var(--inner-spacing-3); - align-items: center; - /* TODO: --type-title doesn't exists. Define it */ - font-size: var(--type-title, 22.499px); - font-style: normal; - font-weight: 500; - /* TODO: --type-title-lineheight doesn't exists. Define it */ - line-height: var(--type-title-lineheight, 31.7px); -} - -.logo { - display: inline-block; - width: 48px; - min-width: 48px; - height: 48px; - border-radius: var(--border-radius-elevation-2); - /* TODO: --bd-neutral doesn't exists. Define it */ - border: 1px solid var(--bd-neutral, #81858b); - background: #f8f8f8; -} diff --git a/app/client/packages/design-system/widgets/src/components/AIChat/src/ChatTitle/types.ts b/app/client/packages/design-system/widgets/src/components/AIChat/src/ChatTitle/types.ts deleted file mode 100644 index 220bbc4efa72..000000000000 --- a/app/client/packages/design-system/widgets/src/components/AIChat/src/ChatTitle/types.ts +++ /dev/null @@ -1,5 +0,0 @@ -import type { HTMLProps } from "react"; - -export interface ChatTitleProps extends HTMLProps<HTMLDivElement> { - title?: string; -} diff --git a/app/client/packages/design-system/widgets/src/components/AIChat/src/ThreadMessage/ThreadMessage.tsx b/app/client/packages/design-system/widgets/src/components/AIChat/src/ThreadMessage/ThreadMessage.tsx deleted file mode 100644 index 9be3e3b7cec3..000000000000 --- a/app/client/packages/design-system/widgets/src/components/AIChat/src/ThreadMessage/ThreadMessage.tsx +++ /dev/null @@ -1,86 +0,0 @@ -import { Flex, Text } from "@appsmith/wds"; -import { clsx } from "clsx"; -import React from "react"; -import Markdown from "react-markdown"; -import SyntaxHighlighter from "react-syntax-highlighter"; -import { monokai } from "react-syntax-highlighter/dist/cjs/styles/hljs"; -import { AssistantSuggestionButton } from "../AssistantSuggestionButton"; -import { UserAvatar } from "../UserAvatar"; -import styles from "./styles.module.css"; -import type { ThreadMessageProps } from "./types"; - -export const ThreadMessage = ({ - className, - content, - isAssistant, - onApplyAssistantSuggestion, - promptSuggestions = [], - username, - ...rest -}: ThreadMessageProps) => { - return ( - <li - className={clsx(styles.root, className)} - data-assistant={isAssistant} - {...rest} - > - {isAssistant ? ( - <div> - <Text className={styles.content}> - <Markdown - // eslint-disable-next-line react-perf/jsx-no-new-object-as-prop - components={{ - code(props) { - const { children, className, ...rest } = props; - const match = /language-(\w+)/.exec(className ?? ""); - - return match ? ( - <SyntaxHighlighter - PreTag="div" - language={match[1]} - style={monokai} - > - {String(children).replace(/\n$/, "")} - </SyntaxHighlighter> - ) : ( - <code {...rest} className={className}> - {children} - </code> - ); - }, - }} - > - {content} - </Markdown> - </Text> - - {promptSuggestions.length > 0 && ( - <Flex - className={styles.suggestions} - gap="spacing-5" - paddingTop="spacing-4" - wrap="wrap" - > - {promptSuggestions.map((suggestion) => ( - <AssistantSuggestionButton - key={suggestion} - // eslint-disable-next-line react-perf/jsx-no-new-function-as-prop - onPress={() => onApplyAssistantSuggestion?.(suggestion)} - > - {suggestion} - </AssistantSuggestionButton> - ))} - </Flex> - )} - </div> - ) : ( - <> - <UserAvatar className={styles.userAvatar} username={username} /> - <div> - <Text className={styles.content}>{content}</Text> - </div> - </> - )} - </li> - ); -}; diff --git a/app/client/packages/design-system/widgets/src/components/AIChat/src/ThreadMessage/index.ts b/app/client/packages/design-system/widgets/src/components/AIChat/src/ThreadMessage/index.ts deleted file mode 100644 index 9916fbd0d566..000000000000 --- a/app/client/packages/design-system/widgets/src/components/AIChat/src/ThreadMessage/index.ts +++ /dev/null @@ -1,2 +0,0 @@ -export * from "./ThreadMessage"; -export * from "./types"; diff --git a/app/client/packages/design-system/widgets/src/components/AIChat/src/ThreadMessage/styles.module.css b/app/client/packages/design-system/widgets/src/components/AIChat/src/ThreadMessage/styles.module.css deleted file mode 100644 index 198d74d9cca0..000000000000 --- a/app/client/packages/design-system/widgets/src/components/AIChat/src/ThreadMessage/styles.module.css +++ /dev/null @@ -1,27 +0,0 @@ -.root { - display: flex; - gap: var(--inner-spacing-4); - padding: var(--inner-spacing-3) 0; -} - -@container (min-width: 700px) { - .root { - padding: var(--inner-spacing-5) 0; - } -} - -.root[data-assistant="false"] { - flex-direction: row-reverse; -} - -.root[data-assistant="false"] .sentTime { - text-align: right; -} - -.sentTime { - margin: 0 0 var(--outer-spacing-3); - /* TODO: --type-caption doesn't exists. Define it */ - font-size: var(--type-caption, 12.247px); - /* TODO: --type-caption-lineheight doesn't exists. Define it */ - line-height: var(--type-caption-lineheight, 17.25px); -} diff --git a/app/client/packages/design-system/widgets/src/components/AIChat/src/ThreadMessage/types.ts b/app/client/packages/design-system/widgets/src/components/AIChat/src/ThreadMessage/types.ts deleted file mode 100644 index 4459c37a5a94..000000000000 --- a/app/client/packages/design-system/widgets/src/components/AIChat/src/ThreadMessage/types.ts +++ /dev/null @@ -1,9 +0,0 @@ -import type { HTMLProps } from "react"; - -export interface ThreadMessageProps extends HTMLProps<HTMLLIElement> { - content: string; - isAssistant: boolean; - username: string; - promptSuggestions?: string[]; - onApplyAssistantSuggestion?: (suggestion: string) => void; -} diff --git a/app/client/packages/design-system/widgets/src/components/AIChat/src/UserAvatar/UserAvatar.tsx b/app/client/packages/design-system/widgets/src/components/AIChat/src/UserAvatar/UserAvatar.tsx deleted file mode 100644 index 2c1667a4f22b..000000000000 --- a/app/client/packages/design-system/widgets/src/components/AIChat/src/UserAvatar/UserAvatar.tsx +++ /dev/null @@ -1,27 +0,0 @@ -import { clsx } from "clsx"; -import React from "react"; -import styles from "./styles.module.css"; -import type { UserAvatarProps } from "./types"; - -export const UserAvatar = ({ - className, - username, - ...rest -}: UserAvatarProps) => { - const getNameInitials = (username: string) => { - const names = username.split(" "); - - // If there is only one name, return the first character of the name. - if (names.length === 1) { - return `${names[0].charAt(0)}`; - } - - return `${names[0].charAt(0)}${names[1]?.charAt(0)}`; - }; - - return ( - <span className={clsx(styles.root, className)} {...rest}> - {getNameInitials(username)} - </span> - ); -}; diff --git a/app/client/packages/design-system/widgets/src/components/AIChat/src/UserAvatar/index.ts b/app/client/packages/design-system/widgets/src/components/AIChat/src/UserAvatar/index.ts deleted file mode 100644 index ee08802f33b5..000000000000 --- a/app/client/packages/design-system/widgets/src/components/AIChat/src/UserAvatar/index.ts +++ /dev/null @@ -1,2 +0,0 @@ -export * from "./UserAvatar"; -export * from "./types"; diff --git a/app/client/packages/design-system/widgets/src/components/AIChat/src/UserAvatar/styles.module.css b/app/client/packages/design-system/widgets/src/components/AIChat/src/UserAvatar/styles.module.css deleted file mode 100644 index b11f3896efca..000000000000 --- a/app/client/packages/design-system/widgets/src/components/AIChat/src/UserAvatar/styles.module.css +++ /dev/null @@ -1,13 +0,0 @@ -.root { - display: inline-block; - width: 28px; - min-width: 28px; - height: 28px; - color: var(--bg-elevation-2, #fff); - text-align: center; - font-size: 14px; - font-weight: 500; - line-height: 28px; - border-radius: var(--inner-spacing-1, 4px); - background: #000; -} diff --git a/app/client/packages/design-system/widgets/src/components/AIChat/src/UserAvatar/types.ts b/app/client/packages/design-system/widgets/src/components/AIChat/src/UserAvatar/types.ts deleted file mode 100644 index 493da46824f5..000000000000 --- a/app/client/packages/design-system/widgets/src/components/AIChat/src/UserAvatar/types.ts +++ /dev/null @@ -1,5 +0,0 @@ -import type { HTMLProps } from "react"; - -export interface UserAvatarProps extends HTMLProps<HTMLSpanElement> { - username: string; -} diff --git a/app/client/packages/design-system/widgets/src/components/AIChat/src/styles.module.css b/app/client/packages/design-system/widgets/src/components/AIChat/src/styles.module.css index b1905d1daf5a..ae94ae2d1f91 100644 --- a/app/client/packages/design-system/widgets/src/components/AIChat/src/styles.module.css +++ b/app/client/packages/design-system/widgets/src/components/AIChat/src/styles.module.css @@ -1,9 +1,9 @@ .root { width: 100%; - border-radius: var(--border-radius-elevation-1); - border: 1px solid var(--color-bd-elevation-1); - /* TODO: --bg-elevation-1 doesn't exists. Define it */ - background: var(--bg-elevation-1, #fbfcfd); + background-color: var(--color-bg-elevation-3); + border-radius: var(--border-radius-elevation-3); + outline: var(--border-width-1) solid var(--color-bd-elevation-3); + overflow: hidden; } .header { @@ -13,7 +13,6 @@ padding: var(--inner-spacing-5) var(--inner-spacing-6); align-items: flex-start; border-bottom: 1px solid var(--color-bd-elevation-1); - background: rgba(255, 255, 255, 0.45); } @container (min-width: 700px) { @@ -23,21 +22,3 @@ align-items: center; } } - -.thread { - display: flex; - flex-direction: column; - gap: var(--inner-spacing-3); - align-self: stretch; - padding: 0px var(--inner-spacing-6) var(--inner-spacing-5) - var(--inner-spacing-6); -} - -.promptForm { - display: flex; - align-items: flex-start; - margin: var(--outer-spacing-4) 0 0 0; - padding: 0 var(--inner-spacing-5) var(--inner-spacing-5) - var(--inner-spacing-5); - gap: var(--outer-spacing-3); -} diff --git a/app/client/packages/design-system/widgets/src/components/AIChat/stories/AIChat.stories.tsx b/app/client/packages/design-system/widgets/src/components/AIChat/stories/AIChat.stories.tsx index 6b0abe2853bf..6026959f0a84 100644 --- a/app/client/packages/design-system/widgets/src/components/AIChat/stories/AIChat.stories.tsx +++ b/app/client/packages/design-system/widgets/src/components/AIChat/stories/AIChat.stories.tsx @@ -1,4 +1,6 @@ +import React from "react"; import { AIChat } from "@appsmith/wds"; +import { useState } from "react"; import type { Meta, StoryObj } from "@storybook/react"; const meta: Meta<typeof AIChat> = { @@ -19,6 +21,12 @@ export const Main: Story = { assistantName: "", isWaitingForResponse: false, }, + render: (args) => { + // eslint-disable-next-line react-hooks/rules-of-hooks + const [prompt, setPrompt] = useState(args.prompt); + + return <AIChat {...args} onPromptChange={setPrompt} prompt={prompt} />; + }, }; export const EmptyHistory: Story = { @@ -69,6 +77,21 @@ export const WithHistory: Story = { content: "Thank you", isAssistant: false, }, + { + id: "5", + content: `Here's an example of markdown code: + +\`\`\`javascript +function greet(name) { + console.log(\`Hello, \${name}!\`); +} + +greet('World'); +\`\`\` + +This code defines a function that greets the given name.`, + isAssistant: true, + }, ], prompt: "", username: "John Doe", diff --git a/app/client/packages/design-system/widgets/src/components/AIChat/tests/AIChat.test.tsx b/app/client/packages/design-system/widgets/src/components/AIChat/tests/AIChat.test.tsx deleted file mode 100644 index ce868dd72c7e..000000000000 --- a/app/client/packages/design-system/widgets/src/components/AIChat/tests/AIChat.test.tsx +++ /dev/null @@ -1,113 +0,0 @@ -import React from "react"; -import "@testing-library/jest-dom"; -import { render, screen, within } from "@testing-library/react"; -import { faker } from "@faker-js/faker"; - -import { AIChat, type AIChatProps } from ".."; -import userEvent from "@testing-library/user-event"; - -const renderComponent = (props: Partial<AIChatProps> = {}) => { - const defaultProps: AIChatProps = { - username: "", - thread: [], - prompt: "", - onPromptChange: jest.fn(), - }; - - return render(<AIChat {...defaultProps} {...props} />); -}; - -describe("@appsmith/wds/AIChat", () => { - it("should render chat's title", () => { - const chatTitle = faker.lorem.words(2); - - renderComponent({ chatTitle }); - - expect(screen.getByTestId("t--aichat-chat-title")).toHaveTextContent( - chatTitle, - ); - }); - - it("should render username", () => { - const username = faker.name.firstName(); - - renderComponent({ username }); - - expect(screen.getByTestId("t--aichat-username")).toHaveTextContent( - username, - ); - }); - - it("should render thread", () => { - const thread = [ - { - id: faker.datatype.uuid(), - content: faker.lorem.paragraph(1), - isAssistant: false, - }, - { - id: faker.datatype.uuid(), - content: faker.lorem.paragraph(2), - isAssistant: true, - }, - ]; - - renderComponent({ thread }); - - const messages = within( - screen.getByTestId("t--aichat-thread"), - ).getAllByRole("listitem"); - - expect(messages).toHaveLength(thread.length); - expect(messages[0]).toHaveTextContent(thread[0].content); - expect(messages[1]).toHaveTextContent(thread[1].content); - }); - - it("should render prompt input placeholder", () => { - const promptInputPlaceholder = faker.lorem.words(3); - - renderComponent({ - promptInputPlaceholder, - }); - - expect(screen.getByRole("textbox")).toHaveAttribute( - "placeholder", - promptInputPlaceholder, - ); - }); - - it("should render prompt input value", () => { - const prompt = faker.lorem.words(3); - - renderComponent({ - prompt, - }); - - expect(screen.getByRole("textbox")).toHaveValue(prompt); - }); - - it("should trigger user's prompt", async () => { - const onPromptChange = jest.fn(); - - renderComponent({ - onPromptChange, - }); - - await userEvent.type(screen.getByRole("textbox"), "A"); - - expect(onPromptChange).toHaveBeenCalledWith("A"); - }); - - it("should submit user's prompt", async () => { - const onSubmit = jest.fn(); - - renderComponent({ - prompt: "ABCD", - onSubmit, - }); - - await userEvent.click(screen.getByRole("button", { name: "Send" })); - - expect(onSubmit).toHaveBeenCalled(); - }); -}); diff --git a/app/client/packages/design-system/widgets/src/components/Avatar/index.ts b/app/client/packages/design-system/widgets/src/components/Avatar/index.ts new file mode 100644 index 000000000000..3bd16e178a03 --- /dev/null +++ b/app/client/packages/design-system/widgets/src/components/Avatar/index.ts @@ -0,0 +1 @@ +export * from "./src"; diff --git a/app/client/packages/design-system/widgets/src/components/Avatar/src/Avatar.tsx b/app/client/packages/design-system/widgets/src/components/Avatar/src/Avatar.tsx new file mode 100644 index 000000000000..d6c7dc28ed8c --- /dev/null +++ b/app/client/packages/design-system/widgets/src/components/Avatar/src/Avatar.tsx @@ -0,0 +1,37 @@ +import React from "react"; +import { clsx } from "clsx"; +import { Text } from "@appsmith/wds"; + +import styles from "./styles.module.css"; +import type { AvatarProps } from "./types"; +import { getTypographyClassName } from "@appsmith/wds-theming"; + +export const Avatar = (props: AvatarProps) => { + const { className, label, size, src, ...rest } = props; + + const getLabelInitials = (label: string) => { + const names = label.split(" "); + + if (names.length === 1) { + return `${names[0].charAt(0)}`; + } + + return `${names[0].charAt(0)}${names[1]?.charAt(0)}`; + }; + + return ( + <span + className={clsx(styles.avatar, className)} + {...rest} + data-size={size ? size : undefined} + > + {Boolean(src) ? ( + <img alt={label} className={styles.avatarImage} src={src} /> + ) : ( + <Text className={getTypographyClassName("body")} fontWeight={500}> + {getLabelInitials(label)} + </Text> + )} + </span> + ); +}; diff --git a/app/client/packages/design-system/widgets/src/components/Avatar/src/index.ts b/app/client/packages/design-system/widgets/src/components/Avatar/src/index.ts new file mode 100644 index 000000000000..3a8b659aee76 --- /dev/null +++ b/app/client/packages/design-system/widgets/src/components/Avatar/src/index.ts @@ -0,0 +1,2 @@ +export * from "./types"; +export * from "./Avatar"; diff --git a/app/client/packages/design-system/widgets/src/components/Avatar/src/styles.module.css b/app/client/packages/design-system/widgets/src/components/Avatar/src/styles.module.css new file mode 100644 index 000000000000..f3172cc40392 --- /dev/null +++ b/app/client/packages/design-system/widgets/src/components/Avatar/src/styles.module.css @@ -0,0 +1,31 @@ +.avatar { + display: inline-flex; + align-items: center; + justify-content: center; + width: var(--sizing-8); + height: var(--sizing-8); +} + +.avatar[data-size="small"] { + width: var(--sizing-6); + height: var(--sizing-6); +} + +.avatar[data-size="large"] { + width: var(--sizing-10); + height: var(--sizing-10); +} + +/* if the avatar has div, that means no source is provided. For this case, we want to add a background color and border radius */ +.avatar:has(div) { + background-color: var(--color-bg-assistive); + color: var(--color-fg-on-assistive); + border-radius: var(--border-radius-elevation-3); +} + +.avatarImage { + border-radius: inherit; + height: 100%; + object-fit: contain; + aspect-ratio: 1 / 1; +} diff --git a/app/client/packages/design-system/widgets/src/components/Avatar/src/types.ts b/app/client/packages/design-system/widgets/src/components/Avatar/src/types.ts new file mode 100644 index 000000000000..3731a231d930 --- /dev/null +++ b/app/client/packages/design-system/widgets/src/components/Avatar/src/types.ts @@ -0,0 +1,13 @@ +import type { HTMLProps } from "react"; + +export interface AvatarProps extends Omit<HTMLProps<HTMLSpanElement>, "size"> { + /** The label of the avatar */ + label: string; + /** The image source of the avatar */ + src?: string; + /** The size of the avatar + * + * @default "medium" + */ + size?: "small" | "medium" | "large"; +} diff --git a/app/client/packages/design-system/widgets/src/components/Avatar/stories/Avatar.stories.tsx b/app/client/packages/design-system/widgets/src/components/Avatar/stories/Avatar.stories.tsx new file mode 100644 index 000000000000..10ca22796eab --- /dev/null +++ b/app/client/packages/design-system/widgets/src/components/Avatar/stories/Avatar.stories.tsx @@ -0,0 +1,43 @@ +import React from "react"; +import { Avatar, Flex } from "@appsmith/wds"; +import type { Meta, StoryObj } from "@storybook/react"; + +const meta: Meta<typeof Avatar> = { + title: "WDS/Widgets/Avatar", + component: Avatar, +}; + +export default meta; +type Story = StoryObj<typeof Avatar>; + +export const Default: Story = { + args: { + label: "John Doe", + }, +}; + +export const WithImage: Story = { + args: { + label: "Jane Smith", + src: "https://assets.appsmith.com/integrations/25720743.png", + }, +}; + +export const SingleInitial: Story = { + args: { + label: "Alice", + }, +}; + +export const Sizes: Story = { + args: { + label: "Alice", + }, + render: (args) => ( + <Flex gap="spacing-2"> + <Avatar {...args} size="small" /> + <Avatar {...args} size="medium" /> + <Avatar {...args} size="large" /> + </Flex> + ), +}; diff --git a/app/client/packages/design-system/widgets/src/components/ChatInput/src/ChatInput.tsx b/app/client/packages/design-system/widgets/src/components/ChatInput/src/ChatInput.tsx index 98feb3794d20..0a5db9e2f762 100644 --- a/app/client/packages/design-system/widgets/src/components/ChatInput/src/ChatInput.tsx +++ b/app/client/packages/design-system/widgets/src/components/ChatInput/src/ChatInput.tsx @@ -6,10 +6,10 @@ import { IconButton, TextAreaInput, } from "@appsmith/wds"; -import React, { useCallback, useRef, useEffect, useState } from "react"; import { useControlledState } from "@react-stately/utils"; import { chain, useLayoutEffect } from "@react-aria/utils"; import { TextField as HeadlessTextField } from "react-aria-components"; +import React, { useCallback, useRef, useEffect, useState } from "react"; import type { ChatInputProps } from "./types"; @@ -22,6 +22,7 @@ export function ChatInput(props: ChatInputProps) { isLoading, isReadOnly, isRequired, + isSubmitDisabled, label, onChange, onSubmit, @@ -91,12 +92,14 @@ export function ChatInput(props: ChatInputProps) { const handleKeyDown = useCallback( (event: React.KeyboardEvent<HTMLTextAreaElement>) => { + if (Boolean(isSubmitDisabled)) return; + if (event.key === "Enter" && (event.metaKey || event.ctrlKey)) { event.preventDefault(); onSubmit?.(); } }, - [onSubmit], + [onSubmit, isSubmitDisabled], ); useLayoutEffect(() => { @@ -112,14 +115,18 @@ export function ChatInput(props: ChatInputProps) { return ( <IconButton icon="player-stop-filled" - isDisabled={isDisabled} + isDisabled={Boolean(isDisabled) || Boolean(isSubmitDisabled)} onPress={onSubmit} /> ); } return ( - <IconButton icon="arrow-up" isDisabled={isDisabled} onPress={onSubmit} /> + <IconButton + icon="arrow-up" + isDisabled={Boolean(isDisabled) || Boolean(isSubmitDisabled)} + onPress={onSubmit} + /> ); })(); diff --git a/app/client/packages/design-system/widgets/src/components/ChatInput/src/types.ts b/app/client/packages/design-system/widgets/src/components/ChatInput/src/types.ts index 936fc5bbf213..649c6e8edc50 100644 --- a/app/client/packages/design-system/widgets/src/components/ChatInput/src/types.ts +++ b/app/client/packages/design-system/widgets/src/components/ChatInput/src/types.ts @@ -1,5 +1,8 @@ import type { TextAreaProps } from "@appsmith/wds"; export interface ChatInputProps extends TextAreaProps { + /** callback function when the user submits the chat input */ onSubmit?: () => void; + /** flag for disable the submit button */ + isSubmitDisabled?: boolean; } diff --git a/app/client/packages/design-system/widgets/src/components/ChatInput/stories/ChatInput.stories.tsx b/app/client/packages/design-system/widgets/src/components/ChatInput/stories/ChatInput.stories.tsx index 634451082af0..3ac580744e65 100644 --- a/app/client/packages/design-system/widgets/src/components/ChatInput/stories/ChatInput.stories.tsx +++ b/app/client/packages/design-system/widgets/src/components/ChatInput/stories/ChatInput.stories.tsx @@ -66,3 +66,9 @@ export const Validation: Story = { </Form> ), }; + +export const SubmitDisabled: Story = { + args: { + isSubmitDisabled: true, + }, +}; diff --git a/app/client/packages/design-system/widgets/src/components/Link/src/index.ts b/app/client/packages/design-system/widgets/src/components/Link/src/index.ts index 3b40a46d8b6b..f5a666c42dc2 100644 --- a/app/client/packages/design-system/widgets/src/components/Link/src/index.ts +++ b/app/client/packages/design-system/widgets/src/components/Link/src/index.ts @@ -1 +1,2 @@ export * from "./Link"; +export { default as linkStyles } from "./styles.module.css"; diff --git a/app/client/packages/design-system/widgets/src/components/Link/stories/Link.stories.tsx b/app/client/packages/design-system/widgets/src/components/Link/stories/Link.stories.tsx index 11c72b849080..48a4be562673 100644 --- a/app/client/packages/design-system/widgets/src/components/Link/stories/Link.stories.tsx +++ b/app/client/packages/design-system/widgets/src/components/Link/stories/Link.stories.tsx @@ -21,7 +21,7 @@ export const Main: Story = { args: { target: "_blank", href: "https://appsmith.com", - children: "This is a link.", + children: "Appsmith.", }, }; diff --git a/app/client/packages/design-system/widgets/src/components/Markdown/index.ts b/app/client/packages/design-system/widgets/src/components/Markdown/index.ts new file mode 100644 index 000000000000..3bd16e178a03 --- /dev/null +++ b/app/client/packages/design-system/widgets/src/components/Markdown/index.ts @@ -0,0 +1 @@ +export * from "./src"; diff --git a/app/client/packages/design-system/widgets/src/components/Markdown/src/Markdown.tsx b/app/client/packages/design-system/widgets/src/components/Markdown/src/Markdown.tsx new file mode 100644 index 000000000000..fa9b7710c188 --- /dev/null +++ b/app/client/packages/design-system/widgets/src/components/Markdown/src/Markdown.tsx @@ -0,0 +1,32 @@ +import React from "react"; +import { clsx } from "clsx"; +import remarkGfm from "remark-gfm"; +import ReactMarkdown from "react-markdown"; +import { getTypographyClassName } from "@appsmith/wds-theming"; + +import styles from "./styles.module.css"; +import { components } from "./components"; +import type { MarkdownProps } from "./types"; + +export const Markdown = (props: MarkdownProps) => { + const { children, className, options, ...rest } = props; + + return ( + <div + className={clsx( + styles.markdown, + getTypographyClassName("body"), + className, + )} + {...rest} + > + <ReactMarkdown + components={components} + remarkPlugins={[remarkGfm]} + {...options} + > + {children} + </ReactMarkdown> + </div> + ); +}; diff --git a/app/client/packages/design-system/widgets/src/components/Markdown/src/components.tsx b/app/client/packages/design-system/widgets/src/components/Markdown/src/components.tsx new file mode 100644 index 000000000000..14c014fe1c0a --- /dev/null +++ b/app/client/packages/design-system/widgets/src/components/Markdown/src/components.tsx @@ -0,0 +1,22 @@ +import type { Components } from "react-markdown"; + +import { a } from "./mdComponents/Link"; +import { code } from "./mdComponents/Code"; +import { p } from "./mdComponents/Paragraph"; +import { ul, ol, li } from "./mdComponents/List"; +import { h1, h2, h3, h4, h5, h6 } from "./mdComponents/Heading"; + +export const components: Components = { + a, + h1, + h2, + h3, + h4, + h5, + h6, + p, + ul, + ol, + li, + code, +}; diff --git a/app/client/packages/design-system/widgets/src/components/Markdown/src/index.ts b/app/client/packages/design-system/widgets/src/components/Markdown/src/index.ts new file mode 100644 index 000000000000..e58086caabf3 --- /dev/null +++ b/app/client/packages/design-system/widgets/src/components/Markdown/src/index.ts @@ -0,0 +1,2 @@ +export * from "./types"; +export * from "./Markdown"; diff --git a/app/client/packages/design-system/widgets/src/components/Markdown/src/mdComponents/Code.tsx b/app/client/packages/design-system/widgets/src/components/Markdown/src/mdComponents/Code.tsx new file mode 100644 index 000000000000..b5683b1e4164 --- /dev/null +++ b/app/client/packages/design-system/widgets/src/components/Markdown/src/mdComponents/Code.tsx @@ -0,0 +1,59 @@ +import { Button, Flex, Text } from "@appsmith/wds"; +import type { ExtraProps } from "react-markdown"; +import React, { useState, useCallback } from "react"; +import { useThemeContext } from "@appsmith/wds-theming"; +import { + atomOneDark as darkTheme, + atomOneLight as lightTheme, +} from "react-syntax-highlighter/dist/cjs/styles/hljs"; +import SyntaxHighlighter from "react-syntax-highlighter"; + +type CodeProps = React.ClassAttributes<HTMLElement> & + React.HTMLAttributes<HTMLElement> & + ExtraProps; + +export const Code = (props: CodeProps) => { + const { children, className, ...rest } = props; + const match = /language-(\w+)/.exec(className ?? ""); + const theme = useThemeContext(); + const [copied, setCopied] = useState(false); + + const handleCopy = useCallback(() => { + navigator.clipboard.writeText(String(children)).then(() => { + setCopied(true); + setTimeout(() => setCopied(false), 2000); + }); + }, [children]); + + return match ? ( + <div data-component="code"> + <Flex + alignItems="center" + justifyContent="space-between" + padding="spacing-1" + > + <Text size="caption">{match[1]}</Text> + <Button icon="copy" onPress={handleCopy} size="small" variant="ghost"> + {copied ? "Copied!" : "Copy"} + </Button> + </Flex> + <SyntaxHighlighter + PreTag="div" + customStyle={{ + backgroundColor: "var(--color-bg-neutral-subtle)", + }} + language={match[1]} + style={theme.colorMode === "dark" ? darkTheme : lightTheme} + useInlineStyles + > + {String(children).replace(/\n$/, "")} + </SyntaxHighlighter> + </div> + ) : ( + <code {...rest} className={className}> + {children} + </code> + ); +}; + +export { Code as code }; diff --git a/app/client/packages/design-system/widgets/src/components/Markdown/src/mdComponents/Heading.tsx b/app/client/packages/design-system/widgets/src/components/Markdown/src/mdComponents/Heading.tsx new file mode 100644 index 000000000000..6f439aa2aca8 --- /dev/null +++ b/app/client/packages/design-system/widgets/src/components/Markdown/src/mdComponents/Heading.tsx @@ -0,0 +1,37 @@ +import React from "react"; +import type { Ref } from "react"; +import type { ExtraProps } from "react-markdown"; +import { Text, type TextProps } from "@appsmith/wds"; + +type HeadingProps = React.ClassAttributes<HTMLDivElement> & + React.HTMLAttributes<HTMLDivElement> & + ExtraProps; + +const createHeading = ( + size: TextProps["size"], + level: 1 | 2 | 3 | 4 | 5 | 6, + fontWeight: TextProps["fontWeight"] = 700, +) => { + const HeadingComponent = ({ children, ref }: HeadingProps) => ( + <Text + color="neutral" + data-component={`h${level}`} + fontWeight={fontWeight} + ref={ref as Ref<HTMLDivElement>} + size={size} + > + {children} + </Text> + ); + + HeadingComponent.displayName = `Heading${level}`; + + return HeadingComponent; +}; + +export const h1 = createHeading("heading", 1); +export const h2 = createHeading("title", 2); +export const h3 = createHeading("subtitle", 3); +export const h4 = createHeading("body", 4); +export const h5 = createHeading("body", 5, 500); +export const h6 = createHeading("body", 6, 300); diff --git a/app/client/packages/design-system/widgets/src/components/Markdown/src/mdComponents/Link.tsx b/app/client/packages/design-system/widgets/src/components/Markdown/src/mdComponents/Link.tsx new file mode 100644 index 000000000000..29582c3a0cde --- /dev/null +++ b/app/client/packages/design-system/widgets/src/components/Markdown/src/mdComponents/Link.tsx @@ -0,0 +1,17 @@ +import React from "react"; +import { Link } from "@appsmith/wds"; +import type { ExtraProps } from "react-markdown"; + +type LinkProps = React.ClassAttributes<HTMLAnchorElement> & + React.AnchorHTMLAttributes<HTMLAnchorElement> & + ExtraProps; + +export const a = (props: LinkProps) => { + const { children, href } = props; + + return ( + <Link data-component="a" href={href} rel="noreferrer" target="_blank"> + {children} + </Link> + ); +}; diff --git a/app/client/packages/design-system/widgets/src/components/Markdown/src/mdComponents/List.tsx b/app/client/packages/design-system/widgets/src/components/Markdown/src/mdComponents/List.tsx new file mode 100644 index 000000000000..aeaab257c800 --- /dev/null +++ b/app/client/packages/design-system/widgets/src/components/Markdown/src/mdComponents/List.tsx @@ -0,0 +1,28 @@ +import React from "react"; +import type { ExtraProps } from "react-markdown"; + +type ULProps = React.ClassAttributes<HTMLUListElement> & + React.HTMLAttributes<HTMLUListElement> & + ExtraProps; + +export const ul = (props: ULProps) => { + const { children } = props; + + return <ul data-component="ul">{children}</ul>; +}; + +type LIProps = React.ClassAttributes<HTMLLIElement> & + React.HTMLAttributes<HTMLLIElement> & + ExtraProps; + +export const li = (props: LIProps) => { + const { children } = props; + + return <li>{children}</li>; +}; + +export const ol = (props: ULProps) => { + const { children } = props; + + return <ol data-component="ol">{children}</ol>; +}; diff --git a/app/client/packages/design-system/widgets/src/components/Markdown/src/mdComponents/Paragraph.tsx b/app/client/packages/design-system/widgets/src/components/Markdown/src/mdComponents/Paragraph.tsx new file mode 100644 index 000000000000..8d0e6bdf7287 --- /dev/null +++ b/app/client/packages/design-system/widgets/src/components/Markdown/src/mdComponents/Paragraph.tsx @@ -0,0 +1,22 @@ +import React, { type Ref } from "react"; +import { Text } from "@appsmith/wds"; +import type { ExtraProps } from "react-markdown"; + +type ParagraphProps = React.ClassAttributes<HTMLDivElement> & + React.HTMLAttributes<HTMLDivElement> & + ExtraProps; + +export const p = (props: ParagraphProps) => { + const { children, ref } = props; + + return ( + <Text + color="neutral" + data-component="p" + ref={ref as Ref<HTMLDivElement>} + size="body" + > + {children} + </Text> + ); +}; diff --git a/app/client/packages/design-system/widgets/src/components/Markdown/src/styles.module.css b/app/client/packages/design-system/widgets/src/components/Markdown/src/styles.module.css new file mode 100644 index 000000000000..658ef72f265f --- /dev/null +++ b/app/client/packages/design-system/widgets/src/components/Markdown/src/styles.module.css @@ -0,0 +1,118 @@ +.markdown { + color: var(--color-fg); + + &::after, + &::before { + /* This is required to remove the compensators of capsizing that comes up due to use of `wds-body-text` class */ + content: none !important; + } + + table { + border: var(--border-width-1) solid var(--color-bd); + border-collapse: separate; + border-radius: var(--border-radius-elevation-3); + border-spacing: 0px; + overflow: hidden; + } + + tr { + display: table-row; + vertical-align: inherit; + border-color: inherit; + } + + th, + td { + padding: var(--inner-spacing-1) var(--inner-spacing-2); + text-align: left; + vertical-align: top; + border-bottom: var(--border-width-1) solid var(--color-bd); + border-right: var(--border-width-1) solid var(--color-bd); + } + + :is(td, th):last-child { + border-right: none; + } + + th { + background-color: var(--color-bg-neutral-subtle); + } + + thead:last-child tr:last-child th, + tbody:last-child tr:last-child td { + border-bottom: none; + } + + /* Headings */ + [data-component="h1"] { + margin-top: var(--inner-spacing-7); + margin-bottom: var(--inner-spacing-4); + } + + [data-component="h2"] { + margin-top: var(--inner-spacing-6); + margin-bottom: var(--inner-spacing-3); + } + + [data-component="h3"] { + margin-top: var(--inner-spacing-5); + margin-bottom: var(--inner-spacing-3); + } + + [data-component="h4"] { + margin-top: var(--inner-spacing-4); + margin-bottom: var(--inner-spacing-2); + } + + [data-component="h5"] { + margin-top: var(--inner-spacing-3); + margin-bottom: var(--inner-spacing-2); + } + + [data-component="h6"] { + margin-top: var(--inner-spacing-2); + margin-bottom: var(--inner-spacing-1); + } + + [data-component="p"] { + margin-bottom: var(--inner-spacing-4); + } + + /* Lists */ + :is(ul, ol) { + margin-top: var(--inner-spacing-2); + margin-bottom: var(--inner-spacing-4); + padding-left: 0; + } + + li { + margin-bottom: var(--inner-spacing-2); + margin-left: 1em; + position: relative; + } + + [data-component="a"]:before, + [data-component="a"]:after { + content: none; + } + + [data-component="code"] { + background-color: var(--color-bg-elevation-2); + border-radius: var(--border-radius-elevation-3); + outline: var(--border-width-1) solid var(--color-bg-neutral-subtle); + margin-bottom: var(--spacing-2); + overflow: auto; + } + + pre { + margin-top: var(--inner-spacing-4); + margin-bottom: var(--inner-spacing-4); + } + + blockquote { + padding-left: var(--inner-spacing-3); + padding-right: var(--inner-spacing-3); + margin-left: 0; + border-left: var(--border-width-2) solid var(--color-bd-neutral); + } +} diff --git a/app/client/packages/design-system/widgets/src/components/Markdown/src/types.ts b/app/client/packages/design-system/widgets/src/components/Markdown/src/types.ts new file mode 100644 index 000000000000..ae16bf203b76 --- /dev/null +++ b/app/client/packages/design-system/widgets/src/components/Markdown/src/types.ts @@ -0,0 +1,10 @@ +import type { Options } from "react-markdown"; + +export interface MarkdownProps { + /** The markdown content to render */ + children: string; + /** Options for react-markdown */ + options?: Options; + /** Additional CSS classes to apply to the component */ + className?: string; +} diff --git a/app/client/packages/design-system/widgets/src/components/Markdown/stories/Markdown.stories.ts b/app/client/packages/design-system/widgets/src/components/Markdown/stories/Markdown.stories.ts new file mode 100644 index 000000000000..08eec4fe8bba --- /dev/null +++ b/app/client/packages/design-system/widgets/src/components/Markdown/stories/Markdown.stories.ts @@ -0,0 +1,62 @@ +import { Markdown } from "@appsmith/wds"; +import type { Meta, StoryObj } from "@storybook/react"; + +const meta: Meta<typeof Markdown> = { + title: "WDS/Widgets/Markdown", + component: Markdown, +}; + +export default meta; +type Story = StoryObj<typeof Markdown>; + +export const Default: Story = { + args: { + children: `# Hello, Markdown! + +This is a paragraph with **bold** and *italic* text. + +## Code Example + +\`\`\`javascript +const greeting = "Hello, World!"; +console.log(greeting); +\`\`\` + +- List item 1 +- List item 2 +- List item 3 + - List item 3.1 + - List item 3.2 + - List item 3.3 + - List item 3.3.1 + - List item 3.3.2 + +1. List item 1 +2. List item 2 +3. List item 3 + +[Visit Appsmith](https://www.appsmith.com) + +# Heading 1 +## Heading 2 +### Heading 3 +#### Heading 4 +##### Heading 5 +###### Heading 6 + +## Table Example + +| Column 1 | Column 2 | Column 3 | +|----------|----------|----------| +| Row 1, Cell 1 | Row 1, Cell 2 | Row 1, Cell 3 | +| Row 2, Cell 1 | Row 2, Cell 2 | Row 2, Cell 3 | +| Row 3, Cell 1 | Row 3, Cell 2 | Row 3, Cell 3 | + +## Blockquote Example + +> This is a blockquote. +> +> It can span multiple lines. +`, + }, +}; diff --git a/app/client/packages/design-system/widgets/src/components/Text/src/Text.tsx b/app/client/packages/design-system/widgets/src/components/Text/src/Text.tsx index 03ebdd7d710d..b3366bf915bc 100644 --- a/app/client/packages/design-system/widgets/src/components/Text/src/Text.tsx +++ b/app/client/packages/design-system/widgets/src/components/Text/src/Text.tsx @@ -9,7 +9,7 @@ import React, { forwardRef } from "react"; import type { TextProps } from "./types"; import styles from "./styles.module.css"; -const _Text = (props: TextProps, ref: Ref<HTMLParagraphElement>) => { +const _Text = (props: TextProps, ref: Ref<HTMLDivElement>) => { const { children, className, diff --git a/app/client/packages/design-system/widgets/src/index.ts b/app/client/packages/design-system/widgets/src/index.ts index c07b2455ab93..b37081c4ecde 100644 --- a/app/client/packages/design-system/widgets/src/index.ts +++ b/app/client/packages/design-system/widgets/src/index.ts @@ -31,6 +31,8 @@ export * from "./components/ListBox"; export * from "./components/ListBoxItem"; export * from "./components/MenuItem"; export * from "./components/ChatInput"; +export * from "./components/Avatar"; +export * from "./components/Markdown"; export * from "./utils"; export * from "./hooks"; diff --git a/app/client/packages/storybook/.storybook/preview-head.html b/app/client/packages/storybook/.storybook/preview-head.html index b0d63966ee2f..b42be270e259 100644 --- a/app/client/packages/storybook/.storybook/preview-head.html +++ b/app/client/packages/storybook/.storybook/preview-head.html @@ -21,7 +21,7 @@ background-color: var(--color-bg-elevation-1) !important; } - code, + code:not(:has(span)), .css-o1d7ko { background-color: var(--color-bg-accent-subtle) !important; color: var(--color-fg-on-accent-subtle) !important; diff --git a/app/client/test/__mocks__/reactMarkdown.tsx b/app/client/test/__mocks__/reactMarkdown.tsx index 91ddc2033132..65a0c9176006 100644 --- a/app/client/test/__mocks__/reactMarkdown.tsx +++ b/app/client/test/__mocks__/reactMarkdown.tsx @@ -3,3 +3,6 @@ import React from "react"; jest.mock("react-markdown", () => (props: { children: unknown }) => { return <>{props.children}</>; }); + +jest.mock("remark-gfm", () => () => { +}) \ No newline at end of file diff --git a/app/client/yarn.lock b/app/client/yarn.lock index c97f664a5bc3..27f65e502630 100644 --- a/app/client/yarn.lock +++ b/app/client/yarn.lock @@ -257,6 +257,7 @@ __metadata: react-aria-components: ^1.2.1 react-markdown: ^9.0.1 react-syntax-highlighter: ^15.5.0 + remark-gfm: ^4.0.0 peerDependencies: react: ^16.8.0 || ^17.0.0-rc.1 || ^18.0.0 languageName: unknown @@ -17791,6 +17792,13 @@ __metadata: languageName: node linkType: hard +"escape-string-regexp@npm:^5.0.0": + version: 5.0.0 + resolution: "escape-string-regexp@npm:5.0.0" + checksum: 20daabe197f3cb198ec28546deebcf24b3dbb1a5a269184381b3116d12f0532e06007f4bc8da25669d6a7f8efb68db0758df4cd981f57bc5b57f521a3e12c59e + languageName: node + linkType: hard + "escodegen@npm:^2.0.0, escodegen@npm:^2.1.0": version: 2.1.0 resolution: "escodegen@npm:2.1.0" @@ -23933,6 +23941,13 @@ __metadata: languageName: node linkType: hard +"markdown-table@npm:^3.0.0": + version: 3.0.3 + resolution: "markdown-table@npm:3.0.3" + checksum: 8fcd3d9018311120fbb97115987f8b1665a603f3134c93fbecc5d1463380c8036f789e2a62c19432058829e594fff8db9ff81c88f83690b2f8ed6c074f8d9e10 + languageName: node + linkType: hard + "markdown-to-jsx@npm:^7.4.5": version: 7.4.7 resolution: "markdown-to-jsx@npm:7.4.7" @@ -23969,6 +23984,18 @@ __metadata: languageName: node linkType: hard +"mdast-util-find-and-replace@npm:^3.0.0": + version: 3.0.1 + resolution: "mdast-util-find-and-replace@npm:3.0.1" + dependencies: + "@types/mdast": ^4.0.0 + escape-string-regexp: ^5.0.0 + unist-util-is: ^6.0.0 + unist-util-visit-parents: ^6.0.0 + checksum: 05d5c4ff02e31db2f8a685a13bcb6c3f44e040bd9dfa54c19a232af8de5268334c8755d79cb456ed4cced1300c4fb83e88444c7ae8ee9ff16869a580f29d08cd + languageName: node + linkType: hard + "mdast-util-from-markdown@npm:^2.0.0": version: 2.0.1 resolution: "mdast-util-from-markdown@npm:2.0.1" @@ -23989,6 +24016,83 @@ __metadata: languageName: node linkType: hard +"mdast-util-gfm-autolink-literal@npm:^2.0.0": + version: 2.0.1 + resolution: "mdast-util-gfm-autolink-literal@npm:2.0.1" + dependencies: + "@types/mdast": ^4.0.0 + ccount: ^2.0.0 + devlop: ^1.0.0 + mdast-util-find-and-replace: ^3.0.0 + micromark-util-character: ^2.0.0 + checksum: 5630b12e072d7004cb132231c94f667fb5813486779cb0dfb0a196d7ae0e048897a43b0b37e080017adda618ddfcbea1d7bf23c0fa31c87bfc683e0898ea1cfe + languageName: node + linkType: hard + +"mdast-util-gfm-footnote@npm:^2.0.0": + version: 2.0.0 + resolution: "mdast-util-gfm-footnote@npm:2.0.0" + dependencies: + "@types/mdast": ^4.0.0 + devlop: ^1.1.0 + mdast-util-from-markdown: ^2.0.0 + mdast-util-to-markdown: ^2.0.0 + micromark-util-normalize-identifier: ^2.0.0 + checksum: 45d26b40e7a093712e023105791129d76e164e2168d5268e113298a22de30c018162683fb7893cdc04ab246dac0087eed708b2a136d1d18ed2b32b3e0cae4a79 + languageName: node + linkType: hard + +"mdast-util-gfm-strikethrough@npm:^2.0.0": + version: 2.0.0 + resolution: "mdast-util-gfm-strikethrough@npm:2.0.0" + dependencies: + "@types/mdast": ^4.0.0 + mdast-util-from-markdown: ^2.0.0 + mdast-util-to-markdown: ^2.0.0 + checksum: fe9b1d0eba9b791ff9001c008744eafe3dd7a81b085f2bf521595ce4a8e8b1b44764ad9361761ad4533af3e5d913d8ad053abec38172031d9ee32a8ebd1c7dbd + languageName: node + linkType: hard + +"mdast-util-gfm-table@npm:^2.0.0": + version: 2.0.0 + resolution: "mdast-util-gfm-table@npm:2.0.0" + dependencies: + "@types/mdast": ^4.0.0 + devlop: ^1.0.0 + markdown-table: ^3.0.0 + mdast-util-from-markdown: ^2.0.0 + mdast-util-to-markdown: ^2.0.0 + checksum: 063a627fd0993548fd63ca0c24c437baf91ba7d51d0a38820bd459bc20bf3d13d7365ef8d28dca99176dd5eb26058f7dde51190479c186dfe6af2e11202957c9 + languageName: node + linkType: hard + +"mdast-util-gfm-task-list-item@npm:^2.0.0": + version: 2.0.0 + resolution: "mdast-util-gfm-task-list-item@npm:2.0.0" + dependencies: + "@types/mdast": ^4.0.0 + devlop: ^1.0.0 + mdast-util-from-markdown: ^2.0.0 + mdast-util-to-markdown: ^2.0.0 + checksum: 37db90c59b15330fc54d790404abf5ef9f2f83e8961c53666fe7de4aab8dd5e6b3c296b6be19797456711a89a27840291d8871ff0438e9b4e15c89d170efe072 + languageName: node + linkType: hard + +"mdast-util-gfm@npm:^3.0.0": + version: 3.0.0 + resolution: "mdast-util-gfm@npm:3.0.0" + dependencies: + mdast-util-from-markdown: ^2.0.0 + mdast-util-gfm-autolink-literal: ^2.0.0 + mdast-util-gfm-footnote: ^2.0.0 + mdast-util-gfm-strikethrough: ^2.0.0 + mdast-util-gfm-table: ^2.0.0 + mdast-util-gfm-task-list-item: ^2.0.0 + mdast-util-to-markdown: ^2.0.0 + checksum: 62039d2f682ae3821ea1c999454863d31faf94d67eb9b746589c7e136076d7fb35fabc67e02f025c7c26fd7919331a0ee1aabfae24f565d9a6a9ebab3371c626 + languageName: node + linkType: hard + "mdast-util-mdx-expression@npm:^2.0.0": version: 2.0.1 resolution: "mdast-util-mdx-expression@npm:2.0.1" @@ -24232,6 +24336,99 @@ __metadata: languageName: node linkType: hard +"micromark-extension-gfm-autolink-literal@npm:^2.0.0": + version: 2.1.0 + resolution: "micromark-extension-gfm-autolink-literal@npm:2.1.0" + dependencies: + micromark-util-character: ^2.0.0 + micromark-util-sanitize-uri: ^2.0.0 + micromark-util-symbol: ^2.0.0 + micromark-util-types: ^2.0.0 + checksum: e00a570c70c837b9cbbe94b2c23b787f44e781cd19b72f1828e3453abca2a9fb600fa539cdc75229fa3919db384491063645086e02249481e6ff3ec2c18f767c + languageName: node + linkType: hard + +"micromark-extension-gfm-footnote@npm:^2.0.0": + version: 2.1.0 + resolution: "micromark-extension-gfm-footnote@npm:2.1.0" + dependencies: + devlop: ^1.0.0 + micromark-core-commonmark: ^2.0.0 + micromark-factory-space: ^2.0.0 + micromark-util-character: ^2.0.0 + micromark-util-normalize-identifier: ^2.0.0 + micromark-util-sanitize-uri: ^2.0.0 + micromark-util-symbol: ^2.0.0 + micromark-util-types: ^2.0.0 + checksum: ac6fb039e98395d37b71ebff7c7a249aef52678b5cf554c89c4f716111d4be62ef99a5d715a5bd5d68fa549778c977d85cb671d1d8506dc8a3a1b46e867ae52f + languageName: node + linkType: hard + +"micromark-extension-gfm-strikethrough@npm:^2.0.0": + version: 2.1.0 + resolution: "micromark-extension-gfm-strikethrough@npm:2.1.0" + dependencies: + devlop: ^1.0.0 + micromark-util-chunked: ^2.0.0 + micromark-util-classify-character: ^2.0.0 + micromark-util-resolve-all: ^2.0.0 + micromark-util-symbol: ^2.0.0 + micromark-util-types: ^2.0.0 + checksum: cdb7a38dd6eefb6ceb6792a44a6796b10f951e8e3e45b8579f599f43e7ae26ccd048c0aa7e441b3c29dd0c54656944fe6eb0098de2bc4b5106fbc0a42e9e016c + languageName: node + linkType: hard + +"micromark-extension-gfm-table@npm:^2.0.0": + version: 2.1.0 + resolution: "micromark-extension-gfm-table@npm:2.1.0" + dependencies: + devlop: ^1.0.0 + micromark-factory-space: ^2.0.0 + micromark-util-character: ^2.0.0 + micromark-util-symbol: ^2.0.0 + micromark-util-types: ^2.0.0 + checksum: 249d695f5f8bd222a0d8a774ec78ea2a2d624cb50a4d008092a54aa87dad1f9d540e151d29696cf849eb1cee380113c4df722aebb3b425a214832a2de5dea1d7 + languageName: node + linkType: hard + +"micromark-extension-gfm-tagfilter@npm:^2.0.0": + version: 2.0.0 + resolution: "micromark-extension-gfm-tagfilter@npm:2.0.0" + dependencies: + micromark-util-types: ^2.0.0 + checksum: cf21552f4a63592bfd6c96ae5d64a5f22bda4e77814e3f0501bfe80e7a49378ad140f827007f36044666f176b3a0d5fea7c2e8e7973ce4b4579b77789f01ae95 + languageName: node + linkType: hard + +"micromark-extension-gfm-task-list-item@npm:^2.0.0": + version: 2.1.0 + resolution: "micromark-extension-gfm-task-list-item@npm:2.1.0" + dependencies: + devlop: ^1.0.0 + micromark-factory-space: ^2.0.0 + micromark-util-character: ^2.0.0 + micromark-util-symbol: ^2.0.0 + micromark-util-types: ^2.0.0 + checksum: b1ad86a4e9d68d9ad536d94fb25a5182acbc85cc79318f4a6316034342f6a71d67983cc13f12911d0290fd09b2bda43cdabe8781a2d9cca2ebe0d421e8b2b8a4 + languageName: node + linkType: hard + +"micromark-extension-gfm@npm:^3.0.0": + version: 3.0.0 + resolution: "micromark-extension-gfm@npm:3.0.0" + dependencies: + micromark-extension-gfm-autolink-literal: ^2.0.0 + micromark-extension-gfm-footnote: ^2.0.0 + micromark-extension-gfm-strikethrough: ^2.0.0 + micromark-extension-gfm-table: ^2.0.0 + micromark-extension-gfm-tagfilter: ^2.0.0 + micromark-extension-gfm-task-list-item: ^2.0.0 + micromark-util-combine-extensions: ^2.0.0 + micromark-util-types: ^2.0.0 + checksum: 2060fa62666a09532d6b3a272d413bc1b25bbb262f921d7402795ac021e1362c8913727e33d7528d5b4ccaf26922ec51208c43f795a702964817bc986de886c9 + languageName: node + linkType: hard + "micromark-factory-destination@npm:^2.0.0": version: 2.0.0 resolution: "micromark-factory-destination@npm:2.0.0" @@ -29372,6 +29569,20 @@ __metadata: languageName: node linkType: hard +"remark-gfm@npm:^4.0.0": + version: 4.0.0 + resolution: "remark-gfm@npm:4.0.0" + dependencies: + "@types/mdast": ^4.0.0 + mdast-util-gfm: ^3.0.0 + micromark-extension-gfm: ^3.0.0 + remark-parse: ^11.0.0 + remark-stringify: ^11.0.0 + unified: ^11.0.0 + checksum: 84bea84e388061fbbb697b4b666089f5c328aa04d19dc544c229b607446bc10902e46b67b9594415a1017bbbd7c811c1f0c30d36682c6d1a6718b66a1558261b + languageName: node + linkType: hard + "remark-parse@npm:^11.0.0": version: 11.0.0 resolution: "remark-parse@npm:11.0.0" @@ -29397,6 +29608,17 @@ __metadata: languageName: node linkType: hard +"remark-stringify@npm:^11.0.0": + version: 11.0.0 + resolution: "remark-stringify@npm:11.0.0" + dependencies: + "@types/mdast": ^4.0.0 + mdast-util-to-markdown: ^2.0.0 + unified: ^11.0.0 + checksum: 59e07460eb629d6c3b3c0f438b0b236e7e6858fd5ab770303078f5a556ec00354d9c7fb9ef6d5f745a4617ac7da1ab618b170fbb4dac120e183fecd9cc86bce6 + languageName: node + linkType: hard + "remixicon-react@npm:^1.0.0": version: 1.0.0 resolution: "remixicon-react@npm:1.0.0"
7626d75ccf1e667dac4e850059ae4227d38fc3cf
2022-04-12 15:32:02
Rishabh Rathod
fix: remove "Error when determining async func" (#12683)
false
remove "Error when determining async func" (#12683)
fix
diff --git a/app/client/src/workers/DataTreeEvaluator.ts b/app/client/src/workers/DataTreeEvaluator.ts index a849900254d7..362f7ee7541e 100644 --- a/app/client/src/workers/DataTreeEvaluator.ts +++ b/app/client/src/workers/DataTreeEvaluator.ts @@ -95,7 +95,7 @@ export default class DataTreeEvaluator { errors: EvalError[] = []; resolvedFunctions: Record<string, any> = {}; currentJSCollectionState: Record<string, any> = {}; - logs: any[] = []; + logs: unknown[] = []; allActionValidationConfig?: { [actionId: string]: ActionValidationConfigMap }; public hasCyclicalDependency = false; constructor( @@ -1076,6 +1076,7 @@ export default class DataTreeEvaluator { action.value, unEvalDataTree, this.resolvedFunctions, + this.logs, ), }; }); diff --git a/app/client/src/workers/evaluate.ts b/app/client/src/workers/evaluate.ts index 9536eed56f29..ffc6418d5e60 100644 --- a/app/client/src/workers/evaluate.ts +++ b/app/client/src/workers/evaluate.ts @@ -354,6 +354,7 @@ export function isFunctionAsync( userFunction: unknown, dataTree: DataTree, resolvedFunctions: Record<string, any>, + logs: unknown[] = [], ) { return (function() { /**** Setting the eval context ****/ @@ -415,7 +416,9 @@ export function isFunctionAsync( } } } catch (e) { - console.error("Error when determining async function", e); + // We do not want to throw errors for internal operations, to users. + // logLevel should help us in debugging this. + logs.push({ error: "Error when determining async function" + e }); } const isAsync = !!self.IS_ASYNC; for (const entity in GLOBAL_DATA) {
5ec2ff15b6842f7704274fe3e45904464b1cc226
2024-11-19 13:25:44
Ayush Pahwa
chore: update logic to calculate length of lint (#36548)
false
update logic to calculate length of lint (#36548)
chore
diff --git a/app/client/src/components/editorComponents/CodeEditor/lintHelpers.test.ts b/app/client/src/components/editorComponents/CodeEditor/lintHelpers.test.ts index 07c0dc443c9c..381429411c13 100644 --- a/app/client/src/components/editorComponents/CodeEditor/lintHelpers.test.ts +++ b/app/client/src/components/editorComponents/CodeEditor/lintHelpers.test.ts @@ -258,6 +258,57 @@ describe("getLintAnnotations()", () => { }, ]); }); + + it("should use provided lintlength when available", () => { + const value = `{{ variable }}`; + const errors: LintError[] = [ + { + errorType: PropertyEvaluationErrorType.LINT, + raw: "variable", + severity: Severity.WARNING, + errorMessage: { + name: "LintingError", + message: "Lint error message.", + }, + errorSegment: "variable", + originalBinding: "variable", + variables: ["variable"], + code: "W001", + line: 0, + ch: 3, + lintLength: 8, // Provided lint length + }, + ]; + + const annotations = getLintAnnotations(value, errors, {}); + + expect(annotations[0].to?.ch).toBe(13); + }); + + it("should calculate lintlength when not provided", () => { + const value = `{{ variable }}`; + const errors: LintError[] = [ + { + errorType: PropertyEvaluationErrorType.LINT, + raw: "variable", + severity: Severity.WARNING, + errorMessage: { + name: "LintingError", + message: "Lint error message.", + }, + errorSegment: "variable", + originalBinding: "variable", + variables: ["variable"], + code: "W001", + line: 0, + ch: 3, + }, + ]; + + const annotations = getLintAnnotations(value, errors, {}); + + expect(annotations[0].to?.ch).toBe(13); + }); }); describe("getFirstNonEmptyPosition", () => { diff --git a/app/client/src/components/editorComponents/CodeEditor/lintHelpers.ts b/app/client/src/components/editorComponents/CodeEditor/lintHelpers.ts index 65a7e34c27a0..125e41ebaf8c 100644 --- a/app/client/src/components/editorComponents/CodeEditor/lintHelpers.ts +++ b/app/client/src/components/editorComponents/CodeEditor/lintHelpers.ts @@ -135,6 +135,7 @@ export const getLintAnnotations = ( code, errorMessage, line, + lintLength, originalBinding, severity, variables, @@ -157,16 +158,20 @@ export const getLintAnnotations = ( }); } - let variableLength = 1; + let calculatedLintLength = 1; + // If lint length is provided, then skip the length calculation logic + if (lintLength && lintLength > 0) { + calculatedLintLength = lintLength; + } // Find the variable with minimal length - if (variables) { + else if (variables) { for (const variable of variables) { if (variable) { - variableLength = - variableLength === 1 + calculatedLintLength = + calculatedLintLength === 1 ? String(variable).length - : Math.min(String(variable).length, variableLength); + : Math.min(String(variable).length, calculatedLintLength); } } } @@ -205,7 +210,7 @@ export const getLintAnnotations = ( }; const to = { line: from.line, - ch: from.ch + variableLength, + ch: from.ch + calculatedLintLength, }; annotations.push({ diff --git a/app/client/src/utils/DynamicBindingUtils.ts b/app/client/src/utils/DynamicBindingUtils.ts index 4e89443bcf13..897a674652b7 100644 --- a/app/client/src/utils/DynamicBindingUtils.ts +++ b/app/client/src/utils/DynamicBindingUtils.ts @@ -436,6 +436,7 @@ export interface LintError extends DataTreeError { line: number; ch: number; originalPath?: string; + lintLength?: number; } export interface DataTreeEvaluationProps {
0df42ed7022430560c79c0085083c4f04595a950
2022-12-23 11:17:42
Shrikant Sharat Kandula
chore: Upgrade test MongoDB to v5 (#18807)
false
Upgrade test MongoDB to v5 (#18807)
chore
diff --git a/app/server/appsmith-server/src/main/resources/application.properties b/app/server/appsmith-server/src/main/resources/application.properties index 93614c238f48..f3b814b45a61 100644 --- a/app/server/appsmith-server/src/main/resources/application.properties +++ b/app/server/appsmith-server/src/main/resources/application.properties @@ -22,7 +22,7 @@ appsmith.codec.max-in-memory-size=${APPSMITH_CODEC_SIZE:100} spring.data.mongodb.uri = ${APPSMITH_MONGODB_URI} # embedded mongo DB version which is used during junit tests -spring.mongodb.embedded.version=4.2.13 +spring.mongodb.embedded.version=5.0.16 # Log properties logging.level.root=info