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
85269c432c576bbb018be7480e0c845c78528076
2024-03-11 18:13:12
gzlinzihong
fix: file picker widgets removing files causing abnormal content (#31646)
false
file picker widgets removing files causing abnormal content (#31646)
fix
diff --git a/app/client/cypress/e2e/Regression/ClientSide/Widgets/Filepicker/FilePickerV2_spec.js b/app/client/cypress/e2e/Regression/ClientSide/Widgets/Filepicker/FilePickerV2_spec.js index 2ed86032a14f..47253f3d615a 100644 --- a/app/client/cypress/e2e/Regression/ClientSide/Widgets/Filepicker/FilePickerV2_spec.js +++ b/app/client/cypress/e2e/Regression/ClientSide/Widgets/Filepicker/FilePickerV2_spec.js @@ -80,5 +80,61 @@ describe( cy.wait(1000); cy.validateEvaluatedValue("[]"); }); + + it("5. Check removed file", function () { + // Go back to widgets page + PageLeftPane.switchSegment(PagePaneSegment.UI); + + cy.openPropertyPane("textwidget"); + cy.updateCodeInput(".t--property-control-text", `{{FilePicker1.files}}`); + + cy.get(widgetsPage.filepickerwidgetv2).click(); + cy.get(widgetsPage.filepickerwidgetv2CloseModalBtn).click(); + + // Set the maximum number of files allowed to be selected in the file picker. + cy.get(commonlocators.filePickerMaxNoOfFiles).type("2"); + + // Set the 'dataFormat' dropdown of our file picker to Base64. + cy.selectDropdownValue(commonlocators.filePickerDataFormat, "Base64"); + + // Upload a new file + cy.get(widgetsPage.filepickerwidgetv2).click(); + cy.get(commonlocators.filePickerInput) + .first() + .selectFile("cypress/fixtures/testRemoveFile1.json", { + force: true, + }); + cy.get(commonlocators.filePickerUploadButton).click(); + //eslint-disable-next-line cypress/no-unnecessary-waiting + cy.wait(500); + + // Upload a new file + cy.get(widgetsPage.filepickerwidgetv2).click(); + cy.get(commonlocators.AddMoreFiles).click(); + cy.get(commonlocators.filePickerInput) + .first() + .selectFile("cypress/fixtures/testRemoveFile2.json", { + force: true, + }); + cy.get(commonlocators.filePickerUploadButton).click(); + //eslint-disable-next-line cypress/no-unnecessary-waiting + cy.wait(500); + + // Check file data + cy.get(".t--widget-textwidget").should( + "contain", + "data:application/json;base64", + ); + + cy.get(widgetsPage.filepickerwidgetv2).click(); + cy.get(commonlocators.filePickerRemoveButton).first().click(); + cy.get(widgetsPage.filepickerwidgetv2CloseModalBtn).click(); + + // Check file data + cy.get(".t--widget-textwidget").should( + "contain", + "data:application/json;base64", + ); + }); }, ); diff --git a/app/client/cypress/fixtures/testRemoveFile1.json b/app/client/cypress/fixtures/testRemoveFile1.json new file mode 100644 index 000000000000..75b566de07c1 --- /dev/null +++ b/app/client/cypress/fixtures/testRemoveFile1.json @@ -0,0 +1,3 @@ +{ + "test": "aa" +} diff --git a/app/client/cypress/fixtures/testRemoveFile2.json b/app/client/cypress/fixtures/testRemoveFile2.json new file mode 100644 index 000000000000..c65511fd4da5 --- /dev/null +++ b/app/client/cypress/fixtures/testRemoveFile2.json @@ -0,0 +1,3 @@ +{ + "aa": "bb" +} diff --git a/app/client/cypress/locators/commonlocators.json b/app/client/cypress/locators/commonlocators.json index 77980a449f4a..7443ea1aaf6d 100644 --- a/app/client/cypress/locators/commonlocators.json +++ b/app/client/cypress/locators/commonlocators.json @@ -233,5 +233,6 @@ "convertanyways": "button:contains('Convert anyways')", "discard": "button:contains('Discard')", "heightProperty": ".rc-select-single input", - "heightPropertyOption": ".rc-select-item-option-content span" + "heightPropertyOption": ".rc-select-item-option-content span", + "filePickerMaxNoOfFiles": ".t--property-control-maxno\\.offiles .CodeMirror-code" } diff --git a/app/client/src/widgets/FilePickerWidgetV2/widget/index.tsx b/app/client/src/widgets/FilePickerWidgetV2/widget/index.tsx index ae83aed2f725..d079f098b444 100644 --- a/app/client/src/widgets/FilePickerWidgetV2/widget/index.tsx +++ b/app/client/src/widgets/FilePickerWidgetV2/widget/index.tsx @@ -571,6 +571,14 @@ class FilePickerWidget extends BaseWidget< if (reason === "removed-by-user") { const fileCount = this.props.selectedFiles?.length || 0; + /** + * We use this.props.selectedFiles to restore the file list that has been read + */ + const fileMap = this.props.selectedFiles!.reduce((acc, cur) => { + acc[cur.id] = cur.data; + return acc; + }, {}); + /** * Once the file is removed we update the selectedFiles * with the current files present in the uppy's internal state @@ -580,7 +588,7 @@ class FilePickerWidget extends BaseWidget< .map((currentFile: UppyFile, index: number) => ({ type: currentFile.type, id: currentFile.id, - data: currentFile.data, + data: fileMap[currentFile.id], name: currentFile.meta ? currentFile.meta.name : `File-${index + fileCount}`,
09d6c881340ed41773a18d69512bc526717013d1
2023-05-24 17:28:55
Dhruvik Neharia
fix: Hide logo upload behind a feature flag (#23596)
false
Hide logo upload behind a feature flag (#23596)
fix
diff --git a/app/client/src/entities/FeatureFlags.ts b/app/client/src/entities/FeatureFlags.ts index d50483241e1a..1c7cbbf75b71 100644 --- a/app/client/src/entities/FeatureFlags.ts +++ b/app/client/src/entities/FeatureFlags.ts @@ -12,6 +12,7 @@ type FeatureFlags = { AUTO_LAYOUT?: boolean; ONE_CLICK_BINDING?: boolean; ask_ai?: boolean; + APP_NAVIGATION_LOGO_UPLOAD?: boolean; }; export default FeatureFlags; diff --git a/app/client/src/pages/Editor/AppSettingsPane/AppSettings/NavigationSettings/index.tsx b/app/client/src/pages/Editor/AppSettingsPane/AppSettings/NavigationSettings/index.tsx index 87b3483fef96..f30f702f9430 100644 --- a/app/client/src/pages/Editor/AppSettingsPane/AppSettings/NavigationSettings/index.tsx +++ b/app/client/src/pages/Editor/AppSettingsPane/AppSettings/NavigationSettings/index.tsx @@ -23,6 +23,7 @@ import { updateApplication } from "@appsmith/actions/applicationActions"; import { Spinner } from "design-system"; import LogoInput from "@appsmith/pages/Editor/NavigationSettings/LogoInput"; import SwitchSettingForLogoConfiguration from "./SwitchSettingForLogoConfiguration"; +import { selectFeatureFlags } from "selectors/usersSelectors"; /** * TODO - @Dhruvik - ImprovedAppNav @@ -46,6 +47,7 @@ export type LogoConfigurationSwitches = { function NavigationSettings() { const application = useSelector(getCurrentApplication); const applicationId = useSelector(getCurrentApplicationId); + const featureFlags = useSelector(selectFeatureFlags); const dispatch = useDispatch(); const [navigationSetting, setNavigationSetting] = useState( application?.applicationDetail?.navigationSetting, @@ -388,21 +390,27 @@ function NavigationSettings() { updateSetting={updateSetting} /> - <SwitchSettingForLogoConfiguration - keyName="logo" - label={createMessage(APP_NAVIGATION_SETTING.showLogoLabel)} - logoConfigurationSwitches={logoConfigurationSwitches} - setLogoConfigurationSwitches={setLogoConfigurationSwitches} - /> + {(navigationSetting?.logoAssetId || + featureFlags.APP_NAVIGATION_LOGO_UPLOAD) && ( + <> + <SwitchSettingForLogoConfiguration + keyName="logo" + label={createMessage(APP_NAVIGATION_SETTING.showLogoLabel)} + logoConfigurationSwitches={logoConfigurationSwitches} + setLogoConfigurationSwitches={setLogoConfigurationSwitches} + /> - {(navigationSetting?.logoConfiguration === - NAVIGATION_SETTINGS.LOGO_CONFIGURATION.LOGO_AND_APPLICATION_TITLE || - navigationSetting?.logoConfiguration === - NAVIGATION_SETTINGS.LOGO_CONFIGURATION.LOGO_ONLY) && ( - <LogoInput - navigationSetting={navigationSetting} - updateSetting={updateSetting} - /> + {(navigationSetting?.logoConfiguration === + NAVIGATION_SETTINGS.LOGO_CONFIGURATION + .LOGO_AND_APPLICATION_TITLE || + navigationSetting?.logoConfiguration === + NAVIGATION_SETTINGS.LOGO_CONFIGURATION.LOGO_ONLY) && ( + <LogoInput + navigationSetting={navigationSetting} + updateSetting={updateSetting} + /> + )} + </> )} <SwitchSettingForLogoConfiguration diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/featureflags/FeatureFlagEnum.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/featureflags/FeatureFlagEnum.java index f81e1dcedbe3..4c3b0ee6f725 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/featureflags/FeatureFlagEnum.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/featureflags/FeatureFlagEnum.java @@ -32,6 +32,7 @@ public enum FeatureFlagEnum { DATASOURCE_ENVIRONMENTS, AUTO_LAYOUT, ONE_CLICK_BINDING, + APP_NAVIGATION_LOGO_UPLOAD, // Add EE flags below this line, to avoid conflicts. RBAC, diff --git a/app/server/appsmith-server/src/main/resources/features/init-flags.yml b/app/server/appsmith-server/src/main/resources/features/init-flags.yml index bd7958ea3728..586be1d19af7 100644 --- a/app/server/appsmith-server/src/main/resources/features/init-flags.yml +++ b/app/server/appsmith-server/src/main/resources/features/init-flags.yml @@ -89,6 +89,15 @@ ff4j: - name: weight value: 1 + - uid: APP_NAVIGATION_LOGO_UPLOAD + enable: true + description: Logo upload feature for app viewer navigation + flipstrategy: + class: com.appsmith.server.featureflags.strategies.EmailBasedRolloutStrategy + param: + - name: emailDomains + value: appsmith.com,moolya.com + # Put EE flags below this line, to avoid conflicts. - uid: ONE_CLICK_BINDING
e944f1b17c8803dca9d3dd088320eb1f47d19f86
2022-02-23 10:22:04
Bhavin K
fix: handled to hide widget in preview mode (#11138)
false
handled to hide widget in preview mode (#11138)
fix
diff --git a/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/PreviewMode/PreviewMode_spec.js b/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/PreviewMode/PreviewMode_spec.js index 9161d9420124..dced5ce447e3 100644 --- a/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/PreviewMode/PreviewMode_spec.js +++ b/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/PreviewMode/PreviewMode_spec.js @@ -1,4 +1,6 @@ const dsl = require("../../../../fixtures/previewMode.json"); +const commonlocators = require("../../../../locators/commonlocators.json"); +const publishPage = require("../../../../locators/publishWidgetspage.json"); describe("Preview mode functionality", function() { before(() => { @@ -26,4 +28,25 @@ describe("Preview mode functionality", function() { `${selector}:first-of-type .t--widget-propertypane-toggle > .t--widget-name`, ).should("not.exist"); }); + + it("check invisible widget should not show in proview mode and should show in edit mode", function() { + cy.get(".t--switch-comment-mode-off").click(); + cy.openPropertyPane("buttonwidget"); + cy.UncheckWidgetProperties(commonlocators.visibleCheckbox); + + // button should not show in preview mode + cy.get(".t--switch-preview-mode-toggle").click(); + cy.get(`${publishPage.buttonWidget} button`).should("not.exist"); + + // Text widget should show + cy.get(`${publishPage.textWidget} .bp3-ui-text`).should("exist"); + + // button should show in edit mode + cy.get(".t--switch-comment-mode-off").click(); + cy.get(`${publishPage.buttonWidget} button`).should("exist"); + }); + + afterEach(() => { + // put your clean up code if any + }); }); diff --git a/app/client/src/components/editorComponents/PreviewModeComponent.tsx b/app/client/src/components/editorComponents/PreviewModeComponent.tsx new file mode 100644 index 000000000000..e076ddf324bc --- /dev/null +++ b/app/client/src/components/editorComponents/PreviewModeComponent.tsx @@ -0,0 +1,22 @@ +import React from "react"; +import { useSelector } from "react-redux"; +import { previewModeSelector } from "selectors/editorSelectors"; + +type Props = { + children: React.ReactNode; + isVisible?: boolean; +}; + +/** + * render only visible components in preview mode + */ +function PreviewModeComponent({ + children, + isVisible, +}: Props): React.ReactElement { + const isPreviewMode = useSelector(previewModeSelector); + if (!isPreviewMode || isVisible) return children as React.ReactElement; + else return <div />; +} + +export default PreviewModeComponent; diff --git a/app/client/src/widgets/BaseWidget.tsx b/app/client/src/widgets/BaseWidget.tsx index ee632b8a22c7..fa133715ea2d 100644 --- a/app/client/src/widgets/BaseWidget.tsx +++ b/app/client/src/widgets/BaseWidget.tsx @@ -38,6 +38,7 @@ import OverlayCommentsWrapper from "comments/inlineComments/OverlayCommentsWrapp import PreventInteractionsOverlay from "components/editorComponents/PreventInteractionsOverlay"; import AppsmithConsole from "utils/AppsmithConsole"; import { ENTITY_TYPE } from "entities/AppsmithConsole"; +import PreviewModeComponent from "components/editorComponents/PreviewModeComponent"; /*** * BaseWidget @@ -313,12 +314,20 @@ abstract class BaseWidget< ); } + addPreviewModeWidget(content: ReactNode): React.ReactElement { + return ( + <PreviewModeComponent isVisible={this.props.isVisible}> + {content} + </PreviewModeComponent> + ); + } + private getWidgetView(): ReactNode { let content: ReactNode; - switch (this.props.renderMode) { case RenderModes.CANVAS: content = this.getCanvasView(); + content = this.addPreviewModeWidget(content); content = this.addPreventInteractionOverlay(content); content = this.addOverlayComments(content); if (!this.props.detachFromLayout) {
8e193add574f81f69409cc49ccb14ad856950c2a
2023-07-26 16:55:06
Nilansh Bansal
fix: Published navSettings on git import (#25709)
false
Published navSettings on git import (#25709)
fix
diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/helpers/ImportExportUtils.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/helpers/ImportExportUtils.java index 23f1b591e4c3..6de6563aa9c3 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/helpers/ImportExportUtils.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/helpers/ImportExportUtils.java @@ -103,4 +103,16 @@ public static void setPropertiesToExistingApplication( copyNestedNonNullProperties(importedApplication, existingApplication); } + + /** + * This method sets the published mode properties in the imported application. + * When a user imports an application from the git repository, since the git only stores the unpublished version, + * the current deployed version in the newly imported app is not updated. This function sets the initial deployed + * version to the same as the edit mode one. + * @param importedApplication + */ + public static void setPublishedApplicationProperties(Application importedApplication) { + importedApplication.setPublishedApplicationDetail(importedApplication.getUnpublishedApplicationDetail()); + importedApplication.setPublishedAppLayout(importedApplication.getUnpublishedAppLayout()); + } } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ce/ImportExportApplicationServiceCEImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ce/ImportExportApplicationServiceCEImpl.java index c82de2ce9d6c..91659a0aca72 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ce/ImportExportApplicationServiceCEImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ce/ImportExportApplicationServiceCEImpl.java @@ -113,6 +113,7 @@ import static com.appsmith.server.constants.ResourceModes.VIEW; import static com.appsmith.server.helpers.ImportExportUtils.sanitizeDatasourceInActionDTO; import static com.appsmith.server.helpers.ImportExportUtils.setPropertiesToExistingApplication; +import static com.appsmith.server.helpers.ImportExportUtils.setPublishedApplicationProperties; import static java.lang.Boolean.TRUE; @Slf4j @@ -1200,6 +1201,13 @@ private Mono<Application> importApplicationInWorkspace( unpublishedPages.addAll(existingApplication.getPages()); return Mono.just(existingApplication); } + // This method sets the published mode properties in the imported + // application.When a user imports an application from the git repo, + // since the git only stores the unpublished version, the current + // deployed version in the newly imported app is not updated. + // This function sets the initial deployed version to the same as the + // edit mode one. + setPublishedApplicationProperties(importedApplication); setPropertiesToExistingApplication( importedApplication, existingApplication); // We are expecting the changes present in DB are committed to git diff --git a/app/server/appsmith-server/src/test/java/com/appsmith/server/solutions/ImportExportApplicationServiceTests.java b/app/server/appsmith-server/src/test/java/com/appsmith/server/solutions/ImportExportApplicationServiceTests.java index 124145cf1fc5..5f9e9dda051e 100644 --- a/app/server/appsmith-server/src/test/java/com/appsmith/server/solutions/ImportExportApplicationServiceTests.java +++ b/app/server/appsmith-server/src/test/java/com/appsmith/server/solutions/ImportExportApplicationServiceTests.java @@ -3053,6 +3053,108 @@ public void importApplication_datasourceWithSameNameAndPlugin_importedWithValidA .verifyComplete(); } + @Test + @WithUserDetails(value = "api_user") + public void + importApplicationInWorkspaceFromGit_WithNavSettingsInEditMode_ImportedAppHasNavSettingsInEditAndViewMode() { + Workspace newWorkspace = new Workspace(); + newWorkspace.setName("import-with-navSettings-in-editMode"); + + Application testApplication = new Application(); + testApplication.setName( + "importApplicationInWorkspaceFromGit_WithNavSettingsInEditMode_ImportedAppHasNavSettingsInEditAndViewMode"); + Application.NavigationSetting appNavigationSetting = new Application.NavigationSetting(); + appNavigationSetting.setOrientation("top"); + testApplication.setUnpublishedApplicationDetail(new ApplicationDetail()); + testApplication.getUnpublishedApplicationDetail().setNavigationSetting(appNavigationSetting); + 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 = importExportApplicationService + .exportApplicationById(savedApplication.getId(), SerialiseApplicationObjective.VERSION_CONTROL) + .flatMap(applicationJson -> { + // setting published mode resource as null, similar to the app json exported to git repo + applicationJson.getExportedApplication().setPublishedApplicationDetail(null); + return importExportApplicationService.importApplicationInWorkspaceFromGit( + workspaceId, applicationJson, savedApplication.getId(), gitData.getBranchName()); + }); + + StepVerifier.create(result) + .assertNext(importedApp -> { + assertThat(importedApp.getUnpublishedApplicationDetail()).isNotNull(); + assertThat(importedApp.getPublishedApplicationDetail()).isNotNull(); + assertThat(importedApp.getUnpublishedApplicationDetail().getNavigationSetting()) + .isNotNull(); + assertEquals( + importedApp + .getUnpublishedApplicationDetail() + .getNavigationSetting() + .getOrientation(), + "top"); + assertThat(importedApp.getPublishedApplicationDetail().getNavigationSetting()) + .isNotNull(); + assertEquals( + importedApp + .getPublishedApplicationDetail() + .getNavigationSetting() + .getOrientation(), + "top"); + }) + .verifyComplete(); + } + + @Test + @WithUserDetails(value = "api_user") + public void importApplicationInWorkspaceFromGit_WithAppLayoutInEditMode_ImportedAppHasAppLayoutInEditAndViewMode() { + Workspace newWorkspace = new Workspace(); + newWorkspace.setName("import-with-appLayout-in-editMode"); + + Application testApplication = new Application(); + testApplication.setName( + "importApplicationInWorkspaceFromGit_WithAppLayoutInEditMode_ImportedAppHasAppLayoutInEditAndViewMode"); + testApplication.setUnpublishedAppLayout(new Application.AppLayout(Application.AppLayout.Type.DESKTOP)); + 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 = importExportApplicationService + .exportApplicationById(savedApplication.getId(), SerialiseApplicationObjective.VERSION_CONTROL) + .flatMap(applicationJson -> { + // setting published mode resource as null, similar to the app json exported to git repo + applicationJson.getExportedApplication().setPublishedAppLayout(null); + return importExportApplicationService.importApplicationInWorkspaceFromGit( + workspaceId, applicationJson, savedApplication.getId(), gitData.getBranchName()); + }); + + StepVerifier.create(result) + .assertNext(importedApp -> { + assertThat(importedApp.getUnpublishedAppLayout()).isNotNull(); + assertThat(importedApp.getPublishedAppLayout()).isNotNull(); + assertThat(importedApp.getUnpublishedAppLayout().getType()) + .isEqualTo(Application.AppLayout.Type.DESKTOP); + assertThat(importedApp.getPublishedAppLayout().getType()) + .isEqualTo(Application.AppLayout.Type.DESKTOP); + }) + .verifyComplete(); + } + @Test @WithUserDetails(value = "api_user") public void
8c4d711f5b244eb84a1903685e202ae6d213d32d
2022-01-30 17:43:35
Abhijeet
chore: Make sure to keep forked application in valid state even if client exits the flow before server responds (#10704)
false
Make sure to keep forked application in valid state even if client exits the flow before server responds (#10704)
chore
diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ce/ApplicationForkingServiceCEImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ce/ApplicationForkingServiceCEImpl.java index c25f166a4012..9a39efa9a1f6 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ce/ApplicationForkingServiceCEImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ce/ApplicationForkingServiceCEImpl.java @@ -44,7 +44,7 @@ public Mono<Application> forkApplicationToOrganization(String srcApplicationId, Mono<User> userMono = sessionUserService.getCurrentUser(); - return Mono.zip(sourceApplicationMono, targetOrganizationMono, userMono) + Mono<Application> forkApplicationMono = Mono.zip(sourceApplicationMono, targetOrganizationMono, userMono) .flatMap(tuple -> { final Application application = tuple.getT1(); final Organization targetOrganization = tuple.getT2(); @@ -75,6 +75,17 @@ public Mono<Application> forkApplicationToOrganization(String srcApplicationId, .flatMap(application -> sendForkApplicationAnalyticsEvent(srcApplicationId, targetOrganizationId, application)); }); + + // Fork application is currently a slow API because it needs to create application, clone all the pages, and then + // copy all the actions and collections. This process may take time and the client may cancel the request. + // This leads to the flow getting stopped mid way producing corrupted DB objects. The following ensures that even + // though the client may have cancelled the flow, the forking of the application should proceed uninterrupted + // and whenever the user refreshes the page, the sane forked application is available. + // 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 -> forkApplicationMono + .subscribe(sink::success, sink::error, null, sink.currentContext()) + ); } public Mono<Application> forkApplicationToOrganization(String srcApplicationId, 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 51aa90da1157..4cc3e10a37eb 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 @@ -61,6 +61,7 @@ import reactor.core.publisher.Mono; import reactor.test.StepVerifier; +import java.time.Duration; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; @@ -382,6 +383,107 @@ public void test3_failForkApplicationWithInvalidPermission() { .verify(); } + @Test + @WithUserDetails(value = "api_user") + public void test4_validForkApplication_cancelledMidWay_createValidApplication() { + + Organization targetOrganization = new Organization(); + targetOrganization.setName("Target Organization"); + targetOrganization = organizationService.create(targetOrganization).block(); + + // Trigger the fork application flow + applicationForkingService.forkApplicationToOrganization(sourceAppId, targetOrganization.getId()) + .timeout(Duration.ofMillis(10)) + .subscribe(); + + // Wait for fork to complete + Mono<Application> forkedAppFromDbMono = Mono.just(targetOrganization) + .flatMap(organization -> { + try { + // Before fetching the forked application, sleep for 5 seconds to ensure that the forking finishes + Thread.sleep(5000); + } catch (InterruptedException e) { + e.printStackTrace(); + } + return applicationService.findByOrganizationId(organization.getId(), READ_APPLICATIONS).next(); + }) + .cache(); + + StepVerifier + .create(forkedAppFromDbMono.zipWhen(application -> + Mono.zip( + newActionService.findAllByApplicationIdAndViewMode(application.getId(), false, READ_ACTIONS, null).collectList(), + actionCollectionService.findAllByApplicationIdAndViewMode(application.getId(), false, READ_ACTIONS, null).collectList(), + newPageService.findNewPagesByApplicationId(application.getId(), READ_PAGES).collectList())) + ) + .assertNext(tuple -> { + Application application = tuple.getT1(); + List<NewAction> actionList = tuple.getT2().getT1(); + List<ActionCollection> actionCollectionList = tuple.getT2().getT2(); + List<NewPage> pageList = tuple.getT2().getT3(); + + assertThat(application).isNotNull(); + assertThat(application.getName()).isEqualTo("1 - public app"); + assertThat(application.getPages().get(0).getDefaultPageId()) + .isEqualTo(application.getPages().get(0).getId()); + assertThat(application.getPublishedPages().get(0).getDefaultPageId()) + .isEqualTo(application.getPublishedPages().get(0).getId()); + + assertThat(pageList).isNotEmpty(); + pageList.forEach(newPage -> { + assertThat(newPage.getDefaultResources()).isNotNull(); + assertThat(newPage.getDefaultResources().getPageId()).isEqualTo(newPage.getId()); + assertThat(newPage.getDefaultResources().getApplicationId()).isEqualTo(application.getId()); + + newPage.getUnpublishedPage() + .getLayouts() + .forEach(layout -> + layout.getLayoutOnLoadActions().forEach(dslActionDTOS -> { + dslActionDTOS.forEach(actionDTO -> { + assertThat(actionDTO.getId()).isEqualTo(actionDTO.getDefaultActionId()); + }); + }) + ); + }); + + assertThat(actionList).hasSize(2); + actionList.forEach(newAction -> { + assertThat(newAction.getDefaultResources()).isNotNull(); + assertThat(newAction.getDefaultResources().getActionId()).isEqualTo(newAction.getId()); + assertThat(newAction.getDefaultResources().getApplicationId()).isEqualTo(application.getId()); + + ActionDTO action = newAction.getUnpublishedAction(); + assertThat(action.getDefaultResources()).isNotNull(); + assertThat(action.getDefaultResources().getPageId()).isEqualTo(application.getPages().get(0).getId()); + if (!StringUtils.isEmpty(action.getDefaultResources().getCollectionId())) { + assertThat(action.getDefaultResources().getCollectionId()).isEqualTo(action.getCollectionId()); + } + }); + + assertThat(actionCollectionList).hasSize(1); + actionCollectionList.forEach(actionCollection -> { + assertThat(actionCollection.getDefaultResources()).isNotNull(); + assertThat(actionCollection.getDefaultResources().getCollectionId()).isEqualTo(actionCollection.getId()); + assertThat(actionCollection.getDefaultResources().getApplicationId()).isEqualTo(application.getId()); + + ActionCollectionDTO unpublishedCollection = actionCollection.getUnpublishedCollection(); + + assertThat(unpublishedCollection.getDefaultToBranchedActionIdsMap()) + .hasSize(1); + unpublishedCollection.getDefaultToBranchedActionIdsMap().keySet() + .forEach(key -> + assertThat(key).isEqualTo(unpublishedCollection.getDefaultToBranchedActionIdsMap().get(key)) + ); + + assertThat(unpublishedCollection.getDefaultResources()).isNotNull(); + assertThat(unpublishedCollection.getDefaultResources().getPageId()) + .isEqualTo(application.getPages().get(0).getId()); + }); + }) + .verifyComplete(); + + } + private Flux<ActionDTO> getActionsInOrganization(Organization organization) { return applicationService .findByOrganizationId(organization.getId(), READ_APPLICATIONS)
36577ad7cc1e38f0b877434351e933652825babc
2024-03-26 21:28:16
Shrikant Sharat Kandula
chore: Remove QueryDSL (#32074)
false
Remove QueryDSL (#32074)
chore
diff --git a/app/server/appsmith-interfaces/pom.xml b/app/server/appsmith-interfaces/pom.xml index 418de9925e22..485fdaacd013 100644 --- a/app/server/appsmith-interfaces/pom.xml +++ b/app/server/appsmith-interfaces/pom.xml @@ -99,19 +99,6 @@ <groupId>com.google.code.gson</groupId> <artifactId>gson</artifactId> </dependency> - <dependency> - <groupId>com.querydsl</groupId> - <artifactId>querydsl-mongodb</artifactId> - </dependency> - <dependency> - <groupId>com.querydsl</groupId> - <artifactId>querydsl-apt</artifactId> - <scope>provided</scope> - </dependency> - <dependency> - <groupId>com.querydsl</groupId> - <artifactId>querydsl-jpa</artifactId> - </dependency> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-text</artifactId> @@ -248,25 +235,4 @@ </dependencies> - <build> - <plugins> - <plugin> - <groupId>com.mysema.maven</groupId> - <artifactId>apt-maven-plugin</artifactId> - <version>1.1.3</version> - <executions> - <execution> - <goals> - <goal>process</goal> - </goals> - <configuration> - <outputDirectory>target/generated-sources/java</outputDirectory> - <processor>org.springframework.data.mongodb.repository.support.MongoAnnotationProcessor</processor> - </configuration> - </execution> - </executions> - </plugin> - </plugins> - </build> - </project> 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 df2b86f4f46e..e2bc67e2dd55 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 @@ -1,7 +1,6 @@ package com.appsmith.external.models; import com.appsmith.external.models.ce.ActionCE_DTO; -import com.querydsl.core.annotations.QueryEmbeddable; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; @@ -12,7 +11,6 @@ @Setter @NoArgsConstructor @ToString(callSuper = true) -@QueryEmbeddable @FieldNameConstants public class ActionDTO extends ActionCE_DTO { public static class Fields extends ActionCE_DTO.Fields {} diff --git a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/BaseDomain.java b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/BaseDomain.java index eb6e7176032c..3d6bf102f5b0 100644 --- a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/BaseDomain.java +++ b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/BaseDomain.java @@ -4,7 +4,6 @@ import com.appsmith.external.views.Views; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonView; -import com.querydsl.core.annotations.QueryTransient; import lombok.AccessLevel; import lombok.Getter; import lombok.Setter; @@ -66,7 +65,6 @@ public abstract class BaseDomain implements Persistable<String>, AppsmithDomain, */ @Deprecated(forRemoval = true) @JsonView(Views.Internal.class) - @QueryTransient @Getter(AccessLevel.NONE) @Setter(AccessLevel.NONE) protected Boolean deleted = false; @@ -83,7 +81,6 @@ public boolean isNew() { return this.getId() == null; } - @QueryTransient @JsonView(Views.Internal.class) public boolean isDeleted() { return deletedAt != null; diff --git a/app/server/appsmith-server/pom.xml b/app/server/appsmith-server/pom.xml index 620b7b587f0f..363b03922246 100644 --- a/app/server/appsmith-server/pom.xml +++ b/app/server/appsmith-server/pom.xml @@ -304,18 +304,6 @@ <version>1.0-SNAPSHOT</version> </dependency> - <dependency> - <groupId>com.querydsl</groupId> - <artifactId>querydsl-mongodb</artifactId> - </dependency> - <dependency> - <groupId>com.querydsl</groupId> - <artifactId>querydsl-apt</artifactId> - </dependency> - <dependency> - <groupId>com.querydsl</groupId> - <artifactId>querydsl-jpa</artifactId> - </dependency> <dependency> <groupId>org.modelmapper</groupId> <artifactId>modelmapper</artifactId> @@ -469,26 +457,6 @@ <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> - - <plugin> - <groupId>com.mysema.maven</groupId> - <artifactId>apt-maven-plugin</artifactId> - <version>1.1.3</version> - <executions> - <execution> - <goals> - <goal>process</goal> - </goals> - <configuration> - <outputDirectory>target/generated-sources/java</outputDirectory> - <processor>org.springframework.data.mongodb.repository.support.MongoAnnotationProcessor</processor> - <options> - <querydsl.listAccessors>true</querydsl.listAccessors> - </options> - </configuration> - </execution> - </executions> - </plugin> </plugins> </build> diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/domains/Application.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/domains/Application.java index 95036505f4f7..a6c2372de2c5 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/domains/Application.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/domains/Application.java @@ -6,7 +6,6 @@ import com.appsmith.server.dtos.CustomJSLibContextDTO; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonView; -import com.querydsl.core.annotations.QueryEntity; import jakarta.validation.constraints.NotNull; import lombok.AllArgsConstructor; import lombok.Data; @@ -35,7 +34,6 @@ @Setter @ToString @NoArgsConstructor -@QueryEntity @Document @FieldNameConstants public class Application extends BaseDomain implements Artifact { diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/dtos/ActionCollectionDTO.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/dtos/ActionCollectionDTO.java index 519477f5bafa..a08bd585e255 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/dtos/ActionCollectionDTO.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/dtos/ActionCollectionDTO.java @@ -1,7 +1,6 @@ package com.appsmith.server.dtos; import com.appsmith.server.dtos.ce.ActionCollectionCE_DTO; -import com.querydsl.core.annotations.QueryEmbeddable; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; @@ -12,7 +11,6 @@ @Setter @NoArgsConstructor @ToString(callSuper = true) -@QueryEmbeddable @FieldNameConstants public class ActionCollectionDTO extends ActionCollectionCE_DTO { public static class Fields extends ActionCollectionCE_DTO.Fields {} diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/migrations/MigrationHelperMethods.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/migrations/MigrationHelperMethods.java index 0097de5c8f1c..a43ee3cdb504 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/migrations/MigrationHelperMethods.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/migrations/MigrationHelperMethods.java @@ -13,7 +13,6 @@ import com.appsmith.server.dtos.ApplicationJson; import com.appsmith.server.helpers.CollectionUtils; import com.appsmith.server.repositories.CacheableRepositoryHelper; -import com.querydsl.core.types.Path; import org.apache.commons.lang.StringUtils; import org.springframework.data.mongodb.core.MongoTemplate; import org.springframework.data.mongodb.core.query.Criteria; @@ -29,7 +28,6 @@ import static com.appsmith.server.constants.ResourceModes.EDIT; import static com.appsmith.server.constants.ResourceModes.VIEW; -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; @@ -212,19 +210,6 @@ public static Query getQueryToFetchAllDomainObjectsWhichAreNotDeletedUsingPlugin return query((new Criteria()).andOperator(pluginIdMatchesSuppliedPluginId, isNotDeleted)); } - /** - * Here 'id' refers to the ObjectId which is used to uniquely identify each Mongo document. 'path' refers to the - * path in the Query DSL object that indicates which field in a document should be matched against the `id`. - * `type` is a POJO class type that indicates which collection we are interested in. eg. path=QNewAction - * .newAction.id, type=NewAction.class - */ - public static <T extends BaseDomain> T fetchDomainObjectUsingId( - String id, MongoTemplate mongoTemplate, Path path, Class<T> type) { - final T domainObject = - mongoTemplate.findOne(query(where(fieldName(path)).is(id)), type); - return domainObject; - } - /** * Here 'id' refers to the ObjectId which is used to uniquely identify each Mongo document. 'path' refers to the * path in the Query DSL object that indicates which field in a document should be matched against the `id`. diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/BaseAppsmithRepositoryCEImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/BaseAppsmithRepositoryCEImpl.java index 86360a1b1db9..f30cce7cf1b5 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/BaseAppsmithRepositoryCEImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/BaseAppsmithRepositoryCEImpl.java @@ -13,8 +13,6 @@ import com.mongodb.DBObject; import com.mongodb.client.model.UpdateOneModel; import com.mongodb.client.model.WriteModel; -import com.querydsl.core.types.Path; -import jakarta.validation.constraints.NotNull; import lombok.NonNull; import org.bson.Document; import org.bson.types.ObjectId; @@ -92,21 +90,6 @@ public BaseAppsmithRepositoryCEImpl( (Class<T>) GenericTypeResolver.resolveTypeArgument(getClass(), BaseAppsmithRepositoryCEImpl.class); } - public static String fieldName(Path<?> path) { - return Optional.ofNullable(path).map(p -> p.getMetadata().getName()).orElse(""); - } - - public static String completeFieldName(@NotNull Path<?> path) { - StringBuilder sb = new StringBuilder(); - - while (!path.getMetadata().isRoot()) { - sb.insert(0, "." + fieldName(path)); - path = path.getMetadata().getParent(); - } - sb.deleteCharAt(0); - return sb.toString(); - } - public static Criteria notDeleted() { return new Criteria() .andOperator(
613db73b15f9a6c5cd1c28fe15b9887a4c26f37c
2020-08-21 11:33:04
Abhinav Jha
fix: Action move & copy issues (#381)
false
Action move & copy issues (#381)
fix
diff --git a/app/client/src/pages/Editor/QueryEditor/Form.tsx b/app/client/src/pages/Editor/QueryEditor/Form.tsx index ae2f5cb9be94..1ef28060c3e8 100644 --- a/app/client/src/pages/Editor/QueryEditor/Form.tsx +++ b/app/client/src/pages/Editor/QueryEditor/Form.tsx @@ -6,7 +6,7 @@ import { Field, } from "redux-form"; import styled, { createGlobalStyle } from "styled-components"; -import { Icon, Popover, Spinner } from "@blueprintjs/core"; +import { Icon, Popover, Spinner, Tag } from "@blueprintjs/core"; import { components, MenuListComponentProps, @@ -14,7 +14,7 @@ import { OptionTypeBase, SingleValueProps, } from "react-select"; -import _ from "lodash"; +import { isString } from "lodash"; import history from "utils/history"; import { DATA_SOURCES_EDITOR_URL } from "constants/routes"; import Button from "components/editorComponents/Button"; @@ -155,6 +155,8 @@ const TooltipStyles = createGlobalStyle` const ErrorMessage = styled.p` font-size: 14px; color: ${Colors.RED}; + display: inline-block; + margin-right: 10px; `; const CreateDatasource = styled.div` height: 44px; @@ -230,7 +232,7 @@ type QueryFormProps = { location: { state: any; }; - editorConfig: []; + editorConfig?: any; loadingFormConfigs: boolean; }; @@ -269,7 +271,7 @@ const QueryEditorForm: React.FC<Props> = (props: Props) => { let output: Record<string, any>[] | null = null; if (executedQueryData) { - if (_.isString(executedQueryData.body)) { + if (isString(executedQueryData.body)) { error = executedQueryData.body; } else { output = executedQueryData.body; @@ -440,10 +442,21 @@ const QueryEditorForm: React.FC<Props> = (props: Props) => { )} </div> - {!_.isNil(editorConfig) ? ( - _.map(editorConfig, renderEachConfig) + {editorConfig && editorConfig.length > 0 ? ( + editorConfig.map(renderEachConfig) ) : ( - <ErrorMessage>An unexpected error occurred</ErrorMessage> + <> + <ErrorMessage>An unexpected error occurred</ErrorMessage> + <Tag + round + intent="warning" + interactive + minimal + onClick={() => window.location.reload()} + > + Refresh + </Tag> + </> )} <div className="executeOnLoad"> <Field @@ -492,7 +505,7 @@ const QueryEditorForm: React.FC<Props> = (props: Props) => { }; const renderEachConfig = (section: any): any => { - return _.map(section.children, (propertyControlOrSection: ControlProps) => { + return section.children.map((propertyControlOrSection: ControlProps) => { if ("children" in propertyControlOrSection) { return renderEachConfig(propertyControlOrSection); } else { @@ -511,6 +524,7 @@ const renderEachConfig = (section: any): any => { console.log(e); } } + return null; }); }; diff --git a/app/client/src/pages/Editor/QueryEditor/index.tsx b/app/client/src/pages/Editor/QueryEditor/index.tsx index 79d041a0d190..bb33cd5e2aa4 100644 --- a/app/client/src/pages/Editor/QueryEditor/index.tsx +++ b/app/client/src/pages/Editor/QueryEditor/index.tsx @@ -53,7 +53,7 @@ type ReduxStateProps = { responses: any; isCreating: boolean; pluginImages: Record<string, string>; - editorConfig: []; + editorConfig: any; loadingFormConfigs: boolean; isEditorInitialized: boolean; }; @@ -157,9 +157,16 @@ class QueryEditor extends React.Component<Props> { const mapStateToProps = (state: AppState, props: any): ReduxStateProps => { const { runErrorMessage } = state.ui.queryPane; const { plugins } = state.entities; + const { editorConfigs, loadingFormConfigs } = plugins; const formData = getFormValues(QUERY_EDITOR_FORM_NAME)(state) as QueryAction; const queryAction = getAction(state, props.match.params.queryId); + let editorConfig: any; + const pluginId = queryAction?.datasource?.pluginId; + + if (editorConfigs && pluginId) { + editorConfig = editorConfigs[pluginId]; + } return { pluginImages: getPluginImages(state), @@ -170,9 +177,7 @@ const mapStateToProps = (state: AppState, props: any): ReduxStateProps => { responses: getActionResponses(state), queryPane: state.ui.queryPane, formData, - editorConfig: queryAction?.pluginId - ? editorConfigs[queryAction.pluginId] - : [], + editorConfig, loadingFormConfigs, isCreating: state.ui.apiPane.isCreating, isEditorInitialized: getIsEditorInitialized(state), diff --git a/app/client/src/sagas/ActionSagas.ts b/app/client/src/sagas/ActionSagas.ts index 0f7c0e6351fa..bca71683c37c 100644 --- a/app/client/src/sagas/ActionSagas.ts +++ b/app/client/src/sagas/ActionSagas.ts @@ -60,8 +60,6 @@ import { QUERIES_EDITOR_ID_URL, API_EDITOR_ID_URL, } from "constants/routes"; -import { changeApi } from "actions/apiPaneActions"; -import { changeQuery } from "actions/queryPaneActions"; export function* createActionSaga(actionPayload: ReduxAction<RestAction>) { try { @@ -292,28 +290,6 @@ function* moveActionSaga( apiID: response.data.id, }); yield put(moveActionSuccess(response.data)); - const applicationId = yield select(getCurrentApplicationId); - - const isApi = actionObject.pluginType === PLUGIN_TYPE_API; - const isQuery = actionObject.pluginType === QUERY_CONSTANT; - - if (isQuery) { - history.push( - QUERIES_EDITOR_ID_URL( - applicationId, - response.data.pageId, - response.data.id, - ), - ); - } else if (isApi) { - history.push( - API_EDITOR_ID_URL( - applicationId, - response.data.pageId, - response.data.id, - ), - ); - } } catch (e) { AppToaster.show({ message: `Error while moving action ${actionObject.name}`, @@ -358,10 +334,6 @@ function* copyActionSaga( apiID: response.data.id, }); yield put(copyActionSuccess(response.data)); - const applicationId = yield select(getCurrentApplicationId); - history.push( - API_EDITOR_ID_URL(applicationId, response.data.pageId, response.data.id), - ); } catch (e) { AppToaster.show({ message: `Error while copying action ${actionObject.name}`, @@ -490,15 +462,18 @@ function* setActionPropertySaga(action: ReduxAction<SetActionPropertyPayload>) { function* handleMoveOrCopySaga(actionPayload: ReduxAction<{ id: string }>) { const { id } = actionPayload.payload; - const action = yield select(getAction, id); + const action: Action = yield select(getAction, id); const isApi = action.pluginType === PLUGIN_TYPE_API; const isQuery = action.pluginType === QUERY_CONSTANT; + const applicationId = yield select(getCurrentApplicationId); if (isApi) { - yield put(changeApi(id)); + history.push(API_EDITOR_ID_URL(applicationId, action.pageId, action.id)); } if (isQuery) { - yield put(changeQuery(id)); + history.push( + QUERIES_EDITOR_ID_URL(applicationId, action.pageId, action.id), + ); } } diff --git a/app/client/src/sagas/ApiPaneSagas.ts b/app/client/src/sagas/ApiPaneSagas.ts index 5ee63e33a103..dfb8ae459969 100644 --- a/app/client/src/sagas/ApiPaneSagas.ts +++ b/app/client/src/sagas/ApiPaneSagas.ts @@ -135,7 +135,11 @@ function* initializeExtraFormDataSaga() { DEFAULT_API_ACTION.actionConfiguration?.headers, ); - const queryParameters = get(values, "actionConfiguration.queryParameters"); + const queryParameters = get( + values, + "actionConfiguration.queryParameters", + [], + ); if (!extraformData[values.id]) { yield put( change(API_EDITOR_FORM_NAME, "actionConfiguration.headers", headers),
5d7b785639dc3356e813e141cd0d9f45e7e40a6d
2024-11-25 10:06:14
Kevin Blanco
chore: update README.md to reflect Youtube stats (#36874)
false
update README.md to reflect Youtube stats (#36874)
chore
diff --git a/README.md b/README.md index 9174c78f6dae..42964895ce7e 100644 --- a/README.md +++ b/README.md @@ -15,6 +15,12 @@ <a href="https://docs.appsmith.com/getting-started/setup/installation-guides/docker?utm_source=github&utm_medium=organic&utm_campaign=readme&utm_content=badge"> <img src="https://img.shields.io/docker/pulls/appsmith/appsmith-ce?color=4591df&style=for-the-badge"> </a> +<a href="https://www.youtube.com/@appsmith/?sub_confirmation=1" target="_blank"> + <img alt="YouTube Channel Subscribers" src="https://img.shields.io/youtube/channel/subscribers/UCMYwzPG2txS8nR5ZbNY6T5g?color=00FF0&style=for-the-badge"> +</a> +<a href="https://www.youtube.com/@appsmith/?sub_confirmation=1" target="_blank"> + <img alt="YouTube Channel Views" src="https://img.shields.io/youtube/channel/views/UCMYwzPG2txS8nR5ZbNY6T5g?color=00FF0&style=for-the-badge"> +</a> </p> ---
b7b5770a089efb1d55c717b2c965fb74a0d61257
2024-10-24 11:08:28
sneha122
fix: google sheets query getting executed even after changing sheet (#37006)
false
google sheets query getting executed even after changing sheet (#37006)
fix
diff --git a/app/server/appsmith-plugins/googleSheetsPlugin/src/main/java/com/external/constants/ErrorMessages.java b/app/server/appsmith-plugins/googleSheetsPlugin/src/main/java/com/external/constants/ErrorMessages.java index 466b205d2e07..53937354c813 100644 --- a/app/server/appsmith-plugins/googleSheetsPlugin/src/main/java/com/external/constants/ErrorMessages.java +++ b/app/server/appsmith-plugins/googleSheetsPlugin/src/main/java/com/external/constants/ErrorMessages.java @@ -39,6 +39,9 @@ public class ErrorMessages extends BasePluginErrorMessages { public static final String MISSING_ROW_INDEX_ERROR_MSG = "Missing required field 'Row index'"; + public static final String MISSING_SPREADSHEET_URL_SELECTED_SHEETS_ERROR_MSG = + "Missing required field 'Spreadsheet Url'. Please check if your datasource is authorized to use this spreadsheet."; + public static final String UNABLE_TO_CREATE_URI_ERROR_MSG = "Unable to create URI"; public static final String MISSING_VALID_RESPONSE_ERROR_MSG = "Missing a valid response object."; diff --git a/app/server/appsmith-plugins/googleSheetsPlugin/src/main/java/com/external/plugins/GoogleSheetsPlugin.java b/app/server/appsmith-plugins/googleSheetsPlugin/src/main/java/com/external/plugins/GoogleSheetsPlugin.java index e99f97a9fe55..f336d54b8fc2 100644 --- a/app/server/appsmith-plugins/googleSheetsPlugin/src/main/java/com/external/plugins/GoogleSheetsPlugin.java +++ b/app/server/appsmith-plugins/googleSheetsPlugin/src/main/java/com/external/plugins/GoogleSheetsPlugin.java @@ -51,7 +51,7 @@ import static com.appsmith.external.helpers.PluginUtils.getDataValueSafelyFromFormData; import static com.appsmith.external.helpers.PluginUtils.setDataValueSafelyInFormData; import static com.appsmith.external.helpers.PluginUtils.validConfigurationPresentInFormData; -import static com.external.utils.SheetsUtil.getUserAuthorizedSheetIds; +import static com.external.utils.SheetsUtil.validateAndGetUserAuthorizedSheetIds; import static java.lang.Boolean.TRUE; @Slf4j @@ -175,7 +175,8 @@ public Mono<ActionExecutionResult> executeCommon( // This will get list of authorised sheet ids from datasource config, and transform execution response to // contain only authorised files - final Set<String> userAuthorizedSheetIds = getUserAuthorizedSheetIds(datasourceConfiguration); + final Set<String> userAuthorizedSheetIds = + validateAndGetUserAuthorizedSheetIds(datasourceConfiguration, methodConfig); // Triggering the actual REST API call return executionMethod @@ -338,7 +339,8 @@ public Mono<TriggerResultDTO> trigger( // This will get list of authorised sheet ids from datasource config, and transform trigger response to // contain only authorised files - Set<String> userAuthorizedSheetIds = getUserAuthorizedSheetIds(datasourceConfiguration); + Set<String> userAuthorizedSheetIds = + validateAndGetUserAuthorizedSheetIds(datasourceConfiguration, methodConfig); return triggerMethod .getTriggerClient(client, methodConfig) 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 90b1e17698db..ee8506e3dfea 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 @@ -1,7 +1,11 @@ package com.external.utils; +import com.appsmith.external.exceptions.pluginExceptions.AppsmithPluginError; +import com.appsmith.external.exceptions.pluginExceptions.AppsmithPluginException; import com.appsmith.external.models.DatasourceConfiguration; import com.appsmith.external.models.OAuth2; +import com.external.config.MethodConfig; +import com.external.constants.ErrorMessages; import com.external.enums.GoogleSheetMethodEnum; import com.fasterxml.jackson.databind.JsonNode; @@ -17,8 +21,10 @@ 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; - public static Set<String> getUserAuthorizedSheetIds(DatasourceConfiguration datasourceConfiguration) { + public static Set<String> validateAndGetUserAuthorizedSheetIds( + DatasourceConfiguration datasourceConfiguration, MethodConfig methodConfig) { OAuth2 oAuth2 = (OAuth2) datasourceConfiguration.getAuthentication(); + Set<String> userAuthorisedSheetIds = null; if (!isEmpty(datasourceConfiguration.getProperties()) && datasourceConfiguration.getProperties().size() > 1 && datasourceConfiguration.getProperties().get(USER_AUTHORIZED_SHEET_IDS_INDEX) != null @@ -33,9 +39,23 @@ public static Set<String> getUserAuthorizedSheetIds(DatasourceConfiguration data .getProperties() .get(USER_AUTHORIZED_SHEET_IDS_INDEX) .getValue(); - return new HashSet<String>(temp); + userAuthorisedSheetIds = new HashSet<String>(temp); + + // This is added specifically for selected gsheets, so that whenever authorisation changes from one sheet to + // another + // We throw an error, this is done because when we use drive.file scope which is for selected sheets through + // file picker + // The access token for this scope grants access to all selected sheets across datasources + // we want to constraint the access for datasource to the sheet which was selected during ds authorisation + if (methodConfig != null + && methodConfig.getSpreadsheetId() != null + && !userAuthorisedSheetIds.contains(methodConfig.getSpreadsheetId())) { + throw new AppsmithPluginException( + AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, + ErrorMessages.MISSING_SPREADSHEET_URL_SELECTED_SHEETS_ERROR_MSG); + } } - return null; + return userAuthorisedSheetIds; } public static Map<String, String> getSpreadsheetData( diff --git a/app/server/appsmith-plugins/googleSheetsPlugin/src/test/java/com/external/config/SheetsUtilTest.java b/app/server/appsmith-plugins/googleSheetsPlugin/src/test/java/com/external/config/SheetsUtilTest.java index 1b5d7856880a..c99f3f2ecd6f 100644 --- a/app/server/appsmith-plugins/googleSheetsPlugin/src/test/java/com/external/config/SheetsUtilTest.java +++ b/app/server/appsmith-plugins/googleSheetsPlugin/src/test/java/com/external/config/SheetsUtilTest.java @@ -1,22 +1,22 @@ package com.external.config; +import com.appsmith.external.exceptions.pluginExceptions.AppsmithPluginException; import com.appsmith.external.models.DatasourceConfiguration; import com.appsmith.external.models.OAuth2; import com.appsmith.external.models.Property; +import com.external.constants.ErrorMessages; import com.external.utils.SheetsUtil; import com.fasterxml.jackson.core.JsonProcessingException; import org.junit.jupiter.api.Test; -import java.util.ArrayList; -import java.util.List; -import java.util.Set; +import java.util.*; -import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.*; public class SheetsUtilTest { @Test - public void testGetUserAuthorizedSheetIds_allsheets_returnsNull() throws JsonProcessingException { + public void testValidateAndGetUserAuthorizedSheetIds_allsheets_returnsNull() throws JsonProcessingException { DatasourceConfiguration dsConfig = new DatasourceConfiguration(); List<Property> propList = new ArrayList<Property>(); Property prop = new Property(); @@ -24,12 +24,13 @@ public void testGetUserAuthorizedSheetIds_allsheets_returnsNull() throws JsonPro prop.setValue("test_email"); propList.add(prop); dsConfig.setProperties(propList); - Set<String> result = SheetsUtil.getUserAuthorizedSheetIds(dsConfig); - assertEquals(result, null); + Set<String> result = SheetsUtil.validateAndGetUserAuthorizedSheetIds(dsConfig, null); + assertEquals(null, result); } @Test - public void testGetUserAuthorizedSheetIds_specificSheets_returnsSetOfFileIds() throws JsonProcessingException { + public void testValidateAndGetUserAuthorizedSheetIds_specificSheets_returnsSetOfFileIds() + throws JsonProcessingException { DatasourceConfiguration dsConfig = new DatasourceConfiguration(); List<Property> propList = new ArrayList<Property>(); OAuth2 oAuth2 = new OAuth2(); @@ -47,7 +48,92 @@ public void testGetUserAuthorizedSheetIds_specificSheets_returnsSetOfFileIds() t propList.add(prop2); dsConfig.setProperties(propList); - Set<String> result = SheetsUtil.getUserAuthorizedSheetIds(dsConfig); - assertEquals(result.size(), 1); + Set<String> result = SheetsUtil.validateAndGetUserAuthorizedSheetIds(dsConfig, null); + assertEquals(1, result.size()); + } + + @Test + public void testValidateAndGetUserAuthorizedSheetIds_invalidSpecificSheets_throwsException() { + DatasourceConfiguration dsConfig = new DatasourceConfiguration(); + List<Property> propList = new ArrayList<>(); + OAuth2 oAuth2 = new OAuth2(); + + oAuth2.setScopeString("https://www.googleapis.com/auth/drive.file"); + dsConfig.setAuthentication(oAuth2); + + Property prop1 = new Property("emailAddress", "test_email"); + propList.add(prop1); + + List<String> ids = new ArrayList<>(); + ids.add("id1"); + + Property prop2 = new Property("userAuthorizedSheetIds", ids); + propList.add(prop2); + + dsConfig.setProperties(propList); + + // Create formData map with only the spreadsheetUrl + Map<String, Object> formData = new HashMap<>(); + Map<String, Object> spreadsheetUrlData = new HashMap<>(); + spreadsheetUrlData.put("data", "https://docs.google.com/spreadsheets/d/id2"); + formData.put("sheetUrl", spreadsheetUrlData); + + MethodConfig methodConfig = new MethodConfig(formData); + + AppsmithPluginException exception = assertThrows(AppsmithPluginException.class, () -> { + SheetsUtil.validateAndGetUserAuthorizedSheetIds(dsConfig, methodConfig); + }); + + String expectedErrorMessage = ErrorMessages.MISSING_SPREADSHEET_URL_SELECTED_SHEETS_ERROR_MSG; + assertEquals(expectedErrorMessage, exception.getMessage()); + } + + @Test + public void testValidateAndGetUserAuthorizedSheetIds_validSpecificSheets_returnsAuthorisedSheetIds() { + DatasourceConfiguration dsConfig = new DatasourceConfiguration(); + List<Property> propList = new ArrayList<>(); + OAuth2 oAuth2 = new OAuth2(); + + oAuth2.setScopeString("https://www.googleapis.com/auth/drive.file"); + dsConfig.setAuthentication(oAuth2); + + Property prop1 = new Property("emailAddress", "test_email"); + propList.add(prop1); + + List<String> ids = new ArrayList<>(); + ids.add("id1"); + + Property prop2 = new Property("userAuthorizedSheetIds", ids); + propList.add(prop2); + + dsConfig.setProperties(propList); + + // Create formData map with the spreadsheetUrl + Map<String, Object> formData = new HashMap<>(); + Map<String, Object> spreadsheetUrlData = new HashMap<>(); + spreadsheetUrlData.put("data", "https://docs.google.com/spreadsheets/d/id1"); + formData.put("sheetUrl", spreadsheetUrlData); + + MethodConfig methodConfig = new MethodConfig(formData); + + Set<String> result = SheetsUtil.validateAndGetUserAuthorizedSheetIds(dsConfig, methodConfig); + + assertEquals(1, result.size()); + assertTrue(result.contains("id1")); + } + + @Test + public void testValidateAndGetUserAuthorizedSheetIds_allSheets_returnsNull() { + DatasourceConfiguration dsConfig = new DatasourceConfiguration(); + OAuth2 oAuth2 = new OAuth2(); + + oAuth2.setScopeString("https://www.googleapis.com/auth/drive,https://www.googleapis.com/auth/spreadsheets"); + dsConfig.setAuthentication(oAuth2); + + // Not adding any properties to dsConfig + + Set<String> result = SheetsUtil.validateAndGetUserAuthorizedSheetIds(dsConfig, null); + + assertNull(result); } }
8428990ceec06fb51f02fe24a2a7d3ff308f0042
2021-07-26 13:30:27
Snyk bot
fix: app/server/appsmith-interfaces/pom.xml to reduce vulnerabilities (#6063)
false
app/server/appsmith-interfaces/pom.xml to reduce vulnerabilities (#6063)
fix
diff --git a/app/server/appsmith-interfaces/pom.xml b/app/server/appsmith-interfaces/pom.xml index f6b5510ac3a6..439d2e11da8a 100644 --- a/app/server/appsmith-interfaces/pom.xml +++ b/app/server/appsmith-interfaces/pom.xml @@ -79,7 +79,7 @@ <dependency> <groupId>com.querydsl</groupId> <artifactId>querydsl-mongodb</artifactId> - <version>4.2.2</version> + <version>5.0.0</version> </dependency> <dependency> <groupId>com.querydsl</groupId> @@ -90,7 +90,7 @@ <dependency> <groupId>com.querydsl</groupId> <artifactId>querydsl-jpa</artifactId> - <version>4.2.2</version> + <version>5.0.0</version> </dependency> <dependency> <groupId>org.apache.commons</groupId>
53e3890066a5133967f2ae3925d120b729662aac
2023-07-21 18:19:28
Saroj
ci: Fix for artifact name to download (#25599)
false
Fix for artifact name to download (#25599)
ci
diff --git a/.github/workflows/ci-test-custom-script.yml b/.github/workflows/ci-test-custom-script.yml index 306428f4fee5..cb6adc6da34e 100644 --- a/.github/workflows/ci-test-custom-script.yml +++ b/.github/workflows/ci-test-custom-script.yml @@ -87,11 +87,13 @@ jobs: run: echo "$STEPS_CONTEXT" # In case this is second attempt try restoring failed tests + - if : steps.run_result.outputs.run_result == 'failedtest' + run: echo "failed_spec_artifact=failed-spec-ci-$((${{github.run_attempt}}-1))" >> $GITHUB_ENV - name: Restore the previous failed combine result if: steps.run_result.outputs.run_result == 'failedtest' uses: actions/download-artifact@v3 with: - name: failed-spec-ci-$((${{github.run_attempt}}-1)) + name: ${{ env.failed_spec_artifact }} path: ~/failed_spec_ci # failed_spec_env will contain list of all failed specs
95e4525ecbf64bf656b11bea3d77904be945ca26
2023-10-24 12:13:37
arunvjn
fix: Removes platform functions from autocomplete list in data fields (#28217)
false
Removes platform functions from autocomplete list in data fields (#28217)
fix
diff --git a/app/client/cypress/e2e/Regression/ClientSide/Autocomplete/Autocomplete_setters_spec.ts b/app/client/cypress/e2e/Regression/ClientSide/Autocomplete/Autocomplete_setters_spec.ts index a3826f622b5a..2f23daf1c4fa 100644 --- a/app/client/cypress/e2e/Regression/ClientSide/Autocomplete/Autocomplete_setters_spec.ts +++ b/app/client/cypress/e2e/Regression/ClientSide/Autocomplete/Autocomplete_setters_spec.ts @@ -40,22 +40,22 @@ describe("Autocomplete tests for setters", () => { agHelper.GetElementsNAssertTextPresence( locators._hints, - "Button1.setColor()", + "Button1.setColor", ); agHelper.GetElementsNAssertTextPresence( locators._hints, - "Button1.setDisabled()", + "Button1.setDisabled", ); agHelper.GetElementsNAssertTextPresence( locators._hints, - "Button1.setVisibility()", + "Button1.setVisibility", ); agHelper.RemoveCharsNType(locators._codeMirrorTextArea, 7, "Input1.set"); - agHelper.GetElementsNAssertTextPresence(locators._hints, "setValue()"); - agHelper.GetElementsNAssertTextPresence(locators._hints, "setDisabled()"); - agHelper.GetElementsNAssertTextPresence(locators._hints, "setVisibility()"); + agHelper.GetElementsNAssertTextPresence(locators._hints, "setValue"); + agHelper.GetElementsNAssertTextPresence(locators._hints, "setDisabled"); + agHelper.GetElementsNAssertTextPresence(locators._hints, "setVisibility"); agHelper.RemoveCharsNType( locators._codeMirrorTextArea, @@ -63,14 +63,14 @@ describe("Autocomplete tests for setters", () => { "Checkbox1.set", ); - agHelper.GetElementsNAssertTextPresence(locators._hints, "setValue()"); - agHelper.GetElementsNAssertTextPresence(locators._hints, "setDisabled()"); - agHelper.GetElementsNAssertTextPresence(locators._hints, "setVisibility()"); + agHelper.GetElementsNAssertTextPresence(locators._hints, "setValue"); + agHelper.GetElementsNAssertTextPresence(locators._hints, "setDisabled"); + agHelper.GetElementsNAssertTextPresence(locators._hints, "setVisibility"); agHelper.RemoveCharsNType(locators._codeMirrorTextArea, 13, "Switch1.set"); - agHelper.GetElementsNAssertTextPresence(locators._hints, "setDisabled()"); - agHelper.GetElementsNAssertTextPresence(locators._hints, "setRequired()"); + agHelper.GetElementsNAssertTextPresence(locators._hints, "setDisabled"); + agHelper.GetElementsNAssertTextPresence(locators._hints, "setRequired"); agHelper.Sleep(); //a bit for time for CI }); @@ -78,6 +78,6 @@ describe("Autocomplete tests for setters", () => { entityExplorer.DragDropWidgetNVerify(draggableWidgets.INPUT_V2, 500, 500); entityExplorer.SelectEntityByName("Button1"); propPane.EnterJSContext("onClick", "{{Input1.set", true, false); - agHelper.GetElementsNAssertTextPresence(locators._hints, "setDisabled()"); + agHelper.GetElementsNAssertTextPresence(locators._hints, "setDisabled"); }); }); diff --git a/app/client/cypress/e2e/Regression/ClientSide/Autocomplete/JS_AC1_spec.ts b/app/client/cypress/e2e/Regression/ClientSide/Autocomplete/JS_AC1_spec.ts index 0a46d4af6861..73a39e410622 100644 --- a/app/client/cypress/e2e/Regression/ClientSide/Autocomplete/JS_AC1_spec.ts +++ b/app/client/cypress/e2e/Regression/ClientSide/Autocomplete/JS_AC1_spec.ts @@ -130,22 +130,22 @@ describe("Autocomplete tests", () => { // eval function verification { type: "eval", - expected: "eval()", + expected: "eval", haveOrNotHave: false, }, { type: "Blob", - expected: "Blob()", + expected: "Blob", haveOrNotHave: true, }, { type: "FormData", - expected: "FormData()", + expected: "FormData", haveOrNotHave: true, }, { type: "FileReader", - expected: "FileReader()", + expected: "FileReader", haveOrNotHave: true, }, ]; @@ -167,7 +167,7 @@ describe("Autocomplete tests", () => { agHelper.GetNClick(jsEditor._lineinJsEditor(5)); agHelper.TypeText(locators._codeMirrorTextArea, "this."); - ["myFun2()", "myVar1", "myVar2"].forEach((element, index) => { + ["myFun2", "myVar1", "myVar2"].forEach((element, index) => { agHelper.AssertContains(element); }); }); diff --git a/app/client/cypress/e2e/Regression/ClientSide/Autocomplete/JS_AC2_spec.ts b/app/client/cypress/e2e/Regression/ClientSide/Autocomplete/JS_AC2_spec.ts index 23a1c1b117d4..2b9839205cad 100644 --- a/app/client/cypress/e2e/Regression/ClientSide/Autocomplete/JS_AC2_spec.ts +++ b/app/client/cypress/e2e/Regression/ClientSide/Autocomplete/JS_AC2_spec.ts @@ -49,7 +49,7 @@ describe("Autocomplete tests", () => { 0, ); - agHelper.GetNAssertElementText(locators._hints, "myFun1()", "have.text", 4); + agHelper.GetNAssertElementText(locators._hints, "myFun1", "have.text", 4); // Same check in JSObject1 entityExplorer.SelectEntityByName("JSObject1", "Queries/JS"); @@ -65,7 +65,7 @@ describe("Autocomplete tests", () => { 0, ); - agHelper.GetNAssertElementText(locators._hints, "myFun1()", "have.text", 4); + agHelper.GetNAssertElementText(locators._hints, "myFun1", "have.text", 4); entityExplorer.ActionContextMenuByEntityName({ entityNameinLeftSidebar: "JSObject1", action: "Delete", diff --git a/app/client/cypress/e2e/Regression/ClientSide/IDE/MaintainContext&Focus_spec.js b/app/client/cypress/e2e/Regression/ClientSide/IDE/MaintainContext&Focus_spec.js index 2dafa2f92f4d..ce72d9ea7e54 100644 --- a/app/client/cypress/e2e/Regression/ClientSide/IDE/MaintainContext&Focus_spec.js +++ b/app/client/cypress/e2e/Regression/ClientSide/IDE/MaintainContext&Focus_spec.js @@ -214,7 +214,7 @@ describe("MaintainContext&Focus", function () { cy.assertCursorOnCodeInput(".js-editor", { ch: 2, line: 4 }); cy.get(locators._codeMirrorTextArea).type("showA"); - agHelper.GetNAssertElementText(locators._hints, "showAlert()"); + agHelper.GetNAssertElementText(locators._hints, "showAlert"); agHelper.PressEscape(); cy.assertCursorOnCodeInput(".js-editor", { ch: 7, line: 4 }); diff --git a/app/client/cypress/e2e/Regression/ClientSide/Widgets/Others/Autocomplete_spec.js b/app/client/cypress/e2e/Regression/ClientSide/Widgets/Others/Autocomplete_spec.js index f3783c3532d8..8ab713e68d9a 100644 --- a/app/client/cypress/e2e/Regression/ClientSide/Widgets/Others/Autocomplete_spec.js +++ b/app/client/cypress/e2e/Regression/ClientSide/Widgets/Others/Autocomplete_spec.js @@ -65,13 +65,13 @@ describe("Autocomplete using slash command and mustache tests", function () { // validates all autocomplete functions on entering {{}} in onClick field cy.get(`${dynamicInputLocators.hints} li`) .eq(7) - .should("have.text", "storeValue()"); + .should("have.text", "storeValue"); cy.get(`${dynamicInputLocators.hints} li`) .eq(8) - .should("have.text", "showAlert()"); + .should("have.text", "showAlert"); cy.get(`${dynamicInputLocators.hints} li`) .eq(9) - .should("have.text", "navigateTo()"); + .should("have.text", "navigateTo"); }); }); @@ -147,83 +147,32 @@ describe("Autocomplete using slash command and mustache tests", function () { ); it("Bug 9003: Autocomplete not working for Appsmith specific JS APIs", function () { - cy.openPropertyPane("buttonwidget"); - cy.get(".t--property-control-onclick") - .find(".t--js-toggle") - .click({ force: true }); - cy.EnableAllCodeEditors(); - cy.get(".CodeMirror textarea") - .last() - .focus() - .clear() - .type("{{re") - .then(() => { - cy.get(dynamicInputLocators.hints).should("exist"); - // validates autocomplete suggestion for resetWidget() in onClick field - cy.get(`${dynamicInputLocators.hints} li`) - .eq(0) - .should("have.text", "removeValue()"); - cy.get(`${dynamicInputLocators.hints} li`) - .eq(1) - .should("have.text", "resetWidget()"); - }); - cy.EnableAllCodeEditors(); - cy.get(".CodeMirror textarea") - .last() - .focus() - // clearing the onClick field - .type("{ctrl}{shift}{uparrow}", { parseSpecialCharSequences: true }) - .type("{backspace}", { parseSpecialCharSequences: true }) - .type("{rightarrow}{rightarrow}", { parseSpecialCharSequences: true }) - .type("{ctrl}{shift}{uparrow}", { parseSpecialCharSequences: true }) - .type("{backspace}", { parseSpecialCharSequences: true }) - .type("{{s") - .then(() => { - cy.get(dynamicInputLocators.hints).should("exist"); - // validates autocomplete function suggestions on entering '{{s' in onClick field - cy.get(`${dynamicInputLocators.hints} li`) - .should("contain.text", "storeValue()") - .and("contain.text", "showModal()") - .and("contain.text", "setInterval()") - .and("contain.text", "showAlert()"); - }); - cy.EnableAllCodeEditors(); - cy.get(".CodeMirror textarea") - .last() - .focus() - // clearing the onClick field - .type("{ctrl}{shift}{uparrow}", { parseSpecialCharSequences: true }) - .type("{backspace}", { parseSpecialCharSequences: true }) - .type("{rightarrow}{rightarrow}", { parseSpecialCharSequences: true }) - .type("{ctrl}{shift}{uparrow}", { parseSpecialCharSequences: true }) - .type("{backspace}", { parseSpecialCharSequences: true }) - .type("{{c") - .then(() => { - cy.get(dynamicInputLocators.hints).should("exist"); - // validates autocomplete function suggestions on entering '{{c' in onClick field - cy.get(`${dynamicInputLocators.hints} li`) - .should("contain.text", "closeModal()") - .and("contain.text", "copyToClipboard()") - .and("contain.text", "clearInterval()") - .and("contain.text", "clearStore()"); - }); - cy.EnableAllCodeEditors(); - cy.get(".CodeMirror textarea") - .last() - .focus() - .type("{ctrl}{shift}{uparrow}", { parseSpecialCharSequences: true }) - .type("{backspace}", { parseSpecialCharSequences: true }) - .type("{rightarrow}{rightarrow}", { parseSpecialCharSequences: true }) - .type("{ctrl}{shift}{uparrow}", { parseSpecialCharSequences: true }) - .type("{backspace}", { parseSpecialCharSequences: true }) - .type("{{n") - .then(() => { - cy.get(dynamicInputLocators.hints).should("exist"); - // validates autocomplete suggestions on entering '{{n' in onClick field - cy.get(`${dynamicInputLocators.hints} li`).should( - "contain.text", - "navigateTo()", - ); - }); + _.entityExplorer.SelectEntityByName("Button1", "Widgets"); + _.propPane.ToggleJSMode("onClick", true); + _.propPane.TypeTextIntoField("onClick", "{{storeValue", true); + _.agHelper.GetNAssertElementText(_.locators._hints, "storeValue"); + _.propPane.TypeTextIntoField("onClick", "{{removeValue", true); + _.agHelper.GetNAssertElementText(_.locators._hints, "removeValue"); + _.propPane.TypeTextIntoField("onClick", "{{showAlert", true); + _.agHelper.GetNAssertElementText(_.locators._hints, "showAlert"); + _.propPane.TypeTextIntoField("onClick", "{{setInterval", true); + _.agHelper.GetNAssertElementText(_.locators._hints, "setInterval"); + _.propPane.TypeTextIntoField("onClick", "{{setTimeout", true); + _.agHelper.GetNAssertElementText(_.locators._hints, "setTimeout"); + _.propPane.TypeTextIntoField("onClick", "{{resetWidget", true); + _.agHelper.GetNAssertElementText(_.locators._hints, "resetWidget"); + _.propPane.TypeTextIntoField("onClick", "{{showModal", true); + _.agHelper.GetNAssertElementText(_.locators._hints, "showModal"); + _.propPane.TypeTextIntoField("onClick", "{{copyToClipboard", true); + _.agHelper.GetNAssertElementText(_.locators._hints, "copyToClipboard"); + _.propPane.TypeTextIntoField("onClick", "{{closeModal", true); + _.agHelper.GetNAssertElementText(_.locators._hints, "closeModal"); + _.propPane.TypeTextIntoField("onClick", "{{Text1.setDisabled", true); + _.agHelper.GetNAssertElementText(_.locators._hints, "setDisabled"); + + _.propPane.TypeTextIntoField("Label", "{{storeValue", true); + _.agHelper.AssertElementAbsence(_.locators._hints); + _.propPane.TypeTextIntoField("Label", "{{Text1.setDisabled", true); + _.agHelper.AssertElementAbsence(_.locators._hints); }); }); diff --git a/app/client/src/ce/utils/autocomplete/EntityDefinitions.ts b/app/client/src/ce/utils/autocomplete/EntityDefinitions.ts index a8d393dcf54a..cc2eb104e210 100644 --- a/app/client/src/ce/utils/autocomplete/EntityDefinitions.ts +++ b/app/client/src/ce/utils/autocomplete/EntityDefinitions.ts @@ -57,8 +57,8 @@ export const entityDefinitions = { "!doc": "The response meta of the action", "!type": "?", }, - run: "fn(params: ?) -> +Promise[:t=[!0.<i>.:t]]", - clear: "fn() -> +Promise[:t=[!0.<i>.:t]]", + run: "fn(params: ?) -> +Promise", + clear: "fn() -> +Promise", }; }, }; @@ -101,45 +101,43 @@ export const GLOBAL_FUNCTIONS = { navigateTo: { "!doc": "Action to navigate the user to another page or url", "!type": - "fn(pageNameOrUrl: string, params: {}, target?: string) -> +Promise[:t=[!0.<i>.:t]]", + "fn(pageNameOrUrl: string, params: {}, target?: string) -> +Promise", }, showAlert: { "!doc": "Show a temporary notification style message to the user", - "!type": "fn(message: string, style: string) -> +Promise[:t=[!0.<i>.:t]]", + "!type": "fn(message: string, style: string) -> +Promise", }, showModal: { "!doc": "Open a modal", - "!type": "fn(modalName: string) -> +Promise[:t=[!0.<i>.:t]]", + "!type": "fn(modalName: string) -> +Promise", }, closeModal: { "!doc": "Close a modal", - "!type": "fn(modalName: string) -> +Promise[:t=[!0.<i>.:t]]", + "!type": "fn(modalName: string) -> +Promise", }, storeValue: { "!doc": "Store key value data locally", - "!type": "fn(key: string, value: any) -> +Promise[:t=[!0.<i>.:t]]", + "!type": "fn(key: string, value: any) -> +Promise", }, removeValue: { "!doc": "Remove key value data locally", - "!type": "fn(key: string) -> +Promise[:t=[!0.<i>.:t]]", + "!type": "fn(key: string) -> +Promise", }, clearStore: { "!doc": "Clear all key value data locally", - "!type": "fn() -> +Promise[:t=[!0.<i>.:t]]", + "!type": "fn() -> +Promise", }, download: { "!doc": "Download anything as a file", - "!type": - "fn(data: any, fileName: string, fileType?: string) -> +Promise[:t=[!0.<i>.:t]]", + "!type": "fn(data: any, fileName: string, fileType?: string) -> +Promise", }, copyToClipboard: { "!doc": "Copy text to clipboard", - "!type": "fn(data: string, options: object) -> +Promise[:t=[!0.<i>.:t]]", + "!type": "fn(data: string, options: object) -> +Promise", }, resetWidget: { "!doc": "Reset widget values", - "!type": - "fn(widgetName: string, resetChildren: boolean) -> +Promise[:t=[!0.<i>.:t]]", + "!type": "fn(widgetName: string, resetChildren: boolean) -> +Promise", }, setInterval: { "!doc": "Execute triggers at a given interval", diff --git a/app/client/src/components/editorComponents/CodeEditor/EditorConfig.ts b/app/client/src/components/editorComponents/CodeEditor/EditorConfig.ts index e37c6ed70000..a146df613dba 100644 --- a/app/client/src/components/editorComponents/CodeEditor/EditorConfig.ts +++ b/app/client/src/components/editorComponents/CodeEditor/EditorConfig.ts @@ -58,6 +58,7 @@ export interface FieldEntityInformation { entityType?: ENTITY_TYPE; entityId?: string; propertyPath?: string; + isTriggerPath?: boolean; blockCompletions?: Array<{ parentPath: string; subPath: string }>; example?: ExpectedValueExample; mode?: TEditorModes; diff --git a/app/client/src/components/editorComponents/CodeEditor/index.tsx b/app/client/src/components/editorComponents/CodeEditor/index.tsx index 38f31c43517e..65cd5df06fd7 100644 --- a/app/client/src/components/editorComponents/CodeEditor/index.tsx +++ b/app/client/src/components/editorComponents/CodeEditor/index.tsx @@ -1261,36 +1261,32 @@ class CodeEditor extends Component<Props, State> { expectedType: expected?.autocompleteDataType, example: expected?.example, mode: this.props.mode, + isTriggerPath: false, }; - if (dataTreePath) { - const { entityName, propertyPath } = - getEntityNameAndPropertyPath(dataTreePath); - entityInformation.entityName = entityName; - const entity = configTree[entityName]; - - if (entity) { - if ("ENTITY_TYPE" in entity) { - const entityType = entity.ENTITY_TYPE; - if ( - entityType === ENTITY_TYPE_VALUE.WIDGET || - entityType === ENTITY_TYPE_VALUE.ACTION || - entityType === ENTITY_TYPE_VALUE.JSACTION - ) { - entityInformation.entityType = entityType; - } - } - if (isActionEntity(entity)) - entityInformation.entityId = entity.actionId; - if (isWidgetEntity(entity)) { - const isTriggerPath = entity.triggerPaths[propertyPath]; - entityInformation.entityId = entity.widgetId; - if (isTriggerPath) - entityInformation.expectedType = AutocompleteDataType.FUNCTION; - - entityInformation.widgetType = entity.type; - } - } - entityInformation.propertyPath = propertyPath; + if (!dataTreePath) return entityInformation; + + const { entityName, propertyPath } = + getEntityNameAndPropertyPath(dataTreePath); + entityInformation.entityName = entityName; + entityInformation.propertyPath = propertyPath; + + const entity = configTree[entityName]; + if (!entity) return entityInformation; + if (!entity.ENTITY_TYPE) return entityInformation; + const entityType = entity.ENTITY_TYPE; + entityInformation.entityType = entityType; + + if (isActionEntity(entity)) { + entityInformation.entityId = entity.actionId; + } else if (isWidgetEntity(entity)) { + const isTriggerPath = entity.triggerPaths[propertyPath]; + entityInformation.entityId = entity.widgetId; + if (isTriggerPath) + entityInformation.expectedType = AutocompleteDataType.FUNCTION; + entityInformation.isTriggerPath = isTriggerPath; + entityInformation.widgetType = entity.type; + } else { + entityInformation.isTriggerPath = true; } return entityInformation; }; diff --git a/app/client/src/utils/autocomplete/AutocompleteSortRules.ts b/app/client/src/utils/autocomplete/AutocompleteSortRules.ts index 6660373cfa65..74641ee4c2c2 100644 --- a/app/client/src/utils/autocomplete/AutocompleteSortRules.ts +++ b/app/client/src/utils/autocomplete/AutocompleteSortRules.ts @@ -3,13 +3,14 @@ import { DataTreeFunctionSortOrder, PriorityOrder } from "./dataTypeSortRules"; import type { Completion, DataTreeDefEntityInformation, + TernCompletionResult, } from "./CodemirrorTernService"; import { createCompletionHeader } from "./CodemirrorTernService"; import { AutocompleteDataType } from "./AutocompleteDataType"; interface AutocompleteRule { computeScore( - completion: Completion, + completion: Completion<TernCompletionResult>, entityInfo?: FieldEntityInformation, ): number; } @@ -29,7 +30,7 @@ enum RuleWeight { export class NestedPropertyInsideLiteralRule implements AutocompleteRule { computeScore( - completion: Completion, + completion: Completion<TernCompletionResult>, entityInfo: FieldEntityInformation, ): number { const { token } = entityInfo; @@ -49,7 +50,7 @@ export class AndRule implements AutocompleteRule { constructor(rules: AutocompleteRule[]) { this.rules = rules; } - computeScore(completion: Completion): number { + computeScore(completion: Completion<TernCompletionResult>): number { let score = 0; for (const rule of this.rules) { const localScore = rule.computeScore(completion); @@ -71,7 +72,7 @@ export class AndRule implements AutocompleteRule { class HideInternalDefsRule implements AutocompleteRule { static threshold = -Infinity; - computeScore(completion: Completion): number { + computeScore(completion: Completion<TernCompletionResult>): number { let score = 0; if (completion.text.includes("$__") && completion.text.includes("__$")) { @@ -86,10 +87,10 @@ class HideInternalDefsRule implements AutocompleteRule { * Max score - 0 * Min score - -Infinity */ -class BlockSuggestionsRule implements AutocompleteRule { +class RemoveBlackListedCompletionRule implements AutocompleteRule { static threshold = -Infinity; - computeScore(completion: Completion): number { + computeScore(completion: Completion<TernCompletionResult>): number { let score = 0; const { currentFieldInfo } = AutocompleteSorter; const { blockCompletions } = currentFieldInfo; @@ -98,7 +99,7 @@ class BlockSuggestionsRule implements AutocompleteRule { for (let index = 0; index < blockCompletions.length; index++) { const { subPath } = blockCompletions[index]; if (completion.text === subPath && completion.origin !== "DATA_TREE") { - score = BlockSuggestionsRule.threshold; + score = RemoveBlackListedCompletionRule.threshold; break; } } @@ -115,7 +116,7 @@ class BlockSuggestionsRule implements AutocompleteRule { */ class NoDeepNestedSuggestionsRule implements AutocompleteRule { static threshold = -Infinity; - computeScore(completion: Completion): number { + computeScore(completion: Completion<TernCompletionResult>): number { let score = 0; if (completion.text.split(".").length > 2) score = NoDeepNestedSuggestionsRule.threshold; @@ -130,7 +131,7 @@ class NoDeepNestedSuggestionsRule implements AutocompleteRule { */ class NoSelfReferenceRule implements AutocompleteRule { static threshold = -Infinity; - computeScore(completion: Completion): number { + computeScore(completion: Completion<TernCompletionResult>): number { let score = 0; const entityName = AutocompleteSorter.currentFieldInfo.entityName; if (!entityName) return score; @@ -150,7 +151,7 @@ class NoSelfReferenceRule implements AutocompleteRule { */ class GlobalJSRule implements AutocompleteRule { static threshold = 1 << RuleWeight.GlobalJS; - computeScore(completion: Completion): number { + computeScore(completion: Completion<TernCompletionResult>): number { let score = 0; if (completion.origin === "ecmascript" || completion.origin === "base-64") score += GlobalJSRule.threshold; @@ -165,7 +166,7 @@ class GlobalJSRule implements AutocompleteRule { */ class JSLibraryRule implements AutocompleteRule { static threshold = 1 << RuleWeight.JSLibrary; - computeScore(completion: Completion): number { + computeScore(completion: Completion<TernCompletionResult>): number { const score = 0; if (!completion.origin) return score; if (!completion.origin.startsWith("LIB/")) return score; @@ -180,7 +181,7 @@ class JSLibraryRule implements AutocompleteRule { */ class DataTreeFunctionRule implements AutocompleteRule { static threshold = 1 << RuleWeight.DataTreeFunction; - computeScore(completion: Completion): number { + computeScore(completion: Completion<TernCompletionResult>): number { let score = 0; if (!(completion.origin === "DATA_TREE.APPSMITH.FUNCTIONS")) return score; score += DataTreeFunctionRule.threshold; @@ -200,7 +201,7 @@ class DataTreeFunctionRule implements AutocompleteRule { */ class DataTreeRule implements AutocompleteRule { static threshold = 1 << RuleWeight.DataTreeMatch; - computeScore(completion: Completion): number { + computeScore(completion: Completion<TernCompletionResult>): number { let score = 0; if (!(completion.origin === "DATA_TREE")) return score; score = DataTreeRule.threshold; @@ -216,7 +217,7 @@ class DataTreeRule implements AutocompleteRule { */ class TypeMatchRule implements AutocompleteRule { static threshold = 1 << RuleWeight.TypeMatch; - computeScore(completion: Completion): number { + computeScore(completion: Completion<TernCompletionResult>): number { let score = 0; const currentFieldInfo = AutocompleteSorter.currentFieldInfo; if (completion.type === currentFieldInfo.expectedType) @@ -232,7 +233,7 @@ class TypeMatchRule implements AutocompleteRule { */ class PriorityMatchRule implements AutocompleteRule { static threshold = 1 << RuleWeight.PriorityMatch; - computeScore(completion: Completion): number { + computeScore(completion: Completion<TernCompletionResult>): number { let score = 0; const { currentFieldInfo } = AutocompleteSorter; if (!completion.text) return score; @@ -254,7 +255,7 @@ class PriorityMatchRule implements AutocompleteRule { */ class ScopeMatchRule implements AutocompleteRule { static threshold = 1 << RuleWeight.ScopeMatch; - computeScore(completion: Completion): number { + computeScore(completion: Completion<TernCompletionResult>): number { let score = 0; if (completion.origin === "[doc]" || completion.origin === "customDataTree") score += PriorityMatchRule.threshold; @@ -262,12 +263,36 @@ class ScopeMatchRule implements AutocompleteRule { } } +class BlockAsyncFnsInDataFieldRule implements AutocompleteRule { + static threshold = -Infinity; + static blackList = [ + "setTimeout", + "clearTimeout", + "setInterval", + "clearInterval", + ]; + computeScore( + completion: Completion<TernCompletionResult>, + entityInfo?: FieldEntityInformation | undefined, + ): number { + const score = 0; + if (entityInfo?.isTriggerPath) return score; + if (completion.type !== "FUNCTION") return score; + if (!completion.displayText) return score; + const isAsyncFunction = completion.data?.type?.endsWith("Promise"); + if (isAsyncFunction) return BlockAsyncFnsInDataFieldRule.threshold; + if (BlockAsyncFnsInDataFieldRule.blackList.includes(completion.displayText)) + return BlockAsyncFnsInDataFieldRule.threshold; + return score; + } +} + export class AutocompleteSorter { static entityDefInfo: DataTreeDefEntityInformation | undefined; static currentFieldInfo: FieldEntityInformation; static bestMatchEndIndex: number; static sort( - completions: Completion[], + completions: Completion<TernCompletionResult>[], currentFieldInfo: FieldEntityInformation, entityDefInfo?: DataTreeDefEntityInformation, shouldComputeBestMatch = true, @@ -311,6 +336,7 @@ export class AutocompleteSorter { export class ScoredCompletion { score = 0; static rules = [ + new BlockAsyncFnsInDataFieldRule(), new NoDeepNestedSuggestionsRule(), new NoSelfReferenceRule(), new ScopeMatchRule(), @@ -320,14 +346,14 @@ export class ScoredCompletion { new DataTreeFunctionRule(), new JSLibraryRule(), new GlobalJSRule(), - new BlockSuggestionsRule(), + new RemoveBlackListedCompletionRule(), new HideInternalDefsRule(), new NestedPropertyInsideLiteralRule(), ]; - completion: Completion; + completion: Completion<TernCompletionResult>; constructor( - completion: Completion, + completion: Completion<TernCompletionResult>, currentFieldInfo: FieldEntityInformation, ) { this.completion = completion; diff --git a/app/client/src/utils/autocomplete/CodemirrorTernService.ts b/app/client/src/utils/autocomplete/CodemirrorTernService.ts index a191a347e184..bef4722f505a 100644 --- a/app/client/src/utils/autocomplete/CodemirrorTernService.ts +++ b/app/client/src/utils/autocomplete/CodemirrorTernService.ts @@ -1,6 +1,6 @@ /* eslint-disable @typescript-eslint/ban-ts-comment */ // Heavily inspired from https://github.com/codemirror/CodeMirror/blob/master/addon/tern/tern.js -import type { Server, Def } from "tern"; +import type { Server, Def, QueryRegistry } from "tern"; import type { Hint, Hints } from "codemirror"; import type CodeMirror from "codemirror"; import { @@ -25,12 +25,14 @@ const bigDoc = 250; const cls = "CodeMirror-Tern-"; const hintDelay = 1700; -export interface Completion extends Hint { +export interface Completion< + T = { + doc: string; + }, +> extends Hint { origin: string; type: AutocompleteDataType | string; - data: { - doc: string; - }; + data: T; render?: any; isHeader?: boolean; } @@ -51,6 +53,15 @@ interface TernDoc { changed: { to: number; from: number } | null; } +export interface TernCompletionResult { + name: string; + type?: string | undefined; + depth?: number | undefined; + doc?: string | undefined; + url?: string | undefined; + origin?: string | undefined; +} + interface ArgHints { start: CodeMirror.Position; type: { args: any[]; rettype: null | string }; @@ -196,7 +207,12 @@ class CodeMirrorTernService { this.server.deleteDefs(name); } - requestCallback(error: any, data: any, cm: CodeMirror.Editor, resolve: any) { + requestCallback( + error: any, + data: QueryRegistry["completions"]["result"], + cm: CodeMirror.Editor, + resolve: any, + ) { if (error) return this.showError(cm, error); if (data.completions.length === 0) { return this.showError(cm, "No suggestions"); @@ -208,10 +224,12 @@ class CodeMirrorTernService { const query = this.getQueryForAutocomplete(cm); - let completions: Completion[] = []; + let completions: Completion<TernCompletionResult>[] = []; let after = ""; const { end, start } = data; + if (typeof end === "number" || typeof start === "number") return; + const from = { ...start, ch: start.ch + extraChars, @@ -235,31 +253,27 @@ class CodeMirrorTernService { for (let i = 0; i < data.completions.length; ++i) { const completion = data.completions[i]; + if (typeof completion === "string") continue; const isCustomKeyword = isCustomKeywordType(completion.name); - - if (isCustomKeyword) { - completion.isKeyword = true; - } - let className = typeToIcon(completion.type, completion.isKeyword); - const dataType = getDataType(completion.type); - if (data.guess) className += " " + cls + "guess"; + const className = typeToIcon(completion.type as string, isCustomKeyword); + const dataType = getDataType(completion.type as string); let completionText = completion.name + after; if (dataType === "FUNCTION" && !completion.origin?.startsWith("LIB/")) { if (token.type !== "string" && token.string !== "[") { completionText = completionText + "()"; } } - const codeMirrorCompletion: Completion = { + const codeMirrorCompletion: Completion<TernCompletionResult> = { text: completionText, - displayText: completionText, + displayText: completion.name, className: className, data: completion, - origin: completion.origin, + origin: completion.origin as string, type: dataType, isHeader: false, }; - if (completion.isKeyword) { + if (isCustomKeyword) { codeMirrorCompletion.render = ( element: HTMLElement, self: any, @@ -365,7 +379,7 @@ class CodeMirrorTernService { async getHint(cm: CodeMirror.Editor) { const hints: Record<string, any> = await new Promise((resolve) => { - this.request( + this.request<"completions">( cm, { type: "completions", @@ -419,7 +433,7 @@ class CodeMirrorTernService { } showContextInfo(cm: CodeMirror.Editor, queryName: string, callbackFn?: any) { - this.request(cm, { type: queryName }, (error, data) => { + this.request<"type">(cm, { type: queryName }, (error, data) => { if (error) return this.showError(cm, error); const tip = this.elt( "span", @@ -441,10 +455,10 @@ class CodeMirrorTernService { }); } - request( + request<T extends keyof QueryRegistry>( cm: CodeMirror.Editor, query: RequestQuery | string, - callbackFn: (error: any, data: any) => void, + callbackFn: (error: any, data: QueryRegistry[T]["result"]) => void, pos?: CodeMirror.Position, ) { const doc = this.findDoc(cm.getDoc()); @@ -480,11 +494,7 @@ class CodeMirrorTernService { return (this.docs[name] = data); } - buildRequest( - doc: TernDoc, - query: Partial<RequestQuery> | string, - pos?: CodeMirror.Position, - ) { + buildRequest(doc: TernDoc, query: any, pos?: CodeMirror.Position) { const files = []; let offsetLines = 0; if (typeof query == "string") query = { type: query }; @@ -924,7 +934,7 @@ class CodeMirrorTernService { } } -export const createCompletionHeader = (name: string): Completion => ({ +export const createCompletionHeader = (name: string): Completion<any> => ({ text: name, displayText: name, className: "CodeMirror-hint-header", diff --git a/app/client/src/utils/autocomplete/__tests__/AutocompleteSortRules.test.ts b/app/client/src/utils/autocomplete/__tests__/AutocompleteSortRules.test.ts new file mode 100644 index 000000000000..1b79fa7a6023 --- /dev/null +++ b/app/client/src/utils/autocomplete/__tests__/AutocompleteSortRules.test.ts @@ -0,0 +1,190 @@ +import type { FieldEntityInformation } from "components/editorComponents/CodeEditor/EditorConfig"; +import { AutocompleteSorter } from "../AutocompleteSortRules"; +import type { + Completion, + DataTreeDefEntityInformation, + TernCompletionResult, +} from "../CodemirrorTernService"; +import { ENTITY_TYPE_VALUE } from "entities/DataTree/dataTreeFactory"; + +describe("Autocomplete Ranking", () => { + it("Blocks platform functions in data fields", () => { + const completions: unknown[] = [ + { + text: "appsmith", + displayText: "appsmith", + className: + "CodeMirror-Tern-completion CodeMirror-Tern-completion-object", + data: { + name: "appsmith", + type: "appsmith", + origin: "DATA_TREE", + }, + origin: "DATA_TREE", + type: "OBJECT", + isHeader: false, + }, + { + text: "atob()", + displayText: "atob()", + className: "CodeMirror-Tern-completion CodeMirror-Tern-completion-fn", + data: { + name: "atob", + type: "fn(bString: string) -> string", + doc: "decodes a base64 encoded string", + origin: "base64-js", + }, + origin: "base64-js", + type: "FUNCTION", + isHeader: false, + }, + { + text: "APIQuery", + displayText: "APIQuery", + className: + "CodeMirror-Tern-completion CodeMirror-Tern-completion-object", + data: { + name: "APIQuery", + type: "APIQuery", + doc: "Actions allow you to connect your widgets to your backend data in a secure manner.", + url: "https://docs.appsmith.com/reference/appsmith-framework/query-object", + origin: "DATA_TREE", + }, + origin: "DATA_TREE", + type: "OBJECT", + isHeader: false, + }, + { + text: "APIQuery.clear()", + displayText: "APIQuery.clear()", + className: "CodeMirror-Tern-completion CodeMirror-Tern-completion-fn", + data: { + name: "APIQuery.clear", + type: "fn()", + origin: "DATA_TREE", + }, + origin: "DATA_TREE", + type: "FUNCTION", + isHeader: false, + }, + { + text: "APIQuery.data", + displayText: "APIQuery.data", + className: + "CodeMirror-Tern-completion CodeMirror-Tern-completion-unknown", + data: { + name: "APIQuery.data", + type: "?", + doc: "The response of the action", + origin: "DATA_TREE", + }, + origin: "DATA_TREE", + type: "UNKNOWN", + isHeader: false, + }, + { + text: "APIQuery.run()", + displayText: "APIQuery.run()", + className: "CodeMirror-Tern-completion CodeMirror-Tern-completion-fn", + data: { + name: "APIQuery.run", + type: "fn(params: ?)", + origin: "DATA_TREE", + }, + origin: "DATA_TREE", + type: "FUNCTION", + isHeader: false, + }, + { + text: "Array()", + displayText: "Array()", + className: "CodeMirror-Tern-completion CodeMirror-Tern-completion-fn", + data: { + name: "Array", + type: "fn(size: number)", + doc: "The JavaScript Array global object is a constructor for arrays, which are high-level, list-like objects.", + url: "https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array", + origin: "ecmascript", + }, + origin: "ecmascript", + type: "FUNCTION", + isHeader: false, + }, + { + text: "showAlert()", + displayText: "showAlert()", + className: "CodeMirror-Tern-completion CodeMirror-Tern-completion-fn", + data: { + name: "showAlert", + type: "fn(message: string, style: string)", + doc: "Show a temporary notification style message to the user", + origin: "DATA_TREE.APPSMITH.FUNCTIONS", + }, + origin: "DATA_TREE.APPSMITH.FUNCTIONS", + type: "FUNCTION", + isHeader: false, + }, + ]; + const currentFieldInfo: unknown = { + expectedType: "ARRAY", + example: '[{ "name": "John" }]', + mode: "text-js", + entityName: "Table1", + entityType: "WIDGET", + entityId: "xy1ezsr0l5", + widgetType: "TABLE_WIDGET_V2", + propertyPath: "tableData", + token: { + start: 2, + end: 3, + string: "A", + type: "variable", + state: { + outer: true, + innerActive: { + open: "{{", + close: "}}", + delimStyle: "binding-brackets", + mode: { + electricInput: {}, + blockCommentStart: null, + blockCommentEnd: null, + blockCommentContinue: null, + lineComment: null, + fold: "brace", + closeBrackets: "()[]{}''\"\"``", + helperType: "json", + jsonMode: true, + name: "javascript", + }, + }, + inner: { + lastType: "variable", + cc: [null], + lexical: { + indented: -2, + column: 0, + type: "block", + align: false, + }, + indented: 0, + }, + startingInner: false, + }, + }, + }; + const entityInfo: DataTreeDefEntityInformation = { + type: ENTITY_TYPE_VALUE.WIDGET, + subType: "TABLE_WIDGET_V2", + }; + const sortedCompletionsText = AutocompleteSorter.sort( + completions as Completion<TernCompletionResult>[], + currentFieldInfo as FieldEntityInformation, + entityInfo, + true, + ).map((c) => c.displayText); + expect(sortedCompletionsText).not.toEqual( + expect.arrayContaining(["showAlert(), APIQuery.clear(), APIQuery.run()"]), + ); + }); +}); diff --git a/app/client/src/utils/autocomplete/TernServer.test.ts b/app/client/src/utils/autocomplete/__tests__/TernServer.test.ts similarity index 90% rename from app/client/src/utils/autocomplete/TernServer.test.ts rename to app/client/src/utils/autocomplete/__tests__/TernServer.test.ts index 24f4748a475c..3fd61bfbd05f 100644 --- a/app/client/src/utils/autocomplete/TernServer.test.ts +++ b/app/client/src/utils/autocomplete/__tests__/TernServer.test.ts @@ -1,15 +1,15 @@ import type { Completion, DataTreeDefEntityInformation, -} from "./CodemirrorTernService"; +} from "../CodemirrorTernService"; import CodemirrorTernService, { createCompletionHeader, -} from "./CodemirrorTernService"; -import { AutocompleteDataType } from "./AutocompleteDataType"; -import { MockCodemirrorEditor } from "../../../test/__mocks__/CodeMirrorEditorMock"; +} from "../CodemirrorTernService"; +import { AutocompleteDataType } from "../AutocompleteDataType"; +import { MockCodemirrorEditor } from "../../../../test/__mocks__/CodeMirrorEditorMock"; import { ENTITY_TYPE_VALUE } from "entities/DataTree/dataTreeFactory"; import _ from "lodash"; -import { AutocompleteSorter, ScoredCompletion } from "./AutocompleteSortRules"; +import { AutocompleteSorter, ScoredCompletion } from "../AutocompleteSortRules"; describe("Tern server", () => { it("Check whether the correct value is being sent to tern", () => { @@ -204,7 +204,7 @@ describe("Tern server", () => { const value: any = CodemirrorTernService.requestCallback( null, - testCase.input.requestCallbackData, + testCase.input.requestCallbackData as any, MockCodemirrorEditor as unknown as CodeMirror.Editor, () => null, ); @@ -228,13 +228,11 @@ describe("Tern server sorting", () => { }, }; - const sameEntityCompletion: Completion = { + const sameEntityCompletion: Completion<any> = { text: "sameEntity.tableData", type: AutocompleteDataType.ARRAY, origin: "DATA_TREE", - data: { - doc: "", - }, + data: {}, }; defEntityInformation.set("sameEntity", { type: ENTITY_TYPE_VALUE.WIDGET, @@ -245,13 +243,11 @@ describe("Tern server sorting", () => { subType: "TABLE_WIDGET_V2", }); - const priorityCompletion: Completion = { + const priorityCompletion: Completion<any> = { text: "selectedRow", type: AutocompleteDataType.OBJECT, origin: "DATA_TREE", - data: { - doc: "", - }, + data: {}, }; defEntityInformation.set("sameType", { type: ENTITY_TYPE_VALUE.WIDGET, @@ -262,13 +258,11 @@ describe("Tern server sorting", () => { subType: "TABLE_WIDGET_V2", }); - const diffTypeCompletion: Completion = { + const diffTypeCompletion: Completion<any> = { text: "diffType.tableData", type: AutocompleteDataType.ARRAY, origin: "DATA_TREE.WIDGET", - data: { - doc: "", - }, + data: {}, }; defEntityInformation.set("diffType", { @@ -280,13 +274,11 @@ describe("Tern server sorting", () => { subType: "TABLE_WIDGET_V2", }); - const sameTypeDiffEntityTypeCompletion: Completion = { + const sameTypeDiffEntityTypeCompletion: Completion<any> = { text: "diffEntity.data", type: AutocompleteDataType.OBJECT, origin: "DATA_TREE", - data: { - doc: "", - }, + data: {}, }; defEntityInformation.set("diffEntity", { @@ -294,13 +286,11 @@ describe("Tern server sorting", () => { subType: ENTITY_TYPE_VALUE.ACTION, }); - const dataTreeCompletion: Completion = { + const dataTreeCompletion: Completion<any> = { text: "otherDataTree", type: AutocompleteDataType.STRING, origin: "DATA_TREE", - data: { - doc: "", - }, + data: {}, }; defEntityInformation.set("otherDataTree", { @@ -308,40 +298,32 @@ describe("Tern server sorting", () => { subType: "TEXT_WIDGET", }); - const functionCompletion: Completion = { + const functionCompletion: Completion<any> = { text: "otherDataFunction", type: AutocompleteDataType.FUNCTION, origin: "DATA_TREE.APPSMITH.FUNCTIONS", - data: { - doc: "", - }, + data: {}, }; - const ecmascriptCompletion: Completion = { + const ecmascriptCompletion: Completion<any> = { text: "otherJS", type: AutocompleteDataType.OBJECT, origin: "ecmascript", - data: { - doc: "", - }, + data: {}, }; - const libCompletion: Completion = { + const libCompletion: Completion<any> = { text: "libValue", type: AutocompleteDataType.OBJECT, origin: "LIB/lodash", - data: { - doc: "", - }, + data: {}, }; - const unknownCompletion: Completion = { + const unknownCompletion: Completion<any> = { text: "unknownSuggestion", type: AutocompleteDataType.UNKNOWN, origin: "unknown", - data: { - doc: "", - }, + data: {}, }; const completions = [ diff --git a/app/client/src/utils/autocomplete/dataTreeTypeDefCreator.test.ts b/app/client/src/utils/autocomplete/__tests__/dataTreeTypeDefCreator.test.ts similarity index 99% rename from app/client/src/utils/autocomplete/dataTreeTypeDefCreator.test.ts rename to app/client/src/utils/autocomplete/__tests__/dataTreeTypeDefCreator.test.ts index 6437b1459294..d4d1a904de88 100644 --- a/app/client/src/utils/autocomplete/dataTreeTypeDefCreator.test.ts +++ b/app/client/src/utils/autocomplete/__tests__/dataTreeTypeDefCreator.test.ts @@ -14,7 +14,7 @@ import { flattenDef, generateTypeDef, getFunctionsArgsType, -} from "./defCreatorUtils"; +} from "../defCreatorUtils"; describe("dataTreeTypeDefCreator", () => { it("creates the right def for a widget", () => { diff --git a/app/client/src/utils/autocomplete/defCreatorUtils.ts b/app/client/src/utils/autocomplete/defCreatorUtils.ts index 279a37043cab..afe1a82d8633 100644 --- a/app/client/src/utils/autocomplete/defCreatorUtils.ts +++ b/app/client/src/utils/autocomplete/defCreatorUtils.ts @@ -6,6 +6,7 @@ import { isObject, uniqueId } from "lodash"; import type { Def } from "tern"; import { Types, getType } from "utils/TypeHelpers"; import { shouldAddSetter } from "workers/Evaluation/evaluate"; +import { getTernDocType } from "workers/common/JSLibrary/ternDefinitionGenerator"; export type ExtraDef = Record<string, Def | string>; @@ -132,12 +133,12 @@ export function addSettersToDefinitions( setters.forEach((setterName: string) => { const setter = entityConfig.__setters?.[setterName]; - const setterType = entityConfig.__setters?.[setterName].type; + const setterType = getTernDocType( + entityConfig.__setters?.[setterName].type, + ); if (shouldAddSetter(setter, entity)) { - definitions[ - setterName - ] = `fn(value:${setterType}) -> +Promise[:t=[!0.<i>.:t]]`; + definitions[setterName] = `fn(value:${setterType}) -> +Promise`; } }); } diff --git a/app/client/src/utils/autocomplete/keywordCompletion.ts b/app/client/src/utils/autocomplete/keywordCompletion.ts index 4e6a1f5b32e6..7226d9e0d60f 100644 --- a/app/client/src/utils/autocomplete/keywordCompletion.ts +++ b/app/client/src/utils/autocomplete/keywordCompletion.ts @@ -1,7 +1,7 @@ -import type { Completion } from "./CodemirrorTernService"; +import type { Completion, TernCompletionResult } from "./CodemirrorTernService"; export const getCompletionsForKeyword = ( - completion: Completion, + completion: Completion<TernCompletionResult>, cursorHorizontalPos: number, ) => { const keywordName = completion.text; diff --git a/app/client/src/workers/common/JSLibrary/ternDefinitionGenerator.ts b/app/client/src/workers/common/JSLibrary/ternDefinitionGenerator.ts index 051dedc37687..1a5e416a5060 100644 --- a/app/client/src/workers/common/JSLibrary/ternDefinitionGenerator.ts +++ b/app/client/src/workers/common/JSLibrary/ternDefinitionGenerator.ts @@ -1,7 +1,7 @@ import log from "loglevel"; import type { Def } from "tern"; -function getTernDocType(obj: any) { +export function getTernDocType(obj: any) { const type = typeof obj; switch (type) { case "string":
633493ac74bc858f1b9de5cfe0a1fc63fff0b0df
2022-11-01 22:17:45
f0c1s
chore: remove extra feature flags | FE (#18037)
false
remove extra feature flags | FE (#18037)
chore
diff --git a/app/client/src/entities/FeatureFlags.ts b/app/client/src/entities/FeatureFlags.ts index a0dc5758b327..edd8db896726 100644 --- a/app/client/src/entities/FeatureFlags.ts +++ b/app/client/src/entities/FeatureFlags.ts @@ -3,11 +3,8 @@ type FeatureFlags = { JS_EDITOR?: boolean; MULTIPLAYER?: boolean; SNIPPET?: boolean; - GIT?: boolean; - GIT_IMPORT?: boolean; TEMPLATES_PHASE_2?: boolean; RBAC?: boolean; - AUDIT_LOGS?: boolean; CONTEXT_SWITCHING?: boolean; }; diff --git a/app/client/src/pages/Applications/ImportApplicationModal.tsx b/app/client/src/pages/Applications/ImportApplicationModal.tsx index 773780da96c7..555c549315ff 100644 --- a/app/client/src/pages/Applications/ImportApplicationModal.tsx +++ b/app/client/src/pages/Applications/ImportApplicationModal.tsx @@ -20,8 +20,8 @@ import { import { Colors } from "constants/Colors"; import { DialogComponent as Dialog, - FileType, FilePickerV2, + FileType, Icon, IconSize, SetProgress, @@ -34,7 +34,6 @@ import { GitSyncModalTab } from "entities/GitSync"; import { getIsImportingApplication } from "selectors/applicationSelectors"; import { ReduxActionTypes } from "@appsmith/constants/ReduxActionConstants"; import { Classes } from "@blueprintjs/core"; -import { selectFeatureFlags } from "selectors/usersSelectors"; import Statusbar from "pages/Editor/gitSync/components/Statusbar"; import AnalyticsUtil from "utils/AnalyticsUtil"; @@ -86,8 +85,8 @@ const Row = styled.div` } `; -const FileImportCard = styled.div<{ gitEnabled?: boolean }>` - width: ${(props) => (props.gitEnabled ? "320px" : "100%")}; +const FileImportCard = styled.div` + width: 320px; height: 200px; border: 1px solid ${Colors.GREY_4}; display: flex; @@ -232,7 +231,6 @@ function GitImportCard(props: { children?: ReactNode; handler?: () => void }) { } type ImportApplicationModalProps = { - // import?: (file: any) => void; workspaceId?: string; isModalOpen?: boolean; onClose?: () => void; @@ -296,9 +294,6 @@ function ImportApplicationModal(props: ImportApplicationModalProps) { const onRemoveFile = useCallback(() => setAppFileToBeUploaded(null), []); - const featureFlags = useSelector(selectFeatureFlags); - const { GIT_IMPORT: isGitImportFeatureEnabled } = featureFlags; - return ( <StyledDialog canOutsideClickClose @@ -324,10 +319,7 @@ function ImportApplicationModal(props: ImportApplicationModalProps) { </TextWrapper> {!importingApplication && ( <Row> - <FileImportCard - className="t--import-json-card" - gitEnabled={isGitImportFeatureEnabled} - > + <FileImportCard className="t--import-json-card"> <FilePickerV2 containerClickable description={createMessage(IMPORT_APP_FROM_FILE_MESSAGE)} @@ -339,7 +331,7 @@ function ImportApplicationModal(props: ImportApplicationModalProps) { uploadIcon="file-line" /> </FileImportCard> - {isGitImportFeatureEnabled && <GitImportCard handler={onGitImport} />} + <GitImportCard handler={onGitImport} /> </Row> )} {importingApplication && (
c98bbbe6aef3ecc4e5fcae5bb1982f1d80e06401
2021-11-24 10:13:50
Favour Ohanekwu
fix: properly update dependency map (#9169)
false
properly update dependency map (#9169)
fix
diff --git a/app/client/src/workers/DataTreeEvaluator.ts b/app/client/src/workers/DataTreeEvaluator.ts index f0e50aff7b83..df6f8ecca068 100644 --- a/app/client/src/workers/DataTreeEvaluator.ts +++ b/app/client/src/workers/DataTreeEvaluator.ts @@ -450,21 +450,7 @@ export default class DataTreeEvaluator { entityName: string, ): DependencyMap { const dependencies: DependencyMap = {}; - if (isAction(entity) || isWidget(entity)) { - const dynamicBindingPathList = getEntityDynamicBindingPathList(entity); - if (dynamicBindingPathList.length) { - dynamicBindingPathList.forEach((dynamicPath) => { - const propertyPath = dynamicPath.key; - const unevalPropValue = _.get(entity, propertyPath); - const { jsSnippets } = getDynamicBindings(unevalPropValue); - const existingDeps = - dependencies[`${entityName}.${propertyPath}`] || []; - dependencies[`${entityName}.${propertyPath}`] = existingDeps.concat( - jsSnippets.filter((jsSnippet) => !!jsSnippet), - ); - }); - } - } + if (isWidget(entity)) { // Make property dependant on the default property as any time the default changes // the property needs to change @@ -518,6 +504,23 @@ export default class DataTreeEvaluator { }); } } + + if (isAction(entity) || isWidget(entity)) { + const dynamicBindingPathList = getEntityDynamicBindingPathList(entity); + if (dynamicBindingPathList.length) { + dynamicBindingPathList.forEach((dynamicPath) => { + const propertyPath = dynamicPath.key; + const unevalPropValue = _.get(entity, propertyPath); + const { jsSnippets } = getDynamicBindings(unevalPropValue); + const existingDeps = + dependencies[`${entityName}.${propertyPath}`] || []; + dependencies[`${entityName}.${propertyPath}`] = existingDeps.concat( + jsSnippets.filter((jsSnippet) => !!jsSnippet), + ); + }); + } + } + return dependencies; } diff --git a/app/client/src/workers/evaluation.test.ts b/app/client/src/workers/evaluation.test.ts index 043a4d49fa0e..786fe8541b62 100644 --- a/app/client/src/workers/evaluation.test.ts +++ b/app/client/src/workers/evaluation.test.ts @@ -356,16 +356,16 @@ describe("DataTreeEvaluator", () => { Text2: ["Text2.text"], Text3: ["Text3.text"], Text4: ["Text4.text"], - Table1: [ + Table1: expect.arrayContaining([ "Table1.tableData", "Table1.searchText", "Table1.selectedRowIndex", "Table1.selectedRowIndices", - ], - Dropdown1: [ + ]), + Dropdown1: expect.arrayContaining([ "Dropdown1.selectedOptionValue", "Dropdown1.selectedOptionValueArr", - ], + ]), "Text2.text": ["Text1.text"], "Text3.text": ["Text1.text"], "Dropdown1.selectedOptionValue": [],
c7f0b636d8e350f1a927cd5e8a8e4d34087a0338
2023-08-19 07:06:22
NandanAnantharamu
test: updated tests for flaky behaviour (#26395)
false
updated tests for flaky behaviour (#26395)
test
diff --git a/app/client/cypress/e2e/Regression/ClientSide/AppNavigation/TopStacked_spec.ts b/app/client/cypress/e2e/Regression/ClientSide/AppNavigation/TopStacked_spec.ts index f69a203eb856..8e562c3cff51 100644 --- a/app/client/cypress/e2e/Regression/ClientSide/AppNavigation/TopStacked_spec.ts +++ b/app/client/cypress/e2e/Regression/ClientSide/AppNavigation/TopStacked_spec.ts @@ -102,16 +102,18 @@ describe("Test Top + Stacked navigation style", function () { agHelper .GetElement(appSettings.locators._scrollArrows) .first() - .trigger("mousedown"); + .trigger("mousedown", { force: true }); agHelper.Sleep(1500); agHelper .GetElement(appSettings.locators._scrollArrows) .first() .trigger("mouseup", { force: true }); - agHelper - .GetElement(appSettings.locators._navigationMenuItem) - .contains(pageName) - .should("be.visible"); + agHelper.GetNAssertContains( + `${appSettings.locators._navigationMenuItem} span`, + pageName, + "exist", + 0, + ); }); it("4. Navigation's background should be default to white, and should change when background color is set to theme", () => { diff --git a/app/client/cypress/e2e/Regression/ClientSide/Widgets/Sliders/NumberSlider_spec.ts b/app/client/cypress/e2e/Regression/ClientSide/Widgets/Sliders/NumberSlider_spec.ts index f2e54d7da578..19d23fd290fe 100644 --- a/app/client/cypress/e2e/Regression/ClientSide/Widgets/Sliders/NumberSlider_spec.ts +++ b/app/client/cypress/e2e/Regression/ClientSide/Widgets/Sliders/NumberSlider_spec.ts @@ -179,6 +179,7 @@ describe("Number Slider spec", () => { propPane.UpdatePropertyFieldValue("Max. value", "-30"); agHelper.GetElement(locators._sliderThumb).focus().type("{rightArrow}"); + agHelper.Sleep(2000); agHelper .GetText(getWidgetSelector(draggableWidgets.TEXT), "text") .then(($label) => { @@ -188,7 +189,7 @@ describe("Number Slider spec", () => { // Verify in Preview mode negative value agHelper.GetNClick(locators._enterPreviewMode); agHelper.GetElement(locators._sliderThumb).focus().type("{rightArrow}"); - agHelper.Sleep(1000); + agHelper.Sleep(2000); agHelper .GetText(getWidgetSelector(draggableWidgets.TEXT), "text") .then(($label) => { @@ -199,7 +200,7 @@ describe("Number Slider spec", () => { // Verify in Deploy mode negative value deployMode.DeployApp(); agHelper.GetElement(locators._sliderThumb).focus().type("{rightArrow}"); - agHelper.Sleep(1000); + agHelper.Sleep(2000); agHelper .GetText(getWidgetSelector(draggableWidgets.TEXT), "text", 0) .then(($label) => {
4b8e9806efe26c4ba3cc0a67321bd5d8096119e5
2022-10-18 09:45:41
albinAppsmith
fix: removed global style from design system dropdown component (#17392)
false
removed global style from design system dropdown component (#17392)
fix
diff --git a/app/client/package.json b/app/client/package.json index a4d9e3f3f1de..0a1418f2fc91 100644 --- a/app/client/package.json +++ b/app/client/package.json @@ -46,7 +46,7 @@ "cypress-log-to-output": "^1.1.2", "dayjs": "^1.10.6", "deep-diff": "^1.0.2", - "design-system": "npm:@appsmithorg/[email protected]", + "design-system": "npm:@appsmithorg/[email protected]", "downloadjs": "^1.4.7", "draft-js": "^0.11.7", "emoji-mart": "^3.0.1", diff --git a/app/client/yarn.lock b/app/client/yarn.lock index 8602121ac4c5..a3f096cbd73e 100644 --- a/app/client/yarn.lock +++ b/app/client/yarn.lock @@ -6211,10 +6211,10 @@ depd@~1.1.2: version "1.1.2" resolved "https://registry.npmjs.org/depd/-/depd-1.1.2.tgz" -"design-system@npm:@appsmithorg/[email protected]": - version "1.0.27" - resolved "https://registry.yarnpkg.com/@appsmithorg/design-system/-/design-system-1.0.27.tgz#5c30c9d2e336ca993539225009c4cf45b41c1387" - integrity sha512-a/eyZzJY3N9l55w2TjKmt/VgnmC9Sa8jpq1yekta9X3SNKLayfCk4PU7Sjd6p9mJDikZRl+otJWkGKl1pvbtYg== +"design-system@npm:@appsmithorg/[email protected]": + version "1.0.28" + resolved "https://registry.yarnpkg.com/@appsmithorg/design-system/-/design-system-1.0.28.tgz#40ad863ab73b83d960a7f8dfa932c250ea70efc5" + integrity sha512-Dsq2c+s4X64Bq0Q4bVnnmaYnstEFNuqLX6yvjiASmp3kRD46m01DgkI8aAQAMWvNKqAanmmi++QV3jfrUEQJVA== dependencies: "@blueprintjs/datetime" "3.23.6" copy-to-clipboard "^3.3.1"
5b0d701a27da161e36bc8aa8fdf77036fcb7387e
2023-02-20 19:08:33
Shrikant Sharat Kandula
chore: Refactor tenant email param (#20759)
false
Refactor tenant email param (#20759)
chore
diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/UserServiceCE.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/UserServiceCE.java index 5a6e39a68065..68fc61c84cf8 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/UserServiceCE.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/UserServiceCE.java @@ -46,7 +46,7 @@ Mono<? extends User> createNewUserAndSendInviteEmail(String email, String origin Flux<User> getAllByEmails(Set<String> emails, AclPermission permission); - Mono<Map<String, String>> updateTenantLogoInParams(Map<String, String> params); + Mono<Map<String, String>> updateTenantLogoInParams(Map<String, String> params, String origin); Mono<User> updateWithoutPermission(String id, User update); } 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 d9250f1d9c46..830c2e6bf802 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 @@ -257,7 +257,7 @@ public Mono<Boolean> forgotPasswordTokenGenerate(ResetUserPasswordDTO resetUserP Map<String, String> params = new HashMap<>(); params.put("resetUrl", resetUrl); - return updateTenantLogoInParams(params) + return updateTenantLogoInParams(params, resetUserPasswordDTO.getBaseUrl()) .flatMap(updatedParams -> emailSender.sendMail(email, "Appsmith Password Reset", FORGOT_PASSWORD_EMAIL_TEMPLATE, updatedParams) ); @@ -562,7 +562,7 @@ public Mono<User> sendWelcomeEmail(User user, String originHeader) { Map<String, String> params = new HashMap<>(); params.put("primaryLinkUrl", originHeader); - return updateTenantLogoInParams(params) + return updateTenantLogoInParams(params, originHeader) .flatMap(updatedParams -> emailSender.sendMail( user.getEmail(), "Welcome to Appsmith", @@ -645,7 +645,7 @@ public Mono<? extends User> createNewUserAndSendInviteEmail(String email, String Map<String, String> params = getEmailParams(workspace, inviter, inviteUrl, true); // We have sent out the emails. Just send back the saved user. - return updateTenantLogoInParams(params) + return updateTenantLogoInParams(params, originHeader) .flatMap(updatedParams -> emailSender.sendMail(createdUser.getEmail(), "Invite for Appsmith", INVITE_USER_EMAIL_TEMPLATE, updatedParams) ) @@ -790,7 +790,7 @@ public Flux<User> getAllByEmails(Set<String> emails, AclPermission permission) { } @Override - public Mono<Map<String, String>> updateTenantLogoInParams(Map<String, String> params) { + public Mono<Map<String, String>> updateTenantLogoInParams(Map<String, String> params, String origin) { return Mono.just(params); } }
4ebdc73e4fc6b9ac4235613236e95e9351ce02fc
2022-10-13 18:59:20
sneha122
fix: Added frontend validation checks for access token url and url in authenticated API datasource configuration (#17340)
false
Added frontend validation checks for access token url and url in authenticated API datasource configuration (#17340)
fix
diff --git a/app/client/src/ce/constants/messages.ts b/app/client/src/ce/constants/messages.ts index ea5b26f4709a..c67d042db5f0 100644 --- a/app/client/src/ce/constants/messages.ts +++ b/app/client/src/ce/constants/messages.ts @@ -1252,6 +1252,8 @@ export const GENERATE_PAGE = () => "Generate page from data table"; export const GENERATE_PAGE_DESCRIPTION = () => "Start app with a simple CRUD UI and customize it"; export const ADD_PAGE_FROM_TEMPLATE = () => "Add Page From Template"; +export const INVALID_URL = () => + "Please enter a valid URL, for example, https://example.com"; // Alert options and labels for showMessage types export const ALERT_STYLE_OPTIONS = [ diff --git a/app/client/src/components/formControls/BaseControl.tsx b/app/client/src/components/formControls/BaseControl.tsx index 491c42e168e5..d0f1f7bf82d4 100644 --- a/app/client/src/components/formControls/BaseControl.tsx +++ b/app/client/src/components/formControls/BaseControl.tsx @@ -82,6 +82,7 @@ export interface ControlData { sectionName?: string; disabled?: boolean; staticDependencyPathList?: string[]; + validator?: (value: string) => { isValid: boolean; message: string }; } export type FormConfigType = Omit<ControlData, "configProperty"> & { configProperty?: string; diff --git a/app/client/src/components/formControls/InputTextControl.tsx b/app/client/src/components/formControls/InputTextControl.tsx index 89bf722625e1..d16b6cb74b78 100644 --- a/app/client/src/components/formControls/InputTextControl.tsx +++ b/app/client/src/components/formControls/InputTextControl.tsx @@ -32,6 +32,7 @@ export function InputText(props: { encrypted?: boolean; disabled?: boolean; customStyles?: Record<string, any>; + validator?: (value: string) => { isValid: boolean; message: string }; }) { const { dataType, disabled, name, placeholder } = props; @@ -54,6 +55,7 @@ function renderComponent( placeholder: string; dataType?: InputType; disabled?: boolean; + validator?: (value: string) => { isValid: boolean; message: string }; } & { meta: Partial<WrappedFieldMetaProps>; input: Partial<WrappedFieldInputProps>; @@ -68,6 +70,7 @@ function renderComponent( placeholder={props.placeholder} value={props.input.value} {...props.input} + validator={props.validator} width="100%" /> ); @@ -85,6 +88,7 @@ class InputTextControl extends BaseControl<InputControlProps> { propertyValue, subtitle, validationMessage, + validator, } = this.props; return ( @@ -98,6 +102,7 @@ class InputTextControl extends BaseControl<InputControlProps> { placeholder={placeholderText} subtitle={subtitle} validationMessage={validationMessage} + validator={validator} value={propertyValue} /> ); @@ -139,6 +144,7 @@ export interface InputControlProps extends ControlProps { subtitle?: string; encrypted?: boolean; disabled?: boolean; + validator?: (value: string) => { isValid: boolean; message: string }; } export default InputTextControl; diff --git a/app/client/src/pages/Editor/DataSourceEditor/RestAPIDatasourceForm.tsx b/app/client/src/pages/Editor/DataSourceEditor/RestAPIDatasourceForm.tsx index 97e10d4c1dc7..625c8734889d 100644 --- a/app/client/src/pages/Editor/DataSourceEditor/RestAPIDatasourceForm.tsx +++ b/app/client/src/pages/Editor/DataSourceEditor/RestAPIDatasourceForm.tsx @@ -44,6 +44,7 @@ import { createMessage, CONTEXT_DELETE, CONFIRM_CONTEXT_DELETE, + INVALID_URL, } from "@appsmith/constants/messages"; import Collapsible from "./Collapsible"; import _ from "lodash"; @@ -332,6 +333,22 @@ class DatasourceRestAPIEditor extends React.Component< ); }; + urlValidator = (value: string) => { + const validationRegex = "^(http|https)://"; + if (value) { + const regex = new RegExp(validationRegex); + + return regex.test(value) + ? { isValid: true, message: "" } + : { + isValid: false, + message: createMessage(INVALID_URL), + }; + } + + return { isValid: true, message: "" }; + }; + render = () => { return ( <> @@ -440,6 +457,7 @@ class DatasourceRestAPIEditor extends React.Component< "TEXT", false, true, + this.urlValidator, )} </FormInputContainer> <FormInputContainer data-replay-id={btoa("headers")}> @@ -785,6 +803,7 @@ class DatasourceRestAPIEditor extends React.Component< "TEXT", false, false, + this.urlValidator, )} </FormInputContainer> <FormInputContainer data-replay-id={btoa("authentication.clientId")}> @@ -1030,6 +1049,7 @@ class DatasourceRestAPIEditor extends React.Component< dataType: "TEXT" | "PASSWORD" | "NUMBER", encrypted: boolean, isRequired: boolean, + fieldValidator?: (value: string) => { isValid: boolean; message: string }, ) { return ( <FormControl @@ -1045,6 +1065,7 @@ class DatasourceRestAPIEditor extends React.Component< conditionals: {}, placeholderText: placeholderText, formName: DATASOURCE_REST_API_FORM, + validator: fieldValidator, }} formName={DATASOURCE_REST_API_FORM} multipleConfig={[]} diff --git a/app/client/src/pages/Editor/__tests__/AuthenticatedAPIErrorValidation.test.tsx b/app/client/src/pages/Editor/__tests__/AuthenticatedAPIErrorValidation.test.tsx new file mode 100644 index 000000000000..66a5cad2175b --- /dev/null +++ b/app/client/src/pages/Editor/__tests__/AuthenticatedAPIErrorValidation.test.tsx @@ -0,0 +1,100 @@ + +import React from "react"; +import "@testing-library/jest-dom"; +import { render, screen } from "test/testUtils"; +import userEvent from "@testing-library/user-event"; +import FormControl from "../FormControl"; +import { createMessage, INVALID_URL } from "ce/constants/messages"; +import FormControlRegistry from "utils/formControl/FormControlRegistry"; +import { reduxForm } from "redux-form"; + +let container: any = null; + +const urlValidator = (value: string) => { + const validationRegex = "^(http|https)://"; + if (value) { + const regex = new RegExp(validationRegex); + + return regex.test(value) + ? { isValid: true, message: "" } + : { + isValid: false, + message: createMessage(INVALID_URL), + }; + } + + return { isValid: true, message: "" }; +} + +function renderComponent() { + function formControlComponent() { + return <FormControl + config={{ + id: "", + isValid: false, + isRequired: true, + controlType: "INPUT_TEXT", + dataType: "TEXT", + configProperty: "authentication.accessTokenUrl", + encrypted: false, + label: "Access Token URL", + conditionals: {}, + placeholderText: "https://example.com/login/oauth/access_token", + formName: "DatasourceRestAPIForm", + validator: urlValidator, + }} + formName="DatasourceRestAPIForm" + multipleConfig={[]} + />; + }; + + const Parent = reduxForm<any, any>({ + validate: () => { + return {}; + }, + form: "DatasourceRestAPIForm", + touchOnBlur: true, + })(formControlComponent); + + render( + <Parent />, + ); +} + +describe("Authenticated API URL validations", () => { + beforeEach(() => { + container = document.createElement("div"); + document.body.appendChild(container); + FormControlRegistry.registerFormControlBuilders(); + }); + + it("enter invalid token url and check for errors", async () => { + renderComponent(); + const inputFormControl = document.querySelectorAll(".t--form-control-INPUT_TEXT"); + expect(inputFormControl.length).toBe(1); + + const inputBox = inputFormControl[0].querySelectorAll("input"); + expect(inputBox.length).toBe(1) + + await userEvent.type(inputBox[0], "test value"); + expect(inputBox[0]).toHaveValue("test value"); + + const errorText = screen.getAllByText("Please enter a valid URL, for example, https://example.com"); + expect(errorText).toBeDefined(); + }); + + it("enter valid token url and check for errors", async () => { + renderComponent(); + const inputFormControl = document.querySelectorAll(".t--form-control-INPUT_TEXT"); + expect(inputFormControl.length).toBe(1); + + const inputBox = inputFormControl[0].querySelectorAll("input"); + expect(inputBox.length).toBe(1) + + await userEvent.type(inputBox[0], "https://example.com"); + expect(inputBox[0]).toHaveValue("https://example.com"); + + const errorText = screen.queryAllByText("Please enter a valid URL, for example, https://example.com"); + expect(errorText.length).toBe(0); + }); +}); \ No newline at end of file
183cc97b50596931085ad4859a1cc88b8285d0e6
2021-08-01 23:42:41
Nayan
fix: Mark comment threads as viewed when they are resolved (#6251)
false
Mark comment threads as viewed when they are resolved (#6251)
fix
diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/CustomCommentThreadRepositoryImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/CustomCommentThreadRepositoryImpl.java index 7e8bcbb144fc..4525db319974 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/CustomCommentThreadRepositoryImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/CustomCommentThreadRepositoryImpl.java @@ -67,9 +67,14 @@ public Mono<UpdateResult> removeSubscriber(String threadId, String username) { @Override public Mono<Long> countUnreadThreads(String applicationId, String userEmail) { + String resolvedActiveFieldKey = String.format("%s.%s", + fieldName(QCommentThread.commentThread.resolvedState), + fieldName(QCommentThread.commentThread.resolvedState.active) + ); List<Criteria> criteriaList = List.of( - where(fieldName(QCommentThread.commentThread.viewedByUsers)).ne(userEmail), - where(fieldName(QCommentThread.commentThread.applicationId)).is(applicationId) + where(fieldName(QCommentThread.commentThread.viewedByUsers)).ne(userEmail), + where(fieldName(QCommentThread.commentThread.applicationId)).is(applicationId), + where(resolvedActiveFieldKey).is(false) ); return count(criteriaList, AclPermission.READ_THREAD); } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/CommentServiceImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/CommentServiceImpl.java index 263f1882e7b9..c6e1a68ce61c 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/CommentServiceImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/CommentServiceImpl.java @@ -280,6 +280,15 @@ public Mono<CommentThread> createThread(CommentThread commentThread, String orig } return saveCommentThread(commentThread, application, user); }) + .flatMap(thread -> { + if(thread.getWidgetType() != null) { + return analyticsService.sendCreateEvent( + thread, Map.of("widgetType", thread.getWidgetType()) + ); + } else { + return analyticsService.sendCreateEvent(thread); + } + }) .flatMapMany(thread -> { List<Mono<Comment>> commentSaverMonos = new ArrayList<>(); @@ -439,11 +448,8 @@ public Mono<List<CommentThread>> getThreadsByApplicationId(CommentThreadFilterDT for (CommentThread thread : threads) { thread.setComments(new LinkedList<>()); - if (thread.getViewedByUsers() != null && thread.getViewedByUsers().contains(user.getUsername())) { - thread.setIsViewed(true); - } else { - thread.setIsViewed(false); - } + thread.setIsViewed((thread.getViewedByUsers() != null && thread.getViewedByUsers().contains(user.getUsername())) + || thread.getResolvedState().getActive()); threadsByThreadId.put(thread.getId(), thread); } diff --git a/app/server/appsmith-server/src/test/java/com/appsmith/server/repositories/CustomCommentThreadRepositoryImplTest.java b/app/server/appsmith-server/src/test/java/com/appsmith/server/repositories/CustomCommentThreadRepositoryImplTest.java index a6f22cca1de7..958b7146cde2 100644 --- a/app/server/appsmith-server/src/test/java/com/appsmith/server/repositories/CustomCommentThreadRepositoryImplTest.java +++ b/app/server/appsmith-server/src/test/java/com/appsmith/server/repositories/CustomCommentThreadRepositoryImplTest.java @@ -15,9 +15,11 @@ import reactor.core.publisher.Mono; import reactor.test.StepVerifier; +import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; +import java.util.UUID; import static org.assertj.core.api.Assertions.assertThat; @@ -155,4 +157,60 @@ public void findThread_WhenFilterExists_ReturnsFilteredResults() { } ).verifyComplete(); } + + private CommentThread createThreadToTestUnreadCountByResolvedState( + String username, String applicationId, boolean isResolved, Boolean isRead) { + CommentThread.CommentThreadState resolvedState = new CommentThread.CommentThreadState(); + resolvedState.setActive(isResolved); + + Set<String> viewedByUsers = new HashSet<>(); + if(isRead) { + viewedByUsers.add(username); + } + + CommentThread commentThread = createThreadWithPolicies(username); + commentThread.setApplicationId(applicationId); + commentThread.setResolvedState(resolvedState); + commentThread.setViewedByUsers(viewedByUsers); + return commentThread; + } + + @Test + @WithUserDetails(value = "api_user") + public void countUnreadThreads_WhenResolvedAndUnread_ResolvedNotCounted() { + String testApplicationId = UUID.randomUUID().toString(); + CommentThread.CommentThreadState resolvedState = new CommentThread.CommentThreadState(); + resolvedState.setActive(true); + + CommentThread.CommentThreadState unresolvedState = new CommentThread.CommentThreadState(); + unresolvedState.setActive(false); + + CommentThread unresolvedUnread = createThreadToTestUnreadCountByResolvedState( + "api_user", testApplicationId, false, false + ); + CommentThread unresolvedRead = createThreadToTestUnreadCountByResolvedState( + "api_user", testApplicationId, false, true + ); + CommentThread resolvedUnread = createThreadToTestUnreadCountByResolvedState( + "api_user", testApplicationId, true, false + ); + + List<CommentThread> threadList = List.of(unresolvedUnread, unresolvedRead, resolvedUnread); + + Mono<Long> unreadCountMono = commentThreadRepository + .saveAll(threadList) + .collectList() + .flatMap(commentThreads -> { + CommentThreadFilterDTO filterDTO = new CommentThreadFilterDTO(); + filterDTO.setApplicationId("sample-application-id-1"); + filterDTO.setResolved(false); + return commentThreadRepository.countUnreadThreads(testApplicationId, "api_user"); + }); + + StepVerifier.create(unreadCountMono).assertNext( + unreadCount -> { + assertThat(unreadCount).isEqualTo(1); + } + ).verifyComplete(); + } } diff --git a/app/server/appsmith-server/src/test/java/com/appsmith/server/services/CommentServiceTest.java b/app/server/appsmith-server/src/test/java/com/appsmith/server/services/CommentServiceTest.java index 2c8985200f80..e9856b10470b 100644 --- a/app/server/appsmith-server/src/test/java/com/appsmith/server/services/CommentServiceTest.java +++ b/app/server/appsmith-server/src/test/java/com/appsmith/server/services/CommentServiceTest.java @@ -288,23 +288,29 @@ public void getUnreadCount() { ); Set<Policy> policies = Set.copyOf(stringPolicyMap.values()); + CommentThread.CommentThreadState resolvedState = new CommentThread.CommentThreadState(); + resolvedState.setActive(false); + // first thread which is read by api_user CommentThread c1 = new CommentThread(); c1.setApplicationId("test-application-1"); c1.setViewedByUsers(Set.of("api_user", "user2")); c1.setPolicies(policies); + c1.setResolvedState(resolvedState); // second thread which is not read by api_user CommentThread c2 = new CommentThread(); c2.setApplicationId("test-application-1"); c2.setViewedByUsers(Set.of("user2")); c2.setPolicies(policies); + c2.setResolvedState(resolvedState); // third thread which is read by api_user but in another application CommentThread c3 = new CommentThread(); c3.setApplicationId("test-application-2"); c3.setViewedByUsers(Set.of("user2", "api_user")); c3.setPolicies(policies); + c3.setResolvedState(resolvedState); Mono<Long> unreadCountMono = commentThreadRepository .saveAll(List.of(c1, c2, c3)) // save all the threads
b8ca5cb8166bab1b7bcf5673f1f25f81bb91e7f4
2021-11-30 11:18:13
Favour Ohanekwu
fix: remove moment interface objects from completions (#9379)
false
remove moment interface objects from completions (#9379)
fix
diff --git a/app/client/src/constants/defs/moment.json b/app/client/src/constants/defs/moment.json index de5060af9c13..3adf0222e7e1 100644 --- a/app/client/src/constants/defs/moment.json +++ b/app/client/src/constants/defs/moment.json @@ -1,5 +1,617 @@ { "!name": "LIB/moment", + "!define":{ + "Moment": { + "startOf": { + "!type": "fn(unitOfTime: ?) -> Moment", + "!url": "https://momentjs.com/docs/#/manipulating/start-of/", + "!doc": "Mutates the original moment by setting it to the start of a unit of time" + }, + "endOf": { + "!type": "fn(unitOfTime: ?) -> Moment", + "!url": "https://momentjs.com/docs/#/manipulating/end-of/", + "!doc": "Mutates the original moment by setting it to the end of a unit of time" + }, + "isValid": { + "!type": "fn() -> bool", + "!url": "https://momentjs.com/docs/#/parsing/is-valid/", + "!doc": "Check whether the Moment considers the date invalid" + }, + "invalidAt": { + "!type": "fn() -> number", + "!url": "https://momentjs.com/docs/#/parsing/is-valid/", + "!doc": "Returns which date unit overflowed" + }, + "hasAlignedHourOffset": { + "!type": "fn(other?: MomentInput) -> boolean" + }, + "creationData": { + "!type": "fn() -> MomentCreationData", + "!url": "https://momentjs.com/docs/#/parsing/creation-data/", + "!doc": "After a moment object is created, all of the inputs can be accessed with creationData() method" + }, + "parsingFlags": { + "!type": "fn() -> MomentParsingFlags", + "!url": "https://momentjs.com/docs/#/parsing/is-valid/", + "!doc": "You can check the metrics used by #isValid using moment#parsingFlags, which returns an object" + }, + "add": { + "!type": "fn(amount?: DurationInputArg1, unit?: DurationInputArg2) -> Moment", + "!url": "https://momentjs.com/docs/#/manipulating/add/", + "!doc": "Mutates the original moment by adding time." + }, + "subtract": { + "!type": "fn(amount?: DurationInputArg1, unit?: DurationInputArg2) -> Moment", + "!url": "https://momentjs.com/docs/#/manipulating/subtract/", + "!doc": "Mutates the original moment by subtracting time" + }, + "calender": { + "!type": "fn(fntime?: MomentInput, formats?: CalendarSpec) -> string", + "!url": "https://momentjs.com/docs/#/displaying/calendar-time/", + "!doc": "Calendar time displays time relative to a given referenceDay (defaults to the start of today)" + }, + "valueOf": { + "!type": "fn() -> number", + "!url": "https://momentjs.com/docs/#/displaying/unix-timestamp-milliseconds/", + "!doc": "Unix timestamp in milliseconds" + }, + "local": { + "!type": "fn(keepLocalTime?: boolean) -> Moment", + "!doc": "Current date/time in local mode" + }, + "isLocal": { + "!type": "fn() -> bool" + }, + "utc": { + "!type": "fn(keepLocalTime?: boolean) -> Moment", + "!url": "https://momentjs.com/docs/#/manipulating/utc/", + "!doc": "Current date/time in UTC mode" + }, + "isUTC": { + "!type": "fn() -> bool" + }, + "parseZone": { + "!type": "fn() -> Moment" + }, + "format": { + "!type": "fn(format?: string) -> string", + "!url": "https://momentjs.com/docs/#/displaying/format/", + "!doc": "Takes a string of tokens and replaces them with their corresponding values" + }, + "isAfter": { + "!type": "fn(inp?: MomentInput, granularity?: ?) -> bool", + "!url": "https://momentjs.com/docs/#/query/is-after/", + "!doc": "Check if a moment is after another moment." + }, + "isSame": { + "!type": "fn(inp?: MomentInput, granularity?: ?) -> bool", + "!url": "https://momentjs.com/docs/#/query/is-same/", + "!doc": "Check if a moment is the same as another moment." + }, + "isBefore": { + "!type": "fn(inp?: MomentInput, granularity?: ?) -> bool", + "!url": "https://momentjs.com/docs/#/query/is-before/", + "!doc": "Check if a moment is before another moment" + }, + "fromNow": { + "!type": "fn(withoutSuffix?: bool) -> string", + "!url": "https://momentjs.com/docs/#/displaying/fromnow/", + "!doc": "Get relative time" + }, + "from": { + "!type": "fn(inp: MomentInput, suffix?: boolean) -> string", + "!url": "https://momentjs.com/docs/#/displaying/from/", + "!doc": "Returns a moment in relation to a time other than now" + }, + "to": { + "!type": "fn(inp: MomentInput, suffix?: boolean) -> string", + "!url": "https://momentjs.com/docs/#/displaying/to/", + "!doc": "Display a moment in relation to a time other than now" + }, + "toNow": { + "!type": "fn(withoutPrefix?: boolean) -> string", + "!url": "https://momentjs.com/docs/#/displaying/tonow/", + "!doc": "Display relative time" + }, + "diff": { + "!type": "fn(b: MomentInput, unitOfTime?: unitOfTime.Diff, precise?: boolean) -> number", + "!url": "https://momentjs.com/docs/#/displaying/difference/", + "!doc": "Get the difference in milliseconds" + }, + "toArray": { + "!type": "fn() -> [number]", + "!url": "https://momentjs.com/docs/#/displaying/as-array/", + "!doc": "Returns an array that mirrors the parameters from new Date()" + }, + "clone": { + "!type": "fn() -> Moment", + "!url": "https://momentjs.com/docs/#/parsing/moment-clone/", + "!doc": "Returns the clone of a moment," + }, + "year": { + "!type": "fn(y: number) -> Moment", + "!url": "https://momentjs.com/docs/#/get-set/year/", + "!doc": "Gets or sets the year" + }, + "quarter": { + "!type": "fn() -> number|fn(q: number) -> Moment", + "!url": "https://momentjs.com/docs/#/get-set/quarter/", + "!doc": "Gets or sets the quarter" + }, + "quarters": { + "!type": "fn() -> number|fn(q: number) -> Moment", + "!url": "https://momentjs.com/docs/#/get-set/quarter/", + "!doc": "Gets or sets the quarter" + }, + "month": { + "!type": "fn() -> number", + "!url": "https://momentjs.com/docs/#/get-set/month/", + "!doc": "Gets or sets the month" + }, + "day": { + "!type": "fn() -> number", + "!url": "https://momentjs.com/docs/#/get-set/day/", + "!doc": "Gets or sets the day of the week." + }, + "days": { + "!type": "fn(d?: number|string) -> number|Moment", + "!url": "https://momentjs.com/docs/#/get-set/day/" + }, + "date": { + "!type": "fn() -> number", + "!url": "https://momentjs.com/docs/#/get-set/date/", + "!doc": "Gets or sets the day of the month." + }, + "hour": { + "!type": "fn() -> number", + "!url": "https://momentjs.com/docs/#/get-set/hour/", + "!doc": "Gets or sets the hour." + }, + "hours": { + "!type": "fn(h?: number) -> number|Moment", + "!url": "https://momentjs.com/docs/#/get-set/hour/", + "!doc": "Gets or sets the hour." + }, + "minute": { + "!type": "fn() -> number", + "!url": "https://momentjs.com/docs/#/get-set/minute/", + "!doc": "Gets or sets the minutes." + }, + "minutes": { + "!type": "fn(m?: number) -> Moment|number", + "!url": "https://momentjs.com/docs/#/get-set/minute/", + "!doc": "Gets or sets the minutes." + }, + "second": { + "!type": "fn([s])", + "!url": "https://momentjs.com/docs/#/get-set/second/", + "!doc": "Gets or sets the seconds." + }, + "seconds": { + "!type": "fn([s])", + "!url": "https://momentjs.com/docs/#/get-set/second/", + "!doc": "Gets or sets the seconds." + }, + "millisecond": { + "!type": "fn([ms])", + "!url": "https://momentjs.com/docs/#/get-set/millisecond/", + "!doc": "Gets or sets the milliseconds." + }, + "milliseconds": { + "!type": "fn([ms])", + "!url": "https://momentjs.com/docs/#/get-set/millisecond/", + "!doc": "Gets or sets the milliseconds." + }, + "weekday": { + "!type": "fn(d?: number) -> number|Moment", + "!url": "https://momentjs.com/docs/#/get-set/weekday/", + "!doc": "Gets or sets the day of the week according to the locale" + }, + "isoWeekday": { + "!type": "fn(d?: number|string) -> number|Moment", + "!url": "https://momentjs.com/docs/#/get-set/iso-weekday/", + "!doc": "Gets or sets the ISO day of the week with 1 being Monday and 7 being Sunday" + }, + "weekYear": { + "!type": "fn(d?: number) -> number|Moment", + "!url": "https://momentjs.com/docs/#/get-set/week-year/", + "!doc": "Gets or sets the week-year according to the locale" + }, + "isoWeekYear": { + "!type": "fn(d?: number) -> number|Moment", + "!url": "https://momentjs.com/docs/#/get-set/iso-week-year/", + "!doc": "Gets or sets the ISO week-year" + }, + "week": { + "!type": "fn(d?: number) -> number|Moment", + "!url": "https://momentjs.com/docs/#/get-set/week/", + "!doc": "Gets or sets the week of the year" + }, + "weeks": { + "!type": "fn(d?: number) -> number|Moment", + "!url": "https://momentjs.com/docs/#/get-set/week/", + "!doc": "Gets or sets the week of the year" + }, + "isoWeek": { + "!type": "fn(d?: number) -> number|Moment", + "!url": "https://momentjs.com/docs/#/get-set/iso-week/", + "!doc": "Gets or sets the ISO week of the year" + }, + "isoWeeks": { + "!type": "fn(d?: number) -> number|Moment", + "!url": "https://momentjs.com/docs/#/get-set/iso-week/", + "!doc": "Gets or sets the ISO week of the year" + }, + "weeksInYear": { + "!type": "fn() -> number", + "!url": "https://momentjs.com/docs/#/get-set/weeks-in-year/", + "!doc": "Gets the number of weeks according to locale in the current moment's year" + }, + "weeksInWeekYear": { + "!type": "fn() -> number" + }, + "isoWeeksInYear": { + "!type": "fn() -> number", + "!url": "https://momentjs.com/docs/#/get-set/iso-weeks-in-year/", + "!doc": "Gets the number of weeks in the current moment's year, according to ISO weeks" + }, + "isoWeeksInISOWeekYear": { + "!type": "fn() -> number" + }, + "dayOfYear": { + "!type": "fn(d?: number) -> number|Moment", + "!url": "https://momentjs.com/docs/#/get-set/day-of-year/", + "!doc": "Gets or sets the day of the year" + }, + "get": { + "!type": "fn(unit: ?) -> number", + "!url": "https://momentjs.com/docs/#/get-set/get/", + "!doc": "String getter" + }, + "set": { + "!type": "fn(unit: ?, value: number) -> Moment", + "!url": "https://momentjs.com/docs/#/get-set/set/", + "!doc": "Generic setter, accepting unit as first argument, and value as second" + }, + "toDate": { + "!type": "fn()", + "!url": "https://momentjs.com/docs/#/displaying/as-javascript-date/", + "!doc": "Get a copy of the native Date object that Moment.js wraps" + }, + "toISOString": { + "!type": "fn(keepOffset?: boolean) -> string", + "!url": "https://momentjs.com/docs/#/displaying/as-iso-string/", + "!doc": "Formats a string to the ISO8601 standard" + }, + "inspect": { + "!type": "fn() -> string", + "!url": "https://momentjs.com/docs/#/displaying/inspect/", + "!doc": "Returns a machine readable string, that can be evaluated to produce the same moment" + }, + "toJSON": { + "!type": "fn() -> string", + "!url": "https://momentjs.com/docs/#/displaying/as-json/", + "!doc": "When serializing an object to JSON, if there is a Moment object, it will be represented as an ISO8601 string, adjusted to UTC" + }, + "unix": { + "!type": "fn() -> number", + "!url": "https://momentjs.com/docs/#/displaying/unix-timestamp/", + "!doc": "Outputs a Unix timestamp (the number of seconds since the Unix Epoch)" + }, + "isLeapYear": { + "!type": "fn() -> bool", + "!url": "https://momentjs.com/docs/#/query/is-leap-year/", + "!doc": "Returns true if that year is a leap year, and false if it is not" + }, + "zone": { + "!type": "fn(b: number|string) -> Moment", + "!url": "https://momentjs.com/docs/#/manipulating/timezone-offset/", + "!doc": "Get the time zone offset in minutes" + }, + "utcOffset": { + "!type": "fn(b?: number|string, keepLocalTime?: boolean) -> Moment", + "!url": "https://momentjs.com/docs/#/manipulating/utc-offset/", + "!doc": "Get or set the UTC offset in minutes" + }, + "isUtcOffset": { + "!type": "fn() -> boolean" + }, + "daysInMonth": { + "!type": "fn() -> number", + "!url": "https://momentjs.com/docs/#/displaying/days-in-month/", + "!doc": "Get the number of days in the current month" + }, + "isDST": { + "!type": "fn() -> boolean", + "!url": "https://momentjs.com/docs/#/query/is-daylight-saving-time/", + "!doc": "Get the number of days in the current month" + }, + "zoneAbbr": { + "!type": "fn() -> string" + }, + "zoneName": { + "!type": "fn() -> string" + }, + "isSameOrAfter": { + "!type": "fn(inp?: MomentInput, granularity?: ?) -> bool", + "!url": "https://momentjs.com/docs/#/query/is-same-or-after/", + "!doc": "Check if a moment is after or the same as another moment" + }, + "isSameOrBefore": { + "!type": "fn(inp?: MomentInput, granularity?: ?) -> bool", + "!url": "https://momentjs.com/docs/#/query/is-same-or-before/", + "!doc": "Check if a moment is before or the same as another moment" + }, + "isBetween": { + "!type": "fn(a: MomentInput, b: MomentInput, granularity?: ?, inclusivity?: ?) -> bool", + "!url": "https://momentjs.com/docs/#/query/is-between/", + "!doc": "Check if a moment is between two other moments," + }, + "locale": { + "!type": "fn(locale: LocaleSpecifier) -> string|Moment", + "!url": "https://momentjs.com/docs/#/i18n/instance-locale/", + "!doc": "A global locale configuration can be problematic when passing around moments that may need to be formatted into different locale" + }, + "localeData": { + "!type": "fn() -> Locale" + }, + "toObject": { + "!type": "fn() -> MomentObjectOutput", + "!url": "https://momentjs.com/docs/#/displaying/as-object/", + "!doc": "Returns an object containing year, month, day-of-month, hour, minute, seconds, milliseconds" + } + }, + "Duration": { + "clone": { + "!type": "fn() -> Duration", + "!url": "https://momentjs.com/docs/#/durations/clone/", + "!doc": "Create a clone of a duration" + }, + "humanize": { + "!type": "fn(argWithSuffix?: boolean, argThresholds?: argThresholdOpts) -> string", + "!url": "https://momentjs.com/docs/#/durations/humanize/" + }, + "abs": { + "!type": "fn() -> Duration" + }, + "as": { + "!type": "fn(units: ?) -> number", + "!url": "https://momentjs.com/docs/#/durations/as/" + }, + "get": { + "!type": "fn(units: ?) -> number", + "!url": "https://momentjs.com/docs/#/durations/get/", + "!doc": "Alternate to Duration#x() getters" + }, + "milliseconds": { + "!type": "fn() -> number", + "!url": "https://momentjs.com/docs/#/durations/milliseconds/", + "!doc": "Get the number of milliseconds in a duration" + }, + "asMilliseconds": { + "!type": "fn() -> number", + "!url": "https://momentjs.com/docs/#/durations/milliseconds/", + "!doc": "Get the length of the duration in milliseconds" + }, + "seconds": { + "!type": "fn() -> number", + "!url": "https://momentjs.com/docs/#/durations/seconds/", + "!doc": "Get the number of seconds in a duration" + }, + "asSeconds": { + "!type": "fn() -> number", + "!url": "https://momentjs.com/docs/#/durations/seconds/", + "!doc": "Get the length of the duration in seconds" + }, + "minutes": { + "!type": "fn() -> number", + "!url": "https://momentjs.com/docs/#/durations/minutes/", + "!doc": "Gets the minutes (0 - 59)" + }, + "asMinutes": { + "!type": "fn() -> number", + "!url": "https://momentjs.com/docs/#/durations/minutes/", + "!doc": "Gets the length of the duration in minutes" + }, + "hours": { + "!type": "fn() -> number", + "!url": "https://momentjs.com/docs/#/durations/hours/", + "!doc": "Gets the hours (0 - 23)" + }, + "asHours": { + "!type": "fn() -> number", + "!url": "https://momentjs.com/docs/#/durations/hours/", + "!doc": "Gets the length of the duration in hours" + }, + "days": { + "!type": "fn() -> number", + "!url": "https://momentjs.com/docs/#/durations/days/", + "!doc": "Gets the days (0 - 30)" + }, + "asDays": { + "!type": "fn() -> number", + "!url": "https://momentjs.com/docs/#/durations/days/", + "!doc": "Gets the length of the duration in days" + }, + "weeks": { + "!type": "fn() -> number", + "!url": "https://momentjs.com/docs/#/durations/weeks/", + "!doc": "Gets the weeks (0 - 4)" + }, + "asWeeks": { + "!type": "fn() -> number", + "!url": "https://momentjs.com/docs/#/durations/weeks/", + "!doc": "Gets the length of the duration in weeks" + }, + "months": { + "!type": "fn() -> number", + "!url": "https://momentjs.com/docs/#/durations/months/", + "!doc": "Gets the months (0 - 11)." + }, + "asMonths": { + "!type": "fn() -> number", + "!url": "https://momentjs.com/docs/#/durations/months/", + "!doc": "Gets the length of the duration in months" + }, + "years": { + "!type": "fn() -> number", + "!url": "https://momentjs.com/docs/#/durations/years/", + "!doc": "Gets the years" + }, + "asYears": { + "!type": "fn() -> number", + "!url": "https://momentjs.com/docs/#/durations/years/", + "!doc": "Gets the length of the duration in years" + }, + "add": { + "!type": "fn(inp?: DurationInputArg1, unit?: DurationInputArg2) -> Duration", + "!url": "https://momentjs.com/docs/#/durations/add/", + "!doc": "Mutates the original duration by adding time" + }, + "subtract": { + "!type": "fn(inp?: DurationInputArg1, unit?: DurationInputArg2) -> Duration", + "!url": "https://momentjs.com/docs/#/durations/subtract/", + "!doc": "Mutates the original duration by subtracting time" + }, + "locale": { + "!type": "fn(locale: LocaleSpecifier) -> Duration", + "!url": "https://momentjs.com/docs/#/durations/locale/", + "!doc": "Get or set the locale of a duration" + }, + "localeData": { + "!type": "fn() -> Locale" + }, + "toISOString": { + "!type": "fn() -> string", + "!url": "https://momentjs.com/docs/#/durations/as-iso-string/", + "!doc": "Returns duration in string as specified by ISO 8601 standard" + }, + "toJSON": { + "!type": "fn() -> string", + "!url": "https://momentjs.com/docs/#/durations/as-json/", + "!doc": "When serializing a duration object to JSON, it will be represented as an ISO8601 string" + }, + "isValid": { + "!type": "fn() -> boolean" + } + }, + "Locale": { + "calendar": { + "!type": "fn(key?: CalendarKey, m?: Moment, now?: Moment) -> string", + "!url": "https://momentjs.com/docs/#/customization/calendar/" + }, + "longDateFormat": { + "!type": "fn(key: LongDateFormatKey) -> string", + "!url": "https://momentjs.com/docs/#/i18n/locale-data/", + "!doc": "Returns the full format of abbreviated date-time formats LT, L, LL and so on" + }, + "invalidDate": { + "!type": "fn() -> string", + "!url": "https://momentjs.com/docs/#/i18n/locale-data/", + "!doc": "Returns a translation of 'Invalid date'" + }, + "ordinal": { + "!type": "fn(n: number) -> string", + "!url": "https://momentjs.com/docs/#/i18n/locale-data/", + "!doc": "Convert number to ordinal string 1 -> 1st" + }, + "preparse": { + "!type": "fn(inp: string) -> string", + "!url": "https://momentjs.com/docs/#/i18n/locale-data/", + "!doc": "Called before parsing on every input string" + }, + "postformat": { + "!type": "fn(inp: string) -> string", + "!url": "https://momentjs.com/docs/#/i18n/locale-data/", + "!doc": "Called after formatting on every string" + }, + "relativeTime": { + "!type": "fn(n: number, withoutSuffix: boolean, key: RelativeTimeKey, isFuture: boolean) -> string", + "!url": "https://momentjs.com/docs/#/i18n/locale-data/", + "!doc": "Returns relative time string, key is on of 's', 'm', 'mm', 'h', 'hh', 'd', 'dd', 'M', 'MM', 'y', 'yy'" + }, + "pastFuture": { + "!type": "fn(diff: number, absRelTime: string) -> string", + "!url": "https://momentjs.com/docs/#/i18n/locale-data/", + "!doc": "Convert relTime string to past or future string depending on diff" + }, + "set": { + "!type": "fn(config: Object) -> void", + "!url": "https://momentjs.com/docs/#/i18n/locale-data/", + "!doc": "Convert relTime string to past or future string depending on diff" + }, + "months": { + "!type": "fn(m?: Moment, format?: string) -> string|[string]", + "!url": "https://momentjs.com/docs/#/i18n/locale-data/", + "!doc": "Full month name of m" + }, + "monthsShort": { + "!type": "fn(m?: Moment, format?: string) -> string|[string]", + "!url": "https://momentjs.com/docs/#/i18n/locale-data/", + "!doc": "Short month name of m" + }, + "monthsParse": { + "!type": "fn(monthName: string, format: string, strict: bool) -> number", + "!url": "https://momentjs.com/docs/#/i18n/locale-data/", + "!doc": "Returns month id (0 to 11) of input" + }, + "monthsRegex": { + "!type": "fn(strict: bool) -> RegExp" + }, + "monthsShortRegex": { + "!type": "fn(strict: boolean) -> RegExp" + }, + "week": { + "!type": "fn(m: Moment) -> number", + "!url": "https://momentjs.com/docs/#/i18n/locale-data/", + "!doc": "returns week-of-year of m" + }, + "firstDayOfYear": { + "!type": "fn() -> number", + "!url": "https://momentjs.com/docs/#/i18n/locale-data/", + "!doc": "0-15 Used to determine first week of the year" + }, + "weekdays": { + "!type": "fn(m: Moment, format?: string) -> string", + "!url": "https://momentjs.com/docs/#/i18n/locale-data/", + "!doc": "Full weekday name of m" + }, + "weekdaysMin": { + "!type": "fn(m: Moment, format?: string) -> string", + "!url": "https://momentjs.com/docs/#/i18n/locale-data/", + "!doc": "min weekday name of m" + }, + "weekdaysShort": { + "!type": "fn(m: Moment) -> string", + "!url": "https://momentjs.com/docs/#/i18n/locale-data/", + "!doc": "Short weekday name of m" + }, + "weekdaysParse": { + "!type": "fn(weekdayName: string, format: string, strict: boolean) -> number", + "!url": "https://momentjs.com/docs/#/i18n/locale-data/", + "!doc": "Returns weekday id (0 to 6) of input" + }, + "weekdaysRegex": { + "!type": "fn(strict: bool) -> RegExp" + }, + "weekdaysShortRegex": { + "!type": "fn(strict: bool) -> RegExp" + }, + "weekdaysMinRegex": { + "!type": "fn(strict: bool) -> RegExp" + }, + "isPM": { + "!type": "fn(input: string) -> bool", + "!url": "https://momentjs.com/docs/#/i18n/locale-data/", + "!doc": "Returns true if input represents PM" + }, + "meridiem": { + "!type": "fn(hour: number, minute: number, isLower: bool) -> string", + "!url": "https://momentjs.com/docs/#/i18n/locale-data/", + "!doc": "Returns am/pm string for particular time-of-day in upper/lower case" + } + } + }, "moment": { "!type": "fn(inp?: MomentInput, format?: MomentFormatSpecification, strict?: boolean) -> Moment", "!url": "https://momentjs.com/docs/#/parsing/", @@ -116,615 +728,6 @@ "!type": "fn(input: string) -> number", "!url": "https://momentjs.com/docs/#/parsing/string-format/" } - }, - "Moment": { - "startOf": { - "!type": "fn(unitOfTime: ?) -> Moment", - "!url": "https://momentjs.com/docs/#/manipulating/start-of/", - "!doc": "Mutates the original moment by setting it to the start of a unit of time" - }, - "endOf": { - "!type": "fn(unitOfTime: ?) -> Moment", - "!url": "https://momentjs.com/docs/#/manipulating/end-of/", - "!doc": "Mutates the original moment by setting it to the end of a unit of time" - }, - "isValid": { - "!type": "fn() -> bool", - "!url": "https://momentjs.com/docs/#/parsing/is-valid/", - "!doc": "Check whether the Moment considers the date invalid" - }, - "invalidAt": { - "!type": "fn() -> number", - "!url": "https://momentjs.com/docs/#/parsing/is-valid/", - "!doc": "Returns which date unit overflowed" - }, - "hasAlignedHourOffset": { - "!type": "fn(other?: MomentInput) -> boolean" - }, - "creationData": { - "!type": "fn() -> MomentCreationData", - "!url": "https://momentjs.com/docs/#/parsing/creation-data/", - "!doc": "After a moment object is created, all of the inputs can be accessed with creationData() method" - }, - "parsingFlags": { - "!type": "fn() -> MomentParsingFlags", - "!url": "https://momentjs.com/docs/#/parsing/is-valid/", - "!doc": "You can check the metrics used by #isValid using moment#parsingFlags, which returns an object" - }, - "add": { - "!type": "fn(amount?: DurationInputArg1, unit?: DurationInputArg2) -> Moment", - "!url": "https://momentjs.com/docs/#/manipulating/add/", - "!doc": "Mutates the original moment by adding time." - }, - "subtract": { - "!type": "fn(amount?: DurationInputArg1, unit?: DurationInputArg2) -> Moment", - "!url": "https://momentjs.com/docs/#/manipulating/subtract/", - "!doc": "Mutates the original moment by subtracting time" - }, - "calender": { - "!type": "fn(fntime?: MomentInput, formats?: CalendarSpec) -> string", - "!url": "https://momentjs.com/docs/#/displaying/calendar-time/", - "!doc": "Calendar time displays time relative to a given referenceDay (defaults to the start of today)" - }, - "valueOf": { - "!type": "fn() -> number", - "!url": "https://momentjs.com/docs/#/displaying/unix-timestamp-milliseconds/", - "!doc": "Unix timestamp in milliseconds" - }, - "local": { - "!type": "fn(keepLocalTime?: boolean) -> Moment", - "!doc": "Current date/time in local mode" - }, - "isLocal": { - "!type": "fn() -> bool" - }, - "utc": { - "!type": "fn(keepLocalTime?: boolean) -> Moment", - "!url": "https://momentjs.com/docs/#/manipulating/utc/", - "!doc": "Current date/time in UTC mode" - }, - "isUTC": { - "!type": "fn() -> bool" - }, - "parseZone": { - "!type": "fn() -> Moment" - }, - "format": { - "!type": "fn(format?: string) -> string", - "!url": "https://momentjs.com/docs/#/displaying/format/", - "!doc": "Takes a string of tokens and replaces them with their corresponding values" - }, - "isAfter": { - "!type": "fn(inp?: MomentInput, granularity?: ?) -> bool", - "!url": "https://momentjs.com/docs/#/query/is-after/", - "!doc": "Check if a moment is after another moment." - }, - "isSame": { - "!type": "fn(inp?: MomentInput, granularity?: ?) -> bool", - "!url": "https://momentjs.com/docs/#/query/is-same/", - "!doc": "Check if a moment is the same as another moment." - }, - "isBefore": { - "!type": "fn(inp?: MomentInput, granularity?: ?) -> bool", - "!url": "https://momentjs.com/docs/#/query/is-before/", - "!doc": "Check if a moment is before another moment" - }, - "fromNow": { - "!type": "fn(withoutSuffix?: bool) -> string", - "!url": "https://momentjs.com/docs/#/displaying/fromnow/", - "!doc": "Get relative time" - }, - "from": { - "!type": "fn(inp: MomentInput, suffix?: boolean) -> string", - "!url": "https://momentjs.com/docs/#/displaying/from/", - "!doc": "Returns a moment in relation to a time other than now" - }, - "to": { - "!type": "fn(inp: MomentInput, suffix?: boolean) -> string", - "!url": "https://momentjs.com/docs/#/displaying/to/", - "!doc": "Display a moment in relation to a time other than now" - }, - "toNow": { - "!type": "fn(withoutPrefix?: boolean) -> string", - "!url": "https://momentjs.com/docs/#/displaying/tonow/", - "!doc": "Display relative time" - }, - "diff": { - "!type": "fn(b: MomentInput, unitOfTime?: unitOfTime.Diff, precise?: boolean) -> number", - "!url": "https://momentjs.com/docs/#/displaying/difference/", - "!doc": "Get the difference in milliseconds" - }, - "toArray": { - "!type": "fn() -> [number]", - "!url": "https://momentjs.com/docs/#/displaying/as-array/", - "!doc": "Returns an array that mirrors the parameters from new Date()" - }, - "clone": { - "!type": "fn() -> Moment", - "!url": "https://momentjs.com/docs/#/parsing/moment-clone/", - "!doc": "Returns the clone of a moment," - }, - "year": { - "!type": "fn(y: number) -> Moment", - "!url": "https://momentjs.com/docs/#/get-set/year/", - "!doc": "Gets or sets the year" - }, - "quarter": { - "!type": "fn() -> number|fn(q: number) -> Moment", - "!url": "https://momentjs.com/docs/#/get-set/quarter/", - "!doc": "Gets or sets the quarter" - }, - "quarters": { - "!type": "fn() -> number|fn(q: number) -> Moment", - "!url": "https://momentjs.com/docs/#/get-set/quarter/", - "!doc": "Gets or sets the quarter" - }, - "month": { - "!type": "fn() -> number", - "!url": "https://momentjs.com/docs/#/get-set/month/", - "!doc": "Gets or sets the month" - }, - "day": { - "!type": "fn() -> number", - "!url": "https://momentjs.com/docs/#/get-set/day/", - "!doc": "Gets or sets the day of the week." - }, - "days": { - "!type": "fn(d?: number|string) -> number|Moment", - "!url": "https://momentjs.com/docs/#/get-set/day/" - }, - "date": { - "!type": "fn() -> number", - "!url": "https://momentjs.com/docs/#/get-set/date/", - "!doc": "Gets or sets the day of the month." - }, - "hour": { - "!type": "fn() -> number", - "!url": "https://momentjs.com/docs/#/get-set/hour/", - "!doc": "Gets or sets the hour." - }, - "hours": { - "!type": "fn(h?: number) -> number|Moment", - "!url": "https://momentjs.com/docs/#/get-set/hour/", - "!doc": "Gets or sets the hour." - }, - "minute": { - "!type": "fn() -> number", - "!url": "https://momentjs.com/docs/#/get-set/minute/", - "!doc": "Gets or sets the minutes." - }, - "minutes": { - "!type": "fn(m?: number) -> Moment|number", - "!url": "https://momentjs.com/docs/#/get-set/minute/", - "!doc": "Gets or sets the minutes." - }, - "second": { - "!type": "fn([s])", - "!url": "https://momentjs.com/docs/#/get-set/second/", - "!doc": "Gets or sets the seconds." - }, - "seconds": { - "!type": "fn([s])", - "!url": "https://momentjs.com/docs/#/get-set/second/", - "!doc": "Gets or sets the seconds." - }, - "millisecond": { - "!type": "fn([ms])", - "!url": "https://momentjs.com/docs/#/get-set/millisecond/", - "!doc": "Gets or sets the milliseconds." - }, - "milliseconds": { - "!type": "fn([ms])", - "!url": "https://momentjs.com/docs/#/get-set/millisecond/", - "!doc": "Gets or sets the milliseconds." - }, - "weekday": { - "!type": "fn(d?: number) -> number|Moment", - "!url": "https://momentjs.com/docs/#/get-set/weekday/", - "!doc": "Gets or sets the day of the week according to the locale" - }, - "isoWeekday": { - "!type": "fn(d?: number|string) -> number|Moment", - "!url": "https://momentjs.com/docs/#/get-set/iso-weekday/", - "!doc": "Gets or sets the ISO day of the week with 1 being Monday and 7 being Sunday" - }, - "weekYear": { - "!type": "fn(d?: number) -> number|Moment", - "!url": "https://momentjs.com/docs/#/get-set/week-year/", - "!doc": "Gets or sets the week-year according to the locale" - }, - "isoWeekYear": { - "!type": "fn(d?: number) -> number|Moment", - "!url": "https://momentjs.com/docs/#/get-set/iso-week-year/", - "!doc": "Gets or sets the ISO week-year" - }, - "week": { - "!type": "fn(d?: number) -> number|Moment", - "!url": "https://momentjs.com/docs/#/get-set/week/", - "!doc": "Gets or sets the week of the year" - }, - "weeks": { - "!type": "fn(d?: number) -> number|Moment", - "!url": "https://momentjs.com/docs/#/get-set/week/", - "!doc": "Gets or sets the week of the year" - }, - "isoWeek": { - "!type": "fn(d?: number) -> number|Moment", - "!url": "https://momentjs.com/docs/#/get-set/iso-week/", - "!doc": "Gets or sets the ISO week of the year" - }, - "isoWeeks": { - "!type": "fn(d?: number) -> number|Moment", - "!url": "https://momentjs.com/docs/#/get-set/iso-week/", - "!doc": "Gets or sets the ISO week of the year" - }, - "weeksInYear": { - "!type": "fn() -> number", - "!url": "https://momentjs.com/docs/#/get-set/weeks-in-year/", - "!doc": "Gets the number of weeks according to locale in the current moment's year" - }, - "weeksInWeekYear": { - "!type": "fn() -> number" - }, - "isoWeeksInYear": { - "!type": "fn() -> number", - "!url": "https://momentjs.com/docs/#/get-set/iso-weeks-in-year/", - "!doc": "Gets the number of weeks in the current moment's year, according to ISO weeks" - }, - "isoWeeksInISOWeekYear": { - "!type": "fn() -> number" - }, - "dayOfYear": { - "!type": "fn(d?: number) -> number|Moment", - "!url": "https://momentjs.com/docs/#/get-set/day-of-year/", - "!doc": "Gets or sets the day of the year" - }, - "get": { - "!type": "fn(unit: ?) -> number", - "!url": "https://momentjs.com/docs/#/get-set/get/", - "!doc": "String getter" - }, - "set": { - "!type": "fn(unit: ?, value: number) -> Moment", - "!url": "https://momentjs.com/docs/#/get-set/set/", - "!doc": "Generic setter, accepting unit as first argument, and value as second" - }, - "toDate": { - "!type": "fn()", - "!url": "https://momentjs.com/docs/#/displaying/as-javascript-date/", - "!doc": "Get a copy of the native Date object that Moment.js wraps" - }, - "toISOString": { - "!type": "fn(keepOffset?: boolean) -> string", - "!url": "https://momentjs.com/docs/#/displaying/as-iso-string/", - "!doc": "Formats a string to the ISO8601 standard" - }, - "inspect": { - "!type": "fn() -> string", - "!url": "https://momentjs.com/docs/#/displaying/inspect/", - "!doc": "Returns a machine readable string, that can be evaluated to produce the same moment" - }, - "toJSON": { - "!type": "fn() -> string", - "!url": "https://momentjs.com/docs/#/displaying/as-json/", - "!doc": "When serializing an object to JSON, if there is a Moment object, it will be represented as an ISO8601 string, adjusted to UTC" - }, - "unix": { - "!type": "fn() -> number", - "!url": "https://momentjs.com/docs/#/displaying/unix-timestamp/", - "!doc": "Outputs a Unix timestamp (the number of seconds since the Unix Epoch)" - }, - "isLeapYear": { - "!type": "fn() -> bool", - "!url": "https://momentjs.com/docs/#/query/is-leap-year/", - "!doc": "Returns true if that year is a leap year, and false if it is not" - }, - "zone": { - "!type": "fn(b: number|string) -> Moment", - "!url": "https://momentjs.com/docs/#/manipulating/timezone-offset/", - "!doc": "Get the time zone offset in minutes" - }, - "utcOffset": { - "!type": "fn(b?: number|string, keepLocalTime?: boolean) -> Moment", - "!url": "https://momentjs.com/docs/#/manipulating/utc-offset/", - "!doc": "Get or set the UTC offset in minutes" - }, - "isUtcOffset": { - "!type": "fn() -> boolean" - }, - "daysInMonth": { - "!type": "fn() -> number", - "!url": "https://momentjs.com/docs/#/displaying/days-in-month/", - "!doc": "Get the number of days in the current month" - }, - "isDST": { - "!type": "fn() -> boolean", - "!url": "https://momentjs.com/docs/#/query/is-daylight-saving-time/", - "!doc": "Get the number of days in the current month" - }, - "zoneAbbr": { - "!type": "fn() -> string" - }, - "zoneName": { - "!type": "fn() -> string" - }, - "isSameOrAfter": { - "!type": "fn(inp?: MomentInput, granularity?: ?) -> bool", - "!url": "https://momentjs.com/docs/#/query/is-same-or-after/", - "!doc": "Check if a moment is after or the same as another moment" - }, - "isSameOrBefore": { - "!type": "fn(inp?: MomentInput, granularity?: ?) -> bool", - "!url": "https://momentjs.com/docs/#/query/is-same-or-before/", - "!doc": "Check if a moment is before or the same as another moment" - }, - "isBetween": { - "!type": "fn(a: MomentInput, b: MomentInput, granularity?: ?, inclusivity?: ?) -> bool", - "!url": "https://momentjs.com/docs/#/query/is-between/", - "!doc": "Check if a moment is between two other moments," - }, - "locale": { - "!type": "fn(locale: LocaleSpecifier) -> string|Moment", - "!url": "https://momentjs.com/docs/#/i18n/instance-locale/", - "!doc": "A global locale configuration can be problematic when passing around moments that may need to be formatted into different locale" - }, - "localeData": { - "!type": "fn() -> Locale" - }, - "toObject": { - "!type": "fn() -> MomentObjectOutput", - "!url": "https://momentjs.com/docs/#/displaying/as-object/", - "!doc": "Returns an object containing year, month, day-of-month, hour, minute, seconds, milliseconds" - } - }, - "Duration": { - "clone": { - "!type": "fn() -> Duration", - "!url": "https://momentjs.com/docs/#/durations/clone/", - "!doc": "Create a clone of a duration" - }, - "humanize": { - "!type": "fn(argWithSuffix?: boolean, argThresholds?: argThresholdOpts) -> string", - "!url": "https://momentjs.com/docs/#/durations/humanize/" - }, - "abs": { - "!type": "fn() -> Duration" - }, - "as": { - "!type": "fn(units: ?) -> number", - "!url": "https://momentjs.com/docs/#/durations/as/" - }, - "get": { - "!type": "fn(units: ?) -> number", - "!url": "https://momentjs.com/docs/#/durations/get/", - "!doc": "Alternate to Duration#x() getters" - }, - "milliseconds": { - "!type": "fn() -> number", - "!url": "https://momentjs.com/docs/#/durations/milliseconds/", - "!doc": "Get the number of milliseconds in a duration" - }, - "asMilliseconds": { - "!type": "fn() -> number", - "!url": "https://momentjs.com/docs/#/durations/milliseconds/", - "!doc": "Get the length of the duration in milliseconds" - }, - "seconds": { - "!type": "fn() -> number", - "!url": "https://momentjs.com/docs/#/durations/seconds/", - "!doc": "Get the number of seconds in a duration" - }, - "asSeconds": { - "!type": "fn() -> number", - "!url": "https://momentjs.com/docs/#/durations/seconds/", - "!doc": "Get the length of the duration in seconds" - }, - "minutes": { - "!type": "fn() -> number", - "!url": "https://momentjs.com/docs/#/durations/minutes/", - "!doc": "Gets the minutes (0 - 59)" - }, - "asMinutes": { - "!type": "fn() -> number", - "!url": "https://momentjs.com/docs/#/durations/minutes/", - "!doc": "Gets the length of the duration in minutes" - }, - "hours": { - "!type": "fn() -> number", - "!url": "https://momentjs.com/docs/#/durations/hours/", - "!doc": "Gets the hours (0 - 23)" - }, - "asHours": { - "!type": "fn() -> number", - "!url": "https://momentjs.com/docs/#/durations/hours/", - "!doc": "Gets the length of the duration in hours" - }, - "days": { - "!type": "fn() -> number", - "!url": "https://momentjs.com/docs/#/durations/days/", - "!doc": "Gets the days (0 - 30)" - }, - "asDays": { - "!type": "fn() -> number", - "!url": "https://momentjs.com/docs/#/durations/days/", - "!doc": "Gets the length of the duration in days" - }, - "weeks": { - "!type": "fn() -> number", - "!url": "https://momentjs.com/docs/#/durations/weeks/", - "!doc": "Gets the weeks (0 - 4)" - }, - "asWeeks": { - "!type": "fn() -> number", - "!url": "https://momentjs.com/docs/#/durations/weeks/", - "!doc": "Gets the length of the duration in weeks" - }, - "months": { - "!type": "fn() -> number", - "!url": "https://momentjs.com/docs/#/durations/months/", - "!doc": "Gets the months (0 - 11)." - }, - "asMonths": { - "!type": "fn() -> number", - "!url": "https://momentjs.com/docs/#/durations/months/", - "!doc": "Gets the length of the duration in months" - }, - "years": { - "!type": "fn() -> number", - "!url": "https://momentjs.com/docs/#/durations/years/", - "!doc": "Gets the years" - }, - "asYears": { - "!type": "fn() -> number", - "!url": "https://momentjs.com/docs/#/durations/years/", - "!doc": "Gets the length of the duration in years" - }, - "add": { - "!type": "fn(inp?: DurationInputArg1, unit?: DurationInputArg2) -> Duration", - "!url": "https://momentjs.com/docs/#/durations/add/", - "!doc": "Mutates the original duration by adding time" - }, - "subtract": { - "!type": "fn(inp?: DurationInputArg1, unit?: DurationInputArg2) -> Duration", - "!url": "https://momentjs.com/docs/#/durations/subtract/", - "!doc": "Mutates the original duration by subtracting time" - }, - "locale": { - "!type": "fn(locale: LocaleSpecifier) -> Duration", - "!url": "https://momentjs.com/docs/#/durations/locale/", - "!doc": "Get or set the locale of a duration" - }, - "localeData": { - "!type": "fn() -> Locale" - }, - "toISOString": { - "!type": "fn() -> string", - "!url": "https://momentjs.com/docs/#/durations/as-iso-string/", - "!doc": "Returns duration in string as specified by ISO 8601 standard" - }, - "toJSON": { - "!type": "fn() -> string", - "!url": "https://momentjs.com/docs/#/durations/as-json/", - "!doc": "When serializing a duration object to JSON, it will be represented as an ISO8601 string" - }, - "isValid": { - "!type": "fn() -> boolean" - } - }, - "Locale": { - "calendar": { - "!type": "fn(key?: CalendarKey, m?: Moment, now?: Moment) -> string", - "!url": "https://momentjs.com/docs/#/customization/calendar/" - }, - "longDateFormat": { - "!type": "fn(key: LongDateFormatKey) -> string", - "!url": "https://momentjs.com/docs/#/i18n/locale-data/", - "!doc": "Returns the full format of abbreviated date-time formats LT, L, LL and so on" - }, - "invalidDate": { - "!type": "fn() -> string", - "!url": "https://momentjs.com/docs/#/i18n/locale-data/", - "!doc": "Returns a translation of 'Invalid date'" - }, - "ordinal": { - "!type": "fn(n: number) -> string", - "!url": "https://momentjs.com/docs/#/i18n/locale-data/", - "!doc": "Convert number to ordinal string 1 -> 1st" - }, - "preparse": { - "!type": "fn(inp: string) -> string", - "!url": "https://momentjs.com/docs/#/i18n/locale-data/", - "!doc": "Called before parsing on every input string" - }, - "postformat": { - "!type": "fn(inp: string) -> string", - "!url": "https://momentjs.com/docs/#/i18n/locale-data/", - "!doc": "Called after formatting on every string" - }, - "relativeTime": { - "!type": "fn(n: number, withoutSuffix: boolean, key: RelativeTimeKey, isFuture: boolean) -> string", - "!url": "https://momentjs.com/docs/#/i18n/locale-data/", - "!doc": "Returns relative time string, key is on of 's', 'm', 'mm', 'h', 'hh', 'd', 'dd', 'M', 'MM', 'y', 'yy'" - }, - "pastFuture": { - "!type": "fn(diff: number, absRelTime: string) -> string", - "!url": "https://momentjs.com/docs/#/i18n/locale-data/", - "!doc": "Convert relTime string to past or future string depending on diff" - }, - "set": { - "!type": "fn(config: Object) -> void", - "!url": "https://momentjs.com/docs/#/i18n/locale-data/", - "!doc": "Convert relTime string to past or future string depending on diff" - }, - "months": { - "!type": "fn(m?: Moment, format?: string) -> string|[string]", - "!url": "https://momentjs.com/docs/#/i18n/locale-data/", - "!doc": "Full month name of m" - }, - "monthsShort": { - "!type": "fn(m?: Moment, format?: string) -> string|[string]", - "!url": "https://momentjs.com/docs/#/i18n/locale-data/", - "!doc": "Short month name of m" - }, - "monthsParse": { - "!type": "fn(monthName: string, format: string, strict: bool) -> number", - "!url": "https://momentjs.com/docs/#/i18n/locale-data/", - "!doc": "Returns month id (0 to 11) of input" - }, - "monthsRegex": { - "!type": "fn(strict: bool) -> RegExp" - }, - "monthsShortRegex": { - "!type": "fn(strict: boolean) -> RegExp" - }, - "week": { - "!type": "fn(m: Moment) -> number", - "!url": "https://momentjs.com/docs/#/i18n/locale-data/", - "!doc": "returns week-of-year of m" - }, - "firstDayOfYear": { - "!type": "fn() -> number", - "!url": "https://momentjs.com/docs/#/i18n/locale-data/", - "!doc": "0-15 Used to determine first week of the year" - }, - "weekdays": { - "!type": "fn(m: Moment, format?: string) -> string", - "!url": "https://momentjs.com/docs/#/i18n/locale-data/", - "!doc": "Full weekday name of m" - }, - "weekdaysMin": { - "!type": "fn(m: Moment, format?: string) -> string", - "!url": "https://momentjs.com/docs/#/i18n/locale-data/", - "!doc": "min weekday name of m" - }, - "weekdaysShort": { - "!type": "fn(m: Moment) -> string", - "!url": "https://momentjs.com/docs/#/i18n/locale-data/", - "!doc": "Short weekday name of m" - }, - "weekdaysParse": { - "!type": "fn(weekdayName: string, format: string, strict: boolean) -> number", - "!url": "https://momentjs.com/docs/#/i18n/locale-data/", - "!doc": "Returns weekday id (0 to 6) of input" - }, - "weekdaysRegex": { - "!type": "fn(strict: bool) -> RegExp" - }, - "weekdaysShortRegex": { - "!type": "fn(strict: bool) -> RegExp" - }, - "weekdaysMinRegex": { - "!type": "fn(strict: bool) -> RegExp" - }, - "isPM": { - "!type": "fn(input: string) -> bool", - "!url": "https://momentjs.com/docs/#/i18n/locale-data/", - "!doc": "Returns true if input represents PM" - }, - "meridiem": { - "!type": "fn(hour: number, minute: number, isLower: bool) -> string", - "!url": "https://momentjs.com/docs/#/i18n/locale-data/", - "!doc": "Returns am/pm string for particular time-of-day in upper/lower case" - } } + }
12954d4e3dce4f860e929a8fcff85d9e097a9db8
2022-03-02 19:13:24
Bhavin K
fix: changed download flow for image control (#11391)
false
changed download flow for image control (#11391)
fix
diff --git a/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/DisplayWidgets/Image_spec.js b/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/DisplayWidgets/Image_spec.js index f3d2afe8464b..4840ad558467 100644 --- a/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/DisplayWidgets/Image_spec.js +++ b/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/DisplayWidgets/Image_spec.js @@ -64,10 +64,21 @@ describe("Image Widget Functionality", function() { cy.togglebar(commonlocators.visibleCheckbox); cy.PublishtheApp(); cy.get(publish.imageWidget).should("be.visible"); + cy.get(publish.backToEditor).click(); + }); + + it("Image Widget Functionality To check download option and validate image link", function() { + cy.openPropertyPane("imagewidget"); + cy.togglebar(".t--property-control-enabledownload input[type='checkbox']"); + cy.get(publish.imageWidget).trigger("mouseover"); + cy.get(`${publish.imageWidget} a[data-cy=t--image-download]`).should( + "have.attr", + "href", + this.data.NewImage, + ); }); it("In case of an image loading error, show off the error message", () => { - cy.get(publish.backToEditor).click(); cy.openPropertyPane("imagewidget"); // Invalid image url const invalidImageUrl = "https://www.example.com/does-not-exist.jpg"; diff --git a/app/client/src/widgets/ImageWidget/component/index.tsx b/app/client/src/widgets/ImageWidget/component/index.tsx index 5b9c53235a5e..75bf80cb6d96 100644 --- a/app/client/src/widgets/ImageWidget/component/index.tsx +++ b/app/client/src/widgets/ImageWidget/component/index.tsx @@ -57,7 +57,7 @@ const ControlBtnWrapper = styled.div` background: white; `; -const ControlBtn = styled.div` +const ControlBtn = styled.a` height: 25px; width: 45px; color: white; @@ -242,6 +242,7 @@ class ImageComponent extends React.Component< } = this.props; const { showImageControl } = this.state; const showDownloadBtn = enableDownload && (!!imageUrl || !!defaultImageUrl); + const hrefUrl = imageUrl || defaultImageUrl; if (showImageControl && (enableRotation || showDownloadBtn)) { return ( @@ -290,7 +291,12 @@ class ImageComponent extends React.Component< </> )} {showDownloadBtn && ( - <ControlBtn onClick={this.handleImageDownload}> + <ControlBtn + data-cy="t--image-download" + download + href={hrefUrl} + target="_blank" + > <div> <svg fill="none" height="20" viewBox="0 0 20 20" width="20"> <path @@ -321,43 +327,6 @@ class ImageComponent extends React.Component< } }; - handleImageDownload = (e: any) => { - const { defaultImageUrl, imageUrl, widgetId } = this.props; - const fileName = `${widgetId}-download`; - const downloadUrl = imageUrl || defaultImageUrl; - - const xhr = new XMLHttpRequest(); - xhr.open("GET", downloadUrl, true); - xhr.responseType = "blob"; - - xhr.onload = function() { - const urlCreator = window.URL || window.webkitURL; - const imageUrlObj = urlCreator.createObjectURL(this.response); - const tag = document.createElement("a"); - tag.href = imageUrlObj; - tag.download = fileName; - document.body.appendChild(tag); - tag.click(); - document.body.removeChild(tag); - window.URL.revokeObjectURL(imageUrlObj); - }; - // if download fails open image in new tab - xhr.onerror = function() { - const tag = document.createElement("a"); - tag.href = downloadUrl; - tag.target = "_blank"; - document.body.appendChild(tag); - tag.click(); - document.body.removeChild(tag); - }; - xhr.send(); - - if (!!e) { - e.preventDefault(); - e.stopPropagation(); - } - }; - onMouseEnter = () => { const { defaultImageUrl, imageUrl } = this.props; if (defaultImageUrl || imageUrl) {
048e3b02204769fa2c93874ae88b3806180516a6
2024-04-17 11:49:01
Shrikant Sharat Kandula
chore: Remove BaseController on WorkspaceControllerCE (#32254)
false
Remove BaseController on WorkspaceControllerCE (#32254)
chore
diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/controllers/ce/WorkspaceControllerCE.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/controllers/ce/WorkspaceControllerCE.java index dc15e571e676..a9d3f52421d0 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/controllers/ce/WorkspaceControllerCE.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/controllers/ce/WorkspaceControllerCE.java @@ -10,7 +10,8 @@ import com.appsmith.server.services.UserWorkspaceService; import com.appsmith.server.services.WorkspaceService; import com.fasterxml.jackson.annotation.JsonView; -import org.springframework.beans.factory.annotation.Autowired; +import jakarta.validation.Valid; +import lombok.RequiredArgsConstructor; import org.springframework.http.HttpStatus; import org.springframework.http.codec.multipart.Part; import org.springframework.web.bind.annotation.DeleteMapping; @@ -22,24 +23,46 @@ import org.springframework.web.bind.annotation.RequestHeader; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestPart; +import org.springframework.web.bind.annotation.ResponseStatus; import reactor.core.publisher.Mono; import java.util.List; @RequestMapping(Url.WORKSPACE_URL) -public class WorkspaceControllerCE extends BaseController<WorkspaceService, Workspace, String> { +@RequiredArgsConstructor +public class WorkspaceControllerCE { + private final WorkspaceService service; private final UserWorkspaceService userWorkspaceService; - @Autowired - public WorkspaceControllerCE(WorkspaceService workspaceService, UserWorkspaceService userWorkspaceService) { - super(workspaceService); - this.userWorkspaceService = userWorkspaceService; + @JsonView(Views.Public.class) + @GetMapping("/{id}") + public Mono<ResponseDTO<Workspace>> getByIdAndBranchName(@PathVariable String id) { + return service.getById(id).map(workspace -> new ResponseDTO<>(HttpStatus.OK.value(), workspace, null)); + } + + @JsonView(Views.Public.class) + @PostMapping + @ResponseStatus(HttpStatus.CREATED) + public Mono<ResponseDTO<Workspace>> create(@Valid @RequestBody Workspace resource) { + return service.create(resource).map(created -> new ResponseDTO<>(HttpStatus.CREATED.value(), created, null)); + } + + @JsonView(Views.Public.class) + @PutMapping("/{id}") + public Mono<ResponseDTO<Workspace>> update(@PathVariable String id, @RequestBody Workspace resource) { + return service.update(id, resource) + .map(updatedResource -> new ResponseDTO<>(HttpStatus.OK.value(), updatedResource, null)); + } + + @JsonView(Views.Public.class) + @DeleteMapping("/{id}") + public Mono<ResponseDTO<Workspace>> delete(@PathVariable String id) { + return service.archiveById(id) + .map(deletedResource -> new ResponseDTO<>(HttpStatus.OK.value(), deletedResource, null)); } /** * This function would be used to fetch default permission groups of workspace, for which user has access to invite users. - * - * @return */ @JsonView(Views.Public.class) @GetMapping("/{workspaceId}/permissionGroups")
9e896dde06de16f03d318f8374883eb24300f201
2022-03-15 15:29:48
Abhijeet
fix: Fix git repository visibility status check and update error messages for git-checkout API (#11858)
false
Fix git repository visibility status check and update error messages for git-checkout API (#11858)
fix
diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/helpers/GitUtils.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/helpers/GitUtils.java index bcba61fc40a4..9cf31402c0ba 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/helpers/GitUtils.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/helpers/GitUtils.java @@ -15,8 +15,9 @@ public class GitUtils { /** * Sample repo urls : - * [email protected]:user/repoName.git - * https://gitPlatform.com/user/repoName + * [email protected]:user/repoName.git + * ssh://[email protected]/<workspace_ID>/<repo_name>.git + * https://example.com/user/repoName * * @param sshUrl ssh url of repo * @return https url supported by curl command extracted from ssh repo url @@ -26,14 +27,15 @@ public static String convertSshUrlToBrowserSupportedUrl(String sshUrl) { throw new AppsmithException(AppsmithError.INVALID_PARAMETER, "ssh url"); } return sshUrl - .replaceFirst("git@", "https://") - .replaceFirst("(\\.[a-z]*):", "$1/"); + .replaceFirst(".*git@", "https://") + .replaceFirst("(\\.[a-z]*):", "$1/") + .replaceFirst("\\.git$", ""); } /** * Sample repo urls : - * [email protected]:username/reponame.git - * ssh://[email protected]/<workspace_ID>/<repo_name>.git + * [email protected]:username/reponame.git + * ssh://[email protected]/<workspace_ID>/<repo_name>.git * @param remoteUrl ssh url of repo * @return repo name extracted from repo url */ @@ -43,8 +45,8 @@ public static String getRepoName(String remoteUrl) { if (matcher.find()) { return matcher.group(1); } - throw new AppsmithException(AppsmithError.INVALID_GIT_CONFIGURATION, "Remote URL is incorrect! Can you " + - "please provide as per standard format => [email protected]:username/reponame.git"); + throw new AppsmithException(AppsmithError.INVALID_GIT_CONFIGURATION, "Remote URL is incorrect, " + + "please add a URL in standard format. Example: [email protected]:username/reponame.git"); } /** 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 7e45a6a56330..35340effc916 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 @@ -1189,7 +1189,7 @@ public Mono<Application> createBranch(String defaultApplicationId, GitBranchDTO public Mono<Application> checkoutBranch(String defaultApplicationId, String branchName) { if (StringUtils.isEmptyOrNull(branchName)) { - throw new AppsmithException(AppsmithError.INVALID_PARAMETER, FieldName.BRANCH_NAME); + return Mono.error(new AppsmithException(AppsmithError.INVALID_PARAMETER, FieldName.BRANCH_NAME)); } //If the user is trying to check out remote branch, create a new branch if the branch does not exist already diff --git a/app/server/appsmith-server/src/test/java/com/appsmith/server/helpers/GitUtilsTest.java b/app/server/appsmith-server/src/test/java/com/appsmith/server/helpers/GitUtilsTest.java index e74fc9f78065..096acb2effae 100644 --- a/app/server/appsmith-server/src/test/java/com/appsmith/server/helpers/GitUtilsTest.java +++ b/app/server/appsmith-server/src/test/java/com/appsmith/server/helpers/GitUtilsTest.java @@ -16,46 +16,50 @@ public class GitUtilsTest { @Test public void convertSshUrlToBrowserSupportedUrl() { - assertThat(GitUtils.convertSshUrlToBrowserSupportedUrl("[email protected]:user/test/tests/testRepo.git")) - .isEqualTo("https://github.test.net/user/test/tests/testRepo.git"); - assertThat(GitUtils.convertSshUrlToBrowserSupportedUrl("[email protected]:test/testRepo.git")) - .isEqualTo("https://github.com/test/testRepo.git"); - assertThat(GitUtils.convertSshUrlToBrowserSupportedUrl("[email protected]:test/testRepo.git")) - .isEqualTo("https://gitlab.org/test/testRepo.git"); - assertThat(GitUtils.convertSshUrlToBrowserSupportedUrl("[email protected]:test/testRepo.git")) - .isEqualTo("https://bitbucket.in/test/testRepo.git"); + assertThat(GitUtils.convertSshUrlToBrowserSupportedUrl("[email protected]:user/test/tests/testRepo.git")) + .isEqualTo("https://example.test.net/user/test/tests/testRepo"); + assertThat(GitUtils.convertSshUrlToBrowserSupportedUrl("[email protected]:test/testRepo.git")) + .isEqualTo("https://example.com/test/testRepo"); + assertThat(GitUtils.convertSshUrlToBrowserSupportedUrl("[email protected]:test/testRepo.git")) + .isEqualTo("https://example.org/test/testRepo"); + assertThat(GitUtils.convertSshUrlToBrowserSupportedUrl("[email protected]:test/testRepo.git")) + .isEqualTo("https://example.in/test/testRepo"); + assertThat(GitUtils.convertSshUrlToBrowserSupportedUrl("ssh://[email protected]:user/test/tests/testRepo.git")) + .isEqualTo("https://example.test.net/user/test/tests/testRepo"); } @Test public void isRepoPrivate() throws IOException { - assertThat(GitUtils.isRepoPrivate(GitUtils.convertSshUrlToBrowserSupportedUrl("[email protected]:test/testRepo.git"))) + assertThat(GitUtils.isRepoPrivate(GitUtils.convertSshUrlToBrowserSupportedUrl("[email protected]:test/testRepo.git"))) .isEqualTo(Boolean.TRUE); - assertThat(GitUtils.isRepoPrivate(GitUtils.convertSshUrlToBrowserSupportedUrl("[email protected]:test/testRepo.git"))) + assertThat(GitUtils.isRepoPrivate(GitUtils.convertSshUrlToBrowserSupportedUrl("[email protected]:test/testRepo.git"))) .isEqualTo(Boolean.TRUE); - assertThat(GitUtils.isRepoPrivate(GitUtils.convertSshUrlToBrowserSupportedUrl("[email protected]:test/testRepo.git"))) + assertThat(GitUtils.isRepoPrivate(GitUtils.convertSshUrlToBrowserSupportedUrl("[email protected]:test/testRepo.git"))) .isEqualTo(Boolean.TRUE); + assertThat(GitUtils.isRepoPrivate(GitUtils.convertSshUrlToBrowserSupportedUrl("ssh://[email protected]"))) + .isEqualTo(Boolean.FALSE); } @Test public void getRepoName() { - assertThat(GitUtils.getRepoName("[email protected]:user/test/tests/testRepo.git")) + assertThat(GitUtils.getRepoName("[email protected]:user/test/tests/testRepo.git")) .isEqualTo("testRepo"); - assertThat(GitUtils.getRepoName("[email protected]:test/testRepo.git")) + assertThat(GitUtils.getRepoName("[email protected]:test/testRepo.git")) .isEqualTo("testRepo"); - assertThat(GitUtils.getRepoName("[email protected]:test/testRepo.git")) + assertThat(GitUtils.getRepoName("[email protected]:test/testRepo.git")) .isEqualTo("testRepo"); - assertThat(GitUtils.getRepoName("[email protected]:test/testRepo.git")) + assertThat(GitUtils.getRepoName("[email protected]:test/testRepo.git")) .isEqualTo("testRepo"); } @Test public void getGitProviderName() { - assertThat(GitUtils.getGitProviderName("[email protected]:user/test/tests/testRepo.git")) - .isEqualTo("github"); - assertThat(GitUtils.getGitProviderName("[email protected]:test/testRepo.git")) - .isEqualTo("github"); - assertThat(GitUtils.getGitProviderName("[email protected]:test/testRepo.git")) - .isEqualTo("gitlab"); - assertThat(GitUtils.getGitProviderName("[email protected]:test/testRepo.git")) - .isEqualTo("bitbucket"); + assertThat(GitUtils.getGitProviderName("[email protected]:user/test/tests/testRepo.git")) + .isEqualTo("example"); + assertThat(GitUtils.getGitProviderName("[email protected]:test/testRepo.git")) + .isEqualTo("example"); + assertThat(GitUtils.getGitProviderName("[email protected]:test/testRepo.git")) + .isEqualTo("example"); + assertThat(GitUtils.getGitProviderName("[email protected]:test/testRepo.git")) + .isEqualTo("example"); } } diff --git a/app/server/appsmith-server/src/test/java/com/appsmith/server/services/GitServiceTest.java b/app/server/appsmith-server/src/test/java/com/appsmith/server/services/GitServiceTest.java index 0aa159c44165..74d2306d3ba7 100644 --- a/app/server/appsmith-server/src/test/java/com/appsmith/server/services/GitServiceTest.java +++ b/app/server/appsmith-server/src/test/java/com/appsmith/server/services/GitServiceTest.java @@ -1706,6 +1706,19 @@ public void checkoutRemoteBranch_presentInLocal_throwError() { .verify(); } + @Test + @WithUserDetails(value = "api_user") + public void checkoutBranch_branchNotProvided_throwInvalidParameterError() { + + Mono<Application> applicationMono = gitService.checkoutBranch(gitConnectedApplication.getId(), null); + + StepVerifier + .create(applicationMono) + .expectErrorMatches(throwable -> throwable instanceof AppsmithException + && throwable.getMessage().equals(AppsmithError.INVALID_PARAMETER.getMessage(FieldName.BRANCH_NAME))) + .verify(); + } + @Test @WithUserDetails(value = "api_user") public void commitApplication_noChangesInLocal_emptyCommitMessage() throws GitAPIException, IOException {
93fd9465056204ce0af32da67540447e0f39f0ee
2021-03-23 15:49:10
Confidence Okoghenun
chore: Add summary for Mar 18 office hours (#3642)
false
Add summary for Mar 18 office hours (#3642)
chore
diff --git a/office_hours.md b/office_hours.md index eeaa0d2c3515..bbc608867785 100644 --- a/office_hours.md +++ b/office_hours.md @@ -28,6 +28,15 @@ You can find the archives of the calls below with a brief summary of each sessio ## Archives +<strong>18th Mar 2021: Generic S3 plugin, Forkable apps, Google sheets integration</strong> + +<a href = "https://youtu.be/sRpleBfEOxQ">Video Link</a> + +#### Summary + +Nikhil talks about new Appsmith features. Chris Webb from the community shows off what he built using Appsmith. Nidhi from Appsmith demos how to use the new google sheets integration + +------------------ <strong>26th Feb 2021: Community feedback, Oauth 2 Integration, Google Sheets Integration, Switch Widget and Prepared Statements</strong>
73d81a278db20f51ec637ed407d0e59e51655c0f
2025-02-25 15:25:26
vadim
chore: ADS slider polish (#39365)
false
ADS slider polish (#39365)
chore
diff --git a/app/client/packages/design-system/ads/src/Slider/Slider.mdx b/app/client/packages/design-system/ads/src/Slider/Slider.mdx index 52719f3f295d..64e78f9ca18b 100644 --- a/app/client/packages/design-system/ads/src/Slider/Slider.mdx +++ b/app/client/packages/design-system/ads/src/Slider/Slider.mdx @@ -6,10 +6,8 @@ import * as SliderStories from "./Slider.stories"; # Slider -A slider component is used when you want to allow users to select a value from a range of values by dragging a thumb along a track. It is ideal for settings where a range of values is more appropriate than a fixed set of options, such as adjusting volume, brightness, or selecting a price range. +A slider component is used for numerical value input that fall within the range. Users may drag a thumb along a track with a mouse or using touch input. They may also use arrow keys on their keyboard. -<Canvas of={SliderStories.SliderStory} /> - -If the value represents an offset, the fill start can be set to represent the point of origin. This allows the slider fill to start from inside the track. +This UI pattern is ideal alternative to a fixed set of options for selecting a price range or adjusting volume. -<Canvas of={SliderStories.OriginSliderStory} /> +<Canvas of={SliderStories.SliderStory} /> diff --git a/app/client/packages/design-system/ads/src/Slider/Slider.stories.tsx b/app/client/packages/design-system/ads/src/Slider/Slider.stories.tsx index 54b01ed686a8..86ad0c5f136e 100644 --- a/app/client/packages/design-system/ads/src/Slider/Slider.stories.tsx +++ b/app/client/packages/design-system/ads/src/Slider/Slider.stories.tsx @@ -23,13 +23,3 @@ SliderStory.args = { label: "Donuts to buy", getValueLabel: (donuts: string) => `${donuts} of 100 Donuts`, }; - -export const OriginSliderStory = Template.bind({}) as StoryObj; -OriginSliderStory.args = { - maxValue: 100, - minValue: 0, - origin: 50, - step: 1, - value: 50, - label: "Number", -}; diff --git a/app/client/packages/design-system/ads/src/Slider/Slider.styles.tsx b/app/client/packages/design-system/ads/src/Slider/Slider.styles.tsx index 234d15c82edb..214966a47c58 100644 --- a/app/client/packages/design-system/ads/src/Slider/Slider.styles.tsx +++ b/app/client/packages/design-system/ads/src/Slider/Slider.styles.tsx @@ -10,12 +10,12 @@ export const StyledSlider = styled.div<{ align-items: center; touch-action: none; width: 100%; - padding: 0 calc(var(--ads-v2-spaces-5) / 2) calc(var(--ads-v2-spaces-5) / 2); + padding: 0 calc(var(--ads-v2-spaces-5) / 2) var(--ads-v2-spaces-4); ${({ disabled }) => disabled && ` - opacity: 0.6; + opacity: var(--ads-v2-opacity-disabled); cursor: not-allowed !important; `} @@ -33,43 +33,56 @@ export const SliderLabel = styled.div` align-self: stretch; justify-content: space-between; margin: 0 calc(var(--ads-v2-spaces-5) / 2 * -1) var(--ads-v2-spaces-3); + + span { + flex-grow: 1; + text-align: end; + } `; export const Thumb = styled.div` position: absolute; - transform: translateX(-50%); width: var(--ads-v2-spaces-5); height: var(--ads-v2-spaces-5); border-radius: 50%; box-sizing: border-box; - background-color: var(--ads-v2-color-bg-brand-secondary); + background-color: var(--ads-v2-color-bg); + border: 1px solid var(--ads-v2-color-border); cursor: pointer; top: 0; - &:hover { - background-color: var(--ads-v2-color-bg-brand-secondary-emphasis); - } - &:active { - background-color: var(--ads-v2-color-bg-brand-secondary-emphasis-plus); + ${StyledSlider}:hover:not([disabled]) & { + box-shadow: 0 1px var(--ads-v2-spaces-2) 0 rgba(76, 86, 100, 0.18); } `; export const Rail = styled.div` position: absolute; - background-color: var(--ads-v2-color-bg-emphasis); + background-color: var(--ads-v2-color-border); height: var(--ads-v2-spaces-1); transform: translateY(-50%); width: calc(100% + var(--ads-v2-spaces-5)); margin-inline-start: calc(var(--ads-v2-spaces-5) / 2 * -1); + border-radius: var(--ads-v2-border-width-outline); + + ${StyledSlider}:hover:not([disabled]) & { + background-color: var(--ads-v2-color-border-emphasis); + } `; export const FilledRail = styled.div` position: absolute; height: var(--ads-v2-spaces-2); - background-color: var(--ads-v2-color-bg-emphasis-plus); + background-color: var(--ads-v2-color-border-brand-secondary); transform: translateY(-50%); left: 0; margin-inline-start: calc(var(--ads-v2-spaces-5) / 2 * -1); + border-radius: var(--ads-v2-border-width-outline) 0 0 + var(--ads-v2-border-width-outline); + + ${StyledSlider}:hover:not([disabled]) & { + background-color: var(--ads-v2-color-border-brand-secondary-emphasis); + } `; export const TrackContainer = styled.div`
6f69f1935c7d0d4c4e8ffee4b2e20c1ffa81d77a
2023-05-10 13:04:34
Nilansh Bansal
fix: display name validation (server) (#22927)
false
display name validation (server) (#22927)
fix
diff --git a/app/client/src/ce/constants/messages.ts b/app/client/src/ce/constants/messages.ts index 4272db8b48b6..fdbabc79fa1e 100644 --- a/app/client/src/ce/constants/messages.ts +++ b/app/client/src/ce/constants/messages.ts @@ -171,6 +171,9 @@ export const USERS_HAVE_ACCESS_TO_ONLY_THIS_APP = () => "Users will only have access to this application"; export const NO_USERS_INVITED = () => "You haven't invited any users yet"; +export const UPDATE_USER_DETAILS_FAILED = () => + "Unable to update user details."; + export const CREATE_PASSWORD_RESET_SUCCESS = () => `Your password has been set`; export const CREATE_PASSWORD_RESET_SUCCESS_LOGIN_LINK = () => `Login`; diff --git a/app/client/src/ce/sagas/userSagas.tsx b/app/client/src/ce/sagas/userSagas.tsx index b0dfe22a8656..70f2ce04a32e 100644 --- a/app/client/src/ce/sagas/userSagas.tsx +++ b/app/client/src/ce/sagas/userSagas.tsx @@ -21,6 +21,7 @@ import UserApi from "@appsmith/api/UserApi"; import { AUTH_LOGIN_URL, SETUP } from "constants/routes"; import history from "utils/history"; import type { ApiResponse } from "api/ApiResponses"; +import type { ErrorActionPayload } from "sagas/ErrorSagas"; import { validateResponse, getResponseErrorMessage, @@ -72,6 +73,8 @@ import type { SegmentState } from "reducers/uiReducers/analyticsReducer"; import type FeatureFlags from "entities/FeatureFlags"; import UsagePulse from "usagePulse"; import { isAirgapped } from "@appsmith/utils/airgapHelpers"; +import { UPDATE_USER_DETAILS_FAILED } from "ce/constants/messages"; +import { createMessage } from "design-system-old/build/constants/messages"; export function* createUserSaga( action: ReduxActionWithPromise<CreateUserRequest>, @@ -382,9 +385,16 @@ export function* updateUserDetailsSaga(action: ReduxAction<UpdateUserRequest>) { }); } } catch (error) { + const payload: ErrorActionPayload = { + show: true, + error: { + message: + (error as Error).message ?? createMessage(UPDATE_USER_DETAILS_FAILED), + }, + }; yield put({ type: ReduxActionErrorTypes.UPDATE_USER_DETAILS_ERROR, - payload: (error as Error).message, + payload, }); } } 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 fb2c5bf0a3ec..d7d5b7919225 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 @@ -69,6 +69,7 @@ import java.util.Optional; import java.util.Set; import java.util.UUID; +import java.util.regex.Pattern; import static com.appsmith.server.acl.AclPermission.MANAGE_USERS; import static com.appsmith.server.helpers.ValidationUtils.LOGIN_PASSWORD_MAX_LENGTH; @@ -100,6 +101,7 @@ public class UserServiceCEImpl extends BaseService<UserRepository, User, String> private static final String FORGOT_PASSWORD_CLIENT_URL_FORMAT = "%s/user/resetPassword?token=%s"; private static final String INVITE_USER_CLIENT_URL_FORMAT = "%s/user/signup?email=%s"; public static final String INVITE_USER_EMAIL_TEMPLATE = "email/inviteUserTemplate.html"; + private static final Pattern ALLOWED_ACCENTED_CHARACTERS_PATTERN = Pattern.compile("^[\\p{L} 0-9 .\'\\-]+$"); @Autowired public UserServiceCEImpl(Scheduler scheduler, @@ -659,6 +661,14 @@ public Flux<User> get(MultiValueMap<String, String> params) { return Flux.error(new AppsmithException(AppsmithError.UNSUPPORTED_OPERATION)); } + private boolean validateName(String name){ + /* + Regex allows for Accented characters and alphanumeric with some special characters dot (.), apostrophe ('), + hyphen (-) and spaces + */ + return ALLOWED_ACCENTED_CHARACTERS_PATTERN.matcher(name).matches(); + } + @Override public Mono<User> updateCurrentUser(final UserUpdateDTO allUpdates, ServerWebExchange exchange) { List<Mono<Void>> monos = new ArrayList<>(); @@ -668,7 +678,12 @@ public Mono<User> updateCurrentUser(final UserUpdateDTO allUpdates, ServerWebExc if (allUpdates.hasUserUpdates()) { final User updates = new User(); - updates.setName(allUpdates.getName()); + String inputName = allUpdates.getName(); + boolean isValidName = validateName(inputName); + if (!isValidName){ + return Mono.error(new AppsmithException(AppsmithError.INVALID_PARAMETER, FieldName.NAME)); + } + updates.setName(inputName); updatedUserMono = sessionUserService.getCurrentUser() .flatMap(user -> update(user.getEmail(), updates, fieldName(QUser.user.email)) diff --git a/app/server/appsmith-server/src/test/java/com/appsmith/server/services/UserServiceTest.java b/app/server/appsmith-server/src/test/java/com/appsmith/server/services/UserServiceTest.java index bd3bbcb86cab..821a6ed979a2 100644 --- a/app/server/appsmith-server/src/test/java/com/appsmith/server/services/UserServiceTest.java +++ b/app/server/appsmith-server/src/test/java/com/appsmith/server/services/UserServiceTest.java @@ -415,12 +415,39 @@ public void createUserWithInvalidEmailAddress() { @WithUserDetails(value = "api_user") public void updateNameOfUser() { UserUpdateDTO updateUser = new UserUpdateDTO(); - updateUser.setName("New name of api_user"); + updateUser.setName("New name of api user"); StepVerifier.create(userService.updateCurrentUser(updateUser, null)) .assertNext(user -> { assertNotNull(user); - assertThat(user.getEmail()).isEqualTo("api_user"); - assertThat(user.getName()).isEqualTo("New name of api_user"); + assertEquals("api_user", user.getEmail()); + assertEquals("New name of api user", user.getName()); + }) + .verifyComplete(); + } + + @Test + @WithUserDetails(value = "api_user") + public void updateNameOfUser_WithNotAllowedSpecialCharacter_InvalidName() { + UserUpdateDTO updateUser = new UserUpdateDTO(); + updateUser.setName("invalid name@symbol"); + StepVerifier.create(userService.updateCurrentUser(updateUser, null)) + .expectErrorMatches(throwable -> + throwable instanceof AppsmithException + && + throwable.getMessage().contains(AppsmithError.INVALID_PARAMETER.getMessage(FieldName.NAME)) + ) + .verify(); + } + + @Test + @WithUserDetails(value = "api_user") + public void updateNameOfUser_WithAccentedCharacters_IsValid() { + UserUpdateDTO updateUser = new UserUpdateDTO(); + updateUser.setName("ä ö ü è ß Test . '- ðƒ 你好 123'"); + StepVerifier.create(userService.updateCurrentUser(updateUser, null)) + .assertNext(user -> { + assertNotNull(user); + assertEquals("ä ö ü è ß Test . '- ðƒ 你好 123'", user.getName()); }) .verifyComplete(); } @@ -491,9 +518,9 @@ public void updateNameRoleAndUseCaseOfUser() { final UserData userData = tuple.getT2(); assertNotNull(user); assertNotNull(userData); - assertThat(user.getName()).isEqualTo("New name of user here"); - assertThat(userData.getRole()).isEqualTo("New role of user"); - assertThat(userData.getUseCase()).isEqualTo("New use case"); + assertEquals("New name of user here", user.getName()); + assertEquals("New role of user", userData.getRole()); + assertEquals("New use case", userData.getUseCase()); }) .verifyComplete(); }
a9ca63c225187d829a9312e49e4fa001644486f1
2024-08-30 17:06:30
albinAppsmith
fix: Action redesign/remove container query (#36014)
false
Action redesign/remove container query (#36014)
fix
diff --git a/app/client/src/components/formControls/DynamicTextFieldControl.tsx b/app/client/src/components/formControls/DynamicTextFieldControl.tsx index de390e699e62..4bb9c594814f 100644 --- a/app/client/src/components/formControls/DynamicTextFieldControl.tsx +++ b/app/client/src/components/formControls/DynamicTextFieldControl.tsx @@ -65,7 +65,7 @@ class DynamicTextControl extends BaseControl< return ( <Wrapper - className={`t--${configProperty}`} + className={`t--${configProperty} dynamic-text-field-control`} fullWidth={isActionRedesignEnabled} > <DynamicTextField diff --git a/app/client/src/components/formControls/FieldArrayControl.tsx b/app/client/src/components/formControls/FieldArrayControl.tsx index e2e6ed4fa95c..33cdd33725ae 100644 --- a/app/client/src/components/formControls/FieldArrayControl.tsx +++ b/app/client/src/components/formControls/FieldArrayControl.tsx @@ -100,6 +100,7 @@ function NestedComponents(props: any) { <CenteredIconButton alignSelf={"start"} data-testid={`t--where-clause-delete-[${index}]`} + isIconButton kind="tertiary" onClick={(e: React.MouseEvent) => { e.stopPropagation(); diff --git a/app/client/src/pages/Editor/ActionForm/Section/styles.module.css b/app/client/src/pages/Editor/ActionForm/Section/styles.module.css index beac00d105fd..e3d2a2d2f309 100644 --- a/app/client/src/pages/Editor/ActionForm/Section/styles.module.css +++ b/app/client/src/pages/Editor/ActionForm/Section/styles.module.css @@ -5,7 +5,6 @@ width: 100%; max-width: 800px; justify-content: center; - container: uqi-section / inline-size; &[data-standalone="false"] { padding-block: var(--ads-v2-spaces-6); diff --git a/app/client/src/pages/Editor/ActionForm/Zone/styles.module.css b/app/client/src/pages/Editor/ActionForm/Zone/styles.module.css index 6b04213740de..93953ba2b370 100644 --- a/app/client/src/pages/Editor/ActionForm/Zone/styles.module.css +++ b/app/client/src/pages/Editor/ActionForm/Zone/styles.module.css @@ -5,7 +5,7 @@ box-sizing: border-box; &[data-layout="double_column"] { - grid-template-columns: repeat(2, minmax(260px, 1fr)); + grid-template-columns: repeat(auto-fill, minmax(260px, 1fr)); } &[data-layout="single_column"] { @@ -47,11 +47,15 @@ } } } - /* Removable section ends here */ -} -@container uqi-section (max-width: 531px) { - .zone[data-layout="double_column"] { - grid-template-columns: 1fr; + /* Remove when code editor min width is resolved in DynamicTextFeildControl */ + & :global(.dynamic-text-field-control) { + min-width: 260px; } + + /* reset ads select min width */ + & :global(.ads-v2-select > .rc-select-selector) { + min-width: unset; + } + /* Removable section ends here */ }
d9b1729ce368b36659190ca72bd2c14a2259e1da
2024-12-19 15:24:23
Anagh Hegde
chore: refactor crud methods (#38158)
false
refactor crud methods (#38158)
chore
diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/CustomNewActionRepositoryCE.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/CustomNewActionRepositoryCE.java index 80351b502b01..debbd0b8b5d9 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/CustomNewActionRepositoryCE.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/CustomNewActionRepositoryCE.java @@ -80,4 +80,14 @@ Flux<NewAction> findAllPublishedActionsByContextIdAndContextType( String contextId, CreatorContextType contextType, AclPermission permission, boolean includeJs); Flux<NewAction> findAllByApplicationIds(List<String> branchedArtifactIds, List<String> includedFields); + + // @Meta(cursorBatchSize = 10000) + // TODO Implement cursor with batch size + Flux<NewAction> findByApplicationId(String applicationId); + + // @Meta(cursorBatchSize = 10000) + // TODO Implement cursor with batch size + Flux<NewAction> findAllByIdIn(Iterable<String> ids); + + Mono<Long> countByDeletedAtNull(); } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/CustomNewActionRepositoryCEImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/CustomNewActionRepositoryCEImpl.java index 0d56c4dcabb8..33d511dd0990 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/CustomNewActionRepositoryCEImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/CustomNewActionRepositoryCEImpl.java @@ -29,6 +29,7 @@ import java.util.List; import java.util.Optional; import java.util.Set; +import java.util.stream.StreamSupport; import static org.springframework.data.mongodb.core.aggregation.Aggregation.group; import static org.springframework.data.mongodb.core.aggregation.Aggregation.match; @@ -488,4 +489,24 @@ public Flux<NewAction> findAllByApplicationIds(List<String> applicationIds, List .fields(includedFields) .all(); } + + @Override + public Flux<NewAction> findByApplicationId(String applicationId) { + return queryBuilder() + .criteria(Bridge.equal(NewAction.Fields.applicationId, applicationId)) + .all(); + } + + @Override + public Flux<NewAction> findAllByIdIn(Iterable<String> ids) { + List<String> idList = StreamSupport.stream(ids.spliterator(), false).toList(); + return queryBuilder().criteria(Bridge.in(NewAction.Fields.id, idList)).all(); + } + + @Override + public Mono<Long> countByDeletedAtNull() { + return queryBuilder() + .criteria(Bridge.exists(NewAction.Fields.deletedAt)) + .count(); + } } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/NewActionRepositoryCE.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/NewActionRepositoryCE.java index 9b270f2fcb4f..f3bdb2c807ed 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/NewActionRepositoryCE.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/NewActionRepositoryCE.java @@ -5,22 +5,12 @@ import com.appsmith.server.projections.IdPoliciesOnly; import com.appsmith.server.repositories.BaseRepository; import com.appsmith.server.repositories.CustomNewActionRepository; -import org.springframework.data.mongodb.repository.Meta; import reactor.core.publisher.Flux; -import reactor.core.publisher.Mono; import java.util.List; public interface NewActionRepositoryCE extends BaseRepository<NewAction, String>, CustomNewActionRepository { - @Meta(cursorBatchSize = 10000) - Flux<NewAction> findByApplicationId(String applicationId); - - @Meta(cursorBatchSize = 10000) - Flux<NewAction> findAllByIdIn(Iterable<String> ids); - - Mono<Long> countByDeletedAtNull(); - Flux<IdPoliciesOnly> findIdsAndPolicyMapByApplicationIdIn(List<String> applicationIds); Flux<IdAndDatasourceIdNewActionView> findIdAndDatasourceIdByApplicationIdIn(List<String> applicationIds);
487001047c62f82397bdcc48c35a941cf9db1e30
2024-10-17 16:07:17
Abhijeet
chore: Add custom tag for pg build in ad-hoc image builder (#36913)
false
Add custom tag for pg build in ad-hoc image builder (#36913)
chore
diff --git a/.github/workflows/ad-hoc-docker-image.yml b/.github/workflows/ad-hoc-docker-image.yml index 30a8de48ea11..44cfce8435ee 100644 --- a/.github/workflows/ad-hoc-docker-image.yml +++ b/.github/workflows/ad-hoc-docker-image.yml @@ -14,6 +14,11 @@ on: required: false type: string default: ad-hoc + pg_tag: + description: Postgres tag to use for image + required: false + type: string + default: pg jobs: server-build: @@ -94,7 +99,7 @@ jobs: run: | run: | if [[ -f scripts/prepare_server_artifacts.sh ]]; then - scripts/prepare_server_artifacts.sh + PG_TAG=${{ inputs.pg_tag }} scripts/prepare_server_artifacts.sh else echo "No script found to prepare server artifacts" exit 1
c96c0d4f3bd2f37657c00251cb944c653f1bc528
2021-12-28 17:44:32
Favour Ohanekwu
feat: Show evaluated value in embeddedDatasource url (#9198)
false
Show evaluated value in embeddedDatasource url (#9198)
feat
diff --git a/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/ApiPaneTests/API_Edit_spec.js b/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/ApiPaneTests/API_Edit_spec.js index 97668db1ddc6..33c7c10ae9a5 100644 --- a/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/ApiPaneTests/API_Edit_spec.js +++ b/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/ApiPaneTests/API_Edit_spec.js @@ -1,5 +1,6 @@ const testdata = require("../../../../fixtures/testdata.json"); const apiwidget = require("../../../../locators/apiWidgetslocator.json"); +const commonlocators = require("../../../../locators/commonlocators.json"); describe("API Panel Test Functionality", function() { it("Test Search API fetaure", function() { @@ -73,4 +74,15 @@ describe("API Panel Test Functionality", function() { value: "mimeType='application/vnd.google-apps.spreadsheet'", }); }); + + it("Shows evaluated value pane when url field is focused", function() { + cy.NavigateToAPI_Panel(); + cy.CreateAPI("TestAPI"); + cy.get(".CodeMirror-placeholder") + .first() + .click({ + force: true, + }); + cy.get(commonlocators.evaluatedTypeTitle).should("be.visible"); + }); }); diff --git a/app/client/cypress/integration/Smoke_TestSuite/ServerSideTests/ApiPaneTests/API_Bugs_Spec.js b/app/client/cypress/integration/Smoke_TestSuite/ServerSideTests/ApiPaneTests/API_Bugs_Spec.js index bacb8dbf3d66..22653fc02e19 100644 --- a/app/client/cypress/integration/Smoke_TestSuite/ServerSideTests/ApiPaneTests/API_Bugs_Spec.js +++ b/app/client/cypress/integration/Smoke_TestSuite/ServerSideTests/ApiPaneTests/API_Bugs_Spec.js @@ -36,7 +36,7 @@ describe("Rest Bugs tests", function() { ); cy.wait(1000); - cy.contains(commonlocators.entityName, "Page1").click(); + cy.contains(commonlocators.entityName, "Page1").click({ force: true }); cy.clickButton("Get Facts!"); cy.wait(8000); // for all api calls to complete! diff --git a/app/client/src/components/editorComponents/form/fields/EmbeddedDatasourcePathField.tsx b/app/client/src/components/editorComponents/form/fields/EmbeddedDatasourcePathField.tsx index c82c3cc4b327..cd883699fdf9 100644 --- a/app/client/src/components/editorComponents/form/fields/EmbeddedDatasourcePathField.tsx +++ b/app/client/src/components/editorComponents/form/fields/EmbeddedDatasourcePathField.tsx @@ -49,6 +49,11 @@ import { setDatsourceEditorMode } from "actions/datasourceActions"; import { getCurrentApplicationId } from "selectors/editorSelectors"; import { Colors } from "constants/Colors"; import { Indices } from "constants/Layers"; +import { getExpectedValue } from "utils/validation/common"; +import { ValidationTypes } from "constants/WidgetValidation"; +import { DataTree, ENTITY_TYPE } from "entities/DataTree/dataTreeFactory"; +import { getDataTree } from "selectors/dataTreeSelectors"; +import { KeyValuePair } from "entities/Action"; type ReduxStateProps = { orgId: string; @@ -56,6 +61,8 @@ type ReduxStateProps = { datasourceList: Datasource[]; currentPageId?: string; applicationId?: string; + dataTree: DataTree; + actionName: string; }; type ReduxDispatchProps = { @@ -313,6 +320,38 @@ class EmbeddedDatasourcePathComponent extends React.Component<Props> { }; }; + handleEvaluatedValue = () => { + const { actionName, datasource, dataTree } = this.props; + const entity = dataTree[actionName]; + + if (!entity) return ""; + + if ("ENTITY_TYPE" in entity && entity.ENTITY_TYPE === ENTITY_TYPE.ACTION) { + const evaluatedPath = "path" in entity.config ? entity.config.path : ""; + const evaluatedQueryParameters = entity.config.queryParameters + ?.filter((p: KeyValuePair) => p.key) + .map( + (p: KeyValuePair, i: number) => + `${i === 0 ? "?" : "&"}${p.key}=${p.value}`, + ) + .join(""); + + // When Api is generated from a datasource, + // url is gotten from the datasource's configuration + + const evaluatedDatasourceUrl = + "id" in datasource + ? datasource.datasourceConfiguration.url + : entity.datasourceUrl; + + const fullDatasourceUrlPath = + evaluatedDatasourceUrl + evaluatedPath + evaluatedQueryParameters; + + return fullDatasourceUrlPath; + } + return ""; + }; + render() { const { datasource, @@ -337,6 +376,7 @@ class EmbeddedDatasourcePathComponent extends React.Component<Props> { hinting: [bindingHint, this.handleDatasourceHint()], showLightningMenu: false, fill: true, + expected: getExpectedValue({ type: ValidationTypes.SAFE_URL }), }; return ( @@ -345,6 +385,8 @@ class EmbeddedDatasourcePathComponent extends React.Component<Props> { {...props} border={CodeEditorBorder.ALL_SIDE} className="t--datasource-editor" + evaluatedValue={this.handleEvaluatedValue()} + height="35px" /> {displayValue && datasource && !("id" in datasource) ? ( <StoreAsDatasource enable={!!displayValue} /> @@ -374,7 +416,7 @@ class EmbeddedDatasourcePathComponent extends React.Component<Props> { const mapStateToProps = ( state: AppState, - ownProps: { pluginId: string }, + ownProps: { pluginId: string; actionName: string }, ): ReduxStateProps => { const datasourceFromAction = apiFormValueSelector(state, "datasource"); let datasourceMerged = datasourceFromAction; @@ -400,6 +442,8 @@ const mapStateToProps = ( ), currentPageId: state.entities.pageList.currentPageId, applicationId: getCurrentApplicationId(state), + dataTree: getDataTree(state), + actionName: ownProps.actionName, }; }; @@ -420,6 +464,7 @@ function EmbeddedDatasourcePathField( pluginId: string; placeholder?: string; theme: EditorTheme; + actionName: string; }, ) { return ( diff --git a/app/client/src/entities/Action/actionProperties.test.ts b/app/client/src/entities/Action/actionProperties.test.ts index 9b058deab48e..1857e3350c74 100644 --- a/app/client/src/entities/Action/actionProperties.test.ts +++ b/app/client/src/entities/Action/actionProperties.test.ts @@ -28,6 +28,7 @@ describe("getBindingPathsOfAction", () => { data: EvaluationSubstitutionType.TEMPLATE, isLoading: EvaluationSubstitutionType.TEMPLATE, config: EvaluationSubstitutionType.TEMPLATE, + datasourceUrl: EvaluationSubstitutionType.TEMPLATE, }); }); @@ -76,6 +77,7 @@ describe("getBindingPathsOfAction", () => { expect(response).toStrictEqual({ data: EvaluationSubstitutionType.TEMPLATE, isLoading: EvaluationSubstitutionType.TEMPLATE, + datasourceUrl: EvaluationSubstitutionType.TEMPLATE, "config.body": EvaluationSubstitutionType.TEMPLATE, "config.body2": EvaluationSubstitutionType.TEMPLATE, "config.field1": EvaluationSubstitutionType.SMART_SUBSTITUTE, @@ -141,6 +143,7 @@ describe("getBindingPathsOfAction", () => { expect(response).toStrictEqual({ data: EvaluationSubstitutionType.TEMPLATE, isLoading: EvaluationSubstitutionType.TEMPLATE, + datasourceUrl: EvaluationSubstitutionType.TEMPLATE, "config.params[0].key": EvaluationSubstitutionType.TEMPLATE, "config.params[0].value": EvaluationSubstitutionType.TEMPLATE, "config.params[1].key": EvaluationSubstitutionType.TEMPLATE, @@ -196,6 +199,7 @@ describe("getBindingPathsOfAction", () => { expect(response).toStrictEqual({ data: EvaluationSubstitutionType.TEMPLATE, isLoading: EvaluationSubstitutionType.TEMPLATE, + datasourceUrl: EvaluationSubstitutionType.TEMPLATE, "config.key": EvaluationSubstitutionType.TEMPLATE, "config.value": EvaluationSubstitutionType.TEMPLATE, }); @@ -252,6 +256,7 @@ describe("getBindingPathsOfAction", () => { expect(response).toStrictEqual({ data: EvaluationSubstitutionType.TEMPLATE, isLoading: EvaluationSubstitutionType.TEMPLATE, + datasourceUrl: EvaluationSubstitutionType.TEMPLATE, "config.body": EvaluationSubstitutionType.TEMPLATE, "config.field1": EvaluationSubstitutionType.SMART_SUBSTITUTE, }); @@ -262,6 +267,7 @@ describe("getBindingPathsOfAction", () => { expect(response2).toStrictEqual({ data: EvaluationSubstitutionType.TEMPLATE, isLoading: EvaluationSubstitutionType.TEMPLATE, + datasourceUrl: EvaluationSubstitutionType.TEMPLATE, "config.body": EvaluationSubstitutionType.TEMPLATE, "config.body2": EvaluationSubstitutionType.TEMPLATE, }); diff --git a/app/client/src/entities/Action/actionProperties.ts b/app/client/src/entities/Action/actionProperties.ts index 9c9de74ed00d..95f7eb21ab17 100644 --- a/app/client/src/entities/Action/actionProperties.ts +++ b/app/client/src/entities/Action/actionProperties.ts @@ -23,6 +23,7 @@ export const getBindingPathsOfAction = ( const bindingPaths: Record<string, EvaluationSubstitutionType> = { data: EvaluationSubstitutionType.TEMPLATE, isLoading: EvaluationSubstitutionType.TEMPLATE, + datasourceUrl: EvaluationSubstitutionType.TEMPLATE, }; if (!formConfig) { return { diff --git a/app/client/src/entities/Action/index.ts b/app/client/src/entities/Action/index.ts index 6c71d1a53591..2f8dc1d63643 100644 --- a/app/client/src/entities/Action/index.ts +++ b/app/client/src/entities/Action/index.ts @@ -16,11 +16,18 @@ export enum PaginationType { URL = "URL", } +export interface KeyValuePair { + key?: string; + value?: unknown; +} + export interface ActionConfig { timeoutInMillisecond?: number; paginationType?: PaginationType; formData?: Record<string, unknown>; - pluginSpecifiedTemplates?: Array<{ key?: string; value?: unknown }>; + pluginSpecifiedTemplates?: KeyValuePair[]; + path?: string; + queryParameters?: KeyValuePair[]; } export interface ActionProvider { diff --git a/app/client/src/entities/DataTree/dataTreeAction.ts b/app/client/src/entities/DataTree/dataTreeAction.ts index 6e7f276f66c1..d0fe6d015c42 100644 --- a/app/client/src/entities/DataTree/dataTreeAction.ts +++ b/app/client/src/entities/DataTree/dataTreeAction.ts @@ -12,6 +12,8 @@ export const generateDataTreeAction = ( dependencyConfig: DependencyMap = {}, ): DataTreeAction => { let dynamicBindingPathList: DynamicPath[] = []; + let datasourceUrl = ""; + // update paths if ( action.config.dynamicBindingPathList && @@ -19,9 +21,17 @@ export const generateDataTreeAction = ( ) { dynamicBindingPathList = action.config.dynamicBindingPathList.map((d) => ({ ...d, - key: `config.${d.key}`, + key: d.key === "datasourceUrl" ? d.key : `config.${d.key}`, })); } + + if ( + action.config.datasource && + "datasourceConfiguration" in action.config.datasource + ) { + datasourceUrl = action.config.datasource.datasourceConfiguration.url; + } + const dependencyMap: DependencyMap = {}; Object.entries(dependencyConfig).forEach(([dependent, dependencies]) => { dependencyMap[getDataTreeActionConfigPath(dependent)] = dependencies.map( @@ -47,5 +57,6 @@ export const generateDataTreeAction = ( bindingPaths: getBindingPathsOfAction(action.config, editorConfig), dependencyMap, logBlackList: {}, + datasourceUrl, }; }; diff --git a/app/client/src/entities/DataTree/dataTreeFactory.ts b/app/client/src/entities/DataTree/dataTreeFactory.ts index af1b49915d83..26a4fe16f99e 100644 --- a/app/client/src/entities/DataTree/dataTreeFactory.ts +++ b/app/client/src/entities/DataTree/dataTreeFactory.ts @@ -56,6 +56,7 @@ export interface DataTreeAction ENTITY_TYPE: ENTITY_TYPE.ACTION; dependencyMap: DependencyMap; logBlackList: Record<string, true>; + datasourceUrl: string; } export interface DataTreeJSAction { diff --git a/app/client/src/pages/Editor/APIEditor/Form.tsx b/app/client/src/pages/Editor/APIEditor/Form.tsx index 2b8b651bcacc..6b83345ef5b7 100644 --- a/app/client/src/pages/Editor/APIEditor/Form.tsx +++ b/app/client/src/pages/Editor/APIEditor/Form.tsx @@ -617,6 +617,7 @@ function ApiEditorForm(props: Props) { </BoundaryContainer> <DatasourceWrapper className="t--dataSourceField"> <EmbeddedDatasourcePathField + actionName={actionName} name="actionConfiguration.path" placeholder="https://mock-api.appsmith.com/users" pluginId={pluginId} diff --git a/app/client/src/utils/DynamicBindingUtils.ts b/app/client/src/utils/DynamicBindingUtils.ts index 9d7dda32652c..a5559a895314 100644 --- a/app/client/src/utils/DynamicBindingUtils.ts +++ b/app/client/src/utils/DynamicBindingUtils.ts @@ -396,6 +396,21 @@ export function getDynamicBindingsChangesSaga( const bindingField = field.replace("actionConfiguration.", ""); let dynamicBindings: DynamicPath[] = action.dynamicBindingPathList || []; + if ( + action.datasource && + "datasourceConfiguration" in action.datasource && + field === "datasource" + ) { + // only the datasource.datasourceConfiguration.url can be a dynamic field + dynamicBindings = dynamicBindings.filter( + (binding) => binding.key !== "datasourceUrl", + ); + const datasourceUrl = action.datasource.datasourceConfiguration.url; + isDynamicValue(datasourceUrl) && + dynamicBindings.push({ key: "datasourceUrl" }); + return dynamicBindings; + } + // When a key-value pair is added or deleted from a fieldArray // Value is an Array representing the new fieldArray. @@ -433,6 +448,5 @@ export function getDynamicBindingsChangesSaga( dynamicBindings.push({ key: bindingField }); } } - return dynamicBindings; }
0b9857d44f8b77dde39f8bd1ee740ec36ff27720
2023-10-15 02:11:29
Dipyaman Biswas
feat: remove cloudHosting conditional check, change version name (#28086)
false
remove cloudHosting conditional check, change version name (#28086)
feat
diff --git a/app/client/src/ce/constants/messages.ts b/app/client/src/ce/constants/messages.ts index 76ae05963d33..48544eac1d26 100644 --- a/app/client/src/ce/constants/messages.ts +++ b/app/client/src/ce/constants/messages.ts @@ -8,15 +8,10 @@ export function createMessage( } /* - For self hosted, it displays the string "Appsmith Community v1.10.0" or "Appsmith Business v1.10.0". - For cloud hosting, it displays "Appsmith v1.10.0". - This is because Appsmith Cloud doesn't support business features yet. + For self hosted CE, it displays the string "Appsmith Community v1.10.0". */ -export const APPSMITH_DISPLAY_VERSION = ( - edition: string, - version: string, - cloudHosting: boolean, -) => `Appsmith ${!cloudHosting ? edition : ""} ${version}`; +export const APPSMITH_DISPLAY_VERSION = (edition: string, version: string) => + `Appsmith ${edition} ${version}`; export const INTERCOM_CONSENT_MESSAGE = () => `Can we have your email for better support?`; export const YES = () => `Yes`; diff --git a/app/client/src/ce/sagas/SuperUserSagas.tsx b/app/client/src/ce/sagas/SuperUserSagas.tsx index 9df0ffadcef2..0ef62940123c 100644 --- a/app/client/src/ce/sagas/SuperUserSagas.tsx +++ b/app/client/src/ce/sagas/SuperUserSagas.tsx @@ -38,7 +38,7 @@ export function* FetchAdminSettingsSaga() { const isValidResponse: boolean = yield validateResponse(response); if (isValidResponse) { - const { appVersion, cloudHosting } = getAppsmithConfigs(); + const { appVersion } = getAppsmithConfigs(); const settings = { //@ts-expect-error: response is of type unknown ...response.data, @@ -46,7 +46,6 @@ export function* FetchAdminSettingsSaga() { APPSMITH_DISPLAY_VERSION, appVersion.edition, appVersion.id, - cloudHosting, ), }; diff --git a/app/client/src/pages/Editor/FirstTimeUserOnboarding/HelpMenu.tsx b/app/client/src/pages/Editor/FirstTimeUserOnboarding/HelpMenu.tsx index f53b4d372ec8..42c9b327fe37 100644 --- a/app/client/src/pages/Editor/FirstTimeUserOnboarding/HelpMenu.tsx +++ b/app/client/src/pages/Editor/FirstTimeUserOnboarding/HelpMenu.tsx @@ -78,7 +78,7 @@ function HelpMenu(props: { > Help & Resources </Text> - <div className="flex gap-2 flex-wrap mt-2"> + <div className="flex flex-wrap gap-2 mt-2"> <Button data-testid="editor-welcome-tour" kind="secondary" @@ -126,7 +126,6 @@ function HelpMenu(props: { APPSMITH_DISPLAY_VERSION, appVersion.edition, appVersion.id, - cloudHosting, )} </StyledText> <StyledText color="var(--ads-v2-color-fg-muted)" kind={"action-s"}> diff --git a/app/client/src/pages/Editor/HelpButton.tsx b/app/client/src/pages/Editor/HelpButton.tsx index 975f552faad9..5f4b2ba6a614 100644 --- a/app/client/src/pages/Editor/HelpButton.tsx +++ b/app/client/src/pages/Editor/HelpButton.tsx @@ -299,7 +299,6 @@ function HelpButton() { APPSMITH_DISPLAY_VERSION, appVersion.edition, appVersion.id, - cloudHosting, )} </span> <span> diff --git a/app/client/src/pages/Home/LeftPaneBottomSection.tsx b/app/client/src/pages/Home/LeftPaneBottomSection.tsx index 69b595ac4606..ce702d72ff8c 100644 --- a/app/client/src/pages/Home/LeftPaneBottomSection.tsx +++ b/app/client/src/pages/Home/LeftPaneBottomSection.tsx @@ -62,7 +62,7 @@ function LeftPaneBottomSection() { const dispatch = useDispatch(); const onboardingWorkspaces = useSelector(getOnboardingWorkspaces); const isFetchingApplications = useSelector(getIsFetchingApplications); - const { appVersion, cloudHosting } = getAppsmithConfigs(); + const { appVersion } = getAppsmithConfigs(); const howMuchTimeBefore = howMuchTimeBeforeText(appVersion.releaseDate); const user = useSelector(getCurrentUser); const tenantPermissions = useSelector(getTenantPermissions); @@ -141,7 +141,6 @@ function LeftPaneBottomSection() { APPSMITH_DISPLAY_VERSION, appVersion.edition, appVersion.id, - cloudHosting, )} </span> {howMuchTimeBefore !== "" && ( diff --git a/app/client/src/pages/common/MobileSidebar.tsx b/app/client/src/pages/common/MobileSidebar.tsx index 1a4a2a98c245..bd25d1bd375e 100644 --- a/app/client/src/pages/common/MobileSidebar.tsx +++ b/app/client/src/pages/common/MobileSidebar.tsx @@ -86,7 +86,7 @@ const LeftPaneVersionData = styled.div` export default function MobileSideBar(props: MobileSideBarProps) { const user = useSelector(getCurrentUser); const tenantPermissions = useSelector(getTenantPermissions); - const { appVersion, cloudHosting } = getAppsmithConfigs(); + const { appVersion } = getAppsmithConfigs(); const howMuchTimeBefore = howMuchTimeBeforeText(appVersion.releaseDate); const isFeatureEnabled = useFeatureFlag(FEATURE_FLAG.license_gac_enabled); @@ -156,7 +156,6 @@ export default function MobileSideBar(props: MobileSideBarProps) { APPSMITH_DISPLAY_VERSION, appVersion.edition, appVersion.id, - cloudHosting, )} </span> {howMuchTimeBefore !== "" && (
89ae6a02d3441a80edd33c62f82e54ee800f2a35
2021-12-26 18:40:20
Rishabh Saxena
fix: connect git via global config (#9982)
false
connect git via global config (#9982)
fix
diff --git a/app/client/src/pages/Editor/gitSync/Tabs/GitConnection.tsx b/app/client/src/pages/Editor/gitSync/Tabs/GitConnection.tsx index f50c465af128..2e650941b9be 100644 --- a/app/client/src/pages/Editor/gitSync/Tabs/GitConnection.tsx +++ b/app/client/src/pages/Editor/gitSync/Tabs/GitConnection.tsx @@ -313,10 +313,9 @@ function GitConnection({ isImport }: Props) { }), ); } else { - const gitProfile = useGlobalConfigInputVal ? undefined : authorInfo; connectToGit({ remoteUrl, - gitProfile, + gitProfile: authorInfo, isImport, isDefaultProfile: useGlobalConfigInputVal, });
8ee2586f757023681067276d2fdea41cf489bf6e
2023-12-08 11:01:21
Apeksha Bhosale
fix: added query module instance to one click (#29411)
false
added query module instance to one click (#29411)
fix
diff --git a/app/client/src/ce/constants/ModuleInstanceConstants.ts b/app/client/src/ce/constants/ModuleInstanceConstants.ts index ad6900bf65f0..38707bd19024 100644 --- a/app/client/src/ce/constants/ModuleInstanceConstants.ts +++ b/app/client/src/ce/constants/ModuleInstanceConstants.ts @@ -1,4 +1,5 @@ import type { MODULE_TYPE } from "@appsmith/constants/ModuleConstants"; +import type { ActionResponse } from "api/ActionAPI"; export type ModuleId = string; export type ModuleInstanceId = string; @@ -15,3 +16,10 @@ export interface ModuleInstance { [key: string]: string; }; } + +export interface ModuleInstanceData { + config: ModuleInstance; + data: ActionResponse; + isLoading: boolean; +} +export type ModuleInstanceDataState = ModuleInstanceData[]; diff --git a/app/client/src/ce/selectors/entitiesSelector.ts b/app/client/src/ce/selectors/entitiesSelector.ts index 61a6087be029..d998808777ba 100644 --- a/app/client/src/ce/selectors/entitiesSelector.ts +++ b/app/client/src/ce/selectors/entitiesSelector.ts @@ -1331,7 +1331,10 @@ export function getInputsForModule(): Module["inputsForm"] { return []; } -export const getModuleInstances = (): Record<string, ModuleInstance> => { +export const getModuleInstances = ( + /* eslint-disable @typescript-eslint/no-unused-vars */ + state: AppState, +): Record<string, ModuleInstance> => { return {}; }; @@ -1341,3 +1344,7 @@ export const getModuleInstanceEntities = () => { jsCollections: [], }; }; + +export const getQueryModuleInstances = () => { + return []; +}; diff --git a/app/client/src/components/editorComponents/ActionCreator/helpers.tsx b/app/client/src/components/editorComponents/ActionCreator/helpers.tsx index 1cb846076890..4cbe03ee157e 100644 --- a/app/client/src/components/editorComponents/ActionCreator/helpers.tsx +++ b/app/client/src/components/editorComponents/ActionCreator/helpers.tsx @@ -1,3 +1,4 @@ +import type { ReactNode } from "react"; import React from "react"; import { getFunctionNameFromJsObjectExpression, @@ -17,16 +18,20 @@ import { PluginType } from "entities/Action"; import type { JSAction, Variable } from "entities/JSCollection"; import keyBy from "lodash/keyBy"; import { getActionConfig } from "pages/Editor/Explorer/Actions/helpers"; -import { JsFileIconV2 } from "pages/Editor/Explorer/ExplorerIcons"; +import { EntityIcon, JsFileIconV2 } from "pages/Editor/Explorer/ExplorerIcons"; import { useMemo } from "react"; import { useDispatch, useSelector } from "react-redux"; -import type { ActionDataState } from "@appsmith/reducers/entityReducers/actionsReducer"; +import type { + ActionData, + ActionDataState, +} from "@appsmith/reducers/entityReducers/actionsReducer"; import type { JSCollectionData } from "reducers/entityReducers/jsActionsReducer"; import { getCurrentPageId } from "selectors/editorSelectors"; import { getCurrentActions, getJSCollectionFromName, getCurrentJSCollections, + getQueryModuleInstances, } from "@appsmith/selectors/entitiesSelector"; import { getModalDropdownList, @@ -61,6 +66,8 @@ import { isJSAction, } from "@appsmith/workers/Evaluation/evaluationUtils"; import type { DataTreeEntity } from "entities/DataTree/dataTreeTypes"; +import type { ModuleInstanceDataState } from "@appsmith/constants/ModuleInstanceConstants"; +import { MODULE_TYPE } from "@appsmith/constants/ModuleConstants"; const actionList: { label: string; @@ -383,6 +390,16 @@ export function useModalDropdownList(handleClose: () => void) { return finalList; } +export const getQueryInstanceIcon = (type: MODULE_TYPE): ReactNode => { + if (type === MODULE_TYPE.QUERY) { + return ( + <EntityIcon> + <Icon name="module" /> + </EntityIcon> + ); + } +}; + export function getApiQueriesAndJSActionOptionsWithChildren( pageId: string, plugins: any, @@ -390,9 +407,16 @@ export function getApiQueriesAndJSActionOptionsWithChildren( jsActions: Array<JSCollectionData>, dispatch: any, handleClose: () => void, + queryModuleInstances: ModuleInstanceDataState, ) { // this function gets a list of all the queries/apis and attaches it to actionList - getApiAndQueryOptions(plugins, actions, dispatch, handleClose); + getApiAndQueryOptions( + plugins, + actions, + dispatch, + handleClose, + queryModuleInstances, + ); // this function gets a list of all the JS Objects and attaches it to actionList getJSOptions(pageId, jsActions, dispatch); @@ -405,6 +429,7 @@ function getApiAndQueryOptions( actions: ActionDataState, dispatch: any, handleClose: () => void, + queryModuleInstances: ModuleInstanceDataState, ) { const createQueryObject: TreeDropdownOption = { label: "New query", @@ -422,12 +447,12 @@ function getApiAndQueryOptions( }, }; - const queries = actions.filter( - (action) => action.config.pluginType === PluginType.DB, + const queries: ActionDataState = actions.filter( + (action: ActionData) => action.config.pluginType === PluginType.DB, ); - const apis = actions.filter( - (action) => + const apis: ActionDataState = actions.filter( + (action: ActionData) => action.config.pluginType === PluginType.API || action.config.pluginType === PluginType.SAAS || action.config.pluginType === PluginType.REMOTE || @@ -467,6 +492,15 @@ function getApiAndQueryOptions( ), } as TreeDropdownOption); }); + queryModuleInstances.forEach((instance) => { + (queryOptions.children as TreeDropdownOption[]).push({ + label: instance.config.name, + id: instance.config.id, + value: instance.config.name, + type: queryOptions.value, + icon: getQueryInstanceIcon(instance.config.type), + } as TreeDropdownOption); + }); } } @@ -546,6 +580,9 @@ export function useApisQueriesAndJsActionOptions(handleClose: () => void) { const pluginGroups: any = useMemo(() => keyBy(plugins, "id"), [plugins]); const actions = useSelector(getCurrentActions); const jsActions = useSelector(getCurrentJSCollections); + const queryModuleInstances = useSelector( + getQueryModuleInstances, + ) as unknown as ModuleInstanceDataState; // this function gets all the Queries/API's/JS Objects and attaches it to actionList return getApiQueriesAndJSActionOptionsWithChildren( @@ -555,5 +592,6 @@ export function useApisQueriesAndJsActionOptions(handleClose: () => void) { jsActions, dispatch, handleClose, + queryModuleInstances, ); } diff --git a/app/client/src/components/editorComponents/WidgetQueryGeneratorForm/CommonControls/DatasourceDropdown/useSource/useConnectToOptions.tsx b/app/client/src/components/editorComponents/WidgetQueryGeneratorForm/CommonControls/DatasourceDropdown/useSource/useConnectToOptions.tsx index 98ea15651143..23ca00414eef 100644 --- a/app/client/src/components/editorComponents/WidgetQueryGeneratorForm/CommonControls/DatasourceDropdown/useSource/useConnectToOptions.tsx +++ b/app/client/src/components/editorComponents/WidgetQueryGeneratorForm/CommonControls/DatasourceDropdown/useSource/useConnectToOptions.tsx @@ -4,6 +4,7 @@ import { getCurrentActions, getCurrentPageWidgets, getPluginIdPackageNamesMap, + getQueryModuleInstances, } from "@appsmith/selectors/entitiesSelector"; import WidgetFactory from "WidgetProvider/factory"; import { DatasourceImage, ImageWrapper } from "../../../styles"; @@ -17,6 +18,12 @@ import type { ActionData, ActionDataState, } from "@appsmith/reducers/entityReducers/actionsReducer"; +import { EntityIcon } from "pages/Editor/Explorer/ExplorerIcons"; +import { Icon } from "design-system"; +import type { + ModuleInstanceData, + ModuleInstanceDataState, +} from "@appsmith/constants/ModuleInstanceConstants"; enum SortingWeights { alphabetical = 1, @@ -26,7 +33,10 @@ enum SortingWeights { const SORT_INCREAMENT = 1; -function sortQueries(queries: ActionDataState, expectedDatatype: string) { +export function sortQueries( + queries: ActionDataState | ModuleInstanceDataState, + expectedDatatype: string, +) { return queries.sort((A, B) => { const score = { A: 0, @@ -63,7 +73,10 @@ function sortQueries(queries: ActionDataState, expectedDatatype: string) { }); } -function getBindingValue(widget: WidgetProps, query: ActionData) { +export function getBindingValue( + widget: WidgetProps, + query: ActionData | ModuleInstanceData, +) { const defaultBindingValue = `{{${query.config.name}.data}}`; const querySuggestedWidgets = query.data?.suggestedWidgets; if (!querySuggestedWidgets) return defaultBindingValue; @@ -78,6 +91,59 @@ interface ConnectToOptionsProps { widget: WidgetProps; } +export const getQueryIcon = ( + query: ActionData | ModuleInstanceData, + pluginImages: Record<string, string>, +) => { + if (!query.config.hasOwnProperty("sourceModuleId")) { + const action = query as ActionData; + return ( + <ImageWrapper> + <DatasourceImage + alt="" + className="dataSourceImage" + src={pluginImages[action.config.pluginId]} + /> + </ImageWrapper> + ); + } else { + return ( + <EntityIcon> + <Icon name="module" /> + </EntityIcon> + ); + } +}; + +export const getAnalyticsInfo = ( + query: ActionData | ModuleInstanceData, + widget: WidgetProps, + propertyName: string, +) => { + if (query.config.hasOwnProperty("pluginId")) { + const action = query as ActionData; + return { + widgetName: widget.widgetName, + widgetType: widget.type, + propertyName: propertyName, + entityBound: "Query", + entityName: action.config.name, + pluginType: action.config.pluginType, + }; + } + + if (query.config.hasOwnProperty("sourceModuleId")) { + return { + widgetName: widget.widgetName, + widgetType: widget.type, + propertyName: propertyName, + entityBound: "QueryModuleInstance", + entityName: query.config.name, + pluginType: "", + }; + } +}; + /* * useConnectToOptions hook - this returns the dropdown options to connect to a query or a connectable widget. * */ @@ -95,7 +161,9 @@ function useConnectToOptions(props: ConnectToOptionsProps) { const { pluginImages, widget } = props; - let filteredQueries = queries; + const queryModuleInstances = useSelector(getQueryModuleInstances); + let filteredQueries: ActionData[] | ModuleInstanceData[] = queries; + /* Exclude Gsheets from query options till this gets resolved https://github.com/appsmithorg/appsmith/issues/27102*/ if (widget.type === "JSON_FORM_WIDGET") { filteredQueries = queries.filter((query) => { @@ -106,20 +174,16 @@ function useConnectToOptions(props: ConnectToOptionsProps) { }); } + filteredQueries = [...filteredQueries, ...queryModuleInstances] as + | ActionDataState + | ModuleInstanceDataState; + const queryOptions = useMemo(() => { return sortQueries(filteredQueries, expectedType).map((query) => ({ id: query.config.id, label: query.config.name, value: getBindingValue(widget, query), - icon: ( - <ImageWrapper> - <DatasourceImage - alt="" - className="dataSourceImage" - src={pluginImages[query.config.pluginId]} - /> - </ImageWrapper> - ), + icon: getQueryIcon(query, pluginImages), onSelect: function (value?: string, valueOption?: DropdownOptionType) { addBinding(valueOption?.value, false); @@ -130,14 +194,10 @@ function useConnectToOptions(props: ConnectToOptionsProps) { datasourceConnectionMode: "", }); - AnalyticsUtil.logEvent("BIND_EXISTING_DATA_TO_WIDGET", { - widgetName: widget.widgetName, - widgetType: widget.type, - propertyName: propertyName, - entityBound: "Query", - entityName: query.config.name, - pluginType: query.config.pluginType, - }); + AnalyticsUtil.logEvent( + "BIND_EXISTING_DATA_TO_WIDGET", + getAnalyticsInfo(query, widget, propertyName), + ); }, })); }, [filteredQueries, pluginImages, addBinding, widget]); diff --git a/app/client/src/components/propertyControls/ActionSelectorControl.tsx b/app/client/src/components/propertyControls/ActionSelectorControl.tsx index c7b2fe890b20..001e7735bec6 100644 --- a/app/client/src/components/propertyControls/ActionSelectorControl.tsx +++ b/app/client/src/components/propertyControls/ActionSelectorControl.tsx @@ -17,6 +17,7 @@ import { canTranslateToUI, getActionBlocks } from "@shared/ast"; import { getActions, getJSCollections, + getModuleInstances, getPlugins, } from "@appsmith/selectors/entitiesSelector"; import store from "store"; @@ -24,6 +25,8 @@ import keyBy from "lodash/keyBy"; import { getCurrentPageId } from "selectors/editorSelectors"; import { getApiQueriesAndJSActionOptionsWithChildren } from "components/editorComponents/ActionCreator/helpers"; import { selectEvaluationVersion } from "@appsmith/selectors/applicationSelectors"; +import type { ModuleInstanceDataState } from "@appsmith/constants/ModuleInstanceConstants"; +import { MODULE_TYPE } from "@appsmith/constants/ModuleConstants"; class ActionSelectorControl extends BaseControl<ControlProps> { componentRef = React.createRef<HTMLDivElement>(); @@ -98,9 +101,22 @@ class ActionSelectorControl extends BaseControl<ControlProps> { const jsActions = getJSCollections(state); const codeFromProperty = getCodeFromMoustache(value?.trim() || ""); const evaluationVersion = selectEvaluationVersion(state); + const moduleInstances = getModuleInstances(state); + + const queryModuleInstances = Object.values(moduleInstances).map( + (instance) => { + if (instance.type === MODULE_TYPE.QUERY) { + return { + config: instance, + data: undefined, + }; + } + }, + ) as unknown as ModuleInstanceDataState; const actionsArray: string[] = []; const jsActionsArray: string[] = []; + const queryModuleInstanceArray: string[] = []; actions.forEach((action) => { actionsArray.push(action.config.name + ".run"); @@ -113,6 +129,11 @@ class ActionSelectorControl extends BaseControl<ControlProps> { }), ); + queryModuleInstances.forEach((instance) => { + queryModuleInstanceArray.push(instance.config.name + ".run"); + queryModuleInstanceArray.push(instance.config.name + ".clear"); + }); + const canTranslate = canTranslateToUI(codeFromProperty, evaluationVersion); if (codeFromProperty.trim() && !canTranslate) { @@ -135,6 +156,7 @@ class ActionSelectorControl extends BaseControl<ControlProps> { () => { return; }, + queryModuleInstances, ); try {
fa0e900f3f4931484b3092360d782c18362f2651
2022-02-08 00:48:20
Abhijeet
fix: Sort unordered set elements before committing to git repo so as to have same serialised output string for identical set of elements (#10933)
false
Sort unordered set elements before committing to git repo so as to have same serialised output string for identical set of elements (#10933)
fix
diff --git a/app/server/appsmith-git/pom.xml b/app/server/appsmith-git/pom.xml index 104c4856c5c8..58ef301c98d0 100644 --- a/app/server/appsmith-git/pom.xml +++ b/app/server/appsmith-git/pom.xml @@ -89,6 +89,11 @@ <artifactId>spring-test</artifactId> <scope>test</scope> </dependency> + <dependency> + <groupId>org.assertj</groupId> + <artifactId>assertj-core</artifactId> + <scope>test</scope> + </dependency> </dependencies> <build> diff --git a/app/server/appsmith-git/src/main/java/com/appsmith/git/converters/GsonDoubleToLongConverter.java b/app/server/appsmith-git/src/main/java/com/appsmith/git/converters/GsonDoubleToLongConverter.java new file mode 100644 index 000000000000..ce7dfdcfb507 --- /dev/null +++ b/app/server/appsmith-git/src/main/java/com/appsmith/git/converters/GsonDoubleToLongConverter.java @@ -0,0 +1,18 @@ +package com.appsmith.git.converters; + +import com.google.gson.JsonElement; +import com.google.gson.JsonPrimitive; +import com.google.gson.JsonSerializationContext; +import com.google.gson.JsonSerializer; + +import java.lang.reflect.Type; + +public class GsonDoubleToLongConverter implements JsonSerializer<Double> { + @Override + public JsonElement serialize(Double src, Type typeOfSrc, JsonSerializationContext context) { + if(src == src.longValue()) { + return new JsonPrimitive(src.longValue()); + } + return new JsonPrimitive(src); + } +} diff --git a/app/server/appsmith-git/src/main/java/com/appsmith/git/converters/GsonUnorderedToOrderedSetConverter.java b/app/server/appsmith-git/src/main/java/com/appsmith/git/converters/GsonUnorderedToOrderedSetConverter.java new file mode 100644 index 000000000000..580accdd7546 --- /dev/null +++ b/app/server/appsmith-git/src/main/java/com/appsmith/git/converters/GsonUnorderedToOrderedSetConverter.java @@ -0,0 +1,40 @@ +package com.appsmith.git.converters; + +import com.google.gson.Gson; +import com.google.gson.JsonArray; +import com.google.gson.JsonSerializationContext; +import com.google.gson.JsonSerializer; +import org.springframework.util.CollectionUtils; + +import javax.lang.model.type.PrimitiveType; +import java.lang.reflect.Type; +import java.util.Collection; +import java.util.Set; +import java.util.stream.Collectors; + +public class GsonUnorderedToOrderedSetConverter implements JsonSerializer<Set> { + @Override + public JsonArray serialize(Set src, Type typeOfSrc, JsonSerializationContext context) { + // Sort the set so that same elements will not end up in merge conflicts + return (JsonArray) new Gson().toJsonTree(getOrderedResource(src)); + } + + /** + * Sort the primitive datatype objects and string so that we will have predictable sorted output + * e.g. Input => ["abcd", "abc", "abcd1", "1abcd","xyz", "1xyz", "0xyz"] + * Output => ["0xyz","1abcd","1xyz","abc","abcd","abcd1","xyz"] + * + * @param objects set of objects which needs to be sorted before serialisation + * @param <T> + * @return sorted collection + */ + private <T> Collection<T> getOrderedResource(Set<T> objects) { + if (!CollectionUtils.isEmpty(objects)) { + T element = objects.iterator().next(); + if (element instanceof String || element instanceof PrimitiveType) { + return objects.stream().sorted().collect(Collectors.toList()); + } + } + return objects; + } +} diff --git a/app/server/appsmith-git/src/main/java/com/appsmith/git/helpers/FileUtilsImpl.java b/app/server/appsmith-git/src/main/java/com/appsmith/git/helpers/FileUtilsImpl.java index 16b5baf560bb..e34b25e64193 100644 --- a/app/server/appsmith-git/src/main/java/com/appsmith/git/helpers/FileUtilsImpl.java +++ b/app/server/appsmith-git/src/main/java/com/appsmith/git/helpers/FileUtilsImpl.java @@ -5,12 +5,10 @@ import com.appsmith.external.models.ApplicationGitReference; import com.appsmith.external.models.DatasourceStructure; import com.appsmith.git.configurations.GitServiceConfig; +import com.appsmith.git.converters.GsonDoubleToLongConverter; +import com.appsmith.git.converters.GsonUnorderedToOrderedSetConverter; import com.google.gson.Gson; import com.google.gson.GsonBuilder; -import com.google.gson.JsonElement; -import com.google.gson.JsonPrimitive; -import com.google.gson.JsonSerializationContext; -import com.google.gson.JsonSerializer; import com.google.gson.stream.JsonReader; import lombok.Getter; import lombok.RequiredArgsConstructor; @@ -29,7 +27,6 @@ import java.io.IOException; import java.io.InputStream; import java.io.StringWriter; -import java.lang.reflect.Type; import java.nio.charset.StandardCharsets; import java.nio.file.DirectoryNotEmptyException; import java.nio.file.Files; @@ -89,18 +86,12 @@ public Mono<Path> saveApplicationToGitRepo(Path baseRepoSuffix, Path baseRepo = Paths.get(gitServiceConfig.getGitRootPath()).resolve(baseRepoSuffix); - // Gson to pretty format JSON file and keep Integer type as is by default GSON have behavior to - // convert to Double + // Gson to pretty format JSON file + // Keep Long type as is by default GSON have behavior to convert to Double + // Convert unordered set to ordered one Gson gson = new GsonBuilder() - .registerTypeAdapter(Double.class, new JsonSerializer<Double>() { - - @Override - public JsonElement serialize(Double src, Type typeOfSrc, JsonSerializationContext context) { - if(src == src.longValue()) - return new JsonPrimitive(src.longValue()); - return new JsonPrimitive(src); - } - }) + .registerTypeAdapter(Double.class, new GsonDoubleToLongConverter()) + .registerTypeAdapter(Set.class, new GsonUnorderedToOrderedSetConverter()) .disableHtmlEscaping() .setPrettyPrinting() .create(); diff --git a/app/server/appsmith-git/src/main/java/com/appsmith/git/service/GitExecutorImpl.java b/app/server/appsmith-git/src/main/java/com/appsmith/git/service/GitExecutorImpl.java index 25ef3005f30a..7e38f34503e8 100644 --- a/app/server/appsmith-git/src/main/java/com/appsmith/git/service/GitExecutorImpl.java +++ b/app/server/appsmith-git/src/main/java/com/appsmith/git/service/GitExecutorImpl.java @@ -438,13 +438,22 @@ public Mono<GitStatusDTO> getStatus(Path repoPath, String branchName) { modifiedAssets.addAll(status.getRemoved()); modifiedAssets.addAll(status.getUncommittedChanges()); modifiedAssets.addAll(status.getUntracked()); + response.setAdded(status.getAdded()); + response.setRemoved(status.getRemoved()); + long modifiedPages = 0L; long modifiedQueries = 0L; + long modifiedJSObjects = 0L; + long modifiedDatasources = 0L; for (String x : modifiedAssets) { if (x.contains(GitDirectories.PAGE_DIRECTORY + "/")) { modifiedPages++; } else if (x.contains(GitDirectories.ACTION_DIRECTORY + "/")) { modifiedQueries++; + } else if (x.contains(GitDirectories.ACTION_COLLECTION_DIRECTORY + "/")) { + modifiedJSObjects++; + } else if (x.contains(GitDirectories.DATASOURCE_DIRECTORY + "/")) { + modifiedDatasources++; } } response.setModified(modifiedAssets); @@ -452,6 +461,8 @@ public Mono<GitStatusDTO> getStatus(Path repoPath, String branchName) { response.setIsClean(status.isClean()); response.setModifiedPages(modifiedPages); response.setModifiedQueries(modifiedQueries); + response.setModifiedJSObjects(modifiedJSObjects); + response.setModifiedDatasources(modifiedDatasources); BranchTrackingStatus trackingStatus = BranchTrackingStatus.of(git.getRepository(), branchName); if (trackingStatus != null) { diff --git a/app/server/appsmith-git/src/test/java/GsonDoubleToLongConverterTest.java b/app/server/appsmith-git/src/test/java/GsonDoubleToLongConverterTest.java new file mode 100644 index 000000000000..0abc56c7d005 --- /dev/null +++ b/app/server/appsmith-git/src/test/java/GsonDoubleToLongConverterTest.java @@ -0,0 +1,38 @@ +import com.appsmith.git.converters.GsonDoubleToLongConverter; +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import org.junit.Before; +import org.junit.Test; + +import static org.assertj.core.api.Assertions.assertThat; + +public class GsonDoubleToLongConverterTest { + private Gson gson; + + @Before + public void setUp() { + gson = new GsonBuilder() + .registerTypeAdapter(Double.class, new GsonDoubleToLongConverter()) + .create(); + } + + @Test + public void convert_whenNull_returnsNullString() { + String orderedData = gson.toJson((Object) null); + assertThat(orderedData).isEqualTo("null"); + } + + @Test + public void convert_withDoubleInput_returnsDoubleString() { + Double[] data = {1.00, 0.50, 1.50}; + String orderedData = gson.toJson(data); + assertThat(orderedData).isEqualTo("[1,0.5,1.5]"); + } + + @Test + public void convert_withLongInput_returnsLongString() { + Long[] data = {1L, 10L, 100L}; + String orderedData = gson.toJson(data); + assertThat(orderedData).isEqualTo("[1,10,100]"); + } +} diff --git a/app/server/appsmith-git/src/test/java/GsonUnorderedToOrderedSetTest.java b/app/server/appsmith-git/src/test/java/GsonUnorderedToOrderedSetTest.java new file mode 100644 index 000000000000..2698b1c5c662 --- /dev/null +++ b/app/server/appsmith-git/src/test/java/GsonUnorderedToOrderedSetTest.java @@ -0,0 +1,41 @@ +import com.appsmith.git.converters.GsonUnorderedToOrderedSetConverter; +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import org.junit.Before; +import org.junit.Test; + +import java.util.HashSet; +import java.util.Set; + +import static org.assertj.core.api.Assertions.assertThat; + +public class GsonUnorderedToOrderedSetTest { + private Gson gson; + + @Before + public void setUp() { + gson = new GsonBuilder() + .registerTypeAdapter(Set.class, new GsonUnorderedToOrderedSetConverter()) + .create(); + } + + @Test + public void convert_whenEmptySet_returnsEmptyArrayString() { + Set data = new HashSet(); + String orderedData = gson.toJson(data); + assertThat(orderedData).isEqualTo("[]"); + } + + @Test + public void convert_whenNullSet_returnsNullString() { + String orderedData = gson.toJson((Object) null); + assertThat(orderedData).isEqualTo("null"); + } + + @Test + public void convert_withNonEmptySet_returnsOrderedArrayString() { + Set data = Set.of("abcd", "abc", "abcd1", "1abcd","xyz", "1xyz", "0xyz"); + String orderedData = gson.toJson(data, Set.class); + assertThat(orderedData).isEqualTo("[\"0xyz\",\"1abcd\",\"1xyz\",\"abc\",\"abcd\",\"abcd1\",\"xyz\"]"); + } +} diff --git a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/dtos/GitStatusDTO.java b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/dtos/GitStatusDTO.java index 1b051ad58a61..527ed9b2a4b3 100644 --- a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/dtos/GitStatusDTO.java +++ b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/dtos/GitStatusDTO.java @@ -10,9 +10,15 @@ @Data public class GitStatusDTO { - // Name of modified, added and deleted resources for local git repo + // Name of modified, added and deleted resources in local git repo Set<String> modified; + // Name of added resources to local git repo + Set<String> added; + + // Name of deleted resources from local git repo + Set<String> removed; + // Name of conflicting resources Set<String> conflicting; @@ -24,6 +30,12 @@ public class GitStatusDTO { // # of modified actions Long modifiedQueries; + // # of modified JSObjects + Long modifiedJSObjects; + + // # of modified JSObjects + Long modifiedDatasources; + // # of local commits which are not present in remote repo Integer aheadCount; diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/helpers/CompareDslActionDTO.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/helpers/CompareDslActionDTO.java new file mode 100644 index 000000000000..6afe8b58c045 --- /dev/null +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/helpers/CompareDslActionDTO.java @@ -0,0 +1,19 @@ +package com.appsmith.server.helpers; + +import com.appsmith.server.dtos.DslActionDTO; +import org.apache.commons.lang.StringUtils; + +import java.io.Serializable; +import java.util.Comparator; + +public class CompareDslActionDTO implements Comparator<DslActionDTO>, Serializable { + // Method to compare DslActionDTO based on id + @Override + public int compare(DslActionDTO action1, DslActionDTO action2) { + if (action1 != null && !StringUtils.isEmpty(action1.getId()) + && action2 != null && !StringUtils.isEmpty(action2.getId())) { + return action1.getId().compareTo(action2.getId()); + } + return 1; + } +} 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 30d4d769fbec..1a375fce0157 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 @@ -12,6 +12,7 @@ import com.appsmith.server.domains.NewPage; import com.appsmith.server.dtos.ActionCollectionDTO; import com.appsmith.server.dtos.ActionDTO; +import com.appsmith.server.dtos.DslActionDTO; import com.appsmith.server.dtos.PageDTO; import com.appsmith.server.exceptions.AppsmithError; import com.appsmith.server.exceptions.AppsmithException; @@ -35,6 +36,7 @@ import java.util.List; import java.util.Map; import java.util.Set; +import java.util.TreeSet; import java.util.stream.Collectors; import static com.appsmith.external.helpers.BeanCopyUtils.copyNestedNonNullProperties; @@ -304,8 +306,16 @@ private void removeUnwantedFieldsFromLayout(Layout layout) { layout.setAllOnPageLoadActionEdges(null); layout.setActionsUsedInDynamicBindings(null); layout.setMongoEscapedWidgetNames(null); + List<Set<DslActionDTO>> layoutOnLoadActions = layout.getLayoutOnLoadActions(); if (!CollectionUtils.isNullOrEmpty(layout.getLayoutOnLoadActions())) { - layout.getLayoutOnLoadActions().forEach(layoutAction -> layoutAction.forEach(actionDTO -> actionDTO.setDefaultActionId(null))); + // Sort actions based on id to commit to git in ordered manner + for (int dslActionIndex = 0; dslActionIndex < layoutOnLoadActions.size(); dslActionIndex++) { + TreeSet<DslActionDTO> sortedActions = new TreeSet<>(new CompareDslActionDTO()); + sortedActions.addAll(layoutOnLoadActions.get(dslActionIndex)); + sortedActions + .forEach(actionDTO -> actionDTO.setDefaultActionId(null)); + layoutOnLoadActions.set(dslActionIndex, sortedActions); + } } } diff --git a/app/server/appsmith-server/src/test/java/com/appsmith/server/helpers/CompareDslActionDTOTest.java b/app/server/appsmith-server/src/test/java/com/appsmith/server/helpers/CompareDslActionDTOTest.java new file mode 100644 index 000000000000..38bd381f048b --- /dev/null +++ b/app/server/appsmith-server/src/test/java/com/appsmith/server/helpers/CompareDslActionDTOTest.java @@ -0,0 +1,78 @@ +package com.appsmith.server.helpers; + +import com.appsmith.server.dtos.DslActionDTO; +import org.junit.Test; + +import java.util.LinkedList; +import java.util.List; +import java.util.Set; +import java.util.TreeSet; + +import static org.assertj.core.api.Assertions.assertThat; + +public class CompareDslActionDTOTest { + + List<String> sortedActionIds = new LinkedList<>(); + TreeSet<DslActionDTO> orderedActionSet = new TreeSet<>(new CompareDslActionDTO()); + + @Test + public void convert_whenNullActionIds_returnsSetInInputOrder() { + DslActionDTO action1 = new DslActionDTO(); + DslActionDTO action2 = new DslActionDTO(); + action1.setName("testName"); + action2.setName("testName2"); + Set<DslActionDTO> unorderedSet = Set.of(action1, action2); + orderedActionSet.addAll(unorderedSet); + List<String> sortedActionNames = new LinkedList<>(); + for (DslActionDTO dslActionDTO : orderedActionSet) { + sortedActionNames.add(dslActionDTO.getName()); + } + List<String> actionNames = new LinkedList<>(); + for (DslActionDTO dslActionDTO : unorderedSet) { + actionNames.add(dslActionDTO.getName()); + } + assertThat(sortedActionNames).isEqualTo(actionNames); + } + + @Test + public void convert_whenEmptyActionIdSet_returnsSetInInputOrder() { + DslActionDTO action1 = new DslActionDTO(); + DslActionDTO action2 = new DslActionDTO(); + action1.setId(""); + action2.setId("abcd"); + Set<DslActionDTO> actionSet = Set.of(action1, action2); + orderedActionSet.addAll(actionSet); + for (DslActionDTO dslActionDTO : orderedActionSet) { + sortedActionIds.add(dslActionDTO.getId()); + } + List<String> actionIds = new LinkedList<>(); + for (DslActionDTO dslActionDTO : actionSet) { + actionIds.add(dslActionDTO.getId()); + } + // Two lists are defined to be equal if they contain the same elements in the same order. + assertThat(sortedActionIds).isEqualTo(actionIds); + } + + @Test + public void convert_whenNonEmptySet_returnsOrderedResult() { + DslActionDTO action1 = new DslActionDTO(); + DslActionDTO action2 = new DslActionDTO(); + DslActionDTO action3 = new DslActionDTO(); + DslActionDTO action4 = new DslActionDTO(); + DslActionDTO action5 = new DslActionDTO(); + DslActionDTO action6 = new DslActionDTO(); + action1.setId("abc"); + action2.setId("0abc"); + action3.setId("1abc"); + action4.setId("abc0"); + action5.setId("abc1"); + action6.setId("abcd"); + Set<DslActionDTO> actionSet = Set.of(action1, action2, action3, action4, action5, action6); + orderedActionSet.addAll(actionSet); + for (DslActionDTO dslActionDTO : orderedActionSet) { + sortedActionIds.add(dslActionDTO.getId()); + } + // Two lists are defined to be equal if they contain the same elements in the same order. + assertThat(sortedActionIds).isEqualTo(List.of("0abc", "1abc", "abc", "abc0", "abc1", "abcd")); + } +}
a2cd1a8f2d0b4ec9f188dcb3a319fac45015df28
2023-11-10 15:29:20
Manish Kumar
chore: commented out a test case (#28692)
false
commented out a test case (#28692)
chore
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 5184a3a994c6..e9b308463a9a 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 @@ -1910,8 +1910,12 @@ public DatasourceStorageDTO generateSampleDatasourceStorageDTO() { return new DatasourceStorageDTO(null, defaultEnvironmentId, datasourceConfiguration); } - @Test - @WithUserDetails(value = "api_user") + /** + * This is commented out because of a different implementation in EE codebase, will figure out how to fix that + * without mocking the featureFlag. + */ + // @Test + // @WithUserDetails(value = "api_user") public void verifyOnlyOneStorageIsSaved() { Mockito.when(pluginExecutorHelper.getPluginExecutor(Mockito.any())) .thenReturn(Mono.just(new MockPluginExecutor()));
deaf9f9bead003357a4bcd231f87f24e7d36b4bd
2024-08-12 19:29:47
Nidhi
chore: Added multiple scripts to trigger profiles (#35546)
false
Added multiple scripts to trigger profiles (#35546)
chore
diff --git a/deploy/docker/fs/opt/appsmith/record-heap-dump.sh b/deploy/docker/fs/opt/appsmith/record-heap-dump.sh new file mode 100755 index 000000000000..4148a1c45ac4 --- /dev/null +++ b/deploy/docker/fs/opt/appsmith/record-heap-dump.sh @@ -0,0 +1,10 @@ +#!/bin/bash + +set -o errexit +set -o pipefail +set -o nounset +set -o noglob + +location=/appsmith-stacks/heap_dumps/ad-hoc/$(date "+%Y_%m_%d_%H_%S")/heap-profile; +mkdir -p $location; +jcmd $(pgrep -f -- "-jar\sserver.jar") GC.heap_dump filename=$location/${HOSTNAME}.log \ No newline at end of file diff --git a/deploy/docker/fs/opt/appsmith/record-thread-dump.sh b/deploy/docker/fs/opt/appsmith/record-thread-dump.sh new file mode 100755 index 000000000000..0b44d56d9474 --- /dev/null +++ b/deploy/docker/fs/opt/appsmith/record-thread-dump.sh @@ -0,0 +1,10 @@ +#!/bin/bash + +set -o errexit +set -o pipefail +set -o nounset +set -o noglob + +location=/appsmith-stacks/heap_dumps/ad-hoc/$(date "+%Y_%m_%d_%H_%S")/thread-profile; +mkdir -p $location; +jcmd $(pgrep -f -- "-jar\sserver.jar") Thread.print > $location/trace-${HOSTNAME}.log \ No newline at end of file diff --git a/deploy/docker/fs/opt/appsmith/thread-profile-start.sh b/deploy/docker/fs/opt/appsmith/thread-profile-start.sh new file mode 100755 index 000000000000..f7aed6c2c4c6 --- /dev/null +++ b/deploy/docker/fs/opt/appsmith/thread-profile-start.sh @@ -0,0 +1,10 @@ +#!/bin/bash + +set -o errexit +set -o pipefail +set -o nounset +set -o noglob + +location=/appsmith-stacks/heap_dumps/ad-hoc/$(date "+%Y_%m_%d_%H_%S")/thread-profile; +mkdir -p $location; +jcmd $(pgrep -f -- "-jar\sserver.jar") JFR.start name=profile filename=$location/profile-${HOSTNAME}.jfr \ No newline at end of file diff --git a/deploy/docker/fs/opt/appsmith/thread-profile-stop.sh b/deploy/docker/fs/opt/appsmith/thread-profile-stop.sh new file mode 100755 index 000000000000..b4d77507e155 --- /dev/null +++ b/deploy/docker/fs/opt/appsmith/thread-profile-stop.sh @@ -0,0 +1,8 @@ +#!/bin/bash + +set -o errexit +set -o pipefail +set -o nounset +set -o noglob + +jcmd $(pgrep -f -- "-jar\sserver.jar") JFR.dump name=profile \ No newline at end of file
afe630a4afbae7f36a297fbba9b90233bacbf3d2
2025-02-06 17:59:30
Ankita Kinger
chore: Updating data side pane component to get datasource usage map via props (#39066)
false
Updating data side pane component to get datasource usage map via props (#39066)
chore
diff --git a/app/client/src/IDE/Components/SidePaneWrapper.tsx b/app/client/src/IDE/Components/SidePaneWrapper.tsx index 5c1eaf1d88f7..a9883e96c84c 100644 --- a/app/client/src/IDE/Components/SidePaneWrapper.tsx +++ b/app/client/src/IDE/Components/SidePaneWrapper.tsx @@ -15,7 +15,6 @@ const StyledContainer = styled(Flex)<Pick<SidePaneContainerProps, "padded">>` function SidePaneWrapper({ children, padded = false }: SidePaneContainerProps) { return ( <StyledContainer - borderRight="1px solid var(--ads-v2-color-border)" flexDirection="column" height="100%" padded={padded} diff --git a/app/client/src/pages/Editor/IDE/EditorPane/Explorer.tsx b/app/client/src/pages/Editor/IDE/EditorPane/Explorer.tsx index 25f31d1b1960..8a4910e50818 100644 --- a/app/client/src/pages/Editor/IDE/EditorPane/Explorer.tsx +++ b/app/client/src/pages/Editor/IDE/EditorPane/Explorer.tsx @@ -1,4 +1,4 @@ -import React from "react"; +import React, { useMemo } from "react"; import { ExplorerContainer } from "@appsmith/ads"; import { Switch, useRouteMatch } from "react-router"; import { SentryRoute } from "ee/AppRouter"; @@ -18,17 +18,32 @@ import { import SegmentSwitcher from "./components/SegmentSwitcher"; import { useSelector } from "react-redux"; import { getIDEViewMode } from "selectors/ideSelectors"; -import { EditorViewMode } from "ee/entities/IDE/constants"; +import { EditorEntityTab, EditorViewMode } from "ee/entities/IDE/constants"; import { DEFAULT_EXPLORER_PANE_WIDTH } from "constants/AppConstants"; +import { useCurrentEditorState } from "../hooks"; const EditorPaneExplorer = () => { const { path } = useRouteMatch(); const ideViewMode = useSelector(getIDEViewMode); + const { segment } = useCurrentEditorState(); + + const widgetSegmentPaths = useMemo( + () => [ + BUILDER_PATH, + BUILDER_CUSTOM_PATH, + BUILDER_PATH_DEPRECATED, + ...widgetSegmentRoutes.map((route) => `${path}${route}`), + ], + [path], + ); return ( <ExplorerContainer borderRight={ - ideViewMode === EditorViewMode.SplitScreen ? "NONE" : "STANDARD" + ideViewMode === EditorViewMode.SplitScreen || + segment === EditorEntityTab.UI + ? "NONE" + : "STANDARD" } className="ide-editor-left-pane__content" width={ @@ -47,15 +62,7 @@ const EditorPaneExplorer = () => { component={QueryExplorer} path={querySegmentRoutes.map((route) => `${path}${route}`)} /> - <SentryRoute - component={WidgetsSegment} - path={[ - BUILDER_PATH, - BUILDER_CUSTOM_PATH, - BUILDER_PATH_DEPRECATED, - ...widgetSegmentRoutes.map((route) => `${path}${route}`), - ]} - /> + <SentryRoute component={WidgetsSegment} path={widgetSegmentPaths} /> </Switch> </ExplorerContainer> ); diff --git a/app/client/src/pages/Editor/IDE/EditorPane/UI/UIEntityListTree/WidgetContextMenu.tsx b/app/client/src/pages/Editor/IDE/EditorPane/UI/UIEntityListTree/WidgetContextMenu.tsx index 94793e042162..d96a524ed0d5 100644 --- a/app/client/src/pages/Editor/IDE/EditorPane/UI/UIEntityListTree/WidgetContextMenu.tsx +++ b/app/client/src/pages/Editor/IDE/EditorPane/UI/UIEntityListTree/WidgetContextMenu.tsx @@ -55,9 +55,6 @@ export const WidgetContextMenu = (props: { const menuContent = useMemo(() => { return ( <> - <MenuItem onClick={showBinding}> - {createMessage(CONTEXT_SHOW_BINDING)} - </MenuItem> <MenuItem disabled={!canManagePages} onClick={editWidgetName} @@ -65,6 +62,9 @@ export const WidgetContextMenu = (props: { > {createMessage(CONTEXT_RENAME)} </MenuItem> + <MenuItem onClick={showBinding} startIcon="binding-new"> + {createMessage(CONTEXT_SHOW_BINDING)} + </MenuItem> <MenuItem className="error-menuitem" disabled={!canManagePages && widget?.isDeletable !== false} diff --git a/app/client/src/pages/Editor/IDE/EditorPane/index.tsx b/app/client/src/pages/Editor/IDE/EditorPane/index.tsx index 5f520760579f..2c6c166a3d04 100644 --- a/app/client/src/pages/Editor/IDE/EditorPane/index.tsx +++ b/app/client/src/pages/Editor/IDE/EditorPane/index.tsx @@ -1,5 +1,5 @@ import React from "react"; -import { ExplorerContainerBorder, Flex } from "@appsmith/ads"; +import { Flex } from "@appsmith/ads"; import EditorPaneExplorer from "./Explorer"; import Editor from "./Editor"; import { useSelector } from "react-redux"; @@ -12,11 +12,6 @@ const EditorPane = () => { return ( <Flex - borderRight={ - ideViewMode === EditorViewMode.SplitScreen - ? ExplorerContainerBorder.STANDARD - : ExplorerContainerBorder.NONE - } className="ide-editor-left-pane" flexDirection={ ideViewMode === EditorViewMode.SplitScreen ? "column" : "row" diff --git a/app/client/src/pages/Editor/IDE/Header/index.tsx b/app/client/src/pages/Editor/IDE/Header/index.tsx index c26b641ba40d..66b1b86cf722 100644 --- a/app/client/src/pages/Editor/IDE/Header/index.tsx +++ b/app/client/src/pages/Editor/IDE/Header/index.tsx @@ -1,6 +1,5 @@ import React, { useState } from "react"; import { - Flex, Divider, Modal, ModalContent, @@ -158,41 +157,39 @@ const Header = () => { <EditorSaveIndicator isSaving={isSaving} saveError={pageSaveError} /> </IDEHeader.Left> <IDEHeader.Center> - <Flex alignItems={"center"}> - {currentWorkspace.name && ( - <> - <Link className="mr-1.5" to={APPLICATIONS_URL}> - {currentWorkspace.name} - </Link> - {"/"} - <EditorName - applicationId={applicationId} - className="t--application-name editable-application-name max-w-48" - defaultSavingState={ - isSavingName ? SavingState.STARTED : SavingState.NOT_STARTED - } - defaultValue={currentApplication?.name || ""} - editInteractionKind={EditInteractionKind.SINGLE} - editorName="Application" - fill - getNavigationMenu={useNavigationMenuData} - isError={isErroredSavingName} - isNewEditor={ - applicationList.filter((el) => el.id === applicationId) - .length > 0 - } - isPopoverOpen={isPopoverOpen} - onBlur={(value: string) => - updateApplicationDispatch(applicationId || "", { - name: value, - currentApp: true, - }) - } - setIsPopoverOpen={setIsPopoverOpen} - /> - </> - )} - </Flex> + {currentWorkspace.name && ( + <> + <Link className="mr-1.5" to={APPLICATIONS_URL}> + {currentWorkspace.name} + </Link> + {"/"} + <EditorName + applicationId={applicationId} + className="t--application-name editable-application-name max-w-48" + defaultSavingState={ + isSavingName ? SavingState.STARTED : SavingState.NOT_STARTED + } + defaultValue={currentApplication?.name || ""} + editInteractionKind={EditInteractionKind.SINGLE} + editorName="Application" + fill + getNavigationMenu={useNavigationMenuData} + isError={isErroredSavingName} + isNewEditor={ + applicationList.filter((el) => el.id === applicationId) + .length > 0 + } + isPopoverOpen={isPopoverOpen} + onBlur={(value: string) => + updateApplicationDispatch(applicationId || "", { + name: value, + currentApp: true, + }) + } + setIsPopoverOpen={setIsPopoverOpen} + /> + </> + )} </IDEHeader.Center> <IDEHeader.Right> <HelpBar /> 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 42a994c05c73..6d040c9a2fc5 100644 --- a/app/client/src/pages/Editor/IDE/LeftPane/DataSidePane.test.tsx +++ b/app/client/src/pages/Editor/IDE/LeftPane/DataSidePane.test.tsx @@ -7,6 +7,8 @@ import { getIDETestState } from "test/factories/AppIDEFactoryUtils"; 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"; const productsDS = datasourceFactory().build({ name: "Products", @@ -34,13 +36,15 @@ const ordersAction1 = PostgresFactory.build({ }); describe("DataSidePane", () => { - it("renders the ds and count by using the default selector if dsUsageSelector not passed as a props", () => { + it("renders the ds and count by using the dsUsageMap passed as props", () => { const state = getIDETestState({ actions: [usersAction1, usersAction2, ordersAction1], datasources: [productsDS, usersDS, ordersDS], }) as AppState; - render(<DataSidePane />, { + const dsUsageMap = getDatasourceUsageCountForApp(state, IDE_TYPE.App); + + render(<DataSidePane dsUsageMap={dsUsageMap} />, { url: "/app/untitled-application-1/page1-678a356f18346f618bc2c80a/edit/datasource/users-ds-id", initialState: state, }); @@ -66,41 +70,4 @@ describe("DataSidePane", () => { "1 queries in this app", ); }); - - it("it uses the selector dsUsageSelector passed as prop", () => { - const state = getIDETestState({ - datasources: [productsDS, usersDS, ordersDS], - }) as AppState; - - const usageSelector = () => { - return { - [usersDS.id]: "Rendering description for users", - [productsDS.id]: "Rendering description for products", - }; - }; - - render(<DataSidePane dsUsageSelector={usageSelector} />, { - url: "/app/untitled-application-1/page1-2/edit/datasource/users-ds-id", - initialState: state, - }); - - expect(screen.getByText("Databases")).toBeInTheDocument(); - - expect(screen.getAllByRole("listitem")).toHaveLength(3); - - expect(screen.getAllByRole("listitem")[0].textContent).toContain( - "Products", - ); - expect(screen.getAllByRole("listitem")[0].textContent).toContain( - "Rendering description for products", - ); - - expect(screen.getAllByRole("listitem")[1].textContent).toContain("Users"); - expect(screen.getAllByRole("listitem")[1].textContent).toContain( - "Rendering description for users", - ); - - // No description for orders as not passed in by the selector - expect(screen.getAllByRole("listitem")[2].textContent).toEqual("Orders"); - }); }); diff --git a/app/client/src/pages/Editor/IDE/LeftPane/DataSidePane.tsx b/app/client/src/pages/Editor/IDE/LeftPane/DataSidePane.tsx index fe1fd09a857f..5c32f24131ac 100644 --- a/app/client/src/pages/Editor/IDE/LeftPane/DataSidePane.tsx +++ b/app/client/src/pages/Editor/IDE/LeftPane/DataSidePane.tsx @@ -3,7 +3,6 @@ import styled from "styled-components"; import { EntityGroupsList, Flex } from "@appsmith/ads"; import { useSelector } from "react-redux"; import { - getDatasourceUsageCountForApp, getDatasources, getDatasourcesGroupedByPluginCategory, getPlugins, @@ -30,7 +29,6 @@ import { getHasCreateDatasourcePermission } from "ee/utils/BusinessFeatures/perm import { EmptyState } from "@appsmith/ads"; import { getAssetUrl } from "ee/utils/airgapHelpers"; import { getCurrentBasePageId } from "selectors/editorSelectors"; -import { getIDETypeByUrl } from "ee/entities/IDE/utils"; const PaneBody = styled.div` padding: var(--ads-v2-spaces-3) 0; @@ -44,13 +42,11 @@ const DatasourceIcon = styled.img` `; interface DataSidePaneProps { - // TODO: Fix this the next time the file is edited - // eslint-disable-next-line @typescript-eslint/no-explicit-any - dsUsageSelector?: (...args: any[]) => Record<string, string>; + dsUsageMap: Record<string, string>; } const DataSidePane = (props: DataSidePaneProps) => { - const { dsUsageSelector = getDatasourceUsageCountForApp } = props; + const { dsUsageMap } = props; const basePageId = useSelector(getCurrentBasePageId) as string; const [currentSelectedDatasource, setCurrentSelectedDatasource] = useState< string | undefined @@ -60,8 +56,6 @@ const DataSidePane = (props: DataSidePaneProps) => { const plugins = useSelector(getPlugins); const groupedPlugins = keyBy(plugins, "id"); const location = useLocation(); - const ideType = getIDETypeByUrl(location.pathname); - const dsUsageMap = useSelector((state) => dsUsageSelector(state, ideType)); const goToDatasource = useCallback((id: string) => { history.push(datasourcesEditorIdURL({ datasourceId: id })); }, []); @@ -101,12 +95,7 @@ const DataSidePane = (props: DataSidePaneProps) => { ); return ( - <Flex - borderRight="1px solid var(--ads-v2-color-border)" - flexDirection="column" - height="100%" - width="100%" - > + <Flex flexDirection="column" height="100%" width="100%"> <PaneHeader rightIcon={ canCreateDatasource && datasources.length !== 0 ? ( diff --git a/app/client/src/pages/Editor/IDE/LeftPane/index.tsx b/app/client/src/pages/Editor/IDE/LeftPane/index.tsx index 60a8eb743cb2..a8b152005e73 100644 --- a/app/client/src/pages/Editor/IDE/LeftPane/index.tsx +++ b/app/client/src/pages/Editor/IDE/LeftPane/index.tsx @@ -1,4 +1,5 @@ import React, { useMemo } from "react"; +import { useSelector } from "react-redux"; import styled from "styled-components"; import { Switch, useRouteMatch } from "react-router"; import { SentryRoute } from "ee/AppRouter"; @@ -15,11 +16,12 @@ import AppSettingsPane from "./AppSettings"; 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"; -export const LeftPaneContainer = styled.div<{ showRightBorder?: boolean }>` +export const LeftPaneContainer = styled.div` height: 100%; - border-right: ${({ showRightBorder = true }) => - showRightBorder ? "1px solid var(--ads-v2-color-border)" : "none"}; + border-right: 1px solid var(--ads-v2-color-border); background: var(--ads-v2-color-bg); overflow: hidden; `; @@ -45,10 +47,20 @@ const LeftPane = () => { [path], ); + const dsUsageMap = useSelector((state) => + getDatasourceUsageCountForApp(state, IDE_TYPE.App), + ); + return ( - <LeftPaneContainer showRightBorder={false}> + <LeftPaneContainer> <Switch> - <SentryRoute component={DataSidePane} exact path={dataSidePanePaths} /> + <SentryRoute + exact + path={dataSidePanePaths} + render={(routeProps) => ( + <DataSidePane {...routeProps} dsUsageMap={dsUsageMap} /> + )} + /> <SentryRoute component={LibrarySidePane} exact diff --git a/app/client/src/pages/Editor/commons/EditorSettingsPaneContainer.tsx b/app/client/src/pages/Editor/commons/EditorSettingsPaneContainer.tsx index bd3950310873..a0c9b53543fe 100644 --- a/app/client/src/pages/Editor/commons/EditorSettingsPaneContainer.tsx +++ b/app/client/src/pages/Editor/commons/EditorSettingsPaneContainer.tsx @@ -14,8 +14,6 @@ const SettingsPageWrapper = styled.div` &:nth-child(2) { height: 100%; } - - border-right: 1px solid var(--ads-v2-color-border); `; const EditorSettingsPaneContainer = ({
fd0f3d889a29c58f5e02664cd0caa93c5f05d21b
2021-11-01 16:43:54
balajisoundar
chore: Comment super user cypress test (#8945)
false
Comment super user cypress test (#8945)
chore
diff --git a/app/client/cypress/setup-test.sh b/app/client/cypress/setup-test.sh index 54de05c48211..47d47f2ff4c5 100755 --- a/app/client/cypress/setup-test.sh +++ b/app/client/cypress/setup-test.sh @@ -78,6 +78,42 @@ if [ "$status_code" -eq "502" ]; then exit 1 fi +# Create the test user +curl -k --request POST -v 'https://dev.appsmith.com/api/v1/users' \ +--header 'Content-Type: application/json' \ +--data-raw '{ + "name" : "'"$CYPRESS_USERNAME"'", + "email" : "'"$CYPRESS_USERNAME"'", + "source" : "FORM", + "state" : "ACTIVATED", + "isEnabled" : "true", + "password": "'"$CYPRESS_PASSWORD"'" +}' + +#Create another testUser1 +curl -k --request POST -v 'https://dev.appsmith.com/api/v1/users' \ +--header 'Content-Type: application/json' \ +--data-raw '{ + "name" : "'"$CYPRESS_TESTUSERNAME1"'", + "email" : "'"$CYPRESS_TESTUSERNAME1"'", + "source" : "FORM", + "state" : "ACTIVATED", + "isEnabled" : "true", + "password": "'"$CYPRESS_TESTPASSWORD1"'" +}' + +#Create another testUser2 +curl -k --request POST -v 'https://dev.appsmith.com/api/v1/users' \ +--header 'Content-Type: application/json' \ +--data-raw '{ + "name" : "'"$CYPRESS_TESTUSERNAME2"'", + "email" : "'"$CYPRESS_TESTUSERNAME2"'", + "source" : "FORM", + "state" : "ACTIVATED", + "isEnabled" : "true", + "password": "'"$CYPRESS_TESTPASSWORD2"'" +}' + # DEBUG=cypress:* $(npm bin)/cypress version # sed -i -e "s|api_url:.*$|api_url: $CYPRESS_URL|g" /github/home/.cache/Cypress/4.1.0/Cypress/resources/app/packages/server/config/app.yml # cat /github/home/.cache/Cypress/4.1.0/Cypress/resources/app/packages/server/config/app.yml diff --git a/app/client/cypress/support/index.js b/app/client/cypress/support/index.js index b790b6bc90f5..1c34550adb36 100644 --- a/app/client/cypress/support/index.js +++ b/app/client/cypress/support/index.js @@ -38,20 +38,21 @@ before(function() { window.indexedDB.deleteDatabase("Appsmith"); }); - cy.visit("/setup/welcome"); - cy.wait("@getUser"); - cy.url().then((url) => { - if (url.indexOf("setup/welcome") > -1) { - cy.createSuperUser(); - cy.LogOut(); - } - }); + //Temporary commented out to fix loginFromApi command + // cy.visit("/setup/welcome"); + // cy.wait("@getUser"); + // cy.url().then((url) => { + // if (url.indexOf("setup/welcome") > -1) { + // cy.createSuperUser(); + // cy.LogOut(); + // } + // }); - cy.SignupFromAPI(Cypress.env("TESTUSERNAME1"), Cypress.env("TESTPASSWORD1")); - cy.SignupFromAPI(Cypress.env("TESTUSERNAME2"), Cypress.env("TESTPASSWORD2")); - cy.LogOut(); - initLocalstorage(); - Cypress.Cookies.preserveOnce("SESSION"); + // cy.SignupFromAPI(Cypress.env("TESTUSERNAME1"), Cypress.env("TESTPASSWORD1")); + // cy.SignupFromAPI(Cypress.env("TESTUSERNAME2"), Cypress.env("TESTPASSWORD2")); + // cy.LogOut(); + // initLocalstorage(); + // Cypress.Cookies.preserveOnce("SESSION"); const username = Cypress.env("USERNAME"); const password = Cypress.env("PASSWORD"); cy.LoginFromAPI(username, password);
d03d195c6e2666c54adf60069b7062fb5be217ee
2024-01-04 15:26:18
arunvjn
chore: "Revert Lazy load autocomplete and linting services" (#30035)
false
"Revert Lazy load autocomplete and linting services" (#30035)
chore
diff --git a/app/client/src/components/editorComponents/CodeEditor/hintHelpers.ts b/app/client/src/components/editorComponents/CodeEditor/hintHelpers.ts index a0e2117590f5..b80d5ec00ccf 100644 --- a/app/client/src/components/editorComponents/CodeEditor/hintHelpers.ts +++ b/app/client/src/components/editorComponents/CodeEditor/hintHelpers.ts @@ -1,6 +1,6 @@ import type { Hints } from "codemirror"; import CodeMirror from "codemirror"; -import { getCodeMirrorTernService } from "utils/autocomplete/CodemirrorTernService"; +import CodemirrorTernService from "utils/autocomplete/CodemirrorTernService"; import KeyboardShortcuts from "constants/KeyboardShortcuts"; import type { HintHelper } from "components/editorComponents/CodeEditor/EditorConfig"; import { EditorModes } from "components/editorComponents/CodeEditor/EditorConfig"; @@ -17,17 +17,16 @@ import { import { isAISlashCommand } from "@appsmith/components/editorComponents/GPT/trigger"; export const bindingHintHelper: HintHelper = (editor: CodeMirror.Editor) => { - const codeMirrorTernService = getCodeMirrorTernService(); editor.setOption("extraKeys", { // @ts-expect-error: Types are not available ...editor.options.extraKeys, [KeyboardShortcuts.CodeEditor.OpenAutocomplete]: (cm: CodeMirror.Editor) => - checkIfCursorInsideBinding(cm) && codeMirrorTernService.complete(cm), + checkIfCursorInsideBinding(cm) && CodemirrorTernService.complete(cm), [KeyboardShortcuts.CodeEditor.ShowTypeAndInfo]: (cm: CodeMirror.Editor) => { - codeMirrorTernService.showType(cm); + CodemirrorTernService.showType(cm); }, [KeyboardShortcuts.CodeEditor.OpenDocsLink]: (cm: CodeMirror.Editor) => { - codeMirrorTernService.showDocs(cm); + CodemirrorTernService.showDocs(cm); }, }); return { @@ -37,12 +36,12 @@ export const bindingHintHelper: HintHelper = (editor: CodeMirror.Editor) => { additionalData, ): boolean => { if (additionalData && additionalData.blockCompletions) { - codeMirrorTernService.setEntityInformation(editor, { + CodemirrorTernService.setEntityInformation(editor, { ...entityInformation, blockCompletions: additionalData.blockCompletions, }); } else { - codeMirrorTernService.setEntityInformation(editor, entityInformation); + CodemirrorTernService.setEntityInformation(editor, entityInformation); } let shouldShow = false; @@ -58,7 +57,7 @@ export const bindingHintHelper: HintHelper = (editor: CodeMirror.Editor) => { } if (shouldShow) { - codeMirrorTernService.complete(editor); + CodemirrorTernService.complete(editor); return true; } diff --git a/app/client/src/components/editorComponents/CodeEditor/index.tsx b/app/client/src/components/editorComponents/CodeEditor/index.tsx index 088459ff1f2a..9421ab96b15b 100644 --- a/app/client/src/components/editorComponents/CodeEditor/index.tsx +++ b/app/client/src/components/editorComponents/CodeEditor/index.tsx @@ -164,7 +164,7 @@ import { resetActiveEditorField, setActiveEditorField, } from "actions/activeFieldActions"; -import { getCodeMirrorTernService } from "utils/autocomplete/CodemirrorTernService"; +import CodeMirrorTernService from "utils/autocomplete/CodemirrorTernService"; type ReduxStateProps = ReturnType<typeof mapStateToProps>; type ReduxDispatchProps = ReturnType<typeof mapDispatchToProps>; @@ -548,7 +548,7 @@ class CodeEditor extends Component<Props, State> { debouncedArgHints = _.debounce(() => { this.setState({ - ternToolTipActive: getCodeMirrorTernService().updateArgHints(this.editor), + ternToolTipActive: CodeMirrorTernService.updateArgHints(this.editor), }); }, 200); @@ -686,7 +686,7 @@ class CodeEditor extends Component<Props, State> { }); if (this.state.ternToolTipActive) { - getCodeMirrorTernService().closeArgHints(); + CodeMirrorTernService.closeArgHints(); } AnalyticsUtil.logEvent("PEEK_OVERLAY_OPENED", { property: expression, @@ -704,9 +704,7 @@ class CodeEditor extends Component<Props, State> { } if (this.state.ternToolTipActive) { this.setState({ - ternToolTipActive: getCodeMirrorTernService().updateArgHints( - this.editor, - ), + ternToolTipActive: CodeMirrorTernService.updateArgHints(this.editor), }); } }; @@ -915,7 +913,7 @@ class CodeEditor extends Component<Props, State> { // @ts-expect-error: Types are not available this.editor.closeHint(); - getCodeMirrorTernService().closeArgHints(); + CodeMirrorTernService.closeArgHints(); } private handleKeydown = (e: KeyboardEvent) => { diff --git a/app/client/src/entities/Engine/AppEditorEngine.ts b/app/client/src/entities/Engine/AppEditorEngine.ts index c4e8e9f8f13e..ddb46f18e916 100644 --- a/app/client/src/entities/Engine/AppEditorEngine.ts +++ b/app/client/src/entities/Engine/AppEditorEngine.ts @@ -51,7 +51,7 @@ import AppEngine, { PluginsNotFoundError, } from "."; import { fetchJSLibraries } from "actions/JSLibraryActions"; -import { getCodeMirrorTernService } from "utils/autocomplete/CodemirrorTernService"; +import CodemirrorTernService from "utils/autocomplete/CodemirrorTernService"; import { waitForSegmentInit, waitForFetchUserSuccess, @@ -97,7 +97,7 @@ export default class AppEditorEngine extends AppEngine { public *setupEngine(payload: AppEnginePayload): any { yield* super.setupEngine.call(this, payload); yield put(resetEditorSuccess()); - getCodeMirrorTernService().resetServer(); + CodemirrorTernService.resetServer(); } public startPerformanceTracking() { diff --git a/app/client/src/pages/Editor/CustomWidgetBuilder/Editor/CodeEditors/JSEditor.tsx b/app/client/src/pages/Editor/CustomWidgetBuilder/Editor/CodeEditors/JSEditor.tsx index 2f2f7bcf4167..aa86f29fdc22 100644 --- a/app/client/src/pages/Editor/CustomWidgetBuilder/Editor/CodeEditors/JSEditor.tsx +++ b/app/client/src/pages/Editor/CustomWidgetBuilder/Editor/CodeEditors/JSEditor.tsx @@ -11,7 +11,10 @@ import { import { CustomWidgetBuilderContext } from "../.."; import LazyCodeEditor from "components/editorComponents/LazyCodeEditor"; import { getAppsmithScriptSchema } from "widgets/CustomWidget/component/constants"; -import { getCodeMirrorTernService } from "utils/autocomplete/CodemirrorTernService"; +// import { DebuggerLogType } from "../../types"; +// import { PropertyEvaluationErrorType } from "utils/DynamicBindingUtils"; +// import { Severity } from "entities/AppsmithConsole"; +import CodemirrorTernService from "utils/autocomplete/CodemirrorTernService"; import { Spinner } from "design-system"; import { CUSTOM_WIDGET_FEATURE, @@ -50,7 +53,7 @@ export default function JSEditor(props: ContentProps) { useEffect(() => { ["LIB/node-forge", "LIB/moment", "base64-js", "LIB/lodash"].forEach((d) => { - getCodeMirrorTernService().removeDef(d); + CodemirrorTernService.removeDef(d); }); }, []); diff --git a/app/client/src/sagas/EvaluationsSaga.ts b/app/client/src/sagas/EvaluationsSaga.ts index d5f48c23fcff..3dcf99bbd2df 100644 --- a/app/client/src/sagas/EvaluationsSaga.ts +++ b/app/client/src/sagas/EvaluationsSaga.ts @@ -85,7 +85,7 @@ import { } from "@appsmith/selectors/entitiesSelector"; import type { WidgetEntityConfig } from "@appsmith/entities/DataTree/types"; import type { DataTree, UnEvalTree } from "entities/DataTree/dataTreeTypes"; -import { initiateLinting } from "./LintingSagas"; +import { initiateLinting, lintWorker } from "./LintingSagas"; import type { EvalTreeRequestData, EvalTreeResponseData, @@ -582,8 +582,11 @@ function* evalAndLintingHandler( function* evaluationChangeListenerSaga(): any { // Explicitly shutdown old worker if present - yield all([call(evalWorker.shutdown)]); - const [evalWorkerListenerChannel] = yield all([call(evalWorker.start)]); + yield all([call(evalWorker.shutdown), call(lintWorker.shutdown)]); + const [evalWorkerListenerChannel] = yield all([ + call(evalWorker.start), + call(lintWorker.start), + ]); const isFFFetched = yield select(getFeatureFlagsFetched); if (!isFFFetched) { diff --git a/app/client/src/sagas/JSLibrarySaga.ts b/app/client/src/sagas/JSLibrarySaga.ts index 6c0621935966..e2a08b7dca37 100644 --- a/app/client/src/sagas/JSLibrarySaga.ts +++ b/app/client/src/sagas/JSLibrarySaga.ts @@ -21,7 +21,7 @@ import { takeLatest, } from "redux-saga/effects"; import { getCurrentApplicationId } from "selectors/editorSelectors"; -import { getCodeMirrorTernService } from "utils/autocomplete/CodemirrorTernService"; +import CodemirrorTernService from "utils/autocomplete/CodemirrorTernService"; import { EVAL_WORKER_ACTIONS } from "@appsmith/workers/Evaluation/evalWorkerActions"; import { validateResponse } from "./ErrorSagas"; import { EvalWorker } from "./EvaluationsSaga"; @@ -171,7 +171,7 @@ export function* installLibrarySaga(lib: Partial<JSLibrary>) { } try { - getCodeMirrorTernService().updateDef(defs["!name"], defs); + CodemirrorTernService.updateDef(defs["!name"], defs); AnalyticsUtil.logEvent("DEFINITIONS_GENERATION", { url, success: true }); } catch (e) { toast.show( @@ -281,9 +281,7 @@ function* uninstallLibrarySaga(action: ReduxAction<JSLibrary>) { } try { - getCodeMirrorTernService().removeDef( - `LIB/${accessor[accessor.length - 1]}`, - ); + CodemirrorTernService.removeDef(`LIB/${accessor[accessor.length - 1]}`); } catch (e) { log.debug(`Failed to remove definitions for ${name}`, e); } @@ -369,7 +367,7 @@ function* fetchJSLibraries(action: ReduxAction<string>) { for (const lib of libraries) { try { const defs = JSON.parse(lib.defs); - getCodeMirrorTernService().updateDef(defs["!name"], defs); + CodemirrorTernService.updateDef(defs["!name"], defs); } catch (e) { toast.show( createMessage( diff --git a/app/client/src/sagas/LintingSagas.ts b/app/client/src/sagas/LintingSagas.ts index 28e1e7457063..b2a44292ecef 100644 --- a/app/client/src/sagas/LintingSagas.ts +++ b/app/client/src/sagas/LintingSagas.ts @@ -26,7 +26,7 @@ import { selectFeatureFlags } from "@appsmith/selectors/featureFlagsSelectors"; const APPSMITH_CONFIGS = getAppsmithConfigs(); -export let lintWorker: Linter; +export const lintWorker = new Linter(); function* updateLintGlobals( action: ReduxAction<{ add?: boolean; libs: JSLibrary[] }>, @@ -129,12 +129,6 @@ export default function* lintTreeSagaWatcher() { } export function* setupSaga(): any { - const mode = yield select(getAppMode); - if (mode === APP_MODE.PUBLISHED) return; - if (!lintWorker) { - lintWorker = new Linter(); - yield call(lintWorker.start); - } const featureFlags = yield select(selectFeatureFlags); yield call(lintWorker.setup, featureFlags); } diff --git a/app/client/src/sagas/PostEvaluationSagas.ts b/app/client/src/sagas/PostEvaluationSagas.ts index 007b98ffd22a..383c17e8ddfc 100644 --- a/app/client/src/sagas/PostEvaluationSagas.ts +++ b/app/client/src/sagas/PostEvaluationSagas.ts @@ -32,6 +32,7 @@ import log from "loglevel"; import { getAppMode } from "@appsmith/selectors/applicationSelectors"; import { APP_MODE } from "entities/App"; import { dataTreeTypeDefCreator } from "utils/autocomplete/dataTreeTypeDefCreator"; +import CodemirrorTernService from "utils/autocomplete/CodemirrorTernService"; import type { JSAction, JSCollection } from "entities/JSCollection"; import { isWidgetPropertyNamePath } from "utils/widgetEvalUtils"; import type { ActionEntityConfig } from "@appsmith/entities/DataTree/types"; @@ -45,7 +46,6 @@ import type { JSVarMutatedEvents, } from "workers/Evaluation/types"; import { endSpan, startRootSpan } from "UITelemetry/generateTraces"; -import { getCodeMirrorTernService } from "utils/autocomplete/CodemirrorTernService"; let successfulBindingsMap: SuccessfulBindingMap | undefined; @@ -233,7 +233,7 @@ export function* updateTernDefinitions( jsData, configTree, ); - getCodeMirrorTernService().updateDef("DATA_TREE", def, entityInfo); + CodemirrorTernService.updateDef("DATA_TREE", def, entityInfo); const end = performance.now(); log.debug("Tern", { updates }); log.debug("Tern definitions updated took ", (end - start).toFixed(2)); diff --git a/app/client/src/sagas/TernSaga.ts b/app/client/src/sagas/TernSaga.ts index 09e0e68f6cfe..78de77fae491 100644 --- a/app/client/src/sagas/TernSaga.ts +++ b/app/client/src/sagas/TernSaga.ts @@ -11,7 +11,7 @@ import { get } from "lodash"; import { FocusEntity } from "navigation/FocusEntity"; import { select, takeLatest } from "redux-saga/effects"; import { getWidgets } from "./selectors"; -import { getCodeMirrorTernService } from "utils/autocomplete/CodemirrorTernService"; +import CodemirrorTernService from "utils/autocomplete/CodemirrorTernService"; function* handleSetTernRecentEntities(action: ReduxAction<RecentEntity[]>) { const recentEntities = action.payload || []; @@ -59,12 +59,10 @@ function* handleSetTernRecentEntities(action: ReduxAction<RecentEntity[]>) { } } - getCodeMirrorTernService().updateRecentEntities( - Array.from(recentEntityNames), - ); + CodemirrorTernService.updateRecentEntities(Array.from(recentEntityNames)); } function* handleResetTernRecentEntities() { - getCodeMirrorTernService().updateRecentEntities([]); + CodemirrorTernService.updateRecentEntities([]); } export default function* ternSagas() { yield takeLatest( diff --git a/app/client/src/utils/autocomplete/CodemirrorTernService.ts b/app/client/src/utils/autocomplete/CodemirrorTernService.ts index a927b0326a3d..714c4920b004 100644 --- a/app/client/src/utils/autocomplete/CodemirrorTernService.ts +++ b/app/client/src/utils/autocomplete/CodemirrorTernService.ts @@ -1205,6 +1205,10 @@ export const createCompletionHeader = (name: string): Completion<any> => ({ isHeader: true, }); +export default new CodeMirrorTernService({ + async: true, +}); + function dotToBracketNotationAtToken(token: CodeMirror.Token) { return (cm: CodeMirror.Editor, hints: Hints, curr: Hint) => { let completion = curr.text; @@ -1231,14 +1235,3 @@ function dotToBracketNotationAtToken(token: CodeMirror.Token) { cm.replaceRange(completion, hints.from, hints.to); }; } - -let codeMirrorTernService: CodeMirrorTernService; - -export function getCodeMirrorTernService() { - if (!codeMirrorTernService) { - codeMirrorTernService = new CodeMirrorTernService({ - async: true, - }); - } - return codeMirrorTernService; -} diff --git a/app/client/src/utils/autocomplete/TernWorkerService.ts b/app/client/src/utils/autocomplete/TernWorkerService.ts index bb21972fc36c..371acf979ba3 100644 --- a/app/client/src/utils/autocomplete/TernWorkerService.ts +++ b/app/client/src/utils/autocomplete/TernWorkerService.ts @@ -2,7 +2,15 @@ import type { Def, Server } from "tern"; import type { CallbackFn } from "./types"; import { TernWorkerAction } from "./types"; -let ternWorker: Worker; +const ternWorker = new Worker( + new URL("../../workers/Tern/tern.worker.ts", import.meta.url), + { + // Note: the `Worker` part of the name is slightly important – LinkRelPreload_spec.js + // relies on it to find workers in the list of all requests. + name: "TernWorker", + type: "module", + }, +); function getFile(ts: any, name: string, c: CallbackFn) { const buf = ts.docs[name]; @@ -17,17 +25,6 @@ interface TernWorkerServerConstructor { } function TernWorkerServer(this: any, ts: any) { - if (!ternWorker) { - ternWorker = new Worker( - new URL("../../workers/Tern/tern.worker.ts", import.meta.url), - { - // Note: the `Worker` part of the name is slightly important – LinkRelPreload_spec.js - // relies on it to find workers in the list of all requests. - name: "TernWorker", - type: "module", - }, - ); - } const worker = (ts.worker = ternWorker); worker.postMessage({ type: TernWorkerAction.INIT, diff --git a/app/client/src/utils/autocomplete/__tests__/TernServer.test.ts b/app/client/src/utils/autocomplete/__tests__/TernServer.test.ts index aab08ddeb1d3..93cafbb4ee5c 100644 --- a/app/client/src/utils/autocomplete/__tests__/TernServer.test.ts +++ b/app/client/src/utils/autocomplete/__tests__/TernServer.test.ts @@ -2,8 +2,7 @@ import type { Completion, DataTreeDefEntityInformation, } from "../CodemirrorTernService"; -import { - getCodeMirrorTernService, +import CodemirrorTernService, { createCompletionHeader, } from "../CodemirrorTernService"; import { AutocompleteDataType } from "../AutocompleteDataType"; @@ -85,7 +84,7 @@ describe("Tern server", () => { ]; testCases.forEach((testCase) => { - const { value } = getCodeMirrorTernService().getFocusedDocValueAndPos( + const { value } = CodemirrorTernService.getFocusedDocValueAndPos( testCase.input, ); expect(value).toBe(testCase.expectedOutput); @@ -153,10 +152,7 @@ describe("Tern server", () => { type: "string", string: "", }); - const request = getCodeMirrorTernService().buildRequest( - testCase.input, - {}, - ); + const request = CodemirrorTernService.buildRequest(testCase.input, {}); expect(request.query.end).toEqual(testCase.expectedOutput); }); }); @@ -223,9 +219,9 @@ describe("Tern server", () => { }); const mockAddFile = jest.fn(); - getCodeMirrorTernService().server.addFile = mockAddFile; + CodemirrorTernService.server.addFile = mockAddFile; - const value: any = getCodeMirrorTernService().requestCallback( + const value: any = CodemirrorTernService.requestCallback( null, testCase.input.requestCallbackData as any, MockCodemirrorEditor as unknown as CodeMirror.Editor, @@ -363,7 +359,7 @@ describe("Tern server sorting", () => { ]; it("shows best match results", () => { - getCodeMirrorTernService().setEntityInformation( + CodemirrorTernService.setEntityInformation( MockCodemirrorEditor as unknown as CodeMirror.Editor, { entityName: "sameEntity", @@ -371,7 +367,7 @@ describe("Tern server sorting", () => { expectedType: AutocompleteDataType.OBJECT, }, ); - getCodeMirrorTernService().defEntityInformation = defEntityInformation; + CodemirrorTernService.defEntityInformation = defEntityInformation; const sortedCompletions = AutocompleteSorter.sort( _.shuffle(completions), { diff --git a/app/client/src/utils/autocomplete/customDefUtils.ts b/app/client/src/utils/autocomplete/customDefUtils.ts index b599ba7e41ef..c775d42db737 100644 --- a/app/client/src/utils/autocomplete/customDefUtils.ts +++ b/app/client/src/utils/autocomplete/customDefUtils.ts @@ -3,18 +3,18 @@ import { isEmpty } from "lodash"; import { debug } from "loglevel"; import type { AdditionalDynamicDataTree } from "./customTreeTypeDefCreator"; import { customTreeTypeDefCreator } from "./customTreeTypeDefCreator"; -import { getCodeMirrorTernService } from "./CodemirrorTernService"; +import CodemirrorTernService from "./CodemirrorTernService"; class CustomDef { private static lastCustomDataDef: AdditionalDynamicDataTree | undefined; update(customData?: AdditionalDynamicDataTree) { - const codeMirrorTernService = getCodeMirrorTernService(); if (customData && !isEmpty(customData)) { const customDataDef = customTreeTypeDefCreator(customData); if (!equal(CustomDef.lastCustomDataDef, customDataDef)) { const start = performance.now(); - codeMirrorTernService.updateDef("customDataTree", customDataDef); + + CodemirrorTernService.updateDef("customDataTree", customDataDef); debug( "Tern: updateDef for customDataTree took", @@ -26,7 +26,7 @@ class CustomDef { } } else if (CustomDef.lastCustomDataDef) { const start = performance.now(); - codeMirrorTernService.removeDef("customDataTree"); + CodemirrorTernService.removeDef("customDataTree"); debug( "Tern: removeDef for customDataTree took", (performance.now() - start).toFixed(),
5b609e0e8fe1fbd167fab56eb4bf3c3a4b4c4686
2023-08-22 17:32:01
sneha122
feat: Added new api to fetch preview data (#26298)
false
Added new api to fetch preview data (#26298)
feat
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 a78909956432..5aad875c65d3 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 @@ -155,6 +155,24 @@ public enum AppsmithPluginError implements BasePluginError { ErrorType.INTERNAL_ERROR, "{1}", "{2}"), + PLUGIN_GET_PREVIEW_DATA_ERROR( + 500, + AppsmithPluginErrorCode.PLUGIN_GET_PREVIEW_DATA_ERROR.getCode(), + AppsmithPluginErrorCode.PLUGIN_GET_PREVIEW_DATA_ERROR.getDescription(), + AppsmithErrorAction.DEFAULT, + "Failed to get preview data", + ErrorType.DATASOURCE_CONFIGURATION_ERROR, + "{0}", + "{1}"), + PLUGIN_UNSUPPORTED_OPERATION( + 500, + AppsmithPluginErrorCode.PLUGIN_UNSUPPORTED_OPERATION.getCode(), + AppsmithPluginErrorCode.PLUGIN_UNSUPPORTED_OPERATION.getDescription(), + AppsmithErrorAction.DEFAULT, + "Unsupported Operation", + ErrorType.INTERNAL_ERROR, + "{0}", + "{1}"), ; private final Integer httpErrorCode; 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 6510babf1563..4a9ba3f73352 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 @@ -20,7 +20,9 @@ public enum AppsmithPluginErrorCode { PLUGIN_UQI_WHERE_CONDITION_UNKNOWN("PE-UQI-5000", "Where condition could not be parsed"), GENERIC_STALE_CONNECTION("PE-STC-5000", "Secondary stale connection error"), PLUGIN_EXECUTE_ARGUMENT_ERROR("PE-ARG-5000", "Wrong arguments provided"), - PLUGIN_VALIDATE_DATASOURCE_ERROR("PE-DSE-5005", "Failed to validate datasource"); + PLUGIN_VALIDATE_DATASOURCE_ERROR("PE-DSE-5005", "Failed to validate datasource"), + PLUGIN_GET_PREVIEW_DATA_ERROR("PE-DSE-5006", "Failed to get preview data"), + PLUGIN_UNSUPPORTED_OPERATION("PE-DSE-5007", "Unsupported Operation"); private final String code; private final String description; diff --git a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/plugins/PluginExecutor.java b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/plugins/PluginExecutor.java index 0a11ec5ded8d..59f96c76d17c 100644 --- a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/plugins/PluginExecutor.java +++ b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/plugins/PluginExecutor.java @@ -8,6 +8,7 @@ import com.appsmith.external.models.ActionExecutionResult; import com.appsmith.external.models.DatasourceConfiguration; import com.appsmith.external.models.DatasourceStructure; +import com.appsmith.external.models.DatasourceStructure.Template; import com.appsmith.external.models.DatasourceTestResult; import com.appsmith.external.models.Param; import com.appsmith.external.models.TriggerRequestDTO; @@ -325,4 +326,12 @@ default Mono<Void> sanitizeGenerateCRUDPageTemplateInfo( List<ActionConfiguration> actionConfigurationList, Object... args) { return Mono.empty(); } + + /* + * This method returns ActionConfiguration required in order to fetch preview data, + * that needs to be shown on datasource review page. + */ + default ActionConfiguration getSchemaPreviewActionConfig(Template queryTemplate) { + return null; + } } diff --git a/app/server/appsmith-plugins/postgresPlugin/src/main/java/com/external/plugins/PostgresPlugin.java b/app/server/appsmith-plugins/postgresPlugin/src/main/java/com/external/plugins/PostgresPlugin.java index 1a333b2897fd..d57017becb97 100644 --- a/app/server/appsmith-plugins/postgresPlugin/src/main/java/com/external/plugins/PostgresPlugin.java +++ b/app/server/appsmith-plugins/postgresPlugin/src/main/java/com/external/plugins/PostgresPlugin.java @@ -14,6 +14,7 @@ import com.appsmith.external.models.DBAuth; import com.appsmith.external.models.DatasourceConfiguration; import com.appsmith.external.models.DatasourceStructure; +import com.appsmith.external.models.DatasourceStructure.Template; import com.appsmith.external.models.Endpoint; import com.appsmith.external.models.MustacheBindingToken; import com.appsmith.external.models.Param; @@ -60,6 +61,7 @@ import java.sql.Timestamp; import java.sql.Types; import java.time.Duration; +import java.time.Instant; import java.time.LocalDateTime; import java.time.OffsetDateTime; import java.time.format.DateTimeFormatter; @@ -268,6 +270,21 @@ public Mono<ActionExecutionResult> executeParameterized( explicitCastDataTypes); } + @Override + public ActionConfiguration getSchemaPreviewActionConfig(Template queryTemplate) { + ActionConfiguration actionConfig = new ActionConfiguration(); + // Sets query body + actionConfig.setBody(queryTemplate.getBody()); + + // Sets prepared statement to false + Property preparedStatement = new Property(); + preparedStatement.setValue(false); + List<Property> pluginSpecifiedTemplates = new ArrayList<Property>(); + pluginSpecifiedTemplates.add(preparedStatement); + actionConfig.setPluginSpecifiedTemplates(pluginSpecifiedTemplates); + return actionConfig; + } + private Mono<ActionExecutionResult> executeCommon( HikariDataSource connection, DatasourceConfiguration datasourceConfiguration, @@ -285,6 +302,7 @@ private Mono<ActionExecutionResult> executeCommon( String transformedQuery = preparedStatement ? replaceQuestionMarkWithDollarIndex(query) : query; List<RequestParamDTO> requestParams = List.of(new RequestParamDTO(ACTION_CONFIGURATION_BODY, transformedQuery, null, null, psParams)); + Instant requestedAt = Instant.now(); return Mono.fromCallable(() -> { Connection connectionFromPool; @@ -544,6 +562,9 @@ private Mono<ActionExecutionResult> executeCommon( request.setQuery(query); request.setProperties(requestData); request.setRequestParams(requestParams); + if (request.getRequestedAt() == null) { + request.setRequestedAt(requestedAt); + } ActionExecutionResult result = actionExecutionResult; result.setRequest(request); return result; diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/controllers/ce/DatasourceControllerCE.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/controllers/ce/DatasourceControllerCE.java index 80863c6788d5..8219d82c0370 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/controllers/ce/DatasourceControllerCE.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/controllers/ce/DatasourceControllerCE.java @@ -1,8 +1,10 @@ package com.appsmith.server.controllers.ce; +import com.appsmith.external.models.ActionExecutionResult; import com.appsmith.external.models.Datasource; import com.appsmith.external.models.DatasourceStorageDTO; import com.appsmith.external.models.DatasourceStructure; +import com.appsmith.external.models.DatasourceStructure.Template; import com.appsmith.external.models.DatasourceTestResult; import com.appsmith.external.models.TriggerRequestDTO; import com.appsmith.external.models.TriggerResultDTO; @@ -206,4 +208,16 @@ public Mono<ResponseDTO<TriggerResultDTO>> trigger( .trigger(datasourceId, environmentId, triggerRequestDTO) .map(triggerResultDTO -> new ResponseDTO<>(HttpStatus.OK.value(), triggerResultDTO, null)); } + + @JsonView(Views.Public.class) + @PostMapping("/{datasourceId}/schema-preview") + public Mono<ResponseDTO<ActionExecutionResult>> getSchemaPreviewData( + @PathVariable String datasourceId, + @RequestBody Template template, + @RequestHeader(name = FieldName.ENVIRONMENT_ID, required = false) String environmentId) { + log.debug("Going to get schema preview data for datasource with id: '{}'.", datasourceId); + return datasourceStructureSolution + .getSchemaPreviewData(datasourceId, environmentId, template) + .map(actionExecutionResult -> new ResponseDTO<>(HttpStatus.OK.value(), actionExecutionResult, null)); + } } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ce/DatasourceStructureSolutionCE.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ce/DatasourceStructureSolutionCE.java index ff763fe45865..79f78f948e3b 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ce/DatasourceStructureSolutionCE.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ce/DatasourceStructureSolutionCE.java @@ -1,7 +1,9 @@ package com.appsmith.server.solutions.ce; +import com.appsmith.external.models.ActionExecutionResult; import com.appsmith.external.models.DatasourceStorage; import com.appsmith.external.models.DatasourceStructure; +import com.appsmith.external.models.DatasourceStructure.Template; import reactor.core.publisher.Mono; public interface DatasourceStructureSolutionCE { @@ -9,4 +11,7 @@ public interface DatasourceStructureSolutionCE { Mono<DatasourceStructure> getStructure(String datasourceId, boolean ignoreCache, String environmentName); Mono<DatasourceStructure> getStructure(DatasourceStorage datasourceStorage, boolean ignoreCache); + + Mono<ActionExecutionResult> getSchemaPreviewData( + String datasourceId, String environmentName, Template queryTemplate); } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ce/DatasourceStructureSolutionCEImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ce/DatasourceStructureSolutionCEImpl.java index 1c8fa9b16c99..c3b65765bb9e 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ce/DatasourceStructureSolutionCEImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ce/DatasourceStructureSolutionCEImpl.java @@ -4,9 +4,13 @@ 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.ActionConfiguration; +import com.appsmith.external.models.ActionExecutionResult; +import com.appsmith.external.models.Datasource; import com.appsmith.external.models.DatasourceStorage; import com.appsmith.external.models.DatasourceStorageStructure; import com.appsmith.external.models.DatasourceStructure; +import com.appsmith.external.models.DatasourceStructure.Template; import com.appsmith.external.plugins.PluginExecutor; import com.appsmith.server.constants.FieldName; import com.appsmith.server.exceptions.AppsmithError; @@ -172,4 +176,80 @@ public Mono<DatasourceStructure> getStructure(DatasourceStorage datasourceStorag .switchIfEmpty(fetchAndStoreNewStructureMono) .defaultIfEmpty(new DatasourceStructure()); } + + @Override + public Mono<ActionExecutionResult> getSchemaPreviewData( + String datasourceId, String environmentId, Template queryTemplate) { + return datasourceService + .findById(datasourceId, datasourcePermission.getExecutePermission()) + .zipWhen(datasource -> datasourceService.getTrueEnvironmentId( + datasource.getWorkspaceId(), + environmentId, + datasource.getPluginId(), + environmentPermission.getExecutePermission())) + .flatMap(tuple -> { + Datasource datasource = tuple.getT1(); + String trueEnvironmentId = tuple.getT2(); + return datasourceStorageService.findByDatasourceAndEnvironmentIdForExecution( + datasource, trueEnvironmentId); + }) + .flatMap(datasourceStorage -> getSchemaPreviewData(datasourceStorage, queryTemplate)) + .onErrorMap(e -> { + if (!(e instanceof AppsmithPluginException)) { + return new AppsmithPluginException( + AppsmithPluginError.PLUGIN_GET_PREVIEW_DATA_ERROR, e.getMessage()); + } + + return e; + }) + .onErrorResume(error -> { + ActionExecutionResult result = new ActionExecutionResult(); + result.setErrorInfo(error); + return Mono.just(result); + }); + } + + private Mono<ActionExecutionResult> getSchemaPreviewData( + DatasourceStorage datasourceStorage, Template queryTemplate) { + if (Boolean.FALSE.equals(datasourceStorage.getIsValid())) { + return Mono.error(new AppsmithException(AppsmithError.INVALID_DATASOURCE)); + } + + return pluginExecutorHelper + .getPluginExecutor(pluginService.findById(datasourceStorage.getPluginId())) + .switchIfEmpty(Mono.error(new AppsmithException( + AppsmithError.NO_RESOURCE_FOUND, FieldName.PLUGIN, datasourceStorage.getPluginId()))) + .flatMap(pluginExecutor -> { + ActionConfiguration actionConfig = + ((PluginExecutor<Object>) pluginExecutor).getSchemaPreviewActionConfig(queryTemplate); + // actionConfig will be null for plugins which do not have this functionality yet + // Currently its only implemented for PostgreSQL, to be added subsequently for MySQL as well + if (actionConfig != null) { + return datasourceContextService.retryOnce( + datasourceStorage, resourceContext -> ((PluginExecutor<Object>) pluginExecutor) + .executeParameterized( + resourceContext.getConnection(), + null, + datasourceStorage.getDatasourceConfiguration(), + actionConfig)); + } else { + return Mono.error( + new AppsmithPluginException(AppsmithPluginError.PLUGIN_UNSUPPORTED_OPERATION)); + } + }) + .onErrorMap( + StaleConnectionException.class, + error -> new AppsmithPluginException( + AppsmithPluginError.PLUGIN_ERROR, + "Appsmith server found a secondary stale connection. Please reach out to appsmith " + + "customer support to resolve this.")) + .onErrorMap(e -> { + log.error("In the datasourceStorage fetching preview data error mode.", e); + if (!(e instanceof AppsmithPluginException)) { + return new AppsmithPluginException( + AppsmithPluginError.PLUGIN_GET_PREVIEW_DATA_ERROR, e.getMessage()); + } + return e; + }); + } }
058500704efa72c901ff3d519cfa0cfd2be2e3e0
2022-12-02 00:36:49
Tolulope Adetula
fix: multiselect crashing (#18577)
false
multiselect crashing (#18577)
fix
diff --git a/app/client/src/widgets/MultiSelectWidgetV2/widget/index.tsx b/app/client/src/widgets/MultiSelectWidgetV2/widget/index.tsx index 2d1812878c9c..80a1be2e2120 100644 --- a/app/client/src/widgets/MultiSelectWidgetV2/widget/index.tsx +++ b/app/client/src/widgets/MultiSelectWidgetV2/widget/index.tsx @@ -700,6 +700,9 @@ class MultiSelectWidget extends BaseWidget< // { label , value } is needed in the widget mergeLabelAndValue = (): LabelInValueType[] => { + if (!this.props.selectedOptionLabels || !this.props.selectedOptionValues) { + return []; + } const labels = [...this.props.selectedOptionLabels]; const values = [...this.props.selectedOptionValues]; return values.map((value, index) => ({ @@ -747,8 +750,8 @@ export interface MultiSelectWidgetProps extends WidgetProps { isLoading: boolean; selectedOptions: LabelInValueType[]; filterText: string; - selectedOptionValues: string[]; - selectedOptionLabels: string[]; + selectedOptionValues?: string[]; + selectedOptionLabels?: string[]; serverSideFiltering: boolean; onFilterUpdate: string; allowSelectAll?: boolean;
346af80911678a5b294cf07fcccde541d66edb16
2023-09-07 16:00:10
Vijetha-Kaja
test: Cypress - Fix Flaky tests (#27063)
false
Cypress - Fix Flaky tests (#27063)
test
diff --git a/app/client/cypress/e2e/Regression/ClientSide/Widgets/Image/Image2_Spec.ts b/app/client/cypress/e2e/Regression/ClientSide/Widgets/Image/Image2_Spec.ts index 285ace456966..bb2183de6383 100644 --- a/app/client/cypress/e2e/Regression/ClientSide/Widgets/Image/Image2_Spec.ts +++ b/app/client/cypress/e2e/Regression/ClientSide/Widgets/Image/Image2_Spec.ts @@ -155,6 +155,8 @@ describe("Image widget tests", function () { agHelper.AssertExistingToggleState("enabledownload", "false"); propPane.TogglePropertyState("enabledownload", "On"); deployMode.DeployApp(locators._widgetInDeployed(draggableWidgets.IMAGE)); + agHelper.Sleep(2000); //Wait for widget to settle + agHelper.GetNClick(locators._widgetInDeployed(draggableWidgets.IMAGE)); agHelper.HoverElement(locators._widgetInDeployed(draggableWidgets.IMAGE)); agHelper.AssertElementVisibility(widgetLocators.imageDownloadBtn); agHelper.AssertAttribute(widgetLocators.imageDownloadBtn, "href", jpgImg);
93ad64bbf5b4c65156b6f464dbefaa643b19e1ef
2023-10-12 23:02:04
Rudraprasad Das
fix: removing branch name on fork redirect (#27943)
false
removing branch name on fork redirect (#27943)
fix
diff --git a/app/client/src/ce/sagas/ApplicationSagas.tsx b/app/client/src/ce/sagas/ApplicationSagas.tsx index 7177bdb64609..cf02903b545f 100644 --- a/app/client/src/ce/sagas/ApplicationSagas.tsx +++ b/app/client/src/ce/sagas/ApplicationSagas.tsx @@ -696,8 +696,10 @@ export function* forkApplicationSaga( workspaceId: action.payload.workspaceId, }, }); + const pageURL = builderURL({ pageId: application.defaultPageId as string, + params: { branch: null }, }); if (action.payload.editMode) { diff --git a/app/client/src/pages/AppViewer/PrimaryCTA.tsx b/app/client/src/pages/AppViewer/PrimaryCTA.tsx index 15ac6664ee53..fb41ab5cba8a 100644 --- a/app/client/src/pages/AppViewer/PrimaryCTA.tsx +++ b/app/client/src/pages/AppViewer/PrimaryCTA.tsx @@ -117,6 +117,7 @@ function PrimaryCTA(props: Props) { pageId: currentPageID, params: { fork: "true", + branch: null, }, });
cfc89819a89945f148a8d2a3944bd9701df41526
2022-02-02 16:30:01
Danieldare
fix: remove unused icon
false
remove unused icon
fix
diff --git a/app/client/src/components/ads/Icon.tsx b/app/client/src/components/ads/Icon.tsx index 382b1dbb1297..8a05b8a84063 100644 --- a/app/client/src/components/ads/Icon.tsx +++ b/app/client/src/components/ads/Icon.tsx @@ -1,5 +1,5 @@ import React, { forwardRef, Ref } from "react"; -import { ReactComponent as DeleteBin } from "assets/icons/ads/delete.svg"; +// import { ReactComponent as DeleteBin } from "assets/icons/ads/delete.svg"; import { ReactComponent as BookLineIcon } from "assets/icons/ads/book-open-line.svg"; import { ReactComponent as BugIcon } from "assets/icons/ads/bug.svg"; import { ReactComponent as CancelIcon } from "assets/icons/ads/cancel.svg"; @@ -226,7 +226,6 @@ export const IconCollection = [ "database-2-line", "datasource", "delete", - "delete-bin", "delete-blank", "desktop", "discord", @@ -473,9 +472,6 @@ const Icon = forwardRef( case "delete": returnIcon = <Trash />; break; - case "delete-bin": - returnIcon = <DeleteBin />; - break; case "delete-blank": returnIcon = <DeleteBin7 />; break; diff --git a/app/client/src/components/formControls/WhereClauseControl.tsx b/app/client/src/components/formControls/WhereClauseControl.tsx index da0302674d0e..b694d7342a89 100644 --- a/app/client/src/components/formControls/WhereClauseControl.tsx +++ b/app/client/src/components/formControls/WhereClauseControl.tsx @@ -170,7 +170,7 @@ function ConditionComponent(props: any, index: number) { e.stopPropagation(); props.onDeletePressed(index); }} - size={IconSize.XL} + size={IconSize.LARGE} /> </ConditionBox> ); @@ -263,7 +263,7 @@ function ConditionBlock(props: any) { e.stopPropagation(); onDeletePressed(index); }} - size={IconSize.XL} + size={IconSize.LARGE} /> </ConditionBox> );
f14b40cef69da23a236a3a02492139b51ed314e8
2024-02-06 12:56:47
Valera Melnikov
fix: fix modal position and styles (#30805)
false
fix modal position and styles (#30805)
fix
diff --git a/app/client/packages/design-system/headless/src/components/Popover/src/types.ts b/app/client/packages/design-system/headless/src/components/Popover/src/types.ts index 214fcac64d15..f7e40e1eeb16 100644 --- a/app/client/packages/design-system/headless/src/components/Popover/src/types.ts +++ b/app/client/packages/design-system/headless/src/components/Popover/src/types.ts @@ -47,6 +47,10 @@ export interface PopoverProps { triggerRef?: MutableRefObject<HTMLElement | null>; /** Which element to initially focus. Can be either a number (tabbable index as specified by the order) or a ref. */ initialFocus?: number | MutableRefObject<HTMLElement | null>; + /** Determines whether clickOutside is work or not. + * @default false + */ + dismissClickOutside?: boolean; } export interface PopoverContentProps { diff --git a/app/client/packages/design-system/headless/src/components/Popover/src/usePopover.ts b/app/client/packages/design-system/headless/src/components/Popover/src/usePopover.ts index 8cce903f3d65..674ae60427a5 100644 --- a/app/client/packages/design-system/headless/src/components/Popover/src/usePopover.ts +++ b/app/client/packages/design-system/headless/src/components/Popover/src/usePopover.ts @@ -17,6 +17,7 @@ const DEFAULT_POPOVER_OFFSET = 10; export function usePopover({ defaultOpen = false, + dismissClickOutside = false, duration = 0, initialFocus, isOpen: controlledOpen, @@ -56,7 +57,17 @@ export function usePopover({ const click = useClick(context, { enabled: controlledOpen == null, }); - const dismiss = useDismiss(context); + const dismiss = useDismiss(context, { + escapeKey: !dismissClickOutside, + outsidePress: (event) => { + if (dismissClickOutside) return false; + + // By default, click to close popup only work inside the provider + return Boolean( + (event?.target as HTMLElement).closest("[data-theme-provider]"), + ); + }, + }); const role = useRole(context); const interactions = useInteractions([click, dismiss, role]); diff --git a/app/client/packages/design-system/widgets/src/components/Modal/src/ModalFooter.tsx b/app/client/packages/design-system/widgets/src/components/Modal/src/ModalFooter.tsx index 55d0f4530451..020c0df2d240 100644 --- a/app/client/packages/design-system/widgets/src/components/Modal/src/ModalFooter.tsx +++ b/app/client/packages/design-system/widgets/src/components/Modal/src/ModalFooter.tsx @@ -7,7 +7,7 @@ import type { ModalFooterProps } from "./types"; export const ModalFooter = (props: ModalFooterProps) => { const { closeText = "Close", onSubmit, submitText = "Submit" } = props; - const { onClose, setOpen } = usePopoverContext(); + const { setOpen } = usePopoverContext(); const [isLoading, setIsLoading] = useState(false); const handleSubmit = async () => { @@ -19,14 +19,9 @@ export const ModalFooter = (props: ModalFooterProps) => { } }; - const closeHandler = () => { - onClose && onClose(); - setOpen(false); - }; - return ( <Flex alignItems="center" gap="spacing-4" justifyContent="end"> - <Button onPress={closeHandler} variant="ghost"> + <Button onPress={() => setOpen(false)} variant="ghost"> {closeText} </Button> diff --git a/app/client/packages/design-system/widgets/src/components/Modal/src/ModalHeader.tsx b/app/client/packages/design-system/widgets/src/components/Modal/src/ModalHeader.tsx index 7f9071493b09..2b50fa3e5fe9 100644 --- a/app/client/packages/design-system/widgets/src/components/Modal/src/ModalHeader.tsx +++ b/app/client/packages/design-system/widgets/src/components/Modal/src/ModalHeader.tsx @@ -10,7 +10,7 @@ import type { ModalHeaderProps } from "./types"; export const ModalHeader = (props: ModalHeaderProps) => { const { title } = props; - const { onClose, setLabelId, setOpen } = usePopoverContext(); + const { setLabelId, setOpen } = usePopoverContext(); const id = useId(); // Only sets `aria-labelledby` on the Dialog root element @@ -20,17 +20,12 @@ export const ModalHeader = (props: ModalHeaderProps) => { return () => setLabelId(undefined); }, [id, setLabelId]); - const closeHandler = () => { - onClose && onClose(); - setOpen(false); - }; - return ( <Flex alignItems="center" gap="spacing-4" justifyContent="space-between"> <Text id={id} lineClamp={1} title={title} variant="caption"> {title} </Text> - <IconButton icon="x" onPress={closeHandler} variant="ghost" /> + <IconButton icon="x" onPress={() => setOpen(false)} variant="ghost" /> </Flex> ); }; diff --git a/app/client/packages/design-system/widgets/src/components/Modal/src/styles.module.css b/app/client/packages/design-system/widgets/src/components/Modal/src/styles.module.css index 2f1ea60afd0a..b460d819b4ea 100644 --- a/app/client/packages/design-system/widgets/src/components/Modal/src/styles.module.css +++ b/app/client/packages/design-system/widgets/src/components/Modal/src/styles.module.css @@ -1,18 +1,18 @@ .overlay { - /* Redefining the overlay positioning so that the dialog is centered relative to the provider, not the viewport */ - position: absolute !important; background: var(--color-bg-neutral-opacity); display: grid; place-items: center; z-index: var(--z-index-99); + max-width: var(--provider-width); + margin: 0 auto; } .content { background: var(--color-bg); border-radius: var(--border-radius-1); box-shadow: var(--box-shadow-1); - max-width: calc(100vw - var(--outer-spacing-6)); - max-height: calc(100vh - var(--outer-spacing-6)); + max-width: calc(var(--provider-width) - var(--outer-spacing-8)); + max-height: calc(var(--provider-width) - var(--outer-spacing-8)); outline: none; display: flex; flex-direction: column; @@ -38,7 +38,7 @@ } [data-size="large"] .content { - width: calc(var(--provider-width) - var(--outer-spacing-6)); + width: calc(var(--provider-width) - var(--outer-spacing-8)); height: 100%; } diff --git a/app/client/packages/design-system/widgets/src/components/Modal/src/types.ts b/app/client/packages/design-system/widgets/src/components/Modal/src/types.ts index 7761bfdac1b3..11277f435e2b 100644 --- a/app/client/packages/design-system/widgets/src/components/Modal/src/types.ts +++ b/app/client/packages/design-system/widgets/src/components/Modal/src/types.ts @@ -8,7 +8,12 @@ import type { SIZES } from "../../../shared"; export interface ModalProps extends Pick< PopoverProps, - "isOpen" | "setOpen" | "onClose" | "triggerRef" | "initialFocus" + | "isOpen" + | "setOpen" + | "onClose" + | "triggerRef" + | "initialFocus" + | "dismissClickOutside" >, Pick<PopoverModalContentProps, "overlayClassName"> { /** Size of the Modal diff --git a/app/client/src/components/editorComponents/ErrorBoundry.tsx b/app/client/src/components/editorComponents/ErrorBoundry.tsx index 99acb2bff235..9783ddc4aeb5 100644 --- a/app/client/src/components/editorComponents/ErrorBoundry.tsx +++ b/app/client/src/components/editorComponents/ErrorBoundry.tsx @@ -1,11 +1,13 @@ -import type { ReactNode } from "react"; import React from "react"; import styled from "styled-components"; import * as Sentry from "@sentry/react"; import * as log from "loglevel"; +import type { ReactNode, CSSProperties } from "react"; + interface Props { children: ReactNode; + style?: CSSProperties; } interface State { hasError: boolean; @@ -39,7 +41,10 @@ class ErrorBoundary extends React.Component<Props, State> { render() { return ( - <ErrorBoundaryContainer className="error-boundary"> + <ErrorBoundaryContainer + className="error-boundary" + style={this.props.style} + > {this.state.hasError ? ( <p> Oops, Something went wrong. diff --git a/app/client/src/layoutSystems/anvil/canvas/styles.css b/app/client/src/layoutSystems/anvil/canvas/styles.css index bb836d6a5d53..c8fd2927c976 100644 --- a/app/client/src/layoutSystems/anvil/canvas/styles.css +++ b/app/client/src/layoutSystems/anvil/canvas/styles.css @@ -3,8 +3,3 @@ width: 100%; height: 100%; } - -.main-anvil-canvas { - height: calc(100% - 1rem); - overflow-y: auto; -} diff --git a/app/client/src/layoutSystems/anvil/common/widgetComponent/AnvilWidgetComponent.tsx b/app/client/src/layoutSystems/anvil/common/widgetComponent/AnvilWidgetComponent.tsx index 79176cc842ab..7bb702df196f 100644 --- a/app/client/src/layoutSystems/anvil/common/widgetComponent/AnvilWidgetComponent.tsx +++ b/app/client/src/layoutSystems/anvil/common/widgetComponent/AnvilWidgetComponent.tsx @@ -22,7 +22,8 @@ export const AnvilWidgetComponent = (props: BaseWidgetProps) => { if (!detachFromLayout) return props.children; return ( - <ErrorBoundary> + // delete style as soon as we switch to Anvil layout completely + <ErrorBoundary style={{ height: "auto", width: "auto" }}> <WidgetComponentBoundary widgetType={type}> {props.children} </WidgetComponentBoundary> diff --git a/app/client/src/layoutSystems/anvil/utils/AnvilDSLTransformer.ts b/app/client/src/layoutSystems/anvil/utils/AnvilDSLTransformer.ts index 64585681cbd7..3d033fb24215 100644 --- a/app/client/src/layoutSystems/anvil/utils/AnvilDSLTransformer.ts +++ b/app/client/src/layoutSystems/anvil/utils/AnvilDSLTransformer.ts @@ -22,7 +22,6 @@ export function anvilDSLTransformer(dsl: DSLWidget) { layoutStyle: { border: "none", height: "100%", - minHeight: "var(--canvas-height)", padding: "spacing-1", }, isDropTarget: true, diff --git a/app/client/src/layoutSystems/anvil/utils/layouts/renderUtils.tsx b/app/client/src/layoutSystems/anvil/utils/layouts/renderUtils.tsx index 175bade3399c..bba5a3c9ea2a 100644 --- a/app/client/src/layoutSystems/anvil/utils/layouts/renderUtils.tsx +++ b/app/client/src/layoutSystems/anvil/utils/layouts/renderUtils.tsx @@ -125,7 +125,6 @@ export function renderWidgetsInAlignedRow( > = { alignSelf: "stretch", canvasId, - columnGap: "4px", direction: "row", flexBasis: { base: "auto", [`${MOBILE_BREAKPOINT}px`]: "0%" }, flexGrow: 1, diff --git a/app/client/src/layoutSystems/common/mainContainerResizer/MainContainerResizer.tsx b/app/client/src/layoutSystems/common/mainContainerResizer/MainContainerResizer.tsx index 4f2576015e22..01c428e9c379 100644 --- a/app/client/src/layoutSystems/common/mainContainerResizer/MainContainerResizer.tsx +++ b/app/client/src/layoutSystems/common/mainContainerResizer/MainContainerResizer.tsx @@ -13,13 +13,12 @@ const CanvasResizerIcon = importSvg( ); const AutoLayoutCanvasResizer = styled.div` - position: sticky; + position: relative; z-index: var(--on-canvas-ui-z-index); cursor: col-resize; user-select: none; -webkit-user-select: none; width: 2px; - height: 100%; display: flex; background: var(--ads-v2-color-border); align-items: center; @@ -59,12 +58,9 @@ const AutoLayoutCanvasResizer = styled.div` export function MainContainerResizer({ currentPageId, enableMainCanvasResizer, - heightWithTopMargin, isPageInitiated, isPreview, - shouldHaveTopMargin, }: { - heightWithTopMargin: string; isPageInitiated: boolean; shouldHaveTopMargin: boolean; isPreview: boolean; @@ -74,6 +70,7 @@ export function MainContainerResizer({ const appLayout = useSelector(getCurrentApplicationLayout); const ref = useRef<HTMLDivElement>(null); const dispatch = useDispatch(); + const topHeaderHeight = "48px"; useEffect(() => { const ele: HTMLElement | null = document.getElementById(CANVAS_VIEWPORT); @@ -174,8 +171,8 @@ export function MainContainerResizer({ }} ref={ref} style={{ - top: "100%", - height: shouldHaveTopMargin ? heightWithTopMargin : "100vh", + top: isPreview ? topHeaderHeight : "0", + height: isPreview ? `calc(100% - ${topHeaderHeight})` : "100%", }} > <div className="canvas-resizer-icon"> diff --git a/app/client/src/pages/AppViewer/AppPage.tsx b/app/client/src/pages/AppViewer/AppPage.tsx index 71e3fdbba239..8fe9bf7abffc 100644 --- a/app/client/src/pages/AppViewer/AppPage.tsx +++ b/app/client/src/pages/AppViewer/AppPage.tsx @@ -71,10 +71,7 @@ export function AppPage(props: AppPageProps) { > <PageView className="t--app-viewer-page" width={width}> {props.widgetsStructure.widgetId && - renderAppsmithCanvas({ - ...props.widgetsStructure, - classList: isAnvilLayout ? ["main-anvil-canvas"] : [], - } as WidgetProps)} + renderAppsmithCanvas(props.widgetsStructure as WidgetProps)} </PageView> </PageViewWrapper> ); diff --git a/app/client/src/pages/Editor/Canvas.tsx b/app/client/src/pages/Editor/Canvas.tsx index 29a7e30ce57b..11a6adb1164c 100644 --- a/app/client/src/pages/Editor/Canvas.tsx +++ b/app/client/src/pages/Editor/Canvas.tsx @@ -18,8 +18,6 @@ import { getIsAppSettingsPaneWithNavigationTabOpen } from "selectors/appSettings import { CANVAS_ART_BOARD } from "constants/componentClassNameConstants"; import { renderAppsmithCanvas } from "layoutSystems/CanvasFactory"; import type { WidgetProps } from "widgets/BaseWidget"; -import { LayoutSystemTypes } from "layoutSystems/types"; -import { getLayoutSystemType } from "selectors/layoutSystemSelectors"; import { getAppThemeSettings } from "@appsmith/selectors/applicationSelectors"; interface CanvasProps { @@ -28,11 +26,17 @@ interface CanvasProps { enableMainCanvasResizer?: boolean; } +const StyledWDSThemeProvider = styled(WDSThemeProvider)` + min-height: 100%; + display: flex; +`; + const Wrapper = styled.section<{ background: string; width: number; $enableMainCanvasResizer: boolean; }>` + flex: 1; background: ${({ background }) => background}; width: ${({ $enableMainCanvasResizer, width }) => $enableMainCanvasResizer ? `100%` : `${width}px`}; @@ -45,7 +49,6 @@ const Canvas = (props: CanvasProps) => { ); const selectedTheme = useSelector(getSelectedAppTheme); const isWDSEnabled = useFeatureFlag("ab_wds_enabled"); - const layoutSystemType: LayoutSystemTypes = useSelector(getLayoutSystemType); const themeSetting = useSelector(getAppThemeSettings); const themeProps = { @@ -82,14 +85,12 @@ const Canvas = (props: CanvasProps) => { : `mx-auto`; const paddingBottomClass = props.enableMainCanvasResizer ? "" : "pb-52"; - const height = layoutSystemType === LayoutSystemTypes.ANVIL ? "h-full" : ""; - const renderChildren = () => { return ( <Wrapper $enableMainCanvasResizer={!!props.enableMainCanvasResizer} background={isWDSEnabled ? "" : backgroundForCanvas} - className={`relative t--canvas-artboard ${height} ${paddingBottomClass} transition-all duration-400 ${marginHorizontalClass} ${getViewportClassName( + className={`relative t--canvas-artboard ${paddingBottomClass} transition-all duration-400 ${marginHorizontalClass} ${getViewportClassName( canvasWidth, )}`} data-testid={"t--canvas-artboard"} @@ -98,13 +99,7 @@ const Canvas = (props: CanvasProps) => { width={canvasWidth} > {props.widgetsStructure.widgetId && - renderAppsmithCanvas({ - ...props.widgetsStructure, - classList: - layoutSystemType === LayoutSystemTypes.ANVIL - ? ["main-anvil-canvas"] - : [], - } as WidgetProps)} + renderAppsmithCanvas(props.widgetsStructure as WidgetProps)} </Wrapper> ); }; @@ -112,7 +107,9 @@ const Canvas = (props: CanvasProps) => { try { if (isWDSEnabled) { return ( - <WDSThemeProvider theme={theme}>{renderChildren()}</WDSThemeProvider> + <StyledWDSThemeProvider theme={theme}> + {renderChildren()} + </StyledWDSThemeProvider> ); } diff --git a/app/client/src/pages/Editor/WidgetsEditor/MainContainerWrapper.tsx b/app/client/src/pages/Editor/WidgetsEditor/MainContainerWrapper.tsx index 89d76302da29..1654602467aa 100644 --- a/app/client/src/pages/Editor/WidgetsEditor/MainContainerWrapper.tsx +++ b/app/client/src/pages/Editor/WidgetsEditor/MainContainerWrapper.tsx @@ -21,12 +21,10 @@ import { getAppThemeIsChanging, getSelectedAppTheme, } from "selectors/appThemingSelectors"; -import { getCurrentThemeDetails } from "selectors/themeSelectors"; import { getCanvasWidgetsStructure } from "@appsmith/selectors/entitiesSelector"; -import { - AUTOLAYOUT_RESIZER_WIDTH_BUFFER, - useDynamicAppLayout, -} from "utils/hooks/useDynamicAppLayout"; +import { useDynamicAppLayout } from "utils/hooks/useDynamicAppLayout"; +import { LayoutSystemTypes } from "../../../layoutSystems/types"; +import { getLayoutSystemType } from "../../../selectors/layoutSystemSelectors"; import Canvas from "../Canvas"; import type { AppState } from "@appsmith/reducers"; import { useFeatureFlag } from "utils/hooks/useFeatureFlag"; @@ -51,14 +49,8 @@ const Wrapper = styled.section<{ isPreviewingNavigation?: boolean; isAppSettingsPaneWithNavigationTabOpen?: boolean; navigationHeight?: number; - $heightWithTopMargin: string; }>` - /* Create a custom variable that will allow us to measure the height of the canvas down the road */ - --canvas-height: ${(props) => props.$heightWithTopMargin}; - width: ${({ $enableMainCanvasResizer }) => - $enableMainCanvasResizer - ? `calc(100% - ${AUTOLAYOUT_RESIZER_WIDTH_BUFFER}px)` - : `100%`}; + width: 100%; position: relative; overflow-x: auto; overflow-y: auto; @@ -131,7 +123,6 @@ function MainContainerWrapper(props: MainCanvasWrapperProps) { const isFetchingPage = useSelector(getIsFetchingPage); const widgetsStructure = useSelector(getCanvasWidgetsStructure, equal); const pages = useSelector(getViewModePageList); - const theme = useSelector(getCurrentThemeDetails); const selectedTheme = useSelector(getSelectedAppTheme); const shouldHaveTopMargin = !(isPreviewMode || isProtectedMode) || @@ -145,6 +136,9 @@ function MainContainerWrapper(props: MainCanvasWrapperProps) { const isWDSV2Enabled = useFeatureFlag("ab_wds_enabled"); const { canShowResizer, enableMainContainerResizer } = useMainContainerResizer(); + const layoutSystemType: LayoutSystemTypes = useSelector(getLayoutSystemType); + const isAnvilLayout = layoutSystemType === LayoutSystemTypes.ANVIL; + const headerHeight = "40px"; useEffect(() => { return () => { @@ -181,31 +175,10 @@ function MainContainerWrapper(props: MainCanvasWrapperProps) { const isPreviewingNavigation = isPreviewMode || isProtectedMode || isAppSettingsPaneWithNavigationTabOpen; - /** - * calculating exact height to not allow scroll at this component, - * calculating total height of the canvas minus - * - 1. navigation height - * - 1.1 height for top + stacked or top + inline nav style is calculated - * - 1.2 in case of sidebar nav, height is 0 - * - 2. top bar (header with preview/share/deploy buttons) - * - 3. bottom bar (footer with debug/logs buttons) - */ - const topMargin = shouldShowSnapShotBanner ? "4rem" : "0rem"; - const bottomBarHeight = - isPreviewMode || isProtectedMode ? "0px" : theme.bottomBarHeight; - const smallHeaderHeight = showCanvasTopSection - ? theme.smallHeaderHeight - : "0px"; - const scrollBarHeight = - isPreviewMode || isProtectedMode || isPreviewingNavigation ? "8px" : "40px"; - // calculating exact height to not allow scroll at this component, - // calculating total height minus margin on top, top bar and bottom bar and scrollbar height at the bottom - const heightWithTopMargin = `calc(100vh - 2rem - ${topMargin} - ${smallHeaderHeight} - ${bottomBarHeight} - ${scrollBarHeight} - ${navigationHeight}px)`; return ( <> <Wrapper $enableMainCanvasResizer={enableMainContainerResizer} - $heightWithTopMargin={heightWithTopMargin} background={ isPreviewMode || isProtectedMode || @@ -226,7 +199,8 @@ function MainContainerWrapper(props: MainCanvasWrapperProps) { shouldHaveTopMargin && !showCanvasTopSection && !isPreviewingNavigation && - !showAnonymousDataPopup, + !showAnonymousDataPopup && + !isAnvilLayout, "mt-24": shouldShowSnapShotBanner, })} id={CANVAS_VIEWPORT} @@ -236,7 +210,7 @@ function MainContainerWrapper(props: MainCanvasWrapperProps) { isPreviewingNavigation={isPreviewingNavigation} navigationHeight={navigationHeight} style={{ - height: shouldHaveTopMargin ? heightWithTopMargin : "100vh", + height: isPreviewMode ? `calc(100% - ${headerHeight})` : "auto", fontFamily: fontFamily, pointerEvents: isAutoCanvasResizing ? "none" : "auto", }} @@ -257,7 +231,6 @@ function MainContainerWrapper(props: MainCanvasWrapperProps) { <MainContainerResizer currentPageId={currentPageId} enableMainCanvasResizer={enableMainContainerResizer && canShowResizer} - heightWithTopMargin={heightWithTopMargin} isPageInitiated={!isPageInitializing && !!widgetsStructure} isPreview={isPreviewMode || isProtectedMode} shouldHaveTopMargin={shouldHaveTopMargin} diff --git a/app/client/src/pages/Editor/WidgetsEditor/index.tsx b/app/client/src/pages/Editor/WidgetsEditor/index.tsx index c06addd90e50..1558987e37a5 100644 --- a/app/client/src/pages/Editor/WidgetsEditor/index.tsx +++ b/app/client/src/pages/Editor/WidgetsEditor/index.tsx @@ -9,6 +9,9 @@ import { getCurrentPageName, previewModeSelector, } from "selectors/editorSelectors"; +import styled from "styled-components"; +import { LayoutSystemTypes } from "../../../layoutSystems/types"; +import { getLayoutSystemType } from "../../../selectors/layoutSystemSelectors"; import NavigationPreview from "./NavigationPreview"; import AnalyticsUtil from "utils/AnalyticsUtil"; import PerformanceTracker, { @@ -49,6 +52,10 @@ import { import OverlayCanvasContainer from "layoutSystems/common/WidgetNamesCanvas"; import { protectedModeSelector } from "selectors/gitSyncSelectors"; +const BannerWrapper = styled.div` + z-index: calc(var(--on-canvas-ui-z-index) + 1); +`; + function WidgetsEditor() { const dispatch = useDispatch(); const currentPageId = useSelector(getCurrentPageId); @@ -87,6 +94,9 @@ function WidgetsEditor() { LayoutSystemFeatures.ENABLE_CANVAS_OVERLAY_FOR_EDITOR_UI, ]); + const layoutSystemType: LayoutSystemTypes = useSelector(getLayoutSystemType); + const isAnvilLayout = layoutSystemType === LayoutSystemTypes.ANVIL; + useEffect(() => { if (navigationPreviewRef?.current) { const { offsetHeight } = navigationPreviewRef.current; @@ -176,7 +186,7 @@ function WidgetsEditor() { PerformanceTracker.stopTracking(); return ( <EditorContextProvider renderMode="CANVAS"> - <div className="relative flex flex-row w-full overflow-hidden"> + <div className="relative flex flex-row h-full w-full overflow-hidden"> <div className={classNames({ "relative flex flex-col w-full overflow-hidden": true, @@ -189,7 +199,7 @@ function WidgetsEditor() { )} <AnonymousDataPopup /> <div - className="relative flex flex-row w-full overflow-hidden" + className="relative flex flex-row h-full w-full overflow-hidden" data-testid="widgets-editor" draggable id="widgets-editor" @@ -218,11 +228,19 @@ function WidgetsEditor() { isPreview={isPreviewMode || isProtectedMode} isPublished={isPublished} sidebarWidth={isPreviewingNavigation ? sidebarWidth : 0} + style={ + isAnvilLayout + ? { + //This is necessary in order to place WDS modal with position: fixed; relatively to the canvas. + transform: "scale(1)", + } + : {} + } > {shouldShowSnapShotBanner && ( - <div className="absolute top-0 z-1 w-full"> + <BannerWrapper className="absolute top-0 w-full"> <SnapShotBannerCTA /> - </div> + </BannerWrapper> )} <MainContainerWrapper canvasWidth={canvasWidth} diff --git a/app/client/src/widgets/wds/WDSModalWidget/widget/index.tsx b/app/client/src/widgets/wds/WDSModalWidget/widget/index.tsx index c99dedfdae91..837571feaed3 100644 --- a/app/client/src/widgets/wds/WDSModalWidget/widget/index.tsx +++ b/app/client/src/widgets/wds/WDSModalWidget/widget/index.tsx @@ -24,15 +24,17 @@ import type { import { call } from "redux-saga/effects"; import { pasteWidgetsIntoMainCanvas } from "layoutSystems/anvil/utils/paste/mainCanvasPasteUtils"; -const modalBodyStyles: React.CSSProperties = { - minHeight: "var(--sizing-16)", - maxHeight: - "calc(var(--canvas-height) - var(--outer-spacing-4) - var(--outer-spacing-4) - var(--outer-spacing-4) - 100px)", -}; - class WDSModalWidget extends BaseWidget<ModalWidgetProps, WidgetState> { static type = "WDS_MODAL_WIDGET"; + constructor(props: ModalWidgetProps) { + super(props); + + this.state = { + isVisible: this.getModalVisibility(), + }; + } + static getConfig() { return config.metaConfig; } @@ -117,16 +119,14 @@ class WDSModalWidget extends BaseWidget<ModalWidgetProps, WidgetState> { return ( <Modal - isOpen={this.getModalVisibility()} + isOpen={this.state.isVisible as boolean} onClose={this.onModalClose} + setOpen={(val) => this.setState({ isVisible: val })} size={this.props.size} > <ModalContent className={this.props.className}> {this.props.showHeader && <ModalHeader title={this.props.title} />} - <ModalBody - className={WDS_MODAL_WIDGET_CLASSNAME} - style={modalBodyStyles} - > + <ModalBody className={WDS_MODAL_WIDGET_CLASSNAME}> <LayoutProvider {...this.props} /> </ModalBody> {this.props.showFooter && (
5312ee11f3a4cb02f61e46d779822473d5588a75
2023-09-11 18:37:02
Saroj
test: Fix gsheet tests (#27146)
false
Fix gsheet tests (#27146)
test
diff --git a/.github/workflows/ci-test-custom-script.yml b/.github/workflows/ci-test-custom-script.yml index 78537268ddaf..7fde0c71ae95 100644 --- a/.github/workflows/ci-test-custom-script.yml +++ b/.github/workflows/ci-test-custom-script.yml @@ -475,13 +475,13 @@ jobs: path: ~/dockerlogs - name: Rename reports - if: always() + if: failure() && env.failed_spec_env != '' run: | mkdir -p ~/results mv ${{ github.workspace }}/app/client/results ~/results/${{ matrix.job }} - name: Upload cypress report - if: always() + if: failure() && env.failed_spec_env != '' uses: actions/upload-artifact@v3 with: name: results-${{github.run_attempt}} diff --git a/.github/workflows/ci-test-hosted.yml b/.github/workflows/ci-test-hosted.yml index b147f7b999d5..c992b963eb96 100644 --- a/.github/workflows/ci-test-hosted.yml +++ b/.github/workflows/ci-test-hosted.yml @@ -122,7 +122,7 @@ jobs: fi done fi - done < ~/failed_spec_ci/failed_spec_ci-${{ matrix.job }} + done < ~/failed_spec_ci/failed_spec_ci failed_spec_env=${failed_spec_env#,} echo "failed_spec_env=$failed_spec_env" >> $GITHUB_ENV @@ -395,13 +395,13 @@ jobs: env: "NODE_ENV=development" - name: Rename reports - if: always() + if: failure() && env.failed_spec_env != '' run: | mkdir -p ~/results mv ${{ github.workspace }}/app/client/results ~/results/${{ matrix.job }} - name: Upload cypress report - if: always() + if: failure() && env.failed_spec_env != '' uses: actions/upload-artifact@v3 with: name: results-${{github.run_attempt}} diff --git a/.github/workflows/ci-test-limited.yml b/.github/workflows/ci-test-limited.yml index 2be864f7e760..9cf58b3e0d1c 100644 --- a/.github/workflows/ci-test-limited.yml +++ b/.github/workflows/ci-test-limited.yml @@ -527,13 +527,13 @@ jobs: path: ~/dockerlogs - name: Rename reports - if: always() + if: failure() && env.failed_spec_env != '' run: | mkdir -p ~/results mv ${{ github.workspace }}/app/client/results ~/results/${{ matrix.job }} - name: Upload cypress report - if: always() + if: failure() && env.failed_spec_env != '' uses: actions/upload-artifact@v3 with: name: results-${{github.run_attempt}} diff --git a/app/client/cypress/e2e/GSheet/AllAccess_Spec.ts b/app/client/cypress/e2e/GSheet/AllAccess_Spec.ts index 43449f0db5ab..c8f98e60b0fc 100644 --- a/app/client/cypress/e2e/GSheet/AllAccess_Spec.ts +++ b/app/client/cypress/e2e/GSheet/AllAccess_Spec.ts @@ -185,7 +185,7 @@ describe("GSheet-Functional Tests With All Access", function () { inputFieldName: "Cell range", }); dataSources.RunQuery(); - dataSources.RunQueryNVerifyResponseViews(8); + dataSources.RunQueryNVerifyResponseViews(4); dataSources.AssertQueryTableResponse(0, "eac7efa5dbd3d667f26eb3d3ab504464"); }); diff --git a/app/client/cypress/e2e/GSheet/ReadNWrite_Access_Spec.ts b/app/client/cypress/e2e/GSheet/ReadNWrite_Access_Spec.ts index 1db69b8feb68..11e4c9073cda 100644 --- a/app/client/cypress/e2e/GSheet/ReadNWrite_Access_Spec.ts +++ b/app/client/cypress/e2e/GSheet/ReadNWrite_Access_Spec.ts @@ -182,7 +182,7 @@ describe("GSheet-Functional Tests With Read/Write Access", function () { inputFieldName: "Cell range", }); dataSources.RunQuery(); - dataSources.RunQueryNVerifyResponseViews(8); + dataSources.RunQueryNVerifyResponseViews(4); dataSources.AssertQueryTableResponse(0, "eac7efa5dbd3d667f26eb3d3ab504464"); }); diff --git a/app/client/cypress/e2e/GSheet/ReadOnly_Access_Spec.ts b/app/client/cypress/e2e/GSheet/ReadOnly_Access_Spec.ts index 0c936470a2f3..1561282ae97a 100644 --- a/app/client/cypress/e2e/GSheet/ReadOnly_Access_Spec.ts +++ b/app/client/cypress/e2e/GSheet/ReadOnly_Access_Spec.ts @@ -190,7 +190,7 @@ describe("GSheet-Functional Tests With Read Access", function () { inputFieldName: "Cell range", }); dataSources.RunQuery(); - dataSources.RunQueryNVerifyResponseViews(8); + dataSources.RunQueryNVerifyResponseViews(4); dataSources.AssertQueryTableResponse(0, "eac7efa5dbd3d667f26eb3d3ab504464"); }); diff --git a/app/client/cypress/e2e/GSheet/SelectedSheet_Access_Spec.ts b/app/client/cypress/e2e/GSheet/SelectedSheet_Access_Spec.ts index 6bbc774f63b5..4415ae80f0a3 100644 --- a/app/client/cypress/e2e/GSheet/SelectedSheet_Access_Spec.ts +++ b/app/client/cypress/e2e/GSheet/SelectedSheet_Access_Spec.ts @@ -173,7 +173,7 @@ describe("GSheet-Functional Tests With Selected Access", function () { inputFieldName: "Cell range", }); dataSources.RunQuery(); - dataSources.RunQueryNVerifyResponseViews(8); + dataSources.RunQueryNVerifyResponseViews(4); dataSources.AssertQueryTableResponse(0, "eac7efa5dbd3d667f26eb3d3ab504464"); });
e6a7e5cf45b0065da0c4f569b50263ac7bcf092d
2022-01-06 15:43:24
Aman Agarwal
fix: run button loading infinitely due to query update when final and initial value remains same (#10189)
false
run button loading infinitely due to query update when final and initial value remains same (#10189)
fix
diff --git a/app/client/src/components/editorComponents/CodeEditor/index.tsx b/app/client/src/components/editorComponents/CodeEditor/index.tsx index f22fb1249abd..50317417e8d2 100644 --- a/app/client/src/components/editorComponents/CodeEditor/index.tsx +++ b/app/client/src/components/editorComponents/CodeEditor/index.tsx @@ -150,6 +150,8 @@ type State = { isOpened: boolean; autoCompleteVisible: boolean; hinterOpen: boolean; + // Flag for determining whether the entity change has been started or not so that even if the initial and final value remains the same, the status should be changed to not loading + changeStarted: boolean; }; class CodeEditor extends Component<Props, State> { @@ -171,6 +173,7 @@ class CodeEditor extends Component<Props, State> { isOpened: false, autoCompleteVisible: false, hinterOpen: false, + changeStarted: false, }; this.updatePropertyValue = this.updatePropertyValue.bind(this); } @@ -392,9 +395,12 @@ class CodeEditor extends Component<Props, State> { const inputValue = this.props.input.value || ""; if ( this.props.input.onChange && - value !== inputValue && - this.state.isFocused + ((value !== inputValue && this.state.isFocused) || + this.state.changeStarted) ) { + this.setState({ + changeStarted: false, + }); this.props.input.onChange(value); } CodeEditor.updateMarkings(this.editor, this.props.marking); @@ -410,8 +416,12 @@ class CodeEditor extends Component<Props, State> { if ( this.props.input.onChange && value !== inputValue && - this.state.isFocused + this.state.isFocused && + !this.state.changeStarted ) { + this.setState({ + changeStarted: true, + }); this.props.startingEntityUpdation(); } this.handleDebouncedChange(instance, changeObj);
3f87f4959e9a3decddd4f997f65131cb725505d9
2021-11-23 19:40:13
Paul Li
fix: Table Widget Icon Button should be having a default variant (#8664)
false
Table Widget Icon Button should be having a default variant (#8664)
fix
diff --git a/app/client/src/constants/WidgetConstants.tsx b/app/client/src/constants/WidgetConstants.tsx index 79b080cb5e76..8f3d1339cf82 100644 --- a/app/client/src/constants/WidgetConstants.tsx +++ b/app/client/src/constants/WidgetConstants.tsx @@ -69,7 +69,7 @@ export const layoutConfigurations: LayoutConfigurations = { FLUID: { minWidth: -1, maxWidth: -1 }, }; -export const LATEST_PAGE_VERSION = 45; +export const LATEST_PAGE_VERSION = 46; export const GridDefaults = { DEFAULT_CELL_SIZE: 1, diff --git a/app/client/src/utils/DSLMigrations.ts b/app/client/src/utils/DSLMigrations.ts index ed5cc503068a..a5cb5098946e 100644 --- a/app/client/src/utils/DSLMigrations.ts +++ b/app/client/src/utils/DSLMigrations.ts @@ -24,6 +24,7 @@ import { migrateTableWidgetSelectedRowBindings, migrateTableSanitizeColumnKeys, isSortableMigration, + migrateTableWidgetIconButtonVariant, } from "./migrations/TableWidget"; import { migrateTextStyleFromTextWidget } from "./migrations/TextWidgetReplaceTextStyle"; import { DATA_BIND_REGEX_GLOBAL } from "constants/BindingsConstants"; @@ -978,6 +979,10 @@ export const transformDSL = ( } if (currentDSL.version === 44) { currentDSL = isSortableMigration(currentDSL); + currentDSL.version = 45; + } + if (currentDSL.version === 45) { + currentDSL = migrateTableWidgetIconButtonVariant(currentDSL); currentDSL.version = LATEST_PAGE_VERSION; } diff --git a/app/client/src/utils/migrations/TableWidget.ts b/app/client/src/utils/migrations/TableWidget.ts index 5f9f5b8dd114..e63033b30cd3 100644 --- a/app/client/src/utils/migrations/TableWidget.ts +++ b/app/client/src/utils/migrations/TableWidget.ts @@ -462,3 +462,27 @@ export const migrateTableSanitizeColumnKeys = (currentDSL: DSLWidget) => { return currentDSL; }; + +export const migrateTableWidgetIconButtonVariant = (currentDSL: DSLWidget) => { + currentDSL.children = currentDSL.children?.map((child: WidgetProps) => { + if (child.type === "TABLE_WIDGET") { + const primaryColumns = child.primaryColumns as Record< + string, + ColumnProperties + >; + Object.keys(primaryColumns).forEach((accessor: string) => { + const primaryColumn = primaryColumns[accessor]; + + if (primaryColumn.columnType === "iconButton") { + if (!("buttonVariant" in primaryColumn)) { + primaryColumn.buttonVariant = "TERTIARY"; + } + } + }); + } else if (child.children && child.children.length > 0) { + child = migrateTableWidgetIconButtonVariant(child); + } + return child; + }); + return currentDSL; +}; diff --git a/app/client/src/widgets/TableWidget/widget/index.tsx b/app/client/src/widgets/TableWidget/widget/index.tsx index 633c83ac8ed1..8adc62f5d56d 100644 --- a/app/client/src/widgets/TableWidget/widget/index.tsx +++ b/app/client/src/widgets/TableWidget/widget/index.tsx @@ -241,7 +241,7 @@ class TableWidget extends BaseWidget<TableWidgetProps, WidgetState> { ], iconName: (cellProperties.iconName || IconNames.ADD) as IconName, buttonColor: cellProperties.buttonColor || Colors.GREEN, - buttonVariant: cellProperties.buttonVariant, + buttonVariant: cellProperties.buttonVariant || "PRIMARY", borderRadius: cellProperties.borderRadius || "SHARP", boxShadow: cellProperties.boxShadow || "NONE", boxShadowColor: cellProperties.boxShadowColor || "", diff --git a/app/client/src/widgets/TableWidget/widget/propertyConfig.ts b/app/client/src/widgets/TableWidget/widget/propertyConfig.ts index 19b361172738..fb3f7a46da70 100644 --- a/app/client/src/widgets/TableWidget/widget/propertyConfig.ts +++ b/app/client/src/widgets/TableWidget/widget/propertyConfig.ts @@ -819,6 +819,7 @@ export default [ value: ButtonVariantTypes.TERTIARY, }, ], + defaultValue: ButtonVariantTypes.PRIMARY, isBindProperty: true, isTriggerProperty: false, validation: { diff --git a/app/client/src/widgets/TableWidget/widget/propertyUtils.ts b/app/client/src/widgets/TableWidget/widget/propertyUtils.ts index 3cbd1aa8a512..dc193e80a874 100644 --- a/app/client/src/widgets/TableWidget/widget/propertyUtils.ts +++ b/app/client/src/widgets/TableWidget/widget/propertyUtils.ts @@ -198,7 +198,7 @@ export const updateColumnStyles = ( } return; }; -// Select a default Icon Alignment when an icon is chosen +// Select default Icon Alignment when an icon is chosen export function updateIconAlignment( props: TableWidgetProps, propertyPath: string, @@ -225,6 +225,7 @@ export function updateIconAlignment( propertyValue: Alignment.LEFT, }); } + return propertiesToUpdate; }
b697550dffcab9d6b3d6b9bf6ca3d87671520f3f
2023-10-10 15:13:33
arunvjn
chore: Fix bug in unique accessor generation logic for js libraries (#27911)
false
Fix bug in unique accessor generation logic for js libraries (#27911)
chore
diff --git a/app/client/src/workers/Evaluation/handlers/jsLibrary.ts b/app/client/src/workers/Evaluation/handlers/jsLibrary.ts index 600d2ba89e40..f45992d91896 100644 --- a/app/client/src/workers/Evaluation/handlers/jsLibrary.ts +++ b/app/client/src/workers/Evaluation/handlers/jsLibrary.ts @@ -306,8 +306,8 @@ function generateUniqueAccessor( ) { return validVar; } - const index = 1; - while (true && index < 100) { + let index = 0; + while (index++ < 100) { const name = `Library_${index}`; if (!takenAccessors.includes(name) && !takenNamesMap.hasOwnProperty(name)) { return name;
e64f7f3e141549aa022e63fdf5e8f7d1c652e435
2023-11-09 13:19:35
subratadeypappu
fix: Update refactored entity by branched id (#28741)
false
Update refactored entity by branched id (#28741)
fix
diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/newactions/refactors/NewActionRefactoringServiceCEImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/newactions/refactors/NewActionRefactoringServiceCEImpl.java index 3b1835772ae6..aeeb26b15f5a 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/newactions/refactors/NewActionRefactoringServiceCEImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/newactions/refactors/NewActionRefactoringServiceCEImpl.java @@ -114,14 +114,15 @@ public Mono<Void> refactorReferencesInExistingEntities( @Override public Mono<Void> updateRefactoredEntity(RefactorEntityNameDTO refactorEntityNameDTO, String branchName) { return newActionService - .findActionDTObyIdAndViewMode( - refactorEntityNameDTO.getActionId(), false, actionPermission.getEditPermission()) + .findByBranchNameAndDefaultActionId( + branchName, refactorEntityNameDTO.getActionId(), actionPermission.getEditPermission()) + .flatMap(branchedAction -> newActionService.generateActionByViewMode(branchedAction, false)) .flatMap(action -> { action.setName(refactorEntityNameDTO.getNewName()); if (StringUtils.hasLength(refactorEntityNameDTO.getCollectionName())) { action.setFullyQualifiedName(refactorEntityNameDTO.getNewFullyQualifiedName()); } - return newActionService.updateUnpublishedAction(refactorEntityNameDTO.getActionId(), action); + return newActionService.updateUnpublishedAction(action.getId(), action); }) .then(); }
d897d4c1ad01ac858be32e74e1be0c7a46ba3edf
2023-10-06 11:16:06
sharanya-appsmith
test: Cypress - chart widget cases (#27837)
false
Cypress - chart widget cases (#27837)
test
diff --git a/app/client/cypress/e2e/Regression/ClientSide/Widgets/Chart/Chart_widget_spec_1.ts b/app/client/cypress/e2e/Regression/ClientSide/Widgets/Chart/Chart_widget_spec_1.ts new file mode 100644 index 000000000000..7114e7c76fb8 --- /dev/null +++ b/app/client/cypress/e2e/Regression/ClientSide/Widgets/Chart/Chart_widget_spec_1.ts @@ -0,0 +1,85 @@ +import { + agHelper, + entityExplorer, + deployMode, + draggableWidgets, + propPane, + locators, +} from "../../../../../support/Objects/ObjectsCore"; + +describe("", () => { + before(() => { + entityExplorer.DragNDropWidget(draggableWidgets.CHART); + }); + + afterEach(() => { + deployMode.NavigateBacktoEditor(); + entityExplorer.SelectEntityByName("Chart1"); + }); + + it("1. Test pie chart", () => { + propPane.SelectPropertiesDropDown("Chart Type", "Pie chart"); + agHelper.AssertAutoSave(); + deployMode.DeployApp(); + agHelper + .GetElement(locators._widgetInDeployed(draggableWidgets.CHART)) + .matchImageSnapshot("chartwidget/piechartsnapshot"); + deployMode.NavigateBacktoEditor(); + entityExplorer.SelectEntityByName("Chart1"); + propPane.TogglePropertyState("Show Labels", "On"); + deployMode.DeployApp(); + agHelper + .GetElement(locators._widgetInDeployed(draggableWidgets.CHART)) + .matchImageSnapshot("chartwidget/piechartsnapshotwithlabels"); + }); + + it("2. Test line chart", () => { + propPane.TogglePropertyState("Show Labels", "Off"); + propPane.SelectPropertiesDropDown("Chart Type", "Line chart"); + agHelper.AssertAutoSave(); + deployMode.DeployApp(); + agHelper + .GetElement(locators._widgetInDeployed(draggableWidgets.CHART)) + .matchImageSnapshot("chartwidget/linechartsnapshot"); + deployMode.NavigateBacktoEditor(); + entityExplorer.SelectEntityByName("Chart1"); + propPane.TogglePropertyState("Show Labels", "On"); + deployMode.DeployApp(); + agHelper + .GetElement(locators._widgetInDeployed(draggableWidgets.CHART)) + .matchImageSnapshot("chartwidget/linechartsnapshotwithlabels"); + }); + + it("3. Test column chart", () => { + propPane.TogglePropertyState("Show Labels", "Off"); + propPane.SelectPropertiesDropDown("Chart Type", "Column chart"); + deployMode.DeployApp(); + agHelper + .GetElement(locators._widgetInDeployed(draggableWidgets.CHART)) + .matchImageSnapshot("chartwidget/columnchartsnapshot"); + deployMode.NavigateBacktoEditor(); + entityExplorer.SelectEntityByName("Chart1"); + propPane.TogglePropertyState("Show Labels", "On"); + deployMode.DeployApp(); + agHelper + .GetElement(locators._widgetInDeployed(draggableWidgets.CHART)) + .matchImageSnapshot("chartwidget/columnchartsnapshotwithlabels"); + }); + + it("4. Test area chart", () => { + propPane.TogglePropertyState("Show Labels", "Off"); + propPane.SelectPropertiesDropDown("Chart Type", "Area chart"); + agHelper.AssertAutoSave(); + deployMode.DeployApp(); + agHelper + .GetElement(locators._widgetInDeployed(draggableWidgets.CHART)) + .matchImageSnapshot("chartwidget/areachartsnapshot"); + deployMode.NavigateBacktoEditor(); + entityExplorer.SelectEntityByName("Chart1"); + propPane.TogglePropertyState("Show Labels", "On"); + deployMode.DeployApp(); + agHelper + .GetElement(locators._widgetInDeployed(draggableWidgets.CHART)) + .matchImageSnapshot("chartwidget/areachartsnapshotwithlabels"); + }); +}); diff --git a/app/client/cypress/e2e/Regression/ClientSide/Widgets/Chart/Chart_widget_spec_2.ts b/app/client/cypress/e2e/Regression/ClientSide/Widgets/Chart/Chart_widget_spec_2.ts new file mode 100644 index 000000000000..c447a74315bc --- /dev/null +++ b/app/client/cypress/e2e/Regression/ClientSide/Widgets/Chart/Chart_widget_spec_2.ts @@ -0,0 +1,94 @@ +import { + agHelper, + entityExplorer, + deployMode, + draggableWidgets, + propPane, + locators, +} from "../../../../../support/Objects/ObjectsCore"; + +describe("", () => { + before(() => { + entityExplorer.DragNDropWidget(draggableWidgets.CHART); + }); + + it("1. Test Series tile chart", () => { + propPane.SelectPropertiesDropDown("Chart Type", "Pie chart"); + propPane.UpdatePropertyFieldValue( + "Title", + "Data of anime at 2020 @ December", + ); + agHelper.AssertAutoSave(); + deployMode.DeployApp(); + agHelper + .GetElement(locators._widgetInDeployed(draggableWidgets.CHART)) + .matchImageSnapshot("chartwidget/piechartsnapshotwithtitle"); + deployMode.NavigateBacktoEditor(); + entityExplorer.SelectEntityByName("Chart1"); + }); + + it("2. Test Adaptive axis", () => { + propPane.SelectPropertiesDropDown("Chart Type", "Column chart"); + agHelper.AssertAutoSave(); + deployMode.DeployApp(); + agHelper + .GetElement(locators._widgetInDeployed(draggableWidgets.CHART)) + .matchImageSnapshot("chartwidget/columnchartsnapshotwithoutadaptiveaxis"); + deployMode.NavigateBacktoEditor(); + entityExplorer.SelectEntityByName("Chart1"); + propPane.TogglePropertyState("Adaptive axis", "On"); + deployMode.DeployApp(); + agHelper + .GetElement(locators._widgetInDeployed(draggableWidgets.CHART)) + .matchImageSnapshot("chartwidget/columnchartsnapshotwithadaptiveaxis"); + deployMode.NavigateBacktoEditor(); + entityExplorer.SelectEntityByName("Chart1"); + }); + + it("3. Test x axis label orientation chart", () => { + propPane.SelectPropertiesDropDown("Chart Type", "Line chart"); + deployMode.DeployApp(); + agHelper + .GetElement(locators._widgetInDeployed(draggableWidgets.CHART)) + .matchImageSnapshot("chartwidget/linechartWithAutoXAxisLabelOrientation"); + deployMode.NavigateBacktoEditor(); + entityExplorer.SelectEntityByName("Chart1"); + propPane.SelectPropertiesDropDown("x-axis label orientation", "Slant"); + deployMode.DeployApp(); + agHelper + .GetElement(locators._widgetInDeployed(draggableWidgets.CHART)) + .matchImageSnapshot( + "chartwidget/linechartWithSlantXAxisLabelOrientation", + ); + deployMode.NavigateBacktoEditor(); + entityExplorer.SelectEntityByName("Chart1"); + propPane.SelectPropertiesDropDown("x-axis label orientation", "Rotate"); + deployMode.DeployApp(); + agHelper + .GetElement(locators._widgetInDeployed(draggableWidgets.CHART)) + .matchImageSnapshot( + "chartwidget/linechartWithRotateXAxisLabelOrientation", + ); + deployMode.NavigateBacktoEditor(); + entityExplorer.SelectEntityByName("Chart1"); + }); + + it("4. Test x axis label orientation absence in Pie, Bar, Custom Fusion Charts", () => { + propPane.SelectPropertiesDropDown("Chart Type", "Pie chart"); + agHelper.AssertElementAbsence( + propPane._selectPropDropdown("x-axis label orientation"), + ); + propPane.SelectPropertiesDropDown("Chart Type", "Bar chart"); + agHelper.AssertElementAbsence( + propPane._selectPropDropdown("x-axis label orientation"), + ); + propPane.SelectPropertiesDropDown("Chart Type", "Custom Fusion Charts"); + agHelper.AssertElementAbsence( + propPane._selectPropDropdown("x-axis label orientation"), + ); + propPane.SelectPropertiesDropDown("Chart Type", "Column chart"); + agHelper.AssertElementExist( + propPane._selectPropDropdown("x-axis label orientation"), + ); + }); +}); diff --git a/app/client/cypress/snapshots/chartwidget/areachartsnapshot.snap.png b/app/client/cypress/snapshots/chartwidget/areachartsnapshot.snap.png new file mode 100644 index 000000000000..19f12d0e4e46 Binary files /dev/null and b/app/client/cypress/snapshots/chartwidget/areachartsnapshot.snap.png differ diff --git a/app/client/cypress/snapshots/chartwidget/areachartsnapshotwithlabels.snap.png b/app/client/cypress/snapshots/chartwidget/areachartsnapshotwithlabels.snap.png new file mode 100644 index 000000000000..d7168ce30819 Binary files /dev/null and b/app/client/cypress/snapshots/chartwidget/areachartsnapshotwithlabels.snap.png differ diff --git a/app/client/cypress/snapshots/chartwidget/columnchartsnapshot.snap.png b/app/client/cypress/snapshots/chartwidget/columnchartsnapshot.snap.png new file mode 100644 index 000000000000..ed10abc96733 Binary files /dev/null and b/app/client/cypress/snapshots/chartwidget/columnchartsnapshot.snap.png differ diff --git a/app/client/cypress/snapshots/chartwidget/columnchartsnapshotwithadaptiveaxis.snap.png b/app/client/cypress/snapshots/chartwidget/columnchartsnapshotwithadaptiveaxis.snap.png new file mode 100644 index 000000000000..d67bf8abb713 Binary files /dev/null and b/app/client/cypress/snapshots/chartwidget/columnchartsnapshotwithadaptiveaxis.snap.png differ diff --git a/app/client/cypress/snapshots/chartwidget/columnchartsnapshotwithlabels.snap.png b/app/client/cypress/snapshots/chartwidget/columnchartsnapshotwithlabels.snap.png new file mode 100644 index 000000000000..85ea6e291726 Binary files /dev/null and b/app/client/cypress/snapshots/chartwidget/columnchartsnapshotwithlabels.snap.png differ diff --git a/app/client/cypress/snapshots/chartwidget/columnchartsnapshotwithoutadaptiveaxis.snap.png b/app/client/cypress/snapshots/chartwidget/columnchartsnapshotwithoutadaptiveaxis.snap.png new file mode 100644 index 000000000000..c184abd328ec Binary files /dev/null and b/app/client/cypress/snapshots/chartwidget/columnchartsnapshotwithoutadaptiveaxis.snap.png differ diff --git a/app/client/cypress/snapshots/chartwidget/linechartWithAutoXAxisLabelOrientation.snap.png b/app/client/cypress/snapshots/chartwidget/linechartWithAutoXAxisLabelOrientation.snap.png new file mode 100644 index 000000000000..983bd2fac3b1 Binary files /dev/null and b/app/client/cypress/snapshots/chartwidget/linechartWithAutoXAxisLabelOrientation.snap.png differ diff --git a/app/client/cypress/snapshots/chartwidget/linechartWithRotateXAxisLabelOrientation.snap.png b/app/client/cypress/snapshots/chartwidget/linechartWithRotateXAxisLabelOrientation.snap.png new file mode 100644 index 000000000000..e0a524f6e2b7 Binary files /dev/null and b/app/client/cypress/snapshots/chartwidget/linechartWithRotateXAxisLabelOrientation.snap.png differ diff --git a/app/client/cypress/snapshots/chartwidget/linechartWithSlantXAxisLabelOrientation.snap.png b/app/client/cypress/snapshots/chartwidget/linechartWithSlantXAxisLabelOrientation.snap.png new file mode 100644 index 000000000000..99f54011aa2c Binary files /dev/null and b/app/client/cypress/snapshots/chartwidget/linechartWithSlantXAxisLabelOrientation.snap.png differ diff --git a/app/client/cypress/snapshots/chartwidget/linechartsnapshot.snap.png b/app/client/cypress/snapshots/chartwidget/linechartsnapshot.snap.png new file mode 100644 index 000000000000..4ce11795c651 Binary files /dev/null and b/app/client/cypress/snapshots/chartwidget/linechartsnapshot.snap.png differ diff --git a/app/client/cypress/snapshots/chartwidget/linechartsnapshotwithlabels.snap.png b/app/client/cypress/snapshots/chartwidget/linechartsnapshotwithlabels.snap.png new file mode 100644 index 000000000000..c07975dbfc4e Binary files /dev/null and b/app/client/cypress/snapshots/chartwidget/linechartsnapshotwithlabels.snap.png differ diff --git a/app/client/cypress/snapshots/chartwidget/piechartsnapshot.snap.png b/app/client/cypress/snapshots/chartwidget/piechartsnapshot.snap.png new file mode 100644 index 000000000000..646158018126 Binary files /dev/null and b/app/client/cypress/snapshots/chartwidget/piechartsnapshot.snap.png differ diff --git a/app/client/cypress/snapshots/chartwidget/piechartsnapshotwithlabels.snap.png b/app/client/cypress/snapshots/chartwidget/piechartsnapshotwithlabels.snap.png new file mode 100644 index 000000000000..d84973a5e466 Binary files /dev/null and b/app/client/cypress/snapshots/chartwidget/piechartsnapshotwithlabels.snap.png differ diff --git a/app/client/cypress/snapshots/chartwidget/piechartsnapshotwithtitle.snap.png b/app/client/cypress/snapshots/chartwidget/piechartsnapshotwithtitle.snap.png new file mode 100644 index 000000000000..05acfe7fbe9d Binary files /dev/null and b/app/client/cypress/snapshots/chartwidget/piechartsnapshotwithtitle.snap.png differ
71a82b46705c704fe18f37cac8734266edbd1d46
2022-07-11 15:48:24
Hetu Nandu
feat: Add the Zipy identify call (#15060)
false
Add the Zipy identify call (#15060)
feat
diff --git a/app/client/src/utils/AnalyticsUtil.tsx b/app/client/src/utils/AnalyticsUtil.tsx index c4fbe64e88e9..e0e16ea85722 100644 --- a/app/client/src/utils/AnalyticsUtil.tsx +++ b/app/client/src/utils/AnalyticsUtil.tsx @@ -6,6 +6,16 @@ import * as Sentry from "@sentry/react"; import { ANONYMOUS_USERNAME, User } from "constants/userConstants"; import { sha256 } from "js-sha256"; +declare global { + interface Window { + // Zipy is added via script tags in index.html + zipy: { + identify: (uid: string, userInfo: Record<string, string>) => void; + anonymize: () => void; + }; + } +} + export type EventLocation = | "LIGHTNING_MENU" | "API_PANE" @@ -407,6 +417,14 @@ class AnalyticsUtil { if (smartLook.enabled) { smartlookClient.identify(userId, { email: userData.email }); } + + // If zipy was included, identify this user on the platform + if (window.zipy && userId) { + window.zipy.identify(userId, { + email: userData.email, + username: userData.username, + }); + } } static reset() { @@ -416,6 +434,7 @@ class AnalyticsUtil { } windowDoc.analytics && windowDoc.analytics.reset(); windowDoc.mixpanel && windowDoc.mixpanel.reset(); + window.zipy && window.zipy.anonymize(); } }
82280cfde9378e1db13fec571d41f58168477438
2023-04-10 12:32:31
Sangeeth Sivan
feat: util to serve images locally or via remote url (#22080)
false
util to serve images locally or via remote url (#22080)
feat
diff --git a/app/client/download-assets.js b/app/client/download-assets.js new file mode 100644 index 000000000000..05b22ed18da0 --- /dev/null +++ b/app/client/download-assets.js @@ -0,0 +1,61 @@ +const fs = require("fs"); +const path = require("path"); +const https = require("https"); + +const regex = /(?:\${ASSETS_CDN_URL}|https:\/\/assets\.appsmith\.com)[^`"]+/g; + +const rootDir = [ + path.resolve(__dirname, "src"), + path.join(path.resolve(__dirname, "../"), "server", "appsmith-server"), +]; + +function searchFiles(dir) { + fs.readdirSync(dir).forEach((file) => { + const filePath = path.join(dir, file); + const stat = fs.statSync(filePath); + if (stat.isDirectory()) { + searchFiles(filePath); + } else if (stat.isFile() && path.extname(filePath) !== ".class") { + // Skip .class files - server code + const contents = fs.readFileSync(filePath, "utf8"); + const matches = contents.match(regex); + if (matches) { + console.log(`Found ${matches.length} matches in ${filePath}:`); + const replacedMatches = matches.map((match) => { + return match.replace( + /\${ASSETS_CDN_URL}/, + "https://assets.appsmith.com", + ); + }); + replacedMatches.forEach((match) => { + const filename = path.basename(match); + const destPath = path.join(__dirname, "public", filename); + if (fs.existsSync(destPath)) { + console.log(`File already exists: ${filename}`); + return; + } + console.log(`Downloading ${match} to ${destPath}...`); + https.get(match, (response) => { + if (response.statusCode === 200) { + const fileStream = fs.createWriteStream(destPath); + response.pipe(fileStream); + fileStream.on("finish", () => { + fileStream.close(); + console.log(`Downloaded ${match} to ${destPath}`); + }); + } else { + console.error( + `Failed to download ${match}:`, + response.statusCode, + ); + } + }); + }); + } + } + }); +} + +for (const dir of rootDir) { + searchFiles(dir); +} diff --git a/app/client/package.json b/app/client/package.json index 43fcfb687ca3..25376948cff7 100644 --- a/app/client/package.json +++ b/app/client/package.json @@ -13,7 +13,9 @@ "scripts": { "analyze": "yarn cra-bundle-analyzer", "start": "BROWSER=none EXTEND_ESLINT=true REACT_APP_ENVIRONMENT=DEVELOPMENT REACT_APP_CLIENT_LOG_LEVEL=debug HOST=dev.appsmith.com craco start", + "prebuild": "if [ \"$REACT_APP_AIRGAP_ENABLED\" = \"true\" ]; then node download-assets.js; fi", "build": "./build.sh", + "build-airgap": "node download-assets.js && ./build.sh", "build-local": "craco --max-old-space-size=4096 build --config craco.build.config.js", "build-staging": "REACT_APP_ENVIRONMENT=STAGING craco --max-old-space-size=4096 build --config craco.build.config.js", "test": "CYPRESS_BASE_URL=https://dev.appsmith.com cypress/test.sh", @@ -327,4 +329,4 @@ "trim": "0.0.3", "webpack": "5.76.0" } -} \ No newline at end of file +} diff --git a/app/client/src/api/Api.ts b/app/client/src/api/Api.ts index 913e1abbf9d0..1e6094fc3d5b 100644 --- a/app/client/src/api/Api.ts +++ b/app/client/src/api/Api.ts @@ -6,6 +6,7 @@ import { apiFailureResponseInterceptor, apiRequestInterceptor, apiSuccessResponseInterceptor, + blockedApiRoutesForAirgapInterceptor, } from "api/ApiUtils"; //TODO(abhinav): Refactor this to make more composable. @@ -20,7 +21,14 @@ export const apiRequestConfig = { const axiosInstance: AxiosInstance = axios.create(); -axiosInstance.interceptors.request.use(apiRequestInterceptor); +const requestInterceptors = [ + blockedApiRoutesForAirgapInterceptor, + apiRequestInterceptor, +]; +requestInterceptors.forEach((interceptor) => { + axiosInstance.interceptors.request.use(interceptor as any); +}); + axiosInstance.interceptors.response.use( apiSuccessResponseInterceptor, apiFailureResponseInterceptor, diff --git a/app/client/src/api/ApiUtils.ts b/app/client/src/api/ApiUtils.ts index b7d92a70aeac..fea5301bceff 100644 --- a/app/client/src/api/ApiUtils.ts +++ b/app/client/src/api/ApiUtils.ts @@ -25,12 +25,26 @@ import AnalyticsUtil from "utils/AnalyticsUtil"; import { getAppsmithConfigs } from "ce/configs"; import * as Sentry from "@sentry/react"; import { CONTENT_TYPE_HEADER_KEY } from "constants/ApiEditorConstants/CommonApiConstants"; +import { isAirgapped } from "@appsmith/utils/airgapHelpers"; const executeActionRegex = /actions\/execute/; const timeoutErrorRegex = /timeout of (\d+)ms exceeded/; export const axiosConnectionAbortedCode = "ECONNABORTED"; const appsmithConfig = getAppsmithConfigs(); +export const BLOCKED_ROUTES = [ + "v1/app-templates", + "v1/marketplace", + "v1/datasources/mocks", + "v1/usage-pulse", + "v1/applications/releaseItems", + "v1/saas", +]; + +export const BLOCKED_ROUTES_REGEX = new RegExp( + `^(${BLOCKED_ROUTES.join("|")})($|/)`, +); + const makeExecuteActionResponse = (response: any): ActionExecutionResponse => ({ ...response.data, clientMeta: { @@ -44,6 +58,18 @@ const is404orAuthPath = () => { return /^\/404/.test(pathName) || /^\/user\/\w+/.test(pathName); }; +export const blockedApiRoutesForAirgapInterceptor = ( + 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 diff --git a/app/client/src/ce/pages/Home/LeftPaneBottomSection.tsx b/app/client/src/ce/pages/Home/LeftPaneBottomSection.tsx index 15fb6b097deb..235d2391d4f6 100644 --- a/app/client/src/ce/pages/Home/LeftPaneBottomSection.tsx +++ b/app/client/src/ce/pages/Home/LeftPaneBottomSection.tsx @@ -63,7 +63,6 @@ function LeftPaneBottomSection() { const howMuchTimeBefore = howMuchTimeBeforeText(appVersion.releaseDate); const user = useSelector(getCurrentUser); const tenantPermissions = useSelector(getTenantPermissions); - return ( <Wrapper> {showAdminSettings(user) && !isFetchingApplications && ( diff --git a/app/client/src/ce/pages/Upgrade/businessEdition/UpgradeToBEPage.tsx b/app/client/src/ce/pages/Upgrade/businessEdition/UpgradeToBEPage.tsx index b460430ee7a2..78e24aa95f9f 100644 --- a/app/client/src/ce/pages/Upgrade/businessEdition/UpgradeToBEPage.tsx +++ b/app/client/src/ce/pages/Upgrade/businessEdition/UpgradeToBEPage.tsx @@ -8,6 +8,7 @@ import { FooterComponent } from "../Footer"; import useOnUpgrade from "utils/hooks/useOnUpgrade"; import { Colors } from "constants/Colors"; import { ASSETS_CDN_URL } from "constants/ThirdPartyConstants"; +import { getAssetUrl } from "@appsmith/utils/airgapHelpers"; export const UpgradeToBEPageWrapper = styled.div` width: 100%; @@ -74,6 +75,12 @@ export const ContentWrapper = styled.div` overflow: hidden; `; +const BUSINESS_FEATURES_IMAGE = getAssetUrl( + `${ASSETS_CDN_URL}/business-features.svg`, +); + +const UPGRADE_BOX_IMAGE = getAssetUrl(`${ASSETS_CDN_URL}/upgrade-box.svg`); + export const UpgradeToBEPage = () => { const { onUpgrade } = useOnUpgrade({ logEventName: "BILLING_UPGRADE_ADMIN_SETTINGS", @@ -87,14 +94,16 @@ export const UpgradeToBEPage = () => { <ContentWrapper className="content-wrapper"> <LeftWrapper> <img - alt="text-content" - src={`${ASSETS_CDN_URL}/business-features.svg`} + alt="Upgrade to Business Edition" + loading="lazy" + src={BUSINESS_FEATURES_IMAGE} /> </LeftWrapper> <ImageContainer> <img alt="Upgrade to Business Edition" - src={`${ASSETS_CDN_URL}/upgrade-box.svg`} + loading="lazy" + src={UPGRADE_BOX_IMAGE} /> </ImageContainer> </ContentWrapper> diff --git a/app/client/src/ce/sagas/ApplicationSagas.tsx b/app/client/src/ce/sagas/ApplicationSagas.tsx index 7f8ecc490f82..df88575e50a7 100644 --- a/app/client/src/ce/sagas/ApplicationSagas.tsx +++ b/app/client/src/ce/sagas/ApplicationSagas.tsx @@ -112,6 +112,7 @@ import { ANONYMOUS_USERNAME } from "constants/userConstants"; import { getCurrentUser } from "selectors/usersSelectors"; import { ERROR_CODES } from "@appsmith/constants/ApiConstants"; import { safeCrashAppRequest } from "actions/errorActions"; +import { isAirgapped } from "@appsmith/utils/airgapHelpers"; export const getDefaultPageId = ( pages?: ApplicationPagePayload[], @@ -183,6 +184,7 @@ export function* publishApplicationSaga( } export function* getAllApplicationSaga() { + const isAirgappedInstance = isAirgapped(); try { const response: FetchUsersApplicationsWorkspacesResponse = yield call( ApplicationApi.getAllApplication, @@ -212,7 +214,9 @@ export function* getAllApplicationSaga() { payload: workspaceApplication, }); } - yield call(fetchReleases); + if (!isAirgappedInstance) { + yield call(fetchReleases); + } } catch (error) { yield put({ type: ReduxActionErrorTypes.FETCH_USER_APPLICATIONS_WORKSPACES_ERROR, diff --git a/app/client/src/ce/sagas/userSagas.tsx b/app/client/src/ce/sagas/userSagas.tsx index 9a5fad66c666..45a1d43e925e 100644 --- a/app/client/src/ce/sagas/userSagas.tsx +++ b/app/client/src/ce/sagas/userSagas.tsx @@ -71,6 +71,7 @@ import { import type { SegmentState } from "reducers/uiReducers/analyticsReducer"; import type FeatureFlags from "entities/FeatureFlags"; import UsagePulse from "usagePulse"; +import { isAirgapped } from "@appsmith/utils/airgapHelpers"; export function* createUserSaga( action: ReduxActionWithPromise<CreateUserRequest>, @@ -163,7 +164,7 @@ export function* getCurrentUserSaga() { export function* runUserSideEffectsSaga() { const currentUser: User = yield select(getCurrentUser); const { enableTelemetry } = currentUser; - + const isAirgappedInstance = isAirgapped(); if (enableTelemetry) { const promise = initializeAnalyticsAndTrackers(); @@ -182,12 +183,14 @@ export function* runUserSideEffectsSaga() { enableTelemetry && AnalyticsUtil.identifyUser(currentUser); } - // We need to stop and start tracking activity to ensure that the tracking from previous session is not carried forward - UsagePulse.stopTrackingActivity(); - UsagePulse.startTrackingActivity( - enableTelemetry && getAppsmithConfigs().segment.enabled, - currentUser?.isAnonymous ?? false, - ); + if (!isAirgappedInstance) { + // We need to stop and start tracking activity to ensure that the tracking from previous session is not carried forward + UsagePulse.stopTrackingActivity(); + UsagePulse.startTrackingActivity( + enableTelemetry && getAppsmithConfigs().segment.enabled, + currentUser?.isAnonymous ?? false, + ); + } yield put(initAppLevelSocketConnection()); yield put(initPageLevelSocketConnection()); diff --git a/app/client/src/ce/utils/airgapHelpers.tsx b/app/client/src/ce/utils/airgapHelpers.tsx new file mode 100644 index 000000000000..b3b5aba92552 --- /dev/null +++ b/app/client/src/ce/utils/airgapHelpers.tsx @@ -0,0 +1,7 @@ +export const getAssetUrl = (src = "") => { + return src; +}; + +export const isAirgapped = () => { + return false; +}; diff --git a/app/client/src/components/editorComponents/ActionNameEditor.tsx b/app/client/src/components/editorComponents/ActionNameEditor.tsx index b4ba98643b7c..644873695ef9 100644 --- a/app/client/src/components/editorComponents/ActionNameEditor.tsx +++ b/app/client/src/components/editorComponents/ActionNameEditor.tsx @@ -20,6 +20,7 @@ import { ACTION_NAME_PLACEHOLDER, createMessage, } from "@appsmith/constants/messages"; +import { getAssetUrl } from "@appsmith/utils/airgapHelpers"; const ApiNameWrapper = styled.div<{ page?: string }>` min-width: 50%; @@ -102,7 +103,7 @@ function ActionNameEditor(props: ActionNameEditorProps) { {currentPlugin && ( <ApiIconWrapper alt={currentPlugin.name} - src={currentPlugin.iconLocation} + src={getAssetUrl(currentPlugin?.iconLocation)} /> )} <EditableText diff --git a/app/client/src/components/editorComponents/ActionRightPane/SuggestedWidgets.tsx b/app/client/src/components/editorComponents/ActionRightPane/SuggestedWidgets.tsx index 24ab2831f9ca..6b20f4c7bd48 100644 --- a/app/client/src/components/editorComponents/ActionRightPane/SuggestedWidgets.tsx +++ b/app/client/src/components/editorComponents/ActionRightPane/SuggestedWidgets.tsx @@ -20,6 +20,8 @@ import type { SuggestedWidget } from "api/ActionAPI"; import { getDataTree } from "selectors/dataTreeSelectors"; import { getWidgets } from "sagas/selectors"; import { getNextWidgetName } from "sagas/WidgetOperationUtils"; +import { ASSETS_CDN_URL } from "constants/ThirdPartyConstants"; +import { getAssetUrl } from "@appsmith/utils/airgapHelpers"; const WidgetList = styled.div` ${getTypographyByKey("p1")} @@ -68,43 +70,43 @@ export const WIDGET_DATA_FIELD_MAP: Record<string, WidgetBindingInfo> = { label: "items", propertyName: "listData", widgetName: "List", - image: "https://assets.appsmith.com/widgetSuggestion/list.svg", + image: `${ASSETS_CDN_URL}/widgetSuggestion/list.svg`, }, TABLE_WIDGET: { label: "tabledata", propertyName: "tableData", widgetName: "Table", - image: "https://assets.appsmith.com/widgetSuggestion/table.svg", + image: `${ASSETS_CDN_URL}/widgetSuggestion/table.svg`, }, TABLE_WIDGET_V2: { label: "tabledata", propertyName: "tableData", widgetName: "Table", - image: "https://assets.appsmith.com/widgetSuggestion/table.svg", + image: `${ASSETS_CDN_URL}/widgetSuggestion/table.svg`, }, CHART_WIDGET: { label: "chart-series-data-control", propertyName: "chartData", widgetName: "Chart", - image: "https://assets.appsmith.com/widgetSuggestion/chart.svg", + image: `${ASSETS_CDN_URL}/widgetSuggestion/chart.svg`, }, SELECT_WIDGET: { label: "options", propertyName: "options", widgetName: "Select", - image: "https://assets.appsmith.com/widgetSuggestion/dropdown.svg", + image: `${ASSETS_CDN_URL}/widgetSuggestion/dropdown.svg`, }, TEXT_WIDGET: { label: "text", propertyName: "text", widgetName: "Text", - image: "https://assets.appsmith.com/widgetSuggestion/text.svg", + image: `${ASSETS_CDN_URL}/widgetSuggestion/text.svg`, }, INPUT_WIDGET_V2: { label: "text", propertyName: "defaultText", widgetName: "Input", - image: "https://assets.appsmith.com/widgetSuggestion/input.svg", + image: `${ASSETS_CDN_URL}/widgetSuggestion/input.svg`, }, }; @@ -240,7 +242,12 @@ function SuggestedWidgets(props: SuggestedWidgetProps) { > <Tooltip content={createMessage(SUGGESTED_WIDGET_TOOLTIP)}> <div className="image-wrapper"> - {widgetInfo.image && <img src={widgetInfo.image} />} + {widgetInfo.image && ( + <img + alt="widget-info-image" + src={getAssetUrl(widgetInfo.image)} + /> + )} <WidgetOverlay /> </div> </Tooltip> diff --git a/app/client/src/components/editorComponents/CodeEditor/generateQuickCommands.tsx b/app/client/src/components/editorComponents/CodeEditor/generateQuickCommands.tsx index 3cad30a2f53a..64c29744b506 100644 --- a/app/client/src/components/editorComponents/CodeEditor/generateQuickCommands.tsx +++ b/app/client/src/components/editorComponents/CodeEditor/generateQuickCommands.tsx @@ -12,6 +12,7 @@ import { ENTITY_TYPE } from "entities/DataTree/dataTreeFactory"; import { EntityIcon, JsFileIconV2 } from "pages/Editor/Explorer/ExplorerIcons"; import AddDatasourceIcon from "remixicon-react/AddBoxLineIcon"; import { Colors } from "constants/Colors"; +import { getAssetUrl } from "@appsmith/utils/airgapHelpers"; enum Shortcuts { PLUS = "PLUS", @@ -188,7 +189,9 @@ export const generateQuickCommands = ( } else if (pluginIdToImageLocation[data.data.pluginId]) { icon = ( <EntityIcon> - <img src={pluginIdToImageLocation[data.data.pluginId]} /> + <img + src={getAssetUrl(pluginIdToImageLocation[data.data.pluginId])} + /> </EntityIcon> ); } @@ -213,7 +216,9 @@ export const generateQuickCommands = ( render: (element: HTMLElement, self: any, data: any) => { const icon = ( <EntityIcon> - <img src={pluginIdToImageLocation[data.data.pluginId]} /> + <img + src={getAssetUrl(pluginIdToImageLocation[data.data.pluginId])} + /> </EntityIcon> ); ReactDOM.render( diff --git a/app/client/src/components/editorComponents/CodeEditor/index.tsx b/app/client/src/components/editorComponents/CodeEditor/index.tsx index 7a1641508ace..22a05f112bcd 100644 --- a/app/client/src/components/editorComponents/CodeEditor/index.tsx +++ b/app/client/src/components/editorComponents/CodeEditor/index.tsx @@ -134,6 +134,7 @@ import { PEEK_OVERLAY_DELAY, } from "./PeekOverlayPopup/PeekOverlayPopup"; import ConfigTreeActions from "utils/configTree"; +import { getAssetUrl } from "@appsmith/utils/airgapHelpers"; type ReduxStateProps = ReturnType<typeof mapStateToProps>; type ReduxDispatchProps = ReturnType<typeof mapDispatchToProps>; @@ -1319,7 +1320,7 @@ class CodeEditor extends Component<Props, State> { <img alt="img" className="leftImageStyles" - src={this.props.leftImage} + src={getAssetUrl(this.props.leftImage)} /> )} <div diff --git a/app/client/src/components/editorComponents/Debugger/ErrorLogs/components/LogEntityLink.tsx b/app/client/src/components/editorComponents/Debugger/ErrorLogs/components/LogEntityLink.tsx index 11be5b867746..7166e928c21b 100644 --- a/app/client/src/components/editorComponents/Debugger/ErrorLogs/components/LogEntityLink.tsx +++ b/app/client/src/components/editorComponents/Debugger/ErrorLogs/components/LogEntityLink.tsx @@ -14,6 +14,7 @@ import { ENTITY_TYPE } from "entities/AppsmithConsole"; import { PluginType } from "entities/Action"; import { getPlugins } from "selectors/entitiesSelector"; import EntityLink, { DebuggerLinkUI } from "../../EntityLink"; +import { getAssetUrl } from "@appsmith/utils/airgapHelpers"; const EntityLinkWrapper = styled.div` display: flex; @@ -65,7 +66,7 @@ export default function LogEntityLink(props: LogItemProps) { <EntityIcon height={"16px"} width={"16px"}> <img alt="entityIcon" - src={pluginGroups[props.iconId].iconLocation} + src={getAssetUrl(pluginGroups[props.iconId].iconLocation)} /> </EntityIcon> ); diff --git a/app/client/src/components/editorComponents/GlobalSearch/ResultsNotFound.tsx b/app/client/src/components/editorComponents/GlobalSearch/ResultsNotFound.tsx index 4efa635b9a75..c4174f6722fd 100644 --- a/app/client/src/components/editorComponents/GlobalSearch/ResultsNotFound.tsx +++ b/app/client/src/components/editorComponents/GlobalSearch/ResultsNotFound.tsx @@ -5,6 +5,7 @@ import { NO_SEARCH_DATA_TEXT } from "@appsmith/constants/messages"; import { getTypographyByKey } from "design-system-old"; import { ReactComponent as DiscordIcon } from "assets/icons/help/discord.svg"; import AnalyticsUtil from "utils/AnalyticsUtil"; +import { isAirgapped } from "@appsmith/utils/airgapHelpers"; const Container = styled.div` display: flex; @@ -43,24 +44,27 @@ const StyledDiscordIcon = styled(DiscordIcon)` `; function ResultsNotFound() { + const isAirgappedInstance = isAirgapped(); return ( <Container> <img alt="No data" src={NoSearchDataImage} /> <div className="no-data-title">{NO_SEARCH_DATA_TEXT()}</div> - <span className="discord"> - 🤖 Join our{" "} - <span - className="discord-link" - onClick={() => { - window.open("https://discord.gg/rBTTVJp", "_blank"); - AnalyticsUtil.logEvent("DISCORD_LINK_CLICK"); - }} - > - <StyledDiscordIcon color="red" height={22} width={24} /> - Discord Server - </span>{" "} - for more help. - </span> + {!isAirgappedInstance && ( + <span className="discord"> + 🤖 Join our{" "} + <span + className="discord-link" + onClick={() => { + window.open("https://discord.gg/rBTTVJp", "_blank"); + AnalyticsUtil.logEvent("DISCORD_LINK_CLICK"); + }} + > + <StyledDiscordIcon color="red" height={22} width={24} /> + Discord Server + </span>{" "} + for more help. + </span> + )} </Container> ); } diff --git a/app/client/src/components/editorComponents/GlobalSearch/parseDocumentationContent.ts b/app/client/src/components/editorComponents/GlobalSearch/parseDocumentationContent.ts index 9deee4928f2f..995ce6c17010 100644 --- a/app/client/src/components/editorComponents/GlobalSearch/parseDocumentationContent.ts +++ b/app/client/src/components/editorComponents/GlobalSearch/parseDocumentationContent.ts @@ -21,7 +21,7 @@ export const htmlToElement = (html: string) => { * gitbook plugin tags */ const strip = (text: string) => text.replace(/{% .*?%}/gm, ""); - +// TODO: YT iframe airgap checks const getYtIframe = (videoId: string) => { return `<iframe width="100%" height="280" src="https://www.youtube.com/embed/${videoId}" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>`; }; diff --git a/app/client/src/constants/ImagesURL.ts b/app/client/src/constants/ImagesURL.ts index f889df4b9157..7eec9419d6b6 100644 --- a/app/client/src/constants/ImagesURL.ts +++ b/app/client/src/constants/ImagesURL.ts @@ -1,5 +1,7 @@ import { ASSETS_CDN_URL } from "./ThirdPartyConstants"; +import { getAssetUrl } from "@appsmith/utils/airgapHelpers"; + export const getInfoThumbnail = () => - `${ASSETS_CDN_URL}/crud/crud_info_thumbnail.png`; + getAssetUrl(`${ASSETS_CDN_URL}/crud/crud_info_thumbnail.png`); export const getInfoImage = (): string => - `${ASSETS_CDN_URL}/crud/working-flow-chart.png`; + getAssetUrl(`${ASSETS_CDN_URL}/crud/working-flow-chart.png`); diff --git a/app/client/src/constants/serverAssets.ts b/app/client/src/constants/serverAssets.ts new file mode 100644 index 000000000000..af14653f1292 --- /dev/null +++ b/app/client/src/constants/serverAssets.ts @@ -0,0 +1,39 @@ +import { ASSETS_CDN_URL } from "./ThirdPartyConstants"; + +/* Since the script download-assets.js actually needs the url to download the assets, we need the urls we get from server response at build time. */ + +export const postgresqlIcon = `${ASSETS_CDN_URL}/logo/postgresql.svg`; +export const mongodbIcon = `${ASSETS_CDN_URL}/logo/mongodb.svg`; +export const restApiIcon = `${ASSETS_CDN_URL}/RestAPI.png`; +export const mysqlIcon = `${ASSETS_CDN_URL}/logo/mysql.svg`; +export const elasticIcon = `${ASSETS_CDN_URL}/logo/elastic.svg`; +export const dynamoDBIcon = `${ASSETS_CDN_URL}/logo/aws-dynamodb.svg`; +export const redisIcon = `${ASSETS_CDN_URL}/logo/redis.svg`; +export const mssqlIcon = `${ASSETS_CDN_URL}/logo/mssql.svg`; +export const s3Icon = `${ASSETS_CDN_URL}/logo/aws-s3.svg`; +export const googleSheetsIcon = `${ASSETS_CDN_URL}/GoogleSheets.svg`; +export const snowflakeIcon = `${ASSETS_CDN_URL}/logo/snowflake.svg`; +export const arangodbIcon = `${ASSETS_CDN_URL}/logo/arangodb.svg`; +export const jsFileIcon = `${ASSETS_CDN_URL}/JSFile.svg`; +export const smtpIcon = `${ASSETS_CDN_URL}/smtp-icon.svg`; +export const graphqlIcon = `${ASSETS_CDN_URL}/logo/graphql.svg`; +export const oracleIcon = `${ASSETS_CDN_URL}/oracle-db.jpg`; + +// Unsupported plugin assets +export const openaiLogo = `${ASSETS_CDN_URL}/integrations/openai-logo-png.jpg`; +export const firestoreIcon = `${ASSETS_CDN_URL}/logo/firestore.svg`; +export const redshiftIcon = `${ASSETS_CDN_URL}/logo/aws-redshift.svg`; +export const hubspotIcon = `${ASSETS_CDN_URL}/integrations/HubSpot.png`; +export const airtableIcon = `${ASSETS_CDN_URL}/integrations/airtable.svg`; +export const twilioIcon = `${ASSETS_CDN_URL}/integrations/twilio_24.png`; +export const sendgridTwilioIcon = `${ASSETS_CDN_URL}/integrations/sendgrid_twilio.jpg`; +export const huggingFaceLogo = `${ASSETS_CDN_URL}/integrations/Hugging-Face-Logo.png`; +export const dropboxIcon = `${ASSETS_CDN_URL}/integrations/dropbox.png`; +export const figmaIcon = `${ASSETS_CDN_URL}/integrations/Figma-1-logo.png`; + +// Assets for CRUD page generator +export const sqlWorkflowIcon = `${ASSETS_CDN_URL}/crud/workflow_sql.svg`; +export const s3WorkflowIcon = `${ASSETS_CDN_URL}/crud/workflow_s3.svg`; + +// Assets from tenant configuration +export const appsmithFavicon = `${ASSETS_CDN_URL}/appsmith-favicon-orange.ico`; diff --git a/app/client/src/ee/utils/airgapHelpers.tsx b/app/client/src/ee/utils/airgapHelpers.tsx new file mode 100644 index 000000000000..a552fe593e4f --- /dev/null +++ b/app/client/src/ee/utils/airgapHelpers.tsx @@ -0,0 +1 @@ +export * from "ce/utils/airgapHelpers"; diff --git a/app/client/src/pages/Applications/ProductUpdatesModal/index.tsx b/app/client/src/pages/Applications/ProductUpdatesModal/index.tsx index 27c4a054cc55..25bbce9326fd 100644 --- a/app/client/src/pages/Applications/ProductUpdatesModal/index.tsx +++ b/app/client/src/pages/Applications/ProductUpdatesModal/index.tsx @@ -17,6 +17,7 @@ import type { Release } from "./ReleaseComponent"; import ReleaseComponent from "./ReleaseComponent"; import { DialogComponent as Dialog, ScrollIndicator } from "design-system-old"; import { ReduxActionTypes } from "@appsmith/constants/ReduxActionConstants"; +import { isAirgapped } from "@appsmith/utils/airgapHelpers"; const StyledDialog = styled(Dialog)` .bp3-dialog-body { @@ -48,16 +49,21 @@ function ProductUpdatesModal(props: ProductUpdatesModalProps) { const { newReleasesCount, releaseItems } = useSelector( (state: AppState) => state.ui.releases, ); + const isAirgappedInstance = isAirgapped(); const containerRef = useRef<HTMLDivElement>(null); const dispatch = useDispatch(); useEffect(() => { - if (props.hideTrigger && releaseItems.length === 0) { + if ( + props.hideTrigger && + releaseItems.length === 0 && + !isAirgappedInstance + ) { dispatch({ type: ReduxActionTypes.FETCH_RELEASES, }); } - }, []); + }, [isAirgappedInstance]); const onOpening = useCallback(async () => { setIsOpen(true); diff --git a/app/client/src/pages/Editor/APIEditor/ProviderTemplates.tsx b/app/client/src/pages/Editor/APIEditor/ProviderTemplates.tsx index 777d3c83b621..60c72a9ceba3 100644 --- a/app/client/src/pages/Editor/APIEditor/ProviderTemplates.tsx +++ b/app/client/src/pages/Editor/APIEditor/ProviderTemplates.tsx @@ -33,6 +33,7 @@ import AnalyticsUtil from "utils/AnalyticsUtil"; import { getAppCardColorPalette } from "selectors/themeSelectors"; import { getCurrentApplicationId } from "selectors/editorSelectors"; import { integrationEditorURL } from "RouteBuilder"; +import { getAssetUrl } from "@appsmith/utils/airgapHelpers"; const TEMPLATES_TOP_SECTION_HEIGHT = "83px"; @@ -318,13 +319,12 @@ class ProviderTemplates extends React.Component<ProviderTemplatesProps> { {" Back"} </span> <br /> - <ProviderInfo> {providerDetails.imageUrl ? ( <img alt="provider" className="providerImage" - src={providerDetails.imageUrl} + src={getAssetUrl(providerDetails.imageUrl)} /> ) : ( <div> diff --git a/app/client/src/pages/Editor/DataSourceEditor/DBForm.tsx b/app/client/src/pages/Editor/DataSourceEditor/DBForm.tsx index 6a19d5cc3126..2a01f0e40e28 100644 --- a/app/client/src/pages/Editor/DataSourceEditor/DBForm.tsx +++ b/app/client/src/pages/Editor/DataSourceEditor/DBForm.tsx @@ -29,6 +29,7 @@ import DatasourceAuth from "pages/common/datasourceAuth"; import { getDatasourceFormButtonConfig } from "selectors/entitiesSelector"; import { hasManageDatasourcePermission } from "@appsmith/utils/permissionHelpers"; import { TEMP_DATASOURCE_ID } from "constants/Datasource"; +import { getAssetUrl } from "@appsmith/utils/airgapHelpers"; const { cloudHosting } = getAppsmithConfigs(); @@ -115,7 +116,6 @@ class DatasourceDBEditor extends JSONtoForm<Props> { } = this.props; const createFlow = datasourceId === TEMP_DATASOURCE_ID; - return ( <form onSubmit={(e) => { @@ -125,7 +125,10 @@ class DatasourceDBEditor extends JSONtoForm<Props> { {!this.props.hiddenHeader && ( <Header> <FormTitleContainer> - <PluginImage alt="Datasource" src={this.props.pluginImage} /> + <PluginImage + alt="Datasource" + src={getAssetUrl(this.props.pluginImage)} + /> <FormTitle disabled={!createFlow && !canManageDatasource} focusOnMount={this.props.isNewDatasource} diff --git a/app/client/src/pages/Editor/DataSourceEditor/RestAPIDatasourceForm.tsx b/app/client/src/pages/Editor/DataSourceEditor/RestAPIDatasourceForm.tsx index 3e3d1f8477cc..13cdf6495959 100644 --- a/app/client/src/pages/Editor/DataSourceEditor/RestAPIDatasourceForm.tsx +++ b/app/client/src/pages/Editor/DataSourceEditor/RestAPIDatasourceForm.tsx @@ -59,6 +59,7 @@ import { TEMP_DATASOURCE_ID } from "constants/Datasource"; import { hasManageDatasourcePermission } from "@appsmith/utils/permissionHelpers"; import { getPlugin } from "../../../selectors/entitiesSelector"; import type { Plugin } from "api/PluginApi"; +import { getAssetUrl } from "@appsmith/utils/airgapHelpers"; interface DatasourceRestApiEditorProps { initializeReplayEntity: (id: string, data: any) => void; @@ -379,7 +380,7 @@ class DatasourceRestAPIEditor extends React.Component< return !hiddenHeader ? ( <Header> <FormTitleContainer> - <PluginImage alt="Datasource" src={pluginImage} /> + <PluginImage alt="Datasource" src={getAssetUrl(pluginImage)} /> <FormTitle disabled={!createMode && !canManageDatasource} focusOnMount={isNewDatasource} diff --git a/app/client/src/pages/Editor/Explorer/Actions/helpers.tsx b/app/client/src/pages/Editor/Explorer/Actions/helpers.tsx index c39e5086fa72..adfb58a9bf69 100644 --- a/app/client/src/pages/Editor/Explorer/Actions/helpers.tsx +++ b/app/client/src/pages/Editor/Explorer/Actions/helpers.tsx @@ -15,6 +15,7 @@ import { queryEditorIdURL, saasEditorApiIdURL, } from "RouteBuilder"; +import { getAssetUrl } from "@appsmith/utils/airgapHelpers"; // TODO [new_urls] update would break for existing paths // using a common todo, this needs to be fixed @@ -79,7 +80,7 @@ export const ACTION_PLUGIN_MAP: Array<ActionGroupConfig | undefined> = [ if (plugin && plugin.iconLocation) return ( <EntityIcon> - <img alt="entityIcon" src={plugin.iconLocation} /> + <img alt="entityIcon" src={getAssetUrl(plugin.iconLocation)} /> </EntityIcon> ); else if (plugin && plugin.type === PluginType.DB) return dbQueryIcon; diff --git a/app/client/src/pages/Editor/Explorer/ExplorerIcons.tsx b/app/client/src/pages/Editor/Explorer/ExplorerIcons.tsx index 280ccc7095c4..025727302235 100644 --- a/app/client/src/pages/Editor/Explorer/ExplorerIcons.tsx +++ b/app/client/src/pages/Editor/Explorer/ExplorerIcons.tsx @@ -13,6 +13,7 @@ import { ControlIcons } from "icons/ControlIcons"; import { ReactComponent as ApiIcon } from "assets/icons/menu/api-colored.svg"; import { ReactComponent as CurlIcon } from "assets/images/Curl-logo.svg"; import { ReactComponent as GraphqlIcon } from "assets/images/Graphql-logo.svg"; +import { getAssetUrl } from "@appsmith/utils/airgapHelpers"; export const ENTITY_ICON_SIZE = 16; @@ -159,7 +160,12 @@ const PluginIcon = styled.img` export const getPluginIcon = (plugin?: Plugin) => { if (plugin && plugin.iconLocation) { - return <PluginIcon alt={plugin.packageName} src={plugin.iconLocation} />; + return ( + <PluginIcon + alt={plugin.packageName} + src={getAssetUrl(plugin.iconLocation)} + /> + ); } return <PluginIcon alt="plugin-placeholder" src={ImageAlt} />; }; diff --git a/app/client/src/pages/Editor/Explorer/Libraries/index.tsx b/app/client/src/pages/Editor/Explorer/Libraries/index.tsx index a45a4c1a9565..22d8fff46dd7 100644 --- a/app/client/src/pages/Editor/Explorer/Libraries/index.tsx +++ b/app/client/src/pages/Editor/Explorer/Libraries/index.tsx @@ -36,6 +36,7 @@ import { getPagePermissions } from "selectors/editorSelectors"; import { hasCreateActionPermission } from "@appsmith/utils/permissionHelpers"; import recommendedLibraries from "./recommendedLibraries"; import { useTransition, animated } from "react-spring"; +import { isAirgapped } from "@appsmith/utils/airgapHelpers"; const docsURLMap = recommendedLibraries.reduce((acc, lib) => { acc[lib.url] = lib.docsURL; @@ -305,6 +306,8 @@ function JSDependencies() { const canCreateActions = hasCreateActionPermission(pagePermissions); + const isAirgappedInstance = isAirgapped(); + const openInstaller = useCallback(() => { dispatch(toggleInstaller(true)); }, []); @@ -334,7 +337,7 @@ function JSDependencies() { isDefaultExpanded={isOpen} isSticky name="Libraries" - showAddButton={canCreateActions} + showAddButton={canCreateActions && !isAirgappedInstance} step={0} > {dependencyList} diff --git a/app/client/src/pages/Editor/Explorer/Pages/AddPageContextMenu.tsx b/app/client/src/pages/Editor/Explorer/Pages/AddPageContextMenu.tsx index 8c06428ffd1f..496e33354350 100644 --- a/app/client/src/pages/Editor/Explorer/Pages/AddPageContextMenu.tsx +++ b/app/client/src/pages/Editor/Explorer/Pages/AddPageContextMenu.tsx @@ -34,6 +34,7 @@ import HotKeys from "../Files/SubmenuHotkeys"; import { selectFeatureFlags } from "selectors/usersSelectors"; import AnalyticsUtil from "utils/AnalyticsUtil"; import { getIsAutoLayout } from "selectors/editorSelectors"; +import { isAirgapped } from "@appsmith/utils/airgapHelpers"; const MenuItem = styled.div<{ active: boolean }>` display: flex; @@ -77,6 +78,7 @@ function AddPageContextMenu({ const [activeItemIdx, setActiveItemIdx] = useState(0); const featureFlags = useSelector(selectFeatureFlags); const isAutoLayout = useSelector(getIsAutoLayout); + const isAirgappedInstance = isAirgapped(); const menuRef = useCallback( (node) => { @@ -105,7 +107,11 @@ function AddPageContextMenu({ }, ]; - if (featureFlags.TEMPLATES_PHASE_2 && !isAutoLayout) { + if ( + featureFlags.TEMPLATES_PHASE_2 && + !isAutoLayout && + !isAirgappedInstance + ) { items.push({ title: createMessage(ADD_PAGE_FROM_TEMPLATE), icon: Layout2LineIcon, diff --git a/app/client/src/pages/Editor/FirstTimeUserOnboarding/Checklist.tsx b/app/client/src/pages/Editor/FirstTimeUserOnboarding/Checklist.tsx index 98eef2628e05..b0973ba066e8 100644 --- a/app/client/src/pages/Editor/FirstTimeUserOnboarding/Checklist.tsx +++ b/app/client/src/pages/Editor/FirstTimeUserOnboarding/Checklist.tsx @@ -50,6 +50,8 @@ import type { ActionDataState } from "reducers/entityReducers/actionsReducer"; import type { CanvasWidgetsReduxState } from "reducers/entityReducers/canvasWidgetsReducer"; import { triggerWelcomeTour } from "./Utils"; import { builderURL, integrationEditorURL } from "RouteBuilder"; +import { ASSETS_CDN_URL } from "constants/ThirdPartyConstants"; +import { getAssetUrl } from "@appsmith/utils/airgapHelpers"; const Wrapper = styled.div` padding: ${(props) => props.theme.spaces[7]}px 55px; @@ -559,7 +561,10 @@ export default function OnboardingChecklist() { className="flex" onClick={() => triggerWelcomeTour(dispatch)} > - <StyledImg src="https://assets.appsmith.com/Rocket.png" /> + <StyledImg + alt="rocket" + src={getAssetUrl(`${ASSETS_CDN_URL}/Rocket.png`)} + /> <Text style={{ lineHeight: "14px" }} type={TextType.P1}> {createMessage(ONBOARDING_CHECKLIST_FOOTER)} </Text> diff --git a/app/client/src/pages/Editor/FirstTimeUserOnboarding/IntroductionModal.tsx b/app/client/src/pages/Editor/FirstTimeUserOnboarding/IntroductionModal.tsx index 65b34474c910..cb07a629d1d0 100644 --- a/app/client/src/pages/Editor/FirstTimeUserOnboarding/IntroductionModal.tsx +++ b/app/client/src/pages/Editor/FirstTimeUserOnboarding/IntroductionModal.tsx @@ -22,6 +22,7 @@ import styled from "styled-components"; import AnalyticsUtil from "utils/AnalyticsUtil"; import { triggerWelcomeTour } from "./Utils"; import { ASSETS_CDN_URL } from "constants/ThirdPartyConstants"; +import { getAssetUrl } from "@appsmith/utils/airgapHelpers"; const Wrapper = styled.div` display: flex; @@ -170,7 +171,10 @@ export default function IntroductionModal({ close }: IntroductionModalProps) { </ModalContent> </ModalContentTextWrapper> <StyledImgWrapper> - <StyledImg src={getConnectDataImg()} /> + <StyledImg + alt="connect-data-image" + src={getAssetUrl(getConnectDataImg())} + /> </StyledImgWrapper> </ModalContentRow> <ModalContentRow border> @@ -186,7 +190,10 @@ export default function IntroductionModal({ close }: IntroductionModalProps) { </ModalContent> </ModalContentTextWrapper> <StyledImgWrapper> - <StyledImg src={getDragAndDropImg()} /> + <StyledImg + alt="drag-and-drop-img" + src={getAssetUrl(getDragAndDropImg())} + /> </StyledImgWrapper> </ModalContentRow> <ModalContentRow className="border-b-0"> @@ -202,7 +209,10 @@ export default function IntroductionModal({ close }: IntroductionModalProps) { </ModalContent> </ModalContentTextWrapper> <StyledImgWrapper> - <StyledImg src={getPublishAppsImg()} /> + <StyledImg + alt="publish-image" + src={getAssetUrl(getPublishAppsImg())} + /> </StyledImgWrapper> </ModalContentRow> </ModalContentWrapper> diff --git a/app/client/src/pages/Editor/FirstTimeUserOnboarding/Tasks.tsx b/app/client/src/pages/Editor/FirstTimeUserOnboarding/Tasks.tsx index c580f1fbd9b5..e9be666bf45f 100644 --- a/app/client/src/pages/Editor/FirstTimeUserOnboarding/Tasks.tsx +++ b/app/client/src/pages/Editor/FirstTimeUserOnboarding/Tasks.tsx @@ -39,6 +39,7 @@ import AnalyticsUtil from "utils/AnalyticsUtil"; import history from "utils/history"; import IntroductionModal from "./IntroductionModal"; import { integrationEditorURL } from "RouteBuilder"; +import { getAssetUrl } from "@appsmith/utils/airgapHelpers"; const Wrapper = styled.div` width: 100%; @@ -110,7 +111,7 @@ export default function OnboardingTasks() { content = ( <CenteredContainer> <TaskImageContainer> - <TaskImage src={getOnboardingDatasourceImg()} /> + <TaskImage src={getAssetUrl(getOnboardingDatasourceImg())} /> </TaskImageContainer> <TaskHeader className="t--tasks-datasource-header" @@ -164,7 +165,7 @@ export default function OnboardingTasks() { content = ( <CenteredContainer> <TaskImageContainer> - <TaskImage src={getOnboardingQueryImg()} /> + <TaskImage src={getAssetUrl(getOnboardingQueryImg())} /> </TaskImageContainer> <TaskHeader className="t--tasks-datasource-header" @@ -215,7 +216,7 @@ export default function OnboardingTasks() { content = ( <CenteredContainer> <TaskImageContainer> - <TaskImage src={getOnboardingWidgetImg()} /> + <TaskImage src={getAssetUrl(getOnboardingWidgetImg())} /> </TaskImageContainer> <TaskHeader className="t--tasks-datasource-header" diff --git a/app/client/src/pages/Editor/GeneratePage/components/DataSourceOption.tsx b/app/client/src/pages/Editor/GeneratePage/components/DataSourceOption.tsx index a64af76560fe..9552d480a982 100644 --- a/app/client/src/pages/Editor/GeneratePage/components/DataSourceOption.tsx +++ b/app/client/src/pages/Editor/GeneratePage/components/DataSourceOption.tsx @@ -10,6 +10,7 @@ import type { import { Classes, Text, TextType, TooltipComponent } from "design-system-old"; import { FormIcons } from "icons/FormIcons"; import _ from "lodash"; +import { getAssetUrl } from "@appsmith/utils/airgapHelpers"; // ---------- Helpers and constants ---------- @@ -93,7 +94,6 @@ interface DataSourceOptionType extends RenderDropdownOptionType { cypressSelector: string; optionWidth: string; } - function DataSourceOption({ cypressSelector, extraProps, @@ -162,9 +162,9 @@ function DataSourceOption({ <DatasourceImage alt="" className="dataSourceImage" - src={ - pluginImages[(dropdownOption as DropdownOption).data.pluginId] - } + src={getAssetUrl( + pluginImages[(dropdownOption as DropdownOption).data.pluginId], + )} /> </ImageWrapper> ) : null} diff --git a/app/client/src/pages/Editor/GuidedTour/constants.tsx b/app/client/src/pages/Editor/GuidedTour/constants.tsx index 9a914e0a3ae6..db3f28807cb9 100644 --- a/app/client/src/pages/Editor/GuidedTour/constants.tsx +++ b/app/client/src/pages/Editor/GuidedTour/constants.tsx @@ -38,6 +38,8 @@ import { STEP_THREE_TITLE, STEP_TWO_TITLE, } from "@appsmith/constants/messages"; +import { ASSETS_CDN_URL } from "constants/ThirdPartyConstants"; +import { getAssetUrl } from "@appsmith/utils/airgapHelpers"; export const Classes = { GUIDED_TOUR_BORDER: "guided-tour-border", @@ -111,7 +113,9 @@ export const onboardingContainerBlueprint = { }, props: { imageShape: "RECTANGLE", - defaultImage: "https://assets.appsmith.com/widgets/default.png", + defaultImage: getAssetUrl( + `${ASSETS_CDN_URL}/widgets/default.png`, + ), objectFit: "contain", image: "{{CustomersTable.selectedRow.image}}", dynamicBindingPathList: [{ key: "image" }], diff --git a/app/client/src/pages/Editor/IntegrationEditor/DatasourceCard.tsx b/app/client/src/pages/Editor/IntegrationEditor/DatasourceCard.tsx index 4397f38d4c48..c89cc3043ac2 100644 --- a/app/client/src/pages/Editor/IntegrationEditor/DatasourceCard.tsx +++ b/app/client/src/pages/Editor/IntegrationEditor/DatasourceCard.tsx @@ -51,6 +51,7 @@ import { hasDeleteDatasourcePermission, hasManageDatasourcePermission, } from "@appsmith/utils/permissionHelpers"; +import { getAssetUrl } from "@appsmith/utils/airgapHelpers"; const Wrapper = styled.div` padding: 15px; @@ -304,7 +305,7 @@ function DatasourceCard(props: DatasourceCardProps) { <DatasourceImage alt="Datasource" data-testid="active-datasource-image" - src={pluginImages[datasource.pluginId]} + src={getAssetUrl(pluginImages[datasource.pluginId])} /> </DatasourceIconWrapper> <DatasourceName data-testid="active-datasource-name"> diff --git a/app/client/src/pages/Editor/IntegrationEditor/DatasourceHome.tsx b/app/client/src/pages/Editor/IntegrationEditor/DatasourceHome.tsx index 3c16d8344166..44eb1713a4a1 100644 --- a/app/client/src/pages/Editor/IntegrationEditor/DatasourceHome.tsx +++ b/app/client/src/pages/Editor/IntegrationEditor/DatasourceHome.tsx @@ -18,6 +18,7 @@ import { getQueryParams } from "utils/URLUtils"; import { getGenerateCRUDEnabledPluginMap } from "selectors/entitiesSelector"; import type { GenerateCRUDEnabledPluginMap } from "api/PluginApi"; import { getIsGeneratePageInitiator } from "utils/GenerateCrudUtil"; +import { getAssetUrl } from "@appsmith/utils/airgapHelpers"; // This function remove the given key from queryParams and return string const removeQueryParams = (paramKeysToRemove: Array<string>) => { @@ -213,7 +214,7 @@ class DatasourceHomeScreen extends React.Component<Props> { alt="Datasource" className="dataSourceImage" data-testid="database-datasource-image" - src={pluginImages[plugin.id]} + src={getAssetUrl(pluginImages[plugin.id])} /> </div> <p className="t--plugin-name textBtn">{plugin.name}</p> diff --git a/app/client/src/pages/Editor/IntegrationEditor/MockDataSources.tsx b/app/client/src/pages/Editor/IntegrationEditor/MockDataSources.tsx index 89be58aecf63..a817dca548c3 100644 --- a/app/client/src/pages/Editor/IntegrationEditor/MockDataSources.tsx +++ b/app/client/src/pages/Editor/IntegrationEditor/MockDataSources.tsx @@ -9,6 +9,7 @@ import { getCurrentWorkspaceId } from "@appsmith/selectors/workspaceSelectors"; import { getQueryParams } from "utils/URLUtils"; import type { AppState } from "@appsmith/reducers"; import AnalyticsUtil from "utils/AnalyticsUtil"; +import { getAssetUrl } from "@appsmith/utils/airgapHelpers"; const MockDataSourceWrapper = styled.div` overflow: auto; @@ -146,7 +147,7 @@ function MockDatasourceCard(props: MockDatasourceCardProps) { <DatasourceImage alt="Datasource" data-testid="mock-datasource-image" - src={pluginImages[currentPlugin.id]} + src={getAssetUrl(pluginImages[currentPlugin.id])} /> </DatasourceIconWrapper> <DatasourceNameWrapper data-testid="mock-datasource-name-wrapper"> diff --git a/app/client/src/pages/Editor/IntegrationEditor/mockData/index.ts b/app/client/src/pages/Editor/IntegrationEditor/mockData/index.ts index f76f6a0b1633..c3e7f0cad7a8 100644 --- a/app/client/src/pages/Editor/IntegrationEditor/mockData/index.ts +++ b/app/client/src/pages/Editor/IntegrationEditor/mockData/index.ts @@ -1,3 +1,5 @@ +import { getAssetUrl } from "@appsmith/utils/airgapHelpers"; +import { ASSETS_CDN_URL } from "constants/ThirdPartyConstants"; import { PluginPackageName } from "entities/Action"; export const mockPlugins = [ @@ -7,7 +9,7 @@ export const mockPlugins = [ name: "PostgreSQL", type: "DB", packageName: PluginPackageName.POSTGRES, - iconLocation: "https://assets.appsmith.com/logo/postgresql.svg", + iconLocation: getAssetUrl(`${ASSETS_CDN_URL}/logo/postgresql.svg`), documentationLink: "https://docs.appsmith.com/v/v1.2.1/datasource-reference/querying-postgres", responseType: "TABLE", @@ -25,7 +27,7 @@ export const mockPlugins = [ name: "REST API", type: "API", packageName: PluginPackageName.REST_API, - iconLocation: "https://assets.appsmith.com/RestAPI.png", + iconLocation: getAssetUrl(`${ASSETS_CDN_URL}/RestAPI.png`), uiComponent: "ApiEditorForm", datasourceComponent: "RestAPIDatasourceForm", defaultInstall: true, diff --git a/app/client/src/pages/Editor/QueryEditor/EditorJSONtoForm.tsx b/app/client/src/pages/Editor/QueryEditor/EditorJSONtoForm.tsx index 93444a08a926..d8c320745733 100644 --- a/app/client/src/pages/Editor/QueryEditor/EditorJSONtoForm.tsx +++ b/app/client/src/pages/Editor/QueryEditor/EditorJSONtoForm.tsx @@ -128,6 +128,7 @@ import { } from "actions/queryPaneActions"; import { ActionExecutionResizerHeight } from "pages/Editor/APIEditor/constants"; import { getCurrentAppWorkspace } from "@appsmith/selectors/workspaceSelectors"; +import { getAssetUrl } from "@appsmith/utils/airgapHelpers"; const QueryFormContainer = styled.form` flex: 1; @@ -582,7 +583,7 @@ export function EditorJSONtoForm(props: Props) { <img alt="Datasource" className="plugin-image" - src={props.data.image} + src={getAssetUrl(props.data.image)} /> <div className="selected-value">{props.children}</div> </Container> @@ -597,7 +598,7 @@ export function EditorJSONtoForm(props: Props) { <img alt="Datasource" className="plugin-image" - src={props.data.image} + src={getAssetUrl(props.data.image)} /> <div style={{ marginLeft: "6px" }}>{props.children}</div> </Container> diff --git a/app/client/src/pages/Editor/SaaSEditor/DatasourceCard.tsx b/app/client/src/pages/Editor/SaaSEditor/DatasourceCard.tsx index 82e5bc148835..453fe096d61a 100644 --- a/app/client/src/pages/Editor/SaaSEditor/DatasourceCard.tsx +++ b/app/client/src/pages/Editor/SaaSEditor/DatasourceCard.tsx @@ -17,6 +17,7 @@ import history from "utils/history"; import RenderDatasourceInformation from "pages/Editor/DataSourceEditor/DatasourceSection"; import { BaseButton } from "components/designSystems/appsmith/BaseButton"; import { saasEditorDatasourceIdURL } from "RouteBuilder"; +import { getAssetUrl } from "@appsmith/utils/airgapHelpers"; const Wrapper = styled.div` border: 2px solid #d6d6d6; @@ -124,7 +125,7 @@ function DatasourceCard(props: DatasourceCardProps) { <DatasourceImage alt="Datasource" className="dataSourceImage" - src={pluginImages[datasource.pluginId]} + src={getAssetUrl(pluginImages[datasource.pluginId])} /> <DatasourceName>{datasource.name}</DatasourceName> </DatasourceNameWrapper> diff --git a/app/client/src/pages/Editor/SaaSEditor/DatasourceForm.tsx b/app/client/src/pages/Editor/SaaSEditor/DatasourceForm.tsx index 064868fa64f5..294c3ebb2e4e 100644 --- a/app/client/src/pages/Editor/SaaSEditor/DatasourceForm.tsx +++ b/app/client/src/pages/Editor/SaaSEditor/DatasourceForm.tsx @@ -63,6 +63,7 @@ import { } from "ce/constants/messages"; import { selectFeatureFlags } from "selectors/usersSelectors"; import { getDatasourceErrorMessage } from "./errorUtils"; +import { getAssetUrl } from "@appsmith/utils/airgapHelpers"; interface StateProps extends JSONtoFormProps { applicationId: string; @@ -271,7 +272,7 @@ class DatasourceSaaSEditor extends JSONtoForm<Props, State> { const viewMode = !hiddenHeader && new URLSearchParams(params).get("viewMode"); - /* + /* TODO: This flag will be removed once the multiple environment is merged to avoid design inconsistency between different datasources. Search for: GoogleSheetPluginFlag to check for all the google sheet conditional logic throughout the code. */ @@ -300,7 +301,10 @@ class DatasourceSaaSEditor extends JSONtoForm<Props, State> { {!hiddenHeader && ( <Header> <FormTitleContainer> - <PluginImage alt="Datasource" src={this.props.pluginImage} /> + <PluginImage + alt="Datasource" + src={getAssetUrl(this.props.pluginImage)} + /> <FormTitle disabled={!createFlow && !canManageDatasource} focusOnMount={this.props.isNewDatasource} diff --git a/app/client/src/pages/Editor/gitSync/components/DatasourceListItem.tsx b/app/client/src/pages/Editor/gitSync/components/DatasourceListItem.tsx index 5b8011028436..06db6bfd6233 100644 --- a/app/client/src/pages/Editor/gitSync/components/DatasourceListItem.tsx +++ b/app/client/src/pages/Editor/gitSync/components/DatasourceListItem.tsx @@ -4,6 +4,7 @@ import type { Datasource } from "entities/Datasource"; import { PluginImage } from "pages/Editor/DataSourceEditor/JSONtoForm"; import React from "react"; import styled from "styled-components"; +import { getAssetUrl } from "@appsmith/utils/airgapHelpers"; const ListItem = styled.div<{ disabled?: boolean }>` display: flex; @@ -43,7 +44,6 @@ const DsTitle = styled.div` margin-left: ${(props) => props.theme.spaces[2]}px; } `; - function ListItemWrapper(props: { ds: Datasource; selected?: boolean; @@ -59,7 +59,7 @@ function ListItemWrapper(props: { className={`t--ds-list ${selected ? "active" : ""}`} onClick={() => onClick(ds)} > - <PluginImage alt="Datasource" src={plugin.image} /> + <PluginImage alt="Datasource" src={getAssetUrl(plugin.image)} /> <ListLabels> <DsTitle> <Text diff --git a/app/client/src/pages/Settings/config/version.ts b/app/client/src/pages/Settings/config/version.ts index c10ef3092098..37c082170fc0 100644 --- a/app/client/src/pages/Settings/config/version.ts +++ b/app/client/src/pages/Settings/config/version.ts @@ -1,11 +1,17 @@ import type { Dispatch } from "react"; import type { ReduxAction } from "@appsmith/constants/ReduxActionConstants"; import { ReduxActionTypes } from "@appsmith/constants/ReduxActionConstants"; -import type { AdminConfigType } from "@appsmith/pages/AdminSettings/config/types"; +import type { + AdminConfigType, + Setting, +} from "@appsmith/pages/AdminSettings/config/types"; import { SettingCategories, SettingTypes, } from "@appsmith/pages/AdminSettings/config/types"; +import { isAirgapped } from "@appsmith/utils/airgapHelpers"; + +const isAirgappedInstance = isAirgapped(); export const config: AdminConfigType = { icon: "timer-2-line", @@ -33,5 +39,7 @@ export const config: AdminConfigType = { controlType: SettingTypes.LINK, label: "Release Notes", }, - ], + ].filter((setting) => + isAirgappedInstance ? setting.id !== "APPSMITH_VERSION_READ_MORE" : true, + ) as Setting[], }; diff --git a/app/client/src/pages/Templates/DatasourceChip.tsx b/app/client/src/pages/Templates/DatasourceChip.tsx index 0b4d7725bb18..fc03e79624a3 100644 --- a/app/client/src/pages/Templates/DatasourceChip.tsx +++ b/app/client/src/pages/Templates/DatasourceChip.tsx @@ -5,6 +5,7 @@ import { useSelector } from "react-redux"; import type { AppState } from "@appsmith/reducers"; import { getDefaultPlugin } from "selectors/entitiesSelector"; import styled from "styled-components"; +import { getAssetUrl } from "@appsmith/utils/airgapHelpers"; const StyledDatasourceChip = styled.div` background-color: rgba(248, 248, 248, 0.5); @@ -40,7 +41,7 @@ function DatasourceChip(props: DatasourceChipProps) { return ( <StyledDatasourceChip className={props.className}> - <img className="image" src={plugin.iconLocation} /> + <img className="image" src={getAssetUrl(plugin.iconLocation)} /> <span>{plugin.name}</span> </StyledDatasourceChip> ); diff --git a/app/client/src/pages/Templates/WidgetInfo.tsx b/app/client/src/pages/Templates/WidgetInfo.tsx index 9b700cbebd46..60bc5ae57747 100644 --- a/app/client/src/pages/Templates/WidgetInfo.tsx +++ b/app/client/src/pages/Templates/WidgetInfo.tsx @@ -4,6 +4,7 @@ import { useSelector } from "react-redux"; import { Text, FontWeight, TextType } from "design-system-old"; import { IconWrapper } from "constants/IconConstants"; import { getWidgetCards } from "selectors/editorSelectors"; +import { getAssetUrl } from "@appsmith/utils/airgapHelpers"; const Wrapper = styled.div` display: inline-flex; @@ -25,7 +26,7 @@ function WidgetInfo({ widgetType }: WidgetInfoProps) { return ( <Wrapper> <IconWrapper> - <img className="w-8 h-8" src={widgetInfo?.icon} /> + <img className="w-8 h-8" src={getAssetUrl(widgetInfo?.icon)} /> </IconWrapper> <Text type={TextType.H4} weight={FontWeight.NORMAL}> {widgetInfo?.displayName} diff --git a/app/client/src/pages/UserAuth/Container.tsx b/app/client/src/pages/UserAuth/Container.tsx index 5b5adb877436..8f53e61d8151 100644 --- a/app/client/src/pages/UserAuth/Container.tsx +++ b/app/client/src/pages/UserAuth/Container.tsx @@ -3,6 +3,7 @@ import { useSelector } from "react-redux"; import FooterLinks from "./FooterLinks"; import { getTenantConfig } from "@appsmith/selectors/tenantSelectors"; +import { getAssetUrl } from "@appsmith/utils/airgapHelpers"; type ContainerProps = { title: string; @@ -19,7 +20,10 @@ function Container(props: ContainerProps) { return ( <div className="flex flex-col items-center gap-4 my-auto min-w-min"> <div className="bg-white border border-t-4 border-t-[color:var(--ads-color-brand)] py-8 px-6 w-[min(400px,80%)] flex flex-col gap-6 t--login-container"> - <img className="h-8 mx-auto" src={tenantConfig.brandLogoUrl} /> + <img + className="h-8 mx-auto" + src={getAssetUrl(tenantConfig.brandLogoUrl)} + /> <div className="flex flex-col gap-2 text-center"> <h1 className="text-xl font-semibold text-center">{title}</h1> {subtitle && <p className="text-base text-center">{subtitle}</p>} diff --git a/app/client/src/pages/common/ErrorPageHeader.tsx b/app/client/src/pages/common/ErrorPageHeader.tsx index d5f66d9539bb..084f43532541 100644 --- a/app/client/src/pages/common/ErrorPageHeader.tsx +++ b/app/client/src/pages/common/ErrorPageHeader.tsx @@ -19,6 +19,7 @@ import { getSelectedAppTheme } from "selectors/appThemingSelectors"; import { getCurrentApplication } from "selectors/editorSelectors"; import { NAVIGATION_SETTINGS } from "constants/AppConstants"; import { get } from "lodash"; +import { getAssetUrl } from "@appsmith/utils/airgapHelpers"; const StyledPageHeader = styled(StyledHeader)` box-shadow: none; @@ -79,7 +80,11 @@ export function ErrorPageHeader(props: ErrorPageHeaderProps) { }} to={APPLICATIONS_URL} > - <img alt="Logo" className="h-6" src={tenantConfig.brandLogoUrl} /> + <img + alt="Logo" + className="h-6" + src={getAssetUrl(tenantConfig.brandLogoUrl)} + /> </Link> )} </HeaderSection> diff --git a/app/client/src/pages/common/PageHeader.tsx b/app/client/src/pages/common/PageHeader.tsx index f3747c7e020e..11739f28ee6b 100644 --- a/app/client/src/pages/common/PageHeader.tsx +++ b/app/client/src/pages/common/PageHeader.tsx @@ -32,6 +32,7 @@ import { getSelectedAppTheme } from "selectors/appThemingSelectors"; import { getCurrentApplication } from "selectors/editorSelectors"; import { get } from "lodash"; import { NAVIGATION_SETTINGS } from "constants/AppConstants"; +import { getAssetUrl, isAirgapped } from "@appsmith/utils/airgapHelpers"; const StyledPageHeader = styled(StyledHeader)<{ hideShadow?: boolean; @@ -160,6 +161,8 @@ export function PageHeader(props: PageHeaderProps) { return tabs.some((tab) => tab.matcher(location.pathname)); }, [featureFlags, location.pathname]); + const isAirgappedInstance = isAirgapped(); + return ( <StyledPageHeader data-testid="t--appsmith-page-header" @@ -171,7 +174,11 @@ export function PageHeader(props: PageHeaderProps) { <HeaderSection> {tenantConfig.brandLogoUrl && ( <Link className="t--appsmith-logo" to={APPLICATIONS_URL}> - <img alt="Logo" className="h-6" src={tenantConfig.brandLogoUrl} /> + <img + alt="Logo" + className="h-6" + src={getAssetUrl(tenantConfig.brandLogoUrl)} + /> </Link> )} </HeaderSection> @@ -187,19 +194,21 @@ export function PageHeader(props: PageHeaderProps) { <div>Apps</div> </TabName> - <TabName - className="t--templates-tab" - isSelected={ - matchTemplatesPath(location.pathname) || - matchTemplatesIdPath(location.pathname) - } - onClick={() => { - AnalyticsUtil.logEvent("TEMPLATES_TAB_CLICK"); - history.push(TEMPLATES_PATH); - }} - > - <div>Templates</div> - </TabName> + {!isAirgappedInstance && ( + <TabName + className="t--templates-tab" + isSelected={ + matchTemplatesPath(location.pathname) || + matchTemplatesIdPath(location.pathname) + } + onClick={() => { + AnalyticsUtil.logEvent("TEMPLATES_TAB_CLICK"); + history.push(TEMPLATES_PATH); + }} + > + <div>Templates</div> + </TabName> + )} </> )} </Tabs> diff --git a/app/client/src/pages/common/ProfileImage.tsx b/app/client/src/pages/common/ProfileImage.tsx index 9638185ad50c..95b0eb12e065 100644 --- a/app/client/src/pages/common/ProfileImage.tsx +++ b/app/client/src/pages/common/ProfileImage.tsx @@ -47,7 +47,6 @@ export default function ProfileImage(props: { const backgroundColor = shouldRenderImage ? "transparent" : initialsAndColorCode[1]; - return ( <Profile backgroundColor={backgroundColor} diff --git a/app/client/src/pages/setup/Welcome.tsx b/app/client/src/pages/setup/Welcome.tsx index f7f8e3a6bf88..3600e788c608 100644 --- a/app/client/src/pages/setup/Welcome.tsx +++ b/app/client/src/pages/setup/Welcome.tsx @@ -9,6 +9,7 @@ import { WELCOME_HEADER, } from "@appsmith/constants/messages"; import NonSuperUserForm, { SuperUserForm } from "./GetStarted"; +import { getAssetUrl } from "@appsmith/utils/airgapHelpers"; const LandingPageWrapper = styled.div<{ hide: boolean }>` width: ${(props) => props.theme.pageContentWidth}px; @@ -50,8 +51,6 @@ const StyledImageBanner = styled.div` min-width: ${(props) => props.theme.pageContentWidth * 0.45}px; `; -const StyledImage = styled.img``; - const getWelcomeImage = () => `${ASSETS_CDN_URL}/welcome-banner.svg`; type LandingPageProps = { @@ -115,7 +114,7 @@ export default memo(function LandingPage(props: LandingPageProps) { )} </StyledTextBanner> <StyledImageBanner> - <StyledImage src={getWelcomeImage()} /> + <img src={getAssetUrl(getWelcomeImage())} /> </StyledImageBanner> </LandingPageContent> </LandingPageWrapper> diff --git a/app/client/src/reducers/entityReducers/metaWidgetsReducer.test.ts b/app/client/src/reducers/entityReducers/metaWidgetsReducer.test.ts index 9016cc0086ff..481ad40d7ae1 100644 --- a/app/client/src/reducers/entityReducers/metaWidgetsReducer.test.ts +++ b/app/client/src/reducers/entityReducers/metaWidgetsReducer.test.ts @@ -3,13 +3,15 @@ import reducer from "./metaWidgetsReducer"; import { ReduxActionTypes } from "@appsmith/constants/ReduxActionConstants"; import { metaWidgetState } from "utils/metaWidgetState"; import { nestedMetaWidgetInitialState } from "./testData/metaWidgetReducer"; +import { ASSETS_CDN_URL } from "constants/ThirdPartyConstants"; +import { getAssetUrl } from "@appsmith/utils/airgapHelpers"; const modifiedState: MetaWidgetsReduxState = { baowuczcgg: { parentColumnSpace: 1, parentRowSpace: 1, isVisible: true, - defaultImage: "https://assets.appsmith.com/widgets/default.png", + defaultImage: getAssetUrl(`${ASSETS_CDN_URL}/widgets/default.png`), imageShape: "RECTANGLE", maxZoomLevel: 1, enableRotation: false, diff --git a/app/client/src/sagas/ProvidersSaga.ts b/app/client/src/sagas/ProvidersSaga.ts index 1b650926bcd7..7a057f4c637e 100644 --- a/app/client/src/sagas/ProvidersSaga.ts +++ b/app/client/src/sagas/ProvidersSaga.ts @@ -41,6 +41,9 @@ import { import AnalyticsUtil from "utils/AnalyticsUtil"; import { getCurrentWorkspaceId } from "@appsmith/selectors/workspaceSelectors"; import { Toaster, Variant } from "design-system-old"; +import { isAirgapped } from "@appsmith/utils/airgapHelpers"; + +const isAirgappedInstance = isAirgapped(); export function* fetchProviderTemplatesSaga( action: ReduxActionWithPromise<FetchProviderTemplatesRequest>, @@ -226,28 +229,30 @@ export function* searchApiOrProviderSaga( } export default function* providersSagas() { - yield all([ - takeLatest( - ReduxActionTypes.FETCH_PROVIDER_TEMPLATES_INIT, - fetchProviderTemplatesSaga, - ), - takeLatest(ReduxActionTypes.ADD_API_TO_PAGE_INIT, addApiToPageSaga), - takeLatest( - ReduxActionTypes.FETCH_PROVIDERS_CATEGORIES_INIT, - fetchProvidersCategoriesSaga, - ), - debounce( - 300, - ReduxActionTypes.SEARCH_APIORPROVIDERS_INIT, - searchApiOrProviderSaga, - ), - takeLatest( - ReduxActionTypes.FETCH_PROVIDERS_WITH_CATEGORY_INIT, - fetchProvidersWithCategorySaga, - ), - takeLatest( - ReduxActionTypes.FETCH_PROVIDER_DETAILS_BY_PROVIDER_ID_INIT, - fetchProviderDetailsByProviderIdSaga, - ), - ]); + if (!isAirgappedInstance) { + yield all([ + takeLatest( + ReduxActionTypes.FETCH_PROVIDER_TEMPLATES_INIT, + fetchProviderTemplatesSaga, + ), + takeLatest(ReduxActionTypes.ADD_API_TO_PAGE_INIT, addApiToPageSaga), + takeLatest( + ReduxActionTypes.FETCH_PROVIDERS_CATEGORIES_INIT, + fetchProvidersCategoriesSaga, + ), + debounce( + 300, + ReduxActionTypes.SEARCH_APIORPROVIDERS_INIT, + searchApiOrProviderSaga, + ), + takeLatest( + ReduxActionTypes.FETCH_PROVIDERS_WITH_CATEGORY_INIT, + fetchProvidersWithCategorySaga, + ), + takeLatest( + ReduxActionTypes.FETCH_PROVIDER_DETAILS_BY_PROVIDER_ID_INIT, + fetchProviderDetailsByProviderIdSaga, + ), + ]); + } } diff --git a/app/client/src/sagas/TemplatesSagas.ts b/app/client/src/sagas/TemplatesSagas.ts index 9872b4a23825..20cdae49959e 100644 --- a/app/client/src/sagas/TemplatesSagas.ts +++ b/app/client/src/sagas/TemplatesSagas.ts @@ -45,6 +45,9 @@ import { fetchPluginFormConfigs } from "actions/pluginActions"; import { fetchAllPageEntityCompletion, saveLayout } from "actions/pageActions"; import { getAllPageIds } from "./selectors"; import { fetchPageDSLSaga } from "sagas/PageSagas"; +import { isAirgapped } from "@appsmith/utils/airgapHelpers"; + +const isAirgappedInstance = isAirgapped(); function* getAllTemplatesSaga() { try { @@ -320,33 +323,35 @@ function* getTemplateFiltersSaga() { } } +// TODO: Refactor and handle this airgap check in a better way - posssibly in root sagas (sangeeth) export default function* watchActionSagas() { - yield all([ - takeEvery(ReduxActionTypes.GET_ALL_TEMPLATES_INIT, getAllTemplatesSaga), - takeEvery(ReduxActionTypes.GET_TEMPLATE_INIT, getTemplateSaga), - takeEvery( - ReduxActionTypes.GET_SIMILAR_TEMPLATES_INIT, - getSimilarTemplatesSaga, - ), - takeEvery( - ReduxActionTypes.IMPORT_TEMPLATE_TO_WORKSPACE_INIT, - importTemplateToWorkspaceSaga, - ), - takeEvery( - ReduxActionTypes.GET_TEMPLATE_NOTIFICATION_SEEN, - getTemplateNotificationSeenSaga, - ), - takeEvery( - ReduxActionTypes.SET_TEMPLATE_NOTIFICATION_SEEN, - setTemplateNotificationSeenSaga, - ), - takeEvery( - ReduxActionTypes.IMPORT_TEMPLATE_TO_APPLICATION_INIT, - forkTemplateToApplicationSaga, - ), - takeEvery( - ReduxActionTypes.GET_TEMPLATE_FILTERS_INIT, - getTemplateFiltersSaga, - ), - ]); + if (!isAirgappedInstance) + yield all([ + takeEvery(ReduxActionTypes.GET_ALL_TEMPLATES_INIT, getAllTemplatesSaga), + takeEvery(ReduxActionTypes.GET_TEMPLATE_INIT, getTemplateSaga), + takeEvery( + ReduxActionTypes.GET_SIMILAR_TEMPLATES_INIT, + getSimilarTemplatesSaga, + ), + takeEvery( + ReduxActionTypes.IMPORT_TEMPLATE_TO_WORKSPACE_INIT, + importTemplateToWorkspaceSaga, + ), + takeEvery( + ReduxActionTypes.GET_TEMPLATE_NOTIFICATION_SEEN, + getTemplateNotificationSeenSaga, + ), + takeEvery( + ReduxActionTypes.SET_TEMPLATE_NOTIFICATION_SEEN, + setTemplateNotificationSeenSaga, + ), + takeEvery( + ReduxActionTypes.IMPORT_TEMPLATE_TO_APPLICATION_INIT, + forkTemplateToApplicationSaga, + ), + takeEvery( + ReduxActionTypes.GET_TEMPLATE_FILTERS_INIT, + getTemplateFiltersSaga, + ), + ]); } diff --git a/app/client/src/selectors/editorSelectors.tsx b/app/client/src/selectors/editorSelectors.tsx index 0f60ea1b6b77..939cf1549865 100644 --- a/app/client/src/selectors/editorSelectors.tsx +++ b/app/client/src/selectors/editorSelectors.tsx @@ -59,6 +59,7 @@ import type { CanvasWidgetStructure } from "widgets/constants"; import { denormalize } from "utils/canvasStructureHelpers"; import { isAutoHeightEnabledForWidget } from "widgets/WidgetUtils"; import WidgetFactory from "utils/WidgetFactory"; +import { isAirgapped } from "@appsmith/utils/airgapHelpers"; const getIsDraggingOrResizing = (state: AppState) => state.ui.widgetDragResize.isResizing || state.ui.widgetDragResize.isDragging; @@ -342,10 +343,9 @@ export const getWidgetCards = createSelector( getWidgetConfigs, getIsAutoLayout, (widgetConfigs: WidgetConfigReducerState, isAutoLayout: boolean) => { - const cards = Object.values(widgetConfigs.config).filter( - (config) => !config.hideCard, - ); - + const cards = Object.values(widgetConfigs.config).filter((config) => { + return isAirgapped() ? config.widgetName !== "Map" : !config.hideCard; + }); const _cards: WidgetCardProps[] = cards.map((config) => { const { detachFromLayout = false, diff --git a/app/client/src/selectors/entitiesSelector.ts b/app/client/src/selectors/entitiesSelector.ts index e9aba188c703..cbc7cf072bff 100644 --- a/app/client/src/selectors/entitiesSelector.ts +++ b/app/client/src/selectors/entitiesSelector.ts @@ -309,11 +309,9 @@ export const getDatasourcePlugins = createSelector(getPlugins, (plugins) => { export const getPluginImages = createSelector(getPlugins, (plugins) => { const pluginImages: Record<string, string> = {}; - plugins.forEach((plugin) => { pluginImages[plugin.id] = plugin?.iconLocation ?? ImageAlt; }); - return pluginImages; }); diff --git a/app/client/src/utils/BrandingUtils.ts b/app/client/src/utils/BrandingUtils.ts index ed9505d38284..1e588efdd04c 100644 --- a/app/client/src/utils/BrandingUtils.ts +++ b/app/client/src/utils/BrandingUtils.ts @@ -9,15 +9,19 @@ import { ADMIN_BRANDING_FAVICON_FORMAT_ERROR, ADMIN_BRANDING_FAVICON_DIMENSION_ERROR, } from "@appsmith/constants/messages"; +import { ASSETS_CDN_URL } from "constants/ThirdPartyConstants"; +import { getAssetUrl } from "@appsmith/utils/airgapHelpers"; const FAVICON_MAX_WIDTH = 32; const FAVICON_MAX_HEIGHT = 32; const DEFAULT_BRANDING_PRIMARY_COLOR = "#D7D7D7"; export const APPSMITH_BRAND_PRIMARY_COLOR = "#F86A2B"; -export const APPSMITH_BRAND_FAVICON_URL = - "https://assets.appsmith.com/appsmith-favicon-orange.ico"; -export const APPSMITH_BRAND_LOGO_URL = - "https://assets.appsmith.com/appsmith-logo-no-margin.png"; +export const APPSMITH_BRAND_FAVICON_URL = getAssetUrl( + `${ASSETS_CDN_URL}/appsmith-favicon-orange.ico`, +); +export const APPSMITH_BRAND_LOGO_URL = getAssetUrl( + `${ASSETS_CDN_URL}/appsmith-logo-no-margin.png`, +); /** * create brand colors from primary color diff --git a/app/client/src/utils/DSLMigrationsUtils.test.ts b/app/client/src/utils/DSLMigrationsUtils.test.ts index 594842e4bb51..ec4a5363b14b 100644 --- a/app/client/src/utils/DSLMigrationsUtils.test.ts +++ b/app/client/src/utils/DSLMigrationsUtils.test.ts @@ -4,6 +4,7 @@ import type { ContainerWidgetProps } from "widgets/ContainerWidget/widget"; import type { WidgetProps } from "widgets/BaseWidget"; import { OverflowTypes } from "widgets/TextWidget/constants"; import { migrateRadioGroupAlignmentProperty } from "./migrations/RadioGroupWidget"; +import { ASSETS_CDN_URL } from "constants/ThirdPartyConstants"; describe("correctly migrate dsl", () => { it("transformDSL for private widget", () => { @@ -125,7 +126,7 @@ describe("correctly migrate dsl", () => { template: { Image1: { isVisible: true, - defaultImage: "https://assets.appsmith.com/widgets/default.png", + defaultImage: `${ASSETS_CDN_URL}/widgets/default.png`, imageShape: "RECTANGLE", maxZoomLevel: 1, enableRotation: false, @@ -231,17 +232,17 @@ describe("correctly migrate dsl", () => { { id: "001", name: "Blue", - img: "https://assets.appsmith.com/widgets/default.png", + img: `${ASSETS_CDN_URL}/widgets/default.png`, }, { id: "002", name: "Green", - img: "https://assets.appsmith.com/widgets/default.png", + img: `${ASSETS_CDN_URL}/widgets/default.png`, }, { id: "003", name: "Red", - img: "https://assets.appsmith.com/widgets/default.png", + img: `${ASSETS_CDN_URL}/widgets/default.png`, }, ], isCanvas: true, @@ -340,8 +341,7 @@ describe("correctly migrate dsl", () => { }, ], leftColumn: 0, - defaultImage: - "https://assets.appsmith.com/widgets/default.png", + defaultImage: `${ASSETS_CDN_URL}/widgets/default.png`, key: "9cn4ooadxj", image: "{{currentItem.img}}", rightColumn: 16, @@ -728,7 +728,7 @@ describe("correctly migrate dsl", () => { template: { Image1: { isVisible: true, - defaultImage: "https://assets.appsmith.com/widgets/default.png", + defaultImage: `${ASSETS_CDN_URL}/widgets/default.png`, imageShape: "RECTANGLE", maxZoomLevel: 1, enableRotation: false, @@ -833,17 +833,17 @@ describe("correctly migrate dsl", () => { { id: "001", name: "Blue", - img: "https://assets.appsmith.com/widgets/default.png", + img: `${ASSETS_CDN_URL}/widgets/default.png`, }, { id: "002", name: "Green", - img: "https://assets.appsmith.com/widgets/default.png", + img: `${ASSETS_CDN_URL}/widgets/default.png`, }, { id: "003", name: "Red", - img: "https://assets.appsmith.com/widgets/default.png", + img: `${ASSETS_CDN_URL}/widgets/default.png`, }, ], isCanvas: true, @@ -953,8 +953,7 @@ describe("correctly migrate dsl", () => { }, ], leftColumn: 0, - defaultImage: - "https://assets.appsmith.com/widgets/default.png", + defaultImage: `${ASSETS_CDN_URL}/widgets/default.png`, key: "9cn4ooadxj", labelTextSize: "0.875rem", image: "{{currentItem.img}}", @@ -1355,7 +1354,7 @@ describe("correctly migrate dsl", () => { template: { Image1: { isVisible: true, - defaultImage: "https://assets.appsmith.com/widgets/default.png", + defaultImage: `${ASSETS_CDN_URL}/widgets/default.png`, imageShape: "RECTANGLE", maxZoomLevel: 1, enableRotation: false, @@ -1461,17 +1460,17 @@ describe("correctly migrate dsl", () => { { id: "001", name: "Blue", - img: "https://assets.appsmith.com/widgets/default.png", + img: `${ASSETS_CDN_URL}/widgets/default.png`, }, { id: "002", name: "Green", - img: "https://assets.appsmith.com/widgets/default.png", + img: `${ASSETS_CDN_URL}/widgets/default.png`, }, { id: "003", name: "Red", - img: "https://assets.appsmith.com/widgets/default.png", + img: `${ASSETS_CDN_URL}/widgets/default.png`, }, ], isCanvas: true, @@ -1570,8 +1569,7 @@ describe("correctly migrate dsl", () => { }, ], leftColumn: 0, - defaultImage: - "https://assets.appsmith.com/widgets/default.png", + defaultImage: `${ASSETS_CDN_URL}/widgets/default.png`, key: "9cn4ooadxj", image: "{{currentItem.img}}", rightColumn: 16, @@ -1958,7 +1956,7 @@ describe("correctly migrate dsl", () => { template: { Image1: { isVisible: true, - defaultImage: "https://assets.appsmith.com/widgets/default.png", + defaultImage: `${ASSETS_CDN_URL}/widgets/default.png`, imageShape: "RECTANGLE", maxZoomLevel: 1, enableRotation: false, @@ -2063,17 +2061,17 @@ describe("correctly migrate dsl", () => { { id: "001", name: "Blue", - img: "https://assets.appsmith.com/widgets/default.png", + img: `${ASSETS_CDN_URL}/widgets/default.png`, }, { id: "002", name: "Green", - img: "https://assets.appsmith.com/widgets/default.png", + img: `${ASSETS_CDN_URL}/widgets/default.png`, }, { id: "003", name: "Red", - img: "https://assets.appsmith.com/widgets/default.png", + img: `${ASSETS_CDN_URL}/widgets/default.png`, }, ], isCanvas: true, @@ -2183,8 +2181,7 @@ describe("correctly migrate dsl", () => { }, ], leftColumn: 0, - defaultImage: - "https://assets.appsmith.com/widgets/default.png", + defaultImage: `${ASSETS_CDN_URL}/widgets/default.png`, key: "9cn4ooadxj", labelTextSize: "0.875rem", image: "{{currentItem.img}}", diff --git a/app/client/src/utils/WidgetPropsUtils.test.tsx b/app/client/src/utils/WidgetPropsUtils.test.tsx index ac856fc399dc..f8b21e596725 100644 --- a/app/client/src/utils/WidgetPropsUtils.test.tsx +++ b/app/client/src/utils/WidgetPropsUtils.test.tsx @@ -19,6 +19,7 @@ import { getMousePositionsOnCanvas, } from "./WidgetPropsUtils"; import type { WidgetDraggingBlock } from "pages/common/CanvasArenas/hooks/useBlocksToBeDraggedOnCanvas"; +import { ASSETS_CDN_URL } from "constants/ThirdPartyConstants"; describe("WidgetProps tests", () => { it("should convert WidgetDraggingBlocks to occupied Spaces", () => { @@ -643,7 +644,7 @@ describe("Initial value migration test", () => { renderMode: RenderModes.CANVAS, version: 1, onPlay: "", - url: "https://assets.appsmith.com/widgets/bird.mp4", + url: `${ASSETS_CDN_URL}/widgets/bird.mp4`, parentId: "0", isLoading: false, parentColumnSpace: 67.375, @@ -668,7 +669,7 @@ describe("Initial value migration test", () => { renderMode: RenderModes.CANVAS, version: 1, onPlay: "", - url: "https://assets.appsmith.com/widgets/bird.mp4", + url: `${ASSETS_CDN_URL}/widgets/bird.mp4`, parentId: "0", isLoading: false, parentColumnSpace: 67.375, diff --git a/app/client/src/utils/metaWidgetState.ts b/app/client/src/utils/metaWidgetState.ts index 8f078ac9a905..37bf26a763a9 100644 --- a/app/client/src/utils/metaWidgetState.ts +++ b/app/client/src/utils/metaWidgetState.ts @@ -1,3 +1,5 @@ +import { getAssetUrl } from "@appsmith/utils/airgapHelpers"; +import { ASSETS_CDN_URL } from "constants/ThirdPartyConstants"; import type { MetaWidgetsReduxState } from "reducers/entityReducers/metaWidgetsReducer"; export const metaWidgetState: MetaWidgetsReduxState = { @@ -5,7 +7,7 @@ export const metaWidgetState: MetaWidgetsReduxState = { isVisible: true, parentColumnSpace: 1, parentRowSpace: 1, - defaultImage: "https://assets.appsmith.com/widgets/default.png", + defaultImage: getAssetUrl(`${ASSETS_CDN_URL}/widgets/default.png`), imageShape: "RECTANGLE", maxZoomLevel: 1, enableRotation: false, @@ -278,7 +280,7 @@ export const metaWidgetState: MetaWidgetsReduxState = { parentColumnSpace: 1, parentRowSpace: 1, isVisible: true, - defaultImage: "https://assets.appsmith.com/widgets/default.png", + defaultImage: getAssetUrl(`${ASSETS_CDN_URL}/widgets/default.png`), imageShape: "RECTANGLE", maxZoomLevel: 1, enableRotation: false, @@ -661,7 +663,7 @@ export const metaWidgetState: MetaWidgetsReduxState = { parentColumnSpace: 1, parentRowSpace: 1, isVisible: true, - defaultImage: "https://assets.appsmith.com/widgets/default.png", + defaultImage: getAssetUrl(`${ASSETS_CDN_URL}/widgets/default.png`), imageShape: "RECTANGLE", maxZoomLevel: 1, enableRotation: false, diff --git a/app/client/src/utils/testDSLs.ts b/app/client/src/utils/testDSLs.ts index 70647f8a5db3..c22060ade36b 100644 --- a/app/client/src/utils/testDSLs.ts +++ b/app/client/src/utils/testDSLs.ts @@ -1,3 +1,6 @@ +import { getAssetUrl } from "@appsmith/utils/airgapHelpers"; +import { ASSETS_CDN_URL } from "constants/ThirdPartyConstants"; + export const originalDSLForDSLMigrations = { widgetName: "MainContainer", backgroundColor: "none", @@ -313,8 +316,9 @@ export const originalDSLForDSLMigrations = { key: "image", }, ], - defaultImage: - "https://assets.appsmith.com/widgets/default.png", + defaultImage: getAssetUrl( + `${ASSETS_CDN_URL}/widgets/default.png`, + ), key: "52v1r95ynr", image: "{{lst_user.selectedItem.image}}", isDeprecated: false, @@ -1624,8 +1628,9 @@ export const originalDSLForDSLMigrations = { }, ], leftColumn: 0, - defaultImage: - "https://assets.appsmith.com/widgets/default.png", + defaultImage: getAssetUrl( + `${ASSETS_CDN_URL}/widgets/default.png`, + ), key: "6zvrwxg59v", image: "{{lst_user.listData.map((currentItem) => currentItem.image)}}", @@ -2187,8 +2192,9 @@ export const originalDSLForDSLMigrations = { }, ], leftColumn: 0, - defaultImage: - "https://assets.appsmith.com/widgets/default.png", + defaultImage: getAssetUrl( + `${ASSETS_CDN_URL}/widgets/default.png`, + ), key: "6zvrwxg59v", image: "{{currentItem.image}}", isDeprecated: false, diff --git a/app/client/src/widgets/AudioWidget/index.tsx b/app/client/src/widgets/AudioWidget/index.tsx index 637fe54a1e5d..79e1eff6b714 100644 --- a/app/client/src/widgets/AudioWidget/index.tsx +++ b/app/client/src/widgets/AudioWidget/index.tsx @@ -3,6 +3,8 @@ import { ResponsiveBehavior } from "utils/autoLayout/constants"; import IconSVG from "./icon.svg"; import Widget from "./widget"; +import { ASSETS_CDN_URL } from "constants/ThirdPartyConstants"; +import { getAssetUrl } from "@appsmith/utils/airgapHelpers"; export const CONFIG = { type: Widget.getWidgetType(), @@ -14,7 +16,7 @@ export const CONFIG = { rows: 4, columns: 28, widgetName: "Audio", - url: "https://assets.appsmith.com/widgets/birds_chirping.mp3", + url: getAssetUrl(`${ASSETS_CDN_URL}/widgets/birds_chirping.mp3`), autoPlay: false, version: 1, animateLoading: true, diff --git a/app/client/src/widgets/AudioWidget/widget/index.tsx b/app/client/src/widgets/AudioWidget/widget/index.tsx index b43377d1d2fc..22aee1fcd45d 100644 --- a/app/client/src/widgets/AudioWidget/widget/index.tsx +++ b/app/client/src/widgets/AudioWidget/widget/index.tsx @@ -8,6 +8,8 @@ import { retryPromise } from "utils/AppsmithUtils"; import { AutocompleteDataType } from "utils/autocomplete/CodemirrorTernService"; import type { WidgetProps, WidgetState } from "../../BaseWidget"; import BaseWidget from "../../BaseWidget"; +import { ASSETS_CDN_URL } from "constants/ThirdPartyConstants"; +import { getAssetUrl } from "@appsmith/utils/airgapHelpers"; const AudioComponent = lazy(() => retryPromise(() => import("../component"))); @@ -40,8 +42,9 @@ class AudioWidget extends BaseWidget<AudioWidgetProps, WidgetState> { /(http(s)?:\/\/.)?(www\.)?[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,6}\b([-a-zA-Z0-9@:%_\+.~#?&//=]*)/, expected: { type: "Audio URL", - example: - "https://assets.appsmith.com/widgets/birds_chirping.mp3", + example: getAssetUrl( + `${ASSETS_CDN_URL}/widgets/birds_chirping.mp3`, + ), autocompleteDataType: AutocompleteDataType.STRING, }, }, diff --git a/app/client/src/widgets/ImageWidget/index.ts b/app/client/src/widgets/ImageWidget/index.ts index dac4562925b6..9ac19126cd63 100644 --- a/app/client/src/widgets/ImageWidget/index.ts +++ b/app/client/src/widgets/ImageWidget/index.ts @@ -1,12 +1,14 @@ +import { ASSETS_CDN_URL } from "constants/ThirdPartyConstants"; import IconSVG from "./icon.svg"; import Widget from "./widget"; +import { getAssetUrl } from "@appsmith/utils/airgapHelpers"; export const CONFIG = { type: Widget.getWidgetType(), name: "Image", iconSVG: IconSVG, defaults: { - defaultImage: "https://assets.appsmith.com/widgets/default.png", + defaultImage: getAssetUrl(`${ASSETS_CDN_URL}/widgets/default.png`), imageShape: "RECTANGLE", maxZoomLevel: 1, enableRotation: false, diff --git a/app/client/src/widgets/ListWidget/index.ts b/app/client/src/widgets/ListWidget/index.ts index d7c9c5b4a0c1..18affbf99bf2 100644 --- a/app/client/src/widgets/ListWidget/index.ts +++ b/app/client/src/widgets/ListWidget/index.ts @@ -10,6 +10,8 @@ import type { FlattenedWidgetProps } from "widgets/constants"; import { BlueprintOperationTypes } from "widgets/constants"; import IconSVG from "./icon.svg"; import Widget from "./widget"; +import { ASSETS_CDN_URL } from "constants/ThirdPartyConstants"; +import { getAssetUrl } from "@appsmith/utils/airgapHelpers"; export const CONFIG = { type: Widget.getWidgetType(), @@ -89,17 +91,17 @@ export const CONFIG = { { id: "001", name: "Blue", - img: "https://assets.appsmith.com/widgets/default.png", + img: getAssetUrl(`${ASSETS_CDN_URL}/widgets/default.png`), }, { id: "002", name: "Green", - img: "https://assets.appsmith.com/widgets/default.png", + img: getAssetUrl(`${ASSETS_CDN_URL}/widgets/default.png`), }, { id: "003", name: "Red", - img: "https://assets.appsmith.com/widgets/default.png", + img: getAssetUrl(`${ASSETS_CDN_URL}/widgets/default.png`), }, ], widgetName: "List", @@ -157,8 +159,9 @@ export const CONFIG = { }, position: { top: 0, left: 0 }, props: { - defaultImage: - "https://assets.appsmith.com/widgets/default.png", + defaultImage: getAssetUrl( + `${ASSETS_CDN_URL}/widgets/default.png`, + ), imageShape: "RECTANGLE", maxZoomLevel: 1, image: "{{currentItem.img}}", diff --git a/app/client/src/widgets/ListWidgetV2/index.ts b/app/client/src/widgets/ListWidgetV2/index.ts index e39b8ca8a98d..bc148c76d853 100644 --- a/app/client/src/widgets/ListWidgetV2/index.ts +++ b/app/client/src/widgets/ListWidgetV2/index.ts @@ -20,22 +20,24 @@ import { Positioning, ResponsiveBehavior, } from "utils/autoLayout/constants"; +import { ASSETS_CDN_URL } from "constants/ThirdPartyConstants"; +import { getAssetUrl } from "@appsmith/utils/airgapHelpers"; const DEFAULT_LIST_DATA = [ { id: "001", name: "Blue", - img: "https://assets.appsmith.com/widgets/default.png", + img: getAssetUrl(`${ASSETS_CDN_URL}/widgets/default.png`), }, { id: "002", name: "Green", - img: "https://assets.appsmith.com/widgets/default.png", + img: getAssetUrl(`${ASSETS_CDN_URL}/widgets/default.png`), }, { id: "003", name: "Red", - img: "https://assets.appsmith.com/widgets/default.png", + img: getAssetUrl(`${ASSETS_CDN_URL}/widgets/default.png`), }, ]; @@ -161,8 +163,9 @@ export const CONFIG = { }, position: { top: 0, left: 0 }, props: { - defaultImage: - "https://assets.appsmith.com/widgets/default.png", + defaultImage: getAssetUrl( + `${ASSETS_CDN_URL}/widgets/default.png`, + ), imageShape: "RECTANGLE", maxZoomLevel: 1, image: "{{currentItem.img}}", diff --git a/app/client/src/widgets/ListWidgetV2/testData.ts b/app/client/src/widgets/ListWidgetV2/testData.ts index 879ecb9f7a38..132853f92534 100644 --- a/app/client/src/widgets/ListWidgetV2/testData.ts +++ b/app/client/src/widgets/ListWidgetV2/testData.ts @@ -1,3 +1,5 @@ +import { getAssetUrl } from "@appsmith/utils/airgapHelpers"; +import { ASSETS_CDN_URL } from "constants/ThirdPartyConstants"; import type { FlattenedWidgetProps } from "widgets/constants"; export const simpleListInput = { @@ -138,7 +140,7 @@ export const simpleListInput = { }, ], leftColumn: 0, - defaultImage: "https://assets.appsmith.com/widgets/default.png", + defaultImage: getAssetUrl(`${ASSETS_CDN_URL}/widgets/default.png`), key: "47mo8av09c", image: "{{currentItem.img}}", isDeprecated: false, @@ -440,7 +442,7 @@ export const nestedListInput = { }, ], leftColumn: 0, - defaultImage: "https://assets.appsmith.com/widgets/default.png", + defaultImage: getAssetUrl(`${ASSETS_CDN_URL}/widgets/default.png`), key: "2g7ntchr1f", image: "{{currentItem.img}}", isDeprecated: false, @@ -591,17 +593,17 @@ export const nestedListInput = { { id: "001", name: "Blue", - img: "https://assets.appsmith.com/widgets/default.png", + img: getAssetUrl(`${ASSETS_CDN_URL}/widgets/default.png`), }, { id: "002", name: "Green", - img: "https://assets.appsmith.com/widgets/default.png", + img: getAssetUrl(`${ASSETS_CDN_URL}/widgets/default.png`), }, { id: "003", name: "Red", - img: "https://assets.appsmith.com/widgets/default.png", + img: getAssetUrl(`${ASSETS_CDN_URL}/widgets/default.png`), }, ], pageSize: 3, @@ -750,7 +752,7 @@ export const nestedListInput = { }, xyt7kd0vsa: { isVisible: true, - defaultImage: "https://assets.appsmith.com/widgets/default.png", + defaultImage: getAssetUrl(`${ASSETS_CDN_URL}/widgets/default.png`), imageShape: "RECTANGLE", maxZoomLevel: 1, enableRotation: false, diff --git a/app/client/src/widgets/VideoWidget/index.ts b/app/client/src/widgets/VideoWidget/index.ts index 7eb68fa5c513..5c7fc10438da 100644 --- a/app/client/src/widgets/VideoWidget/index.ts +++ b/app/client/src/widgets/VideoWidget/index.ts @@ -1,6 +1,8 @@ +import { ASSETS_CDN_URL } from "constants/ThirdPartyConstants"; import { ResponsiveBehavior } from "utils/autoLayout/constants"; import IconSVG from "./icon.svg"; import Widget from "./widget"; +import { getAssetUrl } from "@appsmith/utils/airgapHelpers"; export const CONFIG = { type: Widget.getWidgetType(), @@ -12,7 +14,7 @@ export const CONFIG = { rows: 28, columns: 24, widgetName: "Video", - url: "https://assets.appsmith.com/widgets/bird.mp4", + url: getAssetUrl(`${ASSETS_CDN_URL}/widgets/bird.mp4`), autoPlay: false, version: 1, animateLoading: true, diff --git a/app/client/src/widgets/VideoWidget/widget/index.tsx b/app/client/src/widgets/VideoWidget/widget/index.tsx index ff7a89e7177c..f5bb573ed4a3 100644 --- a/app/client/src/widgets/VideoWidget/widget/index.tsx +++ b/app/client/src/widgets/VideoWidget/widget/index.tsx @@ -10,6 +10,8 @@ import { retryPromise } from "utils/AppsmithUtils"; import { AutocompleteDataType } from "utils/autocomplete/CodemirrorTernService"; import type { WidgetProps, WidgetState } from "../../BaseWidget"; import BaseWidget from "../../BaseWidget"; +import { ASSETS_CDN_URL } from "constants/ThirdPartyConstants"; +import { getAssetUrl } from "@appsmith/utils/airgapHelpers"; const VideoComponent = lazy(() => retryPromise(() => import("../component"))); @@ -42,7 +44,7 @@ class VideoWidget extends BaseWidget<VideoWidgetProps, WidgetState> { /(http(s)?:\/\/.)?(www\.)?[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,6}\b([-a-zA-Z0-9@:%_\+.~#?&//=]*)/, expected: { type: "Video URL", - example: "https://assets.appsmith.com/widgets/bird.mp4", + example: getAssetUrl(`${ASSETS_CDN_URL}/widgets/bird.mp4`), autocompleteDataType: AutocompleteDataType.STRING, }, },
9c8b05b042028dfea1c3833c18ddd22d96dbb76e
2023-06-15 10:06:31
Dhruvik Neharia
feat: add htmlPageTitle hook and use it in login and sign up pages (#24458)
false
add htmlPageTitle hook and use it in login and sign up pages (#24458)
feat
diff --git a/app/client/src/ce/pages/UserAuth/Login.tsx b/app/client/src/ce/pages/UserAuth/Login.tsx index 71edb24aa5d3..4a94e15694b6 100644 --- a/app/client/src/ce/pages/UserAuth/Login.tsx +++ b/app/client/src/ce/pages/UserAuth/Login.tsx @@ -46,6 +46,8 @@ import { getThirdPartyAuths, getIsFormLoginEnabled, } from "@appsmith/selectors/tenantSelectors"; +import Helmet from "react-helmet"; +import { useHtmlPageTitle } from "@appsmith/utils"; const validate = (values: LoginFormValues, props: ValidateProps) => { const errors: LoginFormValues = {}; @@ -86,6 +88,7 @@ export function Login(props: LoginFormProps) { const isFormLoginEnabled = useSelector(getIsFormLoginEnabled); const socialLoginList = useSelector(getThirdPartyAuths); const queryParams = new URLSearchParams(location.search); + const htmlPageTitle = useHtmlPageTitle(); const invalidCredsForgotPasswordLinkText = createMessage( LOGIN_PAGE_INVALID_CREDS_FORGOT_PASSWORD_LINK, ); @@ -133,6 +136,10 @@ export function Login(props: LoginFormProps) { subtitle={createMessage(LOGIN_PAGE_SUBTITLE)} title={createMessage(LOGIN_PAGE_TITLE)} > + <Helmet> + <title>{htmlPageTitle}</title> + </Helmet> + {showError && ( <Callout kind="error" diff --git a/app/client/src/ce/pages/UserAuth/SignUp.tsx b/app/client/src/ce/pages/UserAuth/SignUp.tsx index 2bf3bff0c6d8..18c376e2dd54 100644 --- a/app/client/src/ce/pages/UserAuth/SignUp.tsx +++ b/app/client/src/ce/pages/UserAuth/SignUp.tsx @@ -47,6 +47,8 @@ import { getIsFormLoginEnabled, getThirdPartyAuths, } from "@appsmith/selectors/tenantSelectors"; +import Helmet from "react-helmet"; +import { useHtmlPageTitle } from "@appsmith/utils"; declare global { interface Window { @@ -93,6 +95,7 @@ export function SignUp(props: SignUpFormProps) { const socialLoginList = useSelector(getThirdPartyAuths); const shouldDisableSignupButton = pristine || !isFormValid; const location = useLocation(); + const htmlPageTitle = useHtmlPageTitle(); const recaptchaStatus = useScript( `https://www.google.com/recaptcha/api.js?render=${googleRecaptchaSiteKey.apiKey}`, @@ -166,6 +169,10 @@ export function SignUp(props: SignUpFormProps) { subtitle={createMessage(SIGNUP_PAGE_SUBTITLE)} title={createMessage(SIGNUP_PAGE_TITLE)} > + <Helmet> + <title>{htmlPageTitle}</title> + </Helmet> + {showError && <Callout kind="error">{errorMessage}</Callout>} {socialLoginList.length > 0 && ( <ThirdPartyAuth logins={socialLoginList} type={"SIGNUP"} /> diff --git a/app/client/src/ce/utils/index.ts b/app/client/src/ce/utils/index.ts index b14ce61b1633..5c806445b98c 100644 --- a/app/client/src/ce/utils/index.ts +++ b/app/client/src/ce/utils/index.ts @@ -9,3 +9,7 @@ export const addItemsInContextMenu = ( ) => { return moreActionItems; }; + +export const useHtmlPageTitle = () => { + return "Appsmith"; +};
4f4d1400c53b2dbe5c8ba920058c86cab18ffaa1
2022-04-20 11:32:01
Aman Agarwal
fix: updated the condition to show expiry key (#13092)
false
updated the condition to show expiry key (#13092)
fix
diff --git a/app/server/appsmith-plugins/amazons3Plugin/src/main/resources/editor/list.json b/app/server/appsmith-plugins/amazons3Plugin/src/main/resources/editor/list.json index 66b0ef0a8646..74391e7262d3 100644 --- a/app/server/appsmith-plugins/amazons3Plugin/src/main/resources/editor/list.json +++ b/app/server/appsmith-plugins/amazons3Plugin/src/main/resources/editor/list.json @@ -98,7 +98,7 @@ "controlType": "QUERY_DYNAMIC_INPUT_TEXT", "initialValue": "5", "conditionals": { - "show": "{{actionConfiguration.formData.signedUrl.data === 'YES'}}" + "show": "{{actionConfiguration.formData.list.signedUrl.data === 'YES'}}" } }, {
df715297ec02c228ffc953337bc798543c40d6c1
2021-12-01 18:36:41
Aman Agarwal
fix: Adding empty array check for mapping keys (#9459)
false
Adding empty array check for mapping keys (#9459)
fix
diff --git a/app/client/src/pages/Editor/QueryEditor/Table.tsx b/app/client/src/pages/Editor/QueryEditor/Table.tsx index 7c62bbbc0fc0..9ca267a09bc8 100644 --- a/app/client/src/pages/Editor/QueryEditor/Table.tsx +++ b/app/client/src/pages/Editor/QueryEditor/Table.tsx @@ -197,16 +197,21 @@ const renderCell = (props: any) => { function Table(props: TableProps) { const data = React.useMemo(() => { const emptyString = ""; - const keys = Object.keys(props.data[0]); - keys.forEach((key) => { - if (key === emptyString) { - const value = props.data[0][key]; - delete props.data[0][key]; - props.data[0][uniqueId()] = value; - } - }); + /* Check for length greater than 0 of rows returned from the query for mappings keys */ + if (props.data?.length > 0) { + const keys = Object.keys(props.data[0]); + keys.forEach((key) => { + if (key === emptyString) { + const value = props.data[0][key]; + delete props.data[0][key]; + props.data[0][uniqueId()] = value; + } + }); - return props.data; + return props.data; + } + + return []; }, [props.data]); const columns = React.useMemo(() => { if (data.length) {
b98d2d2df3eddcbde947bacb65db04f79e8a7085
2024-07-02 14:04:17
Aman Agarwal
fix: restricting passphrase to be sent to client (#34610)
false
restricting passphrase to be sent to client (#34610)
fix
diff --git a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/KeyPairAuth.java b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/KeyPairAuth.java index 2f610961d6e0..87ab49694e2b 100644 --- a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/KeyPairAuth.java +++ b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/KeyPairAuth.java @@ -28,6 +28,6 @@ public class KeyPairAuth extends AuthenticationDTO { @JsonView({Views.Public.class, FromRequest.class}) UploadedFile privateKey; - @JsonView({Views.Public.class, FromRequest.class}) + @JsonView({Views.Internal.class, FromRequest.class}) @Encrypted String passphrase; }
b9752ef5dbde81782f40e64f45d3bfa81f2aafe0
2024-01-10 15:26:52
Jacques Ikot
fix: redundant unit tests in templates (#30189)
false
redundant unit tests in templates (#30189)
fix
diff --git a/app/client/src/pages/Templates/BuildingBlock/BuildingBlock.test.tsx b/app/client/src/pages/Templates/BuildingBlock/BuildingBlock.test.tsx index b2b5e1f9386c..034c2ac41b3f 100644 --- a/app/client/src/pages/Templates/BuildingBlock/BuildingBlock.test.tsx +++ b/app/client/src/pages/Templates/BuildingBlock/BuildingBlock.test.tsx @@ -84,11 +84,4 @@ describe("<BuildingBlock />", () => { fireEvent.click(screen.getByText(MOCK_BUILDING_BLOCK_TITLE)); expect(onForkTemplateClick).not.toHaveBeenCalled(); }); - - // it("opens the fork modal when the fork button is clicked", async () => { - // render(BaseBuildingBlockRender()); - // const forkButton = screen.getByTestId("t--fork-building-block"); - // fireEvent.click(forkButton); - // expect(screen.getByTestId("t--fork-template-modal")).toBeInTheDocument(); - // }); }); diff --git a/app/client/src/pages/Templates/ForkTemplate.tsx b/app/client/src/pages/Templates/ForkTemplate.tsx index f70acdef3362..334542efdc50 100644 --- a/app/client/src/pages/Templates/ForkTemplate.tsx +++ b/app/client/src/pages/Templates/ForkTemplate.tsx @@ -57,10 +57,7 @@ function ForkTemplate({ <Modal onOpenChange={closeModal} open={showForkModal}> <ModalContent style={{ width: "640px" }}> <ModalHeader>{createMessage(CHOOSE_WHERE_TO_FORK)}</ModalHeader> - <ModalBody - data-testid="t--fork-template-modal" - style={{ overflow: "unset", paddingBottom: "4px" }} - > + <ModalBody style={{ overflow: "unset", paddingBottom: "4px" }}> <Select dropdownMatchSelectWidth getPopupContainer={(triggerNode) => triggerNode.parentNode}
dc70220a2feebc25a41c7573d8f2524dd34efc80
2022-05-05 11:08:17
Nidhi
fix: Throw error when trying to import a cURL command that has a subshell in it (#13558)
false
Throw error when trying to import a cURL command that has a subshell in it (#13558)
fix
diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/CurlImporterServiceCEImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/CurlImporterServiceCEImpl.java index 89ca00d09bc7..8f44f3aa9840 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/CurlImporterServiceCEImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/CurlImporterServiceCEImpl.java @@ -16,7 +16,6 @@ import com.appsmith.server.services.NewPageService; import com.appsmith.server.services.PluginService; import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang.StringUtils; @@ -151,10 +150,17 @@ public List<String> lex(String text) { final StringBuilder currentToken = new StringBuilder(); Character quote = null; boolean isEscaped = false; + boolean isDollarSubshellPossible = false; for (int i = 0; i < textLength; ++i) { char currentChar = trimmedText.charAt(i); + if (isDollarSubshellPossible) { + if (currentChar == '(') { + throw new AppsmithException(AppsmithError.GENERIC_BAD_REQUEST, "Please do not try to invoke a subshell in the cURL"); + } + } + if (quote != null) { // We are inside quotes. @@ -162,6 +168,12 @@ public List<String> lex(String text) { currentToken.append(currentChar); isEscaped = false; + } else if (currentChar == '$' && quote != '\'') { + isDollarSubshellPossible = true; + + } else if (currentChar == '`' && quote != '\'') { + throw new AppsmithException(AppsmithError.GENERIC_BAD_REQUEST, "Please do not try to invoke a subshell in the cURL"); + } else if (currentChar == '\\' && quote != '\'') { isEscaped = true; @@ -183,6 +195,12 @@ public List<String> lex(String text) { } isEscaped = false; + } else if (currentChar == '$') { + isDollarSubshellPossible = true; + + } else if (currentChar == '`') { + throw new AppsmithException(AppsmithError.GENERIC_BAD_REQUEST, "Please do not try to invoke a subshell in the cURL"); + } else if (currentChar == '\\') { // This is a backslash that will escape the next character. isEscaped = true; @@ -376,7 +394,6 @@ public ActionDTO parse(List<String> tokens) throws AppsmithException { } catch (MalformedURLException | URISyntaxException e) { // Ignore this argument. May be there's a valid URL later down the arguments list. } - } if (isStateProcessed) { diff --git a/app/server/appsmith-server/src/test/java/com/appsmith/server/services/CurlImporterServiceTest.java b/app/server/appsmith-server/src/test/java/com/appsmith/server/services/CurlImporterServiceTest.java index 13b09234eeb9..38b50fb62804 100644 --- a/app/server/appsmith-server/src/test/java/com/appsmith/server/services/CurlImporterServiceTest.java +++ b/app/server/appsmith-server/src/test/java/com/appsmith/server/services/CurlImporterServiceTest.java @@ -91,6 +91,42 @@ public void lexerTests() { .isEqualTo(List.of("curl", "-H", "X-Something: something \"quoted\" else", "http://httpbin.org/get")); assertThat(curlImporterService.lex("curl -H \"X-Something: something \\\\\\\"quoted\\\" else\" http://httpbin.org/get")) .isEqualTo(List.of("curl", "-H", "X-Something: something \\\"quoted\" else", "http://httpbin.org/get")); + // The following tests are meant for cases when any of the components have nested quotes within them + // In this example, the header argument is surrounded by single quotes, the value for it is surrounded by double quotes, + // and the contents of the value has two single quotes + assertThat(curlImporterService.lex("curl -H 'X-Something: \"something '\\''quoted with nesting'\\'' else\"' http://httpbin.org/get")) + .isEqualTo(List.of("curl", "-H", "X-Something: \"something 'quoted with nesting' else\"", "http://httpbin.org/get")); + // In this example, the header argument is surrounded by single quotes, the value for it is surrounded by double quotes, + // and the contents of the value has one single quote + assertThat(curlImporterService.lex("curl -H 'X-Something: \"something '\\''ed with nesting else\"' http://httpbin.org/get")) + .isEqualTo(List.of("curl", "-H", "X-Something: \"something 'ed with nesting else\"", "http://httpbin.org/get")); + + // In the following test, we're simulating a subshell. This subshell call is outside of quotes + try { + curlImporterService.lex("curl -H 'X-Something: \"something '$(echo test)' quoted with nesting else\"' http://httpbin.org/get"); + } catch (Exception e) { + assertThat(e).isInstanceOf(AppsmithException.class); + assertThat(e.getMessage()).isEqualTo(AppsmithError.GENERIC_BAD_REQUEST.getMessage("Please do not try to invoke a subshell in the cURL")); + } + try { + curlImporterService.lex("curl -H 'X-Something: \"something '`echo test`' quoted with nesting else\"' http://httpbin.org/get"); + } catch (Exception e) { + assertThat(e).isInstanceOf(AppsmithException.class); + assertThat(e.getMessage()).isEqualTo(AppsmithError.GENERIC_BAD_REQUEST.getMessage("Please do not try to invoke a subshell in the cURL")); + } + // In the following test, we're simulating a subshell. Subshells can be inside double-quoted strings as well + try { + curlImporterService.lex("curl -H \"X-Something: 'something $(echo test) quoted with nesting else'\" http://httpbin.org/get"); + } catch (Exception e) { + assertThat(e).isInstanceOf(AppsmithException.class); + assertThat(e.getMessage()).isEqualTo(AppsmithError.GENERIC_BAD_REQUEST.getMessage("Please do not try to invoke a subshell in the cURL")); + } + try { + curlImporterService.lex("curl -H \"X-Something: 'something `echo test` quoted with nesting else'\" http://httpbin.org/get"); + } catch (Exception e) { + assertThat(e).isInstanceOf(AppsmithException.class); + assertThat(e.getMessage()).isEqualTo(AppsmithError.GENERIC_BAD_REQUEST.getMessage("Please do not try to invoke a subshell in the cURL")); + } } @Test @@ -265,6 +301,7 @@ public void urlInSingleQuotes() throws AppsmithException { assertThat(actionConfiguration.getBody()).isNullOrEmpty(); } + @Test public void missingMethod() throws AppsmithException { String command = "curl http://localhost:8080/scrap/api";
eaa9d783df42fe69231c79b172047da559e658fa
2021-09-19 12:45:08
Trisha Anand
fix: Datasource structure command failure for Google Sheets (#7595)
false
Datasource structure command failure for Google Sheets (#7595)
fix
diff --git a/app/server/appsmith-plugins/googleSheetsPlugin/src/main/java/com/external/plugins/GoogleSheetsPlugin.java b/app/server/appsmith-plugins/googleSheetsPlugin/src/main/java/com/external/plugins/GoogleSheetsPlugin.java index dad3831a1dc1..bc6247a10b12 100644 --- a/app/server/appsmith-plugins/googleSheetsPlugin/src/main/java/com/external/plugins/GoogleSheetsPlugin.java +++ b/app/server/appsmith-plugins/googleSheetsPlugin/src/main/java/com/external/plugins/GoogleSheetsPlugin.java @@ -276,7 +276,7 @@ public Mono<ActionExecutionResult> getDatasourceMetadata(List<Property> pluginSp DatasourceConfiguration datasourceConfiguration) { ActionConfiguration actionConfiguration = new ActionConfiguration(); actionConfiguration.setPluginSpecifiedTemplates(pluginSpecifiedTemplates); - return execute(null, datasourceConfiguration, actionConfiguration); + return executeCommon(null, datasourceConfiguration, actionConfiguration); } @Override
997326774b6d8ada14072625fe35ce493c63ece8
2024-03-19 12:52:32
Nirmal Sarswat
chore: Add after delete hook for Appsmith AI datasource (#31466)
false
Add after delete hook for Appsmith AI datasource (#31466)
chore
diff --git a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/plugins/PluginExecutor.java b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/plugins/PluginExecutor.java index 52d0d2da3737..d912594f4a5a 100644 --- a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/plugins/PluginExecutor.java +++ b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/plugins/PluginExecutor.java @@ -178,6 +178,13 @@ default Mono<DatasourceStorage> preSaveHook(DatasourceStorage datasourceStorage) return Mono.just(datasourceStorage); } + /** + * This function is being called as a hook after deleting a datasource. + */ + default Mono<DatasourceStorage> preDeleteHook(DatasourceStorage datasourceStorage) { + return Mono.just(datasourceStorage); + } + /** * This function fetches the structure of the tables/collections in the datasource. It's used to make query creation * easier for the user. diff --git a/app/server/appsmith-plugins/appsmithAiPlugin/src/main/java/com/external/plugins/AppsmithAiPlugin.java b/app/server/appsmith-plugins/appsmithAiPlugin/src/main/java/com/external/plugins/AppsmithAiPlugin.java index 2e4829a04dda..5d44245d8fa6 100644 --- a/app/server/appsmith-plugins/appsmithAiPlugin/src/main/java/com/external/plugins/AppsmithAiPlugin.java +++ b/app/server/appsmith-plugins/appsmithAiPlugin/src/main/java/com/external/plugins/AppsmithAiPlugin.java @@ -204,17 +204,31 @@ public Set<String> validateDatasource(DatasourceConfiguration datasourceConfigur @Override public Mono<DatasourceStorage> preSaveHook(DatasourceStorage datasourceStorage) { + return aiServerService + .associateDatasource(createAssociateDTO(datasourceStorage)) + .thenReturn(datasourceStorage); + } + + @Override + public Mono<DatasourceStorage> preDeleteHook(DatasourceStorage datasourceStorage) { DatasourceConfiguration datasourceConfiguration = datasourceStorage.getDatasourceConfiguration(); - String datasourceId = datasourceStorage.getDatasourceId(); - String workspaceId = datasourceStorage.getWorkspaceId(); if (hasFiles(datasourceConfiguration)) { - AssociateDTO associateDTO = new AssociateDTO(); - associateDTO.setWorkspaceId(workspaceId); - associateDTO.setDatasourceId(datasourceId); - associateDTO.setFileIds(getFileIds(datasourceConfiguration)); - return aiServerService.associateDatasource(associateDTO).thenReturn(datasourceStorage); + return aiServerService + .disassociateDatasource(createAssociateDTO(datasourceStorage)) + .thenReturn(datasourceStorage); } - return super.preSaveHook(datasourceStorage); + return super.preDeleteHook(datasourceStorage); + } + + private AssociateDTO createAssociateDTO(DatasourceStorage datasourceStorage) { + DatasourceConfiguration datasourceConfiguration = datasourceStorage.getDatasourceConfiguration(); + String datasourceId = datasourceStorage.getDatasourceId(); + String workspaceId = datasourceStorage.getWorkspaceId(); + AssociateDTO associateDTO = new AssociateDTO(); + associateDTO.setWorkspaceId(workspaceId); + associateDTO.setDatasourceId(datasourceId); + associateDTO.setFileIds(getFileIds(datasourceConfiguration)); + return associateDTO; } } } diff --git a/app/server/appsmith-plugins/appsmithAiPlugin/src/main/java/com/external/plugins/services/AiServerService.java b/app/server/appsmith-plugins/appsmithAiPlugin/src/main/java/com/external/plugins/services/AiServerService.java index c81fc660804d..1a6c59d50d21 100644 --- a/app/server/appsmith-plugins/appsmithAiPlugin/src/main/java/com/external/plugins/services/AiServerService.java +++ b/app/server/appsmith-plugins/appsmithAiPlugin/src/main/java/com/external/plugins/services/AiServerService.java @@ -14,6 +14,10 @@ public interface AiServerService { * Notify AI server about new datasource creation along with file context if provided */ Mono<Void> associateDatasource(AssociateDTO associateDTO); + /** + * Notify AI server about datasource deletion along with file context if provided + */ + Mono<Void> disassociateDatasource(AssociateDTO associateDTO); Mono<FileStatusDTO> getFilesStatus(List<String> fileIds, SourceDetails sourceDetails); diff --git a/app/server/appsmith-plugins/appsmithAiPlugin/src/main/java/com/external/plugins/services/AiServerServiceImpl.java b/app/server/appsmith-plugins/appsmithAiPlugin/src/main/java/com/external/plugins/services/AiServerServiceImpl.java index 0c1282a96fe9..768b0a97124d 100644 --- a/app/server/appsmith-plugins/appsmithAiPlugin/src/main/java/com/external/plugins/services/AiServerServiceImpl.java +++ b/app/server/appsmith-plugins/appsmithAiPlugin/src/main/java/com/external/plugins/services/AiServerServiceImpl.java @@ -43,6 +43,21 @@ public Mono<Void> associateDatasource(AssociateDTO associateDTO) { .then(); } + @Override + public Mono<Void> disassociateDatasource(AssociateDTO associateDTO) { + URI uri = RequestUtils.getAssociateUri(); + String jsonBody = gson.toJson(associateDTO); + + return RequestUtils.makeRequest( + HttpMethod.DELETE, + uri, + MediaType.APPLICATION_JSON, + new HashMap<>(), + BodyInserters.fromValue(jsonBody)) + .flatMap(RequestUtils::handleResponse) + .then(); + } + @Override public Mono<FileStatusDTO> getFilesStatus(List<String> fileIds, SourceDetails sourceDetails) { Map<String, Object> body = new HashMap<>(); diff --git a/app/server/appsmith-plugins/appsmithAiPlugin/src/main/java/com/external/plugins/utils/FileUtils.java b/app/server/appsmith-plugins/appsmithAiPlugin/src/main/java/com/external/plugins/utils/FileUtils.java index 537d741a6caf..9f224b4deec2 100644 --- a/app/server/appsmith-plugins/appsmithAiPlugin/src/main/java/com/external/plugins/utils/FileUtils.java +++ b/app/server/appsmith-plugins/appsmithAiPlugin/src/main/java/com/external/plugins/utils/FileUtils.java @@ -21,12 +21,13 @@ public static boolean hasFiles(DatasourceConfiguration datasourceConfiguration) public static List<String> getFileIds(DatasourceConfiguration datasourceConfiguration) { if (datasourceConfiguration.getProperties() != null && datasourceConfiguration.getProperties().size() > 0) { - Property fileProperty = datasourceConfiguration.getProperties().get(0); - if (fileProperty.getKey().equalsIgnoreCase(FILES) - && fileProperty.getValue() != null - && fileProperty.getValue() instanceof List) { - List<FileMetadataDTO> files = convertIntoFiles((List<Map<String, Object>>) fileProperty.getValue()); - return files.stream().map(FileMetadataDTO::getId).toList(); + for (Property property : datasourceConfiguration.getProperties()) { + if (property.getKey().equalsIgnoreCase(FILES) + && property.getValue() != null + && property.getValue() instanceof List) { + List<FileMetadataDTO> files = convertIntoFiles((List<Map<String, Object>>) property.getValue()); + return files.stream().map(FileMetadataDTO::getId).toList(); + } } } return List.of(); diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/datasources/base/DatasourceServiceCEImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/datasources/base/DatasourceServiceCEImpl.java index 3ffd62a9996d..524878ce82e5 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/datasources/base/DatasourceServiceCEImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/datasources/base/DatasourceServiceCEImpl.java @@ -830,6 +830,20 @@ public Mono<Datasource> archiveById(String id) { .deleteDatasourceContext(datasourceStorage) .then(datasourceStorageService.archive(datasourceStorage)); }) + .flatMap(datasourceStorage -> { + if (!StringUtils.hasText(toDelete.getPluginId())) { + log.error("Plugin id is missing in datasource, skipping pre-delete hook execution"); + return Mono.just(datasourceStorage); + } + Mono<PluginExecutor> pluginExecutorMono = findPluginExecutor(toDelete.getPluginId()); + return pluginExecutorMono + .flatMap(pluginExecutor -> ((PluginExecutor<Object>) pluginExecutor) + .preDeleteHook(datasourceStorage)) + .onErrorResume(error -> { + log.error("Error occurred while executing after delete hook", error); + return Mono.just(datasourceStorage); + }); + }) .then(repository.archive(toDelete)) .thenReturn(toDelete); }) @@ -841,6 +855,14 @@ public Mono<Datasource> archiveById(String id) { }); } + private Mono<PluginExecutor> findPluginExecutor(String pluginId) { + final Mono<Plugin> pluginMono = pluginService.findById(pluginId).cache(); + return pluginExecutorHelper + .getPluginExecutor(pluginMono) + .switchIfEmpty( + Mono.error(new AppsmithException(AppsmithError.NO_RESOURCE_FOUND, FieldName.PLUGIN, pluginId))); + } + /** * Sets isRecentlyCreated flag to the datasources that were created recently. * It finds the most recent `recentlyUsedCount` numbers of datasources based on the `createdAt` field and set
4a360a87a1405817ee2ffda547a6f9054f74e9b5
2023-10-18 10:55:17
Vemparala Surya Vamsi
fix: remove moment patches (#28084)
false
remove moment patches (#28084)
fix
diff --git a/app/client/cypress/e2e/Regression/ClientSide/Widgets/ListV2/ListV2_SerververSide_spec.js b/app/client/cypress/e2e/Regression/ClientSide/Widgets/ListV2/ListV2_SerververSide_spec.js index aa74bcc26d32..b0376ffe89bc 100644 --- a/app/client/cypress/e2e/Regression/ClientSide/Widgets/ListV2/ListV2_SerververSide_spec.js +++ b/app/client/cypress/e2e/Regression/ClientSide/Widgets/ListV2/ListV2_SerververSide_spec.js @@ -46,11 +46,16 @@ describe("List widget V2 Serverside Pagination", () => { it("2. Next button disabled but visible in view mode when there's no data", () => { agHelper.AssertText(commonlocators.listPaginateActivePage, "text", "1"); agHelper.GetNClick(commonlocators.listPaginateNextButton, 0, true); + cy.wait(1000); agHelper.AssertText(commonlocators.listPaginateActivePage, "text", "2"); + cy.wait(1000); agHelper.GetNClick(commonlocators.listPaginateNextButton, 0, true); + cy.wait(1000); agHelper.AssertText(commonlocators.listPaginateActivePage, "text", "3"); agHelper.AssertElementExist(commonlocators.listPaginateNextButtonDisabled); + agHelper.GetNClick(commonlocators.listPaginatePrevButton, 0, true); + cy.wait(1000); agHelper.AssertText(commonlocators.listPaginateActivePage, "text", "2"); deployMode.NavigateBacktoEditor(); diff --git a/app/client/src/workers/Evaluation/__tests__/generateOpimisedUpdates.test.ts b/app/client/src/workers/Evaluation/__tests__/generateOpimisedUpdates.test.ts index 5424a73699e6..ef23d2dd18cd 100644 --- a/app/client/src/workers/Evaluation/__tests__/generateOpimisedUpdates.test.ts +++ b/app/client/src/workers/Evaluation/__tests__/generateOpimisedUpdates.test.ts @@ -2,6 +2,7 @@ import { applyChange } from "deep-diff"; import produce from "immer"; import { range } from "lodash"; +import moment from "moment"; import { parseUpdatesAndDeleteUndefinedUpdates } from "sagas/EvaluationSaga.utils"; import { EvalErrorTypes } from "utils/DynamicBindingUtils"; @@ -109,6 +110,46 @@ describe("generateOptimisedUpdates", () => { }, ]); }); + describe("ignore invalid moment updates", () => { + test("should generate a null update when it sees an invalid moment object", () => { + const newState = produce(oldState, (draft) => { + draft.Table1.pageSize = moment("invalid value") as any; + }); + const updates = generateOptimisedUpdates(oldState, newState); + expect(updates).toEqual([ + { kind: "E", path: ["Table1", "pageSize"], lhs: 0, rhs: null }, + ]); + }); + test("should generate a regular update when it sees a valid moment object", () => { + const validMoment = moment(); + const newState = produce(oldState, (draft) => { + draft.Table1.pageSize = validMoment as any; + }); + const updates = generateOptimisedUpdates(oldState, newState); + expect(updates).toEqual([ + { kind: "E", path: ["Table1", "pageSize"], lhs: 0, rhs: validMoment }, + ]); + }); + test("should generate no diff update when prev state is already null", () => { + const prevState = produce(oldState, (draft) => { + draft.Table1.pageSize = null as any; + draft.Table1.triggerRowSelection = undefined as any; + }); + const newState = produce(oldState, (draft) => { + draft.Table1.pageSize = moment("invalid value") as any; + draft.Table1.triggerRowSelection = moment("invalid value") as any; + }); + const updates = generateOptimisedUpdates(prevState, newState); + expect(updates).toEqual([ + { + kind: "E", + path: ["Table1", "triggerRowSelection"], + lhs: undefined, + rhs: null, + }, + ]); + }); + }); }); describe("diffs with identicalEvalPathsPatches", () => { diff --git a/app/client/src/workers/Evaluation/helpers.ts b/app/client/src/workers/Evaluation/helpers.ts index be22577896e2..4915b9245645 100644 --- a/app/client/src/workers/Evaluation/helpers.ts +++ b/app/client/src/workers/Evaluation/helpers.ts @@ -4,6 +4,7 @@ import { diff } from "deep-diff"; import type { DataTree } from "entities/DataTree/dataTreeTypes"; import equal from "fast-deep-equal"; import { get, isNumber, isObject } from "lodash"; +import { isMoment } from "moment"; import { EvalErrorTypes } from "utils/DynamicBindingUtils"; export interface DiffReferenceState { @@ -201,6 +202,20 @@ const generateDiffUpdates = ( const lhs = get(oldDataTree, segmentedPath); + //convert all invalid moment objects to nulls ... + //large collect nodes are anyway getting serialised so the invalid objects will be converted to nulls + if (isMoment(rhs) && !rhs.isValid()) { + if (lhs === undefined || lhs !== null) { + attachDirectly.push({ + kind: "E", + lhs, + rhs: null as any, + path: segmentedPath, + }); + } + // ignore invalid moment objects + return true; + } if (rhs === undefined) { //if an undefined value is being set it should be a delete if (lhs !== undefined) {
d1a586e0bb80b65fb444600615c3793cbd1b5c7a
2024-07-30 12:11:27
Rajat Agrawal
ci: Add pre push hook to not allow ee changes in ce (#35276)
false
Add pre push hook to not allow ee changes in ce (#35276)
ci
diff --git a/.github/workflows/client-build.yml b/.github/workflows/client-build.yml index 4dae3f6ecde4..d37853acca87 100644 --- a/.github/workflows/client-build.yml +++ b/.github/workflows/client-build.yml @@ -227,6 +227,7 @@ jobs: reponame: ${{ github.event.repository.name }} gituser: ${{ secrets.CACHE_GIT_USER }} gituseremail: ${{ secrets.CACHE_GIT_EMAIL }} + # git lfs update --force in the script below overrides appsmith git hooks with git lfs hooks since appsmith hooks are not required during workflow runs run: | pwd mkdir cacherepo @@ -234,6 +235,7 @@ jobs: git config --global user.email "$gituseremail" git config --global user.name "$gituser" git clone https://[email protected]/appsmithorg/cibuildcache.git + git lfs update --force git lfs install cd cibuildcache/ if [ "$reponame" = "appsmith" ]; then export repodir="CE"; fi diff --git a/app/client/.husky/pre-push b/app/client/.husky/pre-push new file mode 100755 index 000000000000..7eb289f2e40e --- /dev/null +++ b/app/client/.husky/pre-push @@ -0,0 +1,95 @@ +#!/bin/bash + +echo "Pre push hook called" + +# An example hook script to verify what is about to be pushed. Called by "git +# push" after it has checked the remote status, but before anything has been +# pushed. If this script exits with a non-zero status nothing will be pushed. +# +# This hook is called with the following parameters: +# +# $1 -- Name of the remote to which the push is being done +# $2 -- URL to which the push is being done +# +# If pushing without using a named remote those arguments will be equal. +# +# Information about the commits which are being pushed is supplied as lines to +# the standard input in the form: +# +# <local ref> <local oid> <remote ref> <remote oid> + +appsmith_ee_url="appsmith-ee.git" +appsmith_ce_url="appsmithorg/appsmith.git" + +# Define the null SHA. +null_sha="0000000000000000000000000000000000000000" + +# Function to get list of files between two commits +do_commits_contain_ee_files() { + # Store the commit hashes + from_commit=$1 + to_commit=$2 + string_to_match="app/client/src/ee" + + # to_commit sha can be null if a branch is being pushed for the first to remote + # In that case, we would need to compare the diff against a default branch, like release. + if [ "$to_commit" == "$null_sha" ]; then + echo "comparing changes against release" + + remote_name=$(git remote -v | grep -i $appsmith_ce_url | grep -i fetch | awk '{print $1}') + echo "remote name is $remote_name" + + git fetch $remote_name release + to_commit=$remote_name/release + fi + + echo "to_commit in function is $to_commit" + echo "from_commit is $from_commit" + + # Get the list of files between the two commits + files=$(git diff --name-only $from_commit $to_commit) + + # Iterate over each file + for file in $files; do + # Check if the file path contains the string + if [[ "$file" == *"$string_to_match"* ]]; then + echo "File '$file' matches the string '$string_to_match'" + return 0 + fi + done + return 1 +} + + +remote="$1" +url="$2" + +echo "URL is $url" +echo "remote is $remote" +echo "remote sha is $remote_sha" + +if [[ "$url" == *"$appsmith_ee_url"* ]]; then + echo "Hook invoked on EE repo. Ignoring pre-push hook checks" + exit 0 +fi + +while read local_ref local_sha remote_ref remote_sha +do + echo "pushing from $local_sha to $remote_sha" + echo "local ref is " $local_ref + echo "remote ref is " $remote_ref + + if [ "$local_sha" == "$null_sha" ]; then + echo "Branch is being deleted. Allow push" + exit 0 + fi + + if do_commits_contain_ee_files $local_sha $remote_sha + then + echo -e "Found EE changes in the commits\n" + exit 1 + else + echo -e "Didn't find ee changes in the commits\n" + exit 0 + fi +done \ No newline at end of file
ddefab73060a569be9d2c3efd6fb5eb1434a0c50
2024-05-20 17:22:22
Arpit Mohan
ci: Adding the overwrite: true parameter to actions/upload-artifact@v4 command (#33593)
false
Adding the overwrite: true parameter to actions/upload-artifact@v4 command (#33593)
ci
diff --git a/.github/workflows/build-client-server.yml b/.github/workflows/build-client-server.yml index be764f610389..52253d4d03b4 100644 --- a/.github/workflows/build-client-server.yml +++ b/.github/workflows/build-client-server.yml @@ -220,6 +220,7 @@ jobs: with: name: combined_failed_spec_ci path: ~/combined_failed_spec_ci + overwrite: true - name: Get Latest flaky Tests shell: bash @@ -337,6 +338,7 @@ jobs: with: name: combined_failed_spec_ci path: ~/combined_failed_spec_ci + overwrite: true - name: Get Latest flaky Tests shell: bash diff --git a/.github/workflows/ci-test-custom-script.yml b/.github/workflows/ci-test-custom-script.yml index cc0767916f49..f23531681026 100644 --- a/.github/workflows/ci-test-custom-script.yml +++ b/.github/workflows/ci-test-custom-script.yml @@ -368,6 +368,7 @@ jobs: with: name: cypress-console-logs path: ${{ github.workspace }}/app/client/cypress/cypress-logs + overwrite: true - name: Collect CI container logs if: failure() @@ -383,6 +384,7 @@ jobs: with: name: dockerlogs path: ~/dockerlogs + overwrite: true - name: Rename reports if: failure() @@ -396,6 +398,7 @@ jobs: with: name: results-${{github.run_attempt}} path: ~/results + overwrite: true # Set status = failedtest - name: Set fail if there are test failures @@ -420,6 +423,7 @@ jobs: with: name: server-logs-${{ matrix.job }} path: app/server/server-logs.log + overwrite: true # Set status = success - name: Save the status of the run diff --git a/.github/workflows/ci-test-hosted.yml b/.github/workflows/ci-test-hosted.yml index 0ead26b3fea2..6f2796c63a66 100644 --- a/.github/workflows/ci-test-hosted.yml +++ b/.github/workflows/ci-test-hosted.yml @@ -260,6 +260,7 @@ jobs: with: name: results-${{github.run_attempt}} path: ~/results + overwrite: true - name: Upload cypress snapshots if: failure() @@ -267,6 +268,7 @@ jobs: with: name: snapshots path: ${{ github.workspace }}/app/client/cypress/snapshots + overwrite: true # Set status = failedtest - name: Set fail if there are test failures diff --git a/.github/workflows/ci-test-limited.yml b/.github/workflows/ci-test-limited.yml index 8645cfd0ec10..25f6f04b1d9d 100644 --- a/.github/workflows/ci-test-limited.yml +++ b/.github/workflows/ci-test-limited.yml @@ -371,6 +371,7 @@ jobs: with: name: cypress-console-logs path: ${{ github.workspace }}/app/client/cypress/cypress-logs + overwrite: true - name: Upload cypress snapshots if: always() @@ -378,6 +379,7 @@ jobs: with: name: snapshots path: ${{ github.workspace }}/app/client/cypress/snapshots + overwrite: true - name: Collect CI container logs if: failure() @@ -393,6 +395,7 @@ jobs: with: name: dockerlogs path: ~/dockerlogs + overwrite: true - name: Rename reports if: failure() @@ -406,6 +409,7 @@ jobs: with: name: results-${{github.run_attempt}} path: ~/results + overwrite: true # Set status = failedtest - name: Set fail if there are test failures @@ -431,6 +435,7 @@ jobs: with: name: server-logs-${{ matrix.job }} path: app/server/server-logs.log + overwrite: true # Set status = success - name: Save the status of the run diff --git a/.github/workflows/client-build.yml b/.github/workflows/client-build.yml index d71a78aa1e6e..5619806f78c3 100644 --- a/.github/workflows/client-build.yml +++ b/.github/workflows/client-build.yml @@ -294,6 +294,7 @@ jobs: with: name: client-build path: app/client/build.tar + overwrite: true - name: Put release build in cache if: success() && github.ref == 'refs/heads/release' && (github.event_name == 'push' || github.event_name == 'workflow_dispatch' || github.event_name == 'schedule') diff --git a/.github/workflows/github-release.yml b/.github/workflows/github-release.yml index 9fe4edc313b6..bf230d050ecf 100644 --- a/.github/workflows/github-release.yml +++ b/.github/workflows/github-release.yml @@ -93,6 +93,7 @@ jobs: with: name: client-build path: app/client/build.tar + overwrite: true server-build: needs: @@ -140,6 +141,7 @@ jobs: with: name: server-build path: app/server/dist/ + overwrite: true rts-build: needs: @@ -193,6 +195,7 @@ jobs: with: name: rts-dist path: app/client/packages/rts/rts-dist.tar + overwrite: true package: needs: [prelude, client-build, server-build, rts-build] diff --git a/.github/workflows/pr-cypress.yml b/.github/workflows/pr-cypress.yml index f29916920eda..fb1fa8f50289 100644 --- a/.github/workflows/pr-cypress.yml +++ b/.github/workflows/pr-cypress.yml @@ -155,6 +155,7 @@ jobs: with: name: combined_failed_spec_ci path: ~/combined_failed_spec_ci + overwrite: true - name: Get Latest flaky Tests shell: bash diff --git a/.github/workflows/rts-build.yml b/.github/workflows/rts-build.yml index 5ad6740533a8..01d8201ac876 100644 --- a/.github/workflows/rts-build.yml +++ b/.github/workflows/rts-build.yml @@ -153,6 +153,7 @@ jobs: with: name: rts-dist path: app/client/packages/rts/rts-dist.tar + overwrite: true # Set status = success - name: Save the status of the run diff --git a/.github/workflows/server-build.yml b/.github/workflows/server-build.yml index 9c09c8aca916..6a6d8111b255 100644 --- a/.github/workflows/server-build.yml +++ b/.github/workflows/server-build.yml @@ -227,6 +227,7 @@ jobs: name: failed-server-tests path: app/server/failed-server-tests.txt if-no-files-found: ignore + overwrite: true - name: Fetch server build from cache if: steps.changed-files-specific.outputs.any_changed == 'false' && success() && github.event_name != 'push' && github.event_name != 'workflow_dispatch' && github.event_name != 'schedule' @@ -266,6 +267,7 @@ jobs: with: name: server-build path: app/server/dist/ + overwrite: true - name: Put release build in cache if: success() && github.ref == 'refs/heads/release' && (github.event_name == 'push' || github.event_name == 'workflow_dispatch' || github.event_name == 'schedule') diff --git a/.github/workflows/test-build-docker-image.yml b/.github/workflows/test-build-docker-image.yml index 1b5efeef0d0e..b9810304a268 100644 --- a/.github/workflows/test-build-docker-image.yml +++ b/.github/workflows/test-build-docker-image.yml @@ -261,6 +261,7 @@ jobs: with: name: combined_failed_spec_ci path: ~/combined_failed_spec_ci + overwrite: true - name: Return status for ui-matrix run: |
23937901700d7798c104f7ea21e442ce49de5eaa
2022-06-28 17:53:03
Aswath K
fix: Unable to toggle JS button for table column (#14843)
false
Unable to toggle JS button for table column (#14843)
fix
diff --git a/app/client/src/components/propertyControls/BaseControl.tsx b/app/client/src/components/propertyControls/BaseControl.tsx index e4108378087e..fb1850dd690d 100644 --- a/app/client/src/components/propertyControls/BaseControl.tsx +++ b/app/client/src/components/propertyControls/BaseControl.tsx @@ -30,6 +30,12 @@ class BaseControl<P extends ControlProps, S = {}> extends Component<P, S> { static canDisplayValueInUI(config: ControlData, value: any): boolean { return false; } + + // Only applicable for JSONFormComputeControl & ComputeTablePropertyControl + // eslint-disable-next-line @typescript-eslint/no-unused-vars + static getInputComputedValue(value: string, widgetName: string): string { + return ""; + } } export interface ControlBuilder<T extends ControlProps> { diff --git a/app/client/src/components/propertyControls/ComputeTablePropertyControl.tsx b/app/client/src/components/propertyControls/ComputeTablePropertyControl.tsx index be865061cc6d..1ea4f0f5de95 100644 --- a/app/client/src/components/propertyControls/ComputeTablePropertyControl.tsx +++ b/app/client/src/components/propertyControls/ComputeTablePropertyControl.tsx @@ -95,7 +95,10 @@ class ComputeTablePropertyControl extends BaseControl< const tableId = this.props.widgetProperties.widgetName; const value = propertyValue && isDynamicValue(propertyValue) - ? this.getInputComputedValue(propertyValue, tableId) + ? ComputeTablePropertyControl.getInputComputedValue( + propertyValue, + tableId, + ) : propertyValue ? propertyValue : defaultValue; @@ -126,7 +129,7 @@ class ComputeTablePropertyControl extends BaseControl< ); } - getInputComputedValue = (propertyValue: string, tableId: string) => { + static getInputComputedValue = (propertyValue: string, tableId: string) => { const value = `${propertyValue.substring( `{{${tableId}.sanitizedTableData.map((currentRow) => ( `.length, propertyValue.length - 4, diff --git a/app/client/src/components/propertyControls/JSONFormComputeControl.tsx b/app/client/src/components/propertyControls/JSONFormComputeControl.tsx index 98a56ea7f817..8411290abdea 100644 --- a/app/client/src/components/propertyControls/JSONFormComputeControl.tsx +++ b/app/client/src/components/propertyControls/JSONFormComputeControl.tsx @@ -178,8 +178,10 @@ export const JSToString = (js: string): string => { }; class JSONFormComputeControl extends BaseControl<JSONFormComputeControlProps> { - getInputComputedValue = (propertyValue: string) => { - const { widgetName } = this.props.widgetProperties; + static getInputComputedValue = ( + propertyValue: string, + widgetName: string, + ) => { const { prefixTemplate, suffixTemplate } = getBindingTemplate(widgetName); const value = propertyValue.substring( @@ -236,7 +238,11 @@ class JSONFormComputeControl extends BaseControl<JSONFormComputeControlProps> { const value = (() => { if (propertyValue && isDynamicValue(propertyValue)) { - return this.getInputComputedValue(propertyValue); + const { widgetName } = this.props.widgetProperties; + return JSONFormComputeControl.getInputComputedValue( + propertyValue, + widgetName, + ); } return propertyValue || defaultValue; diff --git a/app/client/src/pages/Editor/PropertyPane/PropertyControl.tsx b/app/client/src/pages/Editor/PropertyPane/PropertyControl.tsx index 46791065d1ef..a57f8bd460fa 100644 --- a/app/client/src/pages/Editor/PropertyPane/PropertyControl.tsx +++ b/app/client/src/pages/Editor/PropertyPane/PropertyControl.tsx @@ -480,22 +480,39 @@ const PropertyControl = memo((props: Props) => { config.controlType, ); + const customJSControl = getCustomJSControl(); + let isToggleDisabled = false; if ( - isDynamic && // JS mode is enabled - propertyValue !== "" && // value is not empty - !canDisplayValueInUI?.(config, propertyValue) // value can't be represented in UI mode + isDynamic // JS toggle button is ON ) { - isToggleDisabled = true; - } + if ( + // Check if value is not empty + propertyValue !== undefined && + propertyValue !== "" + ) { + let value = propertyValue; + // extract out the value from binding, if there is custom JS control (Table & JSONForm widget) + if (customJSControl && isDynamicValue(value)) { + const extractValue = PropertyControlFactory.inputComputedValueMap.get( + customJSControl, + ); + if (extractValue) + value = extractValue(value, widgetProperties.widgetName); + } - // Checks if the value is same as the one defined in theme stylesheet. - if ( - typeof propertyStylesheetValue === "string" && - THEME_BINDING_REGEX.test(propertyStylesheetValue) && - propertyStylesheetValue === propertyValue - ) { - isToggleDisabled = false; + // disable button if value can't be represented in UI mode + if (!canDisplayValueInUI?.(config, value)) isToggleDisabled = true; + } + + // Enable button if the value is same as the one defined in theme stylesheet. + if ( + typeof propertyStylesheetValue === "string" && + THEME_BINDING_REGEX.test(propertyStylesheetValue) && + propertyStylesheetValue === propertyValue + ) { + isToggleDisabled = false; + } } try { @@ -571,7 +588,7 @@ const PropertyControl = memo((props: Props) => { theme: props.theme, }, isDynamic, - getCustomJSControl(), + customJSControl, additionAutocomplete, hideEvaluatedValue(), )} diff --git a/app/client/src/utils/PropertyControlFactory.tsx b/app/client/src/utils/PropertyControlFactory.tsx index 20961e7e7a48..ea2632045141 100644 --- a/app/client/src/utils/PropertyControlFactory.tsx +++ b/app/client/src/utils/PropertyControlFactory.tsx @@ -12,14 +12,20 @@ class PropertyControlFactory { ControlType, typeof BaseControl.canDisplayValueInUI > = new Map(); + static inputComputedValueMap: Map< + ControlType, + typeof BaseControl.getInputComputedValue + > = new Map(); static registerControlBuilder( controlType: ControlType, controlBuilder: ControlBuilder<ControlProps>, validationFn: typeof BaseControl.canDisplayValueInUI, + inputComputedValueFn: typeof BaseControl.getInputComputedValue, ) { this.controlMap.set(controlType, controlBuilder); this.controlUIToggleValidation.set(controlType, validationFn); + this.inputComputedValueMap.set(controlType, inputComputedValueFn); } static createControl( diff --git a/app/client/src/utils/PropertyControlRegistry.tsx b/app/client/src/utils/PropertyControlRegistry.tsx index d3ed42e918da..5074976569a0 100644 --- a/app/client/src/utils/PropertyControlRegistry.tsx +++ b/app/client/src/utils/PropertyControlRegistry.tsx @@ -20,6 +20,7 @@ class PropertyControlRegistry { }, }, Control.canDisplayValueInUI, + Control.getInputComputedValue, ); }, );
73bc0c0fc9aed1723e97c84b2970065196257f8d
2023-02-06 12:36:08
Druthi Polisetty
fix: {{appsmith.user.email}} is not available on page load (#20303)
false
{{appsmith.user.email}} is not available on page load (#20303)
fix
diff --git a/app/client/cypress/integration/Regression_TestSuite/ClientSideTests/BugTests/Bug20275_Spec.js b/app/client/cypress/integration/Regression_TestSuite/ClientSideTests/BugTests/Bug20275_Spec.js new file mode 100644 index 000000000000..5eba7d72208c --- /dev/null +++ b/app/client/cypress/integration/Regression_TestSuite/ClientSideTests/BugTests/Bug20275_Spec.js @@ -0,0 +1,41 @@ +import { ObjectsRegistry } from "../../../../support/Objects/Registry"; +import { WIDGET } from "../../../../locators/WidgetLocators"; + +const jsEditor = ObjectsRegistry.JSEditor, + agHelper = ObjectsRegistry.AggregateHelper, + deployMode = ObjectsRegistry.DeployMode, + locator = ObjectsRegistry.CommonLocators, + ee = ObjectsRegistry.EntityExplorer, + propPane = ObjectsRegistry.PropertyPane; + +describe("Testing if user.email is avaible on page load", function() { + it("Bug: 20275: {{appsmith.user.email}} is not available on page load", function() { + const JS_OBJECT_BODY = `export default{ + myFun1: ()=>{ + showAlert(appsmith.user.email) + }, + }`; + + jsEditor.CreateJSObject(JS_OBJECT_BODY, { + paste: true, + completeReplace: true, + toRun: false, + shouldCreateNewJSObj: true, + prettify: false, + }); + + jsEditor.EnableDisableAsyncFuncSettings("myFun1", true, false); + + ee.DragDropWidgetNVerify(WIDGET.TEXT, 200, 600); + ee.SelectEntityByName("Text1"); + propPane.TypeTextIntoField("Text", "{{appsmith.user.email}}"); + + deployMode.DeployApp(); + + agHelper.ValidateToastMessage(Cypress.env("USERNAME")); + + agHelper + .GetText(locator._textWidgetInDeployed) + .then(($userEmail) => expect($userEmail).to.eq(Cypress.env("USERNAME"))); + }); +}); diff --git a/app/client/cypress/support/Pages/AggregateHelper.ts b/app/client/cypress/support/Pages/AggregateHelper.ts index 70371adc492a..b8b74a766e4c 100644 --- a/app/client/cypress/support/Pages/AggregateHelper.ts +++ b/app/client/cypress/support/Pages/AggregateHelper.ts @@ -18,7 +18,7 @@ const DEFAULT_ENTERVALUE_OPTIONS = { }; export class AggregateHelper { private locator = ObjectsRegistry.CommonLocators; - public mockApiUrl = "http://host.docker.internal:5001/v1/mock-api?records=10" + public mockApiUrl = "http://host.docker.internal:5001/v1/mock-api?records=10"; public isMac = Cypress.platform === "darwin"; private selectLine = `${ this.isMac ? "{cmd}{shift}{leftArrow}" : "{shift}{home}" @@ -296,8 +296,12 @@ export class AggregateHelper { ); } - public ValidateNetworkStatus(aliasName: string, expectedStatus = 200) { - cy.wait(aliasName).should( + public ValidateNetworkStatus( + aliasName: string, + expectedStatus = 200, + timeout = 20000, + ) { + cy.wait(aliasName, { timeout: timeout }).should( "have.nested.property", "response.body.responseMeta.status", expectedStatus, diff --git a/app/client/cypress/support/Pages/GitSync.ts b/app/client/cypress/support/Pages/GitSync.ts index 986de20a69df..c806a05d7cd4 100644 --- a/app/client/cypress/support/Pages/GitSync.ts +++ b/app/client/cypress/support/Pages/GitSync.ts @@ -100,7 +100,7 @@ export class GitSync { this.agHelper.TypeText(this._gitConfigEmailInput, "[email protected]"); this.agHelper.ClickButton("CONNECT"); if (assertConnect) { - this.agHelper.ValidateNetworkStatus("@connectGitLocalRepo"); + this.agHelper.ValidateNetworkStatus("@connectGitLocalRepo", 200, 30000);//Increasing wait time for GitRepo to create in Gitea this.agHelper.AssertElementExist(this._bottomBarCommit, 0, 30000); this.CloseGitSyncModal(); } diff --git a/app/client/src/ce/sagas/userSagas.tsx b/app/client/src/ce/sagas/userSagas.tsx index 82c07be3fa13..1aef7c89756b 100644 --- a/app/client/src/ce/sagas/userSagas.tsx +++ b/app/client/src/ce/sagas/userSagas.tsx @@ -110,7 +110,6 @@ export function* createUserSaga( export function* waitForSegmentInit(skipWithAnonymousId: boolean) { if (skipWithAnonymousId && AnalyticsUtil.getAnonymousId()) return; - yield call(waitForFetchUserSuccess); const currentUser: User | undefined = yield select(getCurrentUser); const segmentState: SegmentState | undefined = yield select(getSegmentState); const appsmithConfig = getAppsmithConfigs(); @@ -165,56 +164,10 @@ export function* getCurrentUserSaga() { const isValidResponse: boolean = yield validateResponse(response); if (isValidResponse) { - //@ts-expect-error: response is of type unknown - const { enableTelemetry } = response.data; - - if (enableTelemetry) { - const promise = initializeAnalyticsAndTrackers(); - - if (promise instanceof Promise) { - const result: boolean = yield promise; - - if (result) { - yield put(segmentInitSuccess()); - } else { - yield put(segmentInitUncertain()); - } - } - } - - 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 - ) { - //@ts-expect-error: response is of type unknown - enableTelemetry && AnalyticsUtil.identifyUser(response.data); - } - - /* - * 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({ type: ReduxActionTypes.FETCH_USER_DETAILS_SUCCESS, payload: response.data, }); - - //@ts-expect-error: response is of type unknown - if (response.data.emptyInstance) { - history.replace(SETUP); - } - - PerformanceTracker.stopAsyncTracking( - PerformanceTransactionName.USER_ME_API, - ); } } catch (error) { PerformanceTracker.stopAsyncTracking( @@ -237,6 +190,50 @@ export function* getCurrentUserSaga() { } } +export function* runUserSideEffectsSaga() { + const currentUser: User = yield select(getCurrentUser); + const { enableTelemetry } = currentUser; + + if (enableTelemetry) { + const promise = initializeAnalyticsAndTrackers(); + + if (promise instanceof Promise) { + const result: boolean = yield promise; + + if (result) { + yield put(segmentInitSuccess()); + } else { + yield put(segmentInitUncertain()); + } + } + } + + if ( + //@ts-expect-error: response is of type unknown + !currentUser.isAnonymous && + currentUser.username !== ANONYMOUS_USERNAME + ) { + enableTelemetry && AnalyticsUtil.identifyUser(currentUser); + } + + /* + * Forking it as we don't want to block application flow + */ + yield fork(initiateUsageTracking, { + //@ts-expect-error: response is of type unknown + isAnonymousUser: currentUser.isAnonymous, + enableTelemetry, + }); + yield put(initAppLevelSocketConnection()); + yield put(initPageLevelSocketConnection()); + + if (currentUser.emptyInstance) { + history.replace(SETUP); + } + + PerformanceTracker.stopAsyncTracking(PerformanceTransactionName.USER_ME_API); +} + export function* forgotPasswordSaga( action: ReduxActionWithPromise<ForgotPasswordRequest>, ) { diff --git a/app/client/src/ee/sagas/userSagas.tsx b/app/client/src/ee/sagas/userSagas.tsx index 217bc74bfe5d..07d56160fc14 100644 --- a/app/client/src/ee/sagas/userSagas.tsx +++ b/app/client/src/ee/sagas/userSagas.tsx @@ -2,6 +2,7 @@ export * from "ce/sagas/userSagas"; import { createUserSaga, getCurrentUserSaga, + runUserSideEffectsSaga, forgotPasswordSaga, resetPasswordSaga, verifyResetPasswordTokenSaga, @@ -23,6 +24,10 @@ export default function* userSagas() { yield all([ takeLatest(ReduxActionTypes.CREATE_USER_INIT, createUserSaga), takeLatest(ReduxActionTypes.FETCH_USER_INIT, getCurrentUserSaga), + takeLatest( + ReduxActionTypes.FETCH_USER_DETAILS_SUCCESS, + runUserSideEffectsSaga, + ), takeLatest(ReduxActionTypes.FORGOT_PASSWORD_INIT, forgotPasswordSaga), takeLatest(ReduxActionTypes.RESET_USER_PASSWORD_INIT, resetPasswordSaga), takeLatest( diff --git a/app/client/src/entities/Engine/AppEditorEngine.ts b/app/client/src/entities/Engine/AppEditorEngine.ts index a9b14a30c16f..604a5ab14028 100644 --- a/app/client/src/entities/Engine/AppEditorEngine.ts +++ b/app/client/src/entities/Engine/AppEditorEngine.ts @@ -49,7 +49,10 @@ import AppEngine, { } from "."; import { fetchJSLibraries } from "actions/JSLibraryActions"; import CodemirrorTernService from "utils/autocomplete/CodemirrorTernService"; -import { waitForSegmentInit } from "ce/sagas/userSagas"; +import { + waitForSegmentInit, + waitForFetchUserSuccess, +} from "ce/sagas/userSagas"; export default class AppEditorEngine extends AppEngine { constructor(mode: APP_MODE) { @@ -132,6 +135,7 @@ export default class AppEditorEngine extends AppEngine { `Unable to fetch actions for the application: ${applicationId}`, ); + yield call(waitForFetchUserSuccess); yield call(waitForSegmentInit, true); yield put(fetchAllPageEntityCompletion([executePageLoadActions()])); } diff --git a/app/client/src/entities/Engine/AppViewerEngine.ts b/app/client/src/entities/Engine/AppViewerEngine.ts index 1acd304701cd..2028fa2c1b03 100644 --- a/app/client/src/entities/Engine/AppViewerEngine.ts +++ b/app/client/src/entities/Engine/AppViewerEngine.ts @@ -24,7 +24,10 @@ import PerformanceTracker, { } from "utils/PerformanceTracker"; import AppEngine, { ActionsNotFoundError, AppEnginePayload } from "."; import { fetchJSLibraries } from "actions/JSLibraryActions"; -import { waitForSegmentInit } from "ce/sagas/userSagas"; +import { + waitForSegmentInit, + waitForFetchUserSuccess, +} from "ce/sagas/userSagas"; export default class AppViewerEngine extends AppEngine { constructor(mode: APP_MODE) { @@ -107,6 +110,7 @@ export default class AppViewerEngine extends AppEngine { `Unable to fetch actions for the application: ${applicationId}`, ); + yield call(waitForFetchUserSuccess); yield call(waitForSegmentInit, true); yield put(fetchAllPageEntityCompletion([executePageLoadActions()])); }
9766775d05af45d43fe4646b5d40211b5ce42522
2024-07-08 15:40:09
Jacques Ikot
fix: hide generate page button in DSFormHeader (#34780)
false
hide generate page button in DSFormHeader (#34780)
fix
diff --git a/app/client/src/pages/Editor/DataSourceEditor/hooks.ts b/app/client/src/pages/Editor/DataSourceEditor/hooks.ts index 0fb97c875241..92dbc646e9f9 100644 --- a/app/client/src/pages/Editor/DataSourceEditor/hooks.ts +++ b/app/client/src/pages/Editor/DataSourceEditor/hooks.ts @@ -123,6 +123,10 @@ export const useShowPageGenerationOnHeader = ( const isGoogleSheetPlugin = isGoogleSheetPluginDS(plugin?.packageName); + const releaseDragDropBuildingBlocks = useFeatureFlag( + FEATURE_FLAG.release_drag_drop_building_blocks_enabled, + ); + const isPluginAllowedToPreviewData = DATASOURCES_ALLOWED_FOR_PREVIEW_MODE.includes(plugin?.name || "") || (plugin?.name === PluginName.MONGO && @@ -151,5 +155,9 @@ export const useShowPageGenerationOnHeader = ( !isPluginAllowedToPreviewData && !!generateCRUDSupportedPlugin[(datasource as Datasource).pluginId]; - return supportTemplateGeneration && canGeneratePage; + return ( + !releaseDragDropBuildingBlocks && // only show generate page button if dragging of building blocks is not enabled (product decision) + supportTemplateGeneration && + canGeneratePage + ); }; diff --git a/app/client/src/pages/Editor/DatasourceInfo/HideGeneratePageButton.test.tsx b/app/client/src/pages/Editor/DatasourceInfo/HideGeneratePageButton.test.tsx index a2b3878aa2c4..38b4c337385a 100644 --- a/app/client/src/pages/Editor/DatasourceInfo/HideGeneratePageButton.test.tsx +++ b/app/client/src/pages/Editor/DatasourceInfo/HideGeneratePageButton.test.tsx @@ -160,6 +160,36 @@ describe("GoogleSheetSchema Component", () => { }); }); +describe("DSFormHeader Component", () => { + it("1. should not render the 'generate page' button when release_drag_drop_building_blocks_enabled is enabled", () => { + (useFeatureFlag as jest.Mock).mockReturnValue(true); + const mockHistoryPush = jest.fn(); + const mockHistoryReplace = jest.fn(); + const mockHistoryLocation = { + pathname: "/", + search: "", + hash: "", + state: {}, + }; + + jest.spyOn(reactRouter, "useHistory").mockReturnValue({ + push: mockHistoryPush, + replace: mockHistoryReplace, + location: mockHistoryLocation, + }); + + jest.spyOn(reactRouter, "useLocation").mockReturnValue(mockHistoryLocation); + + renderDSFormHeader(); + + // Check that the "generate page" button is not rendered + const generatePageButton = screen.queryByText( + createMessage(DATASOURCE_GENERATE_PAGE_BUTTON), + ); + expect(generatePageButton).not.toBeInTheDocument(); + }); +}); + const mockDatasource: Datasource = { id: "667941878b418b52eb273895", userPermissions: [
fd4b6d420a5f0d6d361a12d2fb220b0d75cc3907
2025-02-06 12:12:01
Pawan Kumar
chore: update tags for key value widget (#39024)
false
update tags for key value widget (#39024)
chore
diff --git a/app/client/src/modules/ui-builder/ui/wds/WDSKeyValueWidget/widget/index.tsx b/app/client/src/modules/ui-builder/ui/wds/WDSKeyValueWidget/widget/index.tsx index ddaf0dc75399..b792de4a9eb5 100644 --- a/app/client/src/modules/ui-builder/ui/wds/WDSKeyValueWidget/widget/index.tsx +++ b/app/client/src/modules/ui-builder/ui/wds/WDSKeyValueWidget/widget/index.tsx @@ -10,7 +10,7 @@ class WDSKeyValueWidget extends WDSInputWidget { return { ...super.getConfig(), displayOrder: undefined, - tags: [WIDGET_TAGS.INPUTS], + tags: [WIDGET_TAGS.DISPLAY], name: "KeyValue", }; }
8281a1a2cee7b94ebc33809728b9939e4de23def
2023-02-17 14:12:54
Hetu Nandu
fix: modal opening issues (#20654)
false
modal opening issues (#20654)
fix
diff --git a/app/client/src/pages/Editor/Canvas.tsx b/app/client/src/pages/Editor/Canvas.tsx index 76a351fc624b..ecf4d23299b2 100644 --- a/app/client/src/pages/Editor/Canvas.tsx +++ b/app/client/src/pages/Editor/Canvas.tsx @@ -15,22 +15,18 @@ interface CanvasProps { widgetsStructure: CanvasWidgetStructure; pageId: string; canvasWidth: number; - canvasScale?: number; } const Container = styled.section<{ background: string; width: number; - $canvasScale: number; }>` background: ${({ background }) => background}; width: ${(props) => props.width}px; - transform: scale(${(props) => props.$canvasScale}); - transform-origin: "0 0"; `; const Canvas = (props: CanvasProps) => { - const { canvasScale = 1, canvasWidth } = props; + const { canvasWidth } = props; const isPreviewMode = useSelector(previewModeSelector); const selectedTheme = useSelector(getSelectedAppTheme); @@ -50,7 +46,6 @@ const Canvas = (props: CanvasProps) => { try { return ( <Container - $canvasScale={canvasScale} background={backgroundForCanvas} className="relative mx-auto t--canvas-artboard pb-52" data-testid="t--canvas-artboard" diff --git a/app/client/src/pages/Editor/WidgetsEditor/CanvasContainer.tsx b/app/client/src/pages/Editor/WidgetsEditor/CanvasContainer.tsx index bfd708cf6ca1..c9171969b361 100644 --- a/app/client/src/pages/Editor/WidgetsEditor/CanvasContainer.tsx +++ b/app/client/src/pages/Editor/WidgetsEditor/CanvasContainer.tsx @@ -7,7 +7,6 @@ import { previewModeSelector, getCanvasWidth, showCanvasTopSectionSelector, - getCanvasScale, } from "selectors/editorSelectors"; import styled from "styled-components"; import { getCanvasClassName } from "utils/generators"; @@ -64,7 +63,6 @@ function CanvasContainer() { const shouldHaveTopMargin = !isPreviewMode || pages.length > 1; const isAppThemeChanging = useSelector(getAppThemeIsChanging); const showCanvasTopSection = useSelector(showCanvasTopSectionSelector); - const canvasScale = useSelector(getCanvasScale); const isLayoutingInitialized = useDynamicAppLayout(); const isPageInitializing = isFetchingPage || !isLayoutingInitialized; @@ -91,7 +89,6 @@ function CanvasContainer() { if (!isPageInitializing && widgetsStructure) { node = ( <Canvas - canvasScale={canvasScale} canvasWidth={canvasWidth} pageId={params.pageId} widgetsStructure={widgetsStructure}
995847cdef8de1f5f99b07278f7bc03bd7243700
2022-09-23 10:46:26
Aswath K
fix: Action Selector menu goes out of viewport (#16878)
false
Action Selector menu goes out of viewport (#16878)
fix
diff --git a/app/client/src/components/editorComponents/ActionCreator/Fields.tsx b/app/client/src/components/editorComponents/ActionCreator/Fields.tsx index bc5ee4b00452..92487c27aced 100644 --- a/app/client/src/components/editorComponents/ActionCreator/Fields.tsx +++ b/app/client/src/components/editorComponents/ActionCreator/Fields.tsx @@ -29,6 +29,7 @@ import { APPSMITH_GLOBAL_FUNCTIONS, APPSMITH_NAMESPACED_FUNCTIONS, } from "./constants"; +import { PopoverPosition } from "@blueprintjs/core"; /* eslint-disable @typescript-eslint/ban-types */ /* TODO: Function and object types need to be updated to enable the lint rule */ @@ -291,8 +292,14 @@ const views = { defaultText={props.defaultText} displayValue={props.displayValue} getDefaults={props.getDefaults} + modifiers={{ + preventOverflow: { + boundariesElement: "viewport", + }, + }} onSelect={props.set as Setter} optionTree={props.options} + position={PopoverPosition.AUTO} selectedLabelModifier={props.selectedLabelModifier} selectedValue={props.get(props.value, false) as string} /> diff --git a/app/client/src/utils/ApiPaneUtils.test.ts b/app/client/src/utils/ApiPaneUtils.test.ts index 84cbe6b8c876..542d0a729015 100644 --- a/app/client/src/utils/ApiPaneUtils.test.ts +++ b/app/client/src/utils/ApiPaneUtils.test.ts @@ -1,5 +1,9 @@ import { POST_BODY_FORMAT_OPTIONS } from "constants/ApiEditorConstants/CommonApiConstants"; -import { getContentTypeHeaderValue, getIndextoUpdate, parseUrlForQueryParams } from "utils/ApiPaneUtils"; +import { + getContentTypeHeaderValue, + getIndextoUpdate, + parseUrlForQueryParams, +} from "utils/ApiPaneUtils"; describe("api pane header insertion or removal", () => { describe("index for header needs to be returned", () => { @@ -62,10 +66,12 @@ describe("API Body Format Test", () => { it("it checks whether selected body format is as per the content-type header or not", () => { const headers = [ { - "key": "Content-Type", - "value": "application/x-www-form-urlencoded" - } + key: "Content-Type", + value: "application/x-www-form-urlencoded", + }, ]; - expect(getContentTypeHeaderValue(headers)).toEqual(POST_BODY_FORMAT_OPTIONS.FORM_URLENCODED); + expect(getContentTypeHeaderValue(headers)).toEqual( + POST_BODY_FORMAT_OPTIONS.FORM_URLENCODED, + ); }); });
e2ec25bc7ceb1b0f29062356d890b1528a88b7c4
2023-12-19 18:49:39
Saroj
ci: Skip TBD for every push on release branch (#29732)
false
Skip TBD for every push on release branch (#29732)
ci
diff --git a/.github/workflows/test-build-docker-image.yml b/.github/workflows/test-build-docker-image.yml index db1b8f415b0d..1aae636f3757 100644 --- a/.github/workflows/test-build-docker-image.yml +++ b/.github/workflows/test-build-docker-image.yml @@ -7,9 +7,9 @@ on: # This line enables manual triggering of this workflow. workflow_dispatch: - # trigger for pushes to release and master + # trigger for pushes to master push: - branches: [release] + branches: [master] paths: - "app/client/**" - "app/server/**"
f45dc3baf2c4a2166166e0c465dbb2381ca6e131
2024-03-05 17:23:18
Pawan Kumar
fix: WDS Theming breaking on custom font (#31477)
false
WDS Theming breaking on custom font (#31477)
fix
diff --git a/app/client/src/pages/Editor/Canvas.tsx b/app/client/src/pages/Editor/Canvas.tsx index 11a6adb1164c..1b024f7939c3 100644 --- a/app/client/src/pages/Editor/Canvas.tsx +++ b/app/client/src/pages/Editor/Canvas.tsx @@ -9,7 +9,6 @@ import { useFeatureFlag } from "utils/hooks/useFeatureFlag"; import { combinedPreviewModeSelector } from "selectors/editorSelectors"; import { getSelectedAppTheme } from "selectors/appThemingSelectors"; import { getViewportClassName } from "layoutSystems/autolayout/utils/AutoLayoutUtils"; -import type { FontFamily } from "@design-system/theming"; import { ThemeProvider as WDSThemeProvider, useTheme, @@ -51,21 +50,18 @@ const Canvas = (props: CanvasProps) => { const isWDSEnabled = useFeatureFlag("ab_wds_enabled"); const themeSetting = useSelector(getAppThemeSettings); - const themeProps = { - borderRadius: selectedTheme.properties.borderRadius.appBorderRadius, - seedColor: selectedTheme.properties.colors.primaryColor, - fontFamily: selectedTheme.properties.fontFamily.appFont as FontFamily, - }; const wdsThemeProps = { borderRadius: themeSetting.borderRadius, seedColor: themeSetting.accentColor, colorMode: themeSetting.colorMode.toLowerCase(), - fontFamily: themeSetting.fontFamily as FontFamily, + fontFamily: themeSetting.fontFamily, userSizing: themeSetting.sizing, userDensity: themeSetting.density, iconStyle: themeSetting.iconStyle.toLowerCase(), - }; - const { theme } = useTheme(isWDSEnabled ? wdsThemeProps : themeProps); + } as Parameters<typeof useTheme>[0]; + // in case of non-WDS theme, we will pass an empty object to useTheme hook + // so that fixedLayout theme does not break because of calculations done in useTheme + const { theme } = useTheme(isWDSEnabled ? wdsThemeProps : {}); /** * background for canvas
066f4566f27ce1b607b3e64161a12de49378076c
2023-01-10 05:55:39
Anand Srinivasan
chore: Platform functions extension for EE (#19575)
false
Platform functions extension for EE (#19575)
chore
diff --git a/app/client/src/actions/focusHistoryActions.ts b/app/client/src/actions/focusHistoryActions.ts index 3a5049965dd5..37754b5279a2 100644 --- a/app/client/src/actions/focusHistoryActions.ts +++ b/app/client/src/actions/focusHistoryActions.ts @@ -1,9 +1,18 @@ import { FocusState } from "reducers/uiReducers/focusHistoryReducer"; -import { ReduxActionTypes } from "@appsmith/constants/ReduxActionConstants"; +import { + ReduxAction, + ReduxActionTypes, +} from "@appsmith/constants/ReduxActionConstants"; import { Location } from "history"; import { AppsmithLocationState } from "utils/history"; -export const routeChanged = (location: Location<AppsmithLocationState>) => { +export type RouteChangeActionPayload = { + location: Location<AppsmithLocationState>; +}; + +export const routeChanged = ( + location: Location<AppsmithLocationState>, +): ReduxAction<RouteChangeActionPayload> => { return { type: ReduxActionTypes.ROUTE_CHANGED, payload: { location }, diff --git a/app/client/src/sagas/NavigationSagas.ts b/app/client/src/ce/sagas/NavigationSagas.ts similarity index 94% rename from app/client/src/sagas/NavigationSagas.ts rename to app/client/src/ce/sagas/NavigationSagas.ts index 25cdf24f4a52..46e8316508e5 100644 --- a/app/client/src/sagas/NavigationSagas.ts +++ b/app/client/src/ce/sagas/NavigationSagas.ts @@ -1,5 +1,8 @@ -import { all, call, fork, put, select, takeEvery } from "redux-saga/effects"; -import { setFocusHistory } from "actions/focusHistoryActions"; +import { call, fork, put, select } from "redux-saga/effects"; +import { + RouteChangeActionPayload, + setFocusHistory, +} from "actions/focusHistoryActions"; import { getCurrentFocusInfo } from "selectors/focusHistorySelectors"; import { FocusState } from "reducers/uiReducers/focusHistoryReducer"; import { FocusElementsConfig } from "navigation/FocusElements"; @@ -21,10 +24,7 @@ import history, { } from "utils/history"; import AnalyticsUtil from "utils/AnalyticsUtil"; import { getRecentEntityIds } from "selectors/globalSearchSelectors"; -import { - ReduxAction, - ReduxActionTypes, -} from "ce/constants/ReduxActionConstants"; +import { ReduxAction } from "ce/constants/ReduxActionConstants"; import { getCurrentThemeDetails } from "selectors/themeSelectors"; import { BackgroundTheme, changeAppBackground } from "sagas/ThemeSaga"; import { updateRecentEntitySaga } from "sagas/GlobalSearchSagas"; @@ -38,8 +38,8 @@ function* appBackgroundHandler() { changeAppBackground(currentTheme); } -function* handleRouteChange( - action: ReduxAction<{ location: Location<AppsmithLocationState> }>, +export function* handleRouteChange( + action: ReduxAction<RouteChangeActionPayload>, ) { const { hash, pathname, state } = action.payload.location; try { @@ -84,7 +84,7 @@ function* logNavigationAnalytics(payload: { }); } -function* handlePageChange( +export function* handlePageChange( action: ReduxAction<{ pageId: string; currPath: string; @@ -318,8 +318,3 @@ function shouldStoreStateForCanvas( (currFocusEntity !== FocusEntity.CANVAS || prevPath !== currPath) ); } - -export default function* rootSaga() { - yield all([takeEvery(ReduxActionTypes.ROUTE_CHANGED, handleRouteChange)]); - yield all([takeEvery(ReduxActionTypes.PAGE_CHANGED, handlePageChange)]); -} diff --git a/app/client/src/ce/sagas/index.tsx b/app/client/src/ce/sagas/index.tsx index 68d6213f42c2..ec936baee061 100644 --- a/app/client/src/ce/sagas/index.tsx +++ b/app/client/src/ce/sagas/index.tsx @@ -37,7 +37,7 @@ import gitSyncSagas from "sagas/GitSyncSagas"; import appThemingSaga from "sagas/AppThemingSaga"; import formEvaluationChangeListener from "sagas/FormEvaluationSaga"; import SuperUserSagas from "@appsmith/sagas/SuperUserSagas"; -import NavigationSagas from "sagas/NavigationSagas"; +import NavigationSagas from "@appsmith/sagas/NavigationSagas"; import editorContextSagas from "sagas/editorContextSagas"; import PageVisibilitySaga from "sagas/PageVisibilitySagas"; import JSLibrarySaga from "sagas/JSLibrarySaga"; diff --git a/app/client/src/ce/workers/Evaluation/Actions.ts b/app/client/src/ce/workers/Evaluation/Actions.ts index c9983e7d5177..f365cad44bb8 100644 --- a/app/client/src/ce/workers/Evaluation/Actions.ts +++ b/app/client/src/ce/workers/Evaluation/Actions.ts @@ -1,17 +1,20 @@ /* eslint-disable @typescript-eslint/ban-types */ import { DataTree, DataTreeEntity } from "entities/DataTree/dataTreeFactory"; -import _, { set } from "lodash"; +import { set } from "lodash"; import { ActionDescription, ActionTriggerFunctionNames, } from "@appsmith/entities/DataTree/actionTriggers"; -import { NavigationTargetType } from "sagas/ActionExecution/NavigateActionSaga"; import { promisifyAction } from "workers/Evaluation/PromisifyAction"; -import uniqueId from "lodash/uniqueId"; import { EventType } from "constants/AppsmithActionConstants/ActionConstants"; import { isAction, isAppsmithEntity, isTrueObject } from "./evaluationUtils"; import { EvalContext } from "workers/Evaluation/evaluate"; import { ActionCalledInSyncFieldError } from "workers/Evaluation/errorModifier"; +import { + ActionDescriptionWithExecutionType, + ActionDispatcherWithExecutionType, + PLATFORM_FUNCTIONS, +} from "@appsmith/workers/Evaluation/PlatformFunctions"; declare global { /** All identifiers added to the worker global scope should also @@ -31,145 +34,6 @@ export enum ExecutionType { TRIGGER = "TRIGGER", } -export type ActionDescriptionWithExecutionType = ActionDescription & { - executionType: ExecutionType; -}; - -type ActionDispatcherWithExecutionType = ( - ...args: any[] -) => ActionDescriptionWithExecutionType; - -export const PLATFORM_FUNCTIONS: Record< - string, - ActionDispatcherWithExecutionType -> = { - navigateTo: function( - pageNameOrUrl: string, - params: Record<string, string>, - target?: NavigationTargetType, - ) { - return { - type: "NAVIGATE_TO", - payload: { pageNameOrUrl, params, target }, - executionType: ExecutionType.PROMISE, - }; - }, - showAlert: function( - message: string, - style: "info" | "success" | "warning" | "error" | "default", - ) { - return { - type: "SHOW_ALERT", - payload: { message, style }, - executionType: ExecutionType.PROMISE, - }; - }, - showModal: function(modalName: string) { - return { - type: "SHOW_MODAL_BY_NAME", - payload: { modalName }, - executionType: ExecutionType.PROMISE, - }; - }, - closeModal: function(modalName: string) { - return { - type: "CLOSE_MODAL", - payload: { modalName }, - executionType: ExecutionType.PROMISE, - }; - }, - storeValue: function(key: string, value: string, persist = true) { - // momentarily store this value in local state to support loops - _.set(self, ["appsmith", "store", key], value); - return { - type: "STORE_VALUE", - payload: { - key, - value, - persist, - uniqueActionRequestId: uniqueId("store_value_id_"), - }, - executionType: ExecutionType.PROMISE, - }; - }, - removeValue: function(key: string) { - return { - type: "REMOVE_VALUE", - payload: { key }, - executionType: ExecutionType.PROMISE, - }; - }, - clearStore: function() { - return { - type: "CLEAR_STORE", - executionType: ExecutionType.PROMISE, - payload: null, - }; - }, - download: function(data: string, name: string, type: string) { - return { - type: "DOWNLOAD", - payload: { data, name, type }, - executionType: ExecutionType.PROMISE, - }; - }, - copyToClipboard: function( - data: string, - options?: { debug?: boolean; format?: string }, - ) { - return { - type: "COPY_TO_CLIPBOARD", - payload: { - data, - options: { debug: options?.debug, format: options?.format }, - }, - executionType: ExecutionType.PROMISE, - }; - }, - resetWidget: function(widgetName: string, resetChildren = true) { - return { - type: "RESET_WIDGET_META_RECURSIVE_BY_NAME", - payload: { widgetName, resetChildren }, - executionType: ExecutionType.PROMISE, - }; - }, - setInterval: function(callback: Function, interval: number, id?: string) { - return { - type: "SET_INTERVAL", - payload: { - callback: callback?.toString(), - interval, - id, - }, - executionType: ExecutionType.TRIGGER, - }; - }, - clearInterval: function(id: string) { - return { - type: "CLEAR_INTERVAL", - payload: { - id, - }, - executionType: ExecutionType.TRIGGER, - }; - }, - postWindowMessage: function( - message: unknown, - source: string, - targetOrigin: string, - ) { - return { - type: "POST_MESSAGE", - payload: { - message, - source, - targetOrigin, - }, - executionType: ExecutionType.TRIGGER, - }; - }, -}; - const ENTITY_FUNCTIONS: Record< string, { diff --git a/app/client/src/ce/workers/Evaluation/PlatformFunctions.ts b/app/client/src/ce/workers/Evaluation/PlatformFunctions.ts new file mode 100644 index 000000000000..3107c1238efc --- /dev/null +++ b/app/client/src/ce/workers/Evaluation/PlatformFunctions.ts @@ -0,0 +1,145 @@ +/* eslint-disable @typescript-eslint/ban-types */ +import { ActionDescription } from "@appsmith/entities/DataTree/actionTriggers"; +import { ExecutionType } from "@appsmith/workers/Evaluation/Actions"; +import _ from "lodash"; +import uniqueId from "lodash/uniqueId"; +import { NavigationTargetType } from "sagas/ActionExecution/NavigateActionSaga"; + +export type ActionDescriptionWithExecutionType = ActionDescription & { + executionType: ExecutionType; +}; + +export type ActionDispatcherWithExecutionType = ( + ...args: any[] +) => ActionDescriptionWithExecutionType; + +export const PLATFORM_FUNCTIONS: Record< + string, + ActionDispatcherWithExecutionType +> = { + navigateTo: function( + pageNameOrUrl: string, + params: Record<string, string>, + target?: NavigationTargetType, + ) { + return { + type: "NAVIGATE_TO", + payload: { pageNameOrUrl, params, target }, + executionType: ExecutionType.PROMISE, + }; + }, + showAlert: function( + message: string, + style: "info" | "success" | "warning" | "error" | "default", + ) { + return { + type: "SHOW_ALERT", + payload: { message, style }, + executionType: ExecutionType.PROMISE, + }; + }, + showModal: function(modalName: string) { + return { + type: "SHOW_MODAL_BY_NAME", + payload: { modalName }, + executionType: ExecutionType.PROMISE, + }; + }, + closeModal: function(modalName: string) { + return { + type: "CLOSE_MODAL", + payload: { modalName }, + executionType: ExecutionType.PROMISE, + }; + }, + storeValue: function(key: string, value: string, persist = true) { + // momentarily store this value in local state to support loops + _.set(self, ["appsmith", "store", key], value); + return { + type: "STORE_VALUE", + payload: { + key, + value, + persist, + uniqueActionRequestId: uniqueId("store_value_id_"), + }, + executionType: ExecutionType.PROMISE, + }; + }, + removeValue: function(key: string) { + return { + type: "REMOVE_VALUE", + payload: { key }, + executionType: ExecutionType.PROMISE, + }; + }, + clearStore: function() { + return { + type: "CLEAR_STORE", + executionType: ExecutionType.PROMISE, + payload: null, + }; + }, + download: function(data: string, name: string, type: string) { + return { + type: "DOWNLOAD", + payload: { data, name, type }, + executionType: ExecutionType.PROMISE, + }; + }, + copyToClipboard: function( + data: string, + options?: { debug?: boolean; format?: string }, + ) { + return { + type: "COPY_TO_CLIPBOARD", + payload: { + data, + options: { debug: options?.debug, format: options?.format }, + }, + executionType: ExecutionType.PROMISE, + }; + }, + resetWidget: function(widgetName: string, resetChildren = true) { + return { + type: "RESET_WIDGET_META_RECURSIVE_BY_NAME", + payload: { widgetName, resetChildren }, + executionType: ExecutionType.PROMISE, + }; + }, + setInterval: function(callback: Function, interval: number, id?: string) { + return { + type: "SET_INTERVAL", + payload: { + callback: callback?.toString(), + interval, + id, + }, + executionType: ExecutionType.TRIGGER, + }; + }, + clearInterval: function(id: string) { + return { + type: "CLEAR_INTERVAL", + payload: { + id, + }, + executionType: ExecutionType.TRIGGER, + }; + }, + postWindowMessage: function( + message: unknown, + source: string, + targetOrigin: string, + ) { + return { + type: "POST_MESSAGE", + payload: { + message, + source, + targetOrigin, + }, + executionType: ExecutionType.TRIGGER, + }; + }, +}; diff --git a/app/client/src/ee/sagas/NavigationSagas.ts b/app/client/src/ee/sagas/NavigationSagas.ts new file mode 100644 index 000000000000..42746b20cbbf --- /dev/null +++ b/app/client/src/ee/sagas/NavigationSagas.ts @@ -0,0 +1,13 @@ +export * from "ce/sagas/NavigationSagas"; + +import { ReduxActionTypes } from "ce/constants/ReduxActionConstants"; +import { all, takeEvery } from "redux-saga/effects"; +import { handlePageChange, handleRouteChange } from "ce/sagas/NavigationSagas"; + +export default function* rootSaga() { + yield all([ + takeEvery(ReduxActionTypes.ROUTE_CHANGED, handleRouteChange), + takeEvery(ReduxActionTypes.PAGE_CHANGED, handlePageChange), + // EE sagas called after this + ]); +} diff --git a/app/client/src/ee/workers/Evaluation/PlatformFunctions.ts b/app/client/src/ee/workers/Evaluation/PlatformFunctions.ts new file mode 100644 index 000000000000..db2755dfa48f --- /dev/null +++ b/app/client/src/ee/workers/Evaluation/PlatformFunctions.ts @@ -0,0 +1 @@ +export * from "ce/workers/Evaluation/PlatformFunctions"; diff --git a/app/client/src/workers/Evaluation/evaluate.ts b/app/client/src/workers/Evaluation/evaluate.ts index 5cba6f7943ba..6ff1f738e3ae 100644 --- a/app/client/src/workers/Evaluation/evaluate.ts +++ b/app/client/src/workers/Evaluation/evaluate.ts @@ -18,10 +18,8 @@ import { import { DOM_APIS } from "./SetupDOM"; import { JSLibraries, libraryReservedIdentifiers } from "../common/JSLibrary"; import { errorModifier, FoundPromiseInSyncEvalError } from "./errorModifier"; -import { - PLATFORM_FUNCTIONS, - addDataTreeToContext, -} from "@appsmith/workers/Evaluation/Actions"; +import { addDataTreeToContext } from "@appsmith/workers/Evaluation/Actions"; +import { PLATFORM_FUNCTIONS } from "@appsmith/workers/Evaluation/PlatformFunctions"; export type EvalResult = { result: any;
5d47001dbae8427dc8c74fc4d9b418d3fc527597
2024-03-26 14:09:35
Rishabh Rathod
chore: Prepared statement description changes (#32042)
false
Prepared statement description changes (#32042)
chore
diff --git a/app/client/src/components/editorComponents/PartialImportExport/PartialExportModal/unitTestUtils.ts b/app/client/src/components/editorComponents/PartialImportExport/PartialExportModal/unitTestUtils.ts index 69735e21e825..d417c0995396 100644 --- a/app/client/src/components/editorComponents/PartialImportExport/PartialExportModal/unitTestUtils.ts +++ b/app/client/src/components/editorComponents/PartialImportExport/PartialExportModal/unitTestUtils.ts @@ -9769,7 +9769,7 @@ export const defaultAppState = { }, { label: "Use Prepared Statement", - info: "Turning on Prepared Statement makes your queries resilient against bad things like SQL injections. However, it cannot be used if your dynamic binding contains any SQL keywords like 'SELECT', 'WHERE', 'AND', etc.", + info: "Prepared statements prevent SQL injections on your queries but do not support dynamic bindings outside values in your SQL", configProperty: "actionConfiguration.pluginSpecifiedTemplates[0].value", controlType: "SWITCH", @@ -10085,7 +10085,7 @@ export const defaultAppState = { { label: "Use Prepared Statement", subtitle: - "Turning on Prepared Statement makes your queries resilient against bad things like SQL injections. However, it cannot be used if your dynamic binding contains any SQL keywords like 'SELECT', 'WHERE', 'AND', etc.", + "Prepared statements prevent SQL injections on your queries but do not support dynamic bindings outside values in your SQL", configProperty: "actionConfiguration.pluginSpecifiedTemplates[0].value", controlType: "SWITCH", diff --git a/app/client/src/pages/Editor/SaaSEditor/__data__/FinalState.json b/app/client/src/pages/Editor/SaaSEditor/__data__/FinalState.json index b6f5a2aac969..3522a2917880 100644 --- a/app/client/src/pages/Editor/SaaSEditor/__data__/FinalState.json +++ b/app/client/src/pages/Editor/SaaSEditor/__data__/FinalState.json @@ -1289,7 +1289,7 @@ }, { "label": "Use Prepared Statement", - "info": "Turning on Prepared Statement makes your queries resilient against bad things like SQL injections. However, it cannot be used if your dynamic binding contains any SQL keywords like 'SELECT', 'WHERE', 'AND', etc.", + "info": "Prepared statements prevent SQL injections on your queries but do not support dynamic bindings outside values in your SQL", "configProperty": "actionConfiguration.pluginSpecifiedTemplates[0].value", "controlType": "SWITCH", "initialValue": true @@ -2590,7 +2590,7 @@ }, { "label": "Use Prepared Statement", - "info": "Turning on Prepared Statement makes your queries resilient against bad things like SQL injections. However, it cannot be used if your dynamic binding contains any SQL keywords like 'SELECT', 'WHERE', 'AND', etc.", + "info": "Prepared statements prevent SQL injections on your queries but do not support dynamic bindings outside values in your SQL", "configProperty": "actionConfiguration.pluginSpecifiedTemplates[0].value", "controlType": "SWITCH", "initialValue": true diff --git a/app/client/src/pages/Editor/SaaSEditor/__data__/InitialState.json b/app/client/src/pages/Editor/SaaSEditor/__data__/InitialState.json index 5e63ef3b3820..238a6bae80d0 100644 --- a/app/client/src/pages/Editor/SaaSEditor/__data__/InitialState.json +++ b/app/client/src/pages/Editor/SaaSEditor/__data__/InitialState.json @@ -1288,7 +1288,7 @@ }, { "label": "Use Prepared Statement", - "info": "Turning on Prepared Statement makes your queries resilient against bad things like SQL injections. However, it cannot be used if your dynamic binding contains any SQL keywords like 'SELECT', 'WHERE', 'AND', etc.", + "info": "Prepared statements prevent SQL injections on your queries but do not support dynamic bindings outside values in your SQL", "configProperty": "actionConfiguration.pluginSpecifiedTemplates[0].value", "controlType": "SWITCH", "initialValue": true @@ -2589,7 +2589,7 @@ }, { "label": "Use Prepared Statement", - "info": "Turning on Prepared Statement makes your queries resilient against bad things like SQL injections. However, it cannot be used if your dynamic binding contains any SQL keywords like 'SELECT', 'WHERE', 'AND', etc.", + "info": "Prepared statements prevent SQL injections on your queries but do not support dynamic bindings outside values in your SQL", "configProperty": "actionConfiguration.pluginSpecifiedTemplates[0].value", "controlType": "SWITCH", "initialValue": true diff --git a/app/client/test/factories/MockPluginsState.ts b/app/client/test/factories/MockPluginsState.ts index 586ccacecb86..a9c82f1d7088 100644 --- a/app/client/test/factories/MockPluginsState.ts +++ b/app/client/test/factories/MockPluginsState.ts @@ -6927,7 +6927,7 @@ export default { }, { label: "Use Prepared Statement", - info: "Turning on Prepared Statement makes your queries resilient against bad things like SQL injections. However, it cannot be used if your dynamic binding contains any SQL keywords like 'SELECT', 'WHERE', 'AND', etc.", + info: "Prepared statements prevent SQL injections on your queries but do not support dynamic bindings outside values in your SQL", configProperty: "actionConfiguration.pluginSpecifiedTemplates[0].value", controlType: "SWITCH", @@ -7127,7 +7127,7 @@ export default { { label: "Use Prepared Statement", subtitle: - "Turning on Prepared Statement makes your queries resilient against bad things like SQL injections. However, it cannot be used if your dynamic binding contains any SQL keywords like 'SELECT', 'WHERE', 'AND', etc.", + "Prepared statements prevent SQL injections on your queries but do not support dynamic bindings outside values in your SQL", configProperty: "actionConfiguration.pluginSpecifiedTemplates[0].value", controlType: "SWITCH", diff --git a/app/server/appsmith-plugins/mssqlPlugin/src/main/resources/editor.json b/app/server/appsmith-plugins/mssqlPlugin/src/main/resources/editor.json index 70bd41e87e40..024c96388ae5 100644 --- a/app/server/appsmith-plugins/mssqlPlugin/src/main/resources/editor.json +++ b/app/server/appsmith-plugins/mssqlPlugin/src/main/resources/editor.json @@ -30,7 +30,7 @@ }, { "label": "Use Prepared Statement", - "info": "Turning on Prepared Statement makes your queries resilient against bad things like SQL injections. However, it cannot be used if your dynamic binding contains any SQL keywords like 'SELECT', 'WHERE', 'AND', etc.", + "info": "Prepared statements prevent SQL injections on your queries but do not support dynamic bindings outside values in your SQL", "configProperty": "actionConfiguration.pluginSpecifiedTemplates[0].value", "controlType": "SWITCH", "initialValue": true @@ -38,4 +38,4 @@ ] } ] -} \ No newline at end of file +} diff --git a/app/server/appsmith-plugins/mssqlPlugin/src/main/resources/setting.json b/app/server/appsmith-plugins/mssqlPlugin/src/main/resources/setting.json index 51484a26d59c..7474a0fc06da 100644 --- a/app/server/appsmith-plugins/mssqlPlugin/src/main/resources/setting.json +++ b/app/server/appsmith-plugins/mssqlPlugin/src/main/resources/setting.json @@ -18,7 +18,7 @@ }, { "label": "Use Prepared Statement", - "subtitle": "Turning on Prepared Statement makes your queries resilient against bad things like SQL injections. However, it cannot be used if your dynamic binding contains any SQL keywords like 'SELECT', 'WHERE', 'AND', etc.", + "subtitle": "Prepared statements prevent SQL injections on your queries but do not support dynamic bindings outside values in your SQL", "configProperty": "actionConfiguration.pluginSpecifiedTemplates[0].value", "controlType": "SWITCH", "initialValue": true diff --git a/app/server/appsmith-plugins/mysqlPlugin/src/main/resources/editor.json b/app/server/appsmith-plugins/mysqlPlugin/src/main/resources/editor.json index 70bd41e87e40..024c96388ae5 100644 --- a/app/server/appsmith-plugins/mysqlPlugin/src/main/resources/editor.json +++ b/app/server/appsmith-plugins/mysqlPlugin/src/main/resources/editor.json @@ -30,7 +30,7 @@ }, { "label": "Use Prepared Statement", - "info": "Turning on Prepared Statement makes your queries resilient against bad things like SQL injections. However, it cannot be used if your dynamic binding contains any SQL keywords like 'SELECT', 'WHERE', 'AND', etc.", + "info": "Prepared statements prevent SQL injections on your queries but do not support dynamic bindings outside values in your SQL", "configProperty": "actionConfiguration.pluginSpecifiedTemplates[0].value", "controlType": "SWITCH", "initialValue": true @@ -38,4 +38,4 @@ ] } ] -} \ No newline at end of file +} diff --git a/app/server/appsmith-plugins/mysqlPlugin/src/main/resources/setting.json b/app/server/appsmith-plugins/mysqlPlugin/src/main/resources/setting.json index 51484a26d59c..7474a0fc06da 100644 --- a/app/server/appsmith-plugins/mysqlPlugin/src/main/resources/setting.json +++ b/app/server/appsmith-plugins/mysqlPlugin/src/main/resources/setting.json @@ -18,7 +18,7 @@ }, { "label": "Use Prepared Statement", - "subtitle": "Turning on Prepared Statement makes your queries resilient against bad things like SQL injections. However, it cannot be used if your dynamic binding contains any SQL keywords like 'SELECT', 'WHERE', 'AND', etc.", + "subtitle": "Prepared statements prevent SQL injections on your queries but do not support dynamic bindings outside values in your SQL", "configProperty": "actionConfiguration.pluginSpecifiedTemplates[0].value", "controlType": "SWITCH", "initialValue": true diff --git a/app/server/appsmith-plugins/oraclePlugin/src/main/resources/editor.json b/app/server/appsmith-plugins/oraclePlugin/src/main/resources/editor.json index 6e64b32e1708..14edc4824d5b 100755 --- a/app/server/appsmith-plugins/oraclePlugin/src/main/resources/editor.json +++ b/app/server/appsmith-plugins/oraclePlugin/src/main/resources/editor.json @@ -30,7 +30,7 @@ }, { "label": "Use Prepared Statement", - "info": "Turning on Prepared Statement makes your queries resilient against bad things like SQL injections. However, it cannot be used if your dynamic binding contains any SQL keywords like 'SELECT', 'WHERE', 'AND', etc.", + "info": "Prepared statements prevent SQL injections on your queries but do not support dynamic bindings outside values in your SQL", "configProperty": "actionConfiguration.formData.preparedStatement.data", "controlType": "SWITCH", "initialValue": true @@ -38,4 +38,4 @@ ] } ] -} \ No newline at end of file +} diff --git a/app/server/appsmith-plugins/oraclePlugin/src/main/resources/setting.json b/app/server/appsmith-plugins/oraclePlugin/src/main/resources/setting.json index 38503374c30e..58fea8dc649d 100755 --- a/app/server/appsmith-plugins/oraclePlugin/src/main/resources/setting.json +++ b/app/server/appsmith-plugins/oraclePlugin/src/main/resources/setting.json @@ -18,7 +18,7 @@ }, { "label": "Use Prepared Statement", - "subtitle": "Turning on Prepared Statement makes your queries resilient against bad things like SQL injections. However, it cannot be used if your dynamic binding contains any SQL keywords like 'SELECT', 'WHERE', 'AND', etc.", + "subtitle": "Prepared statements prevent SQL injections on your queries but do not support dynamic bindings outside values in your SQL", "configProperty": "actionConfiguration.formData.preparedStatement.data", "controlType": "SWITCH", "initialValue": true diff --git a/app/server/appsmith-plugins/postgresPlugin/src/main/resources/editor.json b/app/server/appsmith-plugins/postgresPlugin/src/main/resources/editor.json index 32f522a72da8..024c96388ae5 100644 --- a/app/server/appsmith-plugins/postgresPlugin/src/main/resources/editor.json +++ b/app/server/appsmith-plugins/postgresPlugin/src/main/resources/editor.json @@ -30,7 +30,7 @@ }, { "label": "Use Prepared Statement", - "info": "Turning on Prepared Statement makes your queries resilient against bad things like SQL injections. However, it cannot be used if your dynamic binding contains any SQL keywords like 'SELECT', 'WHERE', 'AND', etc.", + "info": "Prepared statements prevent SQL injections on your queries but do not support dynamic bindings outside values in your SQL", "configProperty": "actionConfiguration.pluginSpecifiedTemplates[0].value", "controlType": "SWITCH", "initialValue": true diff --git a/app/server/appsmith-plugins/postgresPlugin/src/main/resources/setting.json b/app/server/appsmith-plugins/postgresPlugin/src/main/resources/setting.json index 51484a26d59c..7474a0fc06da 100644 --- a/app/server/appsmith-plugins/postgresPlugin/src/main/resources/setting.json +++ b/app/server/appsmith-plugins/postgresPlugin/src/main/resources/setting.json @@ -18,7 +18,7 @@ }, { "label": "Use Prepared Statement", - "subtitle": "Turning on Prepared Statement makes your queries resilient against bad things like SQL injections. However, it cannot be used if your dynamic binding contains any SQL keywords like 'SELECT', 'WHERE', 'AND', etc.", + "subtitle": "Prepared statements prevent SQL injections on your queries but do not support dynamic bindings outside values in your SQL", "configProperty": "actionConfiguration.pluginSpecifiedTemplates[0].value", "controlType": "SWITCH", "initialValue": true
9c113da2a2af73c142b678d772b86bc1a2cba7e3
2023-01-13 17:10:58
sneha122
chore: cypress tests added (#19422)
false
cypress tests added (#19422)
chore
diff --git a/app/client/cypress/integration/Smoke_TestSuite/ServerSideTests/Datasources/DSAutosaveImprovements_spec.ts b/app/client/cypress/integration/Smoke_TestSuite/ServerSideTests/Datasources/DSAutosaveImprovements_spec.ts new file mode 100644 index 000000000000..2e72cfdd53c4 --- /dev/null +++ b/app/client/cypress/integration/Smoke_TestSuite/ServerSideTests/Datasources/DSAutosaveImprovements_spec.ts @@ -0,0 +1,92 @@ +import { ObjectsRegistry } from "../../../../support/Objects/Registry"; + +const agHelper = ObjectsRegistry.AggregateHelper, + dataSources = ObjectsRegistry.DataSources; + +let dsName: any; + +describe("Datasource Autosave Improvements Tests", function() { + it("1. Test to verify that delete button is disabled when datasource is in temporary state.", () => { + dataSources.NavigateToDSCreateNew(); + agHelper.GenerateUUID(); + cy.get("@guid").then((uid) => { + dataSources.CreatePlugIn("PostgreSQL"); + dsName = "Postgres" + uid; + agHelper.RenameWithInPane(dsName, false); + // assert delete disabled + agHelper.AssertElementEnabledDisabled( + dataSources._deleteDatasourceButton, + ); + dataSources.SaveDatasource(); + cy.wait(1000); + dataSources.EditDatasource(); + // assert delete disabled + agHelper.AssertElementEnabledDisabled( + dataSources._deleteDatasourceButton, + 0, + false, + ); + agHelper.GoBack(); + agHelper.AssertElementVisible(dataSources._activeDS); + dataSources.DeleteDatasouceFromActiveTab(dsName); + }); + }); + + it("2. Test to verify that when datasource is discarded, no datasource can be seen in active list", () => { + dataSources.NavigateToDSCreateNew(); + agHelper.GenerateUUID(); + cy.get("@guid").then((uid) => { + dataSources.CreatePlugIn("PostgreSQL"); + dataSources.FillPostgresDSForm(); + dataSources.SaveDSFromDialog(false); + + // assert that datasource is not saved and cant be seen in active ds list + dataSources.NavigateToActiveTab(); + agHelper.AssertContains(dsName, "not.exist", dataSources._datasourceCard); + }); + }); + + it("3. Test to verify that when datasource is saved from discard pop, datasource can be seen in active list", () => { + dataSources.NavigateToDSCreateNew(); + agHelper.GenerateUUID(); + cy.get("@guid").then((uid) => { + dataSources.CreatePlugIn("PostgreSQL"); + + dsName = "Postgres" + uid; + agHelper.RenameWithInPane(dsName, false); + + dataSources.FillPostgresDSForm(); + dataSources.SaveDSFromDialog(true); + + // assert that datasource is saved and can be seen in active ds list + dataSources.NavigateToActiveTab(); + agHelper.AssertContains(dsName, "exist", dataSources._datasourceCard); + + // delete datasource + dataSources.DeleteDatasouceFromActiveTab(dsName); + }); + }); + + it("4. Test to verify that Editing existing datasource, state of save button when new changes are made/not made.", () => { + dataSources.NavigateToDSCreateNew(); + agHelper.GenerateUUID(); + cy.get("@guid").then((uid) => { + dataSources.CreateDataSource("Postgres"); + + // Edit Datasource, dont make new changes and check state of save + dataSources.EditDatasource(); + agHelper.AssertElementEnabledDisabled(dataSources._saveDs, 0); + + // Make new changes and check state of datasource + dataSources.FillPostgresDSForm(false, "username", "password"); + agHelper.AssertElementEnabledDisabled(dataSources._saveDs, 0, false); + dataSources.UpdateDatasource(); + + // delete datasource + cy.get("@dsName").then(($dsName) => { + dsName = $dsName; + dataSources.DeleteDatasouceFromActiveTab(dsName); + }); + }); + }); +}); diff --git a/app/client/cypress/support/Pages/AggregateHelper.ts b/app/client/cypress/support/Pages/AggregateHelper.ts index 5dd71ea9ac7c..79128f36821c 100644 --- a/app/client/cypress/support/Pages/AggregateHelper.ts +++ b/app/client/cypress/support/Pages/AggregateHelper.ts @@ -1019,6 +1019,22 @@ export class AggregateHelper { this.Sleep(); } + public AssertElementEnabledDisabled( + selector: ElementType, + index = 0, + disabled = true, + ) { + if (disabled) { + return this.GetElement(selector) + .eq(index) + .should("be.disabled"); + } else { + return this.GetElement(selector) + .eq(index) + .should("not.be.disabled"); + } + } + //Not used: // private xPathToCss(xpath: string) { // return xpath diff --git a/app/client/cypress/support/Pages/DataSources.ts b/app/client/cypress/support/Pages/DataSources.ts index c540008db203..9693d6f9005e 100644 --- a/app/client/cypress/support/Pages/DataSources.ts +++ b/app/client/cypress/support/Pages/DataSources.ts @@ -29,9 +29,9 @@ export class DataSources { private _password = "input[name = 'datasourceConfiguration.authentication.password']"; private _testDs = ".t--test-datasource"; - private _saveDs = ".t--save-datasource"; private _saveAndAuthorizeDS = ".t--save-and-authorize-datasource"; - private _datasourceCard = ".t--datasource"; + _saveDs = ".t--save-datasource"; + _datasourceCard = ".t--datasource"; _editButton = ".t--edit-datasource"; _reconnectDataSourceModal = "[data-cy=t--tab-RECONNECT_DATASOURCES]"; _closeDataSourceModal = ".t--reconnect-close-btn"; @@ -134,6 +134,7 @@ export class DataSources { public _datasourceModalSave = ".t--datasource-modal-save"; public _datasourceModalDoNotSave = ".t--datasource-modal-do-not-save"; + public _deleteDatasourceButton = ".t--delete-datasource"; public AssertViewMode() { this.agHelper.AssertElementExist(this._editButton);
3364bfd1a60f12de55c505f6802b99a97cb47bb7
2022-12-05 10:37:51
Arsalan Yaldram
chore: dependentbot vulnerabilities. (#18528)
false
dependentbot vulnerabilities. (#18528)
chore
diff --git a/app/client/package.json b/app/client/package.json index df206a2df401..aa48c8eebde7 100644 --- a/app/client/package.json +++ b/app/client/package.json @@ -126,7 +126,7 @@ "react-scripts": "^5.0.1", "react-select": "^3.0.8", "react-spring": "^9.4.0", - "react-syntax-highlighter": "^15.4.4", + "react-syntax-highlighter": "^15.5.0", "react-table": "^7.0.0", "react-tabs": "^3.0.0", "react-timer-hook": "^3.0.4", @@ -145,12 +145,11 @@ "shallowequal": "^1.1.0", "showdown": "^1.9.1", "smartlook-client": "^4.5.1", - "socket.io-client": "^4.5.1", + "socket.io-client": "^4.5.4", "styled-components": "^5.2.0", "tern": "^0.21.0", "tinycolor2": "^1.4.2", "toposort": "^2.0.2", - "ts-loader": "^6.0.4", "tslib": "^2.3.1", "typescript": "4.5.5", "unescape-js": "^1.1.4", @@ -199,7 +198,6 @@ "@types/dom-mediacapture-record": "^1.0.11", "@types/downloadjs": "^1.4.2", "@types/draft-js": "^0.11.1", - "@types/emoji-mart": "^3.0.4", "@types/jest": "^27.4.1", "@types/js-beautify": "^1.13.2", "@types/jshint": "^2.12.0", @@ -283,6 +281,7 @@ "semver": "^7.3.5", "ts-jest": "27.0.0", "ts-jest-mock-import-meta": "^0.12.0", + "ts-loader": "^9.4.1", "webpack-merge": "^5.8.0", "workbox-webpack-plugin": "^6.5.3" }, @@ -300,6 +299,8 @@ "focus-trap-react/**/tabbable": "5.2.1", "json-schema": "0.4.0", "node-fetch": "2.6.7", - "babel-plugin-styled-components": "2.0.7" + "babel-plugin-styled-components": "2.0.7", + "minimatch": "^5.0.0", + "loader-utils": "^2.0.4" } } diff --git a/app/client/yarn.lock b/app/client/yarn.lock index dfa3667836c4..d38e41a6e592 100644 --- a/app/client/yarn.lock +++ b/app/client/yarn.lock @@ -1230,7 +1230,7 @@ core-js-pure "^3.0.0" regenerator-runtime "^0.13.4" -"@babel/runtime@^7.0.0", "@babel/runtime@^7.1.2", "@babel/runtime@^7.10.2", "@babel/runtime@^7.11.2", "@babel/runtime@^7.3.1", "@babel/runtime@^7.4.2", "@babel/runtime@^7.4.4", "@babel/runtime@^7.5.5", "@babel/runtime@^7.6.3", "@babel/runtime@^7.7.2", "@babel/runtime@^7.8.4", "@babel/runtime@^7.8.7", "@babel/runtime@^7.9.2": +"@babel/runtime@^7.0.0", "@babel/runtime@^7.1.2", "@babel/runtime@^7.10.2", "@babel/runtime@^7.11.2", "@babel/runtime@^7.4.2", "@babel/runtime@^7.4.4", "@babel/runtime@^7.5.5", "@babel/runtime@^7.6.3", "@babel/runtime@^7.7.2", "@babel/runtime@^7.8.4", "@babel/runtime@^7.8.7", "@babel/runtime@^7.9.2": version "7.11.2" resolved "https://registry.npmjs.org/@babel/runtime/-/runtime-7.11.2.tgz" dependencies: @@ -1268,6 +1268,13 @@ dependencies: regenerator-runtime "^0.13.4" +"@babel/runtime@^7.3.1": + version "7.20.6" + resolved "https://registry.yarnpkg.com/@babel/runtime/-/runtime-7.20.6.tgz#facf4879bfed9b5326326273a64220f099b0fce3" + integrity sha512-Q+8MqP7TiHMWzSfwiJwXCjyf4GYA4Dgw3emg/7xmwsdLJOZUp+nMqcOwOzzYheuM1rhDu8FSj2l0aoMygEuXuA== + dependencies: + regenerator-runtime "^0.13.11" + "@babel/template@^7.10.4", "@babel/template@^7.3.3": version "7.10.4" resolved "https://registry.npmjs.org/@babel/template/-/template-7.10.4.tgz" @@ -2894,12 +2901,6 @@ "@types/react" "*" immutable "~3.7.4" -"@types/emoji-mart@^3.0.4": - version "3.0.4" - resolved "https://registry.npmjs.org/@types/emoji-mart/-/emoji-mart-3.0.4.tgz" - dependencies: - "@types/react" "*" - "@types/eslint-scope@^3.7.3": version "3.7.3" resolved "https://registry.npmjs.org/@types/eslint-scope/-/eslint-scope-3.7.3.tgz" @@ -2967,8 +2968,9 @@ "@types/node" "*" "@types/hast@^2.0.0": - version "2.3.1" - resolved "https://registry.npmjs.org/@types/hast/-/hast-2.3.1.tgz" + version "2.3.4" + resolved "https://registry.yarnpkg.com/@types/hast/-/hast-2.3.4.tgz#8aa5ef92c117d20d974a82bdfb6a648b08c0bafc" + integrity sha512-wLEm0QvaoawEDoTRwzTXp4b4jpwiJDvR5KMnFnVodm3scufTlBOWRD6N1OBf9TZMhjlNsSfcO5V+7AF4+Vy+9g== dependencies: "@types/unist" "*" @@ -3520,8 +3522,9 @@ integrity sha512-F5DIZ36YVLE+PN+Zwws4kJogq47hNgX3Nx6WyDJ3kcplxyke3XIzB8uK5n/Lpm1HBsbGzd6nmGehL8cPekP+Tg== "@types/unist@*": - version "2.0.3" - resolved "https://registry.npmjs.org/@types/unist/-/unist-2.0.3.tgz" + version "2.0.6" + resolved "https://registry.yarnpkg.com/@types/unist/-/unist-2.0.6.tgz#250a7b16c3b91f672a24552ec64678eeb1d3a08d" + integrity sha512-PBjIUxZHOuj0R15/xuwJYjFi+KZdNFrehocChv4g5hu6aFroHue8m0lBP0POdK2nKzbw0cgV1mws8+V/JAcEkQ== "@types/[email protected]": version "1.6.33" @@ -4831,17 +4834,9 @@ boolbase@^1.0.0: version "1.0.0" resolved "https://registry.npmjs.org/boolbase/-/boolbase-1.0.0.tgz" -brace-expansion@^1.1.7: - version "1.1.11" - resolved "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.11.tgz" - integrity sha512-iCuPHDFgrHX7H2vEI/5xpz07zSHB00TpugqhmYtVmMO6518mCuRMoOYFldEBl0g187ufozdaHgWKcYFb61qGiA== - dependencies: - balanced-match "^1.0.0" - concat-map "0.0.1" - brace-expansion@^2.0.1: version "2.0.1" - resolved "https://registry.npmjs.org/brace-expansion/-/brace-expansion-2.0.1.tgz" + resolved "https://registry.yarnpkg.com/brace-expansion/-/brace-expansion-2.0.1.tgz#1edc459e0f0c548486ecf9fc99f2221364b9a0ae" integrity sha512-XnAIvQ8eM+kC6aULx6wuQiwVsnzsi9d3WxzV3FpWTGA19F621kwdbsAcFKXgKUHZWsy+mY6iL1sHTxWEFCytDA== dependencies: balanced-match "^1.0.0" @@ -5056,7 +5051,7 @@ chalk@^1.1.3: strip-ansi "^3.0.0" supports-color "^2.0.0" -chalk@^2.0.0, chalk@^2.3.0, chalk@^2.4.1, chalk@^2.4.2: +chalk@^2.0.0, chalk@^2.4.1, chalk@^2.4.2: version "2.4.2" resolved "https://registry.npmjs.org/chalk/-/chalk-2.4.2.tgz" dependencies: @@ -5116,15 +5111,18 @@ char-regex@^2.0.0: character-entities-legacy@^1.0.0: version "1.1.4" - resolved "https://registry.npmjs.org/character-entities-legacy/-/character-entities-legacy-1.1.4.tgz" + resolved "https://registry.yarnpkg.com/character-entities-legacy/-/character-entities-legacy-1.1.4.tgz#94bc1845dce70a5bb9d2ecc748725661293d8fc1" + integrity sha512-3Xnr+7ZFS1uxeiUDvV02wQ+QDbc55o97tIV5zHScSPJpcLm/r0DFPcoY3tYRp+VZukxuMeKgXYmsXQHO05zQeA== character-entities@^1.0.0: version "1.2.4" - resolved "https://registry.npmjs.org/character-entities/-/character-entities-1.2.4.tgz" + resolved "https://registry.yarnpkg.com/character-entities/-/character-entities-1.2.4.tgz#e12c3939b7eaf4e5b15e7ad4c5e28e1d48c5b16b" + integrity sha512-iBMyeEHxfVnIakwOuDXpVkc54HijNgCyQB2w0VfGQThle6NXn50zU6V/u+LDhxHcDUPojn6Kpga3PTAD8W1bQw== character-reference-invalid@^1.0.0: version "1.1.4" - resolved "https://registry.npmjs.org/character-reference-invalid/-/character-reference-invalid-1.1.4.tgz" + resolved "https://registry.yarnpkg.com/character-reference-invalid/-/character-reference-invalid-1.1.4.tgz#083329cda0eae272ab3dbbf37e9a382c13af1560" + integrity sha512-mKKUkUbhPpQlCOfIuZkvSEgktjPFIsZKRRbC6KWVEMvlzblj3i3asQv5ODsrwt0N3pHAEvjP8KTQPHkp0+6jOg== charcodes@^0.2.0: version "0.2.0" @@ -5381,7 +5379,8 @@ combined-stream@^1.0.6, combined-stream@^1.0.8, combined-stream@~1.0.6: comma-separated-tokens@^1.0.0: version "1.0.8" - resolved "https://registry.npmjs.org/comma-separated-tokens/-/comma-separated-tokens-1.0.8.tgz" + resolved "https://registry.yarnpkg.com/comma-separated-tokens/-/comma-separated-tokens-1.0.8.tgz#632b80b6117867a158f1080ad498b2fbe7e3f5ea" + integrity sha512-GHuDRO12Sypu2cV70d1dkA2EUmXHgntrzbpvOB+Qy+49ypNfGgFQIC2fhhXbnyrJRynDCAARsT7Ou0M6hirpfw== [email protected]: version "2.11.0" @@ -5463,11 +5462,6 @@ compute-scroll-into-view@^1.0.16: version "1.0.16" resolved "https://registry.npmjs.org/compute-scroll-into-view/-/compute-scroll-into-view-1.0.16.tgz" [email protected]: - version "0.0.1" - resolved "https://registry.npmjs.org/concat-map/-/concat-map-0.0.1.tgz" - integrity sha1-2Klr13/Wjfd5OnMDajug1UBdR3s= - config-chain@^1.1.12: version "1.1.13" resolved "https://registry.npmjs.org/config-chain/-/config-chain-1.1.13.tgz" @@ -6608,10 +6602,10 @@ end-of-stream@^1.1.0, end-of-stream@^1.4.1: dependencies: once "^1.4.0" -engine.io-client@~6.2.1: - version "6.2.2" - resolved "https://registry.yarnpkg.com/engine.io-client/-/engine.io-client-6.2.2.tgz#c6c5243167f5943dcd9c4abee1bfc634aa2cbdd0" - integrity sha512-8ZQmx0LQGRTYkHuogVZuGSpDqYZtCM/nv8zQ68VZ+JkOpazJ7ICdsSpaO6iXwvaU30oFg5QJOJWj8zWqhbKjkQ== +engine.io-client@~6.2.3: + version "6.2.3" + resolved "https://registry.yarnpkg.com/engine.io-client/-/engine.io-client-6.2.3.tgz#a8cbdab003162529db85e9de31575097f6d29458" + integrity sha512-aXPtgF1JS3RuuKcpSrBtimSjYvrbhKW9froICH4s0F3XQWLxsKNxqzG39nnvQZQnva4CMvUK63T7shevxRyYHw== dependencies: "@socket.io/component-emitter" "~3.1.0" debug "~4.3.1" @@ -6633,13 +6627,13 @@ enhanced-resolve@^2.2.2: object-assign "^4.0.1" tapable "^0.2.3" -enhanced-resolve@^4.0.0: - version "4.3.0" - resolved "https://registry.npmjs.org/enhanced-resolve/-/enhanced-resolve-4.3.0.tgz" +enhanced-resolve@^5.0.0: + version "5.12.0" + resolved "https://registry.yarnpkg.com/enhanced-resolve/-/enhanced-resolve-5.12.0.tgz#300e1c90228f5b570c4d35babf263f6da7155634" + integrity sha512-QHTXI/sZQmko1cbDoNAa3mJ5qhWUUNAq3vR0/YiD379fWQrcfuoX1+HW2S0MTt7XmoPLapdaDKUtelUSPic7hQ== dependencies: - graceful-fs "^4.1.2" - memory-fs "^0.5.0" - tapable "^1.0.0" + graceful-fs "^4.2.4" + tapable "^2.2.0" enhanced-resolve@^5.9.3: version "5.9.3" @@ -7418,7 +7412,8 @@ fastq@^1.6.0: fault@^1.0.0: version "1.0.4" - resolved "https://registry.npmjs.org/fault/-/fault-1.0.4.tgz" + resolved "https://registry.yarnpkg.com/fault/-/fault-1.0.4.tgz#eafcfc0a6d214fc94601e170df29954a4f842f13" + integrity sha512-CJ0HCB5tL5fYTEA7ToAq5+kTwd++Borf1/bifxd9iT70QcXr4MRrO3Llf8Ifs70q+SJcGHFtnIE/Nw6giCtECA== dependencies: format "^0.2.0" @@ -7753,7 +7748,8 @@ form-data@~2.3.2: format@^0.2.0: version "0.2.2" - resolved "https://registry.npmjs.org/format/-/format-0.2.2.tgz" + resolved "https://registry.yarnpkg.com/format/-/format-0.2.2.tgz#d6170107e9efdc4ed30c9dc39016df942b5cb58b" + integrity sha512-wzsgA6WOq+09wrU1tsJ09udeR/YZRaeArL9e1wPbFg3GG2yDnC2ldKpxs4xunpFF9DgqCqOIra3bc1HWrJ37Ww== [email protected]: version "0.2.0" @@ -8248,12 +8244,14 @@ has@^1.0.3: function-bind "^1.1.1" hast-util-parse-selector@^2.0.0: - version "2.2.4" - resolved "https://registry.npmjs.org/hast-util-parse-selector/-/hast-util-parse-selector-2.2.4.tgz" + version "2.2.5" + resolved "https://registry.yarnpkg.com/hast-util-parse-selector/-/hast-util-parse-selector-2.2.5.tgz#d57c23f4da16ae3c63b3b6ca4616683313499c3a" + integrity sha512-7j6mrk/qqkSehsM92wQjdIgWM2/BW61u/53G6xmC8i1OmEdKLHbk419QKQUjz6LglWsfqoiHmyMRkP1BGjecNQ== hastscript@^6.0.0: version "6.0.0" - resolved "https://registry.npmjs.org/hastscript/-/hastscript-6.0.0.tgz" + resolved "https://registry.yarnpkg.com/hastscript/-/hastscript-6.0.0.tgz#e8768d7eac56c3fdeac8a92830d58e811e5bf640" + integrity sha512-nDM6bvd7lIqDUiYEiu5Sl/+6ReP0BMk/2f4U/Rooccxkj0P5nm+acM5PrGJ/t5I8qPGiqZSE6hVAwZEdZIvP4w== dependencies: "@types/hast" "^2.0.0" comma-separated-tokens "^1.0.0" @@ -8279,7 +8277,8 @@ headers-utils@^3.0.2: highlight.js@^10.4.1, highlight.js@~10.7.0: version "10.7.3" - resolved "https://registry.npmjs.org/highlight.js/-/highlight.js-10.7.3.tgz" + resolved "https://registry.yarnpkg.com/highlight.js/-/highlight.js-10.7.3.tgz#697272e3991356e40c3cac566a74eef681756531" + integrity sha512-tzcUFauisWKNHaRkN4Wjl/ZA07gENAjFl3J/c480dprkGTg5EQstgaNFqBfUqCq54kZRIEcreTsAgF/m2quD7A== history@^4.10.1, history@^4.9.0: version "4.10.1" @@ -8732,11 +8731,13 @@ is-absolute@^1.0.0: is-alphabetical@^1.0.0: version "1.0.4" - resolved "https://registry.npmjs.org/is-alphabetical/-/is-alphabetical-1.0.4.tgz" + resolved "https://registry.yarnpkg.com/is-alphabetical/-/is-alphabetical-1.0.4.tgz#9e7d6b94916be22153745d184c298cbf986a686d" + integrity sha512-DwzsA04LQ10FHTZuL0/grVDk4rFoVH1pjAToYwBrHSxcrBIGQuXrQMtD5U1b0U2XVgKZCTLLP8u2Qxqhy3l2Vg== is-alphanumerical@^1.0.0: version "1.0.4" - resolved "https://registry.npmjs.org/is-alphanumerical/-/is-alphanumerical-1.0.4.tgz" + resolved "https://registry.yarnpkg.com/is-alphanumerical/-/is-alphanumerical-1.0.4.tgz#7eb9a2431f855f6b1ef1a78e326df515696c4dbf" + integrity sha512-UzoZUr+XfVz3t3v4KyGEniVL9BDRoQtY7tOyrRybkVNjDFWyo1yhXNGrrBTQxp3ib9BLAWs7k2YKBQsFRkZG9A== dependencies: is-alphabetical "^1.0.0" is-decimal "^1.0.0" @@ -8817,7 +8818,8 @@ is-date-object@^1.0.1: is-decimal@^1.0.0: version "1.0.4" - resolved "https://registry.npmjs.org/is-decimal/-/is-decimal-1.0.4.tgz" + resolved "https://registry.yarnpkg.com/is-decimal/-/is-decimal-1.0.4.tgz#65a3a5958a1c5b63a706e1b333d7cd9f630d3fa5" + integrity sha512-RGdriMmQQvZ2aqaQq3awNA6dCGtKpiDFcOzrTWrDAT2MiWrKQVPmxLGHl7Y2nNu6led0kEyoX0enY0qXYsv9zw== is-directory@^0.3.1: version "0.3.1" @@ -8871,7 +8873,8 @@ is-glob@^4.0.1, is-glob@^4.0.3: is-hexadecimal@^1.0.0: version "1.0.4" - resolved "https://registry.npmjs.org/is-hexadecimal/-/is-hexadecimal-1.0.4.tgz" + resolved "https://registry.yarnpkg.com/is-hexadecimal/-/is-hexadecimal-1.0.4.tgz#cc35c97588da4bd49a8eedd6bc4082d44dcb23a7" + integrity sha512-gyPJuv83bHMpocVYoqof5VDiZveEoGoFL8m3BXNb2VW8Xs+rz9kqO8LOQ5DH6EsuvilT1ApazU0pyl+ytbPtlw== is-installed-globally@~0.4.0: version "0.4.0" @@ -10026,28 +10029,15 @@ loader-runner@^4.2.0: resolved "https://registry.npmjs.org/loader-runner/-/loader-runner-4.3.0.tgz" integrity sha512-3R/1M+yS3j5ou80Me59j7F9IMs4PXs3VqRrm0TU3AbKPxlmpoY1TNscJV/oGJXo8qCatFGTfDbY6W6ipGOYXfg== -loader-utils@^1.0.2: - version "1.4.2" - resolved "https://registry.yarnpkg.com/loader-utils/-/loader-utils-1.4.2.tgz#29a957f3a63973883eb684f10ffd3d151fec01a3" - integrity sha512-I5d00Pd/jwMD2QCduo657+YM/6L3KZu++pmX9VFncxaxvHcru9jx1lBaFft+r4Mt2jK0Yhp41XlRAihzPxHNCg== - dependencies: - big.js "^5.2.2" - emojis-list "^3.0.0" - json5 "^1.0.1" - -loader-utils@^2.0.0: - version "2.0.0" - resolved "https://registry.npmjs.org/loader-utils/-/loader-utils-2.0.0.tgz" +loader-utils@^2.0.0, loader-utils@^2.0.4, loader-utils@^3.2.0: + version "2.0.4" + resolved "https://registry.yarnpkg.com/loader-utils/-/loader-utils-2.0.4.tgz#8b5cb38b5c34a9a018ee1fc0e6a066d1dfcc528c" + integrity sha512-xXqpXoINfFhgua9xiqD8fPFHgkoq1mmmpE92WlDbm9rNRd/EbRb+Gqf908T2DMfuHjjJlksiK2RbHVOdD/MqSw== dependencies: big.js "^5.2.2" emojis-list "^3.0.0" json5 "^2.1.2" -loader-utils@^3.2.0: - version "3.2.0" - resolved "https://registry.npmjs.org/loader-utils/-/loader-utils-3.2.0.tgz" - integrity sha512-HVl9ZqccQihZ7JM85dco1MvO9G+ONvxoGa9rkhzFsneGLKSUg1gJf9bWzhRhcvm2qChhWpebQhP44qxjKIUCaQ== - localforage@^1.7.3: version "1.9.0" resolved "https://registry.npmjs.org/localforage/-/localforage-1.9.0.tgz" @@ -10269,7 +10259,8 @@ lower-case@^2.0.2: lowlight@^1.17.0: version "1.20.0" - resolved "https://registry.npmjs.org/lowlight/-/lowlight-1.20.0.tgz" + resolved "https://registry.yarnpkg.com/lowlight/-/lowlight-1.20.0.tgz#ddb197d33462ad0d93bf19d17b6c301aa3941888" + integrity sha512-8Ktj+prEb1RoCPkEOrPMYUN/nCggB7qAWe3a7OpMjWQkh3l2RD5wKRQ+o8Q8YuI9RG/xs95waaI/E6ym/7NsTw== dependencies: fault "^1.0.0" highlight.js "~10.7.0" @@ -10417,13 +10408,6 @@ memory-fs@^0.3.0: errno "^0.1.3" readable-stream "^2.0.1" -memory-fs@^0.5.0: - version "0.5.0" - resolved "https://registry.npmjs.org/memory-fs/-/memory-fs-0.5.0.tgz" - dependencies: - errno "^0.1.3" - readable-stream "^2.0.1" - [email protected]: version "1.0.1" resolved "https://registry.npmjs.org/merge-descriptors/-/merge-descriptors-1.0.1.tgz" @@ -10445,14 +10429,7 @@ micro-memoize@^4.0.10: resolved "https://registry.npmjs.org/micro-memoize/-/micro-memoize-4.0.10.tgz" integrity sha512-rk0OlvEQkShjbr2EvGn1+GdCsgLDgABQyM9ZV6VoHNU7hiNM+eSOkjGWhiNabU/XWiEalWbjNQrNO+zcqd+pEA== -micromatch@^4.0.0, micromatch@^4.0.2: - version "4.0.2" - resolved "https://registry.npmjs.org/micromatch/-/micromatch-4.0.2.tgz" - dependencies: - braces "^3.0.1" - picomatch "^2.0.5" - -micromatch@^4.0.4, micromatch@^4.0.5: +micromatch@^4.0.0, micromatch@^4.0.4, micromatch@^4.0.5: version "4.0.5" resolved "https://registry.npmjs.org/micromatch/-/micromatch-4.0.5.tgz" integrity sha512-DMy+ERcEW2q8Z2Po+WNXuw3c5YaUSFjAO5GsJqfEl7UjvtIuFKO6ZrKvcItdy98dwFI2N1tg3zNIdKaQT+aNdA== @@ -10460,6 +10437,13 @@ micromatch@^4.0.4, micromatch@^4.0.5: braces "^3.0.2" picomatch "^2.3.1" +micromatch@^4.0.2: + version "4.0.2" + resolved "https://registry.npmjs.org/micromatch/-/micromatch-4.0.2.tgz" + dependencies: + braces "^3.0.1" + picomatch "^2.0.5" + [email protected]: version "1.44.0" resolved "https://registry.npmjs.org/mime-db/-/mime-db-1.44.0.tgz" @@ -10531,29 +10515,9 @@ minimalistic-assert@^1.0.0: version "1.0.1" resolved "https://registry.npmjs.org/minimalistic-assert/-/minimalistic-assert-1.0.1.tgz" [email protected], minimatch@^3.0.3, minimatch@~3.0.2: - version "3.0.4" - resolved "https://registry.npmjs.org/minimatch/-/minimatch-3.0.4.tgz" - dependencies: - brace-expansion "^1.1.7" - [email protected]: - version "4.2.1" - resolved "https://registry.yarnpkg.com/minimatch/-/minimatch-4.2.1.tgz#40d9d511a46bdc4e563c22c3080cde9c0d8299b4" - integrity sha512-9Uq1ChtSZO+Mxa/CL1eGizn2vRn3MlLgzhT0Iz8zaY8NdvxvB0d5QdPFmCKf7JKA9Lerx5vRrnwO03jsSfGG9g== - dependencies: - brace-expansion "^1.1.7" - -minimatch@^3.0.4, minimatch@^3.1.2: - version "3.1.2" - resolved "https://registry.npmjs.org/minimatch/-/minimatch-3.1.2.tgz" - integrity sha512-J7p63hRiAjw1NDEww1W7i37+ByIrOWO5XQQAzZ3VOcL0PNybwpfmV/N05zFAzwQ9USyEcX6t3UO+K5aqBQOIHw== - dependencies: - brace-expansion "^1.1.7" - -minimatch@^5.0.1: [email protected], [email protected], minimatch@^3.0.3, minimatch@^3.0.4, minimatch@^3.1.2, minimatch@^5.0.0, minimatch@^5.0.1, minimatch@~3.0.2: version "5.1.0" - resolved "https://registry.npmjs.org/minimatch/-/minimatch-5.1.0.tgz" + resolved "https://registry.yarnpkg.com/minimatch/-/minimatch-5.1.0.tgz#1717b464f4971b144f6aabe8f2d0b8e4511e09c7" integrity sha512-9TPBGGak4nHfGZsPBohm9AWg6NoT7QTCehS3BIJABslyZbzxfV78QM2Y6+i741OPZIafFAaiiEMh5OyIrJPgtg== dependencies: brace-expansion "^2.0.1" @@ -11267,7 +11231,8 @@ parent-module@^1.0.0: parse-entities@^2.0.0: version "2.0.0" - resolved "https://registry.npmjs.org/parse-entities/-/parse-entities-2.0.0.tgz" + resolved "https://registry.yarnpkg.com/parse-entities/-/parse-entities-2.0.0.tgz#53c6eb5b9314a1f4ec99fa0fdf7ce01ecda0cbe8" + integrity sha512-kkywGpCcRYhqQIchaWqZ875wzpS/bMKhz5HnN3p7wveJTkTtyAB/AlnS0f8DFSqYW1T82t6yEAkEcB+A1I3MbQ== dependencies: character-entities "^1.0.0" character-entities-legacy "^1.0.0" @@ -12168,15 +12133,11 @@ pretty-format@^28.1.0: ansi-styles "^5.0.0" react-is "^18.0.0" -prismjs@^1.22.0, prismjs@^1.27.0: +prismjs@^1.27.0, prismjs@~1.27.0: version "1.27.0" resolved "https://registry.npmjs.org/prismjs/-/prismjs-1.27.0.tgz" integrity sha512-t13BGPUlFDR7wRB5kQDG4jjl7XeuH6jbJGt11JHPL96qwsEHNX2+68tFXqc1/k+/jALsbSWJKUOT/hcYAZ5LkA== -prismjs@~1.24.0: - version "1.24.1" - resolved "https://registry.npmjs.org/prismjs/-/prismjs-1.24.1.tgz" - process-nextick-args@~2.0.0: version "2.0.1" resolved "https://registry.npmjs.org/process-nextick-args/-/process-nextick-args-2.0.1.tgz" @@ -12243,7 +12204,8 @@ prop-types@^15.5.0, prop-types@^15.5.10, prop-types@^15.5.4, prop-types@^15.5.8, property-information@^5.0.0: version "5.6.0" - resolved "https://registry.npmjs.org/property-information/-/property-information-5.6.0.tgz" + resolved "https://registry.yarnpkg.com/property-information/-/property-information-5.6.0.tgz#61675545fb23002f245c6540ec46077d4da3ed69" + integrity sha512-YUHSPk+A30YPv+0Qf8i9Mbfe/C0hdPXk1s1jPVToV8pk8BQtpw10ct89Eo7OWkutrwqvT0eicAxlOg3dOAu8JA== dependencies: xtend "^4.0.0" @@ -13024,15 +12986,16 @@ react-spring@^9.4.0: "@react-spring/web" "~9.4.0" "@react-spring/zdog" "~9.4.0" -react-syntax-highlighter@^15.4.4: - version "15.4.4" - resolved "https://registry.npmjs.org/react-syntax-highlighter/-/react-syntax-highlighter-15.4.4.tgz" +react-syntax-highlighter@^15.5.0: + version "15.5.0" + resolved "https://registry.yarnpkg.com/react-syntax-highlighter/-/react-syntax-highlighter-15.5.0.tgz#4b3eccc2325fa2ec8eff1e2d6c18fa4a9e07ab20" + integrity sha512-+zq2myprEnQmH5yw6Gqc8lD55QHnpKaU8TOcFeC/Lg/MQSs8UknEA0JC4nTZGFAXC2J2Hyj/ijJ7NlabyPi2gg== dependencies: "@babel/runtime" "^7.3.1" highlight.js "^10.4.1" lowlight "^1.17.0" - prismjs "^1.22.0" - refractor "^3.2.0" + prismjs "^1.27.0" + refractor "^3.6.0" react-table@^7.0.0: version "7.6.0" @@ -13291,13 +13254,14 @@ redux-saga@^1.1.3: loose-envify "^1.4.0" symbol-observable "^1.2.0" -refractor@^3.2.0: - version "3.4.0" - resolved "https://registry.npmjs.org/refractor/-/refractor-3.4.0.tgz" +refractor@^3.6.0: + version "3.6.0" + resolved "https://registry.yarnpkg.com/refractor/-/refractor-3.6.0.tgz#ac318f5a0715ead790fcfb0c71f4dd83d977935a" + integrity sha512-MY9W41IOWxxk31o+YvFCNyNzdkc9M20NoZK5vq6jkv4I/uh2zkWcfudj0Q1fovjUQJrNewS9NMzeTtqPf+n5EA== dependencies: hastscript "^6.0.0" parse-entities "^2.0.0" - prismjs "~1.24.0" + prismjs "~1.27.0" regenerate-unicode-properties@^10.0.1: version "10.0.1" @@ -13325,6 +13289,11 @@ regenerator-runtime@^0.11.0: version "0.11.1" resolved "https://registry.npmjs.org/regenerator-runtime/-/regenerator-runtime-0.11.1.tgz" +regenerator-runtime@^0.13.11: + version "0.13.11" + resolved "https://registry.yarnpkg.com/regenerator-runtime/-/regenerator-runtime-0.13.11.tgz#f6dca3e7ceec20590d07ada785636a90cdca17f9" + integrity sha512-kY1AZVr2Ra+t+piVaJ4gxaFaReZVH40AKNo7UCX6W+dEwBo/2oZJzqfuN1qLq1oL45o56cPaTXELwrTh8Fpggg== + regenerator-runtime@^0.13.3, regenerator-runtime@^0.13.4: version "0.13.7" resolved "https://registry.npmjs.org/regenerator-runtime/-/regenerator-runtime-0.13.7.tgz" @@ -13784,6 +13753,13 @@ semver@^7.3.2: dependencies: lru-cache "^6.0.0" +semver@^7.3.4: + version "7.3.8" + resolved "https://registry.yarnpkg.com/semver/-/semver-7.3.8.tgz#07a78feafb3f7b32347d725e33de7e2a2df67798" + integrity sha512-NB1ctGL5rlHrPJtFDVIVzTyQylMLu9N9VICA6HSFJo8MCGVTMW6gfpicwKmmK/dAjTOrqu5l63JJOpDSrAis3A== + dependencies: + lru-cache "^6.0.0" + semver@^7.3.5: version "7.3.5" resolved "https://registry.npmjs.org/semver/-/semver-7.3.5.tgz" @@ -14033,20 +14009,20 @@ snake-case@^3.0.4: dot-case "^3.0.4" tslib "^2.0.3" -socket.io-client@^4.5.1: - version "4.5.1" - resolved "https://registry.yarnpkg.com/socket.io-client/-/socket.io-client-4.5.1.tgz#cab8da71976a300d3090414e28c2203a47884d84" - integrity sha512-e6nLVgiRYatS+AHXnOnGi4ocOpubvOUCGhyWw8v+/FxW8saHkinG6Dfhi9TU0Kt/8mwJIAASxvw6eujQmjdZVA== +socket.io-client@^4.5.4: + version "4.5.4" + resolved "https://registry.yarnpkg.com/socket.io-client/-/socket.io-client-4.5.4.tgz#d3cde8a06a6250041ba7390f08d2468ccebc5ac9" + integrity sha512-ZpKteoA06RzkD32IbqILZ+Cnst4xewU7ZYK12aS1mzHftFFjpoMz69IuhP/nL25pJfao/amoPI527KnuhFm01g== dependencies: "@socket.io/component-emitter" "~3.1.0" debug "~4.3.2" - engine.io-client "~6.2.1" - socket.io-parser "~4.2.0" + engine.io-client "~6.2.3" + socket.io-parser "~4.2.1" -socket.io-parser@~4.2.0: - version "4.2.0" - resolved "https://registry.yarnpkg.com/socket.io-parser/-/socket.io-parser-4.2.0.tgz#3f01e5bc525d94aa52a97ed5cbc12e229bbc4d6b" - integrity sha512-tLfmEwcEwnlQTxFB7jibL/q2+q8dlVQzj4JdRLJ/W/G1+Fu9VSxCx1Lo+n1HvXxKnM//dUuD0xgiA7tQf57Vng== +socket.io-parser@~4.2.1: + version "4.2.1" + resolved "https://registry.yarnpkg.com/socket.io-parser/-/socket.io-parser-4.2.1.tgz#01c96efa11ded938dcb21cbe590c26af5eff65e5" + integrity sha512-V4GrkLy+HeF1F/en3SpUaM+7XxYXpuMUWLGde1kSSh5nQMN4hLrbPIkD+otwh6q9R6NOQBN4AMaOZ2zVjui82g== dependencies: "@socket.io/component-emitter" "~3.1.0" debug "~4.3.1" @@ -14118,7 +14094,8 @@ sourcemap-codec@^1.4.4, sourcemap-codec@^1.4.8: space-separated-tokens@^1.0.0: version "1.1.5" - resolved "https://registry.npmjs.org/space-separated-tokens/-/space-separated-tokens-1.1.5.tgz" + resolved "https://registry.yarnpkg.com/space-separated-tokens/-/space-separated-tokens-1.1.5.tgz#85f32c3d10d9682007e917414ddc5c26d1aa6899" + integrity sha512-q/JSVd1Lptzhf5bkYm4ob4iWPjx0KiRe3sRFBNrVqbJkFaBm5vbbowy1mymoPNLRa52+oadOhJ+K49wsSeSjTA== spdx-correct@^3.0.0: version "3.1.1" @@ -14848,15 +14825,15 @@ [email protected]: semver "7.x" yargs-parser "20.x" -ts-loader@^6.0.4: - version "6.2.2" - resolved "https://registry.npmjs.org/ts-loader/-/ts-loader-6.2.2.tgz" +ts-loader@^9.4.1: + version "9.4.1" + resolved "https://registry.yarnpkg.com/ts-loader/-/ts-loader-9.4.1.tgz#b6f3d82db0eac5a8295994f8cb5e4940ff6b1060" + integrity sha512-384TYAqGs70rn9F0VBnh6BPTfhga7yFNdC5gXbQpDrBj9/KsT4iRkGqKXhziofHOlE2j6YEaiTYVGKKvPhGWvw== dependencies: - chalk "^2.3.0" - enhanced-resolve "^4.0.0" - loader-utils "^1.0.2" + chalk "^4.1.0" + enhanced-resolve "^5.0.0" micromatch "^4.0.0" - semver "^6.0.0" + semver "^7.3.4" ts-node@^10.7.0: version "10.9.1" @@ -15857,6 +15834,7 @@ xmlchars@^2.2.0: xmlhttprequest-ssl@~2.0.0: version "2.0.0" resolved "https://registry.yarnpkg.com/xmlhttprequest-ssl/-/xmlhttprequest-ssl-2.0.0.tgz#91360c86b914e67f44dce769180027c0da618c67" + integrity sha512-QKxVRxiRACQcVuQEYFsI1hhkrMlrXHPegbbd1yn9UHOmRxY+si12nQYzri3vbzt8VdTTRviqcKxcyllFas5z2A== xtend@^4.0.0, xtend@^4.0.2: version "4.0.2"
d428262bf9335de61a145ac866d6019f8a9a2efe
2022-04-23 18:01:43
f0c1s
fix: Azure SSH url was not accepted for git connection (#12896)
false
Azure SSH url was not accepted for git connection (#12896)
fix
diff --git a/app/client/src/pages/Editor/gitSync/utils.test.ts b/app/client/src/pages/Editor/gitSync/utils.test.ts index edd8f8f5aa18..963fc81f86f0 100644 --- a/app/client/src/pages/Editor/gitSync/utils.test.ts +++ b/app/client/src/pages/Editor/gitSync/utils.test.ts @@ -20,9 +20,12 @@ const validUrls = [ "ssh://host.xz/~user/path/to/repo.git", "ssh://[email protected]/~/path/to/repo.git", "ssh://host.xz/~/path/to/repo.git", + "[email protected]:v3/something/other/thing", + "[email protected]:v3/something/other/thing.git", ]; const invalidUrls = [ + "[email protected]:v3/something/other/thing/", "gitclonegit://a@b:c/d.git", "https://github.com/user/project.git", "http://github.com/user/project.git", diff --git a/app/client/src/pages/Editor/gitSync/utils.ts b/app/client/src/pages/Editor/gitSync/utils.ts index 0938bb6d4573..832e4f39b78b 100644 --- a/app/client/src/pages/Editor/gitSync/utils.ts +++ b/app/client/src/pages/Editor/gitSync/utils.ts @@ -12,7 +12,7 @@ export const getIsStartingWithRemoteBranches = ( ); }; -const GIT_REMOTE_URL_PATTERN = /^((git|ssh)|(git@[\w\.]+))(:(\/\/)?)([\w\.@\:\/\-~]+)(\.git)$/im; +const GIT_REMOTE_URL_PATTERN = /^((git|ssh)|(git@[\w\.]+))(:(\/\/)?)([\w\.@\:\/\-~]+)[^\/]$/im; const gitRemoteUrlRegExp = new RegExp(GIT_REMOTE_URL_PATTERN);
c6d9073b5ed3abb62c1bd46391ebe7875ea4dff4
2025-02-25 22:03:11
sneha122
fix: connection pool config added for dynamoDB to avoid stale connections (#38940)
false
connection pool config added for dynamoDB to avoid stale connections (#38940)
fix
diff --git a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/enums/FeatureFlagEnum.java b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/enums/FeatureFlagEnum.java index bde30a1ef674..22f1423cb70c 100644 --- a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/enums/FeatureFlagEnum.java +++ b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/enums/FeatureFlagEnum.java @@ -20,6 +20,7 @@ public enum FeatureFlagEnum { // Deprecated CE flags over here release_git_autocommit_feature_enabled, release_git_autocommit_eligibility_enabled, + release_dynamodb_connection_time_to_live_enabled, // Add EE flags below this line, to avoid conflicts. } diff --git a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/plugins/PluginExecutor.java b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/plugins/PluginExecutor.java index 5f9cdb89d1b3..361385739267 100644 --- a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/plugins/PluginExecutor.java +++ b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/plugins/PluginExecutor.java @@ -295,6 +295,39 @@ default Mono<TriggerResultDTO> triggerWithFlags( Map<String, Boolean> featureFlagMap) { return this.trigger(connection, datasourceConfiguration, request); } + /* + * Feature flagging implementation is added here as a potential fix to dynamoDB query timeouts problem + * This is a temporary fix and will be removed once we get the confirmation from the user that issue is resolved + * Even if the issue is not resolved, we will know that fix does not work and hence will be removing the code in any case + * https://github.com/appsmithorg/appsmith/issues/39426 Created task here to remove this flag + * This implementation ensures that none of the existing plugins have any impact due to feature flagging, hence if else condition + * This applies to both datasourceCreate and testDatasource methods added below + * */ + default Mono<C> datasourceCreate( + DatasourceConfiguration datasourceConfiguration, Boolean isDynamoDBConnectionTimeToLiveEnabled) { + return this.datasourceCreate(datasourceConfiguration); + } + + default Mono<DatasourceTestResult> testDatasource( + DatasourceConfiguration datasourceConfiguration, Boolean isDynamoDBConnectionTimeToLiveEnabled) { + return this.datasourceCreate(datasourceConfiguration, isDynamoDBConnectionTimeToLiveEnabled) + .flatMap(connection -> { + return this.testDatasource(connection).doFinally(signal -> this.datasourceDestroy(connection)); + }) + .onErrorResume(error -> { + // We always expect to have an error object, but the error object may not be well-formed + final String errorMessage = error.getMessage() == null + ? AppsmithPluginError.PLUGIN_DATASOURCE_TEST_GENERIC_ERROR.getMessage() + : error.getMessage(); + if (error instanceof AppsmithPluginException + && StringUtils.hasLength(((AppsmithPluginException) error).getDownstreamErrorMessage())) { + return Mono.just(new DatasourceTestResult( + ((AppsmithPluginException) error).getDownstreamErrorMessage(), errorMessage)); + } + return Mono.just(new DatasourceTestResult(errorMessage)); + }) + .subscribeOn(Schedulers.boundedElastic()); + } /** * This function is responsible for preparing the action and datasource configurations to be ready for execution. diff --git a/app/server/appsmith-plugins/dynamoPlugin/pom.xml b/app/server/appsmith-plugins/dynamoPlugin/pom.xml index 54e544bc7a13..d1febad2edef 100644 --- a/app/server/appsmith-plugins/dynamoPlugin/pom.xml +++ b/app/server/appsmith-plugins/dynamoPlugin/pom.xml @@ -32,6 +32,23 @@ </exclusion> </exclusions> </dependency> + + <dependency> + <groupId>software.amazon.awssdk</groupId> + <artifactId>apache-client</artifactId> + <version>2.15.3</version> + <scope>compile</scope> + <exclusions> + <exclusion> + <groupId>org.slf4j</groupId> + <artifactId>slf4j-api</artifactId> + </exclusion> + <exclusion> + <groupId>com.fasterxml.jackson.core</groupId> + <artifactId>jackson-databind</artifactId> + </exclusion> + </exclusions> + </dependency> </dependencies> <build> diff --git a/app/server/appsmith-plugins/dynamoPlugin/src/main/java/com/external/plugins/DynamoPlugin.java b/app/server/appsmith-plugins/dynamoPlugin/src/main/java/com/external/plugins/DynamoPlugin.java index 01949363b76f..39b5f9e09a7b 100644 --- a/app/server/appsmith-plugins/dynamoPlugin/src/main/java/com/external/plugins/DynamoPlugin.java +++ b/app/server/appsmith-plugins/dynamoPlugin/src/main/java/com/external/plugins/DynamoPlugin.java @@ -29,6 +29,7 @@ import software.amazon.awssdk.core.SdkBytes; import software.amazon.awssdk.core.SdkField; import software.amazon.awssdk.core.SdkPojo; +import software.amazon.awssdk.http.apache.ApacheHttpClient; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.dynamodb.DynamoDbClient; import software.amazon.awssdk.services.dynamodb.DynamoDbClientBuilder; @@ -42,6 +43,7 @@ import java.lang.reflect.Type; import java.lang.reflect.WildcardType; import java.net.URI; +import java.time.Duration; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; @@ -70,6 +72,7 @@ public class DynamoPlugin extends BasePlugin { private static final String DYNAMO_TYPE_BINARY_SET_LABEL = "BS"; private static final String DYNAMO_TYPE_MAP_LABEL = "M"; private static final String DYNAMO_TYPE_LIST_LABEL = "L"; + private static final Duration CONNECTION_TIME_TO_LIVE = Duration.ofDays(1); public DynamoPlugin(PluginWrapper wrapper) { super(wrapper); @@ -281,32 +284,47 @@ public Mono<ActionExecutionResult> execute( } @Override - public Mono<DynamoDbClient> datasourceCreate(DatasourceConfiguration datasourceConfiguration) { + public Mono<DynamoDbClient> datasourceCreate( + DatasourceConfiguration datasourceConfiguration, Boolean isFlagEnabled) { log.debug(Thread.currentThread().getName() + ": datasourceCreate() called for Dynamo plugin."); return Mono.fromCallable(() -> { log.debug(Thread.currentThread().getName() + ": creating dynamodbclient from DynamoDB plugin."); - final DynamoDbClientBuilder builder = DynamoDbClient.builder(); - - if (!CollectionUtils.isEmpty(datasourceConfiguration.getEndpoints())) { - final Endpoint endpoint = - datasourceConfiguration.getEndpoints().get(0); - builder.endpointOverride( - URI.create("http://" + endpoint.getHost() + ":" + endpoint.getPort())); - } - final DBAuth authentication = (DBAuth) datasourceConfiguration.getAuthentication(); - if (authentication == null || !StringUtils.hasLength(authentication.getDatabaseName())) { - throw new AppsmithPluginException( - AppsmithPluginError.PLUGIN_DATASOURCE_ARGUMENT_ERROR, - DynamoErrorMessages.MISSING_REGION_ERROR_MSG); + /** + * Current understanding is that the issue mentioned in #6030 is because of is because of connection object getting stale. + * Setting connection to live value to 1 day is a precaution move to make sure that we don't land into a situation + * where an older connection can malfunction. + * To understand what this config means please check here: + * {@link https://sdk.amazonaws.com/java/api/latest/software/amazon/awssdk/http/apache/ApacheHttpClient.Builder.html#connectionTimeToLive(java.time.Duration)} + */ + DynamoDbClientBuilder builder; + if (isFlagEnabled) { + log.debug("DynamoDB client builder created with custom connection time to live"); + builder = DynamoDbClient.builder() + .httpClient(ApacheHttpClient.builder() + .connectionTimeToLive(CONNECTION_TIME_TO_LIVE) + .build()); + } else { + builder = DynamoDbClient.builder(); } - builder.region(Region.of(authentication.getDatabaseName())); + return getDynamoDBClientObject(datasourceConfiguration, builder); + }) + .subscribeOn(scheduler); + } - builder.credentialsProvider(StaticCredentialsProvider.create(AwsBasicCredentials.create( - authentication.getUsername(), authentication.getPassword()))); + // This method is not being used right now as we had created a separate method with the same name in the + // DynamoPlugin class. + // which creates dynamoDB client based on feature flagging + // Once feature flagging is removed, we can go back to using this method. + @Override + public Mono<DynamoDbClient> datasourceCreate(DatasourceConfiguration datasourceConfiguration) { + log.debug(Thread.currentThread().getName() + ": datasourceCreate() called for Dynamo plugin."); + return Mono.fromCallable(() -> { + log.debug(Thread.currentThread().getName() + ": creating dynamodbclient from DynamoDB plugin."); + final DynamoDbClientBuilder builder = DynamoDbClient.builder(); - return builder.build(); + return getDynamoDBClientObject(datasourceConfiguration, builder); }) .subscribeOn(scheduler); } @@ -611,4 +629,25 @@ private static boolean isUpperCase(String s) { } return true; } + + private static DynamoDbClient getDynamoDBClientObject( + DatasourceConfiguration dsConfig, DynamoDbClientBuilder builder) { + if (!CollectionUtils.isEmpty(dsConfig.getEndpoints())) { + final Endpoint endpoint = dsConfig.getEndpoints().get(0); + builder.endpointOverride(URI.create("http://" + endpoint.getHost() + ":" + endpoint.getPort())); + } + + final DBAuth authentication = (DBAuth) dsConfig.getAuthentication(); + if (authentication == null || !StringUtils.hasLength(authentication.getDatabaseName())) { + throw new AppsmithPluginException( + AppsmithPluginError.PLUGIN_DATASOURCE_ARGUMENT_ERROR, DynamoErrorMessages.MISSING_REGION_ERROR_MSG); + } + + builder.region(Region.of(authentication.getDatabaseName())); + + builder.credentialsProvider(StaticCredentialsProvider.create( + AwsBasicCredentials.create(authentication.getUsername(), authentication.getPassword()))); + + return builder.build(); + } } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/datasources/base/DatasourceServiceCEImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/datasources/base/DatasourceServiceCEImpl.java index df7decf15976..591ea758900d 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/datasources/base/DatasourceServiceCEImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/datasources/base/DatasourceServiceCEImpl.java @@ -661,8 +661,24 @@ protected Mono<DatasourceTestResult> testDatasourceViaPlugin(DatasourceStorage d .switchIfEmpty(Mono.error(new AppsmithException( AppsmithError.NO_RESOURCE_FOUND, FieldName.PLUGIN, datasourceStorage.getPluginId()))); - return pluginExecutorMono.flatMap(pluginExecutor -> ((PluginExecutor<Object>) pluginExecutor) - .testDatasource(datasourceStorage.getDatasourceConfiguration())); + // Feature flagging implementation is added here as a potential fix to dynamoDB query timeouts problem + // This is a temporary fix and will be removed once we get the confirmation from the user that issue is resolved + // Even if the issue is not resolved, we will know that fix does not work and hence will be removing the code in + // any case + // https://github.com/appsmithorg/appsmith/issues/39426 Created task here to remove this flag + // This implementation ensures that none of the existing plugins have any impact due to feature flagging, hence + // if else condition + return featureFlagService + .check(FeatureFlagEnum.release_dynamodb_connection_time_to_live_enabled) + .flatMap(isDynamoDBConnectionTimeToLiveEnabled -> { + if (isDynamoDBConnectionTimeToLiveEnabled) { + return pluginExecutorMono.flatMap(pluginExecutor -> ((PluginExecutor<Object>) pluginExecutor) + .testDatasource(datasourceStorage.getDatasourceConfiguration(), true)); + } else { + return pluginExecutorMono.flatMap(pluginExecutor -> ((PluginExecutor<Object>) pluginExecutor) + .testDatasource(datasourceStorage.getDatasourceConfiguration())); + } + }); } /* diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/DatasourceContextServiceImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/DatasourceContextServiceImpl.java index 1a686d1635eb..c2d77e79a2b0 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/DatasourceContextServiceImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/DatasourceContextServiceImpl.java @@ -20,7 +20,8 @@ public DatasourceContextServiceImpl( PluginService pluginService, PluginExecutorHelper pluginExecutorHelper, ConfigService configService, - DatasourcePermission datasourcePermission) { + DatasourcePermission datasourcePermission, + FeatureFlagService featureFlagService) { super( datasourceService, @@ -28,6 +29,7 @@ public DatasourceContextServiceImpl( pluginService, pluginExecutorHelper, configService, - datasourcePermission); + datasourcePermission, + featureFlagService); } } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/DatasourceContextServiceCEImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/DatasourceContextServiceCEImpl.java index 69632105e0d3..d4a9682101bc 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/DatasourceContextServiceCEImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/DatasourceContextServiceCEImpl.java @@ -3,6 +3,7 @@ import com.appsmith.external.constants.PluginConstants; import com.appsmith.external.dtos.ExecutePluginDTO; import com.appsmith.external.dtos.RemoteDatasourceDTO; +import com.appsmith.external.enums.FeatureFlagEnum; import com.appsmith.external.exceptions.pluginExceptions.AppsmithPluginException; import com.appsmith.external.exceptions.pluginExceptions.StaleConnectionException; import com.appsmith.external.models.DatasourceStorage; @@ -20,6 +21,7 @@ import com.appsmith.server.helpers.PluginExecutorHelper; import com.appsmith.server.plugins.base.PluginService; import com.appsmith.server.services.ConfigService; +import com.appsmith.server.services.FeatureFlagService; import com.appsmith.server.solutions.DatasourcePermission; import com.google.common.cache.Cache; import com.google.common.cache.CacheBuilder; @@ -68,6 +70,7 @@ public class DatasourceContextServiceCEImpl implements DatasourceContextServiceC private final PluginExecutorHelper pluginExecutorHelper; private final ConfigService configService; private final DatasourcePermission datasourcePermission; + private final FeatureFlagService featureFlagService; private final AppsmithException TOO_MANY_REQUESTS_EXCEPTION = new AppsmithException(AppsmithError.TOO_MANY_FAILED_DATASOURCE_CONNECTION_REQUESTS); @@ -79,7 +82,8 @@ public DatasourceContextServiceCEImpl( PluginService pluginService, PluginExecutorHelper pluginExecutorHelper, ConfigService configService, - DatasourcePermission datasourcePermission) { + DatasourcePermission datasourcePermission, + FeatureFlagService featureFlagService) { this.datasourceService = datasourceService; this.datasourceStorageService = datasourceStorageService; this.pluginService = pluginService; @@ -89,6 +93,7 @@ public DatasourceContextServiceCEImpl( this.datasourceContextSynchronizationMonitorMap = new ConcurrentHashMap<>(); this.configService = configService; this.datasourcePermission = datasourcePermission; + this.featureFlagService = featureFlagService; } private RemovalListener<DatasourceContextIdentifier, DatasourcePluginContext> createRemovalListener() { @@ -209,8 +214,27 @@ public Mono<DatasourceContext<Object>> getCachedDatasourceContextMono( /* Create a fresh datasource context */ DatasourceContext<Object> datasourceContext = new DatasourceContext<>(); - Mono<Object> connectionMonoCache = pluginExecutor - .datasourceCreate(datasourceStorage.getDatasourceConfiguration()) + + // Feature flagging implementation is added here as a potential fix to dynamoDB query timeouts + // problem + // This is a temporary fix and will be removed once we get the confirmation from the user that + // issue is resolved + // Even if the issue is not resolved, we will know that fix does not work and hence will be + // removing the code in any case + // https://github.com/appsmithorg/appsmith/issues/39426 Created task here to remove this flag + // This implementation ensures that none of the existing plugins have any impact due to feature + // flagging, hence if else condition + Mono<Object> connectionMonoCache = featureFlagService + .check(FeatureFlagEnum.release_dynamodb_connection_time_to_live_enabled) + .flatMap(isDynamoDBConnectionTimeToLiveEnabled -> { + if (isDynamoDBConnectionTimeToLiveEnabled) { + return pluginExecutor.datasourceCreate( + datasourceStorage.getDatasourceConfiguration(), true); + } else { + return pluginExecutor.datasourceCreate( + datasourceStorage.getDatasourceConfiguration()); + } + }) .cache(); Mono<DatasourceContext<Object>> datasourceContextMonoCache = connectionMonoCache
e466495b5bb012bc72066211baf4172cb046caa0
2021-11-22 12:38:36
onifade boluwatife
fix: Date picker must exit on pressing esc key when 'close on selecting' is turned off (#8425)
false
Date picker must exit on pressing esc key when 'close on selecting' is turned off (#8425)
fix
diff --git a/app/client/src/widgets/DatePickerWidget2/component/index.tsx b/app/client/src/widgets/DatePickerWidget2/component/index.tsx index ebe3ff05e029..fda72289d323 100644 --- a/app/client/src/widgets/DatePickerWidget2/component/index.tsx +++ b/app/client/src/widgets/DatePickerWidget2/component/index.tsx @@ -21,14 +21,7 @@ import { DATE_WIDGET_DEFAULT_VALIDATION_ERROR, } from "constants/messages"; -enum KEYS { - Tab = "Tab", - Escape = "Escape", -} - -const StyledControlGroup = styled(ControlGroup)<{ - isValid: boolean; -}>` +const StyledControlGroup = styled(ControlGroup)<{ isValid: boolean }>` &&& { .${Classes.INPUT} { color: ${Colors.GREY_10}; @@ -94,12 +87,9 @@ class DatePickerComponent extends React.Component< super(props); this.state = { selectedDate: props.selectedDate, - showPicker: false, }; } - pickerRef: HTMLElement | null = null; - componentDidUpdate(prevProps: DatePickerComponentProps) { if ( this.props.selectedDate !== this.state.selectedDate && @@ -117,11 +107,6 @@ class DatePickerComponent extends React.Component< return _date.isValid() ? _date.toDate() : undefined; }; - handlePopoverRef = (ref: any) => { - // get popover ref as callback - this.pickerRef = ref as HTMLElement; - }; - render() { const now = moment(); const year = now.get("year"); @@ -173,10 +158,6 @@ class DatePickerComponent extends React.Component< closeOnSelection={this.props.closeOnSelection} disabled={this.props.isDisabled} formatDate={this.formatDate} - inputProps={{ - onFocus: this.showPicker, - onKeyDown: this.handleKeyDown, - }} maxDate={maxDate} minDate={minDate} onChange={this.onDateSelected} @@ -184,9 +165,7 @@ class DatePickerComponent extends React.Component< placeholder={"Select Date"} popoverProps={{ usePortal: !this.props.withoutPortal, - isOpen: this.state.showPicker, - onClose: this.closePicker, - popoverRef: this.handlePopoverRef, + canEscapeKeyClose: true, }} shortcuts={this.props.shortcuts} showActionsBar @@ -255,42 +234,14 @@ class DatePickerComponent extends React.Component< */ onDateSelected = (selectedDate: Date | null, isUserChange: boolean) => { if (isUserChange) { - const { closeOnSelection, onDateSelected } = this.props; - + const { onDateSelected } = this.props; const date = selectedDate ? selectedDate.toISOString() : ""; this.setState({ selectedDate: date, - // close picker while user changes in calender - // if closeOnSelection false, do not allow user to close picker - showPicker: !closeOnSelection, }); - onDateSelected(date); } }; - - showPicker = () => { - this.setState({ showPicker: true }); - }; - - closePicker = (e: any) => { - const { closeOnSelection } = this.props; - try { - // user click shortcuts, follow closeOnSelection behaviour otherwise close picker - const showPicker = - this.pickerRef && this.pickerRef.contains(e.target) - ? !closeOnSelection - : false; - this.setState({ showPicker }); - } catch (error) { - this.setState({ showPicker: false }); - } - }; - handleKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => { - if (e.key === KEYS.Tab || e.key === KEYS.Escape) { - this.closePicker(e); - } - }; } interface DatePickerComponentProps extends ComponentProps { @@ -311,7 +262,6 @@ interface DatePickerComponentProps extends ComponentProps { interface DatePickerComponentState { selectedDate?: string; - showPicker?: boolean; } export default DatePickerComponent;
a560051d86934073b9781bba513ceb915a8b70b2
2022-09-30 19:11:04
akash-codemonk
feat: fork templates inside an existing app (#17184)
false
fork templates inside an existing app (#17184)
feat
diff --git a/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/ExplorerTests/Page_Load_Spec.js b/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/ExplorerTests/Page_Load_Spec.js index 83c712801ba8..998f74209940 100644 --- a/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/ExplorerTests/Page_Load_Spec.js +++ b/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/ExplorerTests/Page_Load_Spec.js @@ -1,16 +1,11 @@ const dsl = require("../../../../fixtures/PageLoadDsl.json"); const commonlocators = require("../../../../locators/commonlocators.json"); const publish = require("../../../../locators/publishWidgetspage.json"); -const explorerLocators = require("../../../../locators/explorerlocators.json"); describe("Page Load tests", () => { before(() => { cy.addDsl(dsl); - cy.get(explorerLocators.AddPage) - .first() - .click(); - - cy.skipGenerateCRUDPage(); + cy.CreatePage(); cy.get("h2").contains("Drag and drop a widget here"); }); diff --git a/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/OtherUIFeatures/DynamicLayout_spec.js b/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/OtherUIFeatures/DynamicLayout_spec.js index b39da1fe73b8..33332700cecf 100644 --- a/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/OtherUIFeatures/DynamicLayout_spec.js +++ b/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/OtherUIFeatures/DynamicLayout_spec.js @@ -20,8 +20,6 @@ describe("Dynamic Layout Functionality", function() { .first() .click(); - cy.skipGenerateCRUDPage(); - cy.get(commonlocators.canvas) .invoke("width") .should("be.eq", 450); diff --git a/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/OtherUIFeatures/Fork_Template_To_App_spec.js b/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/OtherUIFeatures/Fork_Template_To_App_spec.js new file mode 100644 index 000000000000..43d9fe0c6c83 --- /dev/null +++ b/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/OtherUIFeatures/Fork_Template_To_App_spec.js @@ -0,0 +1,16 @@ +import widgetLocators from "../../../../locators/Widgets.json"; + +describe("Fork a template to the current app", () => { + it("Fork a template to the current app", () => { + cy.get("[data-cy=start-from-template]").click(); + + cy.xpath( + "//div[text()='Customer Support Dashboard']/following-sibling::div//button[contains(@class, 'fork-button')]", + ).click(); + + cy.get(widgetLocators.toastAction).should( + "contain", + "template added successfully", + ); + }); +}); diff --git a/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/VisualTests/AppPageLayout_spec.js b/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/VisualTests/AppPageLayout_spec.js index 96537a30a69d..24c6a35dbcbd 100644 --- a/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/VisualTests/AppPageLayout_spec.js +++ b/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/VisualTests/AppPageLayout_spec.js @@ -20,7 +20,7 @@ describe("Visual regression tests", () => { }); it("Layout validation for Quick page wizard", () => { - cy.get(".t--GenerateCRUDPage").click(); + cy.get("[data-cy='generate-app']").click(); cy.wait(2000); // taking screenshot of generate crud page cy.get("#root").matchImageSnapshot("quickPageWizard"); @@ -28,7 +28,6 @@ describe("Visual regression tests", () => { it("Layout Validation for App builder Page", () => { cy.get(".bp3-icon-chevron-left").click(); - cy.get(".t--BuildFromScratch").click(); cy.wait(2000); // taking screenshot of app builder page cy.get("#root").matchImageSnapshot("emptyAppBuilder"); diff --git a/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/Widgets/Filepicker/Filepicker1_spec.js b/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/Widgets/Filepicker/Filepicker1_spec.js index 3b954f1b599a..96da7cafbfd2 100644 --- a/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/Widgets/Filepicker/Filepicker1_spec.js +++ b/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/Widgets/Filepicker/Filepicker1_spec.js @@ -6,7 +6,6 @@ describe("FilePicker Widget Functionality", function() { cy.get(".t--new-button") .first() .click(); - cy.get(".t--BuildFromScratch").click(); cy.get(explorer.addWidget).click(); cy.dragAndDropToCanvas("filepickerwidgetv2", { x: 200, y: 600 }); }); diff --git a/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/Widgets/WidgetCopyPaste_spec.js b/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/Widgets/WidgetCopyPaste_spec.js index 90867ed75cbf..0960881289bb 100644 --- a/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/Widgets/WidgetCopyPaste_spec.js +++ b/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/Widgets/WidgetCopyPaste_spec.js @@ -157,9 +157,6 @@ describe("Widget Copy paste", function() { it("should be able to paste widget on the initial generate Page", function() { cy.Createpage("NewPage", false); - //verify that it is in generate page - cy.get(generatePage.buildFromScratchActionCard).should("have.length", 1); - //paste cy.get("body").type(`{${modifierKey}}{v}`); diff --git a/app/client/cypress/integration/Smoke_TestSuite/ServerSideTests/ApiTests/API_Bugs_Spec.js b/app/client/cypress/integration/Smoke_TestSuite/ServerSideTests/ApiTests/API_Bugs_Spec.js index 42116348be3f..e22d9946b96d 100644 --- a/app/client/cypress/integration/Smoke_TestSuite/ServerSideTests/ApiTests/API_Bugs_Spec.js +++ b/app/client/cypress/integration/Smoke_TestSuite/ServerSideTests/ApiTests/API_Bugs_Spec.js @@ -122,9 +122,7 @@ describe("Rest Bugs tests", function() { it("Bug 6863: Clicking on 'debug' crashes the appsmith application", function() { cy.startErrorRoutes(); - cy.get(pages.AddPage) - .first() - .click(); + cy.CreatePage(); cy.wait("@createPage").should( "have.nested.property", "response.body.responseMeta.status", diff --git a/app/client/cypress/integration/Smoke_TestSuite/ServerSideTests/GenerateCRUD/S3_Spec.js b/app/client/cypress/integration/Smoke_TestSuite/ServerSideTests/GenerateCRUD/S3_Spec.js index 14f164986b55..1cab539f0237 100644 --- a/app/client/cypress/integration/Smoke_TestSuite/ServerSideTests/GenerateCRUD/S3_Spec.js +++ b/app/client/cypress/integration/Smoke_TestSuite/ServerSideTests/GenerateCRUD/S3_Spec.js @@ -160,9 +160,7 @@ describe("Generate New CRUD Page Inside from entity explorer", function() { // }); //Create Dummy Page2 : - cy.get(pages.AddPage) - .first() - .click(); + cy.CreatePage(); cy.wait("@createPage").should( "have.nested.property", "response.body.responseMeta.status", @@ -170,9 +168,7 @@ describe("Generate New CRUD Page Inside from entity explorer", function() { ); //Creating CRUD Page3 - cy.get(pages.AddPage) - .first() - .click(); + cy.CreatePage(); cy.wait("@createPage").should( "have.nested.property", "response.body.responseMeta.status", diff --git a/app/client/cypress/locators/GeneratePage.json b/app/client/cypress/locators/GeneratePage.json index 8f733c38c716..09e4340b7120 100644 --- a/app/client/cypress/locators/GeneratePage.json +++ b/app/client/cypress/locators/GeneratePage.json @@ -1,6 +1,5 @@ { - "buildFromScratchActionCard": ".t--BuildFromScratch", - "generateCRUDPageActionCard": ".t--GenerateCRUDPage", + "generateCRUDPageActionCard": "[data-cy='generate-app']", "selectDatasourceDropdown": "[data-cy=t--datasource-dropdown]", "datasourceDropdownOption": "[data-cy=t--datasource-dropdown-option]", "selectTableDropdown": "[data-cy=t--table-dropdown]", diff --git a/app/client/cypress/snapshots/Smoke_TestSuite/ClientSideTests/VisualTests/AppPageLayout_spec.js/apppage.snap.png b/app/client/cypress/snapshots/Smoke_TestSuite/ClientSideTests/VisualTests/AppPageLayout_spec.js/apppage.snap.png index 1cd68f61fb59..dcf479639743 100644 Binary files a/app/client/cypress/snapshots/Smoke_TestSuite/ClientSideTests/VisualTests/AppPageLayout_spec.js/apppage.snap.png and b/app/client/cypress/snapshots/Smoke_TestSuite/ClientSideTests/VisualTests/AppPageLayout_spec.js/apppage.snap.png differ diff --git a/app/client/cypress/snapshots/Smoke_TestSuite/ClientSideTests/VisualTests/AppPageLayout_spec.js/emptyAppBuilder.snap.png b/app/client/cypress/snapshots/Smoke_TestSuite/ClientSideTests/VisualTests/AppPageLayout_spec.js/emptyAppBuilder.snap.png index db7791f62707..423a12733fc5 100644 Binary files a/app/client/cypress/snapshots/Smoke_TestSuite/ClientSideTests/VisualTests/AppPageLayout_spec.js/emptyAppBuilder.snap.png and b/app/client/cypress/snapshots/Smoke_TestSuite/ClientSideTests/VisualTests/AppPageLayout_spec.js/emptyAppBuilder.snap.png differ diff --git a/app/client/cypress/support/Pages/EntityExplorer.ts b/app/client/cypress/support/Pages/EntityExplorer.ts index 574298855c4c..24639195adb0 100644 --- a/app/client/cypress/support/Pages/EntityExplorer.ts +++ b/app/client/cypress/support/Pages/EntityExplorer.ts @@ -86,6 +86,7 @@ export class EntityExplorer { cy.get(this.locator._newPage) .first() .click(); + cy.get("[data-cy='add-page']").click(); this.agHelper.ValidateNetworkStatus("@createPage", 201); } diff --git a/app/client/cypress/support/Pages/HomePage.ts b/app/client/cypress/support/Pages/HomePage.ts index f32957911992..119d53219df4 100644 --- a/app/client/cypress/support/Pages/HomePage.ts +++ b/app/client/cypress/support/Pages/HomePage.ts @@ -45,8 +45,7 @@ export class HomePage { private _applicationName = ".t--application-name"; private _editAppName = "bp3-editable-text-editing"; private _appMenu = ".t--editor-appname-menu-portal .bp3-menu-item"; - private _buildFromScratchActionCard = ".t--BuildFromScratch"; - _buildFromDataTableActionCard = ".t--GenerateCRUDPage"; + _buildFromDataTableActionCard = "[data-cy='generate-app']"; private _selectRole = "//span[text()='Select a role']/ancestor::div"; private _searchInput = "input[type='text']"; _appHoverIcon = (action: string) => ".t--application-" + action + "-link"; @@ -187,7 +186,6 @@ export class HomePage { cy.get(this.locator._loading).should("not.exist"); this.agHelper.Sleep(2000); if (appname) this.RenameApplication(appname); - cy.get(this._buildFromScratchActionCard).click(); //this.agHelper.ValidateNetworkStatus("@updateApplication", 200); } diff --git a/app/client/cypress/support/WorkspaceCommands.js b/app/client/cypress/support/WorkspaceCommands.js index 1ff746de4ac7..0db475d0e72b 100644 --- a/app/client/cypress/support/WorkspaceCommands.js +++ b/app/client/cypress/support/WorkspaceCommands.js @@ -275,8 +275,6 @@ Cypress.Commands.add("CreateAppForWorkspace", (workspaceName, appname) => { cy.AppSetupForRename(); cy.get(homePage.applicationName).type(appname + "{enter}"); - cy.get(generatePage.buildFromScratchActionCard).click(); - cy.wait("@updateApplication").should( "have.nested.property", "response.body.responseMeta.status", @@ -298,7 +296,6 @@ Cypress.Commands.add("CreateAppInFirstListedWorkspace", (appname) => { //cy.get("#loading").should("not.exist"); // eslint-disable-next-line cypress/no-unnecessary-waiting //cy.reload(); - cy.get(generatePage.buildFromScratchActionCard).should("be.visible"); cy.AppSetupForRename(); cy.get(homePage.applicationName).type(appname + "{enter}"); cy.wait("@updateApplication").should( @@ -310,19 +307,6 @@ Cypress.Commands.add("CreateAppInFirstListedWorkspace", (appname) => { cy.get(homePage.applicationName).realHover(); cy.get("body").realHover({ position: "topLeft" }); - cy.waitUntil(() => cy.get(generatePage.buildFromScratchActionCard), { - errorMsg: "Build app from scratch not visible even aft 20 secs", - timeout: 20000, - interval: 1000, - }).then(($ele) => - cy - .wrap($ele) - .should("be.visible") - .click(), - ); - - //cy.get(generatePage.buildFromScratchActionCard).click(); - /* The server created app always has an old dsl so the layout will migrate * To avoid race conditions between that update layout and this one * we wait for that to finish before updating layout here diff --git a/app/client/cypress/support/commands.js b/app/client/cypress/support/commands.js index 77f66a18a5c9..eb762bbe9a12 100644 --- a/app/client/cypress/support/commands.js +++ b/app/client/cypress/support/commands.js @@ -1149,10 +1149,6 @@ Cypress.Commands.add( }, ); -Cypress.Commands.add("skipGenerateCRUDPage", () => { - cy.get(generatePage.buildFromScratchActionCard).click(); -}); - Cypress.Commands.add("updateMapType", (mapType) => { // Command to change the map chart type if the property pane of the map chart widget is opened. cy.get(viewWidgetsPage.mapType) @@ -1900,3 +1896,10 @@ Cypress.Commands.add( }); }, ); + +Cypress.Commands.add("CreatePage", () => { + cy.get(pages.AddPage) + .first() + .click({ force: true }); + cy.get("[data-cy='add-page']").click(); +}); diff --git a/app/client/cypress/support/widgetCommands.js b/app/client/cypress/support/widgetCommands.js index 3336c69f8ed1..7e1cea9cc959 100644 --- a/app/client/cypress/support/widgetCommands.js +++ b/app/client/cypress/support/widgetCommands.js @@ -942,9 +942,7 @@ Cypress.Commands.add("DeleteModal", () => { Cypress.Commands.add("Createpage", (pageName, navigateToCanvasPage = true) => { let pageId; - cy.get(pages.AddPage) - .first() - .click({ force: true }); + cy.CreatePage(); cy.wait("@createPage").then((xhr) => { expect(xhr.response.body.responseMeta.status).to.equal(201); if (pageName) { @@ -957,9 +955,6 @@ Cypress.Commands.add("Createpage", (pageName, navigateToCanvasPage = true) => { cy.get(pages.editInput).type(pageName + "{enter}"); cy.wrap(pageId).as("currentPageId"); } - if (navigateToCanvasPage) { - cy.get(generatePage.buildFromScratchActionCard).click(); - } cy.get("#loading").should("not.exist"); }); }); diff --git a/app/client/src/RouteBuilder.ts b/app/client/src/RouteBuilder.ts index b18a46f457cf..0c7a9b4a545a 100644 --- a/app/client/src/RouteBuilder.ts +++ b/app/client/src/RouteBuilder.ts @@ -151,12 +151,6 @@ export const saasEditorApiIdURL = ( suffix: `saas/${props.pluginPackageName}/api/${props.apiId}`, }); -export const generateTemplateURL = (props: URLBuilderParams): string => - urlBuilder.build({ - ...props, - suffix: GEN_TEMPLATE_URL, - }); - export const generateTemplateFormURL = (props: URLBuilderParams): string => urlBuilder.build({ ...props, diff --git a/app/client/src/actions/applicationActions.ts b/app/client/src/actions/applicationActions.ts index 9aba2fce6b2a..d3117390b7df 100644 --- a/app/client/src/actions/applicationActions.ts +++ b/app/client/src/actions/applicationActions.ts @@ -138,10 +138,17 @@ export const setWorkspaceIdForImport = (workspaceId?: string) => ({ payload: workspaceId, }); +export const setPageIdForImport = (pageId?: string) => ({ + type: ReduxActionTypes.SET_PAGE_ID_FOR_IMPORT, + payload: pageId, +}); + +// pageId can be used to navigate to a particular page instead of the default one export const showReconnectDatasourceModal = (payload: { application: ApplicationResponsePayload; unConfiguredDatasourceList: Datasource[]; workspaceId: string; + pageId?: string; }) => ({ type: ReduxActionTypes.SHOW_RECONNECT_DATASOURCE_MODAL, payload, diff --git a/app/client/src/actions/templateActions.ts b/app/client/src/actions/templateActions.ts index 6fd731ea8c6d..4683623f8337 100644 --- a/app/client/src/actions/templateActions.ts +++ b/app/client/src/actions/templateActions.ts @@ -46,3 +46,25 @@ export const getTemplateInformation = (payload: string) => ({ type: ReduxActionTypes.GET_TEMPLATE_INIT, payload, }); + +export const showTemplatesModal = (payload: boolean) => ({ + type: ReduxActionTypes.SHOW_TEMPLATES_MODAL, + payload, +}); + +export const importTemplateIntoApplication = ( + templateId: string, + templateName: string, + pageNames?: string[], +) => ({ + type: ReduxActionTypes.IMPORT_TEMPLATE_TO_APPLICATION_INIT, + payload: { + templateId, + templateName, + pageNames, + }, +}); + +export const getTemplateFilters = () => ({ + type: ReduxActionTypes.GET_TEMPLATE_FILTERS_INIT, +}); diff --git a/app/client/src/api/TemplatesApi.ts b/app/client/src/api/TemplatesApi.ts index 69f6d7019f4e..c90c19e35a99 100644 --- a/app/client/src/api/TemplatesApi.ts +++ b/app/client/src/api/TemplatesApi.ts @@ -2,7 +2,10 @@ import { AxiosPromise } from "axios"; import Api from "api/Api"; import { ApiResponse } from "./ApiResponses"; import { WidgetType } from "constants/WidgetConstants"; -import { ApplicationResponsePayload } from "./ApplicationApi"; +import { + ApplicationResponsePayload, + ApplicationPagePayload, +} from "./ApplicationApi"; import { Datasource } from "entities/Datasource"; export interface Template { @@ -17,6 +20,7 @@ export interface Template { functions: string[]; useCases: string[]; datasources: string[]; + pages: ApplicationPagePayload[]; } export type FetchTemplatesResponse = ApiResponse<Template[]>; @@ -30,6 +34,12 @@ export type ImportTemplateResponse = ApiResponse<{ application: ApplicationResponsePayload; }>; +export interface TemplateFiltersResponse extends ApiResponse { + data: { + functions: string[]; + }; +} + class TemplatesAPI extends Api { static baseUrl = "v1"; @@ -57,6 +67,21 @@ class TemplatesAPI extends Api { `/app-templates/${templateId}/import/${workspaceId}`, ); } + static importTemplateToApplication( + templateId: string, + applicationId: string, + organizationId: string, + body?: string[], + ): AxiosPromise<ImportTemplateResponse> { + return Api.post( + TemplatesAPI.baseUrl + + `/app-templates/${templateId}/merge/${applicationId}/${organizationId}`, + body, + ); + } + static getTemplateFilters(): AxiosPromise<TemplateFiltersResponse> { + return Api.get(TemplatesAPI.baseUrl + `/app-templates/filters`); + } } export default TemplatesAPI; diff --git a/app/client/src/assets/images/database.svg b/app/client/src/assets/images/database.svg new file mode 100644 index 000000000000..e22526e543c4 --- /dev/null +++ b/app/client/src/assets/images/database.svg @@ -0,0 +1,3 @@ +<svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg"> +<path d="M1.60061 1.7004C0.525619 2.22465 0.000514106 2.7997 0.000514106 3.4246V5.14995C0.000514106 5.77485 0.525619 6.34985 1.60061 6.87461C2.67559 7.39972 4.12518 7.82469 5.97548 8.12475C7.82539 8.42482 9.82521 8.57485 12.0003 8.57485C14.1753 8.57485 16.1752 8.42482 18.025 8.12475C19.8753 7.82469 21.325 7.39972 22.3999 6.87461C23.4749 6.34951 24 5.77485 24 5.14961V3.42494C24 2.80004 23.4749 2.2247 22.3999 1.69993C21.3249 1.17482 19.8753 0.749852 18.025 0.450134C16.1751 0.15024 14.1756 0.000213623 12.0003 0.000213623C9.82517 0.000213623 7.82535 0.150244 5.97548 0.450305C4.15034 0.775147 2.67551 1.175 1.60061 1.7001V1.7004ZM0.000514106 13.2503V15.4251C0.000514106 16.0503 0.525619 16.6253 1.60061 17.1504C2.67559 17.6755 4.12518 18.1002 5.97548 18.4002C7.82539 18.7003 9.82521 18.8503 12.0003 18.8503C14.1753 18.8503 16.1752 18.7003 18.025 18.4002C19.8753 18.1002 21.325 17.6752 22.3999 17.1501C23.4749 16.625 24 16.0503 24 15.4251V13.1502C22.7502 13.9003 21.0751 14.4753 18.9251 14.8501C16.7748 15.2503 14.4752 15.4249 12.0002 15.4249C9.5251 15.4249 7.22536 15.2501 5.07521 14.8499C2.92524 14.4748 1.25014 13.9002 0.000342737 13.15L0.000514106 13.2503ZM0.000342737 18.2498V20.5749C0.000342737 21.1998 0.525448 21.7751 1.60043 22.2999C2.67542 22.825 4.12501 23.25 5.97531 23.5497C7.82522 23.8498 9.82504 23.9998 12.0001 23.9998C14.1751 23.9998 16.175 23.8498 18.0249 23.5497C19.8751 23.2496 21.3248 22.825 22.3997 22.2999C23.4747 21.7748 23.9998 21.1998 23.9998 20.5745V18.2997C22.75 19.0498 21.0749 19.6248 18.925 19.9999C16.775 20.375 14.4751 20.5749 12 20.5749C9.52493 20.5749 7.22519 20.375 5.07504 19.9999C2.92507 19.6248 1.24996 19.0498 0.000171369 18.2997L0.000342737 18.2498ZM0.000171369 8.00027V10.2748C0.000171369 10.8997 0.525277 11.4751 1.60026 11.9998C2.67525 12.5249 4.12484 12.9499 5.97514 13.25C7.82505 13.55 9.82487 13.7001 11.9999 13.7001C14.175 13.7001 16.1748 13.55 18.0247 13.25C19.8749 12.9499 21.3247 12.5249 22.3996 11.9998C23.4746 11.4747 23.9997 10.8997 23.9997 10.2748V7.99993C22.7499 8.75008 21.0748 9.32474 18.9248 9.69982C16.7748 10.0749 14.4749 10.2748 11.9998 10.2748C9.52476 10.2748 7.22502 10.0749 5.07487 9.69982C2.9249 9.32474 1.24979 8.74974 0 7.99993" fill="#575757"/> +</svg> diff --git a/app/client/src/assets/images/layout.svg b/app/client/src/assets/images/layout.svg new file mode 100644 index 000000000000..c8626872f0c7 --- /dev/null +++ b/app/client/src/assets/images/layout.svg @@ -0,0 +1,7 @@ +<svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg"> +<path d="M1.71426 6.10352e-05H22.2854C23.2321 6.10352e-05 23.9997 0.946727 23.9997 1.71433V7.71425C23.9997 8.66092 23.2321 9.42851 22.2854 9.42851H1.71426C0.767599 9.42851 0 8.48185 0 7.71425V1.71433C0 0.76766 0.767599 6.10352e-05 1.71426 6.10352e-05Z" fill="#575757"/> +<path d="M1.71426 12.0001H10.2856C11.2323 12.0001 11.9999 12.9468 11.9999 13.7144V22.2857C11.9999 23.2324 11.2323 24 10.2856 24H1.71426C0.767599 24 0 23.0533 0 22.2857V13.7144C0 12.7677 0.767599 12.0001 1.71426 12.0001Z" fill="#575757"/> +<path d="M23.1428 12.8571H15.4287C15.1223 12.8571 14.8394 13.0205 14.6863 13.2856C14.5333 13.5508 14.5333 13.8776 14.6863 14.1428C14.8394 14.4079 15.1224 14.5713 15.4287 14.5713H23.1428C23.4492 14.5713 23.7321 14.4079 23.8852 14.1428C24.0382 13.8776 24.0382 13.5508 23.8852 13.2856C23.7321 13.0205 23.4491 12.8571 23.1428 12.8571Z" fill="#575757"/> +<path d="M23.1431 17.1421H15.4289C15.1226 17.1421 14.8396 17.3055 14.6866 17.5707C14.5335 17.8358 14.5335 18.1626 14.6866 18.4278C14.8396 18.693 15.1226 18.8564 15.4289 18.8564H23.1431C23.4494 18.8564 23.7324 18.693 23.8854 18.4278C24.0385 18.1626 24.0385 17.8358 23.8854 17.5707C23.7324 17.3055 23.4494 17.1421 23.1431 17.1421Z" fill="#575757"/> +<path d="M23.1431 21.4298H15.4289C15.1226 21.4298 14.8396 21.5932 14.6866 21.8584C14.5335 22.1236 14.5335 22.4504 14.6866 22.7155C14.8396 22.9807 15.1226 23.1441 15.4289 23.1441H23.1431C23.4494 23.1441 23.7324 22.9807 23.8854 22.7155C24.0385 22.4504 24.0385 22.1236 23.8854 21.8584C23.7324 21.5932 23.4494 21.4298 23.1431 21.4298Z" fill="#575757"/> +</svg> diff --git a/app/client/src/ce/constants/ReduxActionConstants.tsx b/app/client/src/ce/constants/ReduxActionConstants.tsx index e256417ec7c3..7bdedcf998f1 100644 --- a/app/client/src/ce/constants/ReduxActionConstants.tsx +++ b/app/client/src/ce/constants/ReduxActionConstants.tsx @@ -30,6 +30,7 @@ export const ReduxActionTypes = { "RESET_DATASOURCE_CONFIG_FETCHED_FOR_IMPORT_FLAG", SET_UNCONFIGURED_DATASOURCES: "SET_UNCONFIGURED_DATASOURCES", SET_WORKSPACE_ID_FOR_IMPORT: "SET_WORKSPACE_ID_FOR_IMPORT", + SET_PAGE_ID_FOR_IMPORT: "SET_PAGE_ID_FOR_IMPORT", RESET_SSH_KEY_PAIR: "RESET_SSH_KEY_PAIR", GIT_INFO_INIT: "GIT_INFO_INIT", IMPORT_APPLICATION_FROM_GIT_ERROR: "IMPORT_APPLICATION_FROM_GIT_ERROR", @@ -637,6 +638,9 @@ export const ReduxActionTypes = { GET_ALL_TEMPLATES_SUCCESS: "GET_ALL_TEMPLATES_SUCCESS", UPDATE_TEMPLATE_FILTERS: "UPDATE_TEMPLATE_FILTERS", SET_TEMPLATE_SEARCH_QUERY: "SET_TEMPLATE_SEARCH_QUERY", + IMPORT_TEMPLATE_TO_APPLICATION_INIT: "IMPORT_TEMPLATE_TO_APPLICATION_INIT", + IMPORT_TEMPLATE_TO_APPLICATION_SUCCESS: + "IMPORT_TEMPLATE_TO_APPLICATION_SUCCESS", IMPORT_TEMPLATE_TO_WORKSPACE_INIT: "IMPORT_TEMPLATE_TO_WORKSPACE_INIT", IMPORT_TEMPLATE_TO_WORKSPACE_SUCCESS: "IMPORT_TEMPLATE_TO_WORKSPACE_SUCCESS", SET_TEMPLATE_NOTIFICATION_SEEN: "SET_TEMPLATE_NOTIFICATION_SEEN", @@ -658,6 +662,9 @@ export const ReduxActionTypes = { SET_ACTIVE_JS_ACTION: "SET_ACTIVE_JS_ACTION", RECORD_RECENTLY_ADDED_WIDGET: "RECORD_RECENTLY_ADDED_WIDGET", REMOVE_FROM_RECENTLY_ADDED_WIDGET: "REMOVE_FROM_RECENTLY_ADDED_WIDGET", + SHOW_TEMPLATES_MODAL: "SHOW_TEMPLATES_MODAL", + GET_TEMPLATE_FILTERS_INIT: "GET_TEMPLATE_FILTERS_INIT", + GET_TEMPLATE_FILTERS_SUCCESS: "GET_TEMPLATE_FILTERS_SUCCESS", UPDATE_CUSTOM_SLUG_INIT: "UPDATE_CUSTOM_SLUG_INIT", UPDATE_CUSTOM_SLUG_SUCCESS: "UPDATE_CUSTOM_SLUG_SUCCESS", INIT_TRIGGER_VALUES: "INIT_TRIGGER_VALUES", @@ -825,9 +832,13 @@ export const ReduxActionErrorTypes = { DELETE_APP_THEME_ERROR: "DELETE_APP_THEME_ERROR", GET_ALL_TEMPLATES_ERROR: "GET_ALL_TEMPLATES_ERROR", GET_SIMILAR_TEMPLATES_ERROR: "GET_SIMILAR_TEMPLATES_ERROR", + IMPORT_TEMPLATE_TO_ORGANISATION_ERROR: + "IMPORT_TEMPLATE_TO_ORGANISATION_ERROR", + IMPORT_TEMPLATE_TO_APPLICATION_ERROR: "IMPORT_TEMPLATE_TO_APPLICATION_ERROR", IMPORT_TEMPLATE_TO_WORKSPACE_ERROR: "IMPORT_TEMPLATE_TO_WORKSPACE_ERROR", GET_DEFAULT_PLUGINS_ERROR: "GET_DEFAULT_PLUGINS_ERROR", GET_TEMPLATE_ERROR: "GET_TEMPLATE_ERROR", + GET_TEMPLATE_FILTERS_ERROR: "GET_TEMPLATE_FILTERS_ERROR", UPDATE_CUSTOM_SLUG_ERROR: "UPDATE_CUSTOM_SLUG_ERROR", }; diff --git a/app/client/src/ce/constants/messages.ts b/app/client/src/ce/constants/messages.ts index bfdcd8bbf6a4..ea5b26f4709a 100644 --- a/app/client/src/ce/constants/messages.ts +++ b/app/client/src/ce/constants/messages.ts @@ -520,10 +520,7 @@ export const BUILD_FROM_SCRATCH_ACTION_SUBTITLE = () => export const BUILD_FROM_SCRATCH_ACTION_TITLE = () => "Build with drag & drop"; -export const GENERATE_PAGE_ACTION_TITLE = () => "Generate from a data table"; - -export const GENERATE_PAGE_ACTION_SUBTITLE = () => - "Start with a simple CRUD UI and customize it"; +export const GENERATE_PAGE_ACTION_TITLE = () => "Generate Page With Data"; export const GENERATE_PAGE_FORM_TITLE = () => "Generate from data"; @@ -1165,6 +1162,8 @@ export const CONTEXT_NO_PAGE = () => "No pages"; export const CONTEXT_REFRESH = () => "Refresh"; export const CONTEXT_CLONE = () => "Clone"; export const CONTEXT_SET_AS_HOME_PAGE = () => "Set as Home Page"; +export const PAGE = () => "Page"; +export const PAGES = () => "Pages"; // Entity explorer export const ADD_DATASOURCE_BUTTON = () => "ADD DATASOURCE"; @@ -1184,7 +1183,7 @@ export const CHOOSE_WHERE_TO_FORK = () => "Choose where to fork the template"; export const SELECT_WORKSPACE = () => "Select Workspace"; export const FORK_TEMPLATE = () => "FORK TEMPLATE"; export const TEMPLATES = () => "TEMPLATES"; -export const FORK_THIS_TEMPLATE = () => "Fork this template"; +export const FORK_THIS_TEMPLATE = () => "Use template"; export const COULDNT_FIND_TEMPLATE = () => "Couldn’t find what you are looking for?"; export const COULDNT_FIND_TEMPLATE_DESCRIPTION = () => @@ -1197,14 +1196,24 @@ export const TEMPLATE_NOTIFICATION_DESCRIPTION = () => export const GO_BACK = () => "GO BACK"; export const OVERVIEW = () => "Overview"; export const FUNCTION = () => "Function"; -export const INDUSTRY = () => "Industry"; +export const INDUSTRY = () => "Use Case"; export const DATASOURCES = () => "Datasources"; export const NOTE = () => "Note:"; export const NOTE_MESSAGE = () => "You can add your datasources as well"; -export const WIDGET_USED = () => "Widgets Used"; +export const WIDGET_USED = () => "Widgets"; export const SIMILAR_TEMPLATES = () => "Similar Templates"; export const VIEW_ALL_TEMPLATES = () => "VIEW ALL TEMPLATES"; export const FILTERS = () => "FILTERS"; +export const TEMPLATE_CARD_TITLE = () => "Start from a template"; +export const TEMPLATE_CARD_DESCRIPTION = () => + "Create app from template by selecting pages"; +export const FILTER_SELECTALL = () => "Select all"; +export const FILTER_SELECT_PAGES = () => "ADD SELECTED PAGES"; +export const FORKING_TEMPLATE = () => "Setting up the template"; +export const FETCHING_TEMPLATES = () => "Loading template details"; +export const FETCHING_TEMPLATE_LIST = () => "Loading templates list"; + +export const TEMPLATES_BACK_BUTTON = () => "BACK TO TEMPLATES"; export const IMAGE_LOAD_ERROR = () => "Unable to display the image"; @@ -1237,6 +1246,13 @@ export const CLEAN_URL_UPDATE = { export const MEMBERS_TAB_TITLE = (length: number) => `Users (${length})`; +export const CREATE_PAGE = () => "New Blank Page"; +export const CANVAS_NEW_PAGE_CARD = () => "Create New Page"; +export const GENERATE_PAGE = () => "Generate page from data table"; +export const GENERATE_PAGE_DESCRIPTION = () => + "Start app with a simple CRUD UI and customize it"; +export const ADD_PAGE_FROM_TEMPLATE = () => "Add Page From Template"; + // Alert options and labels for showMessage types export const ALERT_STYLE_OPTIONS = [ { label: "Info", value: "'info'", id: "info" }, diff --git a/app/client/src/ce/reducers/uiReducers/applicationsReducer.tsx b/app/client/src/ce/reducers/uiReducers/applicationsReducer.tsx index 71101b863bb0..53b6283a5a16 100644 --- a/app/client/src/ce/reducers/uiReducers/applicationsReducer.tsx +++ b/app/client/src/ce/reducers/uiReducers/applicationsReducer.tsx @@ -33,6 +33,7 @@ export const initialState: ApplicationsReduxState = { showAppInviteUsersDialog: false, isImportAppModalOpen: false, workspaceIdForImport: null, + pageIdForImport: "", }; export const handlers = { @@ -467,17 +468,20 @@ export const handlers = { state: ApplicationsReduxState, action: ReduxAction<string>, ) => { - let currentApplication = state.currentApplication; - if (action.payload) { - currentApplication = undefined; - } - return { ...state, - currentApplication, workspaceIdForImport: action.payload, }; }, + [ReduxActionTypes.SET_PAGE_ID_FOR_IMPORT]: ( + state: ApplicationsReduxState, + action: ReduxAction<string>, + ) => { + return { + ...state, + pageIdForImport: action.payload, + }; + }, [ReduxActionTypes.IMPORT_TEMPLATE_TO_WORKSPACE_SUCCESS]: ( state: ApplicationsReduxState, action: ReduxAction<ApplicationPayload>, @@ -514,6 +518,7 @@ export interface ApplicationsReduxState { importedApplication: unknown; isImportAppModalOpen: boolean; workspaceIdForImport: any; + pageIdForImport: string; isDatasourceConfigForImportFetched?: boolean; } diff --git a/app/client/src/constants/routes/appRoutes.ts b/app/client/src/constants/routes/appRoutes.ts index 195b011eec79..8725f3ddd56a 100644 --- a/app/client/src/constants/routes/appRoutes.ts +++ b/app/client/src/constants/routes/appRoutes.ts @@ -52,9 +52,9 @@ export const matchViewerForkPath = (pathName: string) => match(`${VIEWER_CUSTOM_PATH}${VIEWER_FORK_PATH}`)(pathName) || match(`${VIEWER_PATH_DEPRECATED}${VIEWER_FORK_PATH}`)(pathName); export const matchGeneratePagePath = (pathName: string) => - match(`${BUILDER_PATH}${GENERATE_TEMPLATE_PATH}`)(pathName) || - match(`${BUILDER_CUSTOM_PATH}${GENERATE_TEMPLATE_PATH}`)(pathName) || - match(`${BUILDER_PATH_DEPRECATED}${GENERATE_TEMPLATE_PATH}`)(pathName); + match(`${BUILDER_PATH}${GENERATE_TEMPLATE_FORM_PATH}`)(pathName) || + match(`${BUILDER_CUSTOM_PATH}${GENERATE_TEMPLATE_FORM_PATH}`)(pathName) || + match(`${BUILDER_PATH_DEPRECATED}${GENERATE_TEMPLATE_FORM_PATH}`)(pathName); export const addBranchParam = (branch: string) => { const url = new URL(window.location.href); diff --git a/app/client/src/pages/Editor/Explorer/Pages/AddPageContextMenu.tsx b/app/client/src/pages/Editor/Explorer/Pages/AddPageContextMenu.tsx new file mode 100644 index 000000000000..35cdcb692c89 --- /dev/null +++ b/app/client/src/pages/Editor/Explorer/Pages/AddPageContextMenu.tsx @@ -0,0 +1,190 @@ +import React, { useCallback, useState } from "react"; +import FileAddIcon from "remixicon-react/FileAddLineIcon"; +import Database2LineIcon from "remixicon-react/Database2LineIcon"; +import Layout2LineIcon from "remixicon-react/Layout2LineIcon"; +import { Popover2 } from "@blueprintjs/popover2"; +import { + TooltipComponent as Tooltip, + Text, + TextType, + IconWrapper, + IconSize, +} from "design-system"; +import { EntityClassNames } from "../Entity"; +import { TOOLTIP_HOVER_ON_DELAY } from "constants/AppConstants"; +import { Position } from "@blueprintjs/core"; +import EntityAddButton from "../Entity/AddButton"; +import styled from "styled-components"; +import history from "utils/history"; +import { generateTemplateFormURL } from "RouteBuilder"; +import { useParams } from "react-router"; +import { useDispatch } from "react-redux"; +import { ExplorerURLParams } from "../helpers"; +import { showTemplatesModal } from "actions/templateActions"; +import { Colors } from "constants/Colors"; +import { + ADD_PAGE_FROM_TEMPLATE, + ADD_PAGE_TOOLTIP, + CANVAS_NEW_PAGE_CARD, + createMessage, + CREATE_PAGE, + GENERATE_PAGE_ACTION_TITLE, +} from "@appsmith/constants/messages"; +import HotKeys from "../Files/SubmenuHotkeys"; + +const MenuItem = styled.div<{ active: boolean }>` + display: flex; + gap: ${(props) => props.theme.spaces[3]}px; + height: 36px; + width: 250px; + align-items: center; + padding-left: ${(props) => props.theme.spaces[7]}px; + cursor: pointer; + ${(props) => props.active && `background-color: ${Colors.GREY_2};`} + + &:hover { + background-color: ${Colors.GREY_2}; + } +`; + +const Wrapper = styled.div` + .title { + display: flex; + padding: ${(props) => + `${props.theme.spaces[4]}px ${props.theme.spaces[7]}px`}; + } +`; + +type SubMenuProps = { + className: string; + openMenu: boolean; + onMenuClose: () => void; + createPageCallback: () => void; +}; + +function AddPageContextMenu({ + className, + createPageCallback, + onMenuClose, + openMenu, +}: SubMenuProps) { + const [show, setShow] = useState(openMenu); + const dispatch = useDispatch(); + const { pageId } = useParams<ExplorerURLParams>(); + const [activeItemIdx, setActiveItemIdx] = useState(0); + + const menuRef = useCallback( + (node) => { + if (node && show) { + node.focus(); + } + }, + [show], + ); + + const ContextMenuItems = [ + { + title: createMessage(CREATE_PAGE), + icon: FileAddIcon, + onClick: createPageCallback, + "data-cy": "add-page", + }, + { + title: createMessage(GENERATE_PAGE_ACTION_TITLE), + icon: Database2LineIcon, + onClick: () => history.push(generateTemplateFormURL({ pageId })), + "data-cy": "generate-page", + }, + { + title: createMessage(ADD_PAGE_FROM_TEMPLATE), + icon: Layout2LineIcon, + onClick: () => dispatch(showTemplatesModal(true)), + "data-cy": "add-page-from-template", + }, + ]; + + const handleUpKey = useCallback(() => { + setActiveItemIdx((currentActiveIndex) => { + if (currentActiveIndex <= 0) return ContextMenuItems.length - 1; + return Math.max(currentActiveIndex - 1, 0); + }); + }, []); + + const handleDownKey = useCallback(() => { + setActiveItemIdx((currentActiveIndex) => { + if (currentActiveIndex >= ContextMenuItems.length - 1) return 0; + return Math.min(currentActiveIndex + 1, ContextMenuItems.length - 1); + }); + }, []); + + const handleSelect = () => { + const item = ContextMenuItems[activeItemIdx]; + onMenuItemClick(item); + }; + + const onMenuItemClick = (item: typeof ContextMenuItems[number]) => { + setShow(false); + item.onClick(); + }; + + return ( + <Popover2 + className="file-ops" + content={ + <HotKeys + handleDownKey={handleDownKey} + handleSubmitKey={handleSelect} + handleUpKey={handleUpKey} + > + <Wrapper ref={menuRef} tabIndex={0}> + <Text autofocus className="title" type={TextType.H5}> + {createMessage(CANVAS_NEW_PAGE_CARD)} + </Text> + {ContextMenuItems.map((item, idx) => { + const MenuIcon = item.icon; + + return ( + <MenuItem + active={idx === activeItemIdx} + data-cy={item["data-cy"]} + key={item.title} + onClick={() => onMenuItemClick(item)} + > + <IconWrapper color={Colors.GRAY_700} size={IconSize.XXL}> + <MenuIcon /> + </IconWrapper> + <Text color={Colors.MIRAGE} type={TextType.P1}> + {item.title} + </Text> + </MenuItem> + ); + })} + </Wrapper> + </HotKeys> + } + isOpen={show} + minimal + onClose={() => { + setShow(false); + onMenuClose(); + }} + placement="right-start" + > + <Tooltip + boundary="viewport" + className={EntityClassNames.TOOLTIP} + content={createMessage(ADD_PAGE_TOOLTIP)} + disabled={show} + hoverOpenDelay={TOOLTIP_HOVER_ON_DELAY} + position={Position.RIGHT} + > + <EntityAddButton + className={`${className} ${show ? "selected" : ""}`} + onClick={() => setShow(true)} + /> + </Tooltip> + </Popover2> + ); +} + +export default AddPageContextMenu; diff --git a/app/client/src/pages/Editor/Explorer/Pages/index.tsx b/app/client/src/pages/Editor/Explorer/Pages/index.tsx index 12419f3bf238..f5238fbaac2a 100644 --- a/app/client/src/pages/Editor/Explorer/Pages/index.tsx +++ b/app/client/src/pages/Editor/Explorer/Pages/index.tsx @@ -1,4 +1,10 @@ -import React, { useCallback, useMemo, useEffect, useRef } from "react"; +import React, { + useCallback, + useMemo, + useEffect, + useRef, + useState, +} from "react"; import { useDispatch, useSelector } from "react-redux"; import { getCurrentApplicationId, @@ -37,6 +43,7 @@ import useResize, { DIRECTION, CallbackResponseType, } from "utils/hooks/useResize"; +import AddPageContextMenu from "./AddPageContextMenu"; import AnalyticsUtil from "utils/AnalyticsUtil"; import { useLocation } from "react-router"; import { toggleInOnboardingWidgetSelection } from "actions/onboardingActions"; @@ -121,6 +128,8 @@ function Pages() { [location.pathname], ); + const [isMenuOpen, openMenu] = useState(false); + const createPageCallback = useCallback(() => { const name = getNextEntityName( "Page", @@ -133,6 +142,8 @@ function Pages() { dispatch(createPage(applicationId, name, defaultPageLayouts)); }, [dispatch, pages, applicationId]); + const onMenuClose = useCallback(() => openMenu(false), [openMenu]); + const settingsIconWithTooltip = React.useMemo( () => ( <TooltipComponent @@ -220,13 +231,20 @@ function Pages() { alwaysShowRightIcon className="group pages" collapseRef={pageResizeRef} + customAddButton={ + <AddPageContextMenu + className={`${EntityClassNames.ADD_BUTTON} group pages`} + createPageCallback={createPageCallback} + onMenuClose={onMenuClose} + openMenu={isMenuOpen} + /> + } entityId="Pages" icon={""} isDefaultExpanded={isPagesOpen === null ? true : isPagesOpen} name="Pages" onClickPreRightIcon={onPin} onClickRightIcon={onClickRightIcon} - onCreate={createPageCallback} onToggle={onPageToggle} pagesSize={ENTITY_HEIGHT * pages.length} rightIcon={settingsIconWithTooltip} diff --git a/app/client/src/pages/Editor/GeneratePage/components/ActionCard.tsx b/app/client/src/pages/Editor/GeneratePage/components/ActionCard.tsx deleted file mode 100644 index adb778e7c272..000000000000 --- a/app/client/src/pages/Editor/GeneratePage/components/ActionCard.tsx +++ /dev/null @@ -1,87 +0,0 @@ -import React, { JSXElementConstructor } from "react"; -import { IconProps } from "constants/IconConstants"; - -import { Colors } from "constants/Colors"; -import styled from "styled-components"; -import { getTypographyByKey } from "constants/DefaultTheme"; - -export const IconWrapper = styled.div` - flex: 1; - display: flex; - justify-content: center; - align-items: center; -`; - -const RoundBg = styled.div` - width: 40px; - height: 40px; - border-radius: 40px; - background-color: ${Colors.Gallery}; - display: flex; - justify-content: center; - align-items: center; -`; - -export const DescWrapper = styled.div` - flex: 1; - display: flex; - flex-direction: column; - align-items: center; - margin: 20px 0px; -`; - -export const Title = styled.p` - ${(props) => getTypographyByKey(props, "p1")}; - font-weight: 500; - color: ${Colors.CODE_GRAY}; - font-size: 14px; -`; - -export const SubTitle = styled.p` - ${(props) => getTypographyByKey(props, "p1")}; - color: ${Colors.GRAY}; -`; - -const CardWrapper = styled.button` - display: flex; - flex-direction: column; - justify-content: center; - align-items: center; - padding: 20px 30px 10px; - cursor: pointer; - height: 200px; - width: 320px; - margin: 0px 10px; - border: 1px solid ${Colors.MERCURY}; - background-color: ${Colors.WHITE}; - &:hover { - background-color: ${Colors.Gallery}; - } -`; - -type actionCardProps = { - Icon: JSXElementConstructor<IconProps>; - onClick: (e: React.MouseEvent) => void; - subTitle: string; - title: string; - className: string; -}; - -function ActionCard(props: actionCardProps) { - const { className, Icon, onClick } = props; - return ( - <CardWrapper className={className} onClick={onClick}> - <IconWrapper> - <RoundBg> - <Icon color={Colors.GRAY2} height={22} width={22} /> - </RoundBg> - </IconWrapper> - <DescWrapper> - <Title>{props.title}</Title> - <SubTitle>{props.subTitle}</SubTitle> - </DescWrapper> - </CardWrapper> - ); -} - -export default ActionCard; diff --git a/app/client/src/pages/Editor/GeneratePage/components/ActionCards.tsx b/app/client/src/pages/Editor/GeneratePage/components/ActionCards.tsx deleted file mode 100644 index 3a1e70b67cff..000000000000 --- a/app/client/src/pages/Editor/GeneratePage/components/ActionCards.tsx +++ /dev/null @@ -1,66 +0,0 @@ -import React from "react"; -import ActionCard from "./ActionCard"; -import { FormIcons } from "icons/FormIcons"; -import history from "utils/history"; -import { Icon, IconSize } from "design-system"; -import { useParams } from "react-router"; -import { ExplorerURLParams } from "../../Explorer/helpers"; -import { - GENERATE_PAGE_ACTION_SUBTITLE, - GENERATE_PAGE_ACTION_TITLE, - BUILD_FROM_SCRATCH_ACTION_TITLE, - BUILD_FROM_SCRATCH_ACTION_SUBTITLE, -} from "@appsmith/constants/messages"; -import AnalyticsUtil from "utils/AnalyticsUtil"; -import { builderURL, generateTemplateFormURL } from "RouteBuilder"; - -type routeId = { - pageId: string; -}; - -const routeToEmptyEditorFromGenPage = ({ pageId }: routeId): void => { - AnalyticsUtil.logEvent("BUILD_FROM_SCRATCH_ACTION_CARD_CLICK"); - history.push(builderURL({ pageId })); -}; - -const goToGenPageForm = ({ pageId }: routeId): void => { - AnalyticsUtil.logEvent("GEN_CRUD_PAGE_ACTION_CARD_CLICK"); - history.push(generateTemplateFormURL({ pageId })); -}; - -function ActionCards() { - const { pageId } = useParams<ExplorerURLParams>(); - - return ( - <> - <ActionCard - Icon={FormIcons.CREATE_NEW_ICON} - className="t--BuildFromScratch" - onClick={() => - routeToEmptyEditorFromGenPage({ - pageId, - }) - } - subTitle={BUILD_FROM_SCRATCH_ACTION_SUBTITLE()} - title={BUILD_FROM_SCRATCH_ACTION_TITLE()} - /> - - <ActionCard - Icon={({ color }) => ( - <Icon - fillColor={color} - hoverFillColor={color} - name="wand" - size={IconSize.LARGE} - /> - )} - className="t--GenerateCRUDPage" - onClick={() => goToGenPageForm({ pageId })} - subTitle={GENERATE_PAGE_ACTION_SUBTITLE()} - title={GENERATE_PAGE_ACTION_TITLE()} - /> - </> - ); -} - -export default ActionCards; diff --git a/app/client/src/pages/Editor/GeneratePage/components/GeneratePageForm/GeneratePageForm.tsx b/app/client/src/pages/Editor/GeneratePage/components/GeneratePageForm/GeneratePageForm.tsx index 8da36eadcb42..321de963dff2 100644 --- a/app/client/src/pages/Editor/GeneratePage/components/GeneratePageForm/GeneratePageForm.tsx +++ b/app/client/src/pages/Editor/GeneratePage/components/GeneratePageForm/GeneratePageForm.tsx @@ -9,6 +9,7 @@ import { getGenerateCRUDEnabledPluginMap, getIsFetchingSinglePluginForm, getDatasourcesStructure, + getNumberOfEntitiesInCurrentPage, } from "selectors/entitiesSelector"; import { Datasource } from "entities/Datasource"; @@ -181,7 +182,12 @@ function GeneratePageForm() { const datasources: Datasource[] = useSelector(getDatasources); const isGeneratingTemplatePage = useSelector(getIsGeneratingTemplatePage); - const currentMode = useRef(GENERATE_PAGE_MODE.REPLACE_EMPTY); + const numberOfEntities = useSelector(getNumberOfEntitiesInCurrentPage); + const currentMode = useRef( + numberOfEntities > 0 + ? GENERATE_PAGE_MODE.NEW + : GENERATE_PAGE_MODE.REPLACE_EMPTY, + ); const [datasourceIdToBeSelected, setDatasourceIdToBeSelected] = useState< string diff --git a/app/client/src/pages/Editor/GeneratePage/components/PageContent.tsx b/app/client/src/pages/Editor/GeneratePage/components/PageContent.tsx index d51252b2db2a..f24cd69776fa 100644 --- a/app/client/src/pages/Editor/GeneratePage/components/PageContent.tsx +++ b/app/client/src/pages/Editor/GeneratePage/components/PageContent.tsx @@ -1,5 +1,4 @@ import React from "react"; -import ActionCards from "./ActionCards"; import styled from "constants/DefaultTheme"; import GeneratePageForm from "./GeneratePageForm/GeneratePageForm"; @@ -11,11 +10,9 @@ const Container = styled.div` `; function PageContent() { - const pathname = window.location.pathname; - const hasFormRoute = pathname.includes("/form"); return ( <Container> - {!hasFormRoute ? <ActionCards /> : <GeneratePageForm />} + <GeneratePageForm /> </Container> ); } diff --git a/app/client/src/pages/Editor/GlobalHotKeys/GlobalHotKeys.tsx b/app/client/src/pages/Editor/GlobalHotKeys/GlobalHotKeys.tsx index 1d649d0729aa..9f8c0ee6a146 100644 --- a/app/client/src/pages/Editor/GlobalHotKeys/GlobalHotKeys.tsx +++ b/app/client/src/pages/Editor/GlobalHotKeys/GlobalHotKeys.tsx @@ -49,7 +49,7 @@ import { getExplorerPinned } from "selectors/explorerSelector"; import { setExplorerPinnedAction } from "actions/explorerActions"; import { setIsGitSyncModalOpen } from "actions/gitSyncActions"; import { GitSyncModalTab } from "entities/GitSync"; -import { matchBuilderPath, matchGeneratePagePath } from "constants/routes"; +import { matchBuilderPath } from "constants/routes"; type Props = { copySelectedWidget: () => void; @@ -213,10 +213,7 @@ class GlobalHotKeys extends React.Component<Props> { group="Canvas" label="Paste Widget" onKeyDown={() => { - if ( - matchBuilderPath(window.location.pathname) || - matchGeneratePagePath(window.location.pathname) - ) { + if (matchBuilderPath(window.location.pathname)) { this.props.pasteCopiedWidget( this.props.getMousePosition() || { x: 0, y: 0 }, ); diff --git a/app/client/src/pages/Editor/WidgetsEditor/CanvasContainer.tsx b/app/client/src/pages/Editor/WidgetsEditor/CanvasContainer.tsx index 4784781b8664..89008e2f3157 100644 --- a/app/client/src/pages/Editor/WidgetsEditor/CanvasContainer.tsx +++ b/app/client/src/pages/Editor/WidgetsEditor/CanvasContainer.tsx @@ -6,6 +6,7 @@ import { getViewModePageList, previewModeSelector, getCanvasWidth, + showCanvasTopSectionSelector, } from "selectors/editorSelectors"; import styled from "styled-components"; import { getCanvasClassName } from "utils/generators"; @@ -60,6 +61,7 @@ function CanvasContainer() { const params = useParams<{ applicationId: string; pageId: string }>(); const shouldHaveTopMargin = !isPreviewMode || pages.length > 1; const isAppThemeChanging = useSelector(getAppThemeIsChanging); + const showCanvasTopSection = useSelector(showCanvasTopSectionSelector); const isLayoutingInitialized = useDynamicAppLayout(); const isPageInitializing = isFetchingPage || !isLayoutingInitialized; @@ -105,7 +107,8 @@ function CanvasContainer() { className={classNames({ [`${getCanvasClassName()} scrollbar-thin`]: true, "mt-0": !shouldHaveTopMargin, - "mt-8": shouldHaveTopMargin, + "mt-4": showCanvasTopSection, + "mt-8": shouldHaveTopMargin && !showCanvasTopSection, })} key={currentPageId} style={{ diff --git a/app/client/src/pages/Editor/WidgetsEditor/EmptyCanvasSection.tsx b/app/client/src/pages/Editor/WidgetsEditor/EmptyCanvasSection.tsx new file mode 100644 index 000000000000..6bb64cdc9475 --- /dev/null +++ b/app/client/src/pages/Editor/WidgetsEditor/EmptyCanvasSection.tsx @@ -0,0 +1,116 @@ +import React from "react"; +import styled from "styled-components"; +import { ReactComponent as Layout } from "assets/images/layout.svg"; +import { ReactComponent as Database } from "assets/images/database.svg"; +import { Text, TextType } from "design-system"; +import { Colors } from "constants/Colors"; +import { useDispatch, useSelector } from "react-redux"; +import { + selectURLSlugs, + showCanvasTopSectionSelector, +} from "selectors/editorSelectors"; +import AnalyticsUtil from "utils/AnalyticsUtil"; +import history from "utils/history"; +import { generateTemplateFormURL } from "RouteBuilder"; +import { useParams } from "react-router"; +import { ExplorerURLParams } from "../Explorer/helpers"; +import { showTemplatesModal as showTemplatesModalAction } from "actions/templateActions"; +import { + createMessage, + GENERATE_PAGE, + GENERATE_PAGE_DESCRIPTION, + TEMPLATE_CARD_DESCRIPTION, + TEMPLATE_CARD_TITLE, +} from "ce/constants/messages"; + +const Wrapper = styled.div` + margin: ${(props) => + `${props.theme.spaces[7]}px ${props.theme.spaces[16]}px 0px ${props.theme.spaces[13]}px`}; + display: flex; + flex-direction: row; + gap: ${(props) => props.theme.spaces[7]}px; +`; + +const Card = styled.div` + padding: ${(props) => + `${props.theme.spaces[5]}px ${props.theme.spaces[9]}px`}; + border: solid 1px ${Colors.GREY_4}; + background-color: ${Colors.WHITE}; + flex: 1; + display: flex; + flex-direction: row; + align-items: center; + cursor: pointer; + transition: all 0.5s; + + svg { + height: 24px; + width: 24px; + } + + &:hover { + background-color: ${Colors.GREY_2}; + } +`; + +const Content = styled.div` + display: flex; + flex-direction: column; + padding-left: ${(props) => props.theme.spaces[7]}px; +`; + +type routeId = { + applicationSlug: string; + pageId: string; + pageSlug: string; +}; + +const goToGenPageForm = ({ pageId }: routeId): void => { + AnalyticsUtil.logEvent("GEN_CRUD_PAGE_ACTION_CARD_CLICK"); + history.push(generateTemplateFormURL({ pageId })); +}; + +function CanvasTopSection() { + const dispatch = useDispatch(); + const showCanvasTopSection = useSelector(showCanvasTopSectionSelector); + const { pageId } = useParams<ExplorerURLParams>(); + const { applicationSlug, pageSlug } = useSelector(selectURLSlugs); + + if (!showCanvasTopSection) return null; + + const showTemplatesModal = () => { + dispatch(showTemplatesModalAction(true)); + }; + + return ( + <Wrapper> + <Card data-cy="start-from-template" onClick={showTemplatesModal}> + <Layout /> + <Content> + <Text color={Colors.COD_GRAY} type={TextType.P1}> + {createMessage(TEMPLATE_CARD_TITLE)} + </Text> + <Text type={TextType.P3}> + {createMessage(TEMPLATE_CARD_DESCRIPTION)} + </Text> + </Content> + </Card> + <Card + data-cy="generate-app" + onClick={() => goToGenPageForm({ applicationSlug, pageSlug, pageId })} + > + <Database /> + <Content> + <Text color={Colors.COD_GRAY} type={TextType.P1}> + {createMessage(GENERATE_PAGE)} + </Text> + <Text type={TextType.P3}> + {createMessage(GENERATE_PAGE_DESCRIPTION)} + </Text> + </Content> + </Card> + </Wrapper> + ); +} + +export default CanvasTopSection; diff --git a/app/client/src/pages/Editor/WidgetsEditor/index.tsx b/app/client/src/pages/Editor/WidgetsEditor/index.tsx index fc9ffc4e81a6..c3e2dbdb901a 100644 --- a/app/client/src/pages/Editor/WidgetsEditor/index.tsx +++ b/app/client/src/pages/Editor/WidgetsEditor/index.tsx @@ -28,6 +28,7 @@ import { import EditorContextProvider from "components/editorComponents/EditorContextProvider"; import Guide from "../GuidedTour/Guide"; import PropertyPaneContainer from "./PropertyPaneContainer"; +import CanvasTopSection from "./EmptyCanvasSection"; /* eslint-disable react/display-name */ function WidgetsEditor() { @@ -108,17 +109,20 @@ function WidgetsEditor() { <> {guidedTourEnabled && <Guide />} <div className="relative flex flex-row w-full overflow-hidden"> - <div - className="relative flex flex-row w-full overflow-hidden" - data-testid="widgets-editor" - draggable - onClick={handleWrapperClick} - onDragStart={onDragStart} - > - <PageTabs /> - <CanvasContainer /> - <CrudInfoModal /> - <Debugger /> + <div className="relative flex flex-col w-full overflow-hidden"> + <CanvasTopSection /> + <div + className="relative flex flex-row w-full overflow-hidden" + data-testid="widgets-editor" + draggable + onClick={handleWrapperClick} + onDragStart={onDragStart} + > + <PageTabs /> + <CanvasContainer /> + <CrudInfoModal /> + <Debugger /> + </div> </div> <PropertyPaneContainer /> </div> diff --git a/app/client/src/pages/Editor/gitSync/ReconnectDatasourceModal.tsx b/app/client/src/pages/Editor/gitSync/ReconnectDatasourceModal.tsx index 139b37a389a8..9e92708f136c 100644 --- a/app/client/src/pages/Editor/gitSync/ReconnectDatasourceModal.tsx +++ b/app/client/src/pages/Editor/gitSync/ReconnectDatasourceModal.tsx @@ -6,6 +6,7 @@ import { getIsDatasourceConfigForImportFetched, getWorkspaceIdForImport, getUserApplicationsWorkspacesList, + getPageIdForImport, } from "selectors/applicationSelectors"; import { useDispatch, useSelector } from "react-redux"; @@ -23,7 +24,6 @@ import { } from "design-system"; import { Colors } from "constants/Colors"; -import GitErrorPopup from "./components/GitErrorPopup"; import styled, { useTheme } from "styled-components"; import { get } from "lodash"; import { Title } from "./components/StyledComponents"; @@ -51,6 +51,7 @@ import { initDatasourceConnectionDuringImportRequest, resetDatasourceConfigForImportFetchedFlag, setIsReconnectingDatasourcesModalOpen, + setPageIdForImport, setWorkspaceIdForImport, } from "actions/applicationActions"; import { AuthType, Datasource } from "entities/Datasource"; @@ -274,6 +275,7 @@ function ReconnectDatasourceModal() { const dispatch = useDispatch(); const isModalOpen = useSelector(getIsReconnectingDatasourcesModalOpen); const workspaceId = useSelector(getWorkspaceIdForImport); + const pageIdForImport = useSelector(getPageIdForImport); const datasources = useSelector(getUnconfiguredDatasources); const pluginImages = useSelector(getPluginImages); const pluginNames = useSelector(getPluginNames); @@ -344,7 +346,9 @@ function ReconnectDatasourceModal() { dispatch(setWorkspaceIdForImport(workspace.id)); dispatch(setIsReconnectingDatasourcesModalOpen({ isOpen: true })); const defaultPageId = getDefaultPageId(application.pages); - if (defaultPageId) { + if (pageIdForImport) { + setPageId(pageIdForImport); + } else if (defaultPageId) { setPageId(defaultPageId); } if (!datasources.length) { @@ -391,6 +395,7 @@ function ReconnectDatasourceModal() { localStorage.setItem("importedAppPendingInfo", "null"); dispatch(setIsReconnectingDatasourcesModalOpen({ isOpen: false })); dispatch(setWorkspaceIdForImport("")); + dispatch(setPageIdForImport("")); dispatch(resetDatasourceConfigForImportFetchedFlag()); setSelectedDatasourceId(""); }, [dispatch, setIsReconnectingDatasourcesModalOpen, isModalOpen]); @@ -521,86 +526,83 @@ function ReconnectDatasourceModal() { isConfigFetched && !isLoading && !datasource?.isConfigured; return ( - <> - <Dialog - canEscapeKeyClose - canOutsideClickClose - className={Classes.RECONNECT_DATASOURCE_MODAL} - isOpen={isModalOpen} - maxWidth={"1300px"} - onClose={handleClose} - width={"1293px"} - > - <Container> - <TabsContainer> - <TabMenu - activeTabIndex={0} - onSelect={() => undefined} - options={menuOptions} - /> - </TabsContainer> - <BodyContainer> - <Title> - {createMessage(RECONNECT_MISSING_DATASOURCE_CREDENTIALS)} - </Title> - <Section> - <Text color={Colors.BLACK} type={TextType.P1}> - {createMessage( - RECONNECT_MISSING_DATASOURCE_CREDENTIALS_DESCRIPTION, - )} - </Text> - </Section> - <ContentWrapper> - <ListContainer>{mappedDataSources}</ListContainer> - {shouldShowDBForm && ( - <DBFormWrapper> - <DatasourceForm - applicationId={appId} - datasourceId={selectedDatasourceId} - fromImporting - pageId={pageId} - /> - </DBFormWrapper> + <Dialog + canEscapeKeyClose + canOutsideClickClose + className={Classes.RECONNECT_DATASOURCE_MODAL} + isOpen={isModalOpen} + maxWidth={"1300px"} + onClose={handleClose} + width={"1293px"} + > + <Container> + <TabsContainer> + <TabMenu + activeTabIndex={0} + onSelect={() => undefined} + options={menuOptions} + /> + </TabsContainer> + <BodyContainer> + <Title> + {createMessage(RECONNECT_MISSING_DATASOURCE_CREDENTIALS)} + </Title> + <Section> + <Text color={Colors.BLACK} type={TextType.P1}> + {createMessage( + RECONNECT_MISSING_DATASOURCE_CREDENTIALS_DESCRIPTION, )} - {datasource?.isConfigured && SuccessMessages()} - </ContentWrapper> - </BodyContainer> - <SkipToAppButtonWrapper> - <TooltipComponent - boundary="viewport" - content={<TooltipContent />} - maxWidth="320px" - position="bottom-right" - > - <Button - category={Category.tertiary} - className="t--skip-to-application-btn" - href={appURL} - onClick={() => { - AnalyticsUtil.logEvent( - "RECONNECTING_SKIP_TO_APPLICATION_BUTTON_CLICK", - ); - localStorage.setItem("importedAppPendingInfo", "null"); - }} - size={Size.medium} - text={createMessage(SKIP_TO_APPLICATION)} - /> - </TooltipComponent> - </SkipToAppButtonWrapper> - <CloseBtnContainer - className="t--reconnect-close-btn" - onClick={handleClose} + </Text> + </Section> + <ContentWrapper> + <ListContainer>{mappedDataSources}</ListContainer> + {shouldShowDBForm && ( + <DBFormWrapper> + <DatasourceForm + applicationId={appId} + datasourceId={selectedDatasourceId} + fromImporting + pageId={pageId} + /> + </DBFormWrapper> + )} + {datasource?.isConfigured && SuccessMessages()} + </ContentWrapper> + </BodyContainer> + <SkipToAppButtonWrapper> + <TooltipComponent + boundary="viewport" + content={<TooltipContent />} + maxWidth="320px" + position="bottom-right" > - <Icon - fillColor={get(theme, "colors.gitSyncModal.closeIcon")} - name="close-modal" - size={IconSize.XXXXL} + <Button + category={Category.tertiary} + className="t--skip-to-application-btn" + href={appURL} + onClick={() => { + AnalyticsUtil.logEvent( + "RECONNECTING_SKIP_TO_APPLICATION_BUTTON_CLICK", + ); + localStorage.setItem("importedAppPendingInfo", "null"); + }} + size={Size.medium} + text={createMessage(SKIP_TO_APPLICATION)} /> - </CloseBtnContainer> - </Container> - </Dialog> - <GitErrorPopup /> - </> + </TooltipComponent> + </SkipToAppButtonWrapper> + <CloseBtnContainer + className="t--reconnect-close-btn" + onClick={handleClose} + > + <Icon + fillColor={get(theme, "colors.gitSyncModal.closeIcon")} + name="close-modal" + size={IconSize.XXXXL} + /> + </CloseBtnContainer> + </Container> + </Dialog> ); } diff --git a/app/client/src/pages/Editor/index.tsx b/app/client/src/pages/Editor/index.tsx index dbb28a579c2a..4be155d90fc7 100644 --- a/app/client/src/pages/Editor/index.tsx +++ b/app/client/src/pages/Editor/index.tsx @@ -53,6 +53,8 @@ import ImportedApplicationSuccessModal from "./gitSync/ImportedAppSuccessModal"; import { getIsBranchUpdated } from "../utils"; import { APP_MODE } from "entities/App"; import { GIT_BRANCH_QUERY_KEY } from "constants/routes"; +import TemplatesModal from "pages/Templates/TemplatesModal"; +import ReconnectDatasourceModal from "./gitSync/ReconnectDatasourceModal"; type EditorProps = { currentApplicationId?: string; @@ -235,7 +237,9 @@ class Editor extends Component<Props> { <DisconnectGitModal /> <GuidedTourModal /> <RepoLimitExceededErrorModal /> + <TemplatesModal /> <ImportedApplicationSuccessModal /> + <ReconnectDatasourceModal /> </GlobalHotKeys> </div> <RequestConfirmationModal /> diff --git a/app/client/src/pages/Editor/routes.tsx b/app/client/src/pages/Editor/routes.tsx index 79cbf8765b80..cbb26d828483 100644 --- a/app/client/src/pages/Editor/routes.tsx +++ b/app/client/src/pages/Editor/routes.tsx @@ -19,7 +19,6 @@ import { PAGE_LIST_EDITOR_PATH, DATA_SOURCES_EDITOR_ID_PATH, PROVIDER_TEMPLATE_PATH, - GENERATE_TEMPLATE_PATH, GENERATE_TEMPLATE_FORM_PATH, matchBuilderPath, BUILDER_CHECKLIST_PATH, @@ -155,11 +154,6 @@ function EditorsRouter() { exact path={`${path}${PROVIDER_TEMPLATE_PATH}`} /> - <SentryRoute - component={GeneratePage} - exact - path={`${path}${GENERATE_TEMPLATE_PATH}`} - /> <SentryRoute component={GeneratePage} exact diff --git a/app/client/src/pages/Templates/Filters.tsx b/app/client/src/pages/Templates/Filters.tsx index 255dcc598544..52765700dc24 100644 --- a/app/client/src/pages/Templates/Filters.tsx +++ b/app/client/src/pages/Templates/Filters.tsx @@ -2,18 +2,16 @@ import React from "react"; import styled from "styled-components"; import { useDispatch, useSelector } from "react-redux"; import { Collapse } from "@blueprintjs/core"; -import { Classes } from "components/ads/common"; -import { Icon, IconSize, Text, TextType } from "design-system"; +import { Checkbox, Text, TextType } from "design-system"; import { filterTemplates } from "actions/templateActions"; import { createMessage, FILTERS } from "@appsmith/constants/messages"; import { getFilterListSelector, getTemplateFilterSelector, } from "selectors/templatesSelectors"; -import LeftPaneBottomSection from "pages/Home/LeftPaneBottomSection"; import { thinScrollbar } from "constants/DefaultTheme"; -import { Colors } from "constants/Colors"; import AnalyticsUtil from "utils/AnalyticsUtil"; +import { Colors } from "constants/Colors"; const FilterWrapper = styled.div` overflow: auto; @@ -31,48 +29,11 @@ const FilterWrapper = styled.div` } `; -const Wrapper = styled.div` - width: ${(props) => props.theme.homePage.sidebar}px; - height: 100%; - display: flex; - padding-left: ${(props) => props.theme.spaces[7]}px; - padding-top: ${(props) => props.theme.spaces[11]}px; - flex-direction: column; -`; - -const SecondWrapper = styled.div` - height: calc( - 100vh - ${(props) => props.theme.homePage.header + props.theme.spaces[11]}px - ); - position: relative; -`; - -const StyledFilterItem = styled.div<{ selected: boolean }>` - cursor: pointer; - display: flex; - flex-direction: row; - align-items: center; - justify-content: space-between; +const FilterItemWrapper = styled.div<{ selected: boolean }>` padding: ${(props) => - `${props.theme.spaces[2]}px ${props.theme.spaces[6]}px ${props.theme.spaces[2]}px ${props.theme.spaces[11]}px`}; - .${Classes.TEXT} { - color: ${Colors.MIRAGE_2}; - } - ${(props) => - props.selected && - ` - background-color: ${Colors.GALLERY_1}; - .${Classes.TEXT} { - color: ${Colors.EBONY_CLAY_2}; - } - `} - - .${Classes.ICON} { - visibility: ${(props) => (props.selected ? "visible" : "hidden")}; - } - - &:hover { - background-color: ${Colors.GALLERY_1}; + `${props.theme.spaces[4]}px 0px 0px ${props.theme.spaces[11]}px`}; + .filter input + span { + ${(props) => !props.selected && `border: 1.8px solid ${Colors.GRAY_400};`} } `; @@ -125,12 +86,15 @@ function FilterItem({ item, onSelect, selected }: FilterItemProps) { }; return ( - <StyledFilterItem onClick={onClick} selected={selected}> - <Text color={Colors.MIRAGE_2} type={TextType.P1}> - {item.label} - </Text> - <Icon name={"close-x"} size={IconSize.XXXL} /> - </StyledFilterItem> + <FilterItemWrapper selected={selected}> + <Checkbox + backgroundColor={Colors.GREY_900} + className="filter" + isDefaultChecked={selected} + label={item.label} + onCheckChange={onClick} + /> + </FilterItemWrapper> ); } @@ -219,26 +183,21 @@ function Filters() { const selectedFilters = useSelector(getTemplateFilterSelector); return ( - <Wrapper> - <SecondWrapper> - <FilterWrapper> - <StyledFilterCategory className={"title"} type={TextType.H5}> - {createMessage(FILTERS)} - </StyledFilterCategory> - {Object.keys(filters).map((filter) => { - return ( - <FilterCategory - filterList={filters[filter]} - key={filter} - label={filter} - selectedFilters={selectedFilters[filter] ?? []} - /> - ); - })} - </FilterWrapper> - <LeftPaneBottomSection /> - </SecondWrapper> - </Wrapper> + <FilterWrapper className="filter-wrapper"> + <StyledFilterCategory className={"title"} type={TextType.H5}> + {createMessage(FILTERS)} + </StyledFilterCategory> + {Object.keys(filters).map((filter) => { + return ( + <FilterCategory + filterList={filters[filter]} + key={filter} + label={filter} + selectedFilters={selectedFilters[filter] ?? []} + /> + ); + })} + </FilterWrapper> ); } diff --git a/app/client/src/pages/Templates/ForkTemplate.tsx b/app/client/src/pages/Templates/ForkTemplate.tsx index 49ccfc34c445..fe85a58afd2b 100644 --- a/app/client/src/pages/Templates/ForkTemplate.tsx +++ b/app/client/src/pages/Templates/ForkTemplate.tsx @@ -59,46 +59,52 @@ function ForkTemplate({ }; return ( - <StyledDialog - canOutsideClickClose={!isImportingTemplate} - headerIcon={{ name: "fork-2", bgColor: Colors.GEYSER_LIGHT }} - isOpen={showForkModal} - onClose={isImportingTemplate ? noop : onClose} - title={createMessage(CHOOSE_WHERE_TO_FORK)} - trigger={children} - > - <Dropdown - boundary="viewport" - dropdownMaxHeight={"200px"} - fillOptions - onSelect={(_value: string, dropdownOption: any) => - setSelectedWorkspace(dropdownOption) - } - options={workspaceList} - placeholder={createMessage(SELECT_WORKSPACE)} - selected={selectedWorkspace} - showLabelOnly - width={"100%"} - /> - <ButtonsWrapper> - <Button - category={Category.tertiary} - disabled={isImportingTemplate} - onClick={onClose} - size={Size.large} - tag="button" - text={createMessage(CANCEL)} + <> + {children} + <StyledDialog + canOutsideClickClose={!isImportingTemplate} + headerIcon={{ name: "fork-2", bgColor: Colors.GEYSER_LIGHT }} + isOpen={showForkModal} + onClose={isImportingTemplate ? noop : onClose} + title={createMessage(CHOOSE_WHERE_TO_FORK)} + > + <Dropdown + boundary="viewport" + dropdownMaxHeight={"200px"} + fillOptions + onSelect={( + _value: any, + dropdownOption: React.SetStateAction<{ + label: string; + value: string; + }>, + ) => setSelectedWorkspace(dropdownOption)} + options={workspaceList} + placeholder={createMessage(SELECT_WORKSPACE)} + selected={selectedWorkspace} + showLabelOnly + width={"100%"} /> - <Button - className="t--fork-template-button" - isLoading={isImportingTemplate} - onClick={onFork} - size={Size.large} - tag="button" - text={createMessage(FORK_TEMPLATE)} - /> - </ButtonsWrapper> - </StyledDialog> + <ButtonsWrapper> + <Button + category={Category.tertiary} + disabled={isImportingTemplate} + onClick={onClose} + size={Size.large} + tag="button" + text={createMessage(CANCEL)} + /> + <Button + className="t--fork-template-button" + isLoading={isImportingTemplate} + onClick={onFork} + size={Size.large} + tag="button" + text={createMessage(FORK_TEMPLATE)} + /> + </ButtonsWrapper> + </StyledDialog> + </> ); } diff --git a/app/client/src/pages/Templates/Template/SimilarTemplates.tsx b/app/client/src/pages/Templates/Template/SimilarTemplates.tsx new file mode 100644 index 000000000000..5613ea972f83 --- /dev/null +++ b/app/client/src/pages/Templates/Template/SimilarTemplates.tsx @@ -0,0 +1,88 @@ +import { + createMessage, + SIMILAR_TEMPLATES, + VIEW_ALL_TEMPLATES, +} from "@appsmith/constants/messages"; +import { Template as TemplateInterface } from "api/TemplatesApi"; +import { FontWeight, TextType, Text, Icon, IconSize } from "design-system"; +import React from "react"; +import Masonry, { MasonryProps } from "react-masonry-css"; +import styled from "styled-components"; +import Template from "."; +import { Section } from "./TemplateDescription"; + +export const SimilarTemplatesWrapper = styled.div` + padding-right: 132px; + padding-left: 132px; + + .grid { + display: flex; + margin-left: ${(props) => -props.theme.spaces[9]}px; + margin-top: ${(props) => props.theme.spaces[12]}px; + } + + .grid_column { + padding-left: ${(props) => props.theme.spaces[9]}px; + } +`; + +export const SimilarTemplatesTitleWrapper = styled.div` + display: flex; + align-items: center; + justify-content: space-between; +`; + +const BackButtonWrapper = styled.div<{ width?: number }>` + cursor: pointer; + display: flex; + align-items: center; + gap: ${(props) => props.theme.spaces[2]}px; + ${(props) => props.width && `width: ${props.width};`} +`; + +type SimilarTemplatesProp = { + similarTemplates: TemplateInterface[]; + onBackPress: () => void; + breakpointCols: MasonryProps["breakpointCols"]; + onClick: (template: TemplateInterface) => void; + onFork?: (template: TemplateInterface) => void; + className?: string; +}; + +function SimilarTemplates(props: SimilarTemplatesProp) { + if (!props.similarTemplates.length) { + return null; + } + + return ( + <SimilarTemplatesWrapper className={props.className}> + <Section> + <SimilarTemplatesTitleWrapper> + <Text type={TextType.H1} weight={FontWeight.BOLD}> + {createMessage(SIMILAR_TEMPLATES)} + </Text> + <BackButtonWrapper onClick={props.onBackPress}> + <Text type={TextType.P4}>{createMessage(VIEW_ALL_TEMPLATES)}</Text> + <Icon name="view-all" size={IconSize.XL} /> + </BackButtonWrapper> + </SimilarTemplatesTitleWrapper> + <Masonry + breakpointCols={props.breakpointCols} + className="grid" + columnClassName="grid_column" + > + {props.similarTemplates.map((template) => ( + <Template + key={template.id} + onClick={() => props.onClick(template)} + onForkTemplateClick={props.onFork} + template={template} + /> + ))} + </Masonry> + </Section> + </SimilarTemplatesWrapper> + ); +} + +export default SimilarTemplates; diff --git a/app/client/src/pages/Templates/Template/TemplateDescription.tsx b/app/client/src/pages/Templates/Template/TemplateDescription.tsx new file mode 100644 index 000000000000..d895819f76bd --- /dev/null +++ b/app/client/src/pages/Templates/Template/TemplateDescription.tsx @@ -0,0 +1,191 @@ +import { Template } from "api/TemplatesApi"; +import React from "react"; +import { useHistory, useParams } from "react-router"; +import styled from "styled-components"; +import { getTypographyByKey } from "constants/DefaultTheme"; +import DatasourceChip from "../DatasourceChip"; +import { Colors } from "constants/Colors"; +import { + Button, + FontWeight, + IconPositions, + Size, + Text, + TextType, +} from "design-system"; +import { + createMessage, + DATASOURCES, + FORK_THIS_TEMPLATE, + FUNCTION, + INDUSTRY, + NOTE, + NOTE_MESSAGE, + OVERVIEW, + WIDGET_USED, +} from "@appsmith/constants/messages"; +import WidgetInfo from "../WidgetInfo"; +import ForkTemplate from "../ForkTemplate"; +import { templateIdUrl } from "RouteBuilder"; +import { useQuery } from "pages/Editor/utils"; + +export const DescriptionWrapper = styled.div` + display: flex; + gap: ${(props) => props.theme.spaces[17]}px; + margin-top: ${(props) => props.theme.spaces[15]}px; +`; + +export const DescriptionColumn = styled.div` + flex: 1; +`; + +export const Section = styled.div` + padding-top: ${(props) => props.theme.spaces[12]}px; + + .section-content { + margin-top: ${(props) => props.theme.spaces[3]}px; + } + + .template-fork-button { + margin-top: ${(props) => props.theme.spaces[7]}px; + } + + .datasource-note { + margin-top: ${(props) => props.theme.spaces[5]}px; + } +`; + +export const StyledDatasourceChip = styled(DatasourceChip)` + padding: ${(props) => + `${props.theme.spaces[4]}px ${props.theme.spaces[10]}px`}; + .image { + height: 25px; + width: 25px; + } + span { + ${(props) => getTypographyByKey(props, "h4")} + color: ${Colors.EBONY_CLAY}; + } +`; + +export const TemplatesWidgetList = styled.div` + display: flex; + flex-wrap: wrap; + gap: ${(props) => props.theme.spaces[12]}px; +`; + +export const TemplateDatasources = styled.div` + display: flex; + flex-wrap: wrap; + gap: ${(props) => props.theme.spaces[4]}px; +`; + +type TemplateDescriptionProps = { + template: Template; + hideForkButton?: boolean; +}; + +const SHOW_FORK_MODAL_PARAM = "showForkTemplateModal"; + +function TemplateDescription(props: TemplateDescriptionProps) { + const { template } = props; + const params = useParams<{ + templateId: string; + }>(); + const history = useHistory(); + const query = useQuery(); + + const onForkButtonTrigger = () => { + history.replace( + `${templateIdUrl({ id: template.id })}?${SHOW_FORK_MODAL_PARAM}=true`, + ); + }; + + const onForkModalClose = () => { + history.replace(`${templateIdUrl({ id: template.id })}`); + }; + return ( + <DescriptionWrapper> + <DescriptionColumn> + <Section> + <Text type={TextType.H1}>{createMessage(OVERVIEW)}</Text> + <div className="section-content"> + <Text type={TextType.H4} weight={FontWeight.NORMAL}> + {template.description} + </Text> + </div> + {!props.hideForkButton && ( + <ForkTemplate + onClose={onForkModalClose} + showForkModal={!!query.get(SHOW_FORK_MODAL_PARAM)} + templateId={params.templateId} + > + <Button + className="template-fork-button" + data-cy="template-fork-button" + icon="fork-2" + iconPosition={IconPositions.left} + onClick={onForkButtonTrigger} + size={Size.large} + tag="button" + text={createMessage(FORK_THIS_TEMPLATE)} + width="228px" + /> + </ForkTemplate> + )} + </Section> + <Section> + <Text type={TextType.H1}>{createMessage(FUNCTION)}</Text> + <div className="section-content"> + <Text type={TextType.H4} weight={FontWeight.NORMAL}> + {template.functions.join(" • ")} + </Text> + </div> + </Section> + <Section> + <Text type={TextType.H1}>{createMessage(INDUSTRY)}</Text> + <div className="section-content"> + <Text type={TextType.H4} weight={FontWeight.NORMAL}> + {template.useCases.join(" • ")} + </Text> + </div> + </Section> + </DescriptionColumn> + <DescriptionColumn> + <Section> + <Text type={TextType.H1}>{createMessage(DATASOURCES)}</Text> + <div className="section-content"> + <TemplateDatasources> + {template.datasources.map((packageName) => { + return ( + <StyledDatasourceChip + key={packageName} + pluginPackageName={packageName} + /> + ); + })} + </TemplateDatasources> + <div className="datasource-note"> + <Text type={TextType.H4}>{createMessage(NOTE)} </Text> + <Text type={TextType.H4} weight={FontWeight.NORMAL}> + {createMessage(NOTE_MESSAGE)} + </Text> + </div> + </div> + </Section> + <Section> + <Text type={TextType.H1}>{createMessage(WIDGET_USED)}</Text> + <div className="section-content"> + <TemplatesWidgetList> + {template.widgets.map((widgetType) => { + return <WidgetInfo key={widgetType} widgetType={widgetType} />; + })} + </TemplatesWidgetList> + </div> + </Section> + </DescriptionColumn> + </DescriptionWrapper> + ); +} + +export default TemplateDescription; diff --git a/app/client/src/pages/Templates/Template/index.tsx b/app/client/src/pages/Templates/Template/index.tsx index d51aa66c08eb..9e36b535cfbe 100644 --- a/app/client/src/pages/Templates/Template/index.tsx +++ b/app/client/src/pages/Templates/Template/index.tsx @@ -1,7 +1,7 @@ import React, { useState } from "react"; import styled from "styled-components"; -import { Template as TemplateInterface } from "api/TemplatesApi"; import history from "utils/history"; +import { Template as TemplateInterface } from "api/TemplatesApi"; import { Button, Size, TooltipComponent as Tooltip } from "design-system"; import ForkTemplateDialog from "../ForkTemplate"; import DatasourceChip from "../DatasourceChip"; @@ -13,6 +13,7 @@ import { FORK_THIS_TEMPLATE, } from "@appsmith/constants/messages"; import { templateIdUrl } from "RouteBuilder"; +import { Position } from "@blueprintjs/core"; const TemplateWrapper = styled.div` border: 1px solid ${Colors.GEYSER_LIGHT}; @@ -95,7 +96,8 @@ const StyledButton = styled(Button)` export interface TemplateProps { template: TemplateInterface; size?: string; - onClick?: () => void; + onClick?: (id: string) => void; + onForkTemplateClick?: (template: TemplateInterface) => void; } const Template = (props: TemplateProps) => { @@ -109,7 +111,8 @@ const Template = (props: TemplateProps) => { export interface TemplateLayoutProps { template: TemplateInterface; className?: string; - onClick?: () => void; + onClick?: (id: string) => void; + onForkTemplateClick?: (template: TemplateInterface) => void; } export function TemplateLayout(props: TemplateLayoutProps) { @@ -123,13 +126,21 @@ export function TemplateLayout(props: TemplateLayoutProps) { } = props.template; const [showForkModal, setShowForkModal] = useState(false); const onClick = () => { - history.push(templateIdUrl({ id })); - props.onClick && props.onClick(); + if (props.onClick) { + props.onClick(id); + } else { + history.push(templateIdUrl({ id })); + } }; const onForkButtonTrigger = (e: React.MouseEvent<HTMLElement>) => { - e.stopPropagation(); - setShowForkModal(true); + if (props.onForkTemplateClick) { + e.preventDefault(); + props.onForkTemplateClick(props.template); + } else { + e.stopPropagation(); + setShowForkModal(true); + } }; const onForkModalClose = (e?: React.MouseEvent<HTMLElement>) => { @@ -167,10 +178,14 @@ export function TemplateLayout(props: TemplateLayoutProps) { showForkModal={showForkModal} templateId={id} > - <Tooltip content={createMessage(FORK_THIS_TEMPLATE)}> + <Tooltip + content={createMessage(FORK_THIS_TEMPLATE)} + minimal + position={Position.BOTTOM} + > <StyledButton className="t--fork-template fork-button" - icon="fork-2" + icon="plus" size={Size.medium} tag="button" /> diff --git a/app/client/src/pages/Templates/TemplateList.tsx b/app/client/src/pages/Templates/TemplateList.tsx index 803d3bee2eb2..56ed036cb3bd 100644 --- a/app/client/src/pages/Templates/TemplateList.tsx +++ b/app/client/src/pages/Templates/TemplateList.tsx @@ -28,6 +28,8 @@ const Wrapper = styled.div` interface TemplateListProps { templates: TemplateInterface[]; + onTemplateClick?: (id: string) => void; + onForkTemplateClick?: (template: TemplateInterface) => void; } function TemplateList(props: TemplateListProps) { @@ -39,7 +41,13 @@ function TemplateList(props: TemplateListProps) { columnClassName="grid_column" > {props.templates.map((template) => ( - <Template key={template.id} size="large" template={template} /> + <Template + key={template.id} + onClick={props.onTemplateClick} + onForkTemplateClick={props.onForkTemplateClick} + size="large" + template={template} + /> ))} <RequestTemplate /> </Masonry> diff --git a/app/client/src/pages/Templates/TemplateView.tsx b/app/client/src/pages/Templates/TemplateView.tsx index d22fd72a7110..bea53fc091d8 100644 --- a/app/client/src/pages/Templates/TemplateView.tsx +++ b/app/client/src/pages/Templates/TemplateView.tsx @@ -1,29 +1,15 @@ import React, { useEffect, useRef } from "react"; import styled from "styled-components"; -import Masonry from "react-masonry-css"; import { Classes } from "@blueprintjs/core"; import { useParams } from "react-router"; import { useDispatch, useSelector } from "react-redux"; -import { - Button, - Icon, - IconSize, - IconPositions, - Size, - Text, - FontWeight, - TextType, -} from "design-system"; +import { Icon, IconSize, Text, TextType } from "design-system"; import EntityNotFoundPane from "pages/Editor/EntityNotFoundPane"; -import Template from "./Template"; import { Template as TemplateInterface } from "api/TemplatesApi"; -import DatasourceChip from "./DatasourceChip"; -import WidgetInfo from "./WidgetInfo"; import { getActiveTemplateSelector, isFetchingTemplateSelector, } from "selectors/templatesSelectors"; -import ForkTemplate from "./ForkTemplate"; import { getSimilarTemplatesInit, getTemplateInformation, @@ -31,25 +17,12 @@ import { import { AppState } from "@appsmith/reducers"; import history from "utils/history"; import { TEMPLATES_PATH } from "constants/routes"; -import { getTypographyByKey } from "constants/DefaultTheme"; import { Colors } from "constants/Colors"; -import { - createMessage, - GO_BACK, - OVERVIEW, - FORK_THIS_TEMPLATE, - FUNCTION, - INDUSTRY, - NOTE, - NOTE_MESSAGE, - WIDGET_USED, - DATASOURCES, - SIMILAR_TEMPLATES, - VIEW_ALL_TEMPLATES, -} from "@appsmith/constants/messages"; +import { createMessage, GO_BACK } from "@appsmith/constants/messages"; import AnalyticsUtil from "utils/AnalyticsUtil"; import ReconnectDatasourceModal from "pages/Editor/gitSync/ReconnectDatasourceModal"; -import { useQuery } from "pages/Editor/utils"; +import TemplateDescription from "./Template/TemplateDescription"; +import SimilarTemplates from "./Template/SimilarTemplates"; import { templateIdUrl } from "RouteBuilder"; const breakpointColumnsObject = { @@ -86,9 +59,7 @@ const Title = styled(Text)` display: inline-block; `; -const IframeWrapper = styled.div` - height: 734px; - width: 100%; +export const IframeWrapper = styled.div` border-radius: 16px; margin-top: ${(props) => props.theme.spaces[12]}px; @@ -96,78 +67,12 @@ const IframeWrapper = styled.div` border-radius: 0px 0px 16px 16px; box-shadow: 0px 20px 24px -4px rgba(16, 24, 40, 0.1), 0px 8px 8px -4px rgba(16, 24, 40, 0.04); - height: calc(100% - 41px); - } -`; - -const DescriptionWrapper = styled.div` - display: flex; - gap: ${(props) => props.theme.spaces[17]}px; - margin-top: ${(props) => props.theme.spaces[15]}px; -`; - -const DescriptionColumn = styled.div` - flex: 1; -`; - -const Section = styled.div` - padding-top: ${(props) => props.theme.spaces[12]}px; - - .section-content { - margin-top: ${(props) => props.theme.spaces[3]}px; - } - - .template-fork-button { - margin-top: ${(props) => props.theme.spaces[7]}px; - } - - .datasource-note { - margin-top: ${(props) => props.theme.spaces[5]}px; - } -`; - -const StyledDatasourceChip = styled(DatasourceChip)` - padding: ${(props) => - `${props.theme.spaces[4]}px ${props.theme.spaces[10]}px`}; - .image { - height: 25px; - width: 25px; - } - span { - ${(props) => getTypographyByKey(props, "h4")} - color: ${Colors.EBONY_CLAY}; - } -`; - -const TemplatesWidgetList = styled.div` - display: flex; - flex-wrap: wrap; - gap: ${(props) => props.theme.spaces[12]}px; -`; - -const TemplateDatasources = styled.div` - display: flex; - flex-wrap: wrap; - gap: ${(props) => props.theme.spaces[4]}px; -`; - -const SimilarTemplatesWrapper = styled.div` - padding-right: 132px; - padding-left: 132px; - background-color: rgba(248, 248, 248, 0.5); - - .grid { - display: flex; - margin-left: ${(props) => -props.theme.spaces[9]}px; - margin-top: ${(props) => props.theme.spaces[12]}px; - } - - .grid_column { - padding-left: ${(props) => props.theme.spaces[9]}px; + width: 100%; + height: 734px; } `; -const IframeTopBar = styled.div` +export const IframeTopBar = styled.div` width: 100%; background-color: ${Colors.GEYSER_LIGHT}; border-radius: 8px 8px 0px 0px; @@ -222,12 +127,6 @@ const LoadingWrapper = styled.div` } `; -const SimilarTemplatesTitleWrapper = styled.div` - display: flex; - align-items: center; - justify-content: space-between; -`; - function TemplateViewLoader() { return ( <LoadingWrapper> @@ -243,8 +142,6 @@ function TemplateNotFound() { return <EntityNotFoundPane />; } -const SHOW_FORK_MODAL_PARAM = "showForkTemplateModal"; - function TemplateView() { const dispatch = useDispatch(); const similarTemplates = useSelector( @@ -254,23 +151,6 @@ function TemplateView() { const params = useParams<{ templateId: string }>(); const currentTemplate = useSelector(getActiveTemplateSelector); const containerRef = useRef<HTMLDivElement>(null); - const query = useQuery(); - - const onForkButtonTrigger = () => { - if (currentTemplate) { - history.replace( - `${templateIdUrl({ - id: currentTemplate.id, - })}?${SHOW_FORK_MODAL_PARAM}=true`, - ); - } - }; - - const onForkModalClose = () => { - if (currentTemplate) { - history.replace(`${templateIdUrl({ id: currentTemplate.id })}`); - } - }; const goToTemplateListView = () => { history.push(TEMPLATES_PATH); @@ -299,6 +179,7 @@ function TemplateView() { name: template.title, }, }); + history.push(templateIdUrl({ id: template.id })); }; return ( @@ -334,121 +215,14 @@ function TemplateView() { width={"100%"} /> </IframeWrapper> - <DescriptionWrapper> - <DescriptionColumn> - <Section> - <Text type={TextType.H1}>{createMessage(OVERVIEW)}</Text> - <div className="section-content"> - <Text type={TextType.H4} weight={FontWeight.NORMAL}> - {currentTemplate.description} - </Text> - </div> - <ForkTemplate - onClose={onForkModalClose} - showForkModal={!!query.get(SHOW_FORK_MODAL_PARAM)} - templateId={params.templateId} - > - <Button - className="template-fork-button" - data-cy="template-fork-button" - icon="fork-2" - iconPosition={IconPositions.left} - onClick={onForkButtonTrigger} - size={Size.large} - tag="button" - text={createMessage(FORK_THIS_TEMPLATE)} - width="228px" - /> - </ForkTemplate> - </Section> - <Section> - <Text type={TextType.H1}>{createMessage(FUNCTION)}</Text> - <div className="section-content"> - <Text type={TextType.H4} weight={FontWeight.NORMAL}> - {currentTemplate.functions.join(" • ")} - </Text> - </div> - </Section> - <Section> - <Text type={TextType.H1}>{createMessage(INDUSTRY)}</Text> - <div className="section-content"> - <Text type={TextType.H4} weight={FontWeight.NORMAL}> - {currentTemplate.useCases.join(" • ")} - </Text> - </div> - </Section> - </DescriptionColumn> - <DescriptionColumn> - <Section> - <Text type={TextType.H1}>{createMessage(DATASOURCES)}</Text> - <div className="section-content"> - <TemplateDatasources> - {currentTemplate.datasources.map((packageName) => { - return ( - <StyledDatasourceChip - key={packageName} - pluginPackageName={packageName} - /> - ); - })} - </TemplateDatasources> - <div className="datasource-note"> - <Text type={TextType.H4}>{createMessage(NOTE)} </Text> - <Text type={TextType.H4} weight={FontWeight.NORMAL}> - {createMessage(NOTE_MESSAGE)} - </Text> - </div> - </div> - </Section> - <Section> - <Text type={TextType.H1}>{createMessage(WIDGET_USED)}</Text> - <div className="section-content"> - <TemplatesWidgetList> - {currentTemplate.widgets.map((widgetType) => { - return ( - <WidgetInfo - key={widgetType} - widgetType={widgetType} - /> - ); - })} - </TemplatesWidgetList> - </div> - </Section> - </DescriptionColumn> - </DescriptionWrapper> + <TemplateDescription template={currentTemplate} /> </TemplateViewWrapper> - - {!!similarTemplates.length && ( - <SimilarTemplatesWrapper> - <Section> - <SimilarTemplatesTitleWrapper> - <Text type={TextType.H1} weight={FontWeight.BOLD}> - {createMessage(SIMILAR_TEMPLATES)} - </Text> - <BackButtonWrapper onClick={goToTemplateListView}> - <Text type={TextType.P4}> - {createMessage(VIEW_ALL_TEMPLATES)} - </Text> - <Icon name="view-all" size={IconSize.XL} /> - </BackButtonWrapper> - </SimilarTemplatesTitleWrapper> - <Masonry - breakpointCols={breakpointColumnsObject} - className="grid" - columnClassName="grid_column" - > - {similarTemplates.map((template) => ( - <Template - key={template.id} - onClick={() => onSimilarTemplateClick(template)} - template={template} - /> - ))} - </Masonry> - </Section> - </SimilarTemplatesWrapper> - )} + <SimilarTemplates + breakpointCols={breakpointColumnsObject} + onBackPress={goToTemplateListView} + onClick={onSimilarTemplateClick} + similarTemplates={similarTemplates} + /> </Wrapper> )} </PageWrapper> diff --git a/app/client/src/pages/Templates/TemplatesModal/Header.tsx b/app/client/src/pages/Templates/TemplatesModal/Header.tsx new file mode 100644 index 000000000000..6704803f345f --- /dev/null +++ b/app/client/src/pages/Templates/TemplatesModal/Header.tsx @@ -0,0 +1,50 @@ +import { createMessage, TEMPLATES_BACK_BUTTON } from "ce/constants/messages"; +import { Icon, IconSize, Text, TextType } from "design-system"; +import React from "react"; +import styled from "styled-components"; + +const BackButtonWrapper = styled.div<{ width?: number; hidden?: boolean }>` + cursor: pointer; + display: flex; + align-items: center; + gap: ${(props) => props.theme.spaces[2]}px; + ${(props) => props.width && `width: ${props.width};`} + ${(props) => props.hidden && "visibility: hidden;"} +`; + +const CloseIcon = styled(Icon)` + svg { + height: 24px; + width: 24px; + } +`; + +const HeaderWrapper = styled.div` + display: flex; + justify-content: space-between; + padding-bottom: ${(props) => props.theme.spaces[9]}px; +`; + +type TemplateModalHeaderProps = { + onBackPress?: () => void; + onClose: () => void; + hideBackButton?: boolean; + className?: string; +}; + +function TemplateModalHeader(props: TemplateModalHeaderProps) { + return ( + <HeaderWrapper className={props.className}> + <BackButtonWrapper + hidden={props.hideBackButton} + onClick={props.onBackPress} + > + <Icon name="view-less" size={IconSize.XL} /> + <Text type={TextType.P4}>{createMessage(TEMPLATES_BACK_BUTTON)}</Text> + </BackButtonWrapper> + <CloseIcon name="close-x" onClick={props.onClose} /> + </HeaderWrapper> + ); +} + +export default TemplateModalHeader; diff --git a/app/client/src/pages/Templates/TemplatesModal/LoadingScreen.tsx b/app/client/src/pages/Templates/TemplatesModal/LoadingScreen.tsx new file mode 100644 index 000000000000..b0fa5e00391d --- /dev/null +++ b/app/client/src/pages/Templates/TemplatesModal/LoadingScreen.tsx @@ -0,0 +1,34 @@ +import React from "react"; +import styled from "styled-components"; +import { Text, TextType, Spinner } from "design-system"; +import { Classes } from "components/ads"; + +const Wrapper = styled.div` + height: 85vh; + + .${Classes.SPINNER} { + height: 24px; + width: 24px; + } + + justify-content: center; + align-items: center; + display: flex; + flex-direction: column; + gap: ${(props) => props.theme.spaces[9]}px; +`; + +type LoadingScreenProps = { + text: string; +}; + +function LoadingScreen(props: LoadingScreenProps) { + return ( + <Wrapper> + <Spinner /> + <Text type={TextType.DANGER_HEADING}>{props.text}</Text> + </Wrapper> + ); +} + +export default LoadingScreen; diff --git a/app/client/src/pages/Templates/TemplatesModal/PageSelection.tsx b/app/client/src/pages/Templates/TemplatesModal/PageSelection.tsx new file mode 100644 index 000000000000..3d62ebded0ac --- /dev/null +++ b/app/client/src/pages/Templates/TemplatesModal/PageSelection.tsx @@ -0,0 +1,232 @@ +import React, { useEffect, useState } from "react"; +import styled from "styled-components"; +import PagesLineIcon from "remixicon-react/PagesLineIcon"; +import { CheckboxType, Text, TextType, IconWrapper } from "design-system"; +import { Checkmark, Size, Button } from "design-system"; +import { useDispatch } from "react-redux"; +import { importTemplateIntoApplication } from "actions/templateActions"; +import { Template } from "api/TemplatesApi"; +import { ApplicationPagePayload } from "api/ApplicationApi"; +import { + createMessage, + FILTER_SELECTALL, + FILTER_SELECT_PAGES, + PAGE, + PAGES, +} from "ce/constants/messages"; +import { Colors } from "constants/Colors"; +import { Classes } from "components/ads"; + +const Wrapper = styled.div` + width: max(300px, 25%); + padding-left: ${(props) => props.theme.spaces[9]}px; + position: sticky; + top: 0; + position: -webkit-sticky; + height: fit-content; +`; + +const Card = styled.div` + box-shadow: 0 2px 4px -2px rgba(0, 0, 0, 0.06), + 0 4px 8px -2px rgba(0, 0, 0, 0.1); + padding: ${(props) => props.theme.spaces[9]}px; + border: solid 1px ${Colors.GREY_4}; + + hr { + background-color: ${Colors.GRAY_400}; + margin-top: ${(props) => props.theme.spaces[3]}px; + } +`; + +const CardHeader = styled.div` + display: flex; + justify-content: space-between; + align-items: center; + + .checkbox { + margin-left: ${(props) => props.theme.spaces[3]}px; + } +`; + +const StyledCheckMark = styled(Checkmark)` + width: 16px; + height: 16px; + ${(props) => !props.isChecked && `border: 1.8px solid ${Colors.GRAY_400};`} + + &::after { + width: 5px; + height: 9px; + top: 1px; + } +`; + +const CheckboxWrapper = styled.label` + position: relative; + display: block; + width: 16px; + height: 16px; + cursor: pointer; + color: ${(props) => props.theme.colors.checkbox.labelColor}; + input { + position: absolute; + opacity: 0; + cursor: pointer; + height: 0; + width: 0; + } + + input:checked ~ ${StyledCheckMark}:after { + display: block; + } +`; + +const Page = styled.div` + .${Classes.ICON} { + svg { + height: 20px; + width: 20px; + } + margin-right: ${(props) => props.theme.spaces[1]}px; + } + display: flex; + align-items: center; + justify-content: space-between; + margin-top: ${(props) => props.theme.spaces[11]}px; +`; + +const PageName = styled.div` + cursor: pointer; + &:hover { + text-decoration: underline; + text-underline-offset: 2px; + } +`; + +const StyledButton = styled(Button)` + margin-top: ${(props) => props.theme.spaces[11]}px; +`; + +type PageSelectionProps = { + pages: ApplicationPagePayload[]; + template: Template; + onPageSelection: (pageId: string) => void; +}; + +type CustomCheckboxProps = { + onChange: (checked: boolean) => void; + checked: boolean; +}; + +function CustomCheckbox(props: CustomCheckboxProps) { + return ( + <CheckboxWrapper className="checkbox"> + <input + checked={props.checked} + onChange={(e: React.ChangeEvent<HTMLInputElement>) => { + props.onChange(e.target.checked); + }} + type="checkbox" + /> + <StyledCheckMark + backgroundColor={Colors.GREY_900} + isChecked={props.checked} + type={CheckboxType.PRIMARY} + /> + </CheckboxWrapper> + ); +} + +function PageSelection(props: PageSelectionProps) { + const dispatch = useDispatch(); + const [selectedPages, setSelectedPages] = useState( + props.pages.map((page) => page.name), + ); + const pagesText = + props.pages.length > 1 || props.pages.length === 0 + ? createMessage(PAGES) + : createMessage(PAGE); + + useEffect(() => { + setSelectedPages(props.pages.map((page) => page.name)); + }, [props.pages]); + + const onSelection = (selectedPageName: string, checked: boolean) => { + if (checked) { + if (!selectedPages.includes(selectedPageName)) { + setSelectedPages((pages) => [...pages, selectedPageName]); + } + } else { + setSelectedPages((pages) => + pages.filter((pageName) => pageName !== selectedPageName), + ); + } + }; + + const onSelectAllToggle = (checked: boolean) => { + if (checked) { + setSelectedPages(props.pages.map((page) => page.name)); + } else { + setSelectedPages([]); + } + }; + + const importPagesToApp = () => { + dispatch( + importTemplateIntoApplication( + props.template.id, + props.template.title, + selectedPages, + ), + ); + }; + + return ( + <Wrapper> + <Card> + <CardHeader> + <Text type={TextType.H1}> + {props.pages.length} {pagesText} + </Text> + <div className="flex"> + <Text type={TextType.P4}>{createMessage(FILTER_SELECTALL)}</Text> + <CustomCheckbox + checked={selectedPages.length === props.pages.length} + onChange={onSelectAllToggle} + /> + </div> + </CardHeader> + <hr /> + {props.pages.map((page) => { + return ( + <Page key={page.id}> + <PageName + className="flex items-center" + onClick={() => props.onPageSelection(page.id)} + > + <IconWrapper className={Classes.ICON}> + <PagesLineIcon /> + </IconWrapper> + <Text type={TextType.P4}>{page.name.toUpperCase()}</Text> + </PageName> + <CustomCheckbox + checked={selectedPages.includes(page.name)} + onChange={(checked) => onSelection(page.name, checked)} + /> + </Page> + ); + })} + <StyledButton + data-cy="template-fork-button" + disabled={!selectedPages.length} + onClick={importPagesToApp} + size={Size.large} + tag="button" + text={createMessage(FILTER_SELECT_PAGES)} + width="100%" + /> + </Card> + </Wrapper> + ); +} + +export default PageSelection; diff --git a/app/client/src/pages/Templates/TemplatesModal/TemplateDetailedView.tsx b/app/client/src/pages/Templates/TemplatesModal/TemplateDetailedView.tsx new file mode 100644 index 000000000000..dd4939fb6d06 --- /dev/null +++ b/app/client/src/pages/Templates/TemplatesModal/TemplateDetailedView.tsx @@ -0,0 +1,173 @@ +import { + createMessage, + FETCHING_TEMPLATES, + FORKING_TEMPLATE, +} from "@appsmith/constants/messages"; +import { + getSimilarTemplatesInit, + getTemplateInformation, + importTemplateIntoApplication, +} from "actions/templateActions"; +import { Text, TextType } from "design-system"; +import React, { useEffect, useState, useRef } from "react"; +import { useDispatch, useSelector } from "react-redux"; +import { + getActiveTemplateSelector, + isFetchingTemplateSelector, + isImportingTemplateToAppSelector, +} from "selectors/templatesSelectors"; +import styled from "styled-components"; +import { IframeTopBar, IframeWrapper } from "../TemplateView"; +import PageSelection from "./PageSelection"; +import LoadingScreen from "./LoadingScreen"; +import { Template } from "api/TemplatesApi"; +import { generatePath, matchPath } from "react-router"; +import { isURLDeprecated, trimQueryString } from "utils/helpers"; +import { VIEWER_PATH, VIEWER_PATH_DEPRECATED } from "constants/routes"; +import TemplateModalHeader from "./Header"; +import TemplateDescription from "../Template/TemplateDescription"; +import SimilarTemplates from "../Template/SimilarTemplates"; +import { AppState } from "@appsmith/reducers"; + +const breakpointColumns = { + default: 4, + 2100: 3, + 1600: 2, + 1100: 1, +}; + +const Wrapper = styled.div` + height: 85vh; + display: flex; + flex-direction: column; +`; + +const Body = styled.div` + padding: 0 ${(props) => props.theme.spaces[11]}px; + padding-top: ${(props) => props.theme.spaces[7]}px; + height: 80vh; + overflow: auto; + &&::-webkit-scrollbar-thumb { + background-color: ${(props) => props.theme.colors.modal.scrollbar}; + } + &::-webkit-scrollbar { + width: 4px; + } +`; + +const StyledSimilarTemplatesWrapper = styled(SimilarTemplates)` + padding: 0px; +`; + +const TemplateDescriptionWrapper = styled.div` + padding-bottom: 52px; +`; + +type TemplateDetailedViewProps = { + templateId: string; + onBackPress: () => void; + onClose: () => void; +}; + +function TemplateDetailedView(props: TemplateDetailedViewProps) { + const [currentTemplateId, setCurrentTemplateId] = useState(props.templateId); + const [previewUrl, setPreviewUrl] = useState(""); + const dispatch = useDispatch(); + const similarTemplates = useSelector( + (state: AppState) => state.ui.templates.similarTemplates, + ); + const isFetchingTemplate = useSelector(isFetchingTemplateSelector); + const isImportingTemplateToApp = useSelector( + isImportingTemplateToAppSelector, + ); + const currentTemplate = useSelector(getActiveTemplateSelector); + const containerRef = useRef<HTMLDivElement>(null); + const LoadingText = isImportingTemplateToApp + ? createMessage(FORKING_TEMPLATE) + : createMessage(FETCHING_TEMPLATES); + + useEffect(() => { + dispatch(getTemplateInformation(currentTemplateId)); + dispatch(getSimilarTemplatesInit(currentTemplateId)); + }, [currentTemplateId]); + + useEffect(() => { + if (currentTemplate?.appUrl) { + setPreviewUrl(currentTemplate.appUrl); + } + }, [currentTemplate?.id]); + + const onSimilarTemplateClick = (template: Template) => { + setCurrentTemplateId(template.id); + if (containerRef.current) { + containerRef.current.scrollTo({ top: 0 }); + } + }; + + const onForkTemplateClick = (template: Template) => { + dispatch(importTemplateIntoApplication(template.id, template.title)); + }; + + if (isFetchingTemplate || isImportingTemplateToApp) { + return <LoadingScreen text={LoadingText} />; + } + + if (!currentTemplate) { + return null; + } + + // Update the page id in the url + const onPageSelection = (pageId: string) => { + const url = new URL(currentTemplate.appUrl); + const path = isURLDeprecated(url.pathname) + ? VIEWER_PATH_DEPRECATED + : VIEWER_PATH; + const matchViewerPath = matchPath(url.pathname, { + path: [trimQueryString(path)], + }); + url.pathname = generatePath(path, { + ...matchViewerPath?.params, + pageId, + }); + setPreviewUrl(url.toString()); + }; + + return ( + <Wrapper ref={containerRef}> + <TemplateModalHeader + onBackPress={props.onBackPress} + onClose={props.onClose} + /> + <Body className="flex flex-row"> + <div className="flex flex-col flex-1"> + <Text type={TextType.DANGER_HEADING}>{currentTemplate.title}</Text> + <IframeWrapper> + <IframeTopBar> + <div className="round red" /> + <div className="round yellow" /> + <div className="round green" /> + </IframeTopBar> + <iframe src={`${previewUrl}?embed=true`} /> + </IframeWrapper> + <TemplateDescriptionWrapper> + <TemplateDescription hideForkButton template={currentTemplate} /> + </TemplateDescriptionWrapper> + <StyledSimilarTemplatesWrapper + breakpointCols={breakpointColumns} + onBackPress={props.onBackPress} + onClick={onSimilarTemplateClick} + onFork={onForkTemplateClick} + similarTemplates={similarTemplates} + /> + </div> + <PageSelection + onPageSelection={onPageSelection} + pages={currentTemplate.pages || []} + template={currentTemplate} + /> + </Body> + </Wrapper> + ); +} + +export default TemplateDetailedView; diff --git a/app/client/src/pages/Templates/TemplatesModal/TemplateList.tsx b/app/client/src/pages/Templates/TemplatesModal/TemplateList.tsx new file mode 100644 index 000000000000..304b2a57438c --- /dev/null +++ b/app/client/src/pages/Templates/TemplatesModal/TemplateList.tsx @@ -0,0 +1,79 @@ +import { importTemplateIntoApplication } from "actions/templateActions"; +import React from "react"; +import { useDispatch, useSelector } from "react-redux"; +import { isFetchingTemplatesSelector } from "selectors/templatesSelectors"; +import styled from "styled-components"; +import { TemplatesContent } from ".."; +import Filters from "../Filters"; +import LoadingScreen from "./LoadingScreen"; +import { Template } from "api/TemplatesApi"; +import TemplateModalHeader from "./Header"; +import { createMessage, FETCHING_TEMPLATE_LIST } from "ce/constants/messages"; + +const Wrapper = styled.div` + display: flex; + height: 85vh; + overflow: auto; + + .modal-header { + padding-bottom: ${(props) => props.theme.spaces[4]}px; + } +`; + +const FilterWrapper = styled.div` + .filter-wrapper { + width: 200px; + } +`; + +const ListWrapper = styled.div` + height: 79vh; + overflow: auto; + &&::-webkit-scrollbar-thumb { + background-color: ${(props) => props.theme.colors.modal.scrollbar}; + } + &::-webkit-scrollbar { + width: 4px; + } +`; + +type TemplateListProps = { + onTemplateClick: (id: string) => void; + onClose: () => void; +}; + +function TemplateList(props: TemplateListProps) { + const dispatch = useDispatch(); + const onForkTemplateClick = (template: Template) => { + dispatch(importTemplateIntoApplication(template.id, template.title)); + }; + const isFetchingTemplates = useSelector(isFetchingTemplatesSelector); + + if (isFetchingTemplates) { + return <LoadingScreen text={createMessage(FETCHING_TEMPLATE_LIST)} />; + } + + return ( + <Wrapper className="flex flex-col"> + <TemplateModalHeader + className="modal-header" + hideBackButton + onClose={props.onClose} + /> + <div className="flex"> + <FilterWrapper> + <Filters /> + </FilterWrapper> + <ListWrapper> + <TemplatesContent + onForkTemplateClick={onForkTemplateClick} + onTemplateClick={props.onTemplateClick} + stickySearchBar + /> + </ListWrapper> + </div> + </Wrapper> + ); +} + +export default TemplateList; diff --git a/app/client/src/pages/Templates/TemplatesModal/index.tsx b/app/client/src/pages/Templates/TemplatesModal/index.tsx new file mode 100644 index 000000000000..aba66e1d9df9 --- /dev/null +++ b/app/client/src/pages/Templates/TemplatesModal/index.tsx @@ -0,0 +1,84 @@ +import React, { useEffect, useState } from "react"; +import DialogComponent from "components/ads/DialogComponent"; +import { useDispatch, useSelector } from "react-redux"; +import { + templateModalOpenSelector, + templatesCountSelector, +} from "selectors/templatesSelectors"; +import { + getAllTemplates, + getTemplateFilters, + showTemplatesModal, +} from "actions/templateActions"; +import TemplatesList from "./TemplateList"; +import { fetchDefaultPlugins } from "actions/pluginActions"; +import TemplateDetailedView from "./TemplateDetailedView"; +import { isEmpty } from "lodash"; +import { AppState } from "@appsmith/reducers"; + +function TemplatesModal() { + const templatesModalOpen = useSelector(templateModalOpenSelector); + const dispatch = useDispatch(); + const templatesCount = useSelector(templatesCountSelector); + const pluginListLength = useSelector( + (state: AppState) => state.entities.plugins.defaultPluginList.length, + ); + const filters = useSelector( + (state: AppState) => state.ui.templates.allFilters, + ); + const [showTemplateDetails, setShowTemplateDetails] = useState(""); + + useEffect(() => { + setShowTemplateDetails(""); + }, [templatesModalOpen]); + + useEffect(() => { + if (!templatesCount && templatesModalOpen) { + dispatch(getAllTemplates()); + } + }, [templatesCount, templatesModalOpen]); + + useEffect(() => { + if (!pluginListLength) { + dispatch(fetchDefaultPlugins()); + } + }, [pluginListLength]); + + useEffect(() => { + if (isEmpty(filters.functions)) { + dispatch(getTemplateFilters()); + } + }, [filters]); + + const onClose = () => { + dispatch(showTemplatesModal(false)); + setShowTemplateDetails(""); + }; + + const onTemplateClick = (id: string) => { + setShowTemplateDetails(id); + }; + + return ( + <DialogComponent + canEscapeKeyClose + canOutsideClickClose + isOpen={templatesModalOpen} + noModalBodyMarginTop + onClose={onClose} + width={"90%"} + > + {!!showTemplateDetails ? ( + <TemplateDetailedView + onBackPress={() => setShowTemplateDetails("")} + onClose={onClose} + templateId={showTemplateDetails} + /> + ) : ( + <TemplatesList onClose={onClose} onTemplateClick={onTemplateClick} /> + )} + </DialogComponent> + ); +} + +export default TemplatesModal; diff --git a/app/client/src/pages/Templates/TemplatesTabItem.tsx b/app/client/src/pages/Templates/TemplatesTabItem.tsx deleted file mode 100644 index 04e21b954ed6..000000000000 --- a/app/client/src/pages/Templates/TemplatesTabItem.tsx +++ /dev/null @@ -1,129 +0,0 @@ -import { Popover2, Classes as Popover2Classes } from "@blueprintjs/popover2"; -import { useLocation } from "react-router"; -import { setTemplateNotificationSeenAction } from "actions/templateActions"; -import { Classes } from "components/ads"; -import { Icon, IconSize, TextType, Text } from "design-system"; -import { Colors } from "constants/Colors"; -import { matchTemplatesPath } from "constants/routes"; -import { isNull } from "lodash"; -import React, { ReactNode, Suspense, useEffect } from "react"; -import { useDispatch, useSelector } from "react-redux"; -import { - INTRODUCING_TEMPLATES, - createMessage, - TEMPLATE_NOTIFICATION_DESCRIPTION, -} from "@appsmith/constants/messages"; -import { - getIsFetchingApplications, - getUserApplicationsWorkspacesList, -} from "selectors/applicationSelectors"; -import { showTemplateNotificationSelector } from "selectors/templatesSelectors"; -import styled from "styled-components"; -import { AppState } from "@appsmith/reducers"; - -const NotificationWrapper = styled.div` - background-color: ${Colors.SEA_SHELL}; - padding: ${(props) => - `${props.theme.spaces[4]}px ${props.theme.spaces[8]}px`}; - display: flex; - flex-direction: row; - max-width: 376px; - - .${Classes.ICON} { - align-items: unset; - margin-top: ${(props) => props.theme.spaces[0] + 1}px; - } - - .text-wrapper { - display: flex; - flex-direction: column; - margin-left: ${(props) => props.theme.spaces[3]}px; - } - - .description { - margin-top: ${(props) => props.theme.spaces[0] + 2}px; - } -`; - -const StyledPopover = styled.div` - .${Popover2Classes.POPOVER2_TARGET} { - display: flex; - } - display: flex; -`; - -export function TemplateFeatureNotification() { - return ( - <NotificationWrapper> - <Icon name={"info"} size={IconSize.XXXL} /> - <div className={"text-wrapper"}> - <Text color={Colors.CODE_GRAY} type={TextType.H4}> - {createMessage(INTRODUCING_TEMPLATES)} - </Text> - <Text - className="description" - color={Colors.CODE_GRAY} - type={TextType.P1} - > - {createMessage(TEMPLATE_NOTIFICATION_DESCRIPTION)} - </Text> - </div> - </NotificationWrapper> - ); -} - -interface TemplatesTabItemProps { - children: ReactNode; -} - -export function TemplatesTabItem(props: TemplatesTabItemProps) { - const hasSeenNotification = useSelector(showTemplateNotificationSelector); - const isFetchingApplications = useSelector(getIsFetchingApplications); - const workspaceListLength = useSelector( - (state: AppState) => getUserApplicationsWorkspacesList(state).length, - ); - const location = useLocation(); - const dispatch = useDispatch(); - - const showNotification = - !hasSeenNotification && - !isFetchingApplications && - !isNull(hasSeenNotification) && - workspaceListLength; - - const setNotificationSeenFlag = () => { - dispatch(setTemplateNotificationSeenAction(true)); - }; - - useEffect(() => { - if (matchTemplatesPath(location.pathname) && !hasSeenNotification) { - setNotificationSeenFlag(); - } - }, [location.pathname, hasSeenNotification]); - - return ( - <Suspense fallback={<div />}> - <StyledPopover> - <Popover2 - content={<TemplateFeatureNotification />} - enforceFocus={false} - isOpen={!!showNotification} - modifiers={{ - offset: { - enabled: true, - options: { - offset: [0, 0], - }, - }, - }} - onClose={setNotificationSeenFlag} - placement="bottom-start" - portalClassName="templates-notification" - targetTagName="div" - > - {props.children} - </Popover2> - </StyledPopover> - </Suspense> - ); -} diff --git a/app/client/src/pages/Templates/index.tsx b/app/client/src/pages/Templates/index.tsx index f1ff01299ab7..c892d52ec9fc 100644 --- a/app/client/src/pages/Templates/index.tsx +++ b/app/client/src/pages/Templates/index.tsx @@ -1,8 +1,8 @@ import React, { useEffect } from "react"; import styled from "styled-components"; import * as Sentry from "@sentry/react"; -import { Classes, ControlGroup } from "@blueprintjs/core"; -import { debounce, noop } from "lodash"; +import { ControlGroup } from "@blueprintjs/core"; +import { debounce, noop, isEmpty } from "lodash"; import { Switch, Route, useRouteMatch } from "react-router-dom"; import { SearchInput, SearchVariant } from "design-system"; import TemplateList from "./TemplateList"; @@ -12,6 +12,7 @@ import { useDispatch, useSelector } from "react-redux"; import { setHeaderMeta } from "actions/themeActions"; import { getAllTemplates, + getTemplateFilters, setTemplateSearchQuery, } from "actions/templateActions"; import { @@ -31,6 +32,9 @@ import { getAllApplications } from "actions/applicationActions"; import { getTypographyByKey } from "constants/DefaultTheme"; import { Colors } from "constants/Colors"; import { createMessage, SEARCH_TEMPLATES } from "@appsmith/constants/messages"; +import LeftPaneBottomSection from "pages/Home/LeftPaneBottomSection"; +import { Template } from "api/TemplatesApi"; +import LoadingScreen from "./TemplatesModal/LoadingScreen"; import ReconnectDatasourceModal from "pages/Editor/gitSync/ReconnectDatasourceModal"; const SentryRoute = Sentry.withSentryRouting(Route); @@ -41,6 +45,22 @@ const PageWrapper = styled.div` padding-left: 8vw; `; +const SidebarWrapper = styled.div` + width: ${(props) => props.theme.homePage.sidebar}px; + height: 100%; + display: flex; + padding-left: ${(props) => props.theme.spaces[7]}px; + padding-top: ${(props) => props.theme.spaces[11]}px; + flex-direction: column; +`; + +const SecondaryWrapper = styled.div` + height: calc( + 100vh - ${(props) => props.theme.homePage.header + props.theme.spaces[11]}px + ); + position: relative; +`; + export const TemplateListWrapper = styled.div` padding-top: ${(props) => props.theme.spaces[11]}px; width: calc(100% - ${(props) => props.theme.homePage.sidebar}px); @@ -57,24 +77,15 @@ export const ResultsCount = styled.div` padding-bottom: ${(props) => props.theme.spaces[11]}px; `; -const Loader = styled(TemplateListWrapper)` - height: 100vh; - .results-count { - height: 20px; - width: 100px; - } -`; - -const LoadingTemplateList = styled.div` - margin-top: ${(props) => props.theme.spaces[11]}px; - // 200 is to have some space at the bottom - height: calc(100% - 200px); - margin-right: ${(props) => props.theme.spaces[9]}px; - margin-left: ${(props) => props.theme.spaces[12] + 2}px; -`; - -const SearchWrapper = styled.div` +const SearchWrapper = styled.div<{ sticky?: boolean }>` margin-left: ${(props) => props.theme.spaces[11]}px; + ${(props) => + props.sticky && + `position: sticky; + top: 0; + position: -webkit-sticky; + z-index: 1; + background-color: white;`} `; function TemplateRoutes() { @@ -89,6 +100,9 @@ function TemplateRoutes() { const templatesCount = useSelector( (state: AppState) => state.ui.templates.templates.length, ); + const filters = useSelector( + (state: AppState) => state.ui.templates.allFilters, + ); useEffect(() => { dispatch(setHeaderMeta(true, true)); @@ -114,6 +128,12 @@ function TemplateRoutes() { } }, [pluginListLength]); + useEffect(() => { + if (isEmpty(filters.functions)) { + dispatch(getTemplateFilters()); + } + }, [filters]); + return ( <Switch> <SentryRoute component={TemplateView} path={`${path}/:templateId`} /> @@ -122,22 +142,25 @@ function TemplateRoutes() { ); } -function TemplateListLoader() { - return ( - <Loader> - <ResultsCount className={`results-count ${Classes.SKELETON}`} /> - <LoadingTemplateList className={Classes.SKELETON} /> - </Loader> - ); -} +type TemplatesContentProps = { + onTemplateClick?: (id: string) => void; + onForkTemplateClick?: (template: Template) => void; + stickySearchBar?: boolean; +}; -function Templates() { - const templates = useSelector(getSearchedTemplateList); +export function TemplatesContent(props: TemplatesContentProps) { const templateSearchQuery = useSelector(getTemplateSearchQuery); const isFetchingApplications = useSelector(getIsFetchingApplications); const isFetchingTemplates = useSelector(isFetchingTemplatesSelector); - const filterCount = useSelector(getTemplateFiltersLength); + const isLoading = isFetchingApplications || isFetchingTemplates; const dispatch = useDispatch(); + const onChange = (query: string) => { + dispatch(setTemplateSearchQuery(query)); + }; + const debouncedOnChange = debounce(onChange, 250, { maxWait: 1000 }); + const templates = useSelector(getSearchedTemplateList); + const filterCount = useSelector(getTemplateFiltersLength); + let resultsText = templates.length > 1 ? `Showing all ${templates.length} templates` @@ -154,38 +177,46 @@ function Templates() { : ""; } - const isLoading = isFetchingApplications || isFetchingTemplates; + if (isLoading) { + return <LoadingScreen text="Loading templates" />; + } - const onChange = (query: string) => { - dispatch(setTemplateSearchQuery(query)); - }; - const debouncedOnChange = debounce(onChange, 250, { maxWait: 1000 }); + return ( + <> + <SearchWrapper sticky={props.stickySearchBar}> + <ControlGroup> + <SearchInput + cypressSelector={"t--application-search-input"} + defaultValue={templateSearchQuery} + disabled={isLoading} + onChange={debouncedOnChange || noop} + placeholder={createMessage(SEARCH_TEMPLATES)} + variant={SearchVariant.BACKGROUND} + /> + </ControlGroup> + </SearchWrapper> + <ResultsCount>{resultsText}</ResultsCount> + <TemplateList + onForkTemplateClick={props.onForkTemplateClick} + onTemplateClick={props.onTemplateClick} + templates={templates} + /> + </> + ); +} +function Templates() { return ( <PageWrapper> - <ReconnectDatasourceModal /> - <Filters /> + <SidebarWrapper> + <SecondaryWrapper> + <ReconnectDatasourceModal /> + <Filters /> + <LeftPaneBottomSection /> + </SecondaryWrapper> + </SidebarWrapper> <TemplateListWrapper> - {isLoading ? ( - <TemplateListLoader /> - ) : ( - <> - <SearchWrapper> - <ControlGroup> - <SearchInput - cypressSelector={"t--application-search-input"} - defaultValue={templateSearchQuery} - disabled={isLoading} - onChange={debouncedOnChange || noop} - placeholder={createMessage(SEARCH_TEMPLATES)} - variant={SearchVariant.BACKGROUND} - /> - </ControlGroup> - </SearchWrapper> - <ResultsCount>{resultsText}</ResultsCount> - <TemplateList templates={templates} /> - </> - )} + <TemplatesContent /> </TemplateListWrapper> </PageWrapper> ); diff --git a/app/client/src/pages/common/PageHeader.tsx b/app/client/src/pages/common/PageHeader.tsx index 8fe0e2bc55a6..86458e8038d6 100644 --- a/app/client/src/pages/common/PageHeader.tsx +++ b/app/client/src/pages/common/PageHeader.tsx @@ -25,7 +25,6 @@ import { ReactComponent as TwoLineHamburger } from "assets/icons/ads/two-line-ha import MobileSideBar from "./MobileSidebar"; import { Indices } from "constants/Layers"; import { Icon, IconSize } from "design-system"; -import { TemplatesTabItem } from "pages/Templates/TemplatesTabItem"; import { getTemplateNotificationSeenAction } from "actions/templateActions"; const StyledPageHeader = styled(StyledHeader)<{ @@ -180,18 +179,17 @@ export function PageHeader(props: PageHeaderProps) { > <div>Apps</div> </TabName> - <TemplatesTabItem> - <TabName - className="t--templates-tab" - isSelected={ - matchTemplatesPath(location.pathname) || - matchTemplatesIdPath(location.pathname) - } - onClick={() => history.push(TEMPLATES_PATH)} - > - <div>Templates</div> - </TabName> - </TemplatesTabItem> + + <TabName + className="t--templates-tab" + isSelected={ + matchTemplatesPath(location.pathname) || + matchTemplatesIdPath(location.pathname) + } + onClick={() => history.push(TEMPLATES_PATH)} + > + <div>Templates</div> + </TabName> </> )} </Tabs> diff --git a/app/client/src/reducers/uiReducers/templateReducer.ts b/app/client/src/reducers/uiReducers/templateReducer.ts index 804ef357c5f6..914bffd6bc85 100644 --- a/app/client/src/reducers/uiReducers/templateReducer.ts +++ b/app/client/src/reducers/uiReducers/templateReducer.ts @@ -4,18 +4,24 @@ import { ReduxActionErrorTypes, ReduxActionTypes, } from "@appsmith/constants/ReduxActionConstants"; -import { Template } from "api/TemplatesApi"; +import { Template, TemplateFiltersResponse } from "api/TemplatesApi"; const initialState: TemplatesReduxState = { isImportingTemplate: false, + isImportingTemplateToApp: false, + loadingFilters: false, gettingAllTemplates: false, gettingTemplate: false, activeTemplate: null, templates: [], similarTemplates: [], filters: {}, + allFilters: { + functions: [], + }, templateSearchQuery: "", templateNotificationSeen: null, + showTemplatesModal: false, }; const templateReducer = createReducer(initialState, { @@ -96,6 +102,30 @@ const templateReducer = createReducer(initialState, { isImportingTemplate: false, }; }, + [ReduxActionTypes.IMPORT_TEMPLATE_TO_APPLICATION_INIT]: ( + state: TemplatesReduxState, + ) => { + return { + ...state, + isImportingTemplateToApp: true, + }; + }, + [ReduxActionTypes.IMPORT_TEMPLATE_TO_APPLICATION_SUCCESS]: ( + state: TemplatesReduxState, + ) => { + return { + ...state, + isImportingTemplateToApp: false, + }; + }, + [ReduxActionErrorTypes.IMPORT_TEMPLATE_TO_APPLICATION_ERROR]: ( + state: TemplatesReduxState, + ) => { + return { + ...state, + isImportingTemplateToApp: false, + }; + }, [ReduxActionErrorTypes.GET_TEMPLATE_ERROR]: (state: TemplatesReduxState) => { return { ...state, @@ -120,9 +150,45 @@ const templateReducer = createReducer(initialState, { templateNotificationSeen: action.payload, }; }, + [ReduxActionTypes.SHOW_TEMPLATES_MODAL]: ( + state: TemplatesReduxState, + action: ReduxAction<boolean>, + ) => { + return { + ...state, + showTemplatesModal: action.payload, + }; + }, + [ReduxActionTypes.GET_TEMPLATE_FILTERS_INIT]: ( + state: TemplatesReduxState, + ) => { + return { + ...state, + loadingFilters: true, + }; + }, + [ReduxActionTypes.GET_TEMPLATE_FILTERS_SUCCESS]: ( + state: TemplatesReduxState, + action: ReduxAction<boolean>, + ) => { + return { + ...state, + loadingFilters: false, + allFilters: action.payload, + }; + }, + [ReduxActionErrorTypes.GET_TEMPLATE_FILTERS_ERROR]: ( + state: TemplatesReduxState, + ) => { + return { + ...state, + loadingFilters: false, + }; + }, }); export interface TemplatesReduxState { + allFilters: TemplateFiltersResponse["data"] | Record<string, never>; gettingAllTemplates: boolean; gettingTemplate: boolean; templates: Template[]; @@ -131,7 +197,10 @@ export interface TemplatesReduxState { filters: Record<string, string[]>; templateSearchQuery: string; isImportingTemplate: boolean; + isImportingTemplateToApp: boolean; templateNotificationSeen: boolean | null; + showTemplatesModal: boolean; + loadingFilters: boolean; } export default templateReducer; diff --git a/app/client/src/sagas/ApplicationSagas.tsx b/app/client/src/sagas/ApplicationSagas.tsx index 7604592bbbaa..487f01232804 100644 --- a/app/client/src/sagas/ApplicationSagas.tsx +++ b/app/client/src/sagas/ApplicationSagas.tsx @@ -41,6 +41,7 @@ import { resetCurrentApplication, setDefaultApplicationPageSuccess, setIsReconnectingDatasourcesModalOpen, + setPageIdForImport, setWorkspaceIdForImport, showReconnectDatasourceModal, } from "actions/applicationActions"; @@ -86,7 +87,7 @@ import { import { failFastApiCalls } from "./InitSagas"; import { Datasource } from "entities/Datasource"; import { GUIDED_TOUR_STEPS } from "pages/Editor/GuidedTour/constants"; -import { builderURL, generateTemplateURL, viewerURL } from "RouteBuilder"; +import { builderURL, viewerURL } from "RouteBuilder"; import { getDefaultPageId as selectDefaultPageId } from "./selectors"; import PageApi from "api/PageApi"; import { identity, merge, pickBy } from "lodash"; @@ -549,7 +550,6 @@ export function* createApplicationSaga( const FirstTimeUserOnboardingApplicationId: string = yield select( getFirstTimeUserOnboardingApplicationId, ); - let pageURL; if ( isFirstTimeUserOnboardingEnabled && FirstTimeUserOnboardingApplicationId === "" @@ -559,15 +559,12 @@ export function* createApplicationSaga( ReduxActionTypes.SET_FIRST_TIME_USER_ONBOARDING_APPLICATION_ID, payload: application.id, }); - pageURL = builderURL({ - pageId: application.defaultPageId as string, - }); - } else { - pageURL = generateTemplateURL({ - pageId: application.defaultPageId as string, - }); } - history.push(pageURL); + history.push( + builderURL({ + pageId: application.defaultPageId as string, + }), + ); // subscribe to newly created application // users join rooms on connection, so reconnecting @@ -632,10 +629,12 @@ function* showReconnectDatasourcesModalSaga( application: ApplicationResponsePayload; unConfiguredDatasourceList: Array<Datasource>; workspaceId: string; + pageId?: string; }>, ) { const { application, + pageId, unConfiguredDatasourceList, workspaceId, } = action.payload; @@ -648,6 +647,7 @@ function* showReconnectDatasourcesModalSaga( ); yield put(setWorkspaceIdForImport(workspaceId)); + yield put(setPageIdForImport(pageId)); yield put(setIsReconnectingDatasourcesModalOpen({ isOpen: true })); } diff --git a/app/client/src/sagas/PageSagas.tsx b/app/client/src/sagas/PageSagas.tsx index 167268ebd17d..f762b007a7c1 100644 --- a/app/client/src/sagas/PageSagas.tsx +++ b/app/client/src/sagas/PageSagas.tsx @@ -103,11 +103,7 @@ import { GenerateTemplatePageRequest } from "api/PageApi"; import { getAppMode } from "selectors/applicationSelectors"; import { setCrudInfoModalData } from "actions/crudInfoModalActions"; import { selectMultipleWidgetsAction } from "actions/widgetSelectionActions"; -import { - getIsFirstTimeUserOnboardingEnabled, - getFirstTimeUserOnboardingApplicationId, - inGuidedTour, -} from "selectors/onboardingSelectors"; +import { inGuidedTour } from "selectors/onboardingSelectors"; import { fetchJSCollectionsForPage, fetchJSCollectionsForPageSuccess, @@ -117,7 +113,7 @@ import { import WidgetFactory from "utils/WidgetFactory"; import { toggleShowDeviationDialog } from "actions/onboardingActions"; import { DataTree } from "entities/DataTree/dataTreeFactory"; -import { builderURL, generateTemplateURL } from "RouteBuilder"; +import { builderURL } from "RouteBuilder"; import { failFastApiCalls } from "./InitSagas"; import { takeEvery } from "redux-saga/effects"; import { resizePublishedMainCanvasToLowestWidget } from "./WidgetOperationUtils"; @@ -587,29 +583,11 @@ export function* createPageSaga( // TODO: Update URL params here // route to generate template for new page created if (!createPageAction.payload.blockNavigation) { - const firstTimeUserOnboardingApplicationId: string = yield select( - getFirstTimeUserOnboardingApplicationId, - ); - const isFirstTimeUserOnboardingEnabled: boolean = yield select( - getIsFirstTimeUserOnboardingEnabled, + history.push( + builderURL({ + pageId: response.data.id, + }), ); - if ( - firstTimeUserOnboardingApplicationId == - createPageAction.payload.applicationId && - isFirstTimeUserOnboardingEnabled - ) { - history.push( - builderURL({ - pageId: response.data.id, - }), - ); - } else { - history.push( - generateTemplateURL({ - pageId: response.data.id, - }), - ); - } } } } catch (error) { diff --git a/app/client/src/sagas/TemplatesSagas.ts b/app/client/src/sagas/TemplatesSagas.ts index 65c915c37c94..f170a7c00d81 100644 --- a/app/client/src/sagas/TemplatesSagas.ts +++ b/app/client/src/sagas/TemplatesSagas.ts @@ -1,23 +1,46 @@ import { ApplicationPayload, + Page, ReduxAction, ReduxActionErrorTypes, ReduxActionTypes, } from "@appsmith/constants/ReduxActionConstants"; -import { all, put, takeEvery, call } from "redux-saga/effects"; +import { all, put, takeEvery, call, select, take } from "redux-saga/effects"; +import { differenceBy } from "lodash"; import TemplatesAPI, { - FetchTemplateResponse, ImportTemplateResponse, + FetchTemplateResponse, + TemplateFiltersResponse, } from "api/TemplatesApi"; import history from "utils/history"; import { getDefaultPageId } from "./ApplicationSagas"; -import { setTemplateNotificationSeenAction } from "actions/templateActions"; +import { + getAllTemplates, + setTemplateNotificationSeenAction, + showTemplatesModal, +} from "actions/templateActions"; import { getTemplateNotificationSeen, setTemplateNotificationSeen, } from "utils/storage"; import { validateResponse } from "./ErrorSagas"; import { builderURL } from "RouteBuilder"; +import { getCurrentApplicationId } from "selectors/editorSelectors"; +import { getCurrentWorkspaceId } from "@appsmith/selectors/workspaceSelectors"; +import { fetchApplication } from "actions/applicationActions"; +import { APP_MODE } from "entities/App"; +import { getPageList } from "selectors/entitiesSelector"; +import { + executePageLoadActions, + fetchActions, +} from "actions/pluginActionActions"; +import { fetchJSCollections } from "actions/jsActionActions"; +import { failFastApiCalls } from "./InitSagas"; +import { Toaster } from "components/ads/Toast"; +import { Variant } from "components/ads/common"; +import { fetchDatasources } from "actions/datasourceActions"; +import { fetchPluginFormConfigs } from "actions/pluginActions"; +import { fetchAllPageEntityCompletion, saveLayout } from "actions/pageActions"; import { showReconnectDatasourceModal } from "actions/applicationActions"; function* getAllTemplatesSaga() { @@ -79,6 +102,7 @@ function* importTemplateToWorkspaceSaga( }); history.push(pageURL); } + yield put(getAllTemplates()); } } catch (error) { yield put({ @@ -150,6 +174,148 @@ function* getTemplateSaga(action: ReduxAction<string>) { } } +function* postPageAdditionSaga(applicationId: string) { + const afterActionsFetch: boolean = yield failFastApiCalls( + [ + fetchActions({ applicationId }, []), + fetchJSCollections({ applicationId }), + fetchDatasources(), + ], + [ + ReduxActionTypes.FETCH_ACTIONS_SUCCESS, + ReduxActionTypes.FETCH_JS_ACTIONS_SUCCESS, + ReduxActionTypes.FETCH_DATASOURCES_SUCCESS, + ], + [ + ReduxActionErrorTypes.FETCH_ACTIONS_ERROR, + ReduxActionErrorTypes.FETCH_JS_ACTIONS_ERROR, + ReduxActionErrorTypes.FETCH_DATASOURCES_ERROR, + ], + ); + + if (!afterActionsFetch) { + throw new Error("Failed importing template"); + } + + const afterPluginFormsFetch: boolean = yield failFastApiCalls( + [fetchPluginFormConfigs()], + [ReduxActionTypes.FETCH_PLUGIN_FORM_CONFIGS_SUCCESS], + [ReduxActionErrorTypes.FETCH_PLUGIN_FORM_CONFIGS_ERROR], + ); + + if (!afterPluginFormsFetch) { + throw new Error("Failed importing template"); + } + + yield put(fetchAllPageEntityCompletion([executePageLoadActions()])); +} + +function* forkTemplateToApplicationSaga( + action: ReduxAction<{ + templateId: string; + templateName: string; + pageNames?: string[]; + }>, +) { + try { + const pagesToImport = action.payload.pageNames + ? action.payload.pageNames + : undefined; + const applicationId: string = yield select(getCurrentApplicationId); + const workspaceId: string = yield select(getCurrentWorkspaceId); + const response: ImportTemplateResponse = yield call( + TemplatesAPI.importTemplateToApplication, + action.payload.templateId, + applicationId, + workspaceId, + pagesToImport, + ); + const currentListOfPages: Page[] = yield select(getPageList); + // To fetch the new set of pages after merging the template into the existing application + yield put( + fetchApplication({ + mode: APP_MODE.EDIT, + applicationId, + }), + ); + const isValid: boolean = yield validateResponse(response); + + if (isValid) { + const postImportPageList = response.data.application.pages.map((page) => { + return { pageId: page.id, ...page }; + }); + const newPages = differenceBy( + postImportPageList, + currentListOfPages, + "pageId", + ); + + // Fetch the actions/jsobjects of the new set of pages that have been added + yield call(postPageAdditionSaga, applicationId); + + if (response.data.isPartialImport) { + yield put( + showReconnectDatasourceModal({ + application: response.data.application, + unConfiguredDatasourceList: + response.data.unConfiguredDatasourceList, + workspaceId, + pageId: newPages[0].pageId, + }), + ); + } + history.push( + builderURL({ + pageId: newPages[0].pageId, + }), + ); + yield put(showTemplatesModal(false)); + + yield take(ReduxActionTypes.UPDATE_CANVAS_STRUCTURE); + yield put(saveLayout()); + yield put({ + type: ReduxActionTypes.IMPORT_TEMPLATE_TO_APPLICATION_SUCCESS, + payload: response.data.application, + }); + yield put(getAllTemplates()); + + Toaster.show({ + text: `Pages from '${action.payload.templateName}' template added successfully`, + variant: Variant.success, + }); + } + } catch (error) { + yield put({ + type: ReduxActionErrorTypes.IMPORT_TEMPLATE_TO_APPLICATION_ERROR, + payload: { + error, + }, + }); + } +} + +function* getTemplateFiltersSaga() { + try { + const response: TemplateFiltersResponse = yield call( + TemplatesAPI.getTemplateFilters, + ); + const isValid: boolean = yield validateResponse(response); + if (isValid) { + yield put({ + type: ReduxActionTypes.GET_TEMPLATE_FILTERS_SUCCESS, + payload: response.data, + }); + } + } catch (e) { + yield put({ + type: ReduxActionErrorTypes.GET_TEMPLATE_FILTERS_ERROR, + payload: { + e, + }, + }); + } +} + export default function* watchActionSagas() { yield all([ takeEvery(ReduxActionTypes.GET_ALL_TEMPLATES_INIT, getAllTemplatesSaga), @@ -170,5 +336,13 @@ export default function* watchActionSagas() { ReduxActionTypes.SET_TEMPLATE_NOTIFICATION_SEEN, setTemplateNotificationSeenSaga, ), + takeEvery( + ReduxActionTypes.IMPORT_TEMPLATE_TO_APPLICATION_INIT, + forkTemplateToApplicationSaga, + ), + takeEvery( + ReduxActionTypes.GET_TEMPLATE_FILTERS_INIT, + getTemplateFiltersSaga, + ), ]); } diff --git a/app/client/src/sagas/WidgetOperationSagas.tsx b/app/client/src/sagas/WidgetOperationSagas.tsx index cee0ecbf1022..99172dabd187 100644 --- a/app/client/src/sagas/WidgetOperationSagas.tsx +++ b/app/client/src/sagas/WidgetOperationSagas.tsx @@ -139,7 +139,6 @@ import { reflow } from "reflow"; import { getBottomMostRow } from "reflow/reflowUtils"; import { flashElementsById } from "utils/helpers"; import { getSlidingCanvasName } from "constants/componentClassNameConstants"; -import { matchGeneratePagePath } from "constants/routes"; import { builderURL } from "RouteBuilder"; import history from "utils/history"; @@ -1594,11 +1593,7 @@ function* pasteWidgetSaga( const pageId: string = yield select(getCurrentPageId); - if ( - copiedWidgetGroups && - copiedWidgetGroups.length > 0 && - matchGeneratePagePath(window.location.pathname) - ) { + if (copiedWidgetGroups && copiedWidgetGroups.length > 0) { history.push(builderURL({ pageId })); } diff --git a/app/client/src/selectors/applicationSelectors.tsx b/app/client/src/selectors/applicationSelectors.tsx index 0300b4232a79..4cc65f181e6b 100644 --- a/app/client/src/selectors/applicationSelectors.tsx +++ b/app/client/src/selectors/applicationSelectors.tsx @@ -167,6 +167,9 @@ export const getIsImportingApplication = (state: AppState) => export const getWorkspaceIdForImport = (state: AppState) => state.ui.applications.workspaceIdForImport; +export const getPageIdForImport = (state: AppState) => + state.ui.applications.pageIdForImport; + export const getImportedApplication = (state: AppState) => state.ui.applications.importedApplication; diff --git a/app/client/src/selectors/editorSelectors.tsx b/app/client/src/selectors/editorSelectors.tsx index 18f6f7b2b52b..d273d6d0ecc4 100644 --- a/app/client/src/selectors/editorSelectors.tsx +++ b/app/client/src/selectors/editorSelectors.tsx @@ -592,3 +592,13 @@ export const getIsSavingEntity = (state: AppState) => export const selectJSCollections = (state: AppState) => state.entities.jsActions; + +export const showCanvasTopSectionSelector = createSelector( + getCanvasWidgets, + previewModeSelector, + (canvasWidgets, inPreviewMode) => { + if (Object.keys(canvasWidgets).length > 1 || inPreviewMode) return false; + + return true; + }, +); diff --git a/app/client/src/selectors/entitiesSelector.ts b/app/client/src/selectors/entitiesSelector.ts index 33c33cb6e9b3..600dd13d4de2 100644 --- a/app/client/src/selectors/entitiesSelector.ts +++ b/app/client/src/selectors/entitiesSelector.ts @@ -834,3 +834,14 @@ export const getJSCollectionParseErrors = ( return error.errorType === PropertyEvaluationErrorType.PARSE; }); }; + +export const getNumberOfEntitiesInCurrentPage = createSelector( + getCanvasWidgets, + getActionsForCurrentPage, + getJSCollectionsForCurrentPage, + (widgets, actions, jsCollections) => { + return ( + Object.keys(widgets).length - 1 + actions.length + jsCollections.length + ); + }, +); diff --git a/app/client/src/selectors/templatesSelectors.tsx b/app/client/src/selectors/templatesSelectors.tsx index 02d05a03bc10..73725c615933 100644 --- a/app/client/src/selectors/templatesSelectors.tsx +++ b/app/client/src/selectors/templatesSelectors.tsx @@ -19,6 +19,8 @@ export const getTemplatesSelector = (state: AppState) => state.ui.templates.templates; export const isImportingTemplateSelector = (state: AppState) => state.ui.templates.isImportingTemplate; +export const isImportingTemplateToAppSelector = (state: AppState) => + state.ui.templates.isImportingTemplateToApp; export const showTemplateNotificationSelector = (state: AppState) => state.ui.templates.templateNotificationSeen; @@ -63,6 +65,7 @@ export const getFilteredTemplateList = createSelector( getTemplateFiltersLength, (templates, templatesFilters, numberOfFiltersApplied) => { const result: Template[] = []; + const activeTemplateIds: string[] = []; if (!numberOfFiltersApplied) { return templates; @@ -74,12 +77,17 @@ export const getFilteredTemplateList = createSelector( Object.keys(templatesFilters).map((filter) => { templates.map((template) => { + if (activeTemplateIds.includes(template.id)) { + return; + } + if ( template[filter as FilterKeys].some((templateFilter) => { return templatesFilters[filter].includes(templateFilter); }) ) { result.push(template); + activeTemplateIds.push(template.id); } }); }); @@ -135,22 +143,26 @@ export const templatesDatasourceFiltersSelector = createSelector( }, ); +export const templatesFiltersSelector = (state: AppState) => + state.ui.templates.allFilters; + // Get all filters which is associated with atleast one template // If no template is associated with a filter, then the filter shouldn't be in the filter list export const getFilterListSelector = createSelector( getWidgetCards, templatesDatasourceFiltersSelector, getTemplatesSelector, - (widgetConfigs, allDatasources, templates) => { + templatesFiltersSelector, + (widgetConfigs, allDatasources, templates, allTemplateFilters) => { const filters: Record<string, Filter[]> = { datasources: [], - widgets: [], + functions: [], }; - const allWidgets = widgetConfigs.map((widget) => { + const allFunctions = allTemplateFilters.functions.map((item) => { return { - label: widget.displayName, - value: widget.type, + label: item, + value: item, }; }); @@ -181,7 +193,7 @@ export const getFilterListSelector = createSelector( templates.map((template) => { filterFilters("datasources", allDatasources, template); - filterFilters("widgets", allWidgets, template); + filterFilters("functions", allFunctions, template); }); return filters; @@ -199,3 +211,9 @@ export const getForkableWorkspaces = createSelector( }); }, ); + +export const templateModalOpenSelector = (state: AppState) => + state.ui.templates.showTemplatesModal; + +export const templatesCountSelector = (state: AppState) => + state.ui.templates.templates.length;
8f5668e23fc7fa25a2ee65b854af0f8c9b6081d8
2022-10-14 11:09:52
Souma Ghosh
fix: Ends with operator not working as expected (#17519)
false
Ends with operator not working as expected (#17519)
fix
diff --git a/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/Widgets/TableV1/TableFilter2_Spec.ts b/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/Widgets/TableV1/TableFilter2_Spec.ts index f82b4ac98f9e..8d8a8e6d8f3f 100644 --- a/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/Widgets/TableV1/TableFilter2_Spec.ts +++ b/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/Widgets/TableV1/TableFilter2_Spec.ts @@ -359,7 +359,7 @@ describe("Verify various Table_Filter combinations", function() { filterOnlyCondition("starts with", "1"); //Ends with - Open Bug 13334 - //filterOnlyCondition('ends with', '1') + filterOnlyCondition("ends with", "1"); filterOnlyCondition("is exactly", "1"); filterOnlyCondition("empty", "0"); diff --git a/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/Widgets/TableV2/TableV2Filter2_Spec.ts b/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/Widgets/TableV2/TableV2Filter2_Spec.ts index 892f9cce6faf..7448061d95b1 100644 --- a/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/Widgets/TableV2/TableV2Filter2_Spec.ts +++ b/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/Widgets/TableV2/TableV2Filter2_Spec.ts @@ -366,8 +366,8 @@ describe("Verify various Table_Filter combinations", function() { filterOnlyCondition("does not contain", "49"); filterOnlyCondition("starts with", "1"); - //Ends with - Open Bug 13334 - //filterOnlyCondition('ends with', '1') + // Ends with - Open Bug 13334 + filterOnlyCondition("ends with", "1"); filterOnlyCondition("is exactly", "1"); filterOnlyCondition("empty", "0"); diff --git a/app/client/src/widgets/TableWidgetV2/widget/derived.js b/app/client/src/widgets/TableWidgetV2/widget/derived.js index 53fce2c5bbde..c23e64009290 100644 --- a/app/client/src/widgets/TableWidgetV2/widget/derived.js +++ b/app/client/src/widgets/TableWidgetV2/widget/derived.js @@ -444,8 +444,10 @@ export default { try { const _a = a.toString().toLowerCase(); const _b = b.toString().toLowerCase(); - - return _a.length === _a.lastIndexOf(_b) + _b.length; + return ( + _a.lastIndexOf(_b) >= 0 && + _a.length === _a.lastIndexOf(_b) + _b.length + ); } catch (e) { return false; }
4bc17853926c4e8c314cbc8da54a86feee592a93
2024-06-18 15:07:23
Shrikant Sharat Kandula
chore: Deprecate `.findById` signature with `Optional` parameter (#34281)
false
Deprecate `.findById` signature with `Optional` parameter (#34281)
chore
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 82f295645d74..f0306aaf6a05 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 @@ -14,7 +14,6 @@ import reactor.core.publisher.Mono; import java.util.List; -import java.util.Optional; public interface ActionCollectionServiceCE extends CrudService<ActionCollection, String> { @@ -47,10 +46,8 @@ Mono<ActionCollectionDTO> splitValidActionsByViewMode( Mono<ActionCollectionDTO> deleteUnpublishedActionCollection(String id); - Mono<ActionCollectionDTO> deleteUnpublishedActionCollectionWithOptionalPermission( - String id, - Optional<AclPermission> deleteCollectionPermission, - Optional<AclPermission> deleteActionPermission); + Mono<ActionCollectionDTO> deleteUnpublishedActionCollection( + String id, AclPermission deleteCollectionPermission, AclPermission deleteActionPermission); Mono<ActionCollectionDTO> deleteWithoutPermissionUnpublishedActionCollection(String id); 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 00115e7cd6bd..8018b14e23d8 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 @@ -42,7 +42,6 @@ import java.util.List; import java.util.Map; import java.util.Objects; -import java.util.Optional; import java.util.Set; import java.util.UUID; @@ -343,28 +342,18 @@ public Mono<ActionCollectionDTO> update(String id, ActionCollectionDTO actionCol @Override public Mono<ActionCollectionDTO> deleteWithoutPermissionUnpublishedActionCollection(String id) { - return deleteUnpublishedActionCollectionEx( - id, Optional.empty(), Optional.of(actionPermission.getDeletePermission())); + return deleteUnpublishedActionCollection(id, null, actionPermission.getDeletePermission()); } @Override public Mono<ActionCollectionDTO> deleteUnpublishedActionCollection(String id) { - return deleteUnpublishedActionCollectionEx( - id, - Optional.of(actionPermission.getDeletePermission()), - Optional.of(actionPermission.getDeletePermission())); + return deleteUnpublishedActionCollection( + id, actionPermission.getDeletePermission(), actionPermission.getDeletePermission()); } @Override - public Mono<ActionCollectionDTO> deleteUnpublishedActionCollectionWithOptionalPermission( - String id, - Optional<AclPermission> deleteCollectionPermission, - Optional<AclPermission> deleteActionPermission) { - return deleteUnpublishedActionCollectionEx(id, deleteCollectionPermission, deleteActionPermission); - } - - public Mono<ActionCollectionDTO> deleteUnpublishedActionCollectionEx( - String id, Optional<AclPermission> permission, Optional<AclPermission> deleteActionPermission) { + public Mono<ActionCollectionDTO> deleteUnpublishedActionCollection( + String id, AclPermission permission, AclPermission deleteActionPermission) { Mono<ActionCollection> actionCollectionMono = repository .findById(id, permission) .switchIfEmpty(Mono.error( @@ -377,7 +366,7 @@ public Mono<ActionCollectionDTO> deleteUnpublishedActionCollectionEx( && toDelete.getPublishedCollection().getName() != null) { toDelete.getUnpublishedCollection().setDeletedAt(Instant.now()); modifiedActionCollectionMono = newActionService - .findByCollectionIdAndViewMode(id, false, deleteActionPermission.orElse(null)) + .findByCollectionIdAndViewMode(id, false, deleteActionPermission) .flatMap(newAction -> newActionService .deleteGivenNewAction(newAction) // return an empty action so that the filter can remove it from the list diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/applications/git/GitApplicationHelperCEImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/applications/git/GitApplicationHelperCEImpl.java index b7dfd83d4b0d..00f390266fb7 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/applications/git/GitApplicationHelperCEImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/applications/git/GitApplicationHelperCEImpl.java @@ -256,7 +256,7 @@ public Mono<Application> disconnectEntitiesOfDefaultArtifact(Artifact defaultArt // Update all the resources to replace defaultResource Ids with the resource Ids as branchName // will be deleted Flux<NewPage> newPageFlux = Flux.fromIterable(defaultApplication.getPages()) - .flatMap(page -> newPageService.findById(page.getId(), Optional.empty())) + .flatMap(page -> newPageService.findById(page.getId(), null)) .map(newPage -> { newPage.setDefaultResources(null); return createDefaultIdsOrUpdateWithGivenResourceIds(newPage, null); diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/imports/internal/partial/PartialImportServiceCEImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/imports/internal/partial/PartialImportServiceCEImpl.java index 1104aeb233b5..df841c64d410 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/imports/internal/partial/PartialImportServiceCEImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/imports/internal/partial/PartialImportServiceCEImpl.java @@ -58,7 +58,6 @@ import java.util.HashSet; import java.util.List; import java.util.Map; -import java.util.Optional; import java.util.Set; import java.util.regex.Pattern; import java.util.stream.Collectors; @@ -375,7 +374,7 @@ private Mono<String> paneNameMapForActionAndActionCollectionInAppJson( ApplicationJson applicationJson, MappedImportableResourcesDTO mappedImportableResourcesDTO) { return branchedPageIdMono.flatMap( - pageId -> newPageService.findById(pageId, Optional.empty()).flatMap(newPage -> { + pageId -> newPageService.findById(pageId, null).flatMap(newPage -> { String pageName = newPage.getUnpublishedPage().getName(); // update page name reference with newPage Map<String, NewPage> pageNameMap = new HashMap<>(); diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/newactions/base/NewActionServiceCE.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/newactions/base/NewActionServiceCE.java index 734c04316331..da222142a878 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/newactions/base/NewActionServiceCE.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/newactions/base/NewActionServiceCE.java @@ -48,7 +48,7 @@ public interface NewActionServiceCE extends CrudService<NewAction, String> { Mono<ActionDTO> updateUnpublishedAction(String id, ActionDTO action); Mono<Tuple2<ActionDTO, NewAction>> updateUnpublishedActionWithoutAnalytics( - String id, ActionDTO action, Optional<AclPermission> permission); + String id, ActionDTO action, AclPermission permission); Mono<ActionDTO> findByUnpublishedNameAndPageId(String name, String pageId, AclPermission permission); @@ -84,8 +84,7 @@ Flux<NewAction> findAllByApplicationIdAndViewMode( Mono<ActionDTO> deleteUnpublishedAction(String id); - Mono<ActionDTO> deleteUnpublishedActionWithOptionalPermission( - String id, Optional<AclPermission> newActionDeletePermission); + Mono<ActionDTO> deleteUnpublishedAction(String id, AclPermission newActionDeletePermission); Flux<ActionDTO> getUnpublishedActions(MultiValueMap<String, String> params, Boolean includeJsActions); diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/newactions/base/NewActionServiceCEImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/newactions/base/NewActionServiceCEImpl.java index fe280730b79b..e529e95957b5 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/newactions/base/NewActionServiceCEImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/newactions/base/NewActionServiceCEImpl.java @@ -579,7 +579,7 @@ public Mono<ActionDTO> updateUnpublishedAction(String id, ActionDTO action) { action != null ? action.getId() : null, id); - return updateUnpublishedActionWithoutAnalytics(id, action, Optional.of(actionPermission.getEditPermission())) + return updateUnpublishedActionWithoutAnalytics(id, action, actionPermission.getEditPermission()) .zipWhen(zippedActions -> { ActionDTO updatedActionDTO = zippedActions.getT1(); if (updatedActionDTO.getDatasource() != null @@ -626,7 +626,7 @@ public Mono<ActionDTO> updateUnpublishedAction(String id, ActionDTO action) { */ @Override public Mono<Tuple2<ActionDTO, NewAction>> updateUnpublishedActionWithoutAnalytics( - String id, ActionDTO action, Optional<AclPermission> permission) { + String id, ActionDTO action, AclPermission permission) { log.debug( "Updating unpublished action without analytics with action id: {} ", action != null ? action.getId() : null); @@ -848,12 +848,11 @@ public ActionViewDTO generateActionViewDTO(NewAction action, ActionDTO actionDTO @Override public Mono<ActionDTO> deleteUnpublishedAction(String id) { - return deleteUnpublishedActionWithOptionalPermission(id, Optional.of(actionPermission.getDeletePermission())); + return deleteUnpublishedAction(id, actionPermission.getDeletePermission()); } @Override - public Mono<ActionDTO> deleteUnpublishedActionWithOptionalPermission( - String id, Optional<AclPermission> newActionDeletePermission) { + public Mono<ActionDTO> deleteUnpublishedAction(String id, AclPermission newActionDeletePermission) { Mono<NewAction> actionMono = repository .findById(id, newActionDeletePermission) .switchIfEmpty( diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/newactions/importable/NewActionImportableServiceCEImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/newactions/importable/NewActionImportableServiceCEImpl.java index f1da12cc83a8..aba07e6176f2 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/newactions/importable/NewActionImportableServiceCEImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/newactions/importable/NewActionImportableServiceCEImpl.java @@ -36,7 +36,6 @@ import java.util.HashSet; import java.util.List; import java.util.Map; -import java.util.Optional; import java.util.Set; import static com.appsmith.external.helpers.AppsmithBeanUtils.copyNestedNonNullProperties; @@ -99,7 +98,7 @@ public Mono<Void> importEntities( log.info("Deleting {} actions which are no more used", invalidActionIds.size()); return Flux.fromIterable(invalidActionIds) .flatMap(actionId -> newActionService - .deleteUnpublishedActionWithOptionalPermission(actionId, Optional.empty()) + .deleteUnpublishedAction(actionId, null) // 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); diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/newpages/base/NewPageServiceCE.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/newpages/base/NewPageServiceCE.java index 946b439a9881..14911f7b9362 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/newpages/base/NewPageServiceCE.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/newpages/base/NewPageServiceCE.java @@ -23,8 +23,6 @@ public interface NewPageServiceCE extends CrudService<NewPage, String> { Mono<NewPage> findById(String pageId, AclPermission aclPermission); - Mono<NewPage> findById(String pageId, Optional<AclPermission> aclPermission); - Mono<PageDTO> findPageById(String pageId, AclPermission aclPermission, Boolean view); Flux<PageDTO> findByApplicationId(String applicationId, AclPermission permission, Boolean view); @@ -73,7 +71,7 @@ Mono<PageDTO> findByNameAndApplicationIdAndViewMode( Mono<Boolean> archiveByIds(Collection<String> idList); - Mono<NewPage> archiveWithoutPermissionById(String id); + Mono<NewPage> archiveByIdWithoutPermission(String id); Flux<NewPage> saveAll(List<NewPage> pages); diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/newpages/base/NewPageServiceCEImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/newpages/base/NewPageServiceCEImpl.java index 64125e6f3b80..8c28df19e6f3 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/newpages/base/NewPageServiceCEImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/newpages/base/NewPageServiceCEImpl.java @@ -123,11 +123,6 @@ public Mono<PageDTO> findPageById(String pageId, AclPermission aclPermission, Bo return this.findById(pageId, aclPermission).flatMap(page -> getPageByViewMode(page, view)); } - @Override - public Mono<NewPage> findById(String pageId, Optional<AclPermission> aclPermission) { - return repository.findById(pageId, aclPermission); - } - @Override public Flux<PageDTO> findByApplicationId(String applicationId, AclPermission permission, Boolean view) { return findNewPagesByApplicationId(applicationId, permission).flatMap(page -> getPageByViewMode(page, view)); @@ -521,13 +516,13 @@ public Mono<NewPage> archive(NewPage page) { } @Override - public Mono<NewPage> archiveWithoutPermissionById(String id) { - return archiveByIdEx(id, Optional.empty()); + public Mono<NewPage> archiveByIdWithoutPermission(String id) { + return archiveByIdEx(id, null); } @Override public Mono<NewPage> archiveById(String id) { - return archiveByIdEx(id, Optional.of(pagePermission.getDeletePermission())); + return archiveByIdEx(id, pagePermission.getDeletePermission()); } @Override @@ -535,8 +530,8 @@ public Mono<Boolean> archiveByIds(Collection<String> idList) { return repository.archiveAllById(idList); } - public Mono<NewPage> archiveByIdEx(String id, Optional<AclPermission> permission) { - Mono<NewPage> pageMono = this.findById(id, permission) + private Mono<NewPage> archiveByIdEx(String id, AclPermission permission) { + Mono<NewPage> pageMono = findById(id, permission) .switchIfEmpty( Mono.error(new AppsmithException(AppsmithError.NO_RESOURCE_FOUND, FieldName.PAGE_ID, id))) .cache(); diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/newpages/importable/NewPageImportableServiceCEImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/newpages/importable/NewPageImportableServiceCEImpl.java index 9f22c3a1ebc3..f5182774965d 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/newpages/importable/NewPageImportableServiceCEImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/newpages/importable/NewPageImportableServiceCEImpl.java @@ -359,15 +359,10 @@ Mono<Application> savePagesToApplicationMono( // This does not apply to the traditional import via file approach return Flux.fromIterable(invalidPageIds) .flatMap(pageId -> { - return applicationPageService.deleteUnpublishedPageWithOptionalPermission( - pageId, - Optional.empty(), - Optional.empty(), - Optional.empty(), - Optional.empty()); + return applicationPageService.deleteUnpublishedPage(pageId, null, null, null, null); }) .flatMap(page -> newPageService - .archiveWithoutPermissionById(page.getId()) + .archiveByIdWithoutPermission(page.getId()) .onErrorResume(e -> { log.debug( "Unable to archive page {} with error {}", diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/AppsmithRepository.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/AppsmithRepository.java index c3531ffeaf99..6970a7fb324c 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/AppsmithRepository.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/AppsmithRepository.java @@ -14,6 +14,7 @@ public interface AppsmithRepository<T extends BaseDomain> { Mono<T> findById(String id, AclPermission permission); + @Deprecated(forRemoval = true) Mono<T> findById(String id, Optional<AclPermission> permission); Mono<T> updateById(String id, T resource, AclPermission permission); diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/BaseAppsmithRepositoryCEImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/BaseAppsmithRepositoryCEImpl.java index ef44c1b977b4..1e1023cafc4b 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/BaseAppsmithRepositoryCEImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/BaseAppsmithRepositoryCEImpl.java @@ -120,7 +120,7 @@ public Mono<T> findById(String id, AclPermission permission) { /** * @deprecated using `Optional` for function arguments is an anti-pattern. */ - @Deprecated + @Deprecated(forRemoval = true) public Mono<T> findById(String id, Optional<AclPermission> permission) { return findById(id, permission.orElse(null)); } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/ApplicationPageServiceCE.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/ApplicationPageServiceCE.java index da75547982e4..f92cd9d6530a 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/ApplicationPageServiceCE.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/ApplicationPageServiceCE.java @@ -11,7 +11,6 @@ import reactor.core.publisher.Mono; import java.util.List; -import java.util.Optional; public interface ApplicationPageServiceCE { @@ -50,12 +49,12 @@ Mono<PageDTO> getPageAndMigrateDslByBranchAndDefaultPageId( Mono<PageDTO> deleteUnpublishedPageByBranchAndDefaultPageId(String defaultPageId, String branchName); - Mono<PageDTO> deleteUnpublishedPageWithOptionalPermission( + Mono<PageDTO> deleteUnpublishedPage( String id, - Optional<AclPermission> deletePagePermission, - Optional<AclPermission> readApplicationPermission, - Optional<AclPermission> deleteCollectionPermission, - Optional<AclPermission> deleteActionPermission); + AclPermission deletePagePermission, + AclPermission readApplicationPermission, + AclPermission deleteCollectionPermission, + AclPermission deleteActionPermission); Mono<PageDTO> deleteUnpublishedPage(String id); 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 8ed8a3ff763b..45ba0addfa96 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 @@ -905,16 +905,14 @@ public Mono<Application> cloneApplication(String applicationId, String branchNam * which is currently in published state and is being used. * * @param id The pageId which needs to be archived. - * @param deletePagePermission - * @return */ @Override - public Mono<PageDTO> deleteUnpublishedPageWithOptionalPermission( + public Mono<PageDTO> deleteUnpublishedPage( String id, - Optional<AclPermission> deletePagePermission, - Optional<AclPermission> readApplicationPermission, - Optional<AclPermission> deleteCollectionPermission, - Optional<AclPermission> deleteActionPermission) { + AclPermission deletePagePermission, + AclPermission readApplicationPermission, + AclPermission deleteCollectionPermission, + AclPermission deleteActionPermission) { return deleteUnpublishedPageEx( id, deletePagePermission, @@ -925,40 +923,20 @@ public Mono<PageDTO> deleteUnpublishedPageWithOptionalPermission( @Override public Mono<PageDTO> deleteUnpublishedPage(String id) { - - Optional<AclPermission> deletePagePermission = Optional.of(pagePermission.getDeletePermission()); - Optional<AclPermission> readApplicationPermission = Optional.of(applicationPermission.getReadPermission()); - Optional<AclPermission> deleteCollectionPermission = Optional.of(actionPermission.getDeletePermission()); - Optional<AclPermission> deleteActionPermission = Optional.of(actionPermission.getDeletePermission()); return deleteUnpublishedPageEx( id, - deletePagePermission, - readApplicationPermission, - deleteCollectionPermission, - deleteActionPermission); + pagePermission.getDeletePermission(), + applicationPermission.getReadPermission(), + actionPermission.getDeletePermission(), + actionPermission.getDeletePermission()); } - /** - * This function archives the unpublished page. This also archives the unpublished action. The reason that the - * entire action is not deleted at this point is to handle the following edge case : - * An application is published with 1 page and 1 action. - * Post publish, create a new page and move the action from the existing page to the new page. Now delete this newly - * created page. - * In this scenario, if we were to delete all actions associated with the page, we would end up deleting an action - * which is currently in published state and is being used. - * - * @param id The pageId which needs to be archived. - * @param readApplicationPermission - * @param deleteCollectionPermission - * @param deleteActionPermission - * @return - */ private Mono<PageDTO> deleteUnpublishedPageEx( String id, - Optional<AclPermission> deletePagePermission, - Optional<AclPermission> readApplicationPermission, - Optional<AclPermission> deleteCollectionPermission, - Optional<AclPermission> deleteActionPermission) { + AclPermission deletePagePermission, + AclPermission readApplicationPermission, + AclPermission deleteCollectionPermission, + AclPermission deleteActionPermission) { return newPageService .findById(id, deletePagePermission) @@ -969,7 +947,7 @@ private Mono<PageDTO> deleteUnpublishedPageEx( // Application is accessed without any application permission over here. // previously it was getting accessed only with read permission. Mono<Application> applicationMono = applicationService - .findById(page.getApplicationId(), readApplicationPermission.orElse(null)) + .findById(page.getApplicationId(), readApplicationPermission) .switchIfEmpty(Mono.error( new AppsmithException(AppsmithError.NO_RESOURCE_FOUND, FieldName.APPLICATION, id))) .flatMap(application -> { @@ -997,25 +975,20 @@ private Mono<PageDTO> deleteUnpublishedPageEx( }) .flatMap(newPage -> newPageService.getPageByViewMode(newPage, false)); - /** - * Only delete unpublished action and not the entire action. Also filter actions embedded in - * actionCollection which will be deleted while deleting the collection, this will avoid the race - * condition for delete action - */ + // Only delete unpublished action and not the entire action. Also filter actions embedded in + // actionCollection which will be deleted while deleting the collection, this will avoid the race + // condition for delete action Mono<List<ActionDTO>> archivedActionsMono = newActionService .findByPageId(page.getId(), deleteActionPermission) .filter(newAction -> !StringUtils.hasLength( newAction.getUnpublishedAction().getCollectionId())) .flatMap(action -> { log.debug("Going to archive actionId: {} for applicationId: {}", action.getId(), id); - return newActionService.deleteUnpublishedActionWithOptionalPermission( - action.getId(), deleteActionPermission); + return newActionService.deleteUnpublishedAction(action.getId(), deleteActionPermission); }) .collectList(); - /** - * Only delete unpublished action collection and not the entire action collection. - */ + // Only delete unpublished action collection and not the entire action collection. Mono<List<ActionCollectionDTO>> archivedActionCollectionsMono = actionCollectionService .findByPageId(page.getId()) .flatMap(actionCollection -> { @@ -1023,7 +996,7 @@ private Mono<PageDTO> deleteUnpublishedPageEx( "Going to archive actionCollectionId: {} for applicationId: {}", actionCollection.getId(), id); - return actionCollectionService.deleteUnpublishedActionCollectionWithOptionalPermission( + return actionCollectionService.deleteUnpublishedActionCollection( actionCollection.getId(), deleteCollectionPermission, deleteActionPermission); }) .collectList(); diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/CurlImporterServiceCEImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/CurlImporterServiceCEImpl.java index 0b5ca1678a40..d01fcea30102 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/CurlImporterServiceCEImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/CurlImporterServiceCEImpl.java @@ -34,7 +34,6 @@ import java.util.Base64; import java.util.List; import java.util.Map; -import java.util.Optional; import java.util.regex.Pattern; import static org.apache.commons.lang3.StringUtils.isBlank; @@ -127,7 +126,7 @@ protected Mono<String> getBranchedContextId(CreatorContextType contextType, Stri protected Mono<ActionDTO> associateContextIdToActionDTO( ActionDTO actionDTO, CreatorContextType contextType, String contextId) { actionDTO.setPageId(contextId); - return newPageService.findById(contextId, Optional.empty()).map(newPage -> { + return newPageService.findById(contextId, null).map(newPage -> { // Set git related resource IDs actionDTO.setDefaultResources(newPage.getDefaultResources()); return actionDTO; 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 6ded20d9b4c7..8fc8ae95f74d 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 @@ -48,7 +48,6 @@ import java.io.IOException; import java.time.Instant; import java.util.List; -import java.util.Optional; import java.util.Set; import static org.assertj.core.api.Assertions.assertThat; @@ -484,7 +483,7 @@ public void testUpdateUnpublishedActionCollection_withInvalidId_throwsError() th @Test public void testDeleteUnpublishedActionCollection_withInvalidId_throwsError() { - Mockito.when(actionCollectionRepository.findById(Mockito.any(), Mockito.<Optional<AclPermission>>any())) + Mockito.when(actionCollectionRepository.findById(Mockito.any(), Mockito.<AclPermission>any())) .thenReturn(Mono.empty()); final Mono<ActionCollectionDTO> actionCollectionMono = @@ -514,7 +513,7 @@ public void testDeleteUnpublishedActionCollection_withPublishedCollectionAndNoAc Instant deletedAt = Instant.now(); - Mockito.when(actionCollectionRepository.findById(Mockito.any(), Mockito.<Optional<AclPermission>>any())) + Mockito.when(actionCollectionRepository.findById(Mockito.any(), Mockito.<AclPermission>any())) .thenReturn(Mono.just(actionCollection)); Mockito.when(newActionService.findByCollectionIdAndViewMode( @@ -556,7 +555,7 @@ public void testDeleteUnpublishedActionCollection_withPublishedCollectionAndActi unpublishedCollection.setDefaultResources(setDefaultResources(unpublishedCollection)); Instant deletedAt = Instant.now(); - Mockito.when(actionCollectionRepository.findById(Mockito.any(), Mockito.<Optional<AclPermission>>any())) + Mockito.when(actionCollectionRepository.findById(Mockito.any(), Mockito.<AclPermission>any())) .thenReturn(Mono.just(actionCollection)); ActionDTO actionDTO = @@ -607,7 +606,7 @@ public void testDeleteUnpublishedActionCollection_withPublishedCollectionAndActi .getUnpublishedCollection() .setDefaultResources(setDefaultResources(actionCollection.getUnpublishedCollection())); - Mockito.when(actionCollectionRepository.findById(Mockito.any(), Mockito.<Optional<AclPermission>>any())) + Mockito.when(actionCollectionRepository.findById(Mockito.any(), Mockito.<AclPermission>any())) .thenReturn(Mono.just(actionCollection)); ActionDTO actionDTO = @@ -655,7 +654,7 @@ public void testDeleteUnpublishedActionCollection_withPublishedCollectionAndActi .getUnpublishedCollection() .setDefaultResources(setDefaultResources(actionCollection.getUnpublishedCollection())); - Mockito.when(actionCollectionRepository.findById(Mockito.any(), Mockito.<Optional<AclPermission>>any())) + Mockito.when(actionCollectionRepository.findById(Mockito.any(), Mockito.<AclPermission>any())) .thenReturn(Mono.just(actionCollection)); ActionDTO actionDTO = diff --git a/app/server/appsmith-server/src/test/java/com/appsmith/server/services/NewPageServiceTest.java b/app/server/appsmith-server/src/test/java/com/appsmith/server/services/NewPageServiceTest.java index d8485fb0531a..cc1e04452c01 100644 --- a/app/server/appsmith-server/src/test/java/com/appsmith/server/services/NewPageServiceTest.java +++ b/app/server/appsmith-server/src/test/java/com/appsmith/server/services/NewPageServiceTest.java @@ -36,7 +36,6 @@ import java.util.HashMap; import java.util.List; import java.util.Map; -import java.util.Optional; import java.util.Set; import java.util.UUID; import java.util.function.Function; @@ -431,7 +430,7 @@ public void updateDependencyMap_NotNullValue_shouldUpdateDependencyMap() { dependencyMap.put("key3", List.of("val1", "val2")); return newPageService .updateDependencyMap(pageDTO.getId(), dependencyMap, null) - .then(newPageService.findById(pageDTO.getId(), Optional.empty())); + .then(newPageService.findById(pageDTO.getId(), null)); }); StepVerifier.create(newPageMono) @@ -468,7 +467,7 @@ public void updateDependencyMap_NotNullValueAndPublishApplication_shouldUpdateDe return newPageService .updateDependencyMap(pageDTO.getId(), dependencyMap, null) .flatMap(page -> applicationPageService.publish(application.getId(), null, false)) - .then(newPageService.findById(pageDTO.getId(), Optional.empty())); + .then(newPageService.findById(pageDTO.getId(), null)); }); StepVerifier.create(newPageMono) @@ -504,7 +503,7 @@ public void updateDependencyMap_nullValue_shouldUpdateDependencyMap() { }) .flatMap(pageDTO -> newPageService .updateDependencyMap(pageDTO.getId(), null, null) - .then(newPageService.findById(pageDTO.getId(), Optional.empty()))); + .then(newPageService.findById(pageDTO.getId(), null))); StepVerifier.create(newPageMono) .assertNext(newPage -> { diff --git a/app/server/appsmith-server/src/test/java/com/appsmith/server/solutions/PartialImportServiceTest.java b/app/server/appsmith-server/src/test/java/com/appsmith/server/solutions/PartialImportServiceTest.java index 033fc080a7ed..bce377302465 100644 --- a/app/server/appsmith-server/src/test/java/com/appsmith/server/solutions/PartialImportServiceTest.java +++ b/app/server/appsmith-server/src/test/java/com/appsmith/server/solutions/PartialImportServiceTest.java @@ -282,7 +282,7 @@ public void testPartialImport_nonGitConnectedApp_success() { .block(); String pageId = newPageService - .findById(testApplication.getPages().get(0).getId(), Optional.empty()) + .findById(testApplication.getPages().get(0).getId(), null) .block() .getId(); @@ -400,7 +400,7 @@ public void testPartialImport_nameClashInAction_successWithNoNameDuplicates() { .block(); String pageId = newPageService - .findById(testApplication.getPages().get(0).getId(), Optional.empty()) + .findById(testApplication.getPages().get(0).getId(), null) .block() .getId(); @@ -481,7 +481,7 @@ public void testPartialImportWithBuildingBlock_nameClash_success() { .block(); String pageId = newPageService - .findById(testApplication.getPages().get(0).getId(), Optional.empty()) + .findById(testApplication.getPages().get(0).getId(), null) .block() .getId(); BuildingBlockDTO buildingBlockDTO = new BuildingBlockDTO();
2c46d4231129eedb7ca6261e13e08c7615296595
2022-06-09 14:26:31
Tolulope Adetula
fix: CANVAS_SELECTOR
false
CANVAS_SELECTOR
fix
diff --git a/app/client/src/constants/WidgetConstants.tsx b/app/client/src/constants/WidgetConstants.tsx index 4b4e67c78dad..93edb4d1c5e0 100644 --- a/app/client/src/constants/WidgetConstants.tsx +++ b/app/client/src/constants/WidgetConstants.tsx @@ -93,7 +93,7 @@ export const WIDGET_CLASSNAME_PREFIX = "WIDGET_"; export const MAIN_CONTAINER_WIDGET_ID = "0"; export const MAIN_CONTAINER_WIDGET_NAME = "MainContainer"; export const MODAL_PORTAL_CLASSNAME = "bp3-modal-widget"; -export const CANVAS_SELECTOR = ".canvas"; +export const CANVAS_SELECTOR = "canvas"; export const DEFAULT_CENTER = { lat: -34.397, lng: 150.644 }; diff --git a/app/client/src/widgets/MultiSelectWidget/component/index.tsx b/app/client/src/widgets/MultiSelectWidget/component/index.tsx index e0106a85c565..b514cfe05120 100644 --- a/app/client/src/widgets/MultiSelectWidget/component/index.tsx +++ b/app/client/src/widgets/MultiSelectWidget/component/index.tsx @@ -109,7 +109,7 @@ function MultiSelectComponent({ `.${MODAL_PORTAL_CLASSNAME}`, ) as HTMLElement; } - return document.querySelector(CANVAS_SELECTOR) as HTMLElement; + return document.querySelector(`.${CANVAS_SELECTOR}`) as HTMLElement; }, []); const handleSelectAll = () => { diff --git a/app/client/src/widgets/WidgetUtils.ts b/app/client/src/widgets/WidgetUtils.ts index b65d905e751b..627b758ca003 100644 --- a/app/client/src/widgets/WidgetUtils.ts +++ b/app/client/src/widgets/WidgetUtils.ts @@ -542,4 +542,4 @@ export const parseSchemaItem = ( }; export const getMainCanvas = () => - document.querySelector(CANVAS_SELECTOR) as HTMLElement; + document.querySelector(`.${CANVAS_SELECTOR}`) as HTMLElement; diff --git a/app/client/src/widgets/useDropdown.tsx b/app/client/src/widgets/useDropdown.tsx index 982404abe070..55a5cade6bb4 100644 --- a/app/client/src/widgets/useDropdown.tsx +++ b/app/client/src/widgets/useDropdown.tsx @@ -1,4 +1,4 @@ -import React, { useCallback, useLayoutEffect, useRef } from "react"; +import React, { useCallback, useRef } from "react"; import { getMainCanvas } from "./WidgetUtils"; import styled from "styled-components"; import Select from "rc-select"; @@ -23,13 +23,7 @@ const FOCUS_TIMEOUT = 500; // TODO: Refactor More functionalities in MultiSelect, MultiTreeSelect and TreeSelect Components const useDropdown = ({ inputRef, renderMode, selectRef }: useDropdownProps) => { - const popupContainer = useRef<HTMLElement | null>(null); - - // Get PopupContainer on main Canvas - useLayoutEffect(() => { - const parent = getMainCanvas(); - popupContainer.current = parent; - }, []); + const popupContainer = useRef<HTMLElement>(getMainCanvas()); const closeBackDrop = useCallback(() => { if (selectRef.current) { @@ -41,15 +35,14 @@ const useDropdown = ({ inputRef, renderMode, selectRef }: useDropdownProps) => { function BackDrop() { return <BackDropContainer onClick={closeBackDrop} />; } - const getPopupContainer = useCallback( - () => popupContainer.current as HTMLElement, - [], - ); + // Get PopupContainer on main Canvas + const getPopupContainer = useCallback(() => popupContainer.current, []); // When Dropdown is opened disable scrolling within the app except the list of options const onOpen = useCallback((open: boolean) => { if (open) { setTimeout(() => inputRef.current?.focus(), FOCUS_TIMEOUT); + console.log(popupContainer.current); if (popupContainer.current && renderMode === RenderModes.CANVAS) { popupContainer.current.style.overflowY = "hidden"; }
bd558937aa60d6fa4fa92c7023d6d2c44e860119
2023-11-15 16:49:20
Hetu Nandu
fix: Sidebar release blockers (#28871)
false
Sidebar release blockers (#28871)
fix
diff --git a/app/client/cypress/e2e/Regression/ClientSide/Linting/BasicLint_spec.ts b/app/client/cypress/e2e/Regression/ClientSide/Linting/BasicLint_spec.ts index bf05b53bd854..556c4af89312 100644 --- a/app/client/cypress/e2e/Regression/ClientSide/Linting/BasicLint_spec.ts +++ b/app/client/cypress/e2e/Regression/ClientSide/Linting/BasicLint_spec.ts @@ -358,7 +358,6 @@ describe("Linting", () => { installer.uninstallLibrary("uuidjs"); entityExplorer.SelectEntityByName("JSObject3"); agHelper.AssertElementExist(locators._lintErrorElement); - agHelper.RefreshPage(); EditorNavigation.ViaSidebar(SidebarButton.Libraries); installer.OpenInstaller(); installer.InstallLibrary("uuidjs", "UUID"); diff --git a/app/client/cypress/e2e/Sanity/Datasources/SMTPDatasource_spec.js b/app/client/cypress/e2e/Sanity/Datasources/SMTPDatasource_spec.js index d1f076ea2280..96b325141579 100644 --- a/app/client/cypress/e2e/Sanity/Datasources/SMTPDatasource_spec.js +++ b/app/client/cypress/e2e/Sanity/Datasources/SMTPDatasource_spec.js @@ -33,18 +33,23 @@ describe("SMTP datasource test cases using ted", function () { cy.get(queryLocators.queryFromEmail) .first() .type("{{From.text}}", { parseSpecialCharSequences: false }); + agHelper.ClickOutside(); //to close the evaluated pop-up cy.get(queryLocators.queryFromEmail) .eq(1) .type("{{To.text}}", { parseSpecialCharSequences: false }); + agHelper.ClickOutside(); //to close the evaluated pop-up cy.get(queryLocators.queryFromEmail) .eq(4) .type("{{Subject.text}}", { parseSpecialCharSequences: false }); + agHelper.ClickOutside(); //to close the evaluated pop-up cy.get(queryLocators.queryFromEmail) .eq(5) .type("{{Body.text}}", { parseSpecialCharSequences: false }); + agHelper.ClickOutside(); //to close the evaluated pop-up cy.get(queryLocators.queryFromEmail) .eq(6) .type("{{FilePicker.files}}", { parseSpecialCharSequences: false }); + agHelper.ClickOutside(); //to close the evaluated pop-up cy.get(`.t--entity-name:contains("Page1")`) .should("be.visible") .click({ force: true }); diff --git a/app/client/src/pages/Editor/Explorer/Pages/PageContextMenu.tsx b/app/client/src/pages/Editor/Explorer/Pages/PageContextMenu.tsx index 5883363031b5..93b2f13d70ef 100644 --- a/app/client/src/pages/Editor/Explorer/Pages/PageContextMenu.tsx +++ b/app/client/src/pages/Editor/Explorer/Pages/PageContextMenu.tsx @@ -51,6 +51,9 @@ export function PageContextMenu(props: { }) { const dispatch = useDispatch(); const [confirmDelete, setConfirmDelete] = useState(false); + const isAppSidebarEnabled = useFeatureFlag( + FEATURE_FLAG.release_app_sidebar_enabled, + ); /** * delete the page @@ -178,7 +181,7 @@ export function PageContextMenu(props: { value: "setdefault", label: createMessage(CONTEXT_SET_AS_HOME_PAGE), }, - { + !isAppSidebarEnabled && { value: "settings", onSelect: openAppSettingsPane, label: createMessage(CONTEXT_SETTINGS), diff --git a/app/client/src/pages/Editor/IDE/LeftPane/AddLibraryPopover.tsx b/app/client/src/pages/Editor/IDE/LeftPane/AddLibraryPopover.tsx index 72cf3245b1f8..29757d3f373c 100644 --- a/app/client/src/pages/Editor/IDE/LeftPane/AddLibraryPopover.tsx +++ b/app/client/src/pages/Editor/IDE/LeftPane/AddLibraryPopover.tsx @@ -6,17 +6,27 @@ import { PopoverHeader, PopoverTrigger, } from "design-system"; -import React, { useState } from "react"; +import React, { useCallback, useState } from "react"; import { createMessage, customJSLibraryMessages, } from "@appsmith/constants/messages"; import { Installer } from "../../Explorer/Libraries/Installer"; +import { clearInstalls } from "actions/JSLibraryActions"; +import { useDispatch } from "react-redux"; const AddLibraryPopover = () => { const [open, setOpen] = useState(false); + const dispatch = useDispatch(); + const onOpenChange = useCallback( + (open) => { + dispatch(clearInstalls()); + setOpen(open); + }, + [open], + ); return ( - <Popover onOpenChange={setOpen} open={open}> + <Popover onOpenChange={onOpenChange} open={open}> <PopoverTrigger> <Button className="t--install-library-button"
ab5eb0e325d1594ddb3679ddf0b30bdbd7a9eaa2
2022-08-05 11:49:24
ashit-rath
fix: JSONForm field event trigger binding get updated formData values (#15650)
false
JSONForm field event trigger binding get updated formData values (#15650)
fix
diff --git a/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/Widgets/JSONForm/JSONForm_FieldEvents_spec.js b/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/Widgets/JSONForm/JSONForm_FieldEvents_spec.js index 2e6d2eee7688..63ed3b2f1dab 100644 --- a/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/Widgets/JSONForm/JSONForm_FieldEvents_spec.js +++ b/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/Widgets/JSONForm/JSONForm_FieldEvents_spec.js @@ -4,12 +4,13 @@ const dslWithoutSchema = require("../../../../../fixtures/jsonFormDslWithoutSchema.json"); const commonlocators = require("../../../../../locators/commonlocators.json"); +const widgetLocators = require("../../../../../locators/Widgets.json"); -const onSelectionChangeJSBtn = - ".t--property-control-onselectionchange .t--js-toggle"; const fieldPrefix = ".t--jsonformfield"; -describe("JSONForm Radio Group Field", () => { +const toggleJSButton = (name) => `.t--property-control-${name} .t--js-toggle`; + +describe("Radio Group Field", () => { before(() => { const schema = { answer: "Y", @@ -27,10 +28,10 @@ describe("JSONForm Radio Group Field", () => { cy.openFieldConfiguration("answer"); // Enable JS mode for onSelectionChange - cy.get(onSelectionChangeJSBtn).click({ force: true }); + cy.get(toggleJSButton("onselectionchange")).click({ force: true }); // Add onSelectionChange action - cy.testJsontext("onselectionchange", "{{showAlert('Selection change')}}"); + cy.testJsontext("onselectionchange", "{{showAlert(formData.answer)}}"); cy.get(`${fieldPrefix}-answer`) .find("label") @@ -38,6 +39,204 @@ describe("JSONForm Radio Group Field", () => { .click({ force: true }); // Check for alert - cy.get(commonlocators.toastmsg).contains("Selection change"); + cy.get(commonlocators.toastmsg).contains("N"); + }); +}); + +describe("Multiselect Field", () => { + before(() => { + const schema = { + colors: ["BLUE"], + }; + cy.addDsl(dslWithoutSchema); + cy.openPropertyPane("jsonformwidget"); + cy.testJsontext("sourcedata", JSON.stringify(schema)); + cy.closePropertyPane(); + }); + + it("shows updated formData values in onOptionChange binding", () => { + cy.openPropertyPane("jsonformwidget"); + cy.openFieldConfiguration("colors"); + + // Enable JS mode for onOptionChange + cy.get(toggleJSButton("onoptionchange")).click({ force: true }); + + // Add onOptionChange action + cy.testJsontext( + "onoptionchange", + "{{showAlert(formData.colors.join(', '))}}", + ); + + // Click on multiselect field + cy.get(`${fieldPrefix}-colors`) + .find(".rc-select-selection-search-input") + .first() + .focus({ force: true }) + .type("{uparrow}", { force: true }); + cy.dropdownMultiSelectDynamic("Red"); + + // Check for alert + cy.get(commonlocators.toastmsg).contains("BLUE, RED"); + }); +}); + +describe("Select Field", () => { + before(() => { + const schema = { + color: "BLUE", + }; + cy.addDsl(dslWithoutSchema); + cy.openPropertyPane("jsonformwidget"); + cy.testJsontext("sourcedata", JSON.stringify(schema)); + cy.openFieldConfiguration("color"); + cy.selectDropdownValue(commonlocators.jsonFormFieldType, /^Select/); + cy.closePropertyPane(); + }); + + it("shows updated formData values in onOptionChange binding", () => { + cy.openPropertyPane("jsonformwidget"); + cy.openFieldConfiguration("color"); + + // Enable JS mode for onOptionChange + cy.get(toggleJSButton("onoptionchange")).click({ force: true }); + + // Add onOptionChange action + cy.testJsontext("onoptionchange", "{{showAlert(formData.color)}}"); + + // Click on select field + cy.get(`${fieldPrefix}-color`) + .find(widgetLocators.dropdownSingleSelect) + .click({ force: true }); + + // Select "Red" option + cy.get(commonlocators.singleSelectWidgetMenuItem) + .contains("Red") + .click({ force: true }); + + // Check for alert + cy.get(commonlocators.toastmsg).contains("RED"); + }); +}); + +describe("Input Field", () => { + before(() => { + const schema = { + name: "John", + }; + cy.addDsl(dslWithoutSchema); + cy.openPropertyPane("jsonformwidget"); + cy.testJsontext("sourcedata", JSON.stringify(schema)); + cy.closePropertyPane(); + }); + + it("shows updated formData values in onOptionChange binding", () => { + cy.openPropertyPane("jsonformwidget"); + cy.openFieldConfiguration("name"); + + // Enable JS mode for onTextChanged + cy.get(toggleJSButton("ontextchanged")).click({ force: true }); + + // Add onTextChanged action + cy.testJsontext("ontextchanged", "{{showAlert(formData.name)}}"); + + // Change input value + cy.get(`${fieldPrefix}-name`).type(" Doe"); + + // Check for alert + cy.get(commonlocators.toastmsg).contains("John Doe"); + }); +}); + +describe("Checkbox Field", () => { + before(() => { + const schema = { + agree: true, + }; + cy.addDsl(dslWithoutSchema); + cy.openPropertyPane("jsonformwidget"); + cy.testJsontext("sourcedata", JSON.stringify(schema)); + cy.openFieldConfiguration("agree"); + cy.selectDropdownValue(commonlocators.jsonFormFieldType, /^Checkbox/); + cy.closePropertyPane(); + }); + + it("shows updated formData values in onChange binding", () => { + cy.openPropertyPane("jsonformwidget"); + cy.openFieldConfiguration("agree"); + + // Enable JS mode for onCheckChange + cy.get(toggleJSButton("oncheckchange")).click({ force: true }); + + // Add onCheckChange action + cy.testJsontext( + "oncheckchange", + "{{showAlert(formData.agree.toString())}}", + ); + + // Click on select field + cy.get(`${fieldPrefix}-agree input`).click({ force: true }); + + // Check for alert + cy.get(commonlocators.toastmsg).contains("false"); + }); +}); + +describe("Switch Field", () => { + before(() => { + const schema = { + agree: true, + }; + cy.addDsl(dslWithoutSchema); + cy.openPropertyPane("jsonformwidget"); + cy.testJsontext("sourcedata", JSON.stringify(schema)); + cy.closePropertyPane(); + }); + + it("shows updated formData values in onChange binding", () => { + cy.openPropertyPane("jsonformwidget"); + cy.openFieldConfiguration("agree"); + + // Enable JS mode for onChange + cy.get(toggleJSButton("onchange")).click({ force: true }); + + // Add onChange action + cy.testJsontext("onchange", "{{showAlert(formData.agree.toString())}}"); + + // Click on select field + cy.get(`${fieldPrefix}-agree input`).click({ force: true }); + + // Check for alert + cy.get(commonlocators.toastmsg).contains("false"); + }); +}); + +describe("Date Field", () => { + before(() => { + const schema = { + dob: "20/12/1992", + }; + cy.addDsl(dslWithoutSchema); + cy.openPropertyPane("jsonformwidget"); + cy.testJsontext("sourcedata", JSON.stringify(schema)); + cy.closePropertyPane(); + }); + + it("shows updated formData values in onDateSelected binding", () => { + cy.openPropertyPane("jsonformwidget"); + cy.openFieldConfiguration("dob"); + + // Enable JS mode for onDateSelected + cy.get(toggleJSButton("ondateselected")).click({ force: true }); + + // Add onDateSelected action + cy.testJsontext("ondateselected", "{{showAlert(formData.dob)}}"); + + // Click on select field + cy.get(`${fieldPrefix}-dob .bp3-input`) + .clear({ force: true }) + .type("10/08/2010"); + + // Check for alert + cy.get(commonlocators.toastmsg).contains("10/08/2010"); }); }); diff --git a/app/client/src/widgets/JSONFormWidget/FormContext.tsx b/app/client/src/widgets/JSONFormWidget/FormContext.tsx index 52d431908634..14f89be1391c 100644 --- a/app/client/src/widgets/JSONFormWidget/FormContext.tsx +++ b/app/client/src/widgets/JSONFormWidget/FormContext.tsx @@ -1,12 +1,11 @@ import React, { createContext, useMemo } from "react"; -import { ExecuteTriggerPayload } from "constants/AppsmithActionConstants/ActionConstants"; import { RenderMode } from "constants/WidgetConstants"; -import { JSONFormWidgetState } from "./widget"; +import { Action, JSONFormWidgetState } from "./widget"; import { DebouncedExecuteActionPayload } from "widgets/MetaHOC"; type FormContextProps<TValues = any> = React.PropsWithChildren<{ - executeAction: (actionPayload: ExecuteTriggerPayload) => void; + executeAction: (action: Action) => void; renderMode: RenderMode; setMetaInternalFieldState: ( updateCallback: (prevState: JSONFormWidgetState) => JSONFormWidgetState, diff --git a/app/client/src/widgets/JSONFormWidget/component/index.tsx b/app/client/src/widgets/JSONFormWidget/component/index.tsx index 978db9dbd90b..2a250464401f 100644 --- a/app/client/src/widgets/JSONFormWidget/component/index.tsx +++ b/app/client/src/widgets/JSONFormWidget/component/index.tsx @@ -7,7 +7,6 @@ import WidgetStyleContainer, { BoxShadow, } from "components/designSystems/appsmith/WidgetStyleContainer"; import { Color } from "constants/Colors"; -import { ExecuteTriggerPayload } from "constants/AppsmithActionConstants/ActionConstants"; import { FIELD_MAP, MAX_ALLOWED_FIELDS, @@ -17,7 +16,7 @@ import { import { FormContextProvider } from "../FormContext"; import { isEmpty, pick } from "lodash"; import { RenderMode, RenderModes, TEXT_SIZES } from "constants/WidgetConstants"; -import { JSONFormWidgetState } from "../widget"; +import { Action, JSONFormWidgetState } from "../widget"; import { ButtonStyleProps } from "widgets/ButtonWidget/component"; type StyledContainerProps = { @@ -32,7 +31,7 @@ export type JSONFormComponentProps<TValues = any> = { boxShadow?: BoxShadow; boxShadowColor?: string; disabledWhenInvalid?: boolean; - executeAction: (actionPayload: ExecuteTriggerPayload) => void; + executeAction: (action: Action) => void; fieldLimitExceeded: boolean; fixedFooter: boolean; getFormData: () => TValues; diff --git a/app/client/src/widgets/JSONFormWidget/constants.ts b/app/client/src/widgets/JSONFormWidget/constants.ts index 5788a1ad5565..cd15da675d7e 100644 --- a/app/client/src/widgets/JSONFormWidget/constants.ts +++ b/app/client/src/widgets/JSONFormWidget/constants.ts @@ -157,6 +157,10 @@ export type FieldThemeStylesheet = Record< { [key: string]: string } >; +export enum ActionUpdateDependency { + FORM_DATA = "FORM_DATA", +} + export const ARRAY_ITEM_KEY = "__array_item__"; export const ROOT_SCHEMA_KEY = "__root_schema__"; diff --git a/app/client/src/widgets/JSONFormWidget/fields/BaseInputField.tsx b/app/client/src/widgets/JSONFormWidget/fields/BaseInputField.tsx index d6000c5d1f4c..dbb535a3f4cd 100644 --- a/app/client/src/widgets/JSONFormWidget/fields/BaseInputField.tsx +++ b/app/client/src/widgets/JSONFormWidget/fields/BaseInputField.tsx @@ -23,6 +23,7 @@ import { INPUT_TEXT_MAX_CHAR_ERROR, } from "@appsmith/constants/messages"; import { + ActionUpdateDependency, BaseFieldComponentProps, FieldComponentBaseProps, FieldEventProps, @@ -298,6 +299,7 @@ function BaseInputField<TSchemaItem extends SchemaItem>({ event: { type: EventType.ON_TEXT_CHANGE, }, + updateDependencyType: ActionUpdateDependency.FORM_DATA, }); } }, diff --git a/app/client/src/widgets/JSONFormWidget/fields/CheckboxField.tsx b/app/client/src/widgets/JSONFormWidget/fields/CheckboxField.tsx index 65d3208912d3..9cd15e8352cd 100644 --- a/app/client/src/widgets/JSONFormWidget/fields/CheckboxField.tsx +++ b/app/client/src/widgets/JSONFormWidget/fields/CheckboxField.tsx @@ -9,6 +9,7 @@ import useEvents from "./useBlurAndFocusEvents"; import useRegisterFieldValidity from "./useRegisterFieldValidity"; import { AlignWidget } from "widgets/constants"; import { + ActionUpdateDependency, BaseFieldComponentProps, FieldComponentBaseProps, FieldEventProps, @@ -95,6 +96,7 @@ function CheckboxField({ event: { type: EventType.ON_CHECK_CHANGE, }, + updateDependencyType: ActionUpdateDependency.FORM_DATA, }); } }, diff --git a/app/client/src/widgets/JSONFormWidget/fields/DateField.tsx b/app/client/src/widgets/JSONFormWidget/fields/DateField.tsx index 7bd85f749a19..01dff62bf9c4 100644 --- a/app/client/src/widgets/JSONFormWidget/fields/DateField.tsx +++ b/app/client/src/widgets/JSONFormWidget/fields/DateField.tsx @@ -12,6 +12,7 @@ import { BaseFieldComponentProps, FieldEventProps, ComponentDefaultValuesFnProps, + ActionUpdateDependency, } from "../constants"; import { EventType } from "constants/AppsmithActionConstants/ActionConstants"; import { dateFormatOptions } from "../widget/propertyConfig/properties/date"; @@ -146,6 +147,7 @@ function DateField({ event: { type: EventType.ON_DATE_SELECTED, }, + updateDependencyType: ActionUpdateDependency.FORM_DATA, }); } }, diff --git a/app/client/src/widgets/JSONFormWidget/fields/MultiSelectField.tsx b/app/client/src/widgets/JSONFormWidget/fields/MultiSelectField.tsx index d94a05806bca..535e03156435 100644 --- a/app/client/src/widgets/JSONFormWidget/fields/MultiSelectField.tsx +++ b/app/client/src/widgets/JSONFormWidget/fields/MultiSelectField.tsx @@ -15,6 +15,7 @@ import useRegisterFieldValidity from "./useRegisterFieldValidity"; import useUpdateInternalMetaState from "./useUpdateInternalMetaState"; import { Layers } from "constants/Layers"; import { + ActionUpdateDependency, BaseFieldComponentProps, FieldComponentBaseProps, FieldEventProps, @@ -189,6 +190,7 @@ function MultiSelectField({ event: { type: EventType.ON_OPTION_CHANGE, }, + updateDependencyType: ActionUpdateDependency.FORM_DATA, }); } }, diff --git a/app/client/src/widgets/JSONFormWidget/fields/RadioGroupField.tsx b/app/client/src/widgets/JSONFormWidget/fields/RadioGroupField.tsx index 7cc5b799094f..eb8a540483c3 100644 --- a/app/client/src/widgets/JSONFormWidget/fields/RadioGroupField.tsx +++ b/app/client/src/widgets/JSONFormWidget/fields/RadioGroupField.tsx @@ -8,7 +8,11 @@ import Field from "widgets/JSONFormWidget/component/Field"; import RadioGroupComponent from "widgets/RadioGroupWidget/component"; import useRegisterFieldValidity from "./useRegisterFieldValidity"; import { RadioOption } from "widgets/RadioGroupWidget/constants"; -import { BaseFieldComponentProps, FieldComponentBaseProps } from "../constants"; +import { + ActionUpdateDependency, + BaseFieldComponentProps, + FieldComponentBaseProps, +} from "../constants"; import { EventType } from "constants/AppsmithActionConstants/ActionConstants"; import { Colors } from "constants/Colors"; import { BASE_LABEL_TEXT_SIZE } from "../component/FieldLabel"; @@ -79,6 +83,7 @@ function RadioGroupField({ event: { type: EventType.ON_OPTION_CHANGE, }, + updateDependencyType: ActionUpdateDependency.FORM_DATA, }); } }, diff --git a/app/client/src/widgets/JSONFormWidget/fields/SelectField.tsx b/app/client/src/widgets/JSONFormWidget/fields/SelectField.tsx index 6df1eddae794..2a49117740c6 100644 --- a/app/client/src/widgets/JSONFormWidget/fields/SelectField.tsx +++ b/app/client/src/widgets/JSONFormWidget/fields/SelectField.tsx @@ -7,7 +7,11 @@ import FormContext from "../FormContext"; import SelectComponent from "widgets/SelectWidget/component"; import useRegisterFieldValidity from "./useRegisterFieldValidity"; import useUpdateInternalMetaState from "./useUpdateInternalMetaState"; -import { BaseFieldComponentProps, FieldComponentBaseProps } from "../constants"; +import { + ActionUpdateDependency, + BaseFieldComponentProps, + FieldComponentBaseProps, +} from "../constants"; import { EventType } from "constants/AppsmithActionConstants/ActionConstants"; import { DropdownOption } from "widgets/SelectWidget/constants"; import { isPrimitive } from "../helper"; @@ -144,6 +148,7 @@ function SelectField({ event: { type: EventType.ON_OPTION_CHANGE, }, + updateDependencyType: ActionUpdateDependency.FORM_DATA, }); } }, diff --git a/app/client/src/widgets/JSONFormWidget/fields/SwitchField.tsx b/app/client/src/widgets/JSONFormWidget/fields/SwitchField.tsx index 1f8051d7b073..d5834370fb8b 100644 --- a/app/client/src/widgets/JSONFormWidget/fields/SwitchField.tsx +++ b/app/client/src/widgets/JSONFormWidget/fields/SwitchField.tsx @@ -7,6 +7,7 @@ import useEvents from "./useBlurAndFocusEvents"; import useRegisterFieldValidity from "./useRegisterFieldValidity"; import { AlignWidget, AlignWidgetTypes } from "widgets/constants"; import { + ActionUpdateDependency, BaseFieldComponentProps, FieldComponentBaseProps, FieldEventProps, @@ -83,6 +84,7 @@ function SwitchField({ event: { type: EventType.ON_SWITCH_CHANGE, }, + updateDependencyType: ActionUpdateDependency.FORM_DATA, }); } }, diff --git a/app/client/src/widgets/JSONFormWidget/widget/index.tsx b/app/client/src/widgets/JSONFormWidget/widget/index.tsx index 1b5797adfa79..61d879088eb3 100644 --- a/app/client/src/widgets/JSONFormWidget/widget/index.tsx +++ b/app/client/src/widgets/JSONFormWidget/widget/index.tsx @@ -14,6 +14,7 @@ import { ExecuteTriggerPayload, } from "constants/AppsmithActionConstants/ActionConstants"; import { + ActionUpdateDependency, FieldState, FieldThemeStylesheet, ROOT_SCHEMA_KEY, @@ -66,6 +67,10 @@ export type JSONFormWidgetState = { metaInternalFieldState: MetaInternalFieldState; }; +export type Action = ExecuteTriggerPayload & { + updateDependencyType?: ActionUpdateDependency; +}; + const SAVE_FIELD_STATE_DEBOUNCE_TIMEOUT = 400; class JSONFormWidget extends BaseWidget< @@ -74,6 +79,7 @@ class JSONFormWidget extends BaseWidget< > { debouncedParseAndSaveFieldState: any; isWidgetMounting: boolean; + actionQueue: Action[]; constructor(props: JSONFormWidgetProps) { super(props); @@ -84,6 +90,7 @@ class JSONFormWidget extends BaseWidget< ); this.isWidgetMounting = true; + this.actionQueue = []; } state = { @@ -223,6 +230,23 @@ class JSONFormWidget extends BaseWidget< } this.props.updateWidgetMetaProperty("formData", formData); + + if (this.actionQueue.length) { + this.actionQueue.forEach(({ updateDependencyType, ...actionPayload }) => { + if (updateDependencyType === ActionUpdateDependency.FORM_DATA) { + const payload = this.applyGlobalContextToAction(actionPayload, { + formData, + }); + + super.executeAction(payload); + } + }); + + this.actionQueue = this.actionQueue.filter( + ({ updateDependencyType }) => + updateDependencyType !== ActionUpdateDependency.FORM_DATA, + ); + } }; parseAndSaveFieldState = ( @@ -233,20 +257,8 @@ class JSONFormWidget extends BaseWidget< const fieldState = generateFieldState(schema, metaInternalFieldState); const action = klona(afterUpdateAction); - /** - * globalContext from the afterUpdateAction takes precedence as it may have a different - * fieldState value than the one returned from generateFieldState. - * */ - if (action) { - action.globalContext = merge( - { - fieldState, - }, - action?.globalContext, - ); - } - - const actionPayload = action && this.applyGlobalContextToAction(action); + const actionPayload = + action && this.applyGlobalContextToAction(action, { fieldState }); if (!equal(fieldState, this.props.fieldState)) { this.props.updateWidgetMetaProperty( @@ -283,7 +295,10 @@ class JSONFormWidget extends BaseWidget< }); }; - applyGlobalContextToAction = (actionPayload: ExecuteTriggerPayload) => { + applyGlobalContextToAction = ( + actionPayload: ExecuteTriggerPayload, + context: Record<string, unknown> = {}, + ) => { const payload = klona(actionPayload); const { globalContext } = payload; @@ -298,16 +313,23 @@ class JSONFormWidget extends BaseWidget< fieldState: this.props.fieldState, sourceData: this.props.sourceData, }, + context, globalContext, ); return payload; }; - onExecuteAction = (actionPayload: ExecuteTriggerPayload) => { - const payload = this.applyGlobalContextToAction(actionPayload); + onExecuteAction = (action: Action) => { + const { updateDependencyType, ...actionPayload } = action; - super.executeAction(payload); + if (!updateDependencyType) { + const payload = this.applyGlobalContextToAction(actionPayload); + + super.executeAction(payload); + } else { + this.actionQueue.push(action); + } }; onUpdateWidgetProperty = (propertyName: string, propertyValue: any) => {
261700076e4ce4c13e212ee84c7948cd638f697a
2024-04-04 15:10:38
Shrikant Sharat Kandula
chore: Add separate request/response views (#31781)
false
Add separate request/response views (#31781)
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..4b72c9bef844 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.ToResponse; 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(ToResponse.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(ToResponse.class) Boolean isValid; - @JsonProperty(access = JsonProperty.Access.READ_ONLY) - @JsonView(Views.Public.class) + @JsonView(ToResponse.class) Set<String> invalids; @Transient - @JsonProperty(access = JsonProperty.Access.READ_ONLY) - @JsonView(Views.Public.class) + @JsonView(ToResponse.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(ToResponse.class) Set<String> jsonPathKeys; @JsonView(Views.Internal.class) diff --git a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/views/FromRequest.java b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/views/FromRequest.java new file mode 100644 index 000000000000..a58b59469639 --- /dev/null +++ b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/views/FromRequest.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 FromRequest extends Views.Public {} diff --git a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/views/ToResponse.java b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/views/ToResponse.java new file mode 100644 index 000000000000..1d76fdc16613 --- /dev/null +++ b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/views/ToResponse.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 ToResponse 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..7c2b33deb4ec 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,8 @@ import com.appsmith.external.models.ActionDTO; import com.appsmith.external.models.ActionExecutionResult; +import com.appsmith.external.views.FromRequest; +import com.appsmith.external.views.ToResponse; import com.appsmith.external.views.Views; import com.appsmith.server.constants.FieldName; import com.appsmith.server.constants.Url; @@ -16,10 +18,9 @@ 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.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.codec.multipart.Part; @@ -42,47 +43,31 @@ @Slf4j @RequestMapping(Url.ACTION_URL) +@RequiredArgsConstructor public class ActionControllerCE { private final LayoutActionService layoutActionService; 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) { - this.layoutActionService = layoutActionService; - this.newActionService = newActionService; - this.refactoringService = refactoringService; - this.actionExecutionSolution = actionExecutionSolution; - this.observationRegistry = observationRegistry; - } - - @JsonView(Views.Public.class) + @JsonView(ToResponse.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(FromRequest.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) .map(created -> new ResponseDTO<>(HttpStatus.CREATED.value(), created, null)); } - @JsonView(Views.Public.class) + @JsonView(ToResponse.class) @PutMapping("/{defaultActionId}") public Mono<ResponseDTO<ActionDTO>> updateAction( @PathVariable String defaultActionId, - @Valid @RequestBody ActionDTO resource, + @Valid @RequestBody @JsonView(FromRequest.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 +163,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("")
235122e7e33a0aa55d04238eba74462c24ba29c3
2023-12-21 10:22:54
Ankita Kinger
chore: Refactoring API wiring for actions and JS actions to support private entity renaming on EE (#29763)
false
Refactoring API wiring for actions and JS actions to support private entity renaming on EE (#29763)
chore
diff --git a/app/client/src/api/ActionAPI.tsx b/app/client/src/api/ActionAPI.tsx index da36735c7dfc..ac4ca07dc8b1 100644 --- a/app/client/src/api/ActionAPI.tsx +++ b/app/client/src/api/ActionAPI.tsx @@ -10,6 +10,7 @@ import type { WidgetType } from "constants/WidgetConstants"; import { omit } from "lodash"; import type { OtlpSpan } from "UITelemetry/generateTraces"; import { wrapFnWithParentTraceContext } from "UITelemetry/generateTraces"; +import type { ActionContextTypeInterface } from "@appsmith/entities/Engine/actionHelpers"; export interface CreateActionRequest<T> extends APIRequest { datasourceId: string; @@ -141,11 +142,13 @@ export interface CopyActionRequest { } export interface UpdateActionNameRequest { - pageId: string; + pageId?: string; actionId: string; - layoutId: string; + layoutId?: string; newName: string; oldName: string; + moduleId?: string; + contextType?: ActionContextTypeInterface; } export interface FetchActionsPayload { diff --git a/app/client/src/ce/actions/helpers.ts b/app/client/src/ce/actions/helpers.ts index 3a2f800cdca2..ed6504125bb5 100644 --- a/app/client/src/ce/actions/helpers.ts +++ b/app/client/src/ce/actions/helpers.ts @@ -5,6 +5,8 @@ import { } from "actions/apiPaneActions"; import { createNewJSCollection } from "actions/jsPaneActions"; import { ACTION_PARENT_ENTITY_TYPE } from "@appsmith/entities/Engine/actionHelpers"; +import { saveActionName } from "actions/pluginActionActions"; +import { saveJSObjectName } from "actions/jsActionActions"; export const createNewQueryBasedOnParentEntity = ( entityId: string, @@ -37,3 +39,23 @@ export const createNewJSCollectionBasedOnParentEntity = ( ) => { return createNewJSCollection(entityId, from); }; + +export const saveActionNameBasedOnParentEntity = ( + id: string, + name: string, + // Used in EE + // eslint-disable-next-line @typescript-eslint/no-unused-vars + parentEntityType = ACTION_PARENT_ENTITY_TYPE.PAGE, +) => { + return saveActionName({ id, name }); +}; + +export const saveJSObjectNameBasedOnParentEntity = ( + id: string, + name: string, + // Used in EE + // eslint-disable-next-line @typescript-eslint/no-unused-vars + parentEntityType = ACTION_PARENT_ENTITY_TYPE.PAGE, +) => { + return saveJSObjectName({ id, name }); +}; diff --git a/app/client/src/ce/api/JSActionAPI.tsx b/app/client/src/ce/api/JSActionAPI.tsx index 85a46b774058..d4951c24edc5 100644 --- a/app/client/src/ce/api/JSActionAPI.tsx +++ b/app/client/src/ce/api/JSActionAPI.tsx @@ -5,7 +5,7 @@ import type { ApiResponse } from "api/ApiResponses"; import type { Variable, JSAction } from "entities/JSCollection"; import type { PluginType } from "entities/Action"; import type { FetchActionsPayload } from "api/ActionAPI"; -import type { ActionContextType } from "@appsmith/entities/DataTree/types"; +import type { ActionContextTypeInterface } from "@appsmith/entities/Engine/actionHelpers"; export type JSCollectionCreateUpdateResponse = ApiResponse & { id: string; @@ -17,11 +17,13 @@ export interface MoveJSCollectionRequest { name: string; } export interface UpdateJSObjectNameRequest { - pageId: string; + pageId?: string; actionCollectionId: string; - layoutId: string; + layoutId?: string; newName: string; oldName: string; + moduleId?: string; + contextType?: ActionContextTypeInterface; } export interface CreateJSCollectionRequest { @@ -35,7 +37,8 @@ export interface CreateJSCollectionRequest { applicationId: string; pluginType: PluginType; workflowId?: string; - contextType?: ActionContextType; + contextType?: ActionContextTypeInterface; + moduleId?: string; } export interface SetFunctionPropertyPayload { diff --git a/app/client/src/constants/routes/appRoutes.ts b/app/client/src/ce/constants/routes/appRoutes.ts similarity index 98% rename from app/client/src/constants/routes/appRoutes.ts rename to app/client/src/ce/constants/routes/appRoutes.ts index 36d74c39e8fe..855fe741a542 100644 --- a/app/client/src/constants/routes/appRoutes.ts +++ b/app/client/src/ce/constants/routes/appRoutes.ts @@ -152,3 +152,5 @@ export const PLACEHOLDER_PAGE_SLUG = "page"; export const SHOW_FILE_PICKER_KEY = "showPicker"; export const RESPONSE_STATUS = "response_status"; + +export const basePathForActiveAction = [BUILDER_PATH, BUILDER_PATH_DEPRECATED]; diff --git a/app/client/src/ce/entities/DataTree/types.ts b/app/client/src/ce/entities/DataTree/types.ts index f145075ee6d6..7dcd60f015e6 100644 --- a/app/client/src/ce/entities/DataTree/types.ts +++ b/app/client/src/ce/entities/DataTree/types.ts @@ -22,14 +22,6 @@ import type { ModuleInstance } from "@appsmith/constants/ModuleInstanceConstants export type ActionDispatcher = (...args: any[]) => ActionDescription; -export enum CreateNewActionKey { - PAGE = "pageId", -} - -export enum ActionContextType { - PAGE = "PAGE", -} - export const ENTITY_TYPE = { ACTION: "ACTION", WIDGET: "WIDGET", diff --git a/app/client/src/ce/entities/Engine/actionHelpers.ts b/app/client/src/ce/entities/Engine/actionHelpers.ts index d236a8141170..53b7cb248739 100644 --- a/app/client/src/ce/entities/Engine/actionHelpers.ts +++ b/app/client/src/ce/entities/Engine/actionHelpers.ts @@ -8,9 +8,17 @@ import { fetchDatasources } from "actions/datasourceActions"; import { fetchPageDSLs } from "actions/pageActions"; import { fetchPlugins } from "actions/pluginActions"; -export enum ACTION_PARENT_ENTITY_TYPE { - PAGE = "PAGE", -} +export const CreateNewActionKey = { + PAGE: "pageId", +} as const; + +export const ActionContextType = { + PAGE: "PAGE", +} as const; + +export const ACTION_PARENT_ENTITY_TYPE = { + PAGE: "PAGE", +} as const; export const getPageDependencyActions = ( currentWorkspaceId: string = "", diff --git a/app/client/src/ce/pages/Editor/Explorer/hooks.ts b/app/client/src/ce/pages/Editor/Explorer/hooks.ts index 689a70f8e130..05a2374b38bd 100644 --- a/app/client/src/ce/pages/Editor/Explorer/hooks.ts +++ b/app/client/src/ce/pages/Editor/Explorer/hooks.ts @@ -16,13 +16,12 @@ import type { ActionData } from "@appsmith/reducers/entityReducers/actionsReduce import { matchPath, useLocation } from "react-router"; import { API_EDITOR_ID_PATH, - BUILDER_PATH, - BUILDER_PATH_DEPRECATED, JS_COLLECTION_ID_PATH, QUERIES_EDITOR_ID_PATH, } from "constants/routes"; import { SAAS_EDITOR_API_ID_PATH } from "pages/Editor/SaaSEditor/constants"; import { TEMP_DATASOURCE_ID } from "constants/Datasource"; +import { basePathForActiveAction } from "@appsmith/constants/routes/appRoutes"; const findWidgets = (widgets: CanvasStructure, keyword: string) => { if (!widgets || !widgets.widgetName) return widgets; @@ -266,9 +265,10 @@ export const useEntityEditState = (entityId: string) => { export function useActiveAction() { const location = useLocation(); + const path = basePathForActiveAction; const baseMatch = matchPath<{ apiId: string }>(location.pathname, { - path: [BUILDER_PATH, BUILDER_PATH_DEPRECATED], + path, strict: false, exact: false, }); diff --git a/app/client/src/ce/reducers/entityReducers/jsActionsReducer.tsx b/app/client/src/ce/reducers/entityReducers/jsActionsReducer.tsx index acf38d450c7b..27df84526a49 100644 --- a/app/client/src/ce/reducers/entityReducers/jsActionsReducer.tsx +++ b/app/client/src/ce/reducers/entityReducers/jsActionsReducer.tsx @@ -91,7 +91,14 @@ export const handlers = { return { ...jsCollection, isLoading: false, - config: action.payload.data, + config: action.payload.data.isPublic + ? { + ...action.payload.data, + isMainJSCollection: true, + displayName: "Main", + hideContextMenu: true, + } + : action.payload.data, activeJSActionId: findIndex(jsCollection.config.actions, { id: jsCollection.activeJSActionId, diff --git a/app/client/src/constants/routes/index.ts b/app/client/src/constants/routes/index.ts index 0728b7b067fd..bd7bef50303d 100644 --- a/app/client/src/constants/routes/index.ts +++ b/app/client/src/constants/routes/index.ts @@ -1,2 +1,2 @@ export * from "./baseRoutes"; -export * from "./appRoutes"; +export * from "@appsmith/constants/routes/appRoutes"; diff --git a/app/client/src/ee/constants/routes/appRoutes.ts b/app/client/src/ee/constants/routes/appRoutes.ts new file mode 100644 index 000000000000..6fc5b6ffb8d1 --- /dev/null +++ b/app/client/src/ee/constants/routes/appRoutes.ts @@ -0,0 +1 @@ +export * from "ce/constants/routes/appRoutes"; diff --git a/app/client/src/ee/entities/Engine/actionHelpers.ts b/app/client/src/ee/entities/Engine/actionHelpers.ts index 580a3b24fa85..d4a115f6b37b 100644 --- a/app/client/src/ee/entities/Engine/actionHelpers.ts +++ b/app/client/src/ee/entities/Engine/actionHelpers.ts @@ -1,6 +1,16 @@ export * from "ce/entities/Engine/actionHelpers"; +import type { + ActionContextType, + CreateNewActionKey, +} from "ce/entities/Engine/actionHelpers"; import { ACTION_PARENT_ENTITY_TYPE as CE_ACTION_PARENT_ENTITY_TYPE } from "ce/entities/Engine/actionHelpers"; +export type CreateNewActionKeyInterface = + (typeof CreateNewActionKey)[keyof typeof CreateNewActionKey]; + +export type ActionContextTypeInterface = + (typeof ActionContextType)[keyof typeof ActionContextType]; + export const ACTION_PARENT_ENTITY_TYPE = { ...CE_ACTION_PARENT_ENTITY_TYPE, }; diff --git a/app/client/src/entities/Action/index.ts b/app/client/src/entities/Action/index.ts index a0dd33983cf9..de1fbf709407 100644 --- a/app/client/src/entities/Action/index.ts +++ b/app/client/src/entities/Action/index.ts @@ -5,7 +5,7 @@ import type { LayoutOnLoadActionErrors } from "constants/AppsmithActionConstants import type { Plugin } from "api/PluginApi"; import type { AutoGeneratedHeader } from "pages/Editor/APIEditor/helpers"; import type { EventLocation } from "@appsmith/utils/analyticsUtilTypes"; -import type { ActionContextType } from "@appsmith/entities/DataTree/types"; +import type { ActionContextTypeInterface } from "@appsmith/entities/Engine/actionHelpers"; export enum PluginType { API = "API", @@ -163,7 +163,7 @@ export interface BaseAction { moduleId?: string; moduleInstanceId?: string; workflowId?: string; - contextType?: ActionContextType; + contextType?: ActionContextTypeInterface; // This is used to identify the main js collection of a workflow // added here to avoid ts error in entitiesSelector file, in practice // will always be undefined for non js actions diff --git a/app/client/src/entities/JSCollection/index.ts b/app/client/src/entities/JSCollection/index.ts index 11e2089096ea..93cafe915a4e 100644 --- a/app/client/src/entities/JSCollection/index.ts +++ b/app/client/src/entities/JSCollection/index.ts @@ -1,7 +1,7 @@ import type { BaseAction } from "../Action"; import type { PluginType } from "entities/Action"; import type { LayoutOnLoadActionErrors } from "constants/AppsmithActionConstants/ActionConstants"; -import type { ActionContextType } from "@appsmith/entities/DataTree/types"; +import type { ActionContextTypeInterface } from "@appsmith/entities/Engine/actionHelpers"; export interface Variable { name: string; @@ -24,11 +24,15 @@ export interface JSCollection { moduleId?: string; moduleInstanceId?: string; workflowId?: string; - contextType?: ActionContextType; + contextType?: ActionContextTypeInterface; // This is used to identify the main js collection of a workflow // main js collection is the entrypoint for a workflow // cannot be deleted or renamed isMainJSCollection?: boolean; + displayName?: string; + hideEditIconOnEditor?: boolean; + hideContextMenu?: boolean; + hideContextMenuOnEditor?: boolean; } export interface JSActionConfig { diff --git a/app/client/src/pages/Editor/Explorer/Actions/ActionEntity.tsx b/app/client/src/pages/Editor/Explorer/Actions/ActionEntity.tsx index 12b67f85f074..f869d2074c38 100644 --- a/app/client/src/pages/Editor/Explorer/Actions/ActionEntity.tsx +++ b/app/client/src/pages/Editor/Explorer/Actions/ActionEntity.tsx @@ -3,7 +3,6 @@ import { useSelector } from "react-redux"; import Entity, { EntityClassNames } from "../Entity"; import ActionEntityContextMenu from "./ActionEntityContextMenu"; import history, { NavigationMethod } from "utils/history"; -import { saveActionName } from "actions/pluginActionActions"; import PerformanceTracker, { PerformanceTransactionName, } from "utils/PerformanceTracker"; @@ -25,9 +24,15 @@ import { } from "@appsmith/utils/BusinessFeatures/permissionPageHelpers"; import { useFeatureFlag } from "utils/hooks/useFeatureFlag"; import { FEATURE_FLAG } from "@appsmith/entities/FeatureFlag"; +import { saveActionNameBasedOnParentEntity } from "@appsmith/actions/helpers"; +import type { ActionParentEntityTypeInterface } from "@appsmith/entities/Engine/actionHelpers"; -const getUpdateActionNameReduxAction = (id: string, name: string) => { - return saveActionName({ id, name }); +const getUpdateActionNameReduxAction = ( + id: string, + name: string, + parentEntityType: ActionParentEntityTypeInterface, +) => { + return saveActionNameBasedOnParentEntity(id, name, parentEntityType); }; interface ExplorerActionEntityProps { @@ -37,6 +42,7 @@ interface ExplorerActionEntityProps { type: PluginType; isActive: boolean; parentEntityId: string; + parentEntityType: ActionParentEntityTypeInterface; } export const ExplorerActionEntity = memo((props: ExplorerActionEntityProps) => { @@ -113,7 +119,9 @@ export const ExplorerActionEntity = memo((props: ExplorerActionEntityProps) => { name={action.name} searchKeyword={props.searchKeyword} step={props.step} - updateEntityName={getUpdateActionNameReduxAction} + updateEntityName={(id, name) => + getUpdateActionNameReduxAction(id, name, props.parentEntityType) + } /> ); }); diff --git a/app/client/src/pages/Editor/Explorer/Files/FilesContextProvider.tsx b/app/client/src/pages/Editor/Explorer/Files/FilesContextProvider.tsx index 89ed194eb86b..60c23fc3aef8 100644 --- a/app/client/src/pages/Editor/Explorer/Files/FilesContextProvider.tsx +++ b/app/client/src/pages/Editor/Explorer/Files/FilesContextProvider.tsx @@ -1,6 +1,5 @@ import React, { createContext, useMemo } from "react"; import type { ActionParentEntityTypeInterface } from "@appsmith/entities/Engine/actionHelpers"; -import { ACTION_PARENT_ENTITY_TYPE } from "@appsmith/entities/Engine/actionHelpers"; export enum ActionEntityContextMenuItemsEnum { EDIT_NAME = "Edit Name", @@ -10,9 +9,18 @@ export enum ActionEntityContextMenuItemsEnum { DELETE = "Delete", } +export const defaultMenuItems = [ + ActionEntityContextMenuItemsEnum.EDIT_NAME, + ActionEntityContextMenuItemsEnum.DELETE, + ActionEntityContextMenuItemsEnum.SHOW_BINDING, + ActionEntityContextMenuItemsEnum.COPY, + ActionEntityContextMenuItemsEnum.MOVE, +]; + interface FilesContextContextProps { canCreateActions: boolean; editorId: string; // applicationId, workflowId or packageId + menuItems?: ActionEntityContextMenuItemsEnum[]; parentEntityId: string; // page, workflow or module parentEntityType: ActionParentEntityTypeInterface; showModules?: boolean; @@ -36,33 +44,19 @@ export const FilesContextProvider = ({ canCreateActions, children, editorId, + menuItems, parentEntityId, parentEntityType, selectFilesForExplorer, showModules, }: FilesContextProviderProps) => { - const menuItems = useMemo(() => { - const items = [ - ActionEntityContextMenuItemsEnum.EDIT_NAME, - ActionEntityContextMenuItemsEnum.DELETE, - ]; - if (parentEntityType === ACTION_PARENT_ENTITY_TYPE.PAGE) { - items.push( - ActionEntityContextMenuItemsEnum.SHOW_BINDING, - ActionEntityContextMenuItemsEnum.COPY, - ActionEntityContextMenuItemsEnum.MOVE, - ); - } - return items; - }, [parentEntityType]); - const value = useMemo(() => { return { canCreateActions, editorId, parentEntityId, parentEntityType, - menuItems, + menuItems: menuItems || defaultMenuItems, selectFilesForExplorer, showModules, }; @@ -70,6 +64,7 @@ export const FilesContextProvider = ({ canCreateActions, parentEntityId, parentEntityType, + menuItems, showModules, selectFilesForExplorer, editorId, diff --git a/app/client/src/pages/Editor/Explorer/Files/index.tsx b/app/client/src/pages/Editor/Explorer/Files/index.tsx index bcaea6af0e22..fc2f8334b07a 100644 --- a/app/client/src/pages/Editor/Explorer/Files/index.tsx +++ b/app/client/src/pages/Editor/Explorer/Files/index.tsx @@ -117,6 +117,7 @@ function Files() { isActive={entity.id === activeActionId} key={entity.id} parentEntityId={parentEntityId} + parentEntityType={parentEntityType} searchKeyword={""} step={2} type={type} @@ -129,6 +130,7 @@ function Files() { isActive={entity.id === activeActionId} key={entity.id} parentEntityId={parentEntityId} + parentEntityType={parentEntityType} searchKeyword={""} step={2} type={type} diff --git a/app/client/src/pages/Editor/Explorer/JSActions/JSActionContextMenu.tsx b/app/client/src/pages/Editor/Explorer/JSActions/JSActionContextMenu.tsx index 2d0b258a1710..d531997f043c 100644 --- a/app/client/src/pages/Editor/Explorer/JSActions/JSActionContextMenu.tsx +++ b/app/client/src/pages/Editor/Explorer/JSActions/JSActionContextMenu.tsx @@ -35,7 +35,7 @@ interface EntityContextMenuProps { className?: string; canManage: boolean; canDelete: boolean; - showMenuItems: boolean; + hideMenuItems: boolean; } export function JSCollectionEntityContextMenu(props: EntityContextMenuProps) { // Import the context @@ -164,7 +164,7 @@ export function JSCollectionEntityContextMenu(props: EntityContextMenuProps) { }, ].filter(Boolean); - return !props.showMenuItems && optionsTree.length > 0 ? ( + return !props.hideMenuItems && optionsTree.length > 0 ? ( <ContextMenu className={props.className} optionTree={optionsTree as TreeDropdownOption[]} diff --git a/app/client/src/pages/Editor/Explorer/JSActions/JSActionEntity.tsx b/app/client/src/pages/Editor/Explorer/JSActions/JSActionEntity.tsx index d0f786f1da46..5c6db6ac5dbb 100644 --- a/app/client/src/pages/Editor/Explorer/JSActions/JSActionEntity.tsx +++ b/app/client/src/pages/Editor/Explorer/JSActions/JSActionEntity.tsx @@ -2,7 +2,6 @@ import React, { memo, useCallback } from "react"; import Entity, { EntityClassNames } from "../Entity"; import history, { NavigationMethod } from "utils/history"; import JSCollectionEntityContextMenu from "./JSActionContextMenu"; -import { saveJSObjectName } from "actions/jsActionActions"; import { useSelector } from "react-redux"; import { getJSCollection } from "@appsmith/selectors/entitiesSelector"; import type { AppState } from "@appsmith/reducers"; @@ -18,7 +17,8 @@ import { } from "@appsmith/utils/BusinessFeatures/permissionPageHelpers"; import { useFeatureFlag } from "utils/hooks/useFeatureFlag"; import { FEATURE_FLAG } from "@appsmith/entities/FeatureFlag"; -import { Icon } from "design-system"; +import { saveJSObjectNameBasedOnParentEntity } from "@appsmith/actions/helpers"; +import type { ActionParentEntityTypeInterface } from "@appsmith/entities/Engine/actionHelpers"; interface ExplorerJSCollectionEntityProps { step: number; @@ -27,10 +27,15 @@ interface ExplorerJSCollectionEntityProps { isActive: boolean; type: PluginType; parentEntityId: string; + parentEntityType: ActionParentEntityTypeInterface; } -const getUpdateJSObjectName = (id: string, name: string) => { - return saveJSObjectName({ id, name }); +const getUpdateJSObjectName = ( + id: string, + name: string, + parentEntityType: ActionParentEntityTypeInterface, +) => { + return saveJSObjectNameBasedOnParentEntity(id, name, parentEntityType); }; export const ExplorerJSCollectionEntity = memo( @@ -39,7 +44,7 @@ export const ExplorerJSCollectionEntity = memo( getJSCollection(state, props.id), ) as JSCollection; const location = useLocation(); - const { parentEntityId } = props; + const { parentEntityId, parentEntityType } = props; const navigateToUrl = jsCollectionIdURL({ parentEntityId, collectionId: jsAction.id, @@ -78,27 +83,27 @@ export const ExplorerJSCollectionEntity = memo( canDelete={canDeleteJSAction} canManage={canManageJSAction} className={EntityClassNames.CONTEXT_MENU} + hideMenuItems={jsAction?.hideContextMenu || false} id={jsAction.id} name={jsAction.name} - showMenuItems={jsAction?.isMainJSCollection || false} /> ); return ( <Entity action={navigateToJSCollection} active={props.isActive} - alwaysShowRightIcon={!!jsAction.isMainJSCollection} canEditEntityName={canManageJSAction} className="t--jsaction" contextMenu={contextMenu} entityId={jsAction.id} icon={JsFileIconV2(16, 16)} key={jsAction.id} - name={jsAction.name} - rightIcon={!!jsAction.isMainJSCollection && <Icon name="pin-3" />} + name={jsAction?.displayName || jsAction.name} searchKeyword={props.searchKeyword} step={props.step} - updateEntityName={getUpdateJSObjectName} + updateEntityName={(id, name) => + getUpdateJSObjectName(id, name, parentEntityType) + } /> ); }, diff --git a/app/client/src/pages/Editor/IDE/PagesPane/JS_Section.tsx b/app/client/src/pages/Editor/IDE/PagesPane/JS_Section.tsx index ea9cc8486e2e..96fa5d4f1219 100644 --- a/app/client/src/pages/Editor/IDE/PagesPane/JS_Section.tsx +++ b/app/client/src/pages/Editor/IDE/PagesPane/JS_Section.tsx @@ -86,6 +86,7 @@ const JSSection = () => { isActive={JSobject.id === activeActionId} key={JSobject.id} parentEntityId={pageId} + parentEntityType={ACTION_PARENT_ENTITY_TYPE.PAGE} searchKeyword={""} step={2} type={JSobject.type as PluginType} diff --git a/app/client/src/pages/Editor/IDE/PagesPane/ListQuery.tsx b/app/client/src/pages/Editor/IDE/PagesPane/ListQuery.tsx index 8ccc0104553d..e36f2556ceb9 100644 --- a/app/client/src/pages/Editor/IDE/PagesPane/ListQuery.tsx +++ b/app/client/src/pages/Editor/IDE/PagesPane/ListQuery.tsx @@ -80,6 +80,7 @@ const ListQuery = () => { isActive={file.id === activeActionId} key={file.id} parentEntityId={pageId} + parentEntityType={ACTION_PARENT_ENTITY_TYPE.PAGE} searchKeyword={""} step={1} type={file.type} diff --git a/app/client/src/pages/Editor/JSEditor/Form.tsx b/app/client/src/pages/Editor/JSEditor/Form.tsx index 631166c0eeb2..8135f62b78af 100644 --- a/app/client/src/pages/Editor/JSEditor/Form.tsx +++ b/app/client/src/pages/Editor/JSEditor/Form.tsx @@ -321,13 +321,14 @@ function JSEditorForm({ <NameWrapper className="t--nameOfJSObject"> <JSObjectNameEditor disabled={ - !isChangePermitted || !!currentJSCollection.isMainJSCollection + !isChangePermitted || + !!currentJSCollection.hideEditIconOnEditor } saveJSObjectName={saveJSObjectName} /> </NameWrapper> <ActionButtons className="t--formActionButtons"> - {!currentJSCollection.isMainJSCollection && contextMenu} + {!currentJSCollection.hideContextMenuOnEditor && contextMenu} <JSFunctionRun disabled={disableRunFunctionality || !isExecutePermitted} isLoading={isExecutingCurrentJSAction} diff --git a/app/client/src/pages/Editor/JSEditor/JSObjectNameEditor.tsx b/app/client/src/pages/Editor/JSEditor/JSObjectNameEditor.tsx index d9d0e989c379..7867b911e75f 100644 --- a/app/client/src/pages/Editor/JSEditor/JSObjectNameEditor.tsx +++ b/app/client/src/pages/Editor/JSEditor/JSObjectNameEditor.tsx @@ -26,7 +26,7 @@ import NameEditorComponent, { import { getSavingStatusForJSObjectName } from "selectors/actionSelectors"; import type { ReduxAction } from "@appsmith/constants/ReduxActionConstants"; -interface SaveActionNameParams { +export interface SaveActionNameParams { id: string; name: string; } diff --git a/app/client/src/utils/AppsmithUtils.tsx b/app/client/src/utils/AppsmithUtils.tsx index 889271864e93..9e3d2cd2c829 100644 --- a/app/client/src/utils/AppsmithUtils.tsx +++ b/app/client/src/utils/AppsmithUtils.tsx @@ -11,7 +11,8 @@ import { osName } from "react-device-detect"; import type { ActionDataState } from "@appsmith/reducers/entityReducers/actionsReducer"; import type { JSCollectionData } from "@appsmith/reducers/entityReducers/jsActionsReducer"; import AnalyticsUtil from "./AnalyticsUtil"; -import { CreateNewActionKey } from "@appsmith/entities/DataTree/types"; +import type { CreateNewActionKeyInterface } from "@appsmith/entities/Engine/actionHelpers"; +import { CreateNewActionKey } from "@appsmith/entities/Engine/actionHelpers"; export const initializeAnalyticsAndTrackers = async () => { const appsmithConfigs = getAppsmithConfigs(); @@ -198,10 +199,10 @@ export const getDuplicateName = (prefix: string, existingNames: string[]) => { export const createNewApiName = ( actions: ActionDataState, entityId: string, - key: CreateNewActionKey = CreateNewActionKey.PAGE, + key: CreateNewActionKeyInterface = CreateNewActionKey.PAGE, ) => { const pageApiNames = actions - .filter((a) => a.config[key] === entityId) + .filter((a: any) => a.config[key] === entityId) .map((a) => a.config.name); return getNextEntityName("Api", pageApiNames); }; @@ -209,10 +210,10 @@ export const createNewApiName = ( export const createNewJSFunctionName = ( jsActions: JSCollectionData[], entityId: string, - key: CreateNewActionKey = CreateNewActionKey.PAGE, + key: CreateNewActionKeyInterface = CreateNewActionKey.PAGE, ) => { const pageJsFunctionNames = jsActions - .filter((a) => a.config[key] === entityId) + .filter((a: any) => a.config[key] === entityId) .map((a) => a.config.name); return getNextEntityName("JSObject", pageJsFunctionNames); }; @@ -229,10 +230,10 @@ export const createNewQueryName = ( queries: ActionDataState, entityId: string, prefix = "Query", - key: CreateNewActionKey = CreateNewActionKey.PAGE, + key: CreateNewActionKeyInterface = CreateNewActionKey.PAGE, ) => { const pageApiNames = queries - .filter((a) => a.config[key] === entityId) + .filter((a: any) => a.config[key] === entityId) .map((a) => a.config.name); return getNextEntityName(prefix, pageApiNames);
3c8c940caf75140a866be1897041a35aa861ec78
2023-05-04 11:52:57
Shrikant Sharat Kandula
ci: Remove unused java setup step (#22978)
false
Remove unused java setup step (#22978)
ci
diff --git a/.github/workflows/build-docker-image.yml b/.github/workflows/build-docker-image.yml index db2fdae24cd6..b10fc704b046 100644 --- a/.github/workflows/build-docker-image.yml +++ b/.github/workflows/build-docker-image.yml @@ -21,7 +21,7 @@ jobs: defaults: run: shell: bash - + steps: # Check out merge commit - name: Fork based /ok-to-test checkout @@ -30,21 +30,13 @@ jobs: with: fetch-depth: 0 ref: "refs/pull/${{ inputs.pr }}/merge" - + # Checkout the code in the current branch in case the workflow is called because of a branch push event - name: Checkout the head commit of the branch if: inputs.pr == 0 uses: actions/checkout@v3 with: fetch-depth: 0 - - # Setup Java - - name: Set up JDK 17 - if: steps.run_result.outputs.run_result != 'success' - uses: actions/setup-java@v3 - with: - distribution: 'temurin' - java-version: '17' - name: Download the client build artifact if: steps.run_result.outputs.run_result != 'success' @@ -80,13 +72,13 @@ jobs: working-directory: "." run: | docker build -t cicontainer . - + # Saving the docker image to tar file - name: Save Docker image to tar file run: | docker save cicontainer -o cicontainer.tar gzip cicontainer.tar - + # Uploading the artifact to use it in other subsequent runners - name: Upload Docker image to artifacts uses: actions/upload-artifact@v3 @@ -96,4 +88,3 @@ jobs: - name: Save the status of the run run: echo "run_result=success" >> $GITHUB_OUTPUT > ~/run_result - \ No newline at end of file
17dbe63ed3113babf7a6da71e26e351c792b1883
2022-12-15 19:45:46
akash-codemonk
feat: [Context Switching] maintain focus of code editor fields (#18240)
false
[Context Switching] maintain focus of code editor fields (#18240)
feat
diff --git a/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/IDE/Canvas_Context_Property_Pane_spec.js b/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/IDE/Canvas_Context_Property_Pane_spec.js index e909284450a3..5bcf3d1c01ea 100644 --- a/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/IDE/Canvas_Context_Property_Pane_spec.js +++ b/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/IDE/Canvas_Context_Property_Pane_spec.js @@ -31,7 +31,7 @@ describe("Canvas context Property Pane", function() { cy.focusCodeInput(propertyControlSelector); }, () => { - cy.assertSoftFocusOnPropertyPane(propertyControlSelector); + cy.assertCursorOnCodeInput(propertyControlSelector); }, "Button1", ); @@ -160,7 +160,7 @@ describe("Canvas context Property Pane", function() { cy.focusCodeInput(propertyControlSelector); }, () => { - cy.assertSoftFocusOnPropertyPane(propertyControlSelector); + cy.assertCursorOnCodeInput(propertyControlSelector); }, "Table1", ); @@ -241,7 +241,7 @@ describe("Canvas context Property Pane", function() { cy.focusCodeInput(propertyControlSelector); }, () => { - cy.assertSoftFocusOnPropertyPane(propertyControlSelector); + cy.assertCursorOnCodeInput(propertyControlSelector); }, "Table1", ); diff --git a/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/IDE/MaintainContext&Focus_spec.js b/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/IDE/MaintainContext&Focus_spec.js index f23cd92c6c96..c9529e8d7a6b 100644 --- a/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/IDE/MaintainContext&Focus_spec.js +++ b/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/IDE/MaintainContext&Focus_spec.js @@ -1,5 +1,6 @@ import reconnectDatasourceModal from "../../../../locators/ReconnectLocators"; const apiwidget = require("../../../../locators/apiWidgetslocator.json"); +const queryLocators = require("../../../../locators/QueryEditor.json"); import { ObjectsRegistry } from "../../../../support/Objects/Registry"; const homePage = ObjectsRegistry.HomePage; @@ -88,7 +89,7 @@ describe("MaintainContext&Focus", function() { cy.get(`.t--entity-name:contains("Page1")`).click(); cy.get(".t--widget-name").should("have.text", "Text1"); - cy.assertSoftFocusOnPropertyPane(".t--property-control-text", { + cy.assertCursorOnCodeInput(".t--property-control-text", { ch: 2, line: 0, }); @@ -195,4 +196,18 @@ describe("MaintainContext&Focus", function() { // Validate if section with index 1 is expanded dataSources.AssertSectionCollapseState(1, false); }); + + it("10. Maintain focus of form control inputs", () => { + ee.SelectEntityByName("SQL_Query"); + dataSources.ToggleUsePreparedStatement(false); + cy.SearchEntityandOpen("S3_Query"); + cy.get(queryLocators.querySettingsTab).click(); + cy.setQueryTimeout(10000); + + cy.SearchEntityandOpen("SQL_Query"); + cy.get(".t--form-control-SWITCH input").should("be.focused"); + cy.SearchEntityandOpen("S3_Query"); + cy.get(queryLocators.querySettingsTab).click(); + cy.xpath(queryLocators.queryTimeout).should("be.focused"); + }); }); diff --git a/app/client/cypress/support/widgetCommands.js b/app/client/cypress/support/widgetCommands.js index 109306c40830..0379a64c1199 100644 --- a/app/client/cypress/support/widgetCommands.js +++ b/app/client/cypress/support/widgetCommands.js @@ -617,7 +617,7 @@ Cypress.Commands.add( ); Cypress.Commands.add( - "assertSoftFocusOnPropertyPane", + "assertSoftFocusOnCodeInput", ($selector, cursor = { ch: 0, line: 0 }) => { cy.EnableAllCodeEditors(); cy.get($selector) diff --git a/app/client/src/actions/editorContextActions.ts b/app/client/src/actions/editorContextActions.ts index 8ecbc5e7e3f5..6574b49c484f 100644 --- a/app/client/src/actions/editorContextActions.ts +++ b/app/client/src/actions/editorContextActions.ts @@ -5,9 +5,9 @@ import { PropertyPanelContext, } from "reducers/uiReducers/editorContextReducer"; -export const setFocusableCodeEditorField = (path: string | undefined) => { +export const setFocusableInputField = (path: string | undefined) => { return { - type: ReduxActionTypes.SET_FOCUSABLE_CODE_EDITOR_FIELD, + type: ReduxActionTypes.SET_FOCUSABLE_INPUT_FIELD, payload: { path }, }; }; diff --git a/app/client/src/actions/propertyPaneActions.ts b/app/client/src/actions/propertyPaneActions.ts index 505ffc607045..8f3bec9da9f2 100644 --- a/app/client/src/actions/propertyPaneActions.ts +++ b/app/client/src/actions/propertyPaneActions.ts @@ -60,13 +60,6 @@ export const setSelectedPropertyTabIndex = (selectedIndex: number) => { }; }; -export const setFocusablePropertyPaneField = (path?: string) => { - return { - type: ReduxActionTypes.SET_FOCUSABLE_PROPERTY_FIELD, - payload: { path }, - }; -}; - export const setSelectedPropertyPanel = ( path: string | undefined, index: number, diff --git a/app/client/src/ce/constants/ReduxActionConstants.tsx b/app/client/src/ce/constants/ReduxActionConstants.tsx index d476f211771f..28a9f60c626b 100644 --- a/app/client/src/ce/constants/ReduxActionConstants.tsx +++ b/app/client/src/ce/constants/ReduxActionConstants.tsx @@ -687,10 +687,6 @@ export const ReduxActionTypes = { FETCH_CURRENT_TENANT_CONFIG: "FETCH_CURRENT_TENANT_CONFIG", FETCH_CURRENT_TENANT_CONFIG_SUCCESS: "FETCH_CURRENT_TENANT_CONFIG_SUCCESS", SET_FOCUS_HISTORY: "SET_FOCUS_HISTORY", - SET_FOCUSABLE_CODE_EDITOR_FIELD: "SET_FOCUSABLE_CODE_EDITOR_FIELD", - GENERATE_KEY_AND_SET_FOCUSABLE_CODE_EDITOR_FIELD: - "GENERATE_KEY_AND_SET_FOCUSABLE_CODE_EDITOR_FIELD", - SET_FOCUSABLE_PROPERTY_FIELD: "SET_FOCUSABLE_PROPERTY_FIELD", ROUTE_CHANGED: "ROUTE_CHANGED", PAGE_CHANGED: "PAGE_CHANGED", SET_API_PANE_CONFIG_SELECTED_TAB: "SET_API_PANE_CONFIG_SELECTED_TAB", @@ -698,6 +694,7 @@ export const ReduxActionTypes = { SET_API_PANE_RESPONSE_PANE_HEIGHT: "SET_API_PANE_RESPONSE_PANE_HEIGHT", SET_API_RIGHT_PANE_SELECTED_TAB: "SET_API_RIGHT_PANE_SELECTED_TAB", SET_EDITOR_FIELD_FOCUS: "SET_EDITOR_FIELD_FOCUS", + SET_FOCUSABLE_INPUT_FIELD: "SET_FOCUSABLE_INPUT_FIELD", SET_CODE_EDITOR_CURSOR: "SET_CODE_EDITOR_CURSOR", SET_CODE_EDITOR_CURSOR_HISTORY: "SET_CODE_EDITOR_CURSOR_HISTORY", SET_EVAL_POPUP_STATE: "SET_EVAL_POPUP_STATE", diff --git a/app/client/src/components/editorComponents/CodeEditor/index.tsx b/app/client/src/components/editorComponents/CodeEditor/index.tsx index f092fbd11818..3ee64784be76 100644 --- a/app/client/src/components/editorComponents/CodeEditor/index.tsx +++ b/app/client/src/components/editorComponents/CodeEditor/index.tsx @@ -105,7 +105,7 @@ import { interactionAnalyticsEvent } from "utils/AppsmithUtils"; import { AdditionalDynamicDataTree } from "utils/autocomplete/customTreeTypeDefCreator"; import { getCodeEditorLastCursorPosition, - getIsCodeEditorFocused, + getIsInputFieldFocused, } from "selectors/editorContextSelectors"; import { CodeEditorFocusState, @@ -1153,7 +1153,7 @@ const mapStateToProps = (state: AppState, props: EditorProps) => ({ pluginIdToImageLocation: getPluginIdToImageLocation(state), recentEntities: getRecentEntityIds(state), lintErrors: getEntityLintErrors(state, props.dataTreePath), - editorIsFocused: getIsCodeEditorFocused(state, getEditorIdentifier(props)), + editorIsFocused: getIsInputFieldFocused(state, getEditorIdentifier(props)), editorLastCursorPosition: getCodeEditorLastCursorPosition( state, getEditorIdentifier(props), diff --git a/app/client/src/navigation/FocusElements.ts b/app/client/src/navigation/FocusElements.ts index 6fbd7ca80330..9faf375c8e59 100644 --- a/app/client/src/navigation/FocusElements.ts +++ b/app/client/src/navigation/FocusElements.ts @@ -19,7 +19,7 @@ import { getCodeEditorHistory, getExplorerSwitchIndex, getPropertyPanelState, - getFocusableCodeEditorField, + getFocusableInputField, getSelectedCanvasDebuggerTab, getWidgetSelectedPropertyTabIndex, } from "selectors/editorContextSelectors"; @@ -31,7 +31,7 @@ import { setPanelPropertiesState, setWidgetSelectedPropertyTabIndex, } from "actions/editorContextActions"; -import { setFocusableCodeEditorField } from "actions/editorContextActions"; +import { setFocusableInputField } from "actions/editorContextActions"; import { getAllDatasourceCollapsibleState, getSelectedWidgets, @@ -75,17 +75,13 @@ import { setPropertyPaneWidthAction, setSelectedPropertyPanels, } from "actions/propertyPaneActions"; -import { - setAllPropertySectionState, - setFocusablePropertyPaneField, -} from "actions/propertyPaneActions"; +import { setAllPropertySectionState } from "actions/propertyPaneActions"; import { setCanvasDebuggerSelectedTab } from "actions/debuggerActions"; import { setAllDatasourceCollapsible, setDatasourceViewMode, } from "actions/datasourceActions"; import { PluginPackageName } from "entities/Action"; -import { getFocusablePropertyPaneField } from "selectors/propertyPaneSelectors"; export enum FocusElement { ApiPaneConfigTabs = "ApiPaneConfigTabs", @@ -105,8 +101,6 @@ export enum FocusElement { JSPaneConfigTabs = "JSPaneConfigTabs", JSPaneResponseTabs = "JSPaneResponseTabs", JSPaneResponseHeight = "JSPaneResponseHeight", - CodeEditor = "CodeEditor", - PropertyField = "PropertyField", PropertySections = "PropertySections", PropertyTabs = "PropertyTabs", PropertyPanelContext = "PropertyPanelContext", @@ -114,6 +108,7 @@ export enum FocusElement { SelectedPropertyPanel = "SelectedPropertyPanel", SelectedWidgets = "SelectedWidgets", SubEntityCollapsibleState = "SubEntityCollapsibleState", + InputField = "InputField", } type Config = { @@ -211,9 +206,9 @@ export const FocusElementsConfig: Record<FocusEntity, Config[]> = { ], [FocusEntity.JS_OBJECT]: [ { - name: FocusElement.CodeEditor, - selector: getFocusableCodeEditorField, - setter: setFocusableCodeEditorField, + name: FocusElement.InputField, + selector: getFocusableInputField, + setter: setFocusableInputField, }, { name: FocusElement.JSPaneConfigTabs, @@ -236,9 +231,9 @@ export const FocusElementsConfig: Record<FocusEntity, Config[]> = { ], [FocusEntity.QUERY]: [ { - name: FocusElement.CodeEditor, - selector: getFocusableCodeEditorField, - setter: setFocusableCodeEditorField, + name: FocusElement.InputField, + selector: getFocusableInputField, + setter: setFocusableInputField, }, { name: FocusElement.QueryPaneConfigTabs, @@ -267,18 +262,13 @@ export const FocusElementsConfig: Record<FocusEntity, Config[]> = { defaultValue: 0, }, { - name: FocusElement.PropertyField, - selector: getFocusablePropertyPaneField, - setter: setFocusablePropertyPaneField, + name: FocusElement.InputField, + selector: getFocusableInputField, + setter: setFocusableInputField, defaultValue: "", }, ], [FocusEntity.API]: [ - { - name: FocusElement.CodeEditor, - selector: getFocusableCodeEditorField, - setter: setFocusableCodeEditorField, - }, { name: FocusElement.ApiPaneConfigTabs, selector: getApiPaneConfigSelectedTabIndex, @@ -302,6 +292,11 @@ export const FocusElementsConfig: Record<FocusEntity, Config[]> = { setter: setApiPaneResponsePaneHeight, defaultValue: ActionExecutionResizerHeight, }, + { + name: FocusElement.InputField, + selector: getFocusableInputField, + setter: setFocusableInputField, + }, { name: FocusElement.ApiRightPaneTabs, selector: getApiRightPaneSelectedTab, diff --git a/app/client/src/pages/Editor/APIEditor/Pagination.tsx b/app/client/src/pages/Editor/APIEditor/Pagination.tsx index 77107688bd79..a67a389a6619 100644 --- a/app/client/src/pages/Editor/APIEditor/Pagination.tsx +++ b/app/client/src/pages/Editor/APIEditor/Pagination.tsx @@ -17,6 +17,7 @@ import lightmodeThumbnail from "assets/icons/gifs/lightmode_thumbnail.png"; import darkmodeThumbnail from "assets/icons/gifs/darkmode_thumbnail.png"; interface PaginationProps { + actionName: string; onTestClick: (test?: "PREV" | "NEXT") => void; paginationType: PaginationType; theme?: EditorTheme; @@ -183,6 +184,7 @@ export default function Pagination(props: PaginationProps) { border={CodeEditorBorder.ALL_SIDE} className="t--apiFormPaginationPrev" fill={!!true} + focusElementName={`${props.actionName}.actionConfiguration.prev`} height="100%" name="actionConfiguration.prev" theme={props.theme} @@ -208,6 +210,7 @@ export default function Pagination(props: PaginationProps) { border={CodeEditorBorder.ALL_SIDE} className="t--apiFormPaginationNext" fill={!!true} + focusElementName={`${props.actionName}.actionConfiguration.next`} height="100%" name="actionConfiguration.next" theme={props.theme} diff --git a/app/client/src/pages/Editor/APIEditor/RapidApiEditorForm.tsx b/app/client/src/pages/Editor/APIEditor/RapidApiEditorForm.tsx index 3281ecda4906..22a7ef956b46 100644 --- a/app/client/src/pages/Editor/APIEditor/RapidApiEditorForm.tsx +++ b/app/client/src/pages/Editor/APIEditor/RapidApiEditorForm.tsx @@ -256,6 +256,7 @@ function RapidApiEditorForm(props: Props) { title: "Pagination", panelComponent: ( <Pagination + actionName={props.apiName} onTestClick={props.onRunClick} paginationType={props.paginationType} /> diff --git a/app/client/src/pages/Editor/APIEditor/RestAPIForm.tsx b/app/client/src/pages/Editor/APIEditor/RestAPIForm.tsx index 1ea013c29bcc..5c2dd092aebd 100644 --- a/app/client/src/pages/Editor/APIEditor/RestAPIForm.tsx +++ b/app/client/src/pages/Editor/APIEditor/RestAPIForm.tsx @@ -63,6 +63,7 @@ function ApiEditorForm(props: Props) { formName={API_EDITOR_FORM_NAME} paginationUIComponent={ <Pagination + actionName={actionName} onTestClick={props.onRunClick} paginationType={props.paginationType} theme={theme} diff --git a/app/client/src/pages/Editor/FormConfig.tsx b/app/client/src/pages/Editor/FormConfig.tsx index 7269894a04e9..fe202102fafc 100644 --- a/app/client/src/pages/Editor/FormConfig.tsx +++ b/app/client/src/pages/Editor/FormConfig.tsx @@ -1,4 +1,4 @@ -import React from "react"; +import React, { useEffect, useRef } from "react"; import { ControlProps } from "components/formControls/BaseControl"; import { EvaluationError, @@ -18,6 +18,15 @@ import { FormIcons } from "icons/FormIcons"; import { FormControlProps } from "./FormControl"; import { ToggleComponentToJsonHandler } from "components/editorComponents/form/ToggleComponentToJson"; import styled from "styled-components"; +import { useDispatch, useSelector } from "react-redux"; +import { identifyEntityFromPath } from "navigation/FocusEntity"; +import { AppState } from "@appsmith/reducers"; +import { + getPropertyControlFocusElement, + shouldFocusOnPropertyControl, +} from "utils/editorContextUtils"; +import { getIsInputFieldFocused } from "selectors/editorContextSelectors"; +import { setFocusableInputField } from "actions/editorContextActions"; const FlexWrapper = styled.div` display: flex; @@ -59,7 +68,48 @@ interface FormConfigProps extends FormControlProps { // props.children will render the form element export default function FormConfig(props: FormConfigProps) { let top, bottom; + const controlRef = useRef<HTMLDivElement | null>(null); + const dispatch = useDispatch(); + const entityInfo = identifyEntityFromPath( + window.location.pathname, + window.location.hash, + ); + + const handleOnFocus = () => { + if (props.config.configProperty) { + // Need an additional identifier to trigger another render when configProperty + // are same for two different entitites + dispatch( + setFocusableInputField( + `${entityInfo.id}.${props.config.configProperty}`, + ), + ); + } + }; + const shouldFocusPropertyPath: boolean = useSelector((state: AppState) => + getIsInputFieldFocused( + state, + `${entityInfo.id}.${props.config.configProperty}`, + ), + ); + + useEffect(() => { + if (shouldFocusPropertyPath) { + setTimeout(() => { + if (shouldFocusOnPropertyControl(controlRef.current)) { + const focusableElement = getPropertyControlFocusElement( + controlRef.current, + ); + focusableElement?.scrollIntoView({ + block: "center", + behavior: "smooth", + }); + focusableElement?.focus(); + } + }, 0); + } + }, [shouldFocusPropertyPath]); if (props.multipleConfig?.length) { top = ( <div style={{ display: "flex" }}> @@ -86,7 +136,11 @@ export default function FormConfig(props: FormConfigProps) { return ( <div> - <FormConfigWrapper controlType={props.config.controlType}> + <FormConfigWrapper + controlType={props.config.controlType} + onFocus={handleOnFocus} + ref={controlRef} + > {props.config.controlType === "CHECKBOX" ? ( <> {props.children} diff --git a/app/client/src/pages/Editor/PropertyPane/PropertyControl.tsx b/app/client/src/pages/Editor/PropertyPane/PropertyControl.tsx index e4fb60973a89..a3bc9574c4c2 100644 --- a/app/client/src/pages/Editor/PropertyPane/PropertyControl.tsx +++ b/app/client/src/pages/Editor/PropertyPane/PropertyControl.tsx @@ -34,7 +34,6 @@ import { THEME_BINDING_REGEX, } from "utils/DynamicBindingUtils"; import { - getShouldFocusPropertyPath, getWidgetPropsForPropertyName, WidgetProperties, } from "selectors/propertyPaneSelectors"; @@ -55,8 +54,9 @@ import { shouldFocusOnPropertyControl, } from "utils/editorContextUtils"; import PropertyPaneHelperText from "./PropertyPaneHelperText"; -import { setFocusablePropertyPaneField } from "actions/propertyPaneActions"; import WidgetFactory from "utils/WidgetFactory"; +import { getIsInputFieldFocused } from "selectors/editorContextSelectors"; +import { setFocusableInputField } from "actions/editorContextActions"; type Props = PropertyPaneControlConfig & { panel: IPanelProps; @@ -91,7 +91,7 @@ const PropertyControl = memo((props: Props) => { const hasDispatchedPropertyFocus = useRef<boolean>(false); const shouldFocusPropertyPath: boolean = useSelector( (state: AppState) => - getShouldFocusPropertyPath( + getIsInputFieldFocused( state, dataTreePath, hasDispatchedPropertyFocus.current, @@ -576,7 +576,7 @@ const PropertyControl = memo((props: Props) => { if (!shouldFocusPropertyPath) { hasDispatchedPropertyFocus.current = true; setTimeout(() => { - dispatch(setFocusablePropertyPaneField(dataTreePath)); + dispatch(setFocusableInputField(dataTreePath)); }, 0); } }; diff --git a/app/client/src/reducers/uiReducers/editorContextReducer.ts b/app/client/src/reducers/uiReducers/editorContextReducer.ts index 24be20ae5434..ea70c46b8850 100644 --- a/app/client/src/reducers/uiReducers/editorContextReducer.ts +++ b/app/client/src/reducers/uiReducers/editorContextReducer.ts @@ -32,7 +32,7 @@ export type EditorContextState = { entityCollapsibleFields: Record<string, boolean>; subEntityCollapsibleFields: Record<string, boolean>; explorerSwitchIndex: number; - focusableCodeEditor?: string; + focusedInputField?: string; codeEditorHistory: Record<string, CodeEditorContext>; propertySectionState: Record<string, boolean>; selectedPropertyTabIndex: number; @@ -61,14 +61,14 @@ export const isSubEntities = (name: string): boolean => { * Context Reducer to store states of different components of editor */ export const editorContextReducer = createImmerReducer(initialState, { - [ReduxActionTypes.SET_FOCUSABLE_CODE_EDITOR_FIELD]: ( + [ReduxActionTypes.SET_FOCUSABLE_INPUT_FIELD]: ( state: EditorContextState, action: { payload: { path: string }; }, ) => { const { path } = action.payload; - state.focusableCodeEditor = path; + state.focusedInputField = path; }, [ReduxActionTypes.SET_CODE_EDITOR_CURSOR]: ( state: EditorContextState, diff --git a/app/client/src/reducers/uiReducers/propertyPaneReducer.tsx b/app/client/src/reducers/uiReducers/propertyPaneReducer.tsx index 42a7467f25be..92678d197e09 100644 --- a/app/client/src/reducers/uiReducers/propertyPaneReducer.tsx +++ b/app/client/src/reducers/uiReducers/propertyPaneReducer.tsx @@ -76,12 +76,6 @@ const propertyPaneReducer = createImmerReducer(initialState, { ) => { state.width = action.payload; }, - [ReduxActionTypes.SET_FOCUSABLE_PROPERTY_FIELD]: ( - state: PropertyPaneReduxState, - action: ReduxAction<{ path: string }>, - ) => { - state.focusedProperty = action.payload.path; - }, [ReduxActionTypes.SET_SELECTED_PANEL_PROPERTY]: ( state: PropertyPaneReduxState, action: { diff --git a/app/client/src/sagas/editorContextSagas.ts b/app/client/src/sagas/editorContextSagas.ts index 22f552f683aa..aba7cdd41db2 100644 --- a/app/client/src/sagas/editorContextSagas.ts +++ b/app/client/src/sagas/editorContextSagas.ts @@ -13,7 +13,7 @@ import { all, put, takeLatest } from "redux-saga/effects"; import { CodeEditorFocusState, setCodeEditorCursorAction, - setFocusableCodeEditorField, + setFocusableInputField, } from "actions/editorContextActions"; import { FocusEntity, identifyEntityFromPath } from "navigation/FocusEntity"; @@ -28,10 +28,11 @@ function* setEditorFieldFocus(action: ReduxAction<CodeEditorFocusState>) { window.location.pathname, window.location.hash, ); + const ignoredEntities = [FocusEntity.DATASOURCE]; if (key) { - if (entityInfo.entity !== FocusEntity.PROPERTY_PANE) { - yield put(setFocusableCodeEditorField(key)); + if (!ignoredEntities.includes(entityInfo.entity)) { + yield put(setFocusableInputField(key)); } yield put(setCodeEditorCursorAction(key, cursorPosition)); } diff --git a/app/client/src/selectors/editorContextSelectors.ts b/app/client/src/selectors/editorContextSelectors.ts index 9c9a09c10fed..84f14a652702 100644 --- a/app/client/src/selectors/editorContextSelectors.ts +++ b/app/client/src/selectors/editorContextSelectors.ts @@ -11,8 +11,8 @@ import { createSelector } from "reselect"; import { selectFeatureFlags } from "selectors/usersSelectors"; import FeatureFlags from "entities/FeatureFlags"; -export const getFocusableCodeEditorField = (state: AppState) => - state.ui.editorContext.focusableCodeEditor; +export const getFocusableInputField = (state: AppState) => + state.ui.editorContext.focusedInputField; export const getCodeEditorHistory = (state: AppState) => state.ui.editorContext.codeEditorHistory; @@ -67,9 +67,9 @@ export const getSelectedPropertyTabIndex = createSelector( }, ); -export const getIsCodeEditorFocused = createSelector( +export const getIsInputFieldFocused = createSelector( [ - getFocusableCodeEditorField, + getFocusableInputField, selectFeatureFlags, (_state: AppState, key: string | undefined) => key, ], diff --git a/app/client/src/selectors/propertyPaneSelectors.tsx b/app/client/src/selectors/propertyPaneSelectors.tsx index 3863129d2271..27c2df54562c 100644 --- a/app/client/src/selectors/propertyPaneSelectors.tsx +++ b/app/client/src/selectors/propertyPaneSelectors.tsx @@ -20,6 +20,7 @@ import { EVALUATION_PATH } from "utils/DynamicBindingUtils"; import { generateClassName } from "utils/generators"; import { getWidgets } from "sagas/selectors"; import { RegisteredWidgetFeatures } from "utils/WidgetFeatures"; +import { getFocusableInputField } from "./editorContextSelectors"; export type WidgetProperties = WidgetProps & { [EVALUATION_PATH]?: DataTreeEntity; @@ -266,18 +267,6 @@ export const getIsPropertyPaneVisible = createSelector( export const getPropertyPaneWidth = (state: AppState) => { return state.ui.propertyPane.width; }; -export const getFocusablePropertyPaneField = (state: AppState) => - state.ui.propertyPane.focusedProperty; - -export const getShouldFocusPropertyPath = createSelector( - [ - getFocusablePropertyPaneField, - (_state: AppState, key: string | undefined) => key, - ], - (focusableField: string | undefined, key: string | undefined): boolean => { - return !!(key && focusableField === key); - }, -); export const getSelectedPropertyPanelIndex = createSelector( [ @@ -296,7 +285,7 @@ export const getSelectedPropertyPanelIndex = createSelector( export const getShouldFocusPropertySearch = createSelector( getIsCurrentWidgetRecentlyAdded, - getFocusablePropertyPaneField, + getFocusableInputField, ( isCurrentWidgetRecentlyAdded: boolean, focusableField: string | undefined,
4d24aba331c88f1247a4812599ebe12c91187132
2023-12-05 10:47:36
Shrikant Sharat Kandula
feat: Caddy (#28081)
false
Caddy (#28081)
feat
diff --git a/Dockerfile b/Dockerfile index 55e3511a8782..ec74fbbeb628 100644 --- a/Dockerfile +++ b/Dockerfile @@ -29,13 +29,12 @@ ENV PATH /opt/appsmith/utils/node_modules/.bin:/opt/java/bin:/opt/node/bin:$PATH RUN cd ./utils && npm install --only=prod && npm install --only=prod -g . && cd - \ && chmod 0644 /etc/cron.d/* \ - && chmod +x *.sh templates/nginx-app.conf.sh /watchtower-hooks/*.sh \ + && chmod +x *.sh /watchtower-hooks/*.sh \ # Disable setuid/setgid bits for the files inside container. && find / \( -path /proc -prune \) -o \( \( -perm -2000 -o -perm -4000 \) -print -exec chmod -s '{}' + \) || true \ - && node prepare-image.mjs \ && mkdir -p /.mongodb/mongosh /appsmith-stacks \ && chmod ugo+w /etc /appsmith-stacks \ - && chmod -R ugo+w /var/lib/nginx /var/log/nginx /var/run /usr/sbin/cron /.mongodb /etc/ssl /usr/local/share + && chmod -R ugo+w /var/run /usr/sbin/cron /.mongodb /etc/ssl /usr/local/share LABEL com.centurylinklabs.watchtower.lifecycle.pre-check=/watchtower-hooks/pre-check.sh LABEL com.centurylinklabs.watchtower.lifecycle.pre-update=/watchtower-hooks/pre-update.sh diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/configurations/InstanceConfig.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/configurations/InstanceConfig.java index 24c22e27ec52..6995fd4b3af7 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/configurations/InstanceConfig.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/configurations/InstanceConfig.java @@ -31,7 +31,7 @@ public class InstanceConfig implements ApplicationListener<ApplicationReadyEvent private final InstanceConfigHelper instanceConfigHelper; - private static final String WWW_PATH = System.getenv("NGINX_WWW_PATH"); + private static final String WWW_PATH = System.getenv("WWW_PATH"); @Override public void onApplicationEvent(ApplicationReadyEvent applicationReadyEvent) { diff --git a/deploy/docker/fs/opt/appsmith/caddy-reconfigure.mjs b/deploy/docker/fs/opt/appsmith/caddy-reconfigure.mjs new file mode 100644 index 000000000000..0934556225ce --- /dev/null +++ b/deploy/docker/fs/opt/appsmith/caddy-reconfigure.mjs @@ -0,0 +1,133 @@ +import * as fs from "fs" +import {dirname} from "path" +import {spawnSync} from "child_process" +import {X509Certificate} from "crypto" + +const APPSMITH_CUSTOM_DOMAIN = process.env.APPSMITH_CUSTOM_DOMAIN ?? null +const CaddyfilePath = process.env.TMP + "/Caddyfile" + +let certLocation = null +if (APPSMITH_CUSTOM_DOMAIN != null) { + try { + fs.accessSync("/appsmith-stacks/ssl/fullchain.pem", fs.constants.R_OK) + certLocation = "/appsmith-stacks/ssl" + } catch (_) { + // no custom certs, see if old certbot certs are there. + const letsEncryptCertLocation = "/etc/letsencrypt/live/" + APPSMITH_CUSTOM_DOMAIN + const fullChainPath = letsEncryptCertLocation + `/fullchain.pem` + try { + fs.accessSync(fullChainPath, fs.constants.R_OK) + console.log("Old Let's Encrypt cert file exists, now checking if it's expired.") + if (!isCertExpired(fullChainPath)) { + certLocation = letsEncryptCertLocation + } + } catch (_) { + // no certs there either, ignore. + } + } + +} + +const tlsConfig = certLocation == null ? "" : `tls ${certLocation}/fullchain.pem ${certLocation}/privkey.pem` + +const parts = [] + +parts.push(` +{ + admin 127.0.0.1:2019 + persist_config off + acme_ca_root /etc/ssl/certs/ca-certificates.crt + servers { + trusted_proxies static 0.0.0.0/0 + } +} + +(file_server) { + file_server { + precompressed br gzip + disable_canonical_uris + } +} + +(reverse_proxy) { + reverse_proxy { + to 127.0.0.1:{args[0]} + header_up -Forwarded + } +} + +(all-config) { + log { + output stdout + } + skip_log /api/v1/health + + header { + -Server + Content-Security-Policy "frame-ancestors ${process.env.APPSMITH_ALLOWED_FRAME_ANCESTORS ?? "'self' *"}" + X-Content-Type-Options "nosniff" + } + + request_body { + max_size 150MB + } + + handle { + root * {$WWW_PATH} + try_files /loading.html /index.html + import file_server + } + + root * /opt/appsmith/editor + @file file + handle @file { + import file_server + skip_log + } + error /static/* 404 + + handle /info { + root * /opt/appsmith + rewrite * /info.json + import file_server + } + + @backend path /api/* /oauth2/* /login/* + handle @backend { + import reverse_proxy 8080 + } + + handle /rts/* { + import reverse_proxy 8091 + } + + redir /supervisor /supervisor/ + handle_path /supervisor/* { + import reverse_proxy 9001 + } + + handle_errors { + respond "{err.status_code} {err.status_text}" {err.status_code} + } +} + +localhost:80 127.0.0.1:80 { + import all-config +} + +${APPSMITH_CUSTOM_DOMAIN || ":80"} { + import all-config + ${tlsConfig} +} +`) + +fs.mkdirSync(dirname(CaddyfilePath), { recursive: true }) +fs.writeFileSync(CaddyfilePath, parts.join("\n")) +spawnSync("/opt/caddy/caddy", ["fmt", "--overwrite", CaddyfilePath]) +spawnSync("/opt/caddy/caddy", ["reload", "--config", CaddyfilePath]) + +function isCertExpired(path) { + const cert = new X509Certificate(fs.readFileSync(path, "utf-8")) + console.log(path, cert) + return new Date(cert.validTo) < new Date() +} diff --git a/deploy/docker/fs/opt/appsmith/entrypoint.sh b/deploy/docker/fs/opt/appsmith/entrypoint.sh index 45223aeea84f..8ece870a5867 100644 --- a/deploy/docker/fs/opt/appsmith/entrypoint.sh +++ b/deploy/docker/fs/opt/appsmith/entrypoint.sh @@ -9,7 +9,7 @@ stacks_path=/appsmith-stacks export SUPERVISORD_CONF_TARGET="$TMP/supervisor-conf.d/" # export for use in supervisord.conf export MONGODB_TMP_KEY_PATH="$TMP/mongodb-key" # export for use in supervisor process mongodb.conf -mkdir -pv "$SUPERVISORD_CONF_TARGET" "$NGINX_WWW_PATH" +mkdir -pv "$SUPERVISORD_CONF_TARGET" "$WWW_PATH" # ip is a reserved keyword for tracking events in Mixpanel. Instead of showing the ip as is Mixpanel provides derived properties. # As we want derived props alongwith the ip address we are sharing the ip address in separate keys @@ -347,11 +347,6 @@ configure_supervisord() { cp "$supervisord_conf_source/redis.conf" "$SUPERVISORD_CONF_TARGET" mkdir -p "$stacks_path/data/redis" fi - if ! [[ -e "/appsmith-stacks/ssl/fullchain.pem" ]] || ! [[ -e "/appsmith-stacks/ssl/privkey.pem" ]]; then - if [[ -n "${APPSMITH_CUSTOM_DOMAIN-}" ]]; then - cp "$supervisord_conf_source/cron.conf" "$SUPERVISORD_CONF_TARGET" - fi - fi if [[ $runEmbeddedPostgres -eq 1 ]]; then cp "$supervisord_conf_source/postgres.conf" "$SUPERVISORD_CONF_TARGET" fi @@ -443,23 +438,20 @@ init_postgres || runEmbeddedPostgres=0 } init_loading_pages(){ - local starting_page="/opt/appsmith/templates/appsmith_starting.html" - local initializing_page="/opt/appsmith/templates/appsmith_initializing.html" - local editor_load_page="$NGINX_WWW_PATH/loading.html" - cp "$initializing_page" "$NGINX_WWW_PATH/index.html" - # TODO: Also listen on 443, if HTTP certs are available. - cat <<EOF > "$TMP/nginx-app.conf" - server { - listen ${PORT:-80} default_server; - location / { - try_files \$uri \$uri/ /index.html =404; - } - } -EOF - # Start nginx page to display the Appsmith is Initializing page - nginx - # Update editor nginx page for starting page - cp "$starting_page" "$editor_load_page" + export XDG_DATA_HOME=/appsmith-stacks/data # so that caddy saves tls certs and other data under stacks/data/caddy + export XDG_CONFIG_HOME=/appsmith-stacks/configuration + mkdir -p "$XDG_DATA_HOME" "$XDG_CONFIG_HOME" + cp templates/loading.html "$WWW_PATH" + if [[ -z "${APPSMITH_ALLOWED_FRAME_ANCESTORS-}" ]]; then + # https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/frame-ancestors + export APPSMITH_ALLOWED_FRAME_ANCESTORS="'self'" + else + # Remove any extra rules that may be present in the frame ancestors value. This is to prevent this env variable from + # being used to inject more rules to the CSP header. If needed, that should be supported/solved separately. + export APPSMITH_ALLOWED_FRAME_ANCESTORS="${APPSMITH_ALLOWED_FRAME_ANCESTORS%;*}" + fi + node caddy-reconfigure.mjs + /opt/caddy/caddy start --config "$TMP/Caddyfile" } # Main Section @@ -498,8 +490,5 @@ mkdir -p /appsmith-stacks/data/{backup,restore} # Create sub-directory to store services log in the container mounting folder mkdir -p /appsmith-stacks/logs/{supervisor,backend,cron,editor,rts,mongodb,redis,postgres,appsmithctl} -# Stop nginx gracefully -nginx -s quit - # Handle CMD command exec "$@" diff --git a/deploy/docker/fs/opt/appsmith/init_ssl_cert.sh b/deploy/docker/fs/opt/appsmith/init_ssl_cert.sh deleted file mode 100755 index 2a384a78b5b7..000000000000 --- a/deploy/docker/fs/opt/appsmith/init_ssl_cert.sh +++ /dev/null @@ -1,63 +0,0 @@ -#!/bin/bash - -init_ssl_cert() { - APPSMITH_CUSTOM_DOMAIN="$1" - - local rsa_key_size=4096 - local data_path="/appsmith-stacks/data/certificate" - - mkdir -p "$data_path/www" - - echo "Re-generating nginx config template with domain" - /opt/appsmith/templates/nginx-app.conf.sh "0" "$APPSMITH_CUSTOM_DOMAIN" - - echo "Start Nginx to verify certificate" - nginx - - local live_path="/etc/letsencrypt/live/$APPSMITH_CUSTOM_DOMAIN" - local ssl_path="/appsmith-stacks/ssl" - if [[ -e "$ssl_path/fullchain.pem" ]] && [[ -e "$ssl_path/privkey.pem" ]]; then - echo "Existing custom certificate" - echo "Stop Nginx" - nginx -s stop - return - fi - - if [[ -e "$live_path" ]]; then - echo "Existing certificate for domain $APPSMITH_CUSTOM_DOMAIN" - echo "Stop Nginx" - nginx -s stop - return - fi - - echo "Creating certificate for '$APPSMITH_CUSTOM_DOMAIN'" - - echo "Requesting Let's Encrypt certificate for '$APPSMITH_CUSTOM_DOMAIN'..." - echo "Generating OpenSSL key for '$APPSMITH_CUSTOM_DOMAIN'..." - - mkdir -p "$live_path" && openssl req -x509 -nodes -newkey rsa:2048 -days 1 \ - -keyout "$live_path/privkey.pem" \ - -out "$live_path/fullchain.pem" \ - -subj "/CN=localhost" - - echo "Removing key now that validation is done for $APPSMITH_CUSTOM_DOMAIN..." - rm -Rfv /etc/letsencrypt/live/$APPSMITH_CUSTOM_DOMAIN /etc/letsencrypt/archive/$APPSMITH_CUSTOM_DOMAIN /etc/letsencrypt/renewal/$APPSMITH_CUSTOM_DOMAIN.conf - - echo "Generating certification for domain $APPSMITH_CUSTOM_DOMAIN" - mkdir -p "$data_path/certbot" - certbot certonly --webroot --webroot-path="$data_path/certbot" \ - --register-unsafely-without-email \ - --domains $APPSMITH_CUSTOM_DOMAIN \ - --rsa-key-size $rsa_key_size \ - --agree-tos \ - --force-renewal - - if (($? != 0)); then - echo "Stop Nginx due to provisioning fail" - nginx -s stop - return 1 - fi - - echo "Stop Nginx" - nginx -s stop -} diff --git a/deploy/docker/fs/opt/appsmith/prepare-image.mjs b/deploy/docker/fs/opt/appsmith/prepare-image.mjs deleted file mode 100644 index eeced714fe27..000000000000 --- a/deploy/docker/fs/opt/appsmith/prepare-image.mjs +++ /dev/null @@ -1,27 +0,0 @@ -import * as fs from "fs/promises"; - -const TMP = process.env.TMP; -const NGINX_WWW_PATH = process.env.NGINX_WWW_PATH; - -async function applyNginxChanges() { - const contents = await fs.readFile("/etc/nginx/nginx.conf", "utf8") - - const modContents = contents - .replace("pid /run/nginx.pid;", `pid ${TMP}/nginx.pid;`) - .replace("# server_tokens off;", "server_tokens off; more_set_headers 'Server: ';") - .replace("gzip on;", "gzip on; gzip_types *;") - .replace("include /etc/nginx/conf.d/*.conf;", [ - "include /etc/nginx/conf.d/*.conf;", - `include ${TMP}/nginx-app.conf;`, - `root ${NGINX_WWW_PATH};`, - ].join("\n")); - - await Promise.all([ - fs.writeFile("/etc/nginx/nginx.conf.original", contents), - fs.writeFile("/etc/nginx/nginx.conf", modContents), - fs.rm("/etc/nginx/sites-enabled", { recursive: true }), - fs.rm("/etc/nginx/conf.d", { recursive: true }), - ]) -} - -await applyNginxChanges(); diff --git a/deploy/docker/fs/opt/appsmith/renew-certificate.sh b/deploy/docker/fs/opt/appsmith/renew-certificate.sh deleted file mode 100644 index 3a4981accbc5..000000000000 --- a/deploy/docker/fs/opt/appsmith/renew-certificate.sh +++ /dev/null @@ -1,29 +0,0 @@ -#!/usr/bin/env bash - -set -e - -ENV_PATH="/appsmith-stacks/configuration/docker.env" -PRE_DEFINED_ENV_PATH="$TMP/pre-define.env" -if [[ -f /appsmith-stacks/configuration/docker.env ]]; then - echo 'Load environment configuration' - set -o allexport - . "$ENV_PATH" - . "$PRE_DEFINED_ENV_PATH" - set +o allexport -fi - -if [[ -n $APPSMITH_CUSTOM_DOMAIN ]]; then - data_path="/appsmith-stacks/data/certificate" - domain="$APPSMITH_CUSTOM_DOMAIN" - rsa_key_size=4096 - - certbot certonly --webroot --webroot-path="$data_path/certbot" \ - --register-unsafely-without-email \ - --domains $domain \ - --rsa-key-size $rsa_key_size \ - --agree-tos \ - --force-renewal - supervisorctl restart editor -else - echo 'Custom domain not configured. Cannot enable SSL without a custom domain.' >&2 -fi diff --git a/deploy/docker/fs/opt/appsmith/run-caddy.sh b/deploy/docker/fs/opt/appsmith/run-caddy.sh new file mode 100755 index 000000000000..b00d18cb661b --- /dev/null +++ b/deploy/docker/fs/opt/appsmith/run-caddy.sh @@ -0,0 +1,35 @@ +#!/bin/bash + +set -o errexit +set -o nounset +set -o pipefail + +if [[ -z "${APPSMITH_DISABLE_IFRAME_WIDGET_SANDBOX-}" ]]; then + # For backwards compatibility, if this is not set to anything, we default to no sandbox for iframe widgets. + export APPSMITH_DISABLE_IFRAME_WIDGET_SANDBOX="true" +fi + +apply-env-vars() { + original="$1" + served="$2" + node -e ' + const fs = require("fs") + const content = fs.readFileSync("'"$original"'", "utf8").replace( + /\b__(APPSMITH_[A-Z0-9_]+)__\b/g, + (placeholder, name) => (process.env[name] || "") + ) + fs.writeFileSync("'"$served"'", content) + ' + pushd "$(dirname "$served")" + gzip --keep --force "$(basename "$served")" + popd +} + +apply-env-vars /opt/appsmith/editor/index.html "$WWW_PATH/index.html" + +node caddy-reconfigure.mjs + +# Caddy may already be running for the loading page. +/opt/caddy/caddy stop --config "$TMP/Caddyfile" || true + +exec /opt/caddy/caddy run --config "$TMP/Caddyfile" diff --git a/deploy/docker/fs/opt/appsmith/run-nginx.sh b/deploy/docker/fs/opt/appsmith/run-nginx.sh deleted file mode 100755 index e89933b8a4d9..000000000000 --- a/deploy/docker/fs/opt/appsmith/run-nginx.sh +++ /dev/null @@ -1,90 +0,0 @@ -#!/bin/bash - -set -o errexit -set -o nounset -set -o pipefail -set -o xtrace - -ssl_conf_path="/appsmith-stacks/data/certificate/conf" - -mkdir -pv "$ssl_conf_path" - -cat <<EOF > "$ssl_conf_path/options-ssl-nginx.conf" -# This file contains important security parameters. If you modify this file -# manually, Certbot will be unable to automatically provide future security -# updates. Instead, Certbot will print and log an error message with a path to -# the up-to-date file that you will need to refer to when manually updating -# this file. - -ssl_session_cache shared:le_nginx_SSL:10m; -ssl_session_timeout 1440m; -ssl_session_tickets off; - -ssl_protocols TLSv1.2 TLSv1.3; -ssl_prefer_server_ciphers off; - -ssl_ciphers "ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:DHE-RSA-AES128-GCM-SHA256:DHE-RSA-AES256-GCM-SHA384"; -EOF - -cat <<EOF > "$ssl_conf_path/ssl-dhparams.pem" ------BEGIN DH PARAMETERS----- -MIIBCAKCAQEA//////////+t+FRYortKmq/cViAnPTzx2LnFg84tNpWp4TZBFGQz -+8yTnc4kmz75fS/jY2MMddj2gbICrsRhetPfHtXV/WVhJDP1H18GbtCFY2VVPe0a -87VXE15/V8k1mE8McODmi3fipona8+/och3xWKE2rec1MKzKT0g6eXq8CrGCsyT7 -YdEIqUuyyOP7uWrat2DX9GgdT0Kj3jlN9K5W7edjcrsZCwenyO4KbXCeAvzhzffi -7MA0BM0oNC9hkXL+nOmFg/+OTxIy7vKBg8P+OxtMb61zO7X8vC7CIAXFjvGDfRaD -ssbzSibBsu/6iGtCOGEoXJf//////////wIBAg== ------END DH PARAMETERS----- -EOF - -if [[ -z "${APPSMITH_ALLOWED_FRAME_ANCESTORS-}" ]]; then - # https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/frame-ancestors - export APPSMITH_ALLOWED_FRAME_ANCESTORS="'self'" -else - # Remove any extra rules that may be present in the frame ancestors value. This is to prevent this env variable from - # being used to inject more rules to the CSP header. If needed, that should be supported/solved separately. - export APPSMITH_ALLOWED_FRAME_ANCESTORS="${APPSMITH_ALLOWED_FRAME_ANCESTORS%;*}" -fi - -if [[ -z "${APPSMITH_DISABLE_IFRAME_WIDGET_SANDBOX-}" ]]; then - # For backwards compatibility, if this is not set to anything, we default to no sandbox for iframe widgets. - export APPSMITH_DISABLE_IFRAME_WIDGET_SANDBOX="true" -fi - -# Check exist certificate with given custom domain -# Heroku not support for custom domain, only generate HTTP config if deploying on Heroku -use_https=0 -if [[ -n ${APPSMITH_CUSTOM_DOMAIN-} ]] && [[ -z ${DYNO-} ]]; then - use_https=1 - if ! [[ -e "/etc/letsencrypt/live/$APPSMITH_CUSTOM_DOMAIN" ]]; then - source "/opt/appsmith/init_ssl_cert.sh" - if ! init_ssl_cert "$APPSMITH_CUSTOM_DOMAIN"; then - echo "Status code from init_ssl_cert is $?" - use_https=0 - fi - fi -fi - -/opt/appsmith/templates/nginx-app.conf.sh "$use_https" "${APPSMITH_CUSTOM_DOMAIN-}" - -cp -r /opt/appsmith/editor/* "$NGINX_WWW_PATH" - -apply-env-vars() { - original="$1" - served="$2" - node -e ' - const fs = require("fs") - const content = fs.readFileSync("'"$original"'", "utf8").replace( - /\b__(APPSMITH_[A-Z0-9_]+)__\b/g, - (placeholder, name) => (process.env[name] || "") - ) - fs.writeFileSync("'"$served"'", content) - ' - pushd "$(dirname "$served")" - gzip --keep --force "$(basename "$served")" - popd -} - -apply-env-vars /opt/appsmith/editor/index.html "$NGINX_WWW_PATH/index.html" - -exec nginx -g "daemon off;error_log stderr info;" diff --git a/deploy/docker/fs/opt/appsmith/run-starting-page-init.sh b/deploy/docker/fs/opt/appsmith/run-starting-page-init.sh index 310d67f18ed1..78c3c72e1e71 100644 --- a/deploy/docker/fs/opt/appsmith/run-starting-page-init.sh +++ b/deploy/docker/fs/opt/appsmith/run-starting-page-init.sh @@ -1,4 +1,4 @@ #!/bin/bash python3 /opt/appsmith/starting-page-init.py -rm -f "$NGINX_WWW_PATH/loading.html" +rm -f "$WWW_PATH/loading.html" diff --git a/deploy/docker/fs/opt/appsmith/starting-page-init.py b/deploy/docker/fs/opt/appsmith/starting-page-init.py index 45fc9cb7ef4b..3e5c40c0b073 100644 --- a/deploy/docker/fs/opt/appsmith/starting-page-init.py +++ b/deploy/docker/fs/opt/appsmith/starting-page-init.py @@ -9,7 +9,7 @@ LOADING_TEMPLATE_PAGE = r'/opt/appsmith/templates/appsmith_starting.html' -LOADING_PAGE_EDITOR = os.getenv("NGINX_WWW_PATH") + '/loading.html' +LOADING_PAGE_EDITOR = os.getenv("WWW_PATH") + '/loading.html' BACKEND_HEALTH_ENDPOINT = "http://localhost:8080/api/v1/health" LOG_FILE = r'/appsmith-stacks/logs/backend/starting_page_init.log' LOG_FORMAT = '%(asctime)s - %(name)s - %(levelname)s - %(message)s' diff --git a/deploy/docker/fs/opt/appsmith/templates/appsmith_initializing.html b/deploy/docker/fs/opt/appsmith/templates/appsmith_initializing.html deleted file mode 100644 index fba1f0dab20f..000000000000 --- a/deploy/docker/fs/opt/appsmith/templates/appsmith_initializing.html +++ /dev/null @@ -1,87 +0,0 @@ -<!DOCTYPE html> -<html lang="en"> - <head> - <meta charset="utf-8" http-equiv="refresh" content="5"/> - <link - rel="shortcut icon" - href="https://assets.appsmith.com/appsmith-favicon-orange.ico" - /> - <meta - name="viewport" - content="width=device-width, initial-scale=1, shrink-to-fit=no" - /> - <title>Appsmith</title> - </head> - <body> - <div class="main"> - <p class="bold-text"> - Please wait - </p> - <p>Appsmith is initializing. This might take a few minutes.</p> - <div class="loader"></div> - </div> - - <style> - body, - html { - height: 100%; - overflow-x: hidden; - width: 100%; - background-color: #fff; - margin: 0; - color: #182026; - font-family: -apple-system, BlinkMacSystemFont, Segoe UI, Roboto, Oxygen, - Ubuntu, Cantarell, Open Sans, Helvetica Neue, Icons16, sans-serif; - font-size: 14px; - font-weight: 400; - letter-spacing: 0; - } - .main { - display: flex; - align-items: center; - height: 90%; - flex-direction: column; - margin-top: 5%; - text-align: center; - } - .bold-text { - font-family: system-ui; - font-weight: 700; - font-size: 24px; - margin: 24px 0 0; - } - .body-text { - margin: 8px 0 0; - } - - /* Safari */ - @-webkit-keyframes spin { - 0% { - -webkit-transform: rotate(0deg); - } - 100% { - -webkit-transform: rotate(360deg); - } - } - - @keyframes spin { - 0% { - transform: rotate(0deg); - } - 100% { - transform: rotate(360deg); - } - } - - .loader { - border: 4px solid #f3f3f3; - border-radius: 50%; - border-top: 4px solid #939090; - width: 30px; - height: 30px; - -webkit-animation: spin 1s linear infinite; /* Safari */ - animation: spin 1s linear infinite; - } - </style> - </body> -</html> diff --git a/deploy/docker/fs/opt/appsmith/templates/appsmith_starting.html b/deploy/docker/fs/opt/appsmith/templates/loading.html similarity index 92% rename from deploy/docker/fs/opt/appsmith/templates/appsmith_starting.html rename to deploy/docker/fs/opt/appsmith/templates/loading.html index 007a0dfce28a..1bac4bb7f390 100644 --- a/deploy/docker/fs/opt/appsmith/templates/appsmith_starting.html +++ b/deploy/docker/fs/opt/appsmith/templates/loading.html @@ -14,10 +14,8 @@ </head> <body> <div class="main"> - <p class="bold-text"> - Appsmith is starting. - </p> - <p>Please wait until Appsmith is ready. This process usually takes a minute. </p> + <p class="bold-text">Appsmith is starting.</p> + <p>Please wait until Appsmith is ready. This may take a few minutes. </p> <div class="loader"></div> </div> diff --git a/deploy/docker/fs/opt/appsmith/templates/nginx-app.conf.sh b/deploy/docker/fs/opt/appsmith/templates/nginx-app.conf.sh deleted file mode 100755 index d1644fec3c7a..000000000000 --- a/deploy/docker/fs/opt/appsmith/templates/nginx-app.conf.sh +++ /dev/null @@ -1,155 +0,0 @@ -#!/bin/bash - -set -o nounset - -use_https="$1" -custom_domain="${2:-_}" - -if [[ $use_https == 1 ]]; then - # By default, container will use the auto-generate certificate by Let's Encrypt - ssl_cert_path="/etc/letsencrypt/live/$custom_domain/fullchain.pem" - ssl_key_path="/etc/letsencrypt/live/$custom_domain/privkey.pem" - - # In case of existing custom certificate, container will use them to configure SSL - if [[ -e "/appsmith-stacks/ssl/fullchain.pem" ]] && [[ -e "/appsmith-stacks/ssl/privkey.pem" ]]; then - ssl_cert_path="/appsmith-stacks/ssl/fullchain.pem" - ssl_key_path="/appsmith-stacks/ssl/privkey.pem" - fi -fi - -additional_downstream_headers=' -# https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-Content-Type-Options -add_header X-Content-Type-Options "nosniff"; -' - -cat <<EOF > "$TMP/nginx-app.conf" -map \$http_x_forwarded_proto \$origin_scheme { - default \$http_x_forwarded_proto; - '' \$scheme; -} - -map \$http_x_forwarded_host \$origin_host { - default \$http_x_forwarded_host; - '' \$host; -} - -map \$http_forwarded \$final_forwarded { - default '\$http_forwarded, host=\$host;proto=\$scheme'; - '' ''; -} - -# redirect log to stdout for supervisor to capture -access_log /dev/stdout; - -server { - -$( -if [[ $use_https == 1 ]]; then - echo " - listen 80; - server_name $custom_domain; - - location /.well-known/acme-challenge/ { - root /appsmith-stacks/data/certificate/certbot; - } - - location / { - return 301 https://\$host\$request_uri; - } -} - -server { - listen 443 ssl http2; - server_name _; - ssl_certificate $ssl_cert_path; - ssl_certificate_key $ssl_key_path; - include /appsmith-stacks/data/certificate/conf/options-ssl-nginx.conf; - ssl_dhparam /appsmith-stacks/data/certificate/conf/ssl-dhparams.pem; -" -else - echo " - listen ${PORT:-80} default_server; - server_name $custom_domain; -" -fi -) - - client_max_body_size 150m; - - index index.html; - error_page 404 /; - - # 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' *}"; - - $additional_downstream_headers - - location /.well-known/acme-challenge/ { - root /appsmith-stacks/data/certificate/certbot; - } - - location = /supervisor { - return 301 /supervisor/; - } - - location /supervisor/ { - proxy_http_version 1.1; - proxy_buffering off; - proxy_max_temp_file_size 0; - proxy_redirect off; - proxy_set_header Host \$http_host/supervisor/; - proxy_set_header X-Forwarded-For \$proxy_add_x_forwarded_for; - proxy_set_header X-Forwarded-Proto \$origin_scheme; - proxy_set_header X-Forwarded-Host \$origin_host; - proxy_set_header Connection ""; - proxy_pass http://localhost:9001/; - } - - proxy_set_header X-Forwarded-Proto \$origin_scheme; - proxy_set_header X-Forwarded-Host \$origin_host; - proxy_set_header Forwarded \$final_forwarded; - - location / { - try_files /loading.html \$uri /index.html =404; - } - - location = /info { - default_type application/json; - alias /opt/appsmith/info.json; - } - - location ~ ^/static/(js|css|media)\b { - # Files in these folders are hashed, so we can set a long cache time. - add_header Cache-Control "max-age=31104000, immutable"; # 360 days - $additional_downstream_headers - access_log off; - } - - # If the path has an extension at the end, then respond with 404 status if the file not found. - location ~ ^/(?!supervisor/).*\.[a-z]+$ { - try_files \$uri =404; - } - - location /api { - proxy_read_timeout ${APPSMITH_SERVER_TIMEOUT:-60}; - proxy_send_timeout ${APPSMITH_SERVER_TIMEOUT:-60}; - proxy_pass http://localhost:8080; - } - - location /oauth2 { - proxy_pass http://localhost:8080; - } - - location /login { - proxy_pass http://localhost:8080; - } - - location /rts { - proxy_pass http://localhost:${APPSMITH_RTS_PORT:-8091}; - proxy_http_version 1.1; - proxy_set_header Host \$host; - proxy_set_header Connection 'upgrade'; - proxy_set_header Upgrade \$http_upgrade; - } -} -EOF diff --git a/deploy/docker/fs/opt/appsmith/templates/supervisord/application_process/editor.conf b/deploy/docker/fs/opt/appsmith/templates/supervisord/application_process/editor.conf index f3b6d3725270..0b7ab6d0e531 100644 --- a/deploy/docker/fs/opt/appsmith/templates/supervisord/application_process/editor.conf +++ b/deploy/docker/fs/opt/appsmith/templates/supervisord/application_process/editor.conf @@ -1,5 +1,5 @@ [program:editor] -command=/opt/appsmith/run-with-env.sh /opt/appsmith/run-nginx.sh +command=/opt/appsmith/run-with-env.sh /opt/appsmith/run-caddy.sh priority=25 autostart=true autorestart=true
391bfaecd39b6e390c85879b6f37ba6041ee868f
2023-05-31 05:34:45
Ayush Pahwa
fix: Fixes bug of gsheets not going into edit mode (#23839)
false
Fixes bug of gsheets not going into edit mode (#23839)
fix
diff --git a/app/client/src/ee/api/ApiUtils.ts b/app/client/src/ee/api/ApiUtils.ts index c0bb30996f34..080489b3e0f0 100644 --- a/app/client/src/ee/api/ApiUtils.ts +++ b/app/client/src/ee/api/ApiUtils.ts @@ -1,6 +1,6 @@ export * from "ce/api/ApiUtils"; -const DEFAULT_ENV_ID = "unused_env"; +export const DEFAULT_ENV_ID = "unused_env"; export const getEnvironmentIdForHeader = (): string => { return DEFAULT_ENV_ID; diff --git a/app/client/src/pages/Editor/DataSourceEditor/DSFormHeader.tsx b/app/client/src/pages/Editor/DataSourceEditor/DSFormHeader.tsx index 9e614a0d6b2f..06496745e1db 100644 --- a/app/client/src/pages/Editor/DataSourceEditor/DSFormHeader.tsx +++ b/app/client/src/pages/Editor/DataSourceEditor/DSFormHeader.tsx @@ -35,12 +35,12 @@ export const FormTitleContainer = styled.div` export const Header = styled.div` display: flex; flex-direction: row; - flex: "1 1 10%"; align-items: center; justify-content: space-between; border-bottom: 1px solid var(--ads-v2-color-border); padding: var(--ads-v2-spaces-7) 0 var(--ads-v2-spaces-7); margin: 0 var(--ads-v2-spaces-7); + height: 120px; `; export const PluginImageWrapper = styled.div` diff --git a/app/client/src/pages/Editor/DataSourceEditor/index.tsx b/app/client/src/pages/Editor/DataSourceEditor/index.tsx index fa0c36bdbe4e..41aa79e71b96 100644 --- a/app/client/src/pages/Editor/DataSourceEditor/index.tsx +++ b/app/client/src/pages/Editor/DataSourceEditor/index.tsx @@ -193,7 +193,7 @@ class DatasourceEditorRouter extends React.Component<Props, State> { id: "", name: "", userPermissions: [], - showFilterPane: true, + showFilterPane: false, }, unblock: () => { return undefined; @@ -664,6 +664,7 @@ class DatasourceEditorRouter extends React.Component<Props, State> { pluginName={pluginName} pluginPackageName={pluginPackageName} pluginType={pluginType as PluginType} + setDatasourceViewMode={setDatasourceViewMode} showFilterComponent={showFilterComponent} triggerSave={triggerSave} viewMode={viewMode} diff --git a/app/client/src/pages/Editor/SaaSEditor/DatasourceForm.tsx b/app/client/src/pages/Editor/SaaSEditor/DatasourceForm.tsx index 6dda20c5a4b5..5668d0a198d2 100644 --- a/app/client/src/pages/Editor/SaaSEditor/DatasourceForm.tsx +++ b/app/client/src/pages/Editor/SaaSEditor/DatasourceForm.tsx @@ -93,6 +93,7 @@ interface StateProps extends JSONtoFormProps { isDatasourceBeingSaved: boolean; isDatasourceBeingSavedFromPopup: boolean; isFormDirty: boolean; + isPluginAuthorized: boolean; gsheetToken?: string; gsheetProjectID?: string; showDebugger: boolean; @@ -350,6 +351,7 @@ class DatasourceSaaSEditor extends JSONtoForm<Props, State> { hiddenHeader, isDeleting, isInsideReconnectModal, + isPluginAuthorized, isSaving, isTesting, pageId, @@ -369,9 +371,6 @@ class DatasourceSaaSEditor extends JSONtoForm<Props, State> { const isGoogleSheetPlugin = pluginPackageName === PluginPackageName.GOOGLE_SHEETS; - const isPluginAuthorized = - plugin && isDatasourceAuthorizedForQueryCreation(formData, plugin); - const createFlow = datasourceId === TEMP_DATASOURCE_ID; /* @@ -401,7 +400,7 @@ class DatasourceSaaSEditor extends JSONtoForm<Props, State> { datasourceId={datasourceId} isDeleting={isDeleting} isNewDatasource={createFlow} - isPluginAuthorized={isPluginAuthorized || false} + isPluginAuthorized={isPluginAuthorized} pluginImage={pluginImage} pluginName={plugin?.name || ""} pluginType={plugin?.type || ""} @@ -486,6 +485,7 @@ class DatasourceSaaSEditor extends JSONtoForm<Props, State> { pluginPackageName={pluginPackageName} pluginType={plugin?.type as PluginType} scopeValue={scopeValue} + setDatasourceViewMode={setDatasourceViewMode} shouldDisplayAuthMessage={!isGoogleSheetPlugin} showFilterComponent={false} triggerSave={this.props.isDatasourceBeingSavedFromPopup} @@ -578,6 +578,11 @@ const mapStateToProps = (state: AppState, props: any) => { viewMode = viewModeFromURLParams === "true"; } + const isPluginAuthorized = + !!plugin && !!formData + ? isDatasourceAuthorizedForQueryCreation(formData, plugin) + : true; + return { datasource, datasourceButtonConfiguration, @@ -596,6 +601,7 @@ const mapStateToProps = (state: AppState, props: any) => { pluginPackageName: props.pluginPackageName || props.match?.params?.pluginPackageName, initialValues, + isPluginAuthorized, pluginId: pluginId, actions: state.entities.actions, formName: DATASOURCE_SAAS_FORM, @@ -621,8 +627,16 @@ const mapDispatchToProps = (dispatch: any): DatasourceFormFunctions => ({ toggleSaveActionFlag: (flag) => dispatch(toggleSaveActionFlag(flag)), toggleSaveActionFromPopupFlag: (flag) => dispatch(toggleSaveActionFromPopupFlag(flag)), - setDatasourceViewMode: (viewMode: boolean) => - dispatch(setDatasourceViewMode(viewMode)), + setDatasourceViewMode: (viewMode: boolean) => { + // Construct URLSearchParams object instance from current URL querystring. + const queryParams = new URLSearchParams(window.location.search); + + queryParams.set("viewMode", viewMode.toString()); + // Replace current querystring with the new one. + history.replaceState({}, "", "?" + queryParams.toString()); + + dispatch(setDatasourceViewMode(viewMode)); + }, createTempDatasource: (data: any) => dispatch(createTempDatasourceFromForm(data)), loadFilePickerAction: () => dispatch(loadFilePickerAction()), diff --git a/app/client/src/pages/common/datasourceAuth/index.tsx b/app/client/src/pages/common/datasourceAuth/index.tsx index f56bb1efcf54..d22d1bd9df49 100644 --- a/app/client/src/pages/common/datasourceAuth/index.tsx +++ b/app/client/src/pages/common/datasourceAuth/index.tsx @@ -6,7 +6,6 @@ import { updateDatasource, redirectAuthorizationCode, getOAuthAccessToken, - setDatasourceViewMode, createDatasourceFromForm, toggleSaveActionFlag, } from "actions/datasourceActions"; @@ -49,6 +48,7 @@ interface Props { pluginType: PluginType; pluginName: string; pluginPackageName: string; + setDatasourceViewMode: (viewMode: boolean) => void; isSaving: boolean; isTesting: boolean; shouldDisplayAuthMessage?: boolean; @@ -134,6 +134,7 @@ function DatasourceAuth({ isTesting, viewMode, shouldDisplayAuthMessage = true, + setDatasourceViewMode, triggerSave, isFormDirty, scopeValue, @@ -321,7 +322,7 @@ function DatasourceAuth({ params: getQueryParams(), }); history.push(URL); - } else dispatch(setDatasourceViewMode(true)); + } else setDatasourceViewMode(true); }} size="md" > diff --git a/app/client/src/reducers/entityReducers/datasourceReducer.ts b/app/client/src/reducers/entityReducers/datasourceReducer.ts index c5b0cb9bbe47..afeff907df0d 100644 --- a/app/client/src/reducers/entityReducers/datasourceReducer.ts +++ b/app/client/src/reducers/entityReducers/datasourceReducer.ts @@ -12,6 +12,7 @@ import type { import { TEMP_DATASOURCE_ID } from "constants/Datasource"; import type { DropdownOption } from "design-system-old"; import produce from "immer"; +import { assign } from "lodash"; export interface DatasourceDataState { list: Datasource[]; @@ -337,6 +338,15 @@ const datasourceReducer = createReducer(initialState, { state: DatasourceDataState, action: ReduxAction<Datasource>, ): DatasourceDataState => { + return produce(state, (draftState) => { + draftState.loading = false; + draftState.list.forEach((datasource) => { + if (datasource.id === action.payload.id) { + assign(datasource, action.payload); + } + }); + }); + return { ...state, loading: false,
d4937d3a4255182ccee118a0a29f7ab79cf6a856
2024-05-10 16:32:50
Abhinav Jha
fix: Anvil only: Fix issue where Modal Widget doesn't open with `showModal` action (#33348)
false
Anvil only: Fix issue where Modal Widget doesn't open with `showModal` action (#33348)
fix
diff --git a/app/client/src/widgets/wds/WDSModalWidget/widget/index.tsx b/app/client/src/widgets/wds/WDSModalWidget/widget/index.tsx index eed51c15c34d..b08916f0695b 100644 --- a/app/client/src/widgets/wds/WDSModalWidget/widget/index.tsx +++ b/app/client/src/widgets/wds/WDSModalWidget/widget/index.tsx @@ -60,6 +60,12 @@ class WDSModalWidget extends BaseWidget<ModalWidgetProps, WidgetState> { return config.methodsConfig; } + static getDerivedPropertiesMap() { + return { + name: "{{this.widgetName}}", + }; + } + static *performPasteOperation( allWidgets: CanvasWidgetsReduxState, copiedWidgets: CopiedWidgetData[],
6359bfcfbe72c63dc122e7dc5df68ea915935c13
2022-05-26 13:25:08
NandanAnantharamu
test: List testcases (#14009)
false
List testcases (#14009)
test
diff --git a/app/client/cypress/fixtures/listRegression2Dsl.json b/app/client/cypress/fixtures/listRegression2Dsl.json new file mode 100644 index 000000000000..9b43ded25d0b --- /dev/null +++ b/app/client/cypress/fixtures/listRegression2Dsl.json @@ -0,0 +1,708 @@ +{ + "dsl": { + "widgetName": "MainContainer", + "backgroundColor": "none", + "rightColumn": 776, + "snapColumns": 64, + "detachFromLayout": true, + "widgetId": "0", + "topRow": 0, + "bottomRow": 1320, + "containerStyle": "none", + "snapRows": 125, + "parentRowSpace": 1, + "type": "CANVAS_WIDGET", + "canExtend": true, + "version": 58, + "minHeight": 1292, + "parentColumnSpace": 1, + "dynamicBindingPathList": [], + "leftColumn": 0, + "children": [ + { + "isVisible": true, + "backgroundColor": "transparent", + "itemBackgroundColor": "#FFFFFF", + "animateLoading": true, + "gridType": "vertical", + "template": { + "Image1": { + "isVisible": true, + "defaultImage": "https://assets.appsmith.com/widgets/default.png", + "imageShape": "RECTANGLE", + "maxZoomLevel": 1, + "enableRotation": false, + "enableDownload": false, + "objectFit": "cover", + "image": "{{List1.listData.map((currentItem) => currentItem.img)}}", + "widgetName": "Image1", + "version": 1, + "animateLoading": true, + "type": "IMAGE_WIDGET", + "hideCard": false, + "displayName": "Image", + "key": "vxcejy1m0c", + "iconSVG": "/static/media/icon.52d8fb96.svg", + "boxShadow": "none", + "dynamicBindingPathList": [ + { + "key": "image" + }, + { + "key": "borderRadius" + } + ], + "dynamicTriggerPathList": [], + "widgetId": "l3eyhgrus9", + "renderMode": "CANVAS", + "borderRadius": "{{appsmith.theme.borderRadius.appBorderRadius}}", + "isLoading": false, + "leftColumn": 0, + "rightColumn": 16, + "topRow": 0, + "bottomRow": 8, + "parentId": "ku59q894ll" + }, + "Text1": { + "isVisible": true, + "text": "{{List1.listData.map((currentItem) => currentItem.name)}}", + "fontSize": "1rem", + "fontStyle": "BOLD", + "textAlign": "LEFT", + "textColor": "#231F20", + "truncateButtonColor": "#FFC13D", + "widgetName": "Text1", + "shouldTruncate": false, + "overflow": "NONE", + "version": 1, + "animateLoading": true, + "type": "TEXT_WIDGET", + "hideCard": false, + "displayName": "Text", + "key": "yca4fpjxb9", + "iconSVG": "/static/media/icon.97c59b52.svg", + "textStyle": "HEADING", + "boxShadow": "none", + "dynamicBindingPathList": [ + { + "key": "text" + }, + { + "key": "fontFamily" + }, + { + "key": "borderRadius" + } + ], + "dynamicTriggerPathList": [], + "widgetId": "xvuk7zw6i2", + "renderMode": "CANVAS", + "fontFamily": "{{appsmith.theme.fontFamily.appFont}}", + "borderRadius": "{{appsmith.theme.borderRadius.appBorderRadius}}", + "isLoading": false, + "leftColumn": 16, + "rightColumn": 28, + "topRow": 0, + "bottomRow": 4, + "parentId": "ku59q894ll" + }, + "Text2": { + "isVisible": true, + "text": "{{List1.listData.map((currentItem) => currentItem.id)}}", + "fontSize": "1rem", + "fontStyle": "BOLD", + "textAlign": "LEFT", + "textColor": "#231F20", + "truncateButtonColor": "#FFC13D", + "widgetName": "Text2", + "shouldTruncate": false, + "overflow": "NONE", + "version": 1, + "animateLoading": true, + "type": "TEXT_WIDGET", + "hideCard": false, + "displayName": "Text", + "key": "yca4fpjxb9", + "iconSVG": "/static/media/icon.97c59b52.svg", + "textStyle": "BODY", + "boxShadow": "none", + "dynamicBindingPathList": [ + { + "key": "text" + }, + { + "key": "fontFamily" + }, + { + "key": "borderRadius" + } + ], + "dynamicTriggerPathList": [], + "widgetId": "i9cqbzdsxl", + "renderMode": "CANVAS", + "fontFamily": "{{appsmith.theme.fontFamily.appFont}}", + "borderRadius": "{{appsmith.theme.borderRadius.appBorderRadius}}", + "isLoading": false, + "leftColumn": 16, + "rightColumn": 24, + "topRow": 4, + "bottomRow": 8, + "parentId": "ku59q894ll" + }, + "Text3": { + "isVisible": true, + "text": "{{List1.listData.map((currentItem, currentIndex) => {\n return (function(){\n return currentItem.map(item => item.name).join(\",\");\n })();\n })}}", + "fontSize": "1rem", + "fontStyle": "BOLD", + "textAlign": "LEFT", + "textColor": "#231F20", + "truncateButtonColor": "#FFC13D", + "widgetName": "Text3", + "shouldTruncate": false, + "overflow": "NONE", + "version": 1, + "animateLoading": true, + "type": "TEXT_WIDGET", + "hideCard": false, + "displayName": "Text", + "key": "yca4fpjxb9", + "iconSVG": "/static/media/icon.97c59b52.svg", + "widgetId": "jmhrzoucgs", + "renderMode": "CANVAS", + "fontFamily": "{{appsmith.theme.fontFamily.appFont}}", + "borderRadius": "{{appsmith.theme.borderRadius.appBorderRadius}}", + "isLoading": false, + "parentColumnSpace": 5.6796875, + "parentRowSpace": 10, + "leftColumn": 38, + "rightColumn": 54, + "topRow": 1, + "bottomRow": 5, + "parentId": "ku59q894ll", + "dynamicBindingPathList": [ + { + "key": "fontFamily" + }, + { + "key": "borderRadius" + } + ], + "logBlackList": { + "isVisible": true, + "text": true, + "fontSize": true, + "fontStyle": true, + "textAlign": true, + "textColor": true, + "truncateButtonColor": true, + "widgetName": true, + "shouldTruncate": true, + "overflow": true, + "version": true, + "animateLoading": true, + "type": true, + "hideCard": true, + "displayName": true, + "key": true, + "iconSVG": true, + "isCanvas": true, + "minHeight": true, + "widgetId": true, + "renderMode": true, + "fontFamily": true, + "borderRadius": true, + "isLoading": true, + "parentColumnSpace": true, + "parentRowSpace": true, + "leftColumn": true, + "rightColumn": true, + "topRow": true, + "bottomRow": true, + "parentId": true, + "dynamicBindingPathList": true + } + } + }, + "enhancements": true, + "gridGap": 0, + "listData": "[[{ \"name\": \"pawan\"}, { \"name\": \"Vivek\" }], [{ \"name\": \"Ashok\"}, {\"name\": \"rahul\"}]]", + "widgetName": "List1", + "children": [ + { + "isVisible": true, + "widgetName": "Canvas1", + "version": 1, + "detachFromLayout": true, + "type": "CANVAS_WIDGET", + "hideCard": true, + "displayName": "Canvas", + "key": "d2bft20owz", + "containerStyle": "none", + "canExtend": false, + "dropDisabled": true, + "openParentPropertyPane": true, + "noPad": true, + "children": [ + { + "isVisible": true, + "backgroundColor": "white", + "widgetName": "Container1", + "containerStyle": "card", + "borderColor": "transparent", + "borderWidth": "0", + "boxShadow": "{{appsmith.theme.boxShadow.appBoxShadow}}", + "animateLoading": true, + "children": [ + { + "isVisible": true, + "widgetName": "Canvas2", + "version": 1, + "detachFromLayout": true, + "type": "CANVAS_WIDGET", + "hideCard": true, + "displayName": "Canvas", + "key": "d2bft20owz", + "containerStyle": "none", + "canExtend": false, + "children": [ + { + "isVisible": true, + "defaultImage": "https://assets.appsmith.com/widgets/default.png", + "imageShape": "RECTANGLE", + "maxZoomLevel": 1, + "enableRotation": false, + "enableDownload": false, + "objectFit": "cover", + "image": "{{currentItem.img}}", + "widgetName": "Image1", + "version": 1, + "animateLoading": true, + "type": "IMAGE_WIDGET", + "hideCard": false, + "displayName": "Image", + "key": "vxcejy1m0c", + "iconSVG": "/static/media/icon.52d8fb96.svg", + "boxShadow": "none", + "dynamicBindingPathList": [ + { + "key": "image" + }, + { + "key": "borderRadius" + } + ], + "dynamicTriggerPathList": [], + "widgetId": "l3eyhgrus9", + "renderMode": "CANVAS", + "borderRadius": "{{appsmith.theme.borderRadius.appBorderRadius}}", + "isLoading": false, + "leftColumn": 0, + "rightColumn": 16, + "topRow": 0, + "bottomRow": 8, + "parentId": "ku59q894ll", + "logBlackList": { + "isVisible": true, + "defaultImage": true, + "imageShape": true, + "maxZoomLevel": true, + "enableRotation": true, + "enableDownload": true, + "objectFit": true, + "image": true, + "widgetName": true, + "version": true, + "animateLoading": true, + "type": true, + "hideCard": true, + "displayName": true, + "key": true, + "iconSVG": true, + "isCanvas": true, + "boxShadow": true, + "dynamicBindingPathList": true, + "dynamicTriggerPathList": true, + "minHeight": true, + "widgetId": true, + "renderMode": true, + "borderRadius": true, + "isLoading": true, + "parentColumnSpace": true, + "parentRowSpace": true, + "leftColumn": true, + "rightColumn": true, + "topRow": true, + "bottomRow": true, + "parentId": true + } + }, + { + "isVisible": true, + "text": "{{currentItem.name}}", + "fontSize": "1rem", + "fontStyle": "BOLD", + "textAlign": "LEFT", + "textColor": "#231F20", + "truncateButtonColor": "#FFC13D", + "widgetName": "Text1", + "shouldTruncate": false, + "overflow": "NONE", + "version": 1, + "animateLoading": true, + "type": "TEXT_WIDGET", + "hideCard": false, + "displayName": "Text", + "key": "yca4fpjxb9", + "iconSVG": "/static/media/icon.97c59b52.svg", + "textStyle": "HEADING", + "boxShadow": "none", + "dynamicBindingPathList": [ + { + "key": "text" + }, + { + "key": "fontFamily" + }, + { + "key": "borderRadius" + } + ], + "dynamicTriggerPathList": [], + "widgetId": "xvuk7zw6i2", + "renderMode": "CANVAS", + "fontFamily": "{{appsmith.theme.fontFamily.appFont}}", + "borderRadius": "{{appsmith.theme.borderRadius.appBorderRadius}}", + "isLoading": false, + "leftColumn": 16, + "rightColumn": 28, + "topRow": 0, + "bottomRow": 4, + "parentId": "ku59q894ll", + "logBlackList": { + "isVisible": true, + "text": true, + "fontSize": true, + "fontStyle": true, + "textAlign": true, + "textColor": true, + "truncateButtonColor": true, + "widgetName": true, + "shouldTruncate": true, + "overflow": true, + "version": true, + "animateLoading": true, + "type": true, + "hideCard": true, + "displayName": true, + "key": true, + "iconSVG": true, + "isCanvas": true, + "textStyle": true, + "boxShadow": true, + "dynamicBindingPathList": true, + "dynamicTriggerPathList": true, + "minHeight": true, + "widgetId": true, + "renderMode": true, + "fontFamily": true, + "borderRadius": true, + "isLoading": true, + "parentColumnSpace": true, + "parentRowSpace": true, + "leftColumn": true, + "rightColumn": true, + "topRow": true, + "bottomRow": true, + "parentId": true + } + }, + { + "isVisible": true, + "text": "{{currentItem.id}}", + "fontSize": "1rem", + "fontStyle": "BOLD", + "textAlign": "LEFT", + "textColor": "#231F20", + "truncateButtonColor": "#FFC13D", + "widgetName": "Text2", + "shouldTruncate": false, + "overflow": "NONE", + "version": 1, + "animateLoading": true, + "type": "TEXT_WIDGET", + "hideCard": false, + "displayName": "Text", + "key": "yca4fpjxb9", + "iconSVG": "/static/media/icon.97c59b52.svg", + "textStyle": "BODY", + "boxShadow": "none", + "dynamicBindingPathList": [ + { + "key": "text" + }, + { + "key": "fontFamily" + }, + { + "key": "borderRadius" + } + ], + "dynamicTriggerPathList": [], + "widgetId": "i9cqbzdsxl", + "renderMode": "CANVAS", + "fontFamily": "{{appsmith.theme.fontFamily.appFont}}", + "borderRadius": "{{appsmith.theme.borderRadius.appBorderRadius}}", + "isLoading": false, + "leftColumn": 16, + "rightColumn": 24, + "topRow": 4, + "bottomRow": 8, + "parentId": "ku59q894ll", + "logBlackList": { + "isVisible": true, + "text": true, + "fontSize": true, + "fontStyle": true, + "textAlign": true, + "textColor": true, + "truncateButtonColor": true, + "widgetName": true, + "shouldTruncate": true, + "overflow": true, + "version": true, + "animateLoading": true, + "type": true, + "hideCard": true, + "displayName": true, + "key": true, + "iconSVG": true, + "isCanvas": true, + "textStyle": true, + "boxShadow": true, + "dynamicBindingPathList": true, + "dynamicTriggerPathList": true, + "minHeight": true, + "widgetId": true, + "renderMode": true, + "fontFamily": true, + "borderRadius": true, + "isLoading": true, + "parentColumnSpace": true, + "parentRowSpace": true, + "leftColumn": true, + "rightColumn": true, + "topRow": true, + "bottomRow": true, + "parentId": true + } + }, + { + "isVisible": true, + "text": "{{currentItem.map(item => item.name).join(\",\")}}", + "fontSize": "1rem", + "fontStyle": "BOLD", + "textAlign": "LEFT", + "textColor": "#231F20", + "truncateButtonColor": "#FFC13D", + "widgetName": "Text3", + "shouldTruncate": false, + "overflow": "NONE", + "version": 1, + "animateLoading": true, + "type": "TEXT_WIDGET", + "hideCard": false, + "displayName": "Text", + "key": "yca4fpjxb9", + "iconSVG": "/static/media/icon.97c59b52.svg", + "widgetId": "jmhrzoucgs", + "renderMode": "CANVAS", + "fontFamily": "{{appsmith.theme.fontFamily.appFont}}", + "borderRadius": "{{appsmith.theme.borderRadius.appBorderRadius}}", + "isLoading": false, + "parentColumnSpace": 5.6796875, + "parentRowSpace": 10, + "leftColumn": 38, + "rightColumn": 54, + "topRow": 1, + "bottomRow": 5, + "parentId": "ku59q894ll", + "dynamicBindingPathList": [ + { + "key": "fontFamily" + }, + { + "key": "borderRadius" + }, + { + "key": "text" + } + ], + "logBlackList": { + "isVisible": true, + "text": true, + "fontSize": true, + "fontStyle": true, + "textAlign": true, + "textColor": true, + "truncateButtonColor": true, + "widgetName": true, + "shouldTruncate": true, + "overflow": true, + "version": true, + "animateLoading": true, + "type": true, + "hideCard": true, + "displayName": true, + "key": true, + "iconSVG": true, + "isCanvas": true, + "minHeight": true, + "widgetId": true, + "renderMode": true, + "fontFamily": true, + "borderRadius": true, + "isLoading": true, + "parentColumnSpace": true, + "parentRowSpace": true, + "leftColumn": true, + "rightColumn": true, + "topRow": true, + "bottomRow": true, + "parentId": true, + "dynamicBindingPathList": true + }, + "dynamicTriggerPathList": [] + } + ], + "minHeight": null, + "widgetId": "ku59q894ll", + "renderMode": "CANVAS", + "boxShadow": "none", + "borderRadius": "{{appsmith.theme.borderRadius.appBorderRadius}}", + "accentColor": "{{appsmith.theme.colors.primaryColor}}", + "isLoading": false, + "parentColumnSpace": 1, + "parentRowSpace": 1, + "leftColumn": 0, + "rightColumn": null, + "topRow": 0, + "bottomRow": null, + "parentId": "q64lojs35o", + "dynamicBindingPathList": [ + { + "key": "borderRadius" + }, + { + "key": "accentColor" + } + ] + } + ], + "version": 1, + "type": "CONTAINER_WIDGET", + "hideCard": false, + "displayName": "Container", + "key": "py27820ubt", + "iconSVG": "/static/media/icon.1977dca3.svg", + "isCanvas": true, + "dragDisabled": true, + "isDeletable": false, + "disallowCopy": true, + "disablePropertyPane": true, + "openParentPropertyPane": true, + "widgetId": "q64lojs35o", + "renderMode": "CANVAS", + "borderRadius": "{{appsmith.theme.borderRadius.appBorderRadius}}", + "isLoading": false, + "leftColumn": 0, + "rightColumn": 64, + "topRow": 0, + "bottomRow": 12, + "parentId": "no8tmrnpax", + "dynamicBindingPathList": [ + { + "key": "borderRadius" + }, + { + "key": "boxShadow" + } + ] + } + ], + "minHeight": 400, + "widgetId": "no8tmrnpax", + "renderMode": "CANVAS", + "boxShadow": "none", + "borderRadius": "{{appsmith.theme.borderRadius.appBorderRadius}}", + "accentColor": "{{appsmith.theme.colors.primaryColor}}", + "isLoading": false, + "parentColumnSpace": 1, + "parentRowSpace": 1, + "leftColumn": 0, + "rightColumn": 391.5, + "topRow": 0, + "bottomRow": 400, + "parentId": "hvt7qfqiqj", + "dynamicBindingPathList": [ + { + "key": "borderRadius" + }, + { + "key": "accentColor" + } + ] + } + ], + "type": "LIST_WIDGET", + "hideCard": false, + "displayName": "List", + "key": "ux6kqofl7o", + "iconSVG": "/static/media/icon.9925ee17.svg", + "isCanvas": true, + "widgetId": "hvt7qfqiqj", + "renderMode": "CANVAS", + "accentColor": "{{appsmith.theme.colors.primaryColor}}", + "borderRadius": "{{appsmith.theme.borderRadius.appBorderRadius}}", + "boxShadow": "{{appsmith.theme.boxShadow.appBoxShadow}}", + "isLoading": false, + "parentColumnSpace": 16.3125, + "parentRowSpace": 10, + "leftColumn": 14, + "rightColumn": 38, + "topRow": 10, + "bottomRow": 50, + "parentId": "0", + "dynamicBindingPathList": [ + { + "key": "accentColor" + }, + { + "key": "borderRadius" + }, + { + "key": "boxShadow" + }, + { + "key": "template.Image1.image" + }, + { + "key": "template.Text1.text" + }, + { + "key": "template.Text2.text" + }, + { + "key": "template.Text3.text" + } + ], + "privateWidgets": { + "Image1": true, + "Text1": true, + "Text2": true, + "Text3": true + }, + "dynamicTriggerPathList": [] + } + ] + } +} \ No newline at end of file diff --git a/app/client/cypress/fixtures/listRegression3Dsl.json b/app/client/cypress/fixtures/listRegression3Dsl.json new file mode 100644 index 000000000000..1a9993812b2c --- /dev/null +++ b/app/client/cypress/fixtures/listRegression3Dsl.json @@ -0,0 +1,709 @@ +{ + "dsl": { + "widgetName": "MainContainer", + "backgroundColor": "none", + "rightColumn": 4896, + "snapColumns": 64, + "detachFromLayout": true, + "widgetId": "0", + "topRow": 0, + "bottomRow": 5000, + "containerStyle": "none", + "snapRows": 125, + "parentRowSpace": 1, + "type": "CANVAS_WIDGET", + "canExtend": true, + "version": 58, + "minHeight": 1292, + "dynamicTriggerPathList": [], + "parentColumnSpace": 1, + "dynamicBindingPathList": [], + "leftColumn": 0, + "children": [ + { + "isVisible": true, + "backgroundColor": "transparent", + "itemBackgroundColor": "#FFFFFF", + "animateLoading": true, + "gridType": "vertical", + "template": { + "Image1": { + "isVisible": true, + "defaultImage": "https://assets.appsmith.com/widgets/default.png", + "imageShape": "RECTANGLE", + "maxZoomLevel": 1, + "enableRotation": false, + "enableDownload": false, + "objectFit": "cover", + "image": "{{List1.listData.map((currentItem) => currentItem.img)}}", + "widgetName": "Image1", + "version": 1, + "animateLoading": true, + "type": "IMAGE_WIDGET", + "hideCard": false, + "displayName": "Image", + "key": "2hwu01ugse", + "iconSVG": "/static/media/icon.52d8fb96.svg", + "boxShadow": "none", + "dynamicBindingPathList": [ + { + "key": "image" + }, + { + "key": "borderRadius" + } + ], + "dynamicTriggerPathList": [], + "widgetId": "tubj5wpy4d", + "renderMode": "CANVAS", + "borderRadius": "{{appsmith.theme.borderRadius.appBorderRadius}}", + "isLoading": false, + "leftColumn": 0, + "rightColumn": 16, + "topRow": 0, + "bottomRow": 8, + "parentId": "59a6hm4ax9" + }, + "Text1": { + "isVisible": true, + "text": "{{List1.listData.map((currentItem) => currentItem.name)}}", + "fontSize": "1rem", + "fontStyle": "BOLD", + "textAlign": "LEFT", + "textColor": "#231F20", + "truncateButtonColor": "#FFC13D", + "widgetName": "Text1", + "shouldTruncate": false, + "overflow": "NONE", + "version": 1, + "animateLoading": true, + "type": "TEXT_WIDGET", + "hideCard": false, + "displayName": "Text", + "key": "xhyjgpwa7w", + "iconSVG": "/static/media/icon.97c59b52.svg", + "textStyle": "HEADING", + "boxShadow": "none", + "dynamicBindingPathList": [ + { + "key": "text" + }, + { + "key": "fontFamily" + }, + { + "key": "borderRadius" + } + ], + "dynamicTriggerPathList": [], + "widgetId": "ciwmi8h81d", + "renderMode": "CANVAS", + "fontFamily": "{{appsmith.theme.fontFamily.appFont}}", + "borderRadius": "{{appsmith.theme.borderRadius.appBorderRadius}}", + "isLoading": false, + "leftColumn": 16, + "rightColumn": 28, + "topRow": 0, + "bottomRow": 4, + "parentId": "59a6hm4ax9" + }, + "Text2": { + "isVisible": true, + "text": "{{List1.listData.map((currentItem) => currentItem.id)}}", + "fontSize": "1rem", + "fontStyle": "BOLD", + "textAlign": "LEFT", + "textColor": "#231F20", + "truncateButtonColor": "#FFC13D", + "widgetName": "Text2", + "shouldTruncate": false, + "overflow": "NONE", + "version": 1, + "animateLoading": true, + "type": "TEXT_WIDGET", + "hideCard": false, + "displayName": "Text", + "key": "xhyjgpwa7w", + "iconSVG": "/static/media/icon.97c59b52.svg", + "textStyle": "BODY", + "boxShadow": "none", + "dynamicBindingPathList": [ + { + "key": "text" + }, + { + "key": "fontFamily" + }, + { + "key": "borderRadius" + } + ], + "dynamicTriggerPathList": [], + "widgetId": "ike7ax9wrb", + "renderMode": "CANVAS", + "fontFamily": "{{appsmith.theme.fontFamily.appFont}}", + "borderRadius": "{{appsmith.theme.borderRadius.appBorderRadius}}", + "isLoading": false, + "leftColumn": 16, + "rightColumn": 24, + "topRow": 4, + "bottomRow": 8, + "parentId": "59a6hm4ax9" + }, + "Text3": { + "isVisible": true, + "text": "{{List1.listData.map((currentItem, currentIndex) => {\n return (function(){\n return currentItem.name;\n })();\n })}}", + "fontSize": "1rem", + "fontStyle": "BOLD", + "textAlign": "LEFT", + "textColor": "#231F20", + "truncateButtonColor": "#FFC13D", + "widgetName": "Text3", + "shouldTruncate": false, + "overflow": "NONE", + "version": 1, + "animateLoading": true, + "type": "TEXT_WIDGET", + "hideCard": false, + "displayName": "Text", + "key": "xhyjgpwa7w", + "iconSVG": "/static/media/icon.97c59b52.svg", + "widgetId": "5uxmcg4ap0", + "renderMode": "CANVAS", + "fontFamily": "{{appsmith.theme.fontFamily.appFont}}", + "borderRadius": "{{appsmith.theme.borderRadius.appBorderRadius}}", + "isLoading": false, + "parentColumnSpace": 5.6796875, + "parentRowSpace": 10, + "leftColumn": 42, + "rightColumn": 58, + "topRow": 1, + "bottomRow": 5, + "parentId": "59a6hm4ax9", + "dynamicBindingPathList": [ + { + "key": "fontFamily" + }, + { + "key": "borderRadius" + } + ], + "logBlackList": { + "isVisible": true, + "text": true, + "fontSize": true, + "fontStyle": true, + "textAlign": true, + "textColor": true, + "truncateButtonColor": true, + "widgetName": true, + "shouldTruncate": true, + "overflow": true, + "version": true, + "animateLoading": true, + "type": true, + "hideCard": true, + "displayName": true, + "key": true, + "iconSVG": true, + "isCanvas": true, + "minHeight": true, + "widgetId": true, + "renderMode": true, + "fontFamily": true, + "borderRadius": true, + "isLoading": true, + "parentColumnSpace": true, + "parentRowSpace": true, + "leftColumn": true, + "rightColumn": true, + "topRow": true, + "bottomRow": true, + "parentId": true, + "dynamicBindingPathList": true + } + } + }, + "enhancements": true, + "gridGap": 0, + "listData": "[{ \"name\": \"pawan\"}, { \"name\": \"Vivek\" }]", + "widgetName": "List1", + "children": [ + { + "isVisible": true, + "widgetName": "Canvas1", + "version": 1, + "detachFromLayout": true, + "type": "CANVAS_WIDGET", + "hideCard": true, + "displayName": "Canvas", + "key": "he0ujhg80o", + "containerStyle": "none", + "canExtend": false, + "dropDisabled": true, + "openParentPropertyPane": true, + "noPad": true, + "children": [ + { + "isVisible": true, + "backgroundColor": "white", + "widgetName": "Container1", + "containerStyle": "card", + "borderColor": "transparent", + "borderWidth": "0", + "boxShadow": "{{appsmith.theme.boxShadow.appBoxShadow}}", + "animateLoading": true, + "children": [ + { + "isVisible": true, + "widgetName": "Canvas2", + "version": 1, + "detachFromLayout": true, + "type": "CANVAS_WIDGET", + "hideCard": true, + "displayName": "Canvas", + "key": "he0ujhg80o", + "containerStyle": "none", + "canExtend": false, + "children": [ + { + "isVisible": true, + "defaultImage": "https://assets.appsmith.com/widgets/default.png", + "imageShape": "RECTANGLE", + "maxZoomLevel": 1, + "enableRotation": false, + "enableDownload": false, + "objectFit": "cover", + "image": "{{currentItem.img}}", + "widgetName": "Image1", + "version": 1, + "animateLoading": true, + "type": "IMAGE_WIDGET", + "hideCard": false, + "displayName": "Image", + "key": "2hwu01ugse", + "iconSVG": "/static/media/icon.52d8fb96.svg", + "boxShadow": "none", + "dynamicBindingPathList": [ + { + "key": "image" + }, + { + "key": "borderRadius" + } + ], + "dynamicTriggerPathList": [], + "widgetId": "tubj5wpy4d", + "renderMode": "CANVAS", + "borderRadius": "{{appsmith.theme.borderRadius.appBorderRadius}}", + "isLoading": false, + "leftColumn": 0, + "rightColumn": 16, + "topRow": 0, + "bottomRow": 8, + "parentId": "59a6hm4ax9", + "logBlackList": { + "isVisible": true, + "defaultImage": true, + "imageShape": true, + "maxZoomLevel": true, + "enableRotation": true, + "enableDownload": true, + "objectFit": true, + "image": true, + "widgetName": true, + "version": true, + "animateLoading": true, + "type": true, + "hideCard": true, + "displayName": true, + "key": true, + "iconSVG": true, + "isCanvas": true, + "boxShadow": true, + "dynamicBindingPathList": true, + "dynamicTriggerPathList": true, + "minHeight": true, + "widgetId": true, + "renderMode": true, + "borderRadius": true, + "isLoading": true, + "parentColumnSpace": true, + "parentRowSpace": true, + "leftColumn": true, + "rightColumn": true, + "topRow": true, + "bottomRow": true, + "parentId": true + } + }, + { + "isVisible": true, + "text": "{{currentItem.name}}", + "fontSize": "1rem", + "fontStyle": "BOLD", + "textAlign": "LEFT", + "textColor": "#231F20", + "truncateButtonColor": "#FFC13D", + "widgetName": "Text1", + "shouldTruncate": false, + "overflow": "NONE", + "version": 1, + "animateLoading": true, + "type": "TEXT_WIDGET", + "hideCard": false, + "displayName": "Text", + "key": "xhyjgpwa7w", + "iconSVG": "/static/media/icon.97c59b52.svg", + "textStyle": "HEADING", + "boxShadow": "none", + "dynamicBindingPathList": [ + { + "key": "text" + }, + { + "key": "fontFamily" + }, + { + "key": "borderRadius" + } + ], + "dynamicTriggerPathList": [], + "widgetId": "ciwmi8h81d", + "renderMode": "CANVAS", + "fontFamily": "{{appsmith.theme.fontFamily.appFont}}", + "borderRadius": "{{appsmith.theme.borderRadius.appBorderRadius}}", + "isLoading": false, + "leftColumn": 16, + "rightColumn": 28, + "topRow": 0, + "bottomRow": 4, + "parentId": "59a6hm4ax9", + "logBlackList": { + "isVisible": true, + "text": true, + "fontSize": true, + "fontStyle": true, + "textAlign": true, + "textColor": true, + "truncateButtonColor": true, + "widgetName": true, + "shouldTruncate": true, + "overflow": true, + "version": true, + "animateLoading": true, + "type": true, + "hideCard": true, + "displayName": true, + "key": true, + "iconSVG": true, + "isCanvas": true, + "textStyle": true, + "boxShadow": true, + "dynamicBindingPathList": true, + "dynamicTriggerPathList": true, + "minHeight": true, + "widgetId": true, + "renderMode": true, + "fontFamily": true, + "borderRadius": true, + "isLoading": true, + "parentColumnSpace": true, + "parentRowSpace": true, + "leftColumn": true, + "rightColumn": true, + "topRow": true, + "bottomRow": true, + "parentId": true + } + }, + { + "isVisible": true, + "text": "{{currentItem.id}}", + "fontSize": "1rem", + "fontStyle": "BOLD", + "textAlign": "LEFT", + "textColor": "#231F20", + "truncateButtonColor": "#FFC13D", + "widgetName": "Text2", + "shouldTruncate": false, + "overflow": "NONE", + "version": 1, + "animateLoading": true, + "type": "TEXT_WIDGET", + "hideCard": false, + "displayName": "Text", + "key": "xhyjgpwa7w", + "iconSVG": "/static/media/icon.97c59b52.svg", + "textStyle": "BODY", + "boxShadow": "none", + "dynamicBindingPathList": [ + { + "key": "text" + }, + { + "key": "fontFamily" + }, + { + "key": "borderRadius" + } + ], + "dynamicTriggerPathList": [], + "widgetId": "ike7ax9wrb", + "renderMode": "CANVAS", + "fontFamily": "{{appsmith.theme.fontFamily.appFont}}", + "borderRadius": "{{appsmith.theme.borderRadius.appBorderRadius}}", + "isLoading": false, + "leftColumn": 16, + "rightColumn": 24, + "topRow": 4, + "bottomRow": 8, + "parentId": "59a6hm4ax9", + "logBlackList": { + "isVisible": true, + "text": true, + "fontSize": true, + "fontStyle": true, + "textAlign": true, + "textColor": true, + "truncateButtonColor": true, + "widgetName": true, + "shouldTruncate": true, + "overflow": true, + "version": true, + "animateLoading": true, + "type": true, + "hideCard": true, + "displayName": true, + "key": true, + "iconSVG": true, + "isCanvas": true, + "textStyle": true, + "boxShadow": true, + "dynamicBindingPathList": true, + "dynamicTriggerPathList": true, + "minHeight": true, + "widgetId": true, + "renderMode": true, + "fontFamily": true, + "borderRadius": true, + "isLoading": true, + "parentColumnSpace": true, + "parentRowSpace": true, + "leftColumn": true, + "rightColumn": true, + "topRow": true, + "bottomRow": true, + "parentId": true + } + }, + { + "isVisible": true, + "text": "{{currentItem.name}}", + "fontSize": "1rem", + "fontStyle": "BOLD", + "textAlign": "LEFT", + "textColor": "#231F20", + "truncateButtonColor": "#FFC13D", + "widgetName": "Text3", + "shouldTruncate": false, + "overflow": "NONE", + "version": 1, + "animateLoading": true, + "type": "TEXT_WIDGET", + "hideCard": false, + "displayName": "Text", + "key": "xhyjgpwa7w", + "iconSVG": "/static/media/icon.97c59b52.svg", + "widgetId": "5uxmcg4ap0", + "renderMode": "CANVAS", + "fontFamily": "{{appsmith.theme.fontFamily.appFont}}", + "borderRadius": "{{appsmith.theme.borderRadius.appBorderRadius}}", + "isLoading": false, + "parentColumnSpace": 5.6796875, + "parentRowSpace": 10, + "leftColumn": 42, + "rightColumn": 58, + "topRow": 1, + "bottomRow": 5, + "parentId": "59a6hm4ax9", + "dynamicBindingPathList": [ + { + "key": "fontFamily" + }, + { + "key": "borderRadius" + }, + { + "key": "text" + } + ], + "logBlackList": { + "isVisible": true, + "text": true, + "fontSize": true, + "fontStyle": true, + "textAlign": true, + "textColor": true, + "truncateButtonColor": true, + "widgetName": true, + "shouldTruncate": true, + "overflow": true, + "version": true, + "animateLoading": true, + "type": true, + "hideCard": true, + "displayName": true, + "key": true, + "iconSVG": true, + "isCanvas": true, + "minHeight": true, + "widgetId": true, + "renderMode": true, + "fontFamily": true, + "borderRadius": true, + "isLoading": true, + "parentColumnSpace": true, + "parentRowSpace": true, + "leftColumn": true, + "rightColumn": true, + "topRow": true, + "bottomRow": true, + "parentId": true, + "dynamicBindingPathList": true + }, + "dynamicTriggerPathList": [] + } + ], + "minHeight": null, + "widgetId": "59a6hm4ax9", + "renderMode": "CANVAS", + "boxShadow": "none", + "borderRadius": "{{appsmith.theme.borderRadius.appBorderRadius}}", + "accentColor": "{{appsmith.theme.colors.primaryColor}}", + "isLoading": false, + "parentColumnSpace": 1, + "parentRowSpace": 1, + "leftColumn": 0, + "rightColumn": null, + "topRow": 0, + "bottomRow": null, + "parentId": "dcc7z0p61g", + "dynamicBindingPathList": [ + { + "key": "borderRadius" + }, + { + "key": "accentColor" + } + ] + } + ], + "version": 1, + "type": "CONTAINER_WIDGET", + "hideCard": false, + "displayName": "Container", + "key": "ivukmk95oe", + "iconSVG": "/static/media/icon.1977dca3.svg", + "isCanvas": true, + "dragDisabled": true, + "isDeletable": false, + "disallowCopy": true, + "disablePropertyPane": true, + "openParentPropertyPane": true, + "widgetId": "dcc7z0p61g", + "renderMode": "CANVAS", + "borderRadius": "{{appsmith.theme.borderRadius.appBorderRadius}}", + "isLoading": false, + "leftColumn": 0, + "rightColumn": 64, + "topRow": 0, + "bottomRow": 12, + "parentId": "pzvvqub7cs", + "dynamicBindingPathList": [ + { + "key": "borderRadius" + }, + { + "key": "boxShadow" + } + ] + } + ], + "minHeight": 400, + "widgetId": "pzvvqub7cs", + "renderMode": "CANVAS", + "boxShadow": "none", + "borderRadius": "{{appsmith.theme.borderRadius.appBorderRadius}}", + "accentColor": "{{appsmith.theme.colors.primaryColor}}", + "isLoading": false, + "parentColumnSpace": 1, + "parentRowSpace": 1, + "leftColumn": 0, + "rightColumn": 391.5, + "topRow": 0, + "bottomRow": 400, + "parentId": "p87af6bvkx", + "dynamicBindingPathList": [ + { + "key": "borderRadius" + }, + { + "key": "accentColor" + } + ] + } + ], + "type": "LIST_WIDGET", + "hideCard": false, + "displayName": "List", + "key": "zttei3njnj", + "iconSVG": "/static/media/icon.9925ee17.svg", + "isCanvas": true, + "widgetId": "p87af6bvkx", + "renderMode": "CANVAS", + "accentColor": "{{appsmith.theme.colors.primaryColor}}", + "borderRadius": "{{appsmith.theme.borderRadius.appBorderRadius}}", + "boxShadow": "{{appsmith.theme.boxShadow.appBoxShadow}}", + "isLoading": false, + "parentColumnSpace": 16.3125, + "parentRowSpace": 10, + "leftColumn": 16, + "rightColumn": 40, + "topRow": 4, + "bottomRow": 44, + "parentId": "0", + "dynamicBindingPathList": [ + { + "key": "accentColor" + }, + { + "key": "borderRadius" + }, + { + "key": "boxShadow" + }, + { + "key": "template.Image1.image" + }, + { + "key": "template.Text1.text" + }, + { + "key": "template.Text2.text" + }, + { + "key": "template.Text3.text" + } + ], + "privateWidgets": { + "Image1": true, + "Text1": true, + "Text2": true, + "Text3": true + }, + "dynamicTriggerPathList": [] + } + ] + } +} \ No newline at end of file diff --git a/app/client/cypress/fixtures/listRegressionDsl.json b/app/client/cypress/fixtures/listRegressionDsl.json new file mode 100644 index 000000000000..eaa50d68c9fd --- /dev/null +++ b/app/client/cypress/fixtures/listRegressionDsl.json @@ -0,0 +1,708 @@ +{ + "dsl": { + "widgetName": "MainContainer", + "backgroundColor": "none", + "rightColumn": 776, + "snapColumns": 64, + "detachFromLayout": true, + "widgetId": "0", + "topRow": 0, + "bottomRow": 1320, + "containerStyle": "none", + "snapRows": 125, + "parentRowSpace": 1, + "type": "CANVAS_WIDGET", + "canExtend": true, + "version": 58, + "minHeight": 1292, + "parentColumnSpace": 1, + "dynamicBindingPathList": [], + "leftColumn": 0, + "children": [ + { + "isVisible": true, + "backgroundColor": "transparent", + "itemBackgroundColor": "#FFFFFF", + "animateLoading": true, + "gridType": "vertical", + "template": { + "Image1": { + "isVisible": true, + "defaultImage": "https://assets.appsmith.com/widgets/default.png", + "imageShape": "RECTANGLE", + "maxZoomLevel": 1, + "enableRotation": false, + "enableDownload": false, + "objectFit": "cover", + "image": "{{List1.listData.map((currentItem) => currentItem.img)}}", + "widgetName": "Image1", + "version": 1, + "animateLoading": true, + "type": "IMAGE_WIDGET", + "hideCard": false, + "displayName": "Image", + "key": "vxcejy1m0c", + "iconSVG": "/static/media/icon.52d8fb96.svg", + "boxShadow": "none", + "dynamicBindingPathList": [ + { + "key": "image" + }, + { + "key": "borderRadius" + } + ], + "dynamicTriggerPathList": [], + "widgetId": "l3eyhgrus9", + "renderMode": "CANVAS", + "borderRadius": "{{appsmith.theme.borderRadius.appBorderRadius}}", + "isLoading": false, + "leftColumn": 0, + "rightColumn": 16, + "topRow": 0, + "bottomRow": 8, + "parentId": "ku59q894ll" + }, + "Text1": { + "isVisible": true, + "text": "{{List1.listData.map((currentItem) => currentItem.name)}}", + "fontSize": "1rem", + "fontStyle": "BOLD", + "textAlign": "LEFT", + "textColor": "#231F20", + "truncateButtonColor": "#FFC13D", + "widgetName": "Text1", + "shouldTruncate": false, + "overflow": "NONE", + "version": 1, + "animateLoading": true, + "type": "TEXT_WIDGET", + "hideCard": false, + "displayName": "Text", + "key": "yca4fpjxb9", + "iconSVG": "/static/media/icon.97c59b52.svg", + "textStyle": "HEADING", + "boxShadow": "none", + "dynamicBindingPathList": [ + { + "key": "text" + }, + { + "key": "fontFamily" + }, + { + "key": "borderRadius" + } + ], + "dynamicTriggerPathList": [], + "widgetId": "xvuk7zw6i2", + "renderMode": "CANVAS", + "fontFamily": "{{appsmith.theme.fontFamily.appFont}}", + "borderRadius": "{{appsmith.theme.borderRadius.appBorderRadius}}", + "isLoading": false, + "leftColumn": 16, + "rightColumn": 28, + "topRow": 0, + "bottomRow": 4, + "parentId": "ku59q894ll" + }, + "Text2": { + "isVisible": true, + "text": "{{List1.listData.map((currentItem) => currentItem.id)}}", + "fontSize": "1rem", + "fontStyle": "BOLD", + "textAlign": "LEFT", + "textColor": "#231F20", + "truncateButtonColor": "#FFC13D", + "widgetName": "Text2", + "shouldTruncate": false, + "overflow": "NONE", + "version": 1, + "animateLoading": true, + "type": "TEXT_WIDGET", + "hideCard": false, + "displayName": "Text", + "key": "yca4fpjxb9", + "iconSVG": "/static/media/icon.97c59b52.svg", + "textStyle": "BODY", + "boxShadow": "none", + "dynamicBindingPathList": [ + { + "key": "text" + }, + { + "key": "fontFamily" + }, + { + "key": "borderRadius" + } + ], + "dynamicTriggerPathList": [], + "widgetId": "i9cqbzdsxl", + "renderMode": "CANVAS", + "fontFamily": "{{appsmith.theme.fontFamily.appFont}}", + "borderRadius": "{{appsmith.theme.borderRadius.appBorderRadius}}", + "isLoading": false, + "leftColumn": 16, + "rightColumn": 24, + "topRow": 4, + "bottomRow": 8, + "parentId": "ku59q894ll" + }, + "Text3": { + "isVisible": true, + "text": "{{List1.listData.map((currentItem, currentIndex) => {\n return (function(){\n return currentItem;\n })();\n })}}", + "fontSize": "1rem", + "fontStyle": "BOLD", + "textAlign": "LEFT", + "textColor": "#231F20", + "truncateButtonColor": "#FFC13D", + "widgetName": "Text3", + "shouldTruncate": false, + "overflow": "NONE", + "version": 1, + "animateLoading": true, + "type": "TEXT_WIDGET", + "hideCard": false, + "displayName": "Text", + "key": "yca4fpjxb9", + "iconSVG": "/static/media/icon.97c59b52.svg", + "widgetId": "jmhrzoucgs", + "renderMode": "CANVAS", + "fontFamily": "{{appsmith.theme.fontFamily.appFont}}", + "borderRadius": "{{appsmith.theme.borderRadius.appBorderRadius}}", + "isLoading": false, + "parentColumnSpace": 5.6796875, + "parentRowSpace": 10, + "leftColumn": 38, + "rightColumn": 54, + "topRow": 1, + "bottomRow": 5, + "parentId": "ku59q894ll", + "dynamicBindingPathList": [ + { + "key": "fontFamily" + }, + { + "key": "borderRadius" + } + ], + "logBlackList": { + "isVisible": true, + "text": true, + "fontSize": true, + "fontStyle": true, + "textAlign": true, + "textColor": true, + "truncateButtonColor": true, + "widgetName": true, + "shouldTruncate": true, + "overflow": true, + "version": true, + "animateLoading": true, + "type": true, + "hideCard": true, + "displayName": true, + "key": true, + "iconSVG": true, + "isCanvas": true, + "minHeight": true, + "widgetId": true, + "renderMode": true, + "fontFamily": true, + "borderRadius": true, + "isLoading": true, + "parentColumnSpace": true, + "parentRowSpace": true, + "leftColumn": true, + "rightColumn": true, + "topRow": true, + "bottomRow": true, + "parentId": true, + "dynamicBindingPathList": true + } + } + }, + "enhancements": true, + "gridGap": 0, + "listData": "[\"Pawan\", \"Vivek\"]", + "widgetName": "List1", + "children": [ + { + "isVisible": true, + "widgetName": "Canvas1", + "version": 1, + "detachFromLayout": true, + "type": "CANVAS_WIDGET", + "hideCard": true, + "displayName": "Canvas", + "key": "d2bft20owz", + "containerStyle": "none", + "canExtend": false, + "dropDisabled": true, + "openParentPropertyPane": true, + "noPad": true, + "children": [ + { + "isVisible": true, + "backgroundColor": "white", + "widgetName": "Container1", + "containerStyle": "card", + "borderColor": "transparent", + "borderWidth": "0", + "boxShadow": "{{appsmith.theme.boxShadow.appBoxShadow}}", + "animateLoading": true, + "children": [ + { + "isVisible": true, + "widgetName": "Canvas2", + "version": 1, + "detachFromLayout": true, + "type": "CANVAS_WIDGET", + "hideCard": true, + "displayName": "Canvas", + "key": "d2bft20owz", + "containerStyle": "none", + "canExtend": false, + "children": [ + { + "isVisible": true, + "defaultImage": "https://assets.appsmith.com/widgets/default.png", + "imageShape": "RECTANGLE", + "maxZoomLevel": 1, + "enableRotation": false, + "enableDownload": false, + "objectFit": "cover", + "image": "{{currentItem.img}}", + "widgetName": "Image1", + "version": 1, + "animateLoading": true, + "type": "IMAGE_WIDGET", + "hideCard": false, + "displayName": "Image", + "key": "vxcejy1m0c", + "iconSVG": "/static/media/icon.52d8fb96.svg", + "boxShadow": "none", + "dynamicBindingPathList": [ + { + "key": "image" + }, + { + "key": "borderRadius" + } + ], + "dynamicTriggerPathList": [], + "widgetId": "l3eyhgrus9", + "renderMode": "CANVAS", + "borderRadius": "{{appsmith.theme.borderRadius.appBorderRadius}}", + "isLoading": false, + "leftColumn": 0, + "rightColumn": 16, + "topRow": 0, + "bottomRow": 8, + "parentId": "ku59q894ll", + "logBlackList": { + "isVisible": true, + "defaultImage": true, + "imageShape": true, + "maxZoomLevel": true, + "enableRotation": true, + "enableDownload": true, + "objectFit": true, + "image": true, + "widgetName": true, + "version": true, + "animateLoading": true, + "type": true, + "hideCard": true, + "displayName": true, + "key": true, + "iconSVG": true, + "isCanvas": true, + "boxShadow": true, + "dynamicBindingPathList": true, + "dynamicTriggerPathList": true, + "minHeight": true, + "widgetId": true, + "renderMode": true, + "borderRadius": true, + "isLoading": true, + "parentColumnSpace": true, + "parentRowSpace": true, + "leftColumn": true, + "rightColumn": true, + "topRow": true, + "bottomRow": true, + "parentId": true + } + }, + { + "isVisible": true, + "text": "{{currentItem.name}}", + "fontSize": "1rem", + "fontStyle": "BOLD", + "textAlign": "LEFT", + "textColor": "#231F20", + "truncateButtonColor": "#FFC13D", + "widgetName": "Text1", + "shouldTruncate": false, + "overflow": "NONE", + "version": 1, + "animateLoading": true, + "type": "TEXT_WIDGET", + "hideCard": false, + "displayName": "Text", + "key": "yca4fpjxb9", + "iconSVG": "/static/media/icon.97c59b52.svg", + "textStyle": "HEADING", + "boxShadow": "none", + "dynamicBindingPathList": [ + { + "key": "text" + }, + { + "key": "fontFamily" + }, + { + "key": "borderRadius" + } + ], + "dynamicTriggerPathList": [], + "widgetId": "xvuk7zw6i2", + "renderMode": "CANVAS", + "fontFamily": "{{appsmith.theme.fontFamily.appFont}}", + "borderRadius": "{{appsmith.theme.borderRadius.appBorderRadius}}", + "isLoading": false, + "leftColumn": 16, + "rightColumn": 28, + "topRow": 0, + "bottomRow": 4, + "parentId": "ku59q894ll", + "logBlackList": { + "isVisible": true, + "text": true, + "fontSize": true, + "fontStyle": true, + "textAlign": true, + "textColor": true, + "truncateButtonColor": true, + "widgetName": true, + "shouldTruncate": true, + "overflow": true, + "version": true, + "animateLoading": true, + "type": true, + "hideCard": true, + "displayName": true, + "key": true, + "iconSVG": true, + "isCanvas": true, + "textStyle": true, + "boxShadow": true, + "dynamicBindingPathList": true, + "dynamicTriggerPathList": true, + "minHeight": true, + "widgetId": true, + "renderMode": true, + "fontFamily": true, + "borderRadius": true, + "isLoading": true, + "parentColumnSpace": true, + "parentRowSpace": true, + "leftColumn": true, + "rightColumn": true, + "topRow": true, + "bottomRow": true, + "parentId": true + } + }, + { + "isVisible": true, + "text": "{{currentItem.id}}", + "fontSize": "1rem", + "fontStyle": "BOLD", + "textAlign": "LEFT", + "textColor": "#231F20", + "truncateButtonColor": "#FFC13D", + "widgetName": "Text2", + "shouldTruncate": false, + "overflow": "NONE", + "version": 1, + "animateLoading": true, + "type": "TEXT_WIDGET", + "hideCard": false, + "displayName": "Text", + "key": "yca4fpjxb9", + "iconSVG": "/static/media/icon.97c59b52.svg", + "textStyle": "BODY", + "boxShadow": "none", + "dynamicBindingPathList": [ + { + "key": "text" + }, + { + "key": "fontFamily" + }, + { + "key": "borderRadius" + } + ], + "dynamicTriggerPathList": [], + "widgetId": "i9cqbzdsxl", + "renderMode": "CANVAS", + "fontFamily": "{{appsmith.theme.fontFamily.appFont}}", + "borderRadius": "{{appsmith.theme.borderRadius.appBorderRadius}}", + "isLoading": false, + "leftColumn": 16, + "rightColumn": 24, + "topRow": 4, + "bottomRow": 8, + "parentId": "ku59q894ll", + "logBlackList": { + "isVisible": true, + "text": true, + "fontSize": true, + "fontStyle": true, + "textAlign": true, + "textColor": true, + "truncateButtonColor": true, + "widgetName": true, + "shouldTruncate": true, + "overflow": true, + "version": true, + "animateLoading": true, + "type": true, + "hideCard": true, + "displayName": true, + "key": true, + "iconSVG": true, + "isCanvas": true, + "textStyle": true, + "boxShadow": true, + "dynamicBindingPathList": true, + "dynamicTriggerPathList": true, + "minHeight": true, + "widgetId": true, + "renderMode": true, + "fontFamily": true, + "borderRadius": true, + "isLoading": true, + "parentColumnSpace": true, + "parentRowSpace": true, + "leftColumn": true, + "rightColumn": true, + "topRow": true, + "bottomRow": true, + "parentId": true + } + }, + { + "isVisible": true, + "text": "{{currentItem}}", + "fontSize": "1rem", + "fontStyle": "BOLD", + "textAlign": "LEFT", + "textColor": "#231F20", + "truncateButtonColor": "#FFC13D", + "widgetName": "Text3", + "shouldTruncate": false, + "overflow": "NONE", + "version": 1, + "animateLoading": true, + "type": "TEXT_WIDGET", + "hideCard": false, + "displayName": "Text", + "key": "yca4fpjxb9", + "iconSVG": "/static/media/icon.97c59b52.svg", + "widgetId": "jmhrzoucgs", + "renderMode": "CANVAS", + "fontFamily": "{{appsmith.theme.fontFamily.appFont}}", + "borderRadius": "{{appsmith.theme.borderRadius.appBorderRadius}}", + "isLoading": false, + "parentColumnSpace": 5.6796875, + "parentRowSpace": 10, + "leftColumn": 38, + "rightColumn": 54, + "topRow": 1, + "bottomRow": 5, + "parentId": "ku59q894ll", + "dynamicBindingPathList": [ + { + "key": "fontFamily" + }, + { + "key": "borderRadius" + }, + { + "key": "text" + } + ], + "logBlackList": { + "isVisible": true, + "text": true, + "fontSize": true, + "fontStyle": true, + "textAlign": true, + "textColor": true, + "truncateButtonColor": true, + "widgetName": true, + "shouldTruncate": true, + "overflow": true, + "version": true, + "animateLoading": true, + "type": true, + "hideCard": true, + "displayName": true, + "key": true, + "iconSVG": true, + "isCanvas": true, + "minHeight": true, + "widgetId": true, + "renderMode": true, + "fontFamily": true, + "borderRadius": true, + "isLoading": true, + "parentColumnSpace": true, + "parentRowSpace": true, + "leftColumn": true, + "rightColumn": true, + "topRow": true, + "bottomRow": true, + "parentId": true, + "dynamicBindingPathList": true + }, + "dynamicTriggerPathList": [] + } + ], + "minHeight": null, + "widgetId": "ku59q894ll", + "renderMode": "CANVAS", + "boxShadow": "none", + "borderRadius": "{{appsmith.theme.borderRadius.appBorderRadius}}", + "accentColor": "{{appsmith.theme.colors.primaryColor}}", + "isLoading": false, + "parentColumnSpace": 1, + "parentRowSpace": 1, + "leftColumn": 0, + "rightColumn": null, + "topRow": 0, + "bottomRow": null, + "parentId": "q64lojs35o", + "dynamicBindingPathList": [ + { + "key": "borderRadius" + }, + { + "key": "accentColor" + } + ] + } + ], + "version": 1, + "type": "CONTAINER_WIDGET", + "hideCard": false, + "displayName": "Container", + "key": "py27820ubt", + "iconSVG": "/static/media/icon.1977dca3.svg", + "isCanvas": true, + "dragDisabled": true, + "isDeletable": false, + "disallowCopy": true, + "disablePropertyPane": true, + "openParentPropertyPane": true, + "widgetId": "q64lojs35o", + "renderMode": "CANVAS", + "borderRadius": "{{appsmith.theme.borderRadius.appBorderRadius}}", + "isLoading": false, + "leftColumn": 0, + "rightColumn": 64, + "topRow": 0, + "bottomRow": 12, + "parentId": "no8tmrnpax", + "dynamicBindingPathList": [ + { + "key": "borderRadius" + }, + { + "key": "boxShadow" + } + ] + } + ], + "minHeight": 400, + "widgetId": "no8tmrnpax", + "renderMode": "CANVAS", + "boxShadow": "none", + "borderRadius": "{{appsmith.theme.borderRadius.appBorderRadius}}", + "accentColor": "{{appsmith.theme.colors.primaryColor}}", + "isLoading": false, + "parentColumnSpace": 1, + "parentRowSpace": 1, + "leftColumn": 0, + "rightColumn": 391.5, + "topRow": 0, + "bottomRow": 400, + "parentId": "hvt7qfqiqj", + "dynamicBindingPathList": [ + { + "key": "borderRadius" + }, + { + "key": "accentColor" + } + ] + } + ], + "type": "LIST_WIDGET", + "hideCard": false, + "displayName": "List", + "key": "ux6kqofl7o", + "iconSVG": "/static/media/icon.9925ee17.svg", + "isCanvas": true, + "widgetId": "hvt7qfqiqj", + "renderMode": "CANVAS", + "accentColor": "{{appsmith.theme.colors.primaryColor}}", + "borderRadius": "{{appsmith.theme.borderRadius.appBorderRadius}}", + "boxShadow": "{{appsmith.theme.boxShadow.appBoxShadow}}", + "isLoading": false, + "parentColumnSpace": 16.3125, + "parentRowSpace": 10, + "leftColumn": 14, + "rightColumn": 38, + "topRow": 10, + "bottomRow": 50, + "parentId": "0", + "dynamicBindingPathList": [ + { + "key": "accentColor" + }, + { + "key": "borderRadius" + }, + { + "key": "boxShadow" + }, + { + "key": "template.Image1.image" + }, + { + "key": "template.Text1.text" + }, + { + "key": "template.Text2.text" + }, + { + "key": "template.Text3.text" + } + ], + "privateWidgets": { + "Image1": true, + "Text1": true, + "Text2": true, + "Text3": true + }, + "dynamicTriggerPathList": [] + } + ] + } +} \ No newline at end of file diff --git a/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/LayoutWidgets/List_Regression2_spec.js b/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/LayoutWidgets/List_Regression2_spec.js new file mode 100644 index 000000000000..5a34a3a578b5 --- /dev/null +++ b/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/LayoutWidgets/List_Regression2_spec.js @@ -0,0 +1,35 @@ +const dsl = require("../../../../fixtures/listRegression2Dsl.json"); +const publish = require("../../../../locators/publishWidgetspage.json"); +const testdata = require("../../../../fixtures/testdata.json"); +const viewWidgetsPage = require("../../../../locators/ViewWidgets.json"); +const commonlocators = require("../../../../locators/commonlocators.json"); + +describe("Binding the list widget with text widget", function() { + const modifierKey = Cypress.platform === "darwin" ? "meta" : "ctrl"; + + before(() => { + cy.addDsl(dsl); + }); + + it("Validate text widget data based on changes in list widget Data2", function() { + cy.PublishtheApp(); + cy.wait(5000); + cy.get(".t--widget-textwidget span:contains('pawan,Vivek')").should( + "have.length", + 1, + ); + cy.get(".t--widget-textwidget span:contains('Ashok,rahul')").should( + "have.length", + 1, + ); + cy.get(publish.backToEditor).click({ force: true }); + cy.get(".t--text-widget-container:contains('pawan,Vivek')").should( + "have.length", + 1, + ); + cy.get(".t--text-widget-container:contains('Ashok,rahul')").should( + "have.length", + 1, + ); + }); +}); diff --git a/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/LayoutWidgets/List_Regression3_spec.js b/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/LayoutWidgets/List_Regression3_spec.js new file mode 100644 index 000000000000..15676ffea80a --- /dev/null +++ b/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/LayoutWidgets/List_Regression3_spec.js @@ -0,0 +1,35 @@ +const dsl = require("../../../../fixtures/listRegression3Dsl.json"); +const publish = require("../../../../locators/publishWidgetspage.json"); +const testdata = require("../../../../fixtures/testdata.json"); +const viewWidgetsPage = require("../../../../locators/ViewWidgets.json"); +const commonlocators = require("../../../../locators/commonlocators.json"); + +describe("Binding the list widget with text widget", function() { + const modifierKey = Cypress.platform === "darwin" ? "meta" : "ctrl"; + + before(() => { + cy.addDsl(dsl); + }); + + it("Validate text widget data based on changes in list widget Data3", function() { + cy.PublishtheApp(); + cy.wait(5000); + cy.get(".t--widget-textwidget span:contains('Vivek')").should( + "have.length", + 2, + ); + cy.get(".t--widget-textwidget span:contains('pawan')").should( + "have.length", + 2, + ); + cy.get(publish.backToEditor).click({ force: true }); + cy.get(".t--text-widget-container:contains('Vivek')").should( + "have.length", + 2, + ); + cy.get(".t--text-widget-container:contains('pawan')").should( + "have.length", + 2, + ); + }); +}); diff --git a/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/LayoutWidgets/List_Regression_spec.js b/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/LayoutWidgets/List_Regression_spec.js new file mode 100644 index 000000000000..751abeaff8c8 --- /dev/null +++ b/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/LayoutWidgets/List_Regression_spec.js @@ -0,0 +1,115 @@ +const dsl = require("../../../../fixtures/listRegressionDsl.json"); +const publish = require("../../../../locators/publishWidgetspage.json"); +const testdata = require("../../../../fixtures/testdata.json"); +const viewWidgetsPage = require("../../../../locators/ViewWidgets.json"); +const commonlocators = require("../../../../locators/commonlocators.json"); + +describe("Binding the list widget with text widget", function() { + const modifierKey = Cypress.platform === "darwin" ? "meta" : "ctrl"; + + before(() => { + cy.addDsl(dsl); + }); + + it("Validate text widget data based on changes in list widget Data1", function() { + cy.PublishtheApp(); + cy.wait(5000); + cy.get(".t--widget-textwidget span:contains('Vivek')").should( + "have.length", + 1, + ); + cy.get(".t--widget-textwidget span:contains('Pawan')").should( + "have.length", + 1, + ); + cy.get(publish.backToEditor).click({ force: true }); + cy.get(".t--text-widget-container:contains('Vivek')").should( + "have.length", + 1, + ); + cy.get(".t--text-widget-container:contains('Vivek')").should( + "have.length", + 1, + ); + }); + + it.skip("Validate text widget data based on changes in list widget Data2", function() { + cy.SearchEntityandOpen("List1"); + cy.updateComputedValue( + '[[{ "name": "pawan"}, { "name": "Vivek" }], [{ "name": "Ashok"}, {"name": "rahul"}]]', + ); + cy.wait("@updateLayout").should( + "have.nested.property", + "response.body.responseMeta.status", + 200, + ); + cy.SearchEntityandOpen("Text3"); + cy.wait(3000); + cy.updateComputedValue("{{currentItem.map(item => item.name).join(", ")}}"); + cy.wait("@updateLayout").should( + "have.nested.property", + "response.body.responseMeta.status", + 200, + ); + cy.PublishtheApp(); + cy.wait(5000); + cy.get(".t--widget-textwidget span:contains('pawan,Vivek')").should( + "have.length", + 1, + ); + cy.get(".t--widget-textwidget span:contains('Ashok,rahul')").should( + "have.length", + 1, + ); + cy.get(publish.backToEditor).click({ force: true }); + }); + + it.skip("Validate text widget data based on changes in list widget Data3", function() { + cy.SearchEntityandOpen("List1"); + cy.updateComputedValue('[{ "name": "pawan"}, { "name": "Vivek" }]'); + cy.wait("@updateLayout").should( + "have.nested.property", + "response.body.responseMeta.status", + 200, + ); + cy.SearchEntityandOpen("Text3"); + cy.wait(3000); + cy.updateComputedValue("{{currentItem.name}}"); + cy.wait("@updateLayout").should( + "have.nested.property", + "response.body.responseMeta.status", + 200, + ); + cy.PublishtheApp(); + cy.wait(5000); + cy.get(".t--widget-textwidget span:contains('Vivek')").should( + "have.length", + 2, + ); + cy.get(".t--widget-textwidget span:contains('pawan')").should( + "have.length", + 2, + ); + cy.get(publish.backToEditor).click({ force: true }); + }); + + it("Validate delete widget action from side bar", function() { + cy.openPropertyPane("listwidget"); + cy.verifyUpdatedWidgetName("Test"); + cy.get(commonlocators.editWidgetName) + .click({ force: true }) + .type("#$%1234", { delay: 300 }) + .type("{enter}"); + cy.get(".t--widget-name").contains("___1234"); + cy.verifyUpdatedWidgetName("12345"); + cy.get(".t--delete-widget").click({ force: true }); + cy.get(".t--toast-action span") + .eq(0) + .contains("12345 is removed"); + cy.wait("@updateLayout").should( + "have.nested.property", + "response.body.responseMeta.status", + 200, + ); + }); +}); diff --git a/app/client/cypress/locators/ViewWidgets.json b/app/client/cypress/locators/ViewWidgets.json index bb11238d305f..790058e9a0cb 100644 --- a/app/client/cypress/locators/ViewWidgets.json +++ b/app/client/cypress/locators/ViewWidgets.json @@ -32,5 +32,6 @@ "Chartlabel": ".t--draggable-chartwidget g:nth-child(5) text", "PieChartLabel": ".t--draggable-chartwidget g g:nth-child(1) g text", "pickMyLocation": ".t--draggable-mapwidget div[title='Pick My Location']", - "mapChartEntityLabels": ".t--draggable-mapchartwidget g[class*='-entityLabels'] text" + "mapChartEntityLabels": ".t--draggable-mapchartwidget g[class*='-entityLabels'] text", + "listWidget": ".t--draggable-listwidget" } diff --git a/app/client/cypress/support/widgetCommands.js b/app/client/cypress/support/widgetCommands.js index 2a592b78890b..cbd03559f0db 100644 --- a/app/client/cypress/support/widgetCommands.js +++ b/app/client/cypress/support/widgetCommands.js @@ -240,6 +240,14 @@ Cypress.Commands.add("widgetText", (text, inputcss, innercss) => { cy.contains(innercss, text); }); +Cypress.Commands.add("verifyUpdatedWidgetName", (text) => { + cy.get(commonlocators.editWidgetName) + .click({ force: true }) + .type(text, { delay: 300 }) + .type("{enter}"); + cy.get(".t--widget-name").contains(text); +}); + Cypress.Commands.add("verifyWidgetText", (text, inputcss, innercss) => { cy.get(inputcss) .first()
bfeab838f21cc956ee5e5f86de5074f0121ba2e5
2023-03-30 15:53:10
Anagh Hegde
fix: do not create files for empty body of queries in the git repo (#21774)
false
do not create files for empty body of queries in the git repo (#21774)
fix
diff --git a/app/server/appsmith-git/src/main/java/com/appsmith/git/helpers/FileUtilsImpl.java b/app/server/appsmith-git/src/main/java/com/appsmith/git/helpers/FileUtilsImpl.java index 78dca2bf9351..81503ebba46a 100644 --- a/app/server/appsmith-git/src/main/java/com/appsmith/git/helpers/FileUtilsImpl.java +++ b/app/server/appsmith-git/src/main/java/com/appsmith/git/helpers/FileUtilsImpl.java @@ -414,7 +414,7 @@ private boolean saveActions(Object sourceEntity, String body, String resourceNam Files.createDirectories(path); // Write the user written query to .txt file to make conflict handling easier // Body will be null if the action is of type JS - if (body != null) { + if (StringUtils.hasLength(body)) { Path bodyPath = path.resolve(resourceName + CommonConstants.TEXT_FILE_EXTENSION); writeStringToFile(body, bodyPath); } diff --git a/app/server/appsmith-git/src/main/java/com/appsmith/git/service/GitExecutorImpl.java b/app/server/appsmith-git/src/main/java/com/appsmith/git/service/GitExecutorImpl.java index 1a1bedefe9bd..0dacf5e2c894 100644 --- a/app/server/appsmith-git/src/main/java/com/appsmith/git/service/GitExecutorImpl.java +++ b/app/server/appsmith-git/src/main/java/com/appsmith/git/service/GitExecutorImpl.java @@ -494,8 +494,9 @@ public Mono<GitStatusDTO> getStatus(Path repoPath, String branchName) { for (String x : modifiedAssets) { if (x.contains(CommonConstants.CANVAS)) { modifiedPages++; - } else if (x.contains(GitDirectories.ACTION_DIRECTORY + "/") && !x.endsWith(".json")) { - String queryName = x.substring(x.lastIndexOf("/") + 1); + } else if (x.contains(GitDirectories.ACTION_DIRECTORY + "/")) { + String queryName = x.split(GitDirectories.ACTION_DIRECTORY + "/")[1]; + queryName = queryName.substring(0, queryName.indexOf("/")); String pageName = x.split("/")[1]; if (!queriesModified.contains(pageName + queryName)) { queriesModified.add(pageName + queryName);
d9a3253e920659f6519252351ede5ad14d8451d7
2024-12-24 15:47:25
Nidhi
chore: Moved git auth creation and updation to generified artifactservice (#38312)
false
Moved git auth creation and updation to generified artifactservice (#38312)
chore
diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/applications/base/ApplicationServiceCE.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/applications/base/ApplicationServiceCE.java index fd8e5a67ef38..6e6fd23d5055 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/applications/base/ApplicationServiceCE.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/applications/base/ApplicationServiceCE.java @@ -3,7 +3,7 @@ import com.appsmith.server.acl.AclPermission; import com.appsmith.server.domains.Application; import com.appsmith.server.domains.ApplicationMode; -import com.appsmith.server.domains.GitAuth; +import com.appsmith.server.domains.Artifact; import com.appsmith.server.dtos.ApplicationAccessDTO; import com.appsmith.server.dtos.GitAuthDTO; import com.appsmith.server.services.CrudService; @@ -29,7 +29,7 @@ public interface ApplicationServiceCE extends CrudService<Application, String> { Flux<Application> findByWorkspaceIdAndBaseApplicationsInRecentlyUsedOrder(String workspaceId); - Mono<Application> save(Application application); + Mono<Application> save(Artifact application); Mono<Application> updateApplicationWithPresets(String branchedApplicationId, Application application); @@ -53,8 +53,6 @@ Mono<Application> changeViewAccessForAllBranchesByBranchedApplicationId( Mono<Application> setTransientFields(Application application); - Mono<GitAuth> createOrUpdateSshKeyPair(String branchedApplicationId, String keyType); - Mono<GitAuthDTO> getSshKey(String applicationId); Mono<Application> findByBranchNameAndBaseApplicationId( diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/applications/base/ApplicationServiceCEImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/applications/base/ApplicationServiceCEImpl.java index 50872df66db3..afd1ad6335a6 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/applications/base/ApplicationServiceCEImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/applications/base/ApplicationServiceCEImpl.java @@ -1,15 +1,17 @@ package com.appsmith.server.applications.base; -import com.appsmith.external.constants.AnalyticsEvents; import com.appsmith.external.models.ActionDTO; import com.appsmith.external.models.Policy; import com.appsmith.server.acl.AclPermission; +import com.appsmith.server.artifacts.base.artifactbased.ArtifactBasedServiceCE; +import com.appsmith.server.artifacts.permissions.ArtifactPermission; import com.appsmith.server.constants.ApplicationConstants; import com.appsmith.server.constants.Assets; import com.appsmith.server.constants.FieldName; import com.appsmith.server.domains.Application; import com.appsmith.server.domains.ApplicationDetail; import com.appsmith.server.domains.ApplicationMode; +import com.appsmith.server.domains.Artifact; import com.appsmith.server.domains.Asset; import com.appsmith.server.domains.GitArtifactMetadata; import com.appsmith.server.domains.GitAuth; @@ -74,7 +76,7 @@ @Slf4j @Service public class ApplicationServiceCEImpl extends BaseService<ApplicationRepository, Application, String> - implements ApplicationServiceCE { + implements ApplicationServiceCE, ArtifactBasedServiceCE<Application> { private final PolicySolution policySolution; private final PermissionGroupService permissionGroupService; @@ -165,8 +167,9 @@ public Flux<Application> findByWorkspaceId(String workspaceId, AclPermission per * This method is used to fetch all the applications for a given workspaceId. It also sorts the applications based * on recently used order. * For git connected applications only default branched application is returned. - * @param workspaceId workspaceId for which applications are to be fetched - * @return Flux of applications + * + * @param workspaceId workspaceId for which applications are to be fetched + * @return Flux of applications */ @Override public Flux<Application> findByWorkspaceIdAndBaseApplicationsInRecentlyUsedOrder(String workspaceId) { @@ -212,7 +215,8 @@ public Flux<Application> findByWorkspaceIdAndBaseApplicationsInRecentlyUsedOrder } @Override - public Mono<Application> save(Application application) { + public Mono<Application> save(Artifact artifact) { + Application application = (Application) artifact; if (!StringUtils.isEmpty(application.getName())) { application.setSlug(TextUtils.makeSlug(application.getName())); } @@ -227,6 +231,11 @@ public Mono<Application> save(Application application) { return repository.save(application).flatMap(this::setTransientFields); } + @Override + public ArtifactPermission getPermissionService() { + return applicationPermission; + } + @Override public Mono<Application> create(Application object) { throw new UnsupportedOperationException( @@ -649,84 +658,6 @@ private Flux<Application> setTransientFields(Flux<Application> applicationsFlux) }); } - /** - * Generate SSH private and public keys required to communicate with remote. Keys will be stored only in the - * default/root application only and not the child branched application. This decision is taken because the combined - * size of keys is close to 4kB - * - * @param branchedApplicationId application for which the SSH key needs to be generated - * @return public key which will be used by user to copy to relevant platform - */ - @Override - public Mono<GitAuth> createOrUpdateSshKeyPair(String branchedApplicationId, String keyType) { - GitAuth gitAuth = GitDeployKeyGenerator.generateSSHKey(keyType); - return repository - .findById(branchedApplicationId, applicationPermission.getEditPermission()) - .switchIfEmpty(Mono.error( - new AppsmithException(AppsmithError.NO_RESOURCE_FOUND, "application", branchedApplicationId))) - .flatMap(application -> { - GitArtifactMetadata gitData = application.getGitApplicationMetadata(); - // Check if the current application is the root application - - if (gitData != null - && !StringUtils.isEmpty(gitData.getDefaultArtifactId()) - && branchedApplicationId.equals(gitData.getDefaultArtifactId())) { - // This is the root application with update SSH key request - gitAuth.setRegeneratedKey(true); - gitData.setGitAuth(gitAuth); - return save(application); - } else if (gitData == null) { - // This is a root application with generate SSH key request - GitArtifactMetadata gitArtifactMetadata = new GitArtifactMetadata(); - gitArtifactMetadata.setDefaultApplicationId(branchedApplicationId); - gitArtifactMetadata.setGitAuth(gitAuth); - application.setGitApplicationMetadata(gitArtifactMetadata); - return save(application); - } - // Children application with update SSH key request for root application - // Fetch root application and then make updates. We are storing the git metadata only in root - // application - if (StringUtils.isEmpty(gitData.getDefaultArtifactId())) { - throw new AppsmithException( - AppsmithError.INVALID_GIT_CONFIGURATION, - "Unable to find root application, please connect your application to remote repo to resolve this issue."); - } - gitAuth.setRegeneratedKey(true); - - return repository - .findById(gitData.getDefaultArtifactId(), applicationPermission.getEditPermission()) - .flatMap(baseApplication -> { - GitArtifactMetadata gitArtifactMetadata = baseApplication.getGitApplicationMetadata(); - gitArtifactMetadata.setDefaultApplicationId(baseApplication.getId()); - gitArtifactMetadata.setGitAuth(gitAuth); - baseApplication.setGitApplicationMetadata(gitArtifactMetadata); - return save(baseApplication); - }); - }) - .flatMap(application -> { - // Send generate SSH key analytics event - assert application.getId() != null; - final Map<String, Object> eventData = Map.of( - FieldName.APP_MODE, ApplicationMode.EDIT.toString(), FieldName.APPLICATION, application); - final Map<String, Object> data = Map.of( - FieldName.APPLICATION_ID, - application.getId(), - "organizationId", - application.getWorkspaceId(), - "isRegeneratedKey", - gitAuth.isRegeneratedKey(), - FieldName.EVENT_DATA, - eventData); - return analyticsService - .sendObjectEvent(AnalyticsEvents.GENERATE_SSH_KEY, application, data) - .onErrorResume(e -> { - log.warn("Error sending ssh key generation data point", e); - return Mono.just(application); - }); - }) - .thenReturn(gitAuth); - } - /** * Method to get the SSH public key * @@ -1025,9 +956,10 @@ public Flux<String> findBranchedApplicationIdsByBaseApplicationId(String baseApp /** * Gets branched application with the right permission set based on mode of application + * * @param defaultApplicationId : default app id - * @param branchName : branch name of the application - * @param mode : is it edit mode or view mode + * @param branchName : branch name of the application + * @param mode : is it edit mode or view mode * @return : returns a publisher of branched application */ @Override diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/applications/base/ApplicationServiceImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/applications/base/ApplicationServiceImpl.java index 513506baaedf..4c2afe584650 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/applications/base/ApplicationServiceImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/applications/base/ApplicationServiceImpl.java @@ -1,5 +1,7 @@ package com.appsmith.server.applications.base; +import com.appsmith.server.artifacts.base.artifactbased.ArtifactBasedService; +import com.appsmith.server.domains.Application; import com.appsmith.server.repositories.ApplicationRepository; import com.appsmith.server.repositories.NewActionRepository; import com.appsmith.server.services.AnalyticsService; @@ -20,7 +22,8 @@ @Slf4j @Service -public class ApplicationServiceImpl extends ApplicationServiceCECompatibleImpl implements ApplicationService { +public class ApplicationServiceImpl extends ApplicationServiceCECompatibleImpl + implements ApplicationService, ArtifactBasedService<Application> { public ApplicationServiceImpl( Validator validator, diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/artifacts/base/ArtifactService.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/artifacts/base/ArtifactService.java new file mode 100644 index 000000000000..541477b8a020 --- /dev/null +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/artifacts/base/ArtifactService.java @@ -0,0 +1,3 @@ +package com.appsmith.server.artifacts.base; + +public interface ArtifactService extends ArtifactServiceCE {} diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/artifacts/base/ArtifactServiceCE.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/artifacts/base/ArtifactServiceCE.java new file mode 100644 index 000000000000..c8d37afd9a02 --- /dev/null +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/artifacts/base/ArtifactServiceCE.java @@ -0,0 +1,24 @@ +package com.appsmith.server.artifacts.base; + +import com.appsmith.server.artifacts.base.artifactbased.ArtifactBasedService; +import com.appsmith.server.constants.ArtifactType; +import com.appsmith.server.domains.Artifact; +import com.appsmith.server.domains.GitAuth; +import reactor.core.publisher.Mono; + +public interface ArtifactServiceCE { + + /** + * This method returns the appropriate ArtifactBasedService based on the type of artifact. + */ + ArtifactBasedService<? extends Artifact> getArtifactBasedService(ArtifactType artifactType); + + /** + * Generate SSH private and public keys required to communicate with remote. Keys will be stored only in the + * default/root application only and not the child branched application. This decision is taken because the combined + * size of keys is close to 4kB + * + * @return public key which will be used by user to copy to relevant platform + */ + Mono<GitAuth> createOrUpdateSshKeyPair(ArtifactType artifactType, String branchedArtifactId, String keyType); +} diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/artifacts/base/ArtifactServiceCEImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/artifacts/base/ArtifactServiceCEImpl.java new file mode 100644 index 000000000000..c5c4f2a50036 --- /dev/null +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/artifacts/base/ArtifactServiceCEImpl.java @@ -0,0 +1,116 @@ +package com.appsmith.server.artifacts.base; + +import com.appsmith.external.constants.AnalyticsEvents; +import com.appsmith.server.artifacts.base.artifactbased.ArtifactBasedService; +import com.appsmith.server.artifacts.permissions.ArtifactPermission; +import com.appsmith.server.constants.ArtifactType; +import com.appsmith.server.constants.FieldName; +import com.appsmith.server.domains.Application; +import com.appsmith.server.domains.ApplicationMode; +import com.appsmith.server.domains.Artifact; +import com.appsmith.server.domains.GitArtifactMetadata; +import com.appsmith.server.domains.GitAuth; +import com.appsmith.server.exceptions.AppsmithError; +import com.appsmith.server.exceptions.AppsmithException; +import com.appsmith.server.helpers.GitDeployKeyGenerator; +import com.appsmith.server.services.AnalyticsService; +import lombok.extern.slf4j.Slf4j; +import org.springframework.stereotype.Service; +import org.springframework.util.StringUtils; +import reactor.core.publisher.Mono; + +import java.util.Map; + +@Slf4j +@Service +public class ArtifactServiceCEImpl implements ArtifactServiceCE { + + protected final ArtifactBasedService<Application> applicationService; + private final AnalyticsService analyticsService; + + public ArtifactServiceCEImpl( + ArtifactBasedService<Application> applicationService, AnalyticsService analyticsService) { + this.applicationService = applicationService; + this.analyticsService = analyticsService; + } + + @Override + public ArtifactBasedService<? extends Artifact> getArtifactBasedService(ArtifactType artifactType) { + return applicationService; + } + + @Override + public Mono<GitAuth> createOrUpdateSshKeyPair( + ArtifactType artifactType, String branchedArtifactId, String keyType) { + GitAuth gitAuth = GitDeployKeyGenerator.generateSSHKey(keyType); + ArtifactBasedService<? extends Artifact> artifactBasedService = getArtifactBasedService(artifactType); + ArtifactPermission artifactPermission = artifactBasedService.getPermissionService(); + final String artifactTypeName = artifactType.name().toLowerCase(); + return artifactBasedService + .findById(branchedArtifactId, artifactPermission.getEditPermission()) + .switchIfEmpty(Mono.error( + new AppsmithException(AppsmithError.NO_RESOURCE_FOUND, artifactTypeName, branchedArtifactId))) + .flatMap(artifact -> { + GitArtifactMetadata gitData = artifact.getGitArtifactMetadata(); + // Check if the current artifact is the root artifact + + if (gitData != null + && StringUtils.hasLength(gitData.getDefaultArtifactId()) + && branchedArtifactId.equals(gitData.getDefaultArtifactId())) { + // This is the root application with update SSH key request + gitAuth.setRegeneratedKey(true); + gitData.setGitAuth(gitAuth); + return artifactBasedService.save(artifact); + } else if (gitData == null) { + // This is a root application with generate SSH key request + GitArtifactMetadata gitArtifactMetadata = new GitArtifactMetadata(); + gitArtifactMetadata.setDefaultApplicationId(branchedArtifactId); + gitArtifactMetadata.setGitAuth(gitAuth); + artifact.setGitArtifactMetadata(gitArtifactMetadata); + return artifactBasedService.save(artifact); + } + // Children application with update SSH key request for root application + // Fetch root application and then make updates. We are storing the git metadata only in root + // application + if (!StringUtils.hasLength(gitData.getDefaultArtifactId())) { + return Mono.error(new AppsmithException( + AppsmithError.INVALID_GIT_CONFIGURATION, + "Unable to find root " + artifactTypeName + ", please connect your " + artifactTypeName + + " to remote repo to resolve this issue.")); + } + gitAuth.setRegeneratedKey(true); + + return artifactBasedService + .findById(gitData.getDefaultArtifactId(), artifactPermission.getEditPermission()) + .flatMap(baseApplication -> { + GitArtifactMetadata gitArtifactMetadata = baseApplication.getGitArtifactMetadata(); + gitArtifactMetadata.setDefaultApplicationId(baseApplication.getId()); + gitArtifactMetadata.setGitAuth(gitAuth); + baseApplication.setGitArtifactMetadata(gitArtifactMetadata); + return artifactBasedService.save(baseApplication); + }); + }) + .flatMap(artifact -> { + // Send generate SSH key analytics event + assert artifact.getId() != null; + final Map<String, Object> eventData = Map.of( + FieldName.APP_MODE, ApplicationMode.EDIT.toString(), FieldName.APPLICATION, artifact); + final Map<String, Object> data = Map.of( + FieldName.APPLICATION_ID, + artifact.getId(), + "organizationId", + artifact.getWorkspaceId(), + "isRegeneratedKey", + gitAuth.isRegeneratedKey(), + FieldName.EVENT_DATA, + eventData); + return analyticsService + .sendObjectEvent(AnalyticsEvents.GENERATE_SSH_KEY, artifact, data) + .onErrorResume(e -> { + log.warn("Error sending ssh key generation data point", e); + return Mono.just(artifact); + }); + }) + .thenReturn(gitAuth); + } +} diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/artifacts/base/ArtifactServiceImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/artifacts/base/ArtifactServiceImpl.java new file mode 100644 index 000000000000..515b15085268 --- /dev/null +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/artifacts/base/ArtifactServiceImpl.java @@ -0,0 +1,15 @@ +package com.appsmith.server.artifacts.base; + +import com.appsmith.server.artifacts.base.artifactbased.ArtifactBasedService; +import com.appsmith.server.domains.Application; +import com.appsmith.server.services.AnalyticsService; +import org.springframework.stereotype.Service; + +@Service +public class ArtifactServiceImpl extends ArtifactServiceCEImpl implements ArtifactService { + + public ArtifactServiceImpl( + ArtifactBasedService<Application> applicationService, AnalyticsService analyticsService) { + super(applicationService, analyticsService); + } +} diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/artifacts/base/artifactbased/ArtifactBasedService.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/artifacts/base/artifactbased/ArtifactBasedService.java new file mode 100644 index 000000000000..098b1fa10c39 --- /dev/null +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/artifacts/base/artifactbased/ArtifactBasedService.java @@ -0,0 +1,5 @@ +package com.appsmith.server.artifacts.base.artifactbased; + +import com.appsmith.server.domains.Artifact; + +public interface ArtifactBasedService<T extends Artifact> extends ArtifactBasedServiceCE<T> {} diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/artifacts/base/artifactbased/ArtifactBasedServiceCE.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/artifacts/base/artifactbased/ArtifactBasedServiceCE.java new file mode 100644 index 000000000000..90d10e9962c6 --- /dev/null +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/artifacts/base/artifactbased/ArtifactBasedServiceCE.java @@ -0,0 +1,15 @@ +package com.appsmith.server.artifacts.base.artifactbased; + +import com.appsmith.server.acl.AclPermission; +import com.appsmith.server.artifacts.permissions.ArtifactPermission; +import com.appsmith.server.domains.Artifact; +import reactor.core.publisher.Mono; + +public interface ArtifactBasedServiceCE<T extends Artifact> { + + Mono<T> findById(String id, AclPermission aclPermission); + + Mono<T> save(Artifact artifact); + + ArtifactPermission getPermissionService(); +} diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/artifacts/permissions/ArtifactPermission.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/artifacts/permissions/ArtifactPermission.java new file mode 100644 index 000000000000..0d9e4b870662 --- /dev/null +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/artifacts/permissions/ArtifactPermission.java @@ -0,0 +1,3 @@ +package com.appsmith.server.artifacts.permissions; + +public interface ArtifactPermission extends ArtifactPermissionCE {} diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ce/ArtifactPermissionCE.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/artifacts/permissions/ArtifactPermissionCE.java similarity index 70% rename from app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ce/ArtifactPermissionCE.java rename to app/server/appsmith-server/src/main/java/com/appsmith/server/artifacts/permissions/ArtifactPermissionCE.java index f2e9b574bbeb..78423dd64cfb 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ce/ArtifactPermissionCE.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/artifacts/permissions/ArtifactPermissionCE.java @@ -1,9 +1,11 @@ -package com.appsmith.server.solutions.ce; +package com.appsmith.server.artifacts.permissions; import com.appsmith.server.acl.AclPermission; public interface ArtifactPermissionCE { + AclPermission getEditPermission(); + AclPermission getDeletePermission(); AclPermission getGitConnectPermission(); 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 c2774c57edf2..8836312ed8de 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 @@ -1,6 +1,7 @@ package com.appsmith.server.controllers; import com.appsmith.server.applications.base.ApplicationService; +import com.appsmith.server.artifacts.base.ArtifactService; import com.appsmith.server.constants.Url; import com.appsmith.server.controllers.ce.ApplicationControllerCE; import com.appsmith.server.exports.internal.ExportService; @@ -22,6 +23,7 @@ public class ApplicationController extends ApplicationControllerCE { public ApplicationController( + ArtifactService artifactService, ApplicationService service, ApplicationPageService applicationPageService, UserReleaseNotes userReleaseNotes, @@ -33,6 +35,7 @@ public ApplicationController( ImportService importService, ExportService exportService) { super( + artifactService, service, applicationPageService, userReleaseNotes, 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 90f7e717d28b..f1512a8866f9 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 @@ -3,6 +3,8 @@ import com.appsmith.external.models.Datasource; import com.appsmith.external.views.Views; import com.appsmith.server.applications.base.ApplicationService; +import com.appsmith.server.artifacts.base.ArtifactService; +import com.appsmith.server.constants.ArtifactType; import com.appsmith.server.constants.FieldName; import com.appsmith.server.constants.Url; import com.appsmith.server.domains.Application; @@ -62,6 +64,7 @@ @RequiredArgsConstructor public class ApplicationControllerCE { + protected final ArtifactService artifactService; protected final ApplicationService service; private final ApplicationPageService applicationPageService; private final UserReleaseNotes userReleaseNotes; @@ -248,7 +251,8 @@ public Mono<ResponseDTO<ArtifactImportDTO>> importApplicationFromFile( @PostMapping("/ssh-keypair/{branchedApplicationId}") public Mono<ResponseDTO<GitAuth>> generateSSHKeyPair( @PathVariable String branchedApplicationId, @RequestParam(required = false) String keyType) { - return service.createOrUpdateSshKeyPair(branchedApplicationId, keyType) + return artifactService + .createOrUpdateSshKeyPair(ArtifactType.APPLICATION, branchedApplicationId, keyType) .map(created -> new ResponseDTO<>(HttpStatus.CREATED.value(), created, null)); } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/helpers/ImportArtifactPermissionProvider.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/helpers/ImportArtifactPermissionProvider.java index bcc90326cbe7..f60fb62d96e4 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/helpers/ImportArtifactPermissionProvider.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/helpers/ImportArtifactPermissionProvider.java @@ -1,9 +1,9 @@ package com.appsmith.server.helpers; import com.appsmith.server.acl.AclPermission; +import com.appsmith.server.artifacts.permissions.ArtifactPermission; import com.appsmith.server.helpers.ce.ImportArtifactPermissionProviderCE; import com.appsmith.server.solutions.ActionPermission; -import com.appsmith.server.solutions.ArtifactPermission; import com.appsmith.server.solutions.ContextPermission; import com.appsmith.server.solutions.DatasourcePermission; import com.appsmith.server.solutions.WorkspacePermission; diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/helpers/ce/ImportArtifactPermissionProviderCE.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/helpers/ce/ImportArtifactPermissionProviderCE.java index c1ee41c79126..b5422273ff85 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/helpers/ce/ImportArtifactPermissionProviderCE.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/helpers/ce/ImportArtifactPermissionProviderCE.java @@ -3,13 +3,13 @@ import com.appsmith.external.models.BaseDomain; import com.appsmith.external.models.Datasource; import com.appsmith.server.acl.AclPermission; +import com.appsmith.server.artifacts.permissions.ArtifactPermission; import com.appsmith.server.domains.Application; import com.appsmith.server.domains.NewAction; import com.appsmith.server.domains.NewPage; import com.appsmith.server.domains.Workspace; import com.appsmith.server.solutions.ActionPermission; import com.appsmith.server.solutions.ApplicationPermission; -import com.appsmith.server.solutions.ArtifactPermission; import com.appsmith.server.solutions.ContextPermission; import com.appsmith.server.solutions.DatasourcePermission; import com.appsmith.server.solutions.WorkspacePermission; diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ArtifactPermission.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ArtifactPermission.java deleted file mode 100644 index d6cc0b1dec57..000000000000 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ArtifactPermission.java +++ /dev/null @@ -1,5 +0,0 @@ -package com.appsmith.server.solutions; - -import com.appsmith.server.solutions.ce.ArtifactPermissionCE; - -public interface ArtifactPermission extends ArtifactPermissionCE {} diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ce/ApplicationPermissionCE.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ce/ApplicationPermissionCE.java index 1b91b9a08330..2b1620ed4d13 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ce/ApplicationPermissionCE.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ce/ApplicationPermissionCE.java @@ -1,7 +1,7 @@ package com.appsmith.server.solutions.ce; import com.appsmith.server.acl.AclPermission; -import com.appsmith.server.solutions.ArtifactPermission; +import com.appsmith.server.artifacts.permissions.ArtifactPermission; public interface ApplicationPermissionCE extends ArtifactPermission { 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 f8b9091b5a7e..c6b1d5d1c5f5 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 @@ -1,27 +1,13 @@ package com.appsmith.server.controllers; -import com.appsmith.server.applications.base.ApplicationService; -import com.appsmith.server.configurations.ProjectProperties; import com.appsmith.server.configurations.RedisTestContainerConfig; import com.appsmith.server.configurations.SecurityTestConfig; import com.appsmith.server.constants.Url; import com.appsmith.server.dtos.ApplicationImportDTO; import com.appsmith.server.dtos.ArtifactImportDTO; import com.appsmith.server.exceptions.AppsmithErrorCode; -import com.appsmith.server.exports.internal.ExportService; -import com.appsmith.server.exports.internal.partial.PartialExportService; -import com.appsmith.server.fork.internal.ApplicationForkingService; -import com.appsmith.server.helpers.CommonGitFileUtils; import com.appsmith.server.helpers.RedisUtils; import com.appsmith.server.imports.internal.ImportService; -import com.appsmith.server.imports.internal.partial.PartialImportService; -import com.appsmith.server.services.AnalyticsService; -import com.appsmith.server.services.ApplicationPageService; -import com.appsmith.server.services.ApplicationSnapshotService; -import com.appsmith.server.services.SessionUserService; -import com.appsmith.server.services.UserDataService; -import com.appsmith.server.solutions.UserReleaseNotes; -import com.appsmith.server.themes.base.ThemeService; import org.junit.jupiter.api.Test; import org.mockito.Mockito; import org.mockito.stubbing.Answer; @@ -49,51 +35,10 @@ @EnableAutoConfiguration(exclude = ReactiveMultipartAutoConfiguration.class) @Import({SecurityTestConfig.class, RedisUtils.class, RedisTestContainerConfig.class}) public class ApplicationControllerTest { - @MockBean - ApplicationService applicationService; - - @MockBean - ApplicationPageService applicationPageService; - - @MockBean - UserReleaseNotes applicationFetcher; - - @MockBean - ApplicationForkingService applicationForkingService; @MockBean ImportService importService; - @MockBean - ExportService exportService; - - @MockBean - ApplicationSnapshotService applicationSnapshotService; - - @MockBean - ThemeService themeService; - - @MockBean - UserDataService userDataService; - - @MockBean - AnalyticsService analyticsService; - - @MockBean - CommonGitFileUtils commonGitFileUtils; - - @MockBean - SessionUserService sessionUserService; - - @MockBean - PartialExportService partialExportService; - - @MockBean - PartialImportService partialImportService; - - @MockBean - ProjectProperties projectProperties; - @Autowired private WebTestClient webTestClient; diff --git a/app/server/appsmith-server/src/test/java/com/appsmith/server/git/autocommit/AutoCommitServiceTest.java b/app/server/appsmith-server/src/test/java/com/appsmith/server/git/autocommit/AutoCommitServiceTest.java index 66fe0fd2347a..3a7e5f53c350 100644 --- a/app/server/appsmith-server/src/test/java/com/appsmith/server/git/autocommit/AutoCommitServiceTest.java +++ b/app/server/appsmith-server/src/test/java/com/appsmith/server/git/autocommit/AutoCommitServiceTest.java @@ -78,7 +78,7 @@ public class AutoCommitServiceTest { @MockBean DSLMigrationUtils dslMigrationUtils; - @MockBean + @SpyBean ApplicationService applicationService; @MockBean @@ -201,12 +201,13 @@ public void beforeTest() { baseRepoSuffix = Paths.get(WORKSPACE_ID, DEFAULT_APP_ID, REPO_NAME); // used for fetching application on autocommit service and gitAutoCommitHelper.autocommit - Mockito.when(applicationService.findByBranchNameAndBaseApplicationId( - anyString(), anyString(), any(AclPermission.class))) - .thenReturn(Mono.just(testApplication)); + Mockito.doReturn(Mono.just(testApplication)) + .when(applicationService) + .findByBranchNameAndBaseApplicationId(anyString(), anyString(), any(AclPermission.class)); - Mockito.when(applicationService.findById(anyString(), any(AclPermission.class))) - .thenReturn(Mono.just(testApplication)); + Mockito.doReturn(Mono.just(testApplication)) + .when(applicationService) + .findById(anyString(), any(AclPermission.class)); // create page-dto PageDTO pageDTO = createPageDTO(); @@ -224,8 +225,9 @@ public void beforeTest() { .when(gitExecutor) .pushApplication(baseRepoSuffix, REPO_URL, PUBLIC_KEY, PRIVATE_KEY, BRANCH_NAME); - Mockito.when(applicationService.findById(anyString(), any(AclPermission.class))) - .thenReturn(Mono.just(testApplication)); + Mockito.doReturn(Mono.just(testApplication)) + .when(applicationService) + .findById(anyString(), any(AclPermission.class)); Mockito.when(gitPrivateRepoHelper.isBranchProtected(any(), anyString())).thenReturn(Mono.just(FALSE)); @@ -480,12 +482,13 @@ public void testAutoCommit_whenAutoCommitAlreadyInProgressOnSameBranch_returnsIn public void testAutoCommit_whenNoGitMetadata_returnsNonGitApp() { testApplication.setGitApplicationMetadata(null); // used for fetching application on autocommit service and gitAutoCommitHelper.autocommit - Mockito.when(applicationService.findById(anyString(), any(AclPermission.class))) - .thenReturn(Mono.just(testApplication)); + Mockito.doReturn(Mono.just(testApplication)) + .when(applicationService) + .findById(anyString(), any(AclPermission.class)); - Mockito.when(applicationService.findByBranchNameAndBaseApplicationId( - anyString(), anyString(), any(AclPermission.class))) - .thenReturn(Mono.just(testApplication)); + Mockito.doReturn(Mono.just(testApplication)) + .when(applicationService) + .findByBranchNameAndBaseApplicationId(anyString(), anyString(), any(AclPermission.class)); // this would not trigger autocommit Mono<AutoCommitResponseDTO> autoCommitResponseDTOMono = diff --git a/app/server/appsmith-server/src/test/java/com/appsmith/server/git/autocommit/helpers/GitAutoCommitHelperImplTest.java b/app/server/appsmith-server/src/test/java/com/appsmith/server/git/autocommit/helpers/GitAutoCommitHelperImplTest.java index 7af8f7f170e7..80f0f122c5ae 100644 --- a/app/server/appsmith-server/src/test/java/com/appsmith/server/git/autocommit/helpers/GitAutoCommitHelperImplTest.java +++ b/app/server/appsmith-server/src/test/java/com/appsmith/server/git/autocommit/helpers/GitAutoCommitHelperImplTest.java @@ -44,7 +44,7 @@ public class GitAutoCommitHelperImplTest { @MockBean AutoCommitEventHandler autoCommitEventHandler; - @MockBean + @SpyBean ApplicationService applicationService; @MockBean @@ -81,13 +81,14 @@ public void autoCommitApplication_WhenBranchIsProtected_AutoCommitNotTriggered() application.setId(defaultApplicationId); application.setGitApplicationMetadata(new GitArtifactMetadata()); - Mockito.when(applicationService.findById(defaultApplicationId, applicationPermission.getEditPermission())) - .thenReturn(Mono.just(application)); + Mockito.doReturn(Mono.just(application)) + .when(applicationService) + .findById(defaultApplicationId, applicationPermission.getEditPermission()); Mockito.when(gitPrivateRepoHelper.isBranchProtected(any(GitArtifactMetadata.class), eq(branchName))) .thenReturn(Mono.just(Boolean.TRUE)); - Mockito.when(applicationService.findByBranchNameAndBaseApplicationId( - anyString(), anyString(), any(AclPermission.class))) - .thenReturn(Mono.just(application)); + Mockito.doReturn(Mono.just(application)) + .when(applicationService) + .findByBranchNameAndBaseApplicationId(anyString(), anyString(), any(AclPermission.class)); StepVerifier.create(gitAutoCommitHelper.autoCommitClientMigration(defaultApplicationId, branchName)) .assertNext(aBoolean -> { @@ -105,11 +106,12 @@ public void autoCommitApplication_WhenAutoCommitDisabled_AutoCommitNotTriggered( metadata.getAutoCommitConfig().setEnabled(Boolean.FALSE); application.setGitApplicationMetadata(metadata); - Mockito.when(applicationService.findById(defaultApplicationId, applicationPermission.getEditPermission())) - .thenReturn(Mono.just(application)); - Mockito.when(applicationService.findByBranchNameAndBaseApplicationId( - anyString(), anyString(), any(AclPermission.class))) - .thenReturn(Mono.just(application)); + Mockito.doReturn(Mono.just(application)) + .when(applicationService) + .findById(defaultApplicationId, applicationPermission.getEditPermission()); + Mockito.doReturn(Mono.just(application)) + .when(applicationService) + .findByBranchNameAndBaseApplicationId(anyString(), anyString(), any(AclPermission.class)); Mockito.when(gitPrivateRepoHelper.isBranchProtected(any(GitArtifactMetadata.class), eq(branchName))) .thenReturn(Mono.just(Boolean.FALSE)); @@ -126,13 +128,14 @@ public void autoCommitApplication_WhenAnotherCommitIsRunning_AutoCommitNotTrigge application.setId(defaultApplicationId); application.setGitApplicationMetadata(new GitArtifactMetadata()); - Mockito.when(applicationService.findById(defaultApplicationId, applicationPermission.getEditPermission())) - .thenReturn(Mono.just(application)); + Mockito.doReturn(Mono.just(application)) + .when(applicationService) + .findById(defaultApplicationId, applicationPermission.getEditPermission()); Mockito.when(gitPrivateRepoHelper.isBranchProtected(any(GitArtifactMetadata.class), eq(branchName))) .thenReturn(Mono.just(Boolean.FALSE)); - Mockito.when(applicationService.findByBranchNameAndBaseApplicationId( - anyString(), anyString(), any(AclPermission.class))) - .thenReturn(Mono.just(application)); + Mockito.doReturn(Mono.just(application)) + .when(applicationService) + .findByBranchNameAndBaseApplicationId(anyString(), anyString(), any(AclPermission.class)); Mono<Boolean> autoCommitMono = redisUtils .startAutoCommit(defaultApplicationId, branchName) @@ -158,11 +161,12 @@ public void autoCommitApplication_WhenAllConditionsMatched_AutoCommitTriggered() metaData.setGitAuth(gitAuth); application.setGitApplicationMetadata(metaData); - Mockito.when(applicationService.findById(defaultApplicationId, applicationPermission.getEditPermission())) - .thenReturn(Mono.just(application)); - Mockito.when(applicationService.findByBranchNameAndBaseApplicationId( - anyString(), anyString(), any(AclPermission.class))) - .thenReturn(Mono.just(application)); + Mockito.doReturn(Mono.just(application)) + .when(applicationService) + .findById(defaultApplicationId, applicationPermission.getEditPermission()); + Mockito.doReturn(Mono.just(application)) + .when(applicationService) + .findByBranchNameAndBaseApplicationId(anyString(), anyString(), any(AclPermission.class)); Mockito.when(commonGitService.fetchRemoteChanges(any(Application.class), any(Application.class), anyBoolean())) .thenReturn(Mono.just(branchTrackingStatus)); @@ -256,11 +260,12 @@ public void autoCommitApplication_WhenRemoteAhead_AutoCommitNotTriggered() { metadata.getAutoCommitConfig().setEnabled(Boolean.TRUE); application.setGitApplicationMetadata(metadata); - Mockito.when(applicationService.findById(defaultApplicationId, applicationPermission.getEditPermission())) - .thenReturn(Mono.just(application)); - Mockito.when(applicationService.findByBranchNameAndBaseApplicationId( - anyString(), anyString(), any(AclPermission.class))) - .thenReturn(Mono.just(application)); + Mockito.doReturn(Mono.just(application)) + .when(applicationService) + .findById(defaultApplicationId, applicationPermission.getEditPermission()); + Mockito.doReturn(Mono.just(application)) + .when(applicationService) + .findByBranchNameAndBaseApplicationId(anyString(), anyString(), any(AclPermission.class)); Mockito.when(commonGitService.fetchRemoteChanges(any(Application.class), any(Application.class), anyBoolean())) .thenReturn(Mono.just(branchTrackingStatus)); @@ -291,12 +296,13 @@ public void autoCommitApplication_WhenServerRequiresMigration_successIfEverythin application.setGitApplicationMetadata(metaData); - Mockito.when(applicationService.findById(anyString(), any(AclPermission.class))) - .thenReturn(Mono.just(application)); + Mockito.doReturn(Mono.just(application)) + .when(applicationService) + .findById(anyString(), any(AclPermission.class)); - Mockito.when(applicationService.findByBranchNameAndBaseApplicationId( - anyString(), anyString(), any(AclPermission.class))) - .thenReturn(Mono.just(application)); + Mockito.doReturn(Mono.just(application)) + .when(applicationService) + .findByBranchNameAndBaseApplicationId(anyString(), anyString(), any(AclPermission.class)); Mockito.when(commonGitService.fetchRemoteChanges(any(Application.class), any(Application.class), anyBoolean())) .thenReturn(Mono.just(branchTrackingStatus)); @@ -335,12 +341,13 @@ public void autoCommitApplication_WhenServerDoesNotRequireMigration_returnFalse( metaData.setGitAuth(gitAuth); application.setGitApplicationMetadata(metaData); - Mockito.when(applicationService.findById(anyString(), any(AclPermission.class))) - .thenReturn(Mono.just(application)); + Mockito.doReturn(Mono.just(application)) + .when(applicationService) + .findById(anyString(), any(AclPermission.class)); - Mockito.when(applicationService.findByBranchNameAndBaseApplicationId( - anyString(), anyString(), any(AclPermission.class))) - .thenReturn(Mono.just(application)); + Mockito.doReturn(Mono.just(application)) + .when(applicationService) + .findByBranchNameAndBaseApplicationId(anyString(), anyString(), any(AclPermission.class)); StepVerifier.create(gitAutoCommitHelper.autoCommitServerMigration(defaultApplicationId, branchName)) .assertNext(isAutoCommitPublished -> { diff --git a/app/server/appsmith-server/src/test/java/com/appsmith/server/refactors/ce/RefactoringServiceCEImplTest.java b/app/server/appsmith-server/src/test/java/com/appsmith/server/refactors/ce/RefactoringServiceCEImplTest.java index 61d74b6a9116..dcbfbd0aad29 100644 --- a/app/server/appsmith-server/src/test/java/com/appsmith/server/refactors/ce/RefactoringServiceCEImplTest.java +++ b/app/server/appsmith-server/src/test/java/com/appsmith/server/refactors/ce/RefactoringServiceCEImplTest.java @@ -66,7 +66,7 @@ class RefactoringServiceCEImplTest { @MockBean private UpdateLayoutService updateLayoutService; - @MockBean + @SpyBean private ApplicationService applicationService; @MockBean @@ -161,7 +161,7 @@ public void testRefactorCollectionName_withEmptyActions_returnsValidLayout() { Application application = new Application(); application.setId("testAppId"); application.setEvaluationVersion(EVALUATION_VERSION); - Mockito.when(applicationService.findById(Mockito.anyString())).thenReturn(Mono.just(application)); + Mockito.doReturn(Mono.just(application)).when(applicationService).findById(Mockito.anyString()); Mockito.when(newActionService.findByPageIdAndViewMode(Mockito.anyString(), Mockito.anyBoolean(), Mockito.any())) .thenReturn(Flux.empty()); @@ -287,7 +287,7 @@ public void testRefactorCollectionName_withActions_returnsValidLayout() { Application application = new Application(); application.setId("testAppId"); application.setEvaluationVersion(EVALUATION_VERSION); - Mockito.when(applicationService.findById(Mockito.anyString())).thenReturn(Mono.just(application)); + Mockito.doReturn(Mono.just(application)).when(applicationService).findById(Mockito.anyString()); NewAction newAction = new NewAction(); ActionDTO actionDTO = new ActionDTO(); diff --git a/app/server/appsmith-server/src/test/java/com/appsmith/server/services/ce/ApplicationServiceCETest.java b/app/server/appsmith-server/src/test/java/com/appsmith/server/services/ce/ApplicationServiceCETest.java index f71b19257321..89c9a9adabd4 100644 --- a/app/server/appsmith-server/src/test/java/com/appsmith/server/services/ce/ApplicationServiceCETest.java +++ b/app/server/appsmith-server/src/test/java/com/appsmith/server/services/ce/ApplicationServiceCETest.java @@ -14,6 +14,8 @@ import com.appsmith.server.acl.AclPermission; import com.appsmith.server.actioncollections.base.ActionCollectionService; import com.appsmith.server.applications.base.ApplicationService; +import com.appsmith.server.artifacts.base.ArtifactService; +import com.appsmith.server.constants.ArtifactType; import com.appsmith.server.constants.FieldName; import com.appsmith.server.datasources.base.DatasourceService; import com.appsmith.server.domains.ActionCollection; @@ -176,6 +178,9 @@ public class ApplicationServiceCETest { static Application gitConnectedApp = new Application(); + @Autowired + ArtifactService artifactService; + @Autowired ApplicationService applicationService; @@ -3514,8 +3519,8 @@ public void generateSshKeyPair_WhenDefaultApplicationIdNotSet_CurrentAppUpdated( Mono<Application> applicationMono = applicationPageService .createApplication(unsavedApplication) - .flatMap(savedApplication -> applicationService - .createOrUpdateSshKeyPair(savedApplication.getId(), null) + .flatMap(savedApplication -> artifactService + .createOrUpdateSshKeyPair(ArtifactType.APPLICATION, savedApplication.getId(), null) .thenReturn(savedApplication.getId())) .flatMap(testApplicationId -> applicationRepository.findById(testApplicationId, MANAGE_APPLICATIONS)); @@ -3544,8 +3549,8 @@ public void generateSshKeyPair_WhenDefaultApplicationIdSet_DefaultApplicationUpd .createApplication(unsavedMainApp, workspaceId) .block(); - Mono<Tuple2<Application, Application>> tuple2Mono = applicationService - .createOrUpdateSshKeyPair(savedApplication.getId(), null) + Mono<Tuple2<Application, Application>> tuple2Mono = artifactService + .createOrUpdateSshKeyPair(ArtifactType.APPLICATION, savedApplication.getId(), null) .thenReturn(savedApplication) .flatMap(savedMainApp -> { Application unsavedChildApp = new Application(); @@ -3555,8 +3560,8 @@ public void generateSshKeyPair_WhenDefaultApplicationIdSet_DefaultApplicationUpd unsavedChildApp.setWorkspaceId(workspaceId); return applicationPageService.createApplication(unsavedChildApp, workspaceId); }) - .flatMap(savedChildApp -> applicationService - .createOrUpdateSshKeyPair(savedChildApp.getId(), null) + .flatMap(savedChildApp -> artifactService + .createOrUpdateSshKeyPair(ArtifactType.APPLICATION, savedChildApp.getId(), null) .thenReturn(savedChildApp)) .flatMap(savedChildApp -> { // fetch and return both child and main applications diff --git a/app/server/appsmith-server/src/test/java/com/appsmith/server/services/ce/ApplicationSnapshotServiceUnitTest.java b/app/server/appsmith-server/src/test/java/com/appsmith/server/services/ce/ApplicationSnapshotServiceUnitTest.java index f278c9f1143f..b9620e099287 100644 --- a/app/server/appsmith-server/src/test/java/com/appsmith/server/services/ce/ApplicationSnapshotServiceUnitTest.java +++ b/app/server/appsmith-server/src/test/java/com/appsmith/server/services/ce/ApplicationSnapshotServiceUnitTest.java @@ -24,6 +24,7 @@ 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.boot.test.mock.mockito.SpyBean; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; import reactor.test.StepVerifier; @@ -41,7 +42,7 @@ @SpringBootTest public class ApplicationSnapshotServiceUnitTest { - @MockBean + @SpyBean ApplicationService applicationService; @MockBean @@ -82,9 +83,9 @@ public void createApplicationSnapshot_WhenApplicationTooLarge_SnapshotCreatedSuc ApplicationJson applicationJson = new ApplicationJson(); applicationJson.setPageList(List.of(newPage)); - Mockito.when(applicationService.findBranchedApplicationId( - branchName, defaultAppId, AclPermission.MANAGE_APPLICATIONS)) - .thenReturn(Mono.just(branchedAppId)); + Mockito.doReturn(Mono.just(branchedAppId)) + .when(applicationService) + .findBranchedApplicationId(branchName, defaultAppId, AclPermission.MANAGE_APPLICATIONS); Mockito.when(exportService.exportByArtifactId( branchedAppId, SerialiseArtifactObjective.VERSION_CONTROL, ArtifactType.APPLICATION)) @@ -119,8 +120,9 @@ public void restoreSnapshot_WhenSnapshotHasMultipleChunks_RestoredSuccessfully() application.setWorkspaceId(workspaceId); application.setId(branchedAppId); - Mockito.when(applicationService.findById(branchedAppId, AclPermission.MANAGE_APPLICATIONS)) - .thenReturn(Mono.just(application)); + Mockito.doReturn(Mono.just(application)) + .when(applicationService) + .findById(branchedAppId, AclPermission.MANAGE_APPLICATIONS); ApplicationJson applicationJson = new ApplicationJson(); applicationJson.setExportedApplication(application); diff --git a/app/server/appsmith-server/src/test/java/com/appsmith/server/solutions/ce/ActionExecutionSolutionCEImplTest.java b/app/server/appsmith-server/src/test/java/com/appsmith/server/solutions/ce/ActionExecutionSolutionCEImplTest.java index ff664b5ee37c..0fc84add17f8 100644 --- a/app/server/appsmith-server/src/test/java/com/appsmith/server/solutions/ce/ActionExecutionSolutionCEImplTest.java +++ b/app/server/appsmith-server/src/test/java/com/appsmith/server/solutions/ce/ActionExecutionSolutionCEImplTest.java @@ -107,7 +107,7 @@ class ActionExecutionSolutionCEImplTest { @MockBean NewPageService newPageService; - @MockBean + @SpyBean ApplicationService applicationService; @SpyBean
132a0c2e25c30fade152ac2a89ddb550e0e5ef30
2023-08-21 17:23:20
Saroj
ci: Update ce push workflow to use dime defenders (#26527)
false
Update ce push workflow to use dime defenders (#26527)
ci
diff --git a/.github/workflows/test-build-docker-image.yml b/.github/workflows/test-build-docker-image.yml index 8cbf41b2232c..8d409d0ce1eb 100644 --- a/.github/workflows/test-build-docker-image.yml +++ b/.github/workflows/test-build-docker-image.yml @@ -60,7 +60,7 @@ jobs: # Only run if the build step is successful if: success() name: ci-test - uses: ./.github/workflows/ci-test.yml + uses: ./.github/workflows/ci-test-custom-script.yml secrets: inherit with: pr: 0 @@ -102,6 +102,44 @@ jobs: rm -f ~/combined_failed_spec_ci cat ~/failed_spec_ci/failed_spec_ci* >> ~/combined_failed_spec_ci + - name: CI test failures + if: needs.ci-test.result != 'success' + shell: bash + run: | + new_failed_spec_env="<ol>$(sort -u ~/combined_failed_spec_ci | sed 's/|cypress|cypress/\n/g' | sed 's/^/<li>/')</ol>" + echo "$new_failed_spec_env" + echo "new_failed_spec_env<<EOF" >> $GITHUB_ENV + echo "$new_failed_spec_env" >> $GITHUB_ENV + echo "EOF" >> $GITHUB_ENV + + - name: Generate slack message + continue-on-error: true + if: always() + id: slack_notification + run: | + if [[ "${{ needs.ci-test.result }}" != "success" ]]; then + echo "slack_message=There are test failures in the run.<br>${{env.new_failed_spec_env}}<br>Please check the <${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}|Github Actions> for more details." >> $GITHUB_OUTPUT + echo "slack_color=#FF0000" >> $GITHUB_OUTPUT + else + echo "slack_message=All tests passed successfully :tada: . Github Action: <${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}|Click here!>" >> $GITHUB_OUTPUT + echo "slack_color=#00FF00" >> $GITHUB_OUTPUT + fi + + - name: Slack Notification + continue-on-error: true + if: always() + uses: rtCamp/action-slack-notify@v2 + env: + SLACK_CHANNEL: cypresspushworkflow + SLACK_COLOR: ${{steps.slack_notification.outputs.slack_color}} + SLACK_ICON: https://app.slack.com/services/B05D17E4QVB + SLACK_TITLE: 'Result:' + SLACK_USERNAME: Cypress Push Workflows + SLACK_WEBHOOK: ${{ secrets.SLACK_WEBHOOK_HOSTED }} + MSG_MINIMAL: Ref,Event,Commit + SLACK_FOOTER: 'Appsmith Push Workflows' + SLACK_MESSAGE: ${{steps.slack_notification.outputs.slack_message}} + # Force save the CI failed spec list into a cache - name: Store the combined run result for CI if: needs.ci-test.result != 'success'
73b3079a89ce5e323d759c9310cb8bc53f640eb0
2023-12-29 17:51:22
ashit-rath
fix: Revert "chore: Refactoring multiple environments to use editorId instead of appId" (#29942)
false
Revert "chore: Refactoring multiple environments to use editorId instead of appId" (#29942)
fix
diff --git a/app/client/src/ce/actions/applicationActions.ts b/app/client/src/ce/actions/applicationActions.ts index 5070f37d26f0..0f4781432f36 100644 --- a/app/client/src/ce/actions/applicationActions.ts +++ b/app/client/src/ce/actions/applicationActions.ts @@ -219,18 +219,9 @@ export const setIsReconnectingDatasourcesModalOpen = (payload: { payload, }); -export const setWorkspaceIdForImport = ({ - editorId = "", - workspaceId, -}: { - editorId: string; - workspaceId?: string; -}) => ({ +export const setWorkspaceIdForImport = (workspaceId?: string) => ({ type: ReduxActionTypes.SET_WORKSPACE_ID_FOR_IMPORT, - payload: { - workspaceId, - editorId, - }, + payload: workspaceId, }); export const setPageIdForImport = (pageId?: string) => ({ diff --git a/app/client/src/ce/actions/environmentAction.ts b/app/client/src/ce/actions/environmentAction.ts index cf28077c36d7..ff48d6d74760 100644 --- a/app/client/src/ce/actions/environmentAction.ts +++ b/app/client/src/ce/actions/environmentAction.ts @@ -8,15 +8,10 @@ export const setCurrentEditingEnvironmentID = (currentEditingId: string) => ({ }); // Redux action to fetch environments -export const fetchingEnvironmentConfigs = ({ - editorId, +export const fetchingEnvironmentConfigs = ( + workspaceId: string, fetchDatasourceMeta = false, - workspaceId, -}: { - editorId: string; - fetchDatasourceMeta: boolean; - workspaceId: string; -}) => ({ +) => ({ type: "", - payload: { workspaceId, editorId, fetchDatasourceMeta }, + payload: { workspaceId, fetchDatasourceMeta }, }); diff --git a/app/client/src/ce/components/SwitchEnvironment/index.tsx b/app/client/src/ce/components/SwitchEnvironment/index.tsx index 86c89bb4edbe..138c7df6c0ce 100644 --- a/app/client/src/ce/components/SwitchEnvironment/index.tsx +++ b/app/client/src/ce/components/SwitchEnvironment/index.tsx @@ -14,6 +14,7 @@ import { } from "@appsmith/selectors/rampSelectors"; import { isDatasourceInViewMode } from "selectors/ui"; import { matchDatasourcePath, matchSAASGsheetsPath } from "constants/routes"; +import { useLocation } from "react-router"; import { RAMP_NAME, RampFeature, @@ -47,8 +48,6 @@ const StyledIcon = styled(Icon)` interface Props { viewMode?: boolean; - editorId: string; - onChangeEnv?: () => void; } interface EnvironmentType { @@ -75,8 +74,7 @@ const TooltipLink = styled(Link)` `; export default function SwitchEnvironment({}: Props) { - const [disableSwitchEnvironment, setDisableSwitchEnvironment] = - useState(false); + const [diableSwitchEnvironment, setDiableSwitchEnvironment] = useState(false); // Fetching feature flags from the store and checking if the feature is enabled const showRampSelector = showProductRamps(RAMP_NAME.MULTIPLE_ENV, true); const canShowRamp = useSelector(showRampSelector); @@ -85,14 +83,14 @@ export default function SwitchEnvironment({}: Props) { feature: RampFeature.MultipleEnv, }); const rampLink = useSelector(rampLinkSelector); - + const location = useLocation(); //listen to url change and disable switch environment if datasource page is open useEffect(() => { - setDisableSwitchEnvironment( + setDiableSwitchEnvironment( !!matchDatasourcePath(window.location.pathname) || !!matchSAASGsheetsPath(window.location.pathname), ); - }, [window.location.pathname]); + }, [location.pathname]); //URL for datasource edit and review page is same //this parameter helps us to differentiate between the two. const isDatasourceViewMode = useSelector(isDatasourceInViewMode); @@ -127,7 +125,7 @@ export default function SwitchEnvironment({}: Props) { return ( <Wrapper - aria-disabled={disableSwitchEnvironment && !isDatasourceViewMode} + aria-disabled={diableSwitchEnvironment && !isDatasourceViewMode} data-testid="t--switch-env" > <Select @@ -135,7 +133,7 @@ export default function SwitchEnvironment({}: Props) { dropdownClassName="select_environemnt_dropdown" getPopupContainer={(triggerNode) => triggerNode.parentNode.parentNode} isDisabled={ - (disableSwitchEnvironment && !isDatasourceViewMode) || + (diableSwitchEnvironment && !isDatasourceViewMode) || environmentList.length === 1 } listHeight={400} diff --git a/app/client/src/ce/constants/routes/appRoutes.ts b/app/client/src/ce/constants/routes/appRoutes.ts index 11bb2513208e..8b2be99cc246 100644 --- a/app/client/src/ce/constants/routes/appRoutes.ts +++ b/app/client/src/ce/constants/routes/appRoutes.ts @@ -1,9 +1,6 @@ // Leaving this require here. The path-to-regexp module has a commonJS version and an ESM one. // We are loading the correct one with the typings with our compilerOptions property "moduleResolution" set to "node". Ref: https://stackoverflow.com/questions/59013618/unable-to-find-module-path-to-regexp // All solutions from closed issues on their repo have been tried. Ref: https://github.com/pillarjs/path-to-regexp/issues/193 - -import { matchPath } from "react-router"; - // eslint-disable-next-line @typescript-eslint/no-var-requires const { match } = require("path-to-regexp"); @@ -72,19 +69,12 @@ export const APP_STATE_PATH = `/:appState`; export const matchApiBasePath = match(API_EDITOR_BASE_PATH); export const matchApiPath = match(API_EDITOR_ID_PATH); -export const matchDatasourcePath = (pathname: string) => - matchPath(pathname, { - path: [`${BUILDER_PATH}${DATA_SOURCES_EDITOR_ID_PATH}`], - strict: false, - exact: false, - }); - -export const matchSAASGsheetsPath = (pathname: string) => - matchPath(pathname, { - path: [`${BUILDER_PATH}${SAAS_GSHEET_EDITOR_ID_PATH}`], - strict: false, - exact: false, - }); +export const matchDatasourcePath = match( + `${BUILDER_PATH}${DATA_SOURCES_EDITOR_ID_PATH}`, +); +export const matchSAASGsheetsPath = match( + `${BUILDER_PATH}${SAAS_GSHEET_EDITOR_ID_PATH}`, +); export const matchQueryBasePath = match(QUERIES_EDITOR_BASE_PATH); export const matchQueryPath = match(QUERIES_EDITOR_ID_PATH); export const matchQueryBuilderPath = match( diff --git a/app/client/src/ce/pages/Applications/CreateNewAppsOption.tsx b/app/client/src/ce/pages/Applications/CreateNewAppsOption.tsx index 62d4d7533752..05706c41b871 100644 --- a/app/client/src/ce/pages/Applications/CreateNewAppsOption.tsx +++ b/app/client/src/ce/pages/Applications/CreateNewAppsOption.tsx @@ -226,13 +226,7 @@ const CreateNewAppsOption = ({ dispatch(fetchPlugins()); dispatch(fetchMockDatasources()); if (application?.workspaceId) { - dispatch( - fetchingEnvironmentConfigs({ - editorId: application.id, - fetchDatasourceMeta: true, - workspaceId: application?.workspaceId, - }), - ); + dispatch(fetchingEnvironmentConfigs(application?.workspaceId, true)); } setUseType(START_WITH_TYPE.DATA); }; diff --git a/app/client/src/ce/reducers/uiReducers/applicationsReducer.tsx b/app/client/src/ce/reducers/uiReducers/applicationsReducer.tsx index 314c273cbbdf..3e66671144dd 100644 --- a/app/client/src/ce/reducers/uiReducers/applicationsReducer.tsx +++ b/app/client/src/ce/reducers/uiReducers/applicationsReducer.tsx @@ -644,11 +644,11 @@ export const handlers = { }), [ReduxActionTypes.SET_WORKSPACE_ID_FOR_IMPORT]: ( state: ApplicationsReduxState, - action: ReduxAction<{ workspaceId: string }>, + action: ReduxAction<string>, ) => { return { ...state, - workspaceIdForImport: action.payload.workspaceId, + workspaceIdForImport: action.payload, }; }, [ReduxActionTypes.SET_PAGE_ID_FOR_IMPORT]: ( diff --git a/app/client/src/ce/sagas/ApplicationSagas.tsx b/app/client/src/ce/sagas/ApplicationSagas.tsx index a44ba647df16..323ece5954df 100644 --- a/app/client/src/ce/sagas/ApplicationSagas.tsx +++ b/app/client/src/ce/sagas/ApplicationSagas.tsx @@ -317,7 +317,6 @@ export function* fetchAppAndPagesSaga( type: ReduxActionTypes.SET_CURRENT_WORKSPACE_ID, payload: { workspaceId: response.data.workspaceId, - editorId: response.data.application?.id, }, }); @@ -736,7 +735,6 @@ export function* forkApplicationSaga( type: ReduxActionTypes.SET_CURRENT_WORKSPACE_ID, payload: { workspaceId: action.payload.workspaceId, - editorId: application.id, }, }); @@ -801,7 +799,7 @@ export function* showReconnectDatasourcesModalSaga( setUnconfiguredDatasourcesDuringImport(unConfiguredDatasourceList || []), ); - yield put(setWorkspaceIdForImport({ editorId: application.id, workspaceId })); + yield put(setWorkspaceIdForImport(workspaceId)); yield put(setPageIdForImport(pageId)); yield put(setIsReconnectingDatasourcesModalOpen({ isOpen: true })); } diff --git a/app/client/src/ce/sagas/PageSagas.tsx b/app/client/src/ce/sagas/PageSagas.tsx index 1e47763d8029..4011c9c5ffeb 100644 --- a/app/client/src/ce/sagas/PageSagas.tsx +++ b/app/client/src/ce/sagas/PageSagas.tsx @@ -202,7 +202,6 @@ export function* fetchPageListSaga( type: ReduxActionTypes.SET_CURRENT_WORKSPACE_ID, payload: { workspaceId, - editorId: applicationId, }, }); yield put({ diff --git a/app/client/src/components/BottomBar/index.tsx b/app/client/src/components/BottomBar/index.tsx index e6f682b4e19b..26eca910ad66 100644 --- a/app/client/src/components/BottomBar/index.tsx +++ b/app/client/src/components/BottomBar/index.tsx @@ -6,27 +6,12 @@ import ManualUpgrades from "./ManualUpgrades"; import { Button } from "design-system"; import SwitchEnvironment from "@appsmith/components/SwitchEnvironment"; import { Container, Wrapper } from "./components"; -import { useSelector } from "react-redux"; -import { getCurrentApplicationId } from "selectors/editorSelectors"; -import { useDispatch } from "react-redux"; -import { softRefreshActions } from "actions/pluginActionActions"; export default function BottomBar({ viewMode }: { viewMode: boolean }) { - const appId = useSelector(getCurrentApplicationId) || ""; - const dispatch = useDispatch(); - - const onChangeEnv = () => { - dispatch(softRefreshActions()); - }; - return ( <Container> <Wrapper> - <SwitchEnvironment - editorId={appId} - onChangeEnv={onChangeEnv} - viewMode={viewMode} - /> + <SwitchEnvironment viewMode={viewMode} /> {!viewMode && <QuickGitActions />} </Wrapper> {!viewMode && ( diff --git a/app/client/src/pages/Applications/ImportApplicationModal.tsx b/app/client/src/pages/Applications/ImportApplicationModal.tsx index 5baeee1c7e77..406afafcb061 100644 --- a/app/client/src/pages/Applications/ImportApplicationModal.tsx +++ b/app/client/src/pages/Applications/ImportApplicationModal.tsx @@ -204,7 +204,7 @@ function ImportApplicationModal(props: ImportApplicationModalProps) { dispatch({ type: ReduxActionTypes.GIT_INFO_INIT, }); - dispatch(setWorkspaceIdForImport({ editorId: appId || "", workspaceId })); + dispatch(setWorkspaceIdForImport(workspaceId)); dispatch( setIsGitSyncModalOpen({ diff --git a/app/client/src/pages/Editor/gitSync/GitSyncModal/GitSyncModalV1.tsx b/app/client/src/pages/Editor/gitSync/GitSyncModal/GitSyncModalV1.tsx index 8715a75e088a..135815936f14 100644 --- a/app/client/src/pages/Editor/gitSync/GitSyncModal/GitSyncModalV1.tsx +++ b/app/client/src/pages/Editor/gitSync/GitSyncModal/GitSyncModalV1.tsx @@ -29,7 +29,6 @@ import { IMPORT_FROM_GIT_REPOSITORY, } from "@appsmith/constants/messages"; import { GitSyncModalTab } from "entities/GitSync"; -import { getCurrentApplicationId } from "selectors/editorSelectors"; const ModalContentContainer = styled(ModalContent)` min-height: 650px; @@ -68,13 +67,10 @@ function GitSyncModalV1(props: { isImport?: boolean }) { const isGitConnected = useSelector(getIsGitConnected); const activeTabKey = useSelector(getActiveGitSyncModalTab); - const appId = useSelector(getCurrentApplicationId); const handleClose = useCallback(() => { dispatch(setIsGitSyncModalOpen({ isOpen: false })); - dispatch( - setWorkspaceIdForImport({ editorId: appId || "", workspaceId: "" }), - ); + dispatch(setWorkspaceIdForImport("")); }, [dispatch, setIsGitSyncModalOpen]); const setActiveTabKey = useCallback( diff --git a/app/client/src/pages/Editor/gitSync/GitSyncModal/GitSyncModalV2.tsx b/app/client/src/pages/Editor/gitSync/GitSyncModal/GitSyncModalV2.tsx index 51d9b442de62..3757e970da24 100644 --- a/app/client/src/pages/Editor/gitSync/GitSyncModal/GitSyncModalV2.tsx +++ b/app/client/src/pages/Editor/gitSync/GitSyncModal/GitSyncModalV2.tsx @@ -32,7 +32,6 @@ import ConnectionSuccess from "../Tabs/ConnectionSuccess"; import styled from "styled-components"; import ReconnectSSHError from "../components/ReconnectSSHError"; import { getCurrentAppGitMetaData } from "@appsmith/selectors/applicationSelectors"; -import { getCurrentApplicationId } from "selectors/editorSelectors"; const StyledModalContent = styled(ModalContent)` &&& { @@ -54,7 +53,6 @@ function GitSyncModalV2({ isImport = false }: GitSyncModalV2Props) { const isModalOpen = useSelector(getIsGitSyncModalOpen); const isGitConnected = useSelector(getIsGitConnected); const isDeploying = useSelector(getIsDeploying); - const appId = useSelector(getCurrentApplicationId); const menuOptions = [ { @@ -115,9 +113,7 @@ function GitSyncModalV2({ isImport = false }: GitSyncModalV2Props) { const handleClose = useCallback(() => { dispatch(setIsGitSyncModalOpen({ isOpen: false })); - dispatch( - setWorkspaceIdForImport({ editorId: appId || "", workspaceId: "" }), - ); + dispatch(setWorkspaceIdForImport("")); }, [dispatch, setIsGitSyncModalOpen]); return ( diff --git a/app/client/src/pages/Editor/gitSync/ReconnectDatasourceModal.tsx b/app/client/src/pages/Editor/gitSync/ReconnectDatasourceModal.tsx index 00663324fe8b..ab172e91b064 100644 --- a/app/client/src/pages/Editor/gitSync/ReconnectDatasourceModal.tsx +++ b/app/client/src/pages/Editor/gitSync/ReconnectDatasourceModal.tsx @@ -348,12 +348,7 @@ function ReconnectDatasourceModal() { (app: any) => app.id === queryAppId, ); if (application) { - dispatch( - setWorkspaceIdForImport({ - editorId: appId || "", - workspaceId: workspace.id, - }), - ); + dispatch(setWorkspaceIdForImport(workspace.id)); dispatch(setIsReconnectingDatasourcesModalOpen({ isOpen: true })); const defaultPageId = getDefaultPageId(application.pages); if (pageIdForImport) { @@ -433,9 +428,7 @@ function ReconnectDatasourceModal() { const onClose = () => { localStorage.setItem("importedAppPendingInfo", "null"); dispatch(setIsReconnectingDatasourcesModalOpen({ isOpen: false })); - dispatch( - setWorkspaceIdForImport({ editorId: appId || "", workspaceId: "" }), - ); + dispatch(setWorkspaceIdForImport("")); dispatch(setPageIdForImport("")); dispatch(resetDatasourceConfigForImportFetchedFlag()); setSelectedDatasourceId(""); diff --git a/app/client/src/pages/Editor/gitSync/Tabs/GitConnectionV2/ChooseGitProvider.tsx b/app/client/src/pages/Editor/gitSync/Tabs/GitConnectionV2/ChooseGitProvider.tsx index 2a1e9ed59de9..00d68295007d 100644 --- a/app/client/src/pages/Editor/gitSync/Tabs/GitConnectionV2/ChooseGitProvider.tsx +++ b/app/client/src/pages/Editor/gitSync/Tabs/GitConnectionV2/ChooseGitProvider.tsx @@ -42,7 +42,6 @@ import { createMessage, } from "@appsmith/constants/messages"; import AnalyticsUtil from "utils/AnalyticsUtil"; -import { getCurrentApplicationId } from "selectors/editorSelectors"; const WellInnerContainer = styled.div` padding-left: 16px; @@ -71,7 +70,6 @@ function ChooseGitProvider({ onChange = noop, value = {}, }: ChooseGitProviderProps) { - const appId = useSelector(getCurrentApplicationId); const workspace = useSelector(getCurrentAppWorkspace); const isMobile = useIsMobileDevice(); @@ -82,12 +80,7 @@ function ChooseGitProvider({ dispatch({ type: ReduxActionTypes.GIT_INFO_INIT, }); - dispatch( - setWorkspaceIdForImport({ - editorId: appId || "", - workspaceId: workspace.id, - }), - ); + dispatch(setWorkspaceIdForImport(workspace.id)); dispatch( setIsGitSyncModalOpen({ diff --git a/app/client/src/utils/storage.ts b/app/client/src/utils/storage.ts index e1df8e6ed8e4..9ee97910d1a4 100644 --- a/app/client/src/utils/storage.ts +++ b/app/client/src/utils/storage.ts @@ -116,29 +116,10 @@ export const getCopiedWidgets = async () => { return []; }; -export const updateCurrentEnvironmentDetails = async () => { - try { - const currentEnvDetails = await getSavedCurrentEnvironmentDetails(false); - if (currentEnvDetails.appId) { - await store.setItem(STORAGE_KEYS.CURRENT_ENV, { - envId: currentEnvDetails.envId, - editorId: currentEnvDetails.appId, - }); - } - return true; - } catch (error) { - log.error("An error occurred when updating current env: ", error); - return false; - } -}; - // Function to save the current environment and the appId in indexedDB -export const saveCurrentEnvironment = async ( - envId: string, - editorId: string, -) => { +export const saveCurrentEnvironment = async (envId: string, appId: string) => { try { - await store.setItem(STORAGE_KEYS.CURRENT_ENV, { envId, editorId }); + await store.setItem(STORAGE_KEYS.CURRENT_ENV, { envId, appId }); return true; } catch (error) { log.error("An error occurred when storing current env: ", error); @@ -147,28 +128,22 @@ export const saveCurrentEnvironment = async ( }; // Function to fetch the current environment and related appId from indexedDB -export const getSavedCurrentEnvironmentDetails = async ( - callUpdate = true, -): Promise<{ +export const getSavedCurrentEnvironmentDetails = async (): Promise<{ envId: string; - editorId: string; - appId?: string; + appId: string; }> => { try { - if (callUpdate) { - await updateCurrentEnvironmentDetails(); - } return ( (await store.getItem(STORAGE_KEYS.CURRENT_ENV)) || { envId: "", - editorId: "", + appId: "", } ); } catch (error) { log.error("An error occurred when fetching current env: ", error); return { envId: "", - editorId: "", + appId: "", }; } };
33d834719378282616040ab79367af9fced00681
2022-05-19 12:41:54
Bhavin K
fix: handle selectedValues value (#13887)
false
handle selectedValues value (#13887)
fix
diff --git a/app/client/src/widgets/CheckboxGroupWidget/widget/index.tsx b/app/client/src/widgets/CheckboxGroupWidget/widget/index.tsx index a7e7086b45b7..4451cb6b8cad 100644 --- a/app/client/src/widgets/CheckboxGroupWidget/widget/index.tsx +++ b/app/client/src/widgets/CheckboxGroupWidget/widget/index.tsx @@ -519,7 +519,7 @@ class CheckboxGroupWidget extends BaseWidget< optionAlignment={this.props.optionAlignment} options={compact(this.props.options)} rowSpace={this.props.parentRowSpace} - selectedValues={this.props.selectedValues} + selectedValues={this.props.selectedValues || []} widgetId={this.props.widgetId} /> ); @@ -531,7 +531,7 @@ class CheckboxGroupWidget extends BaseWidget< private handleCheckboxChange = (value: string) => { return (event: React.FormEvent<HTMLElement>) => { - let { selectedValues } = this.props; + let { selectedValues = [] } = this.props; const isChecked = (event.target as HTMLInputElement).checked; if (isChecked) { selectedValues = [...selectedValues, value]; @@ -558,7 +558,7 @@ class CheckboxGroupWidget extends BaseWidget< private handleSelectAllChange = (state: SelectAllState) => { return () => { - let { selectedValues } = this.props; + let { selectedValues = [] } = this.props; switch (state) { case SelectAllStates.UNCHECKED:
d52490cabb2a80ea4d3f9ce644e3707b021329c9
2024-12-23 15:15:53
Subhrashis Das
feat: Standardize log patterns across all services for consistency. (#38285)
false
Standardize log patterns across all services for consistency. (#38285)
feat
diff --git a/deploy/docker/fs/opt/appsmith/templates/supervisord/application_process/backend.conf b/deploy/docker/fs/opt/appsmith/templates/supervisord/application_process/backend.conf index a9f4ed00ecdd..37674e8dd166 100644 --- a/deploy/docker/fs/opt/appsmith/templates/supervisord/application_process/backend.conf +++ b/deploy/docker/fs/opt/appsmith/templates/supervisord/application_process/backend.conf @@ -1,15 +1,15 @@ [program:backend] command=/opt/appsmith/run-with-env.sh /opt/appsmith/run-java.sh -priority=20 -autostart=true autorestart=true -startsecs=20 +autostart=true +priority=20 startretries=3 -stdout_logfile=%(ENV_APPSMITH_LOG_DIR)s/%(program_name)s/%(program_name)s-%(ENV_HOSTNAME)s.log -redirect_stderr=true -stdout_logfile_maxbytes=10MB -stderr_logfile_maxbytes=10MB -stdout_logfile_backups=10 -stderr_logfile_backups=10 -stdout_events_enabled=true +startsecs=20 stderr_events_enabled=true +stderr_logfile=%(ENV_APPSMITH_LOG_DIR)s/%(program_name)s/%(ENV_HOSTNAME)s-stderr.log +stderr_logfile_backups=0 +stderr_logfile_maxbytes=30MB +stdout_events_enabled=true +stdout_logfile=%(ENV_APPSMITH_LOG_DIR)s/%(program_name)s/%(ENV_HOSTNAME)s-stdout.log +stdout_logfile_backups=0 +stdout_logfile_maxbytes=30MB diff --git a/deploy/docker/fs/opt/appsmith/templates/supervisord/application_process/editor.conf b/deploy/docker/fs/opt/appsmith/templates/supervisord/application_process/editor.conf index 8fa54215d50d..0efa5a7b4eb2 100644 --- a/deploy/docker/fs/opt/appsmith/templates/supervisord/application_process/editor.conf +++ b/deploy/docker/fs/opt/appsmith/templates/supervisord/application_process/editor.conf @@ -1,16 +1,16 @@ [program:editor] command=/opt/appsmith/run-with-env.sh /opt/appsmith/run-caddy.sh -priority=25 -autostart=true autorestart=true -startsecs=0 +autostart=true +priority=25 startretries=3 -stdout_logfile=%(ENV_APPSMITH_LOG_DIR)s/%(program_name)s/access-%(ENV_HOSTNAME)s.log -stderr_logfile=%(ENV_APPSMITH_LOG_DIR)s/%(program_name)s/error-%(ENV_HOSTNAME)s.log -stdout_logfile_maxbytes=10MB -stderr_logfile_maxbytes=10MB -stdout_logfile_backups=2 -stderr_logfile_backups=2 -stdout_events_enabled=true +startsecs=0 stderr_events_enabled=true +stderr_logfile=%(ENV_APPSMITH_LOG_DIR)s/%(program_name)s/%(ENV_HOSTNAME)s-stderr.log +stderr_logfile_backups=0 +stderr_logfile_maxbytes=30MB +stdout_events_enabled=true +stdout_logfile=%(ENV_APPSMITH_LOG_DIR)s/%(program_name)s/%(ENV_HOSTNAME)s-stdout.log +stdout_logfile_backups=0 +stdout_logfile_maxbytes=30MB stopsignal=QUIT diff --git a/deploy/docker/fs/opt/appsmith/templates/supervisord/application_process/rts.conf b/deploy/docker/fs/opt/appsmith/templates/supervisord/application_process/rts.conf index 6900f17a17fc..2ff862db027f 100644 --- a/deploy/docker/fs/opt/appsmith/templates/supervisord/application_process/rts.conf +++ b/deploy/docker/fs/opt/appsmith/templates/supervisord/application_process/rts.conf @@ -1,16 +1,16 @@ [program:rts] directory=/opt/appsmith/rts/bundle command=/opt/appsmith/run-with-env.sh node server.js -priority=15 -autostart=true autorestart=true -startsecs=0 +autostart=true +priority=15 startretries=3 -stdout_logfile=%(ENV_APPSMITH_LOG_DIR)s/%(program_name)s/%(program_name)s-%(ENV_HOSTNAME)s.log -redirect_stderr=true -stdout_logfile_maxbytes=10MB -stderr_logfile_maxbytes=10MB -stdout_logfile_backups=2 -stderr_logfile_backups=2 -stdout_events_enabled=true +startsecs=0 stderr_events_enabled=true +stderr_logfile=%(ENV_APPSMITH_LOG_DIR)s/%(program_name)s/%(ENV_HOSTNAME)s-stderr.log +stderr_logfile_backups=0 +stderr_logfile_maxbytes=30MB +stdout_events_enabled=true +stdout_logfile=%(ENV_APPSMITH_LOG_DIR)s/%(program_name)s/%(ENV_HOSTNAME)s-stdout.log +stdout_logfile_backups=0 +stdout_logfile_maxbytes=30MB diff --git a/deploy/docker/fs/opt/appsmith/templates/supervisord/mongodb.conf b/deploy/docker/fs/opt/appsmith/templates/supervisord/mongodb.conf index 7e7b0a7bd392..3072b0fe5f16 100644 --- a/deploy/docker/fs/opt/appsmith/templates/supervisord/mongodb.conf +++ b/deploy/docker/fs/opt/appsmith/templates/supervisord/mongodb.conf @@ -1,16 +1,16 @@ [program:mongodb] directory=/appsmith-stacks/data/mongodb command=mongod --port 27017 --dbpath . --logpath %(ENV_APPSMITH_LOG_DIR)s/%(program_name)s/db.log --replSet mr1 --keyFile %(ENV_MONGODB_TMP_KEY_PATH)s --bind_ip localhost -priority=10 -autostart=true autorestart=true -startsecs=10 +autostart=true +priority=10 startretries=3 -stdout_logfile=%(ENV_APPSMITH_LOG_DIR)s/%(program_name)s/%(program_name)s.log -redirect_stderr=true -stdout_logfile_maxbytes=10MB -stderr_logfile_maxbytes=10MB -stdout_logfile_backups=2 -stderr_logfile_backups=2 -stdout_events_enabled=true +startsecs=10 stderr_events_enabled=true +stderr_logfile=%(ENV_APPSMITH_LOG_DIR)s/%(program_name)s/%(ENV_HOSTNAME)s-stderr.log +stderr_logfile_backups=0 +stderr_logfile_maxbytes=30MB +stdout_events_enabled=true +stdout_logfile=%(ENV_APPSMITH_LOG_DIR)s/%(program_name)s/%(ENV_HOSTNAME)s-stdout.log +stdout_logfile_backups=0 +stdout_logfile_maxbytes=30MB diff --git a/deploy/docker/fs/opt/appsmith/templates/supervisord/postgres.conf b/deploy/docker/fs/opt/appsmith/templates/supervisord/postgres.conf index 2dd1aa8d0596..8886239f88ed 100644 --- a/deploy/docker/fs/opt/appsmith/templates/supervisord/postgres.conf +++ b/deploy/docker/fs/opt/appsmith/templates/supervisord/postgres.conf @@ -2,15 +2,14 @@ directory=/appsmith-stacks/data/postgres/main user=postgres command=/opt/appsmith/run-postgres.sh -autostart=true autorestart=true +autostart=true startretries=3 -stdout_logfile=%(ENV_APPSMITH_LOG_DIR)s/%(program_name)s/%(program_name)s.log -redirect_stderr=true -stdout_logfile_maxbytes=10MB -stderr_logfile_maxbytes=10MB -stdout_logfile_backups=2 -stderr_logfile_backups=2 -stdout_events_enabled=true stderr_events_enabled=true - +stderr_logfile=%(ENV_APPSMITH_LOG_DIR)s/%(program_name)s/%(ENV_HOSTNAME)s-stderr.log +stderr_logfile_backups=0 +stderr_logfile_maxbytes=30MB +stdout_events_enabled=true +stdout_logfile=%(ENV_APPSMITH_LOG_DIR)s/%(program_name)s/%(ENV_HOSTNAME)s-stdout.log +stdout_logfile_backups=0 +stdout_logfile_maxbytes=30MB diff --git a/deploy/docker/fs/opt/appsmith/templates/supervisord/redis.conf b/deploy/docker/fs/opt/appsmith/templates/supervisord/redis.conf index 5fb91c84fe9d..e02ef0a7bec8 100644 --- a/deploy/docker/fs/opt/appsmith/templates/supervisord/redis.conf +++ b/deploy/docker/fs/opt/appsmith/templates/supervisord/redis.conf @@ -3,16 +3,16 @@ directory=/etc/redis ; The `--save` is for saving session data to disk more often, so recent sessions aren't cleared on restart. ; The empty string to `--logfile` is for logging to stdout so that supervisor can capture it. command=redis-server --save 15 1 --dir /appsmith-stacks/data/redis --daemonize no --logfile "" -priority=5 -autostart=true autorestart=true -startsecs=0 +autostart=true +priority=5 startretries=3 -stdout_logfile=%(ENV_APPSMITH_LOG_DIR)s/%(program_name)s/%(program_name)s.log -redirect_stderr=true -stdout_logfile_maxbytes=10MB -stderr_logfile_maxbytes=10MB -stdout_logfile_backups=2 -stderr_logfile_backups=2 -stdout_events_enabled=true +startsecs=0 stderr_events_enabled=true +stderr_logfile=%(ENV_APPSMITH_LOG_DIR)s/%(program_name)s/%(ENV_HOSTNAME)s-stderr.log +stderr_logfile_backups=0 +stderr_logfile_maxbytes=30MB +stdout_events_enabled=true +stdout_logfile=%(ENV_APPSMITH_LOG_DIR)s/%(program_name)s/%(ENV_HOSTNAME)s-stdout.log +stdout_logfile_backups=0 +stdout_logfile_maxbytes=30MB
dd7ad6a3ed799a7f41d4ed62a3aabb182a8e1315
2021-09-08 17:05:06
Ayush Pahwa
feat: Updating query fom render according to new json structure (#7188)
false
Updating query fom render according to new json structure (#7188)
feat
diff --git a/app/client/src/pages/Editor/QueryEditor/EditorJSONtoForm.tsx b/app/client/src/pages/Editor/QueryEditor/EditorJSONtoForm.tsx index eab8099c1b30..0bfa35908fc7 100644 --- a/app/client/src/pages/Editor/QueryEditor/EditorJSONtoForm.tsx +++ b/app/client/src/pages/Editor/QueryEditor/EditorJSONtoForm.tsx @@ -508,66 +508,62 @@ export function EditorJSONtoForm(props: Props) { const renderConfig = (editorConfig: any) => { // Selectively rendering form based on uiComponent prop return uiComponent === UIComponentTypes.UQIDbEditorForm - ? editorConfig.map(renderEachConfigV2(formName)) + ? editorConfig.map((config: any, idx: number) => { + return renderEachConfigV2(formName, config, idx); + }) : editorConfig.map(renderEachConfig(formName)); }; // V2 call to make rendering more flexible, used for UQI forms - const renderEachConfigV2 = (formName: string) => (section: any): any => { - return section.children.map( - (formControlOrSection: ControlProps, idx: number) => { - if ( - !!formControlOrSection && - props.hasOwnProperty("formEvaluationState") && - !!props.formEvaluationState - ) { - let allowToRender = true; - if ( - formControlOrSection.hasOwnProperty("configProperty") && - props.formEvaluationState.hasOwnProperty( - formControlOrSection.configProperty, - ) - ) { - allowToRender = - props?.formEvaluationState[formControlOrSection.configProperty] - .visible; - } else if ( - formControlOrSection.hasOwnProperty("serverLabel") && - !!formControlOrSection.serverLabel && - props.formEvaluationState.hasOwnProperty( - formControlOrSection.serverLabel, - ) - ) { - allowToRender = - props?.formEvaluationState[formControlOrSection.serverLabel] - .visible; - } - - if (!allowToRender) return null; - } - - // If component is type section, render it's children - if ( - formControlOrSection.hasOwnProperty("controlType") && - formControlOrSection.controlType === "SECTION" && - formControlOrSection.hasOwnProperty("children") - ) { - return renderEachConfigV2(formName)(formControlOrSection); - } - try { - const { configProperty } = formControlOrSection; - return ( - <FieldWrapper key={`${configProperty}_${idx}`}> - <FormControl config={formControlOrSection} formName={formName} /> - </FieldWrapper> - ); - } catch (e) { - log.error(e); - } - - return null; - }, - ); + const renderEachConfigV2 = (formName: string, section: any, idx: number) => { + if ( + !!section && + props.hasOwnProperty("formEvaluationState") && + !!props.formEvaluationState + ) { + let allowToRender = true; + if ( + section.hasOwnProperty("configProperty") && + props.formEvaluationState.hasOwnProperty(section.configProperty) + ) { + allowToRender = + props?.formEvaluationState[section.configProperty].visible; + } else if ( + section.hasOwnProperty("identifier") && + !!section.identifier && + props.formEvaluationState.hasOwnProperty(section.identifier) + ) { + allowToRender = props?.formEvaluationState[section.identifier].visible; + } + + if (!allowToRender) return null; + } + if (section.hasOwnProperty("controlType")) { + // If component is type section, render it's children + if ( + section.controlType === "SECTION" && + section.hasOwnProperty("children") + ) { + return section.children.map((section: any, idx: number) => { + return renderEachConfigV2(formName, section, idx); + }); + } + try { + const { configProperty } = section; + return ( + <FieldWrapper key={`${configProperty}_${idx}`}> + <FormControl config={section} formName={formName} /> + </FieldWrapper> + ); + } catch (e) { + log.error(e); + } + } else { + return section.map((section: any, idx: number) => { + renderEachConfigV2(formName, section, idx); + }); + } + return null; }; // Recursive call to render forms pre UQI diff --git a/app/client/src/sagas/FormEvaluationSaga.ts b/app/client/src/sagas/FormEvaluationSaga.ts index 232f07838a6d..4ad7ddc6e812 100644 --- a/app/client/src/sagas/FormEvaluationSaga.ts +++ b/app/client/src/sagas/FormEvaluationSaga.ts @@ -25,13 +25,13 @@ const generateInitialEvalState = (formConfig: any) => { // Any element is only added to the eval state if they have a conditional statement present, if not they are allowed to be rendered if (formConfig.hasOwnProperty("conditionals")) { - let key = "unkowns"; + let key = "unknowns"; // A unique key is used to refer the object in the eval state, can be configProperty or serverLabel if (formConfig.hasOwnProperty("configProperty")) { key = formConfig.configProperty; - } else if (formConfig.hasOwnProperty("serverLabel")) { - key = formConfig.serverLabel; + } else if (formConfig.hasOwnProperty("identifier")) { + key = formConfig.identifier; } // Conditionals are stored in the eval state itself for quick access