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
774c8ca0c51b1b8c86707a84f8fedfd34bea6998
2024-12-18 14:34:15
Nidhi
test: CGS discard tests (#38206)
false
CGS discard tests (#38206)
test
diff --git a/app/server/appsmith-server/src/test/java/com/appsmith/server/git/ops/GitDiscardTests.java b/app/server/appsmith-server/src/test/java/com/appsmith/server/git/ops/GitDiscardTests.java new file mode 100644 index 000000000000..7ca39f4bcb55 --- /dev/null +++ b/app/server/appsmith-server/src/test/java/com/appsmith/server/git/ops/GitDiscardTests.java @@ -0,0 +1,293 @@ +package com.appsmith.server.git.ops; + +import com.appsmith.external.dtos.GitStatusDTO; +import com.appsmith.external.dtos.MergeStatusDTO; +import com.appsmith.external.git.handler.FSGitHandler; +import com.appsmith.server.applications.base.ApplicationService; +import com.appsmith.server.constants.ArtifactType; +import com.appsmith.server.domains.Application; +import com.appsmith.server.domains.GitArtifactMetadata; +import com.appsmith.server.domains.GitAuth; +import com.appsmith.server.domains.GitProfile; +import com.appsmith.server.domains.User; +import com.appsmith.server.domains.Workspace; +import com.appsmith.server.dtos.ApplicationJson; +import com.appsmith.server.dtos.ArtifactExchangeJson; +import com.appsmith.server.dtos.GitConnectDTO; +import com.appsmith.server.dtos.PageDTO; +import com.appsmith.server.git.central.CentralGitService; +import com.appsmith.server.git.central.GitHandlingService; +import com.appsmith.server.git.central.GitType; +import com.appsmith.server.helpers.CommonGitFileUtils; +import com.appsmith.server.helpers.MockPluginExecutor; +import com.appsmith.server.helpers.PluginExecutorHelper; +import com.appsmith.server.migrations.JsonSchemaMigration; +import com.appsmith.server.services.ApplicationPageService; +import com.appsmith.server.services.UserService; +import com.appsmith.server.services.WorkspaceService; +import com.fasterxml.jackson.databind.MapperFeature; +import com.fasterxml.jackson.databind.ObjectMapper; +import org.apache.commons.lang.StringUtils; +import org.eclipse.jgit.api.errors.GitAPIException; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestInstance; +import org.mockito.Mockito; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.mock.mockito.SpyBean; +import org.springframework.core.io.ClassPathResource; +import org.springframework.security.test.context.support.WithUserDetails; +import reactor.core.publisher.Mono; +import reactor.test.StepVerifier; + +import java.io.IOException; +import java.nio.charset.Charset; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.time.Duration; +import java.util.UUID; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; + +@SpringBootTest +@TestInstance(TestInstance.Lifecycle.PER_CLASS) +public class GitDiscardTests { + + @Autowired + CentralGitService centralGitService; + + @Autowired + ApplicationService applicationService; + + @Autowired + ApplicationPageService applicationPageService; + + @Autowired + WorkspaceService workspaceService; + + @Autowired + UserService userService; + + @Autowired + ObjectMapper objectMapper; + + @Autowired + JsonSchemaMigration jsonSchemaMigration; + + @SpyBean + FSGitHandler fsGitHandler; + + @SpyBean + CommonGitFileUtils commonGitFileUtils; + + @SpyBean + GitHandlingService gitHandlingService; + + @SpyBean + PluginExecutorHelper pluginExecutorHelper; + + private Application createApplicationConnectedToGit(String name, String branchName, String workspaceId) + throws IOException { + + Mockito.doReturn(Mono.just(new MockPluginExecutor())) + .when(pluginExecutorHelper) + .getPluginExecutor(any()); + + if (StringUtils.isEmpty(branchName)) { + branchName = "foo"; + } + Mockito.doReturn(Mono.just(branchName)) + .when(fsGitHandler) + .cloneRemoteIntoArtifactRepo(any(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString()); + Mockito.doReturn(Mono.just("commit")) + .when(fsGitHandler) + .commitArtifact( + any(Path.class), + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyBoolean(), + Mockito.anyBoolean()); + Mockito.doReturn(Mono.just(true)).when(fsGitHandler).checkoutToBranch(any(Path.class), Mockito.anyString()); + Mockito.doReturn(Mono.just("success")) + .when(fsGitHandler) + .pushApplication(any(Path.class), any(), any(), any(), any()); + Mockito.doReturn(Mono.just(true)).when(commonGitFileUtils).checkIfDirectoryIsEmpty(any(Path.class)); + Mockito.doReturn(Mono.just(Paths.get("textPath"))) + .when(commonGitFileUtils) + .initializeReadme(any(Path.class), Mockito.anyString(), Mockito.anyString()); + Mockito.doReturn(Mono.just(Paths.get("path"))) + .when(commonGitFileUtils) + .saveArtifactToLocalRepoWithAnalytics(any(Path.class), any(), Mockito.anyString()); + + Application testApplication = new Application(); + testApplication.setName(name); + testApplication.setWorkspaceId(workspaceId); + Application application1 = + applicationPageService.createApplication(testApplication).block(); + + GitArtifactMetadata gitArtifactMetadata = new GitArtifactMetadata(); + GitAuth gitAuth = new GitAuth(); + gitAuth.setPublicKey("testkey"); + gitAuth.setPrivateKey("privatekey"); + gitArtifactMetadata.setGitAuth(gitAuth); + gitArtifactMetadata.setDefaultApplicationId(application1.getId()); + gitArtifactMetadata.setRepoName("testRepo"); + application1.setGitApplicationMetadata(gitArtifactMetadata); + application1 = applicationService.save(application1).block(); + + PageDTO page = new PageDTO(); + page.setName("New Page"); + page.setApplicationId(application1.getId()); + applicationPageService.createPage(page).block(); + + GitProfile gitProfile = new GitProfile(); + gitProfile.setAuthorEmail("[email protected]"); + gitProfile.setAuthorName("testUser"); + GitConnectDTO gitConnectDTO = new GitConnectDTO(); + gitConnectDTO.setRemoteUrl("[email protected]:test/testRepo.git"); + gitConnectDTO.setGitProfile(gitProfile); + return centralGitService + .connectArtifactToGit( + application1.getId(), gitConnectDTO, "baseUrl", ArtifactType.APPLICATION, GitType.FILE_SYSTEM) + .map(artifact -> (Application) artifact) + .block(); + } + + private Mono<? extends ArtifactExchangeJson> createArtifactJson(String filePath) throws IOException { + + ClassPathResource classPathResource = new ClassPathResource(filePath); + + String artifactJson = classPathResource.getContentAsString(Charset.defaultCharset()); + + Class<? extends ArtifactExchangeJson> exchangeJsonType = ApplicationJson.class; + + ArtifactExchangeJson artifactExchangeJson = + objectMapper.copy().disable(MapperFeature.USE_ANNOTATIONS).readValue(artifactJson, exchangeJsonType); + + return jsonSchemaMigration.migrateArtifactExchangeJsonToLatestSchema(artifactExchangeJson, null, null); + } + + @Test + @WithUserDetails(value = "api_user") + public void discardChanges_whenUpstreamChangesAvailable_discardsSuccessfully() throws IOException { + User apiUser = userService.findByEmail("api_user").block(); + Workspace toCreate = new Workspace(); + toCreate.setName("Workspace_" + UUID.randomUUID()); + Workspace workspace = + workspaceService.create(toCreate, apiUser, Boolean.FALSE).block(); + assertThat(workspace).isNotNull(); + + Application application = + createApplicationConnectedToGit("discard-changes", "discard-change-branch", workspace.getId()); + MergeStatusDTO mergeStatusDTO = new MergeStatusDTO(); + mergeStatusDTO.setStatus("2 commits pulled"); + mergeStatusDTO.setMergeAble(true); + + ArtifactExchangeJson artifactExchangeJson = createArtifactJson( + "test_assets/ImportExportServiceTest/valid-application-without-action-collection.json") + .block(); + ((Application) artifactExchangeJson.getArtifact()).setName("discardChangesAvailable"); + + GitStatusDTO gitStatusDTO = new GitStatusDTO(); + gitStatusDTO.setAheadCount(2); + gitStatusDTO.setBehindCount(0); + gitStatusDTO.setIsClean(true); + + Mockito.doReturn(Mono.just(Paths.get("path"))) + .when(commonGitFileUtils) + .saveArtifactToLocalRepoWithAnalytics(any(Path.class), any(), Mockito.anyString()); + Mockito.doReturn(Mono.just(artifactExchangeJson)) + .when(gitHandlingService) + .recreateArtifactJsonFromLastCommit(Mockito.any()); + Mockito.doReturn(Mono.just(true)).when(fsGitHandler).rebaseBranch(any(Path.class), Mockito.anyString()); + + Mono<Application> applicationMono = centralGitService + .discardChanges(application.getId(), ArtifactType.APPLICATION, GitType.FILE_SYSTEM) + .map(artifact -> (Application) artifact); + + StepVerifier.create(applicationMono) + .assertNext(application1 -> { + assertThat(application1.getPages()).isNotEqualTo(application.getPages()); + }) + .verifyComplete(); + } + + @Test + @WithUserDetails(value = "api_user") + public void discardChanges_whenCancelledMidway_discardsSuccessfully() throws IOException, GitAPIException { + User apiUser = userService.findByEmail("api_user").block(); + Workspace toCreate = new Workspace(); + toCreate.setName("Workspace_" + UUID.randomUUID()); + Workspace workspace = + workspaceService.create(toCreate, apiUser, Boolean.FALSE).block(); + assertThat(workspace).isNotNull(); + + Application application = createApplicationConnectedToGit( + "discard-changes-midway", "discard-change-midway-branch", workspace.getId()); + MergeStatusDTO mergeStatusDTO = new MergeStatusDTO(); + mergeStatusDTO.setStatus("Nothing to fetch from remote. All changes are upto date."); + mergeStatusDTO.setMergeAble(true); + + ArtifactExchangeJson artifactExchangeJson = createArtifactJson( + "test_assets/ImportExportServiceTest/valid-application-without-action-collection.json") + .block(); + ((Application) artifactExchangeJson.getArtifact()).setName("discard-changes-midway"); + + GitStatusDTO gitStatusDTO = new GitStatusDTO(); + gitStatusDTO.setAheadCount(0); + gitStatusDTO.setBehindCount(0); + gitStatusDTO.setIsClean(true); + + Mockito.doReturn(Mono.just(Paths.get("path"))) + .when(commonGitFileUtils) + .saveArtifactToLocalRepoWithAnalytics(any(Path.class), any(), Mockito.anyString()); + Mockito.doReturn(Mono.just(artifactExchangeJson)) + .when(gitHandlingService) + .recreateArtifactJsonFromLastCommit(Mockito.any()); + Mockito.doReturn(Mono.just(mergeStatusDTO)) + .when(fsGitHandler) + .pullApplication( + any(Path.class), + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyString()); + Mockito.doReturn(Mono.just(gitStatusDTO)).when(fsGitHandler).getStatus(any(Path.class), Mockito.anyString()); + Mockito.doReturn(Mono.just("fetched")) + .when(fsGitHandler) + .fetchRemote( + any(Path.class), + Mockito.anyString(), + Mockito.anyString(), + eq(true), + Mockito.anyString(), + Mockito.anyBoolean()); + + centralGitService + .discardChanges(application.getId(), ArtifactType.APPLICATION, GitType.FILE_SYSTEM) + .map(artifact -> (Application) artifact) + .timeout(Duration.ofNanos(100)) + .subscribe(); + + // Wait for git clone to complete + Mono<Application> applicationFromDbMono = Mono.just(application).flatMap(application1 -> { + try { + // Before fetching the git connected application, sleep for 5 seconds to ensure that the clone + // completes + Thread.sleep(5000); + } catch (InterruptedException e) { + e.printStackTrace(); + } + return applicationService.getById(application1.getId()); + }); + + StepVerifier.create(applicationFromDbMono) + .assertNext(application1 -> { + assertThat(application1).isNotEqualTo(application); + }) + .verifyComplete(); + } +}
3370e7e284f3d9316dc9c3a84035b23443d65ab1
2023-11-09 16:35:18
Nidhi
chore: Refactored on page load logic to be generic wrt creator context (#28633)
false
Refactored on page load logic to be generic wrt creator context (#28633)
chore
diff --git a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/CreatorContextType.java b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/CreatorContextType.java new file mode 100644 index 000000000000..67c26876938e --- /dev/null +++ b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/CreatorContextType.java @@ -0,0 +1,6 @@ +package com.appsmith.external.models; + +public enum CreatorContextType { + PAGE, + MODULE +} diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/exceptions/AppsmithError.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/exceptions/AppsmithError.java index 7058e16a81c3..debdd9841d24 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/exceptions/AppsmithError.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/exceptions/AppsmithError.java @@ -200,10 +200,11 @@ public enum AppsmithError { + " \"message\" : \"Binding path in the widget not found. Please reach out to Appsmith customer support to resolve this.\"," + " \"widgetName\" : \"{1}\"," + " \"widgetId\" : \"{2}\"," - + " \"pageId\" : \"{4}\"," + + " \"creatorId\" : \"{4}\"," + " \"layoutId\" : \"{5}\"," + " \"errorDetail\" : \"{8}\"," - + " \"dynamicBinding\" : {6}", + + " \"dynamicBinding\" : {6}," + + " \"creatorType\" : \"{9}\"", AppsmithErrorAction.LOG_EXTERNALLY, "Invalid dynamic binding reference", ErrorType.BAD_REQUEST, diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/newactions/onpageload/ActionOnPageLoadServiceCEImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/newactions/onpageload/ActionOnPageLoadServiceCEImpl.java deleted file mode 100644 index 87819addff3b..000000000000 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/newactions/onpageload/ActionOnPageLoadServiceCEImpl.java +++ /dev/null @@ -1,47 +0,0 @@ -package com.appsmith.server.newactions.onpageload; - -import com.appsmith.external.models.ActionDTO; -import com.appsmith.external.models.Executable; -import com.appsmith.server.newactions.base.NewActionService; -import com.appsmith.server.onpageload.executables.ExecutableOnPageLoadServiceCE; -import com.appsmith.server.solutions.ActionPermission; -import lombok.RequiredArgsConstructor; -import lombok.extern.slf4j.Slf4j; -import reactor.core.publisher.Flux; -import reactor.core.publisher.Mono; - -@Slf4j -@RequiredArgsConstructor -public class ActionOnPageLoadServiceCEImpl implements ExecutableOnPageLoadServiceCE<ActionDTO> { - - private final NewActionService newActionService; - private final ActionPermission actionPermission; - - @Override - public Flux<Executable> getAllExecutablesByPageIdFlux(String pageId) { - return newActionService - .findByPageIdAndViewMode(pageId, false, actionPermission.getEditPermission()) - .flatMap(newAction -> newActionService.generateActionByViewMode(newAction, false)) - .map(actionDTO -> (Executable) actionDTO) - .cache(); - } - - @Override - public Mono<Executable> fillSelfReferencingPaths(ActionDTO executable) { - return newActionService.fillSelfReferencingDataPaths(executable).map(actionDTO -> actionDTO); - } - - @Override - public Flux<Executable> getUnpublishedOnLoadExecutablesExplicitSetByUserInPageFlux(String pageId) { - return newActionService - .findUnpublishedOnLoadActionsExplicitSetByUserInPage(pageId) - .flatMap(newAction -> newActionService.generateActionByViewMode(newAction, false)); - } - - @Override - public Mono<Executable> updateUnpublishedExecutable(String id, Executable executable) { - return newActionService - .updateUnpublishedAction(id, (ActionDTO) executable) - .map(updated -> updated); - } -} diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/newactions/onpageload/ActionOnPageLoadServiceImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/newactions/onpageload/ActionOnPageLoadServiceImpl.java deleted file mode 100644 index 4fed6b539043..000000000000 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/newactions/onpageload/ActionOnPageLoadServiceImpl.java +++ /dev/null @@ -1,17 +0,0 @@ -package com.appsmith.server.newactions.onpageload; - -import com.appsmith.external.models.ActionDTO; -import com.appsmith.server.newactions.base.NewActionService; -import com.appsmith.server.onpageload.executables.ExecutableOnPageLoadService; -import com.appsmith.server.solutions.ActionPermission; -import lombok.extern.slf4j.Slf4j; -import org.springframework.stereotype.Service; - -@Slf4j -@Service -public class ActionOnPageLoadServiceImpl extends ActionOnPageLoadServiceCEImpl - implements ExecutableOnPageLoadService<ActionDTO> { - public ActionOnPageLoadServiceImpl(NewActionService newActionService, ActionPermission actionPermission) { - super(newActionService, actionPermission); - } -} diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/newpages/onload/ExecutableOnPageLoadServiceCEImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/newpages/onload/ExecutableOnPageLoadServiceCEImpl.java new file mode 100644 index 000000000000..b173931d221c --- /dev/null +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/newpages/onload/ExecutableOnPageLoadServiceCEImpl.java @@ -0,0 +1,108 @@ +package com.appsmith.server.newpages.onload; + +import com.appsmith.external.models.ActionDTO; +import com.appsmith.external.models.Executable; +import com.appsmith.server.constants.FieldName; +import com.appsmith.server.domains.Layout; +import com.appsmith.server.domains.NewPage; +import com.appsmith.server.dtos.PageDTO; +import com.appsmith.server.exceptions.AppsmithError; +import com.appsmith.server.exceptions.AppsmithException; +import com.appsmith.server.newactions.base.NewActionService; +import com.appsmith.server.newpages.base.NewPageService; +import com.appsmith.server.onload.executables.ExecutableOnLoadServiceCE; +import com.appsmith.server.services.ApplicationService; +import com.appsmith.server.solutions.ActionPermission; +import com.appsmith.server.solutions.PagePermission; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.BeanUtils; +import org.springframework.stereotype.Service; +import reactor.core.publisher.Flux; +import reactor.core.publisher.Mono; + +import java.util.List; + +@Slf4j +@RequiredArgsConstructor +@Service +public class ExecutableOnPageLoadServiceCEImpl implements ExecutableOnLoadServiceCE<NewPage> { + + private final NewActionService newActionService; + private final NewPageService newPageService; + private final ApplicationService applicationService; + + private final ActionPermission actionPermission; + private final PagePermission pagePermission; + + @Override + public Flux<Executable> getAllExecutablesByCreatorIdFlux(String creatorId) { + return newActionService + .findByPageIdAndViewMode(creatorId, false, actionPermission.getEditPermission()) + .flatMap(newAction -> newActionService.generateActionByViewMode(newAction, false)) + .map(actionDTO -> (Executable) actionDTO) + .cache(); + } + + @Override + public Mono<Executable> fillSelfReferencingPaths(Executable executable) { + return newActionService + .fillSelfReferencingDataPaths((ActionDTO) executable) + .map(actionDTO -> actionDTO); + } + + @Override + public Flux<Executable> getUnpublishedOnLoadExecutablesExplicitSetByUserInPageFlux(String creatorId) { + return newActionService + .findUnpublishedOnLoadActionsExplicitSetByUserInPage(creatorId) + .flatMap(newAction -> newActionService.generateActionByViewMode(newAction, false)); + } + + @Override + public Mono<Executable> updateUnpublishedExecutable(String id, Executable executable) { + return newActionService + .updateUnpublishedAction(id, (ActionDTO) executable) + .map(updated -> updated); + } + + @Override + public Mono<Layout> findAndUpdateLayout(String creatorId, String layoutId, Layout layout) { + Mono<PageDTO> pageDTOMono = newPageService + .findByIdAndLayoutsId(creatorId, layoutId, pagePermission.getEditPermission(), false) + .switchIfEmpty(Mono.error(new AppsmithException( + AppsmithError.ACL_NO_RESOURCE_FOUND, + FieldName.PAGE_ID + " or " + FieldName.LAYOUT_ID, + creatorId + ", " + layoutId))); + + return pageDTOMono + .flatMap(page -> { + List<Layout> layoutList = page.getLayouts(); + // Because the findByIdAndLayoutsId call returned non-empty result, we are guaranteed to find the + // layoutId here. + for (Layout storedLayout : layoutList) { + if (storedLayout.getId().equals(layoutId)) { + // Now that all the on load actions have been computed, set the vertices, edges, actions in + // DSL in the layout for re-use to avoid computing DAG unnecessarily. + + BeanUtils.copyProperties(layout, storedLayout); + storedLayout.setId(layoutId); + + break; + } + } + page.setLayouts(layoutList); + return applicationService + .saveLastEditInformation(page.getApplicationId()) + .then(newPageService.saveUnpublishedPage(page)); + }) + .flatMap(page -> { + List<Layout> layoutList = page.getLayouts(); + for (Layout storedLayout : layoutList) { + if (storedLayout.getId().equals(layoutId)) { + return Mono.just(storedLayout); + } + } + return Mono.empty(); + }); + } +} diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/newpages/onload/ExecutableOnPageLoadServiceImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/newpages/onload/ExecutableOnPageLoadServiceImpl.java new file mode 100644 index 000000000000..18f09af14ffe --- /dev/null +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/newpages/onload/ExecutableOnPageLoadServiceImpl.java @@ -0,0 +1,25 @@ +package com.appsmith.server.newpages.onload; + +import com.appsmith.server.domains.NewPage; +import com.appsmith.server.newactions.base.NewActionService; +import com.appsmith.server.newpages.base.NewPageService; +import com.appsmith.server.onload.executables.ExecutableOnLoadService; +import com.appsmith.server.services.ApplicationService; +import com.appsmith.server.solutions.ActionPermission; +import com.appsmith.server.solutions.PagePermission; +import lombok.extern.slf4j.Slf4j; +import org.springframework.stereotype.Service; + +@Slf4j +@Service +public class ExecutableOnPageLoadServiceImpl extends ExecutableOnPageLoadServiceCEImpl + implements ExecutableOnLoadService<NewPage> { + public ExecutableOnPageLoadServiceImpl( + NewActionService newActionService, + NewPageService newPageService, + ApplicationService applicationService, + ActionPermission actionPermission, + PagePermission pagePermission) { + super(newActionService, newPageService, applicationService, actionPermission, pagePermission); + } +} diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/onload/executables/ExecutableOnLoadService.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/onload/executables/ExecutableOnLoadService.java new file mode 100644 index 000000000000..7c380a27d825 --- /dev/null +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/onload/executables/ExecutableOnLoadService.java @@ -0,0 +1,5 @@ +package com.appsmith.server.onload.executables; + +import com.appsmith.external.models.BaseDomain; + +public interface ExecutableOnLoadService<T extends BaseDomain> extends ExecutableOnLoadServiceCE<T> {} diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/onload/executables/ExecutableOnLoadServiceCE.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/onload/executables/ExecutableOnLoadServiceCE.java new file mode 100644 index 000000000000..e951fcf6179a --- /dev/null +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/onload/executables/ExecutableOnLoadServiceCE.java @@ -0,0 +1,20 @@ +package com.appsmith.server.onload.executables; + +import com.appsmith.external.models.BaseDomain; +import com.appsmith.external.models.Executable; +import com.appsmith.server.domains.Layout; +import reactor.core.publisher.Flux; +import reactor.core.publisher.Mono; + +public interface ExecutableOnLoadServiceCE<T extends BaseDomain> { + + Flux<Executable> getAllExecutablesByCreatorIdFlux(String creatorId); + + Mono<Executable> fillSelfReferencingPaths(Executable executable); + + Flux<Executable> getUnpublishedOnLoadExecutablesExplicitSetByUserInPageFlux(String creatorId); + + Mono<Executable> updateUnpublishedExecutable(String id, Executable executable); + + Mono<Layout> findAndUpdateLayout(String creatorId, String layoutId, Layout layout); +} diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/onload/internal/OnLoadExecutablesUtil.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/onload/internal/OnLoadExecutablesUtil.java new file mode 100644 index 000000000000..50024413e896 --- /dev/null +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/onload/internal/OnLoadExecutablesUtil.java @@ -0,0 +1,3 @@ +package com.appsmith.server.onload.internal; + +public interface OnLoadExecutablesUtil extends OnLoadExecutablesUtilCE {} diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/onpageload/internal/PageLoadExecutablesUtilCE.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/onload/internal/OnLoadExecutablesUtilCE.java similarity index 73% rename from app/server/appsmith-server/src/main/java/com/appsmith/server/onpageload/internal/PageLoadExecutablesUtilCE.java rename to app/server/appsmith-server/src/main/java/com/appsmith/server/onload/internal/OnLoadExecutablesUtilCE.java index 87fdd307790c..3237ee77d04c 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/onpageload/internal/PageLoadExecutablesUtilCE.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/onload/internal/OnLoadExecutablesUtilCE.java @@ -1,32 +1,35 @@ -package com.appsmith.server.onpageload.internal; +package com.appsmith.server.onload.internal; import com.appsmith.external.dtos.DslExecutableDTO; import com.appsmith.external.dtos.LayoutExecutableUpdateDTO; +import com.appsmith.external.models.CreatorContextType; import com.appsmith.external.models.Executable; import com.appsmith.server.domains.ExecutableDependencyEdge; +import com.appsmith.server.domains.Layout; import reactor.core.publisher.Mono; import java.util.List; import java.util.Map; import java.util.Set; -public interface PageLoadExecutablesUtilCE { +public interface OnLoadExecutablesUtilCE { Mono<List<Set<DslExecutableDTO>>> findAllOnLoadExecutables( - String pageId, + String creatorId, Integer evaluatedVersion, Set<String> widgetNames, Set<ExecutableDependencyEdge> edges, Map<String, Set<String>> widgetDynamicBindingsMap, List<Executable> flatPageLoadExecutables, - Set<String> executablesUsedInDSL); + Set<String> executablesUsedInDSL, + CreatorContextType creatorType); /** * !!!WARNING!!! This function edits the parameters executableUpdatesRef and messagesRef which are eventually returned back to * the caller with the updates values. * * @param onLoadExecutables : All the actions which have been found to be on page load - * @param pageId + * @param creatorId * @param executableUpdatesRef : Empty array list which would be set in this function with all the page actions whose * execute on load setting has changed (whether flipped from true to false, or vice versa) * @param messagesRef : Empty array list which would be set in this function with all the messagesRef that should be @@ -35,7 +38,10 @@ Mono<List<Set<DslExecutableDTO>>> findAllOnLoadExecutables( */ Mono<Boolean> updateExecutablesExecuteOnLoad( List<Executable> onLoadExecutables, - String pageId, + String creatorId, List<LayoutExecutableUpdateDTO> executableUpdatesRef, - List<String> messagesRef); + List<String> messagesRef, + CreatorContextType creatorType); + + Mono<Layout> findAndUpdateLayout(String creatorId, CreatorContextType creatorType, String layoutId, Layout layout); } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/onpageload/internal/PageLoadExecutablesUtilCEImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/onload/internal/OnLoadExecutablesUtilCEImpl.java similarity index 94% rename from app/server/appsmith-server/src/main/java/com/appsmith/server/onpageload/internal/PageLoadExecutablesUtilCEImpl.java rename to app/server/appsmith-server/src/main/java/com/appsmith/server/onload/internal/OnLoadExecutablesUtilCEImpl.java index 681b506f056f..035b4f611949 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/onpageload/internal/PageLoadExecutablesUtilCEImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/onload/internal/OnLoadExecutablesUtilCEImpl.java @@ -1,17 +1,20 @@ -package com.appsmith.server.onpageload.internal; +package com.appsmith.server.onload.internal; import com.appsmith.external.dtos.DslExecutableDTO; import com.appsmith.external.dtos.LayoutExecutableUpdateDTO; import com.appsmith.external.helpers.MustacheHelper; import com.appsmith.external.models.ActionDTO; +import com.appsmith.external.models.CreatorContextType; import com.appsmith.external.models.EntityDependencyNode; import com.appsmith.external.models.EntityReferenceType; import com.appsmith.external.models.Executable; import com.appsmith.external.models.Property; import com.appsmith.server.domains.ExecutableDependencyEdge; +import com.appsmith.server.domains.Layout; +import com.appsmith.server.domains.NewPage; import com.appsmith.server.exceptions.AppsmithError; import com.appsmith.server.exceptions.AppsmithException; -import com.appsmith.server.onpageload.executables.ExecutableOnPageLoadService; +import com.appsmith.server.onload.executables.ExecutableOnLoadService; import com.appsmith.server.services.AstService; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; @@ -48,11 +51,11 @@ @Slf4j @RequiredArgsConstructor -public class PageLoadExecutablesUtilCEImpl implements PageLoadExecutablesUtilCE { +public class OnLoadExecutablesUtilCEImpl implements OnLoadExecutablesUtilCE { private final AstService astService; private final ObjectMapper objectMapper; - private final ExecutableOnPageLoadService<ActionDTO> actionExecutableOnPageLoadService; + private final ExecutableOnLoadService<NewPage> pageExecutableOnLoadService; /** * The following regex finds the immediate parent of an entity path. @@ -75,7 +78,7 @@ public class PageLoadExecutablesUtilCEImpl implements PageLoadExecutablesUtilCE * !!!WARNING!!! : This function edits the parameters edges, executablesUsedInDSL and flatPageLoadExecutables * and the same are used by the caller function for further processing. * - * @param pageId : Argument used for fetching executables in this page + * @param creatorId : Argument used for fetching executables in this page * @param evaluatedVersion : Depending on the evaluated version, the way the AST parsing logic picks entities in the dynamic binding will change * @param widgetNames : Set of widget names which SHOULD have been populated before calling this function. * @param edgesRef : Set where this function adds all the relationships (dependencies) between executables @@ -92,22 +95,22 @@ public class PageLoadExecutablesUtilCEImpl implements PageLoadExecutablesUtilCE * in the list. */ public Mono<List<Set<DslExecutableDTO>>> findAllOnLoadExecutables( - String pageId, + String creatorId, Integer evaluatedVersion, Set<String> widgetNames, Set<ExecutableDependencyEdge> edgesRef, Map<String, Set<String>> widgetDynamicBindingsMap, List<Executable> flatPageLoadExecutablesRef, - Set<String> executablesUsedInDSLRef) { + Set<String> executablesUsedInDSLRef, + CreatorContextType creatorType) { - Set<String> onPageLoadExecutableSetRef = new HashSet<>(); + Set<String> onLoadExecutableSetRef = new HashSet<>(); Set<String> explicitUserSetOnLoadExecutablesRef = new HashSet<>(); Set<String> bindingsFromExecutablesRef = ConcurrentHashMap.newKeySet(); // Function `extractAndSetExecutableBindingsInGraphEdges` updates this map to keep a track of all the - // executables which - // have been discovered while walking the executables to ensure that we don't end up in a recursive infinite - // loop + // executables which have been discovered while walking the executables to ensure that we don't end up in a + // recursive infinite loop // in case of a cyclical relationship between executables (and not specific paths) and helps us exit at the // appropriate junction. // e.g : Consider the following relationships : @@ -116,13 +119,13 @@ public Mono<List<Set<DslExecutableDTO>>> findAllOnLoadExecutables( // In the above case, the two executables depend on each other without there being a real cyclical dependency. Map<String, EntityDependencyNode> executablesFoundDuringWalkRef = new HashMap<>(); - Flux<Executable> allExecutablesByPageIdFlux = getAllExecutablesByPageIdFlux(pageId); + Flux<Executable> allExecutablesByCreatorIdFlux = getAllExecutablesByCreatorIdFlux(creatorId, creatorType); - Mono<Map<String, Executable>> executableNameToExecutableMapMono = allExecutablesByPageIdFlux + Mono<Map<String, Executable>> executableNameToExecutableMapMono = allExecutablesByCreatorIdFlux .collectMap(Executable::getValidName, executable -> executable) .cache(); - Mono<Set<String>> executablesInPageMono = allExecutablesByPageIdFlux + Mono<Set<String>> executablesInCreatorContextMono = allExecutablesByCreatorIdFlux .map(Executable::getValidName) .collect(Collectors.toSet()) .cache(); @@ -147,17 +150,17 @@ public Mono<List<Set<DslExecutableDTO>>> findAllOnLoadExecutables( Mono<Set<ExecutableDependencyEdge>> createAllEdgesForPageMono = directlyReferencedExecutablesToGraphMono // Add dependencies of all on page load executables set by the user in the graph .flatMap(updatedEdges -> addExplicitUserSetOnLoadExecutablesToGraph( - pageId, + creatorId, updatedEdges, explicitUserSetOnLoadExecutablesRef, executablesFoundDuringWalkRef, bindingsFromExecutablesRef, executableNameToExecutableMapMono, executableBindingsInDslRef, - evaluatedVersion)) + evaluatedVersion, + creatorType)) // For all the executables found so far, recursively walk the dynamic bindings of the executables to - // find more - // relationships with other executables (& widgets) + // find more relationships with other executables (& widgets) .flatMap(updatedEdges -> recursivelyAddExecutablesAndTheirDependentsToGraphFromBindings( updatedEdges, executablesFoundDuringWalkRef, @@ -165,7 +168,7 @@ public Mono<List<Set<DslExecutableDTO>>> findAllOnLoadExecutables( executableNameToExecutableMapMono, evaluatedVersion)) // At last, add all the widget relationships to the graph as well. - .zipWith(executablesInPageMono) + .zipWith(executablesInCreatorContextMono) .flatMap(tuple -> { Set<ExecutableDependencyEdge> updatedEdges = tuple.getT1(); return addWidgetRelationshipToGraph(updatedEdges, widgetDynamicBindingsMap, evaluatedVersion); @@ -173,7 +176,7 @@ public Mono<List<Set<DslExecutableDTO>>> findAllOnLoadExecutables( // Create a graph given edges Mono<DirectedAcyclicGraph<String, DefaultEdge>> createGraphMono = Mono.zip( - executablesInPageMono, createAllEdgesForPageMono) + executablesInCreatorContextMono, createAllEdgesForPageMono) .map(tuple -> { Set<String> allExecutables = tuple.getT1(); Set<ExecutableDependencyEdge> updatedEdges = tuple.getT2(); @@ -190,7 +193,7 @@ public Mono<List<Set<DslExecutableDTO>>> findAllOnLoadExecutables( return computeOnPageLoadExecutablesSchedulingOrder( graph, - onPageLoadExecutableSetRef, + onLoadExecutableSetRef, executableNameToExecutableMap, explicitUserSetOnLoadExecutablesRef); }) @@ -199,15 +202,15 @@ public Mono<List<Set<DslExecutableDTO>>> findAllOnLoadExecutables( // This scenario would happen if an explicitly turned on for page load executable does not have any // relationships in the page with any widgets/executables. Set<String> pageLoadExecutableNames = new HashSet<>(); - pageLoadExecutableNames.addAll(onPageLoadExecutableSetRef); + pageLoadExecutableNames.addAll(onLoadExecutableSetRef); pageLoadExecutableNames.addAll(explicitUserSetOnLoadExecutablesRef); - pageLoadExecutableNames.removeAll(onPageLoadExecutableSetRef); + pageLoadExecutableNames.removeAll(onLoadExecutableSetRef); // If any of the explicitly set on page load executables havent been added yet, add them to the 0th // set // of executables set since no relationships were found with any other appsmith entity if (!pageLoadExecutableNames.isEmpty()) { - onPageLoadExecutableSetRef.addAll(pageLoadExecutableNames); + onLoadExecutableSetRef.addAll(pageLoadExecutableNames); // In case there are no page load executables, initialize the 0th set of page load executables // list. @@ -224,7 +227,7 @@ public Mono<List<Set<DslExecutableDTO>>> findAllOnLoadExecutables( // Transform the schedule order into client feasible DTO Mono<List<Set<DslExecutableDTO>>> computeCompletePageLoadExecutableScheduleMono = filterAndTransformSchedulingOrderToDTO( - onPageLoadExecutableSetRef, + onLoadExecutableSetRef, executableNameToExecutableMapMono, computeOnPageLoadScheduleNamesMono) .cache(); @@ -234,7 +237,7 @@ public Mono<List<Set<DslExecutableDTO>>> findAllOnLoadExecutables( Mono<List<Executable>> flatPageLoadExecutablesMono = computeCompletePageLoadExecutableScheduleMono .then(executableNameToExecutableMapMono) .map(executableMap -> { - onPageLoadExecutableSetRef.stream() + onLoadExecutableSetRef.stream() .forEach(executableName -> flatPageLoadExecutablesRef.add(executableMap.get(executableName))); return flatPageLoadExecutablesRef; @@ -246,17 +249,18 @@ public Mono<List<Set<DslExecutableDTO>>> findAllOnLoadExecutables( @Override public Mono<Boolean> updateExecutablesExecuteOnLoad( List<Executable> onLoadExecutables, - String pageId, + String creatorId, List<LayoutExecutableUpdateDTO> executableUpdatesRef, - List<String> messagesRef) { + List<String> messagesRef, + CreatorContextType creatorType) { List<Executable> toUpdateExecutables = new ArrayList<>(); // Fetch all the actions which exist in this page. - Flux<Executable> pageExecutablesFlux = - this.getAllExecutablesByPageIdFlux(pageId).cache(); + Flux<Executable> creatorContextExecutablesFlux = + this.getAllExecutablesByCreatorIdFlux(creatorId, creatorType).cache(); // Before we update the actions, fetch all the actions which are currently set to execute on load. - Mono<List<Executable>> existingOnPageLoadExecutablesMono = pageExecutablesFlux + Mono<List<Executable>> existingOnLoadExecutablesMono = creatorContextExecutablesFlux .flatMap(executable -> { if (TRUE.equals(executable.getExecuteOnLoad())) { return Mono.just(executable); @@ -265,26 +269,26 @@ public Mono<Boolean> updateExecutablesExecuteOnLoad( }) .collectList(); - return existingOnPageLoadExecutablesMono - .zipWith(pageExecutablesFlux.collectList()) + return existingOnLoadExecutablesMono + .zipWith(creatorContextExecutablesFlux.collectList()) .flatMap(tuple -> { - List<Executable> existingOnPageLoadExecutables = tuple.getT1(); - List<Executable> pageExecutables = tuple.getT2(); + List<Executable> existingOnLoadExecutables = tuple.getT1(); + List<Executable> creatorContextExecutables = tuple.getT2(); // There are no actions in this page. No need to proceed further since no actions would get updated - if (pageExecutables.isEmpty()) { + if (creatorContextExecutables.isEmpty()) { return Mono.just(FALSE); } // No actions require an update if no actions have been found as page load actions as well as // existing on load page actions are empty - if (existingOnPageLoadExecutables.isEmpty() + if (existingOnLoadExecutables.isEmpty() && (onLoadExecutables == null || onLoadExecutables.isEmpty())) { return Mono.just(FALSE); } // Extract names of existing page load actions and new page load actions for quick lookup. - Set<String> existingOnPageLoadExecutableNames = existingOnPageLoadExecutables.stream() + Set<String> existingOnLoadExecutableNames = existingOnLoadExecutables.stream() .map(Executable::getValidName) .collect(Collectors.toSet()); @@ -294,15 +298,15 @@ public Mono<Boolean> updateExecutablesExecuteOnLoad( // Calculate the actions which would need to be updated from execute on load TRUE to FALSE. Set<String> turnedOffExecutableNames = new HashSet<>(); - turnedOffExecutableNames.addAll(existingOnPageLoadExecutableNames); + turnedOffExecutableNames.addAll(existingOnLoadExecutableNames); turnedOffExecutableNames.removeAll(newOnLoadExecutableNames); // Calculate the actions which would need to be updated from execute on load FALSE to TRUE Set<String> turnedOnExecutableNames = new HashSet<>(); turnedOnExecutableNames.addAll(newOnLoadExecutableNames); - turnedOnExecutableNames.removeAll(existingOnPageLoadExecutableNames); + turnedOnExecutableNames.removeAll(existingOnLoadExecutableNames); - for (Executable executable : pageExecutables) { + for (Executable executable : creatorContextExecutables) { String executableName = executable.getValidName(); // If a user has ever set execute on load, this field can not be changed automatically. It has @@ -331,11 +335,11 @@ public Mono<Boolean> updateExecutablesExecuteOnLoad( // Add newly turned on page actions to report back to the caller executableUpdatesRef.addAll( - addExecutableUpdatesForExecutableNames(pageExecutables, turnedOnExecutableNames)); + addExecutableUpdatesForExecutableNames(creatorContextExecutables, turnedOnExecutableNames)); // Add newly turned off page actions to report back to the caller - executableUpdatesRef.addAll( - addExecutableUpdatesForExecutableNames(pageExecutables, turnedOffExecutableNames)); + executableUpdatesRef.addAll(addExecutableUpdatesForExecutableNames( + creatorContextExecutables, turnedOffExecutableNames)); // Now add messagesRef that would eventually be displayed to the developer user informing them // about the action setting change. @@ -356,23 +360,29 @@ public Mono<Boolean> updateExecutablesExecuteOnLoad( }); } + @Override + public Mono<Layout> findAndUpdateLayout( + String creatorId, CreatorContextType creatorType, String layoutId, Layout layout) { + return pageExecutableOnLoadService.findAndUpdateLayout(creatorId, layoutId, layout); + } + private Mono<Executable> updateUnpublishedExecutable(String id, Executable executable) { if (executable instanceof ActionDTO actionDTO) { - return actionExecutableOnPageLoadService.updateUnpublishedExecutable(id, actionDTO); + return pageExecutableOnLoadService.updateUnpublishedExecutable(id, actionDTO); } else return Mono.just(executable); } private List<LayoutExecutableUpdateDTO> addExecutableUpdatesForExecutableNames( - List<Executable> pageExecutables, Set<String> updatedExecutableNames) { + List<Executable> executables, Set<String> updatedExecutableNames) { - return pageExecutables.stream() - .filter(pageExecutable -> updatedExecutableNames.contains(pageExecutable.getValidName())) + return executables.stream() + .filter(executable -> updatedExecutableNames.contains(executable.getValidName())) .map(Executable::createLayoutExecutableUpdateDTO) .collect(Collectors.toList()); } - protected Flux<Executable> getAllExecutablesByPageIdFlux(String pageId) { - return actionExecutableOnPageLoadService.getAllExecutablesByPageIdFlux(pageId); + protected Flux<Executable> getAllExecutablesByCreatorIdFlux(String creatorId, CreatorContextType creatorType) { + return pageExecutableOnLoadService.getAllExecutablesByCreatorIdFlux(creatorId); } /** @@ -613,7 +623,7 @@ protected Mono<Executable> updateExecutableSelfReferencingPaths(EntityDependency protected <T extends Executable> Mono<Executable> fillSelfReferencingPaths(T executable) { if (executable instanceof ActionDTO actionDTO) { - return actionExecutableOnPageLoadService.fillSelfReferencingPaths(actionDTO); + return pageExecutableOnLoadService.fillSelfReferencingPaths(actionDTO); } else return Mono.just(executable); } @@ -902,7 +912,7 @@ private Mono<Set<ExecutableDependencyEdge>> recursivelyAddExecutablesAndTheirDep * !!! WARNING !!! : This function updates the set `explicitUserSetOnLoadExecutables` and adds the names of all such * executables found in this function. * - * @param pageId + * @param creatorId * @param edges * @param explicitUserSetOnLoadExecutables * @param executablesFoundDuringWalkRef @@ -910,17 +920,18 @@ private Mono<Set<ExecutableDependencyEdge>> recursivelyAddExecutablesAndTheirDep * @return */ private Mono<Set<ExecutableDependencyEdge>> addExplicitUserSetOnLoadExecutablesToGraph( - String pageId, + String creatorId, Set<ExecutableDependencyEdge> edges, Set<String> explicitUserSetOnLoadExecutables, Map<String, EntityDependencyNode> executablesFoundDuringWalkRef, Set<String> bindingsFromExecutablesRef, Mono<Map<String, Executable>> executableNameToExecutableMapMono, Set<EntityDependencyNode> executableBindingsInDsl, - int evalVersion) { + int evalVersion, + CreatorContextType creatorType) { // First fetch all the executables which have been tagged as on load by the user explicitly. - return getUnpublishedOnLoadExecutablesExplicitSetByUserInPageFlux(pageId) + return getUnpublishedOnLoadExecutablesExplicitSetByUserInCreatorContextFlux(creatorId, creatorType) .flatMap(this::fillSelfReferencingPaths) // Add the vertices and edges to the graph for these executables .flatMap(executable -> { @@ -941,8 +952,9 @@ private Mono<Set<ExecutableDependencyEdge>> addExplicitUserSetOnLoadExecutablesT .thenReturn(edges); } - protected Flux<Executable> getUnpublishedOnLoadExecutablesExplicitSetByUserInPageFlux(String pageId) { - return actionExecutableOnPageLoadService.getUnpublishedOnLoadExecutablesExplicitSetByUserInPageFlux(pageId); + protected Flux<Executable> getUnpublishedOnLoadExecutablesExplicitSetByUserInCreatorContextFlux( + String creatorId, CreatorContextType creatorType) { + return pageExecutableOnLoadService.getUnpublishedOnLoadExecutablesExplicitSetByUserInPageFlux(creatorId); } /** diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/onload/internal/OnLoadExecutablesUtilImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/onload/internal/OnLoadExecutablesUtilImpl.java new file mode 100644 index 000000000000..fd04d515198a --- /dev/null +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/onload/internal/OnLoadExecutablesUtilImpl.java @@ -0,0 +1,20 @@ +package com.appsmith.server.onload.internal; + +import com.appsmith.server.domains.NewPage; +import com.appsmith.server.onload.executables.ExecutableOnLoadService; +import com.appsmith.server.services.AstService; +import com.fasterxml.jackson.databind.ObjectMapper; +import lombok.extern.slf4j.Slf4j; +import org.springframework.stereotype.Component; + +@Slf4j +@Component +public class OnLoadExecutablesUtilImpl extends OnLoadExecutablesUtilCEImpl implements OnLoadExecutablesUtil { + + public OnLoadExecutablesUtilImpl( + AstService astService, + ObjectMapper objectMapper, + ExecutableOnLoadService<NewPage> pageExecutableOnLoadService) { + super(astService, objectMapper, pageExecutableOnLoadService); + } +} diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/onpageload/executables/ExecutableOnPageLoadService.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/onpageload/executables/ExecutableOnPageLoadService.java deleted file mode 100644 index 1208180f9a40..000000000000 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/onpageload/executables/ExecutableOnPageLoadService.java +++ /dev/null @@ -1,5 +0,0 @@ -package com.appsmith.server.onpageload.executables; - -import com.appsmith.external.models.Executable; - -public interface ExecutableOnPageLoadService<T extends Executable> extends ExecutableOnPageLoadServiceCE<T> {} diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/onpageload/executables/ExecutableOnPageLoadServiceCE.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/onpageload/executables/ExecutableOnPageLoadServiceCE.java deleted file mode 100644 index fbbb07005ad3..000000000000 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/onpageload/executables/ExecutableOnPageLoadServiceCE.java +++ /dev/null @@ -1,16 +0,0 @@ -package com.appsmith.server.onpageload.executables; - -import com.appsmith.external.models.Executable; -import reactor.core.publisher.Flux; -import reactor.core.publisher.Mono; - -public interface ExecutableOnPageLoadServiceCE<T extends Executable> { - - Flux<Executable> getAllExecutablesByPageIdFlux(String pageId); - - Mono<Executable> fillSelfReferencingPaths(T executable); - - Flux<Executable> getUnpublishedOnLoadExecutablesExplicitSetByUserInPageFlux(String pageId); - - Mono<Executable> updateUnpublishedExecutable(String id, Executable executable); -} diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/onpageload/internal/PageLoadExecutablesUtil.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/onpageload/internal/PageLoadExecutablesUtil.java deleted file mode 100644 index d6b824c4c7dc..000000000000 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/onpageload/internal/PageLoadExecutablesUtil.java +++ /dev/null @@ -1,3 +0,0 @@ -package com.appsmith.server.onpageload.internal; - -public interface PageLoadExecutablesUtil extends PageLoadExecutablesUtilCE {} diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/onpageload/internal/PageLoadExecutablesUtilImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/onpageload/internal/PageLoadExecutablesUtilImpl.java deleted file mode 100644 index 5b1471e43f4b..000000000000 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/onpageload/internal/PageLoadExecutablesUtilImpl.java +++ /dev/null @@ -1,20 +0,0 @@ -package com.appsmith.server.onpageload.internal; - -import com.appsmith.external.models.ActionDTO; -import com.appsmith.server.onpageload.executables.ExecutableOnPageLoadService; -import com.appsmith.server.services.AstService; -import com.fasterxml.jackson.databind.ObjectMapper; -import lombok.extern.slf4j.Slf4j; -import org.springframework.stereotype.Component; - -@Slf4j -@Component -public class PageLoadExecutablesUtilImpl extends PageLoadExecutablesUtilCEImpl implements PageLoadExecutablesUtil { - - public PageLoadExecutablesUtilImpl( - AstService astService, - ObjectMapper objectMapper, - ExecutableOnPageLoadService<ActionDTO> actionExecutableOnPageLoadService) { - super(astService, objectMapper, actionExecutableOnPageLoadService); - } -} diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/LayoutActionServiceImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/LayoutActionServiceImpl.java index 2ecbd42872e3..58b448d9c589 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/LayoutActionServiceImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/LayoutActionServiceImpl.java @@ -5,7 +5,7 @@ import com.appsmith.server.helpers.ResponseUtils; import com.appsmith.server.newactions.base.NewActionService; import com.appsmith.server.newpages.base.NewPageService; -import com.appsmith.server.onpageload.internal.PageLoadExecutablesUtil; +import com.appsmith.server.onload.internal.OnLoadExecutablesUtil; import com.appsmith.server.services.ce.LayoutActionServiceCEImpl; import com.appsmith.server.solutions.ActionPermission; import com.appsmith.server.solutions.PagePermission; @@ -22,7 +22,7 @@ public LayoutActionServiceImpl( AnalyticsService analyticsService, NewPageService newPageService, NewActionService newActionService, - PageLoadExecutablesUtil pageLoadActionsUtil, + OnLoadExecutablesUtil pageLoadActionsUtil, SessionUserService sessionUserService, ActionCollectionService actionCollectionService, CollectionService collectionService, diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/LayoutActionServiceCEImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/LayoutActionServiceCEImpl.java index e71ce5e6fbfe..ca95d742a157 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/LayoutActionServiceCEImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/LayoutActionServiceCEImpl.java @@ -9,6 +9,7 @@ import com.appsmith.external.helpers.AppsmithEventContextType; import com.appsmith.external.helpers.MustacheHelper; import com.appsmith.external.models.ActionDTO; +import com.appsmith.external.models.CreatorContextType; import com.appsmith.external.models.Datasource; import com.appsmith.external.models.DefaultResources; import com.appsmith.external.models.Executable; @@ -25,7 +26,6 @@ import com.appsmith.server.dtos.ActionCollectionDTO; import com.appsmith.server.dtos.ActionMoveDTO; import com.appsmith.server.dtos.LayoutDTO; -import com.appsmith.server.dtos.PageDTO; import com.appsmith.server.dtos.ce.UpdateMultiplePageLayoutDTO; import com.appsmith.server.exceptions.AppsmithError; import com.appsmith.server.exceptions.AppsmithException; @@ -34,7 +34,7 @@ import com.appsmith.server.helpers.WidgetSpecificUtils; import com.appsmith.server.newactions.base.NewActionService; import com.appsmith.server.newpages.base.NewPageService; -import com.appsmith.server.onpageload.internal.PageLoadExecutablesUtil; +import com.appsmith.server.onload.internal.OnLoadExecutablesUtil; import com.appsmith.server.services.AnalyticsService; import com.appsmith.server.services.ApplicationService; import com.appsmith.server.services.CollectionService; @@ -46,7 +46,6 @@ import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import net.minidev.json.JSONObject; -import org.springframework.beans.BeanUtils; import org.springframework.stereotype.Service; import org.springframework.util.CollectionUtils; import org.springframework.util.LinkedMultiValueMap; @@ -81,7 +80,7 @@ public class LayoutActionServiceCEImpl implements LayoutActionServiceCE { private final AnalyticsService analyticsService; private final NewPageService newPageService; private final NewActionService newActionService; - private final PageLoadExecutablesUtil pageLoadActionsUtil; + private final OnLoadExecutablesUtil onLoadExecutablesUtil; private final SessionUserService sessionUserService; private final ActionCollectionService actionCollectionService; private final CollectionService collectionService; @@ -280,7 +279,7 @@ public Mono<ActionDTO> moveAction(ActionMoveDTO actionMoveDTO, String branchName * @param dsl * @param widgetNames * @param widgetDynamicBindingsMap - * @param pageId + * @param creatorId * @param layoutId * @param escapedWidgetNames * @return @@ -289,9 +288,10 @@ private JSONObject extractAllWidgetNamesAndDynamicBindingsFromDSL( JSONObject dsl, Set<String> widgetNames, Map<String, Set<String>> widgetDynamicBindingsMap, - String pageId, + String creatorId, String layoutId, - Set<String> escapedWidgetNames) + Set<String> escapedWidgetNames, + CreatorContextType creatorType) throws AppsmithException { if (dsl.get(FieldName.WIDGET_NAME) == null) { // This isn't a valid widget configuration. No need to traverse this. @@ -345,11 +345,12 @@ private JSONObject extractAllWidgetNamesAndDynamicBindingsFromDSL( widgetName, widgetId, fieldPath, - pageId, + creatorId, layoutId, oldParent, nextKey, - "Index out of bounds for list"); + "Index out of bounds for list", + creatorType); } } else { throw new AppsmithException( @@ -358,11 +359,12 @@ private JSONObject extractAllWidgetNamesAndDynamicBindingsFromDSL( widgetName, widgetId, fieldPath, - pageId, + creatorId, layoutId, oldParent, nextKey, - "Child of list is not in an indexed path"); + "Child of list is not in an indexed path", + creatorType); } } // After updating the parent, check for the types @@ -373,11 +375,12 @@ private JSONObject extractAllWidgetNamesAndDynamicBindingsFromDSL( widgetName, widgetId, fieldPath, - pageId, + creatorId, layoutId, oldParent, nextKey, - "New element is null"); + "New element is null", + creatorType); } else if (parent instanceof String) { // If we get String value, then this is a leaf node isLeafNode = true; @@ -396,11 +399,12 @@ private JSONObject extractAllWidgetNamesAndDynamicBindingsFromDSL( widgetName, widgetId, fieldPath, - pageId, + creatorId, layoutId, bindingAsString, nextKey, - "Binding path has no mustache bindings"); + "Binding path has no mustache bindings", + creatorType); } catch (JsonProcessingException e) { throw new AppsmithException(AppsmithError.JSON_PROCESSING_ERROR, parent); } @@ -437,7 +441,13 @@ private JSONObject extractAllWidgetNamesAndDynamicBindingsFromDSL( if (!CollectionUtils.isEmpty(data)) { object.putAll(data); JSONObject child = extractAllWidgetNamesAndDynamicBindingsFromDSL( - object, widgetNames, widgetDynamicBindingsMap, pageId, layoutId, escapedWidgetNames); + object, + widgetNames, + widgetDynamicBindingsMap, + creatorId, + layoutId, + escapedWidgetNames, + creatorType); newChildren.add(child); } } @@ -656,8 +666,13 @@ public Mono<String> updatePageLayoutsByPageId(String pageId) { } private Mono<Boolean> sendUpdateLayoutAnalyticsEvent( - String pageId, String layoutId, JSONObject dsl, boolean isSuccess, Throwable error) { - return Mono.zip(sessionUserService.getCurrentUser(), newPageService.getById(pageId)) + String creatorId, + String layoutId, + JSONObject dsl, + boolean isSuccess, + Throwable error, + CreatorContextType creatorType) { + return Mono.zip(sessionUserService.getCurrentUser(), newPageService.getById(creatorId)) .flatMap(tuple -> { User t1 = tuple.getT1(); NewPage t2 = tuple.getT2(); @@ -667,8 +682,10 @@ private Mono<Boolean> sendUpdateLayoutAnalyticsEvent( t1.getUsername(), "appId", t2.getApplicationId(), - "pageId", - pageId, + "creatorId", + creatorId, + "creatorType", + creatorType, "layoutId", layoutId, "isSuccessfulExecution", @@ -686,7 +703,12 @@ private Mono<Boolean> sendUpdateLayoutAnalyticsEvent( }); } - private Mono<LayoutDTO> updateLayoutDsl(String pageId, String layoutId, Layout layout, Integer evaluatedVersion) { + private Mono<LayoutDTO> updateLayoutDsl( + String creatorId, + String layoutId, + Layout layout, + Integer evaluatedVersion, + CreatorContextType creatorType) { JSONObject dsl = layout.getDsl(); if (dsl == null) { // There is no DSL here. No need to process anything. Return as is. @@ -698,9 +720,9 @@ private Mono<LayoutDTO> updateLayoutDsl(String pageId, String layoutId, Layout l Set<String> escapedWidgetNames = new HashSet<>(); try { dsl = extractAllWidgetNamesAndDynamicBindingsFromDSL( - dsl, widgetNames, widgetDynamicBindingsMap, pageId, layoutId, escapedWidgetNames); + dsl, widgetNames, widgetDynamicBindingsMap, creatorId, layoutId, escapedWidgetNames, creatorType); } catch (Throwable t) { - return sendUpdateLayoutAnalyticsEvent(pageId, layoutId, dsl, false, t) + return sendUpdateLayoutAnalyticsEvent(creatorId, layoutId, dsl, false, t, creatorType) .then(Mono.error(t)); } @@ -710,30 +732,31 @@ private Mono<LayoutDTO> updateLayoutDsl(String pageId, String layoutId, Layout l layout.setMongoEscapedWidgetNames(escapedWidgetNames); } - Set<String> actionNames = new HashSet<>(); + Set<String> executableNames = new HashSet<>(); Set<ExecutableDependencyEdge> edges = new HashSet<>(); Set<String> executablesUsedInDSL = new HashSet<>(); - List<Executable> flatmapPageLoadExecutables = new ArrayList<>(); + List<Executable> flatmapOnLoadExecutables = new ArrayList<>(); List<LayoutExecutableUpdateDTO> executableUpdatesRef = new ArrayList<>(); List<String> messagesRef = new ArrayList<>(); - AtomicReference<Boolean> validOnPageLoadExecutables = new AtomicReference<>(Boolean.TRUE); + AtomicReference<Boolean> validOnLoadExecutables = new AtomicReference<>(Boolean.TRUE); // setting the layoutOnLoadActionActionErrors to empty to remove the existing errors before new DAG calculation. layout.setLayoutOnLoadActionErrors(new ArrayList<>()); - Mono<List<Set<DslExecutableDTO>>> allOnLoadExecutablesMono = pageLoadActionsUtil + Mono<List<Set<DslExecutableDTO>>> allOnLoadExecutablesMono = onLoadExecutablesUtil .findAllOnLoadExecutables( - pageId, + creatorId, evaluatedVersion, widgetNames, edges, widgetDynamicBindingsMap, - flatmapPageLoadExecutables, - executablesUsedInDSL) + flatmapOnLoadExecutables, + executablesUsedInDSL, + creatorType) .onErrorResume(AppsmithException.class, error -> { log.info(error.getMessage()); - validOnPageLoadExecutables.set(FALSE); + validOnLoadExecutables.set(FALSE); layout.setLayoutOnLoadActionErrors(List.of(new ErrorDTO( error.getAppErrorCode(), error.getErrorType(), @@ -749,62 +772,26 @@ private Mono<LayoutDTO> updateLayoutDsl(String pageId, String layoutId, Layout l .flatMap(allOnLoadExecutables -> { // If there has been an error (e.g. cyclical dependency), then don't update any actions. // This is so that unnecessary updates don't happen to actions while the page is in invalid state. - if (!validOnPageLoadExecutables.get()) { + if (!validOnLoadExecutables.get()) { return Mono.just(allOnLoadExecutables); } - // Update these actions to be executed on load, unless the user has touched the executeOnLoad + // Update these executables to be executed on load, unless the user has touched the executeOnLoad // setting for this - return pageLoadActionsUtil + return onLoadExecutablesUtil .updateExecutablesExecuteOnLoad( - flatmapPageLoadExecutables, pageId, executableUpdatesRef, messagesRef) + flatmapOnLoadExecutables, creatorId, executableUpdatesRef, messagesRef, creatorType) .thenReturn(allOnLoadExecutables); }) - .zipWith(newPageService - .findByIdAndLayoutsId(pageId, layoutId, pagePermission.getEditPermission(), false) - .switchIfEmpty(Mono.error(new AppsmithException( - AppsmithError.ACL_NO_RESOURCE_FOUND, - FieldName.PAGE_ID + " or " + FieldName.LAYOUT_ID, - pageId + ", " + layoutId)))) - // Now update the page layout with the page load actions and the graph. - .flatMap(tuple -> { - List<Set<DslExecutableDTO>> onLoadActions = tuple.getT1(); - PageDTO page = tuple.getT2(); - - List<Layout> layoutList = page.getLayouts(); - // Because the findByIdAndLayoutsId call returned non-empty result, we are guaranteed to find the - // layoutId here. - for (Layout storedLayout : layoutList) { - if (storedLayout.getId().equals(layoutId)) { - // Now that all the on load actions have been computed, set the vertices, edges, actions in - // DSL - // in the layout for re-use to avoid computing DAG unnecessarily. - layout.setLayoutOnLoadActions(onLoadActions); - layout.setAllOnPageLoadActionNames(actionNames); - layout.setActionsUsedInDynamicBindings(executablesUsedInDSL); - // The below field is to ensure that we record if the page load actions computation was - // valid - // when last stored in the database. - layout.setValidOnPageLoadActions(validOnPageLoadExecutables.get()); - - BeanUtils.copyProperties(layout, storedLayout); - storedLayout.setId(layoutId); - - break; - } - } - page.setLayouts(layoutList); - return applicationService - .saveLastEditInformation(page.getApplicationId()) - .then(newPageService.saveUnpublishedPage(page)); - }) - .flatMap(page -> { - List<Layout> layoutList = page.getLayouts(); - for (Layout storedLayout : layoutList) { - if (storedLayout.getId().equals(layoutId)) { - return Mono.just(storedLayout); - } - } - return Mono.empty(); + // Now update the page layout with the page load executables and the graph. + .flatMap(onLoadExecutables -> { + layout.setLayoutOnLoadActions(onLoadExecutables); + layout.setAllOnPageLoadActionNames(executableNames); + layout.setActionsUsedInDynamicBindings(executablesUsedInDSL); + // The below field is to ensure that we record if the page load actions computation was + // valid when last stored in the database. + layout.setValidOnPageLoadActions(validOnLoadExecutables.get()); + + return onLoadExecutablesUtil.findAndUpdateLayout(creatorId, creatorType, layoutId, layout); }) .map(savedLayout -> { savedLayout.setDsl(this.unescapeMongoSpecialCharacters(savedLayout)); @@ -815,7 +802,7 @@ private Mono<LayoutDTO> updateLayoutDsl(String pageId, String layoutId, Layout l layoutDTO.setActionUpdates(executableUpdatesRef); layoutDTO.setMessages(messagesRef); - return sendUpdateLayoutAnalyticsEvent(pageId, layoutId, finalDsl, true, null) + return sendUpdateLayoutAnalyticsEvent(creatorId, layoutId, finalDsl, true, null, creatorType) .thenReturn(layoutDTO); }); } @@ -831,7 +818,7 @@ public Mono<LayoutDTO> updateLayout(String pageId, String applicationId, String if (evaluationVersion == null) { evaluationVersion = EVALUATION_VERSION; } - return updateLayoutDsl(pageId, layoutId, layout, evaluationVersion); + return updateLayoutDsl(pageId, layoutId, layout, evaluationVersion, CreatorContextType.PAGE); }); } diff --git a/app/server/appsmith-server/src/test/java/com/appsmith/server/services/LayoutServiceTest.java b/app/server/appsmith-server/src/test/java/com/appsmith/server/services/LayoutServiceTest.java index be0e5dfaae21..efc8ccc1bcc3 100644 --- a/app/server/appsmith-server/src/test/java/com/appsmith/server/services/LayoutServiceTest.java +++ b/app/server/appsmith-server/src/test/java/com/appsmith/server/services/LayoutServiceTest.java @@ -3,6 +3,7 @@ import com.appsmith.external.dtos.DslExecutableDTO; import com.appsmith.external.models.ActionConfiguration; import com.appsmith.external.models.ActionDTO; +import com.appsmith.external.models.CreatorContextType; import com.appsmith.external.models.Datasource; import com.appsmith.external.models.PluginType; import com.appsmith.external.models.Property; @@ -571,21 +572,27 @@ private Mono<LayoutDTO> createComplexAppForExecuteOnLoad(Mono<PageDTO> pageMono) Layout newLayout = new Layout(); JSONObject obj = new JSONObject(Map.of( - "widgetName", "testWidget", - "key", "value-updated", - "another", "Hello people of the {{input1.text}} planet!", - "dynamicGet", "some dynamic {{\"anIgnoredAction.data:\" + aGetAction.data}}", + "widgetName", + "testWidget", + "key", + "value-updated", + "another", + "Hello people of the {{input1.text}} planet!", + "dynamicGet", + "some dynamic {{\"anIgnoredAction.data:\" + aGetAction.data}}", "dynamicPost", - "some dynamic {{\n" + "(function(ignoredAction1){\n" - + "\tlet a = ignoredAction1.data\n" - + "\tlet ignoredAction2 = { data: \"nothing\" }\n" - + "\tlet b = ignoredAction2.data\n" - + "\tlet c = \"ignoredAction3.data\"\n" - + "\t// ignoredAction4.data\n" - + "\treturn aPostAction.data\n" - + "})(anotherPostAction.data)}}", - "dynamicPostWithAutoExec", "some dynamic {{aPostActionWithAutoExec.data}}", - "dynamicDelete", "some dynamic {{aDeleteAction.data}}")); + "some dynamic {{\n" + "(function(ignoredAction1){\n" + + "\tlet a = ignoredAction1.data\n" + + "\tlet ignoredAction2 = { data: \"nothing\" }\n" + + "\tlet b = ignoredAction2.data\n" + + "\tlet c = \"ignoredAction3.data\"\n" + + "\t// ignoredAction4.data\n" + + "\treturn aPostAction.data\n" + + "})(anotherPostAction.data)}}", + "dynamicPostWithAutoExec", + "some dynamic {{aPostActionWithAutoExec.data}}", + "dynamicDelete", + "some dynamic {{aDeleteAction.data}}")); obj.putAll(Map.of( "collection1Key", "some dynamic {{Collection.anAsyncCollectionActionWithoutCall.data}}", "collection2Key", "some dynamic {{Collection.aSyncCollectionActionWithoutCall.data}}", @@ -1303,7 +1310,8 @@ public void testIncorrectDynamicBindingPathInDsl() { layoutId.get(), oldParent, "dynamicGet_IncorrectKey", - "New element is null")); + "New element is null", + CreatorContextType.PAGE)); return true; }) .verify();
1f07be34fd6eecbe8babd18dfd1e8051265f5604
2024-12-04 15:40:32
sneha122
fix: appsmith ai app git import issue fixed (#37921)
false
appsmith ai app git import issue fixed (#37921)
fix
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 9f224b4deec2..27acf3d3bc0f 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 @@ -19,7 +19,8 @@ public static boolean hasFiles(DatasourceConfiguration datasourceConfiguration) } public static List<String> getFileIds(DatasourceConfiguration datasourceConfiguration) { - if (datasourceConfiguration.getProperties() != null + if (datasourceConfiguration != null + && datasourceConfiguration.getProperties() != null && datasourceConfiguration.getProperties().size() > 0) { for (Property property : datasourceConfiguration.getProperties()) { if (property.getKey().equalsIgnoreCase(FILES) diff --git a/app/server/appsmith-plugins/appsmithAiPlugin/src/test/java/com/external/plugins/services/FileUtilTest.java b/app/server/appsmith-plugins/appsmithAiPlugin/src/test/java/com/external/plugins/services/FileUtilTest.java new file mode 100644 index 000000000000..c242428d61f7 --- /dev/null +++ b/app/server/appsmith-plugins/appsmithAiPlugin/src/test/java/com/external/plugins/services/FileUtilTest.java @@ -0,0 +1,44 @@ +package com.external.plugins.services; + +import com.appsmith.external.models.DatasourceConfiguration; +import com.appsmith.external.models.Property; +import com.external.plugins.utils.FileUtils; +import org.junit.jupiter.api.Test; +import org.testcontainers.junit.jupiter.Testcontainers; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import static org.assertj.core.api.Assertions.assertThat; + +@Testcontainers +public class FileUtilTest { + @Test + public void getFileIds_withNullDatasourceConfig_returnsEmptyList() { + DatasourceConfiguration datasourceConfiguration = null; + List<String> actualFileIds = FileUtils.getFileIds(datasourceConfiguration); + assertThat(actualFileIds).isEmpty(); + } + + @Test + public void getFileIds_withValidDatasourceConfig_returnsFileIdList() { + DatasourceConfiguration datasourceConfiguration = new DatasourceConfiguration(); + datasourceConfiguration.setUrl("https://example.com"); + + // create file object + Map<String, Object> fileMap = new HashMap<String, Object>(); + fileMap.put("id", "fileId"); + fileMap.put("name", "fileName"); + fileMap.put("size", 10); + fileMap.put("mimetype", "fileMimetype"); + + Property property = new Property(); + property.setKey("Files"); + property.setValue(List.of(fileMap)); + + datasourceConfiguration.setProperties(List.of(property)); + List<String> actualFileIds = FileUtils.getFileIds(datasourceConfiguration); + assertThat(actualFileIds).contains("fileId"); + } +}
5aadb4161ee9ed3b2ea50b4128995a797b37ea07
2023-01-16 19:52:55
Manish Kumar
chore: datasourceContextService refactor (#19485)
false
datasourceContextService refactor (#19485)
chore
diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/domains/DatasourceContextIdentifier.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/domains/DatasourceContextIdentifier.java new file mode 100644 index 000000000000..586d390d182c --- /dev/null +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/domains/DatasourceContextIdentifier.java @@ -0,0 +1,29 @@ +package com.appsmith.server.domains; + +import com.appsmith.server.domains.ce.DatasourceContextIdentifierCE; +import lombok.NoArgsConstructor; + +/** + * This class is for generating keys for dsContext. + * The object of this class will be used as keys for dsContext + */ +@NoArgsConstructor +public class DatasourceContextIdentifier extends DatasourceContextIdentifierCE { + + public DatasourceContextIdentifier(String datasourceId, String environmentId) { + super(datasourceId, environmentId); + } + + @Override + public boolean equals(Object obj) { + // since the usage of environmentId will be mandatory in the EE version, + // this will have override in the EE version, which will not allow null EE values. + return super.equals(obj); + } + + @Override + public int hashCode() { + return super.hashCode(); + } + +} diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/domains/ce/DatasourceContextIdentifierCE.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/domains/ce/DatasourceContextIdentifierCE.java new file mode 100644 index 000000000000..eceee1ff602f --- /dev/null +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/domains/ce/DatasourceContextIdentifierCE.java @@ -0,0 +1,56 @@ +package com.appsmith.server.domains.ce; + +import lombok.AllArgsConstructor; +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.Setter; + +import static org.springframework.util.StringUtils.hasLength; + +/** + * This class is for generating keys for dsContext. + * The object of this class will be used as keys for dsContext + */ +@Getter +@Setter +@NoArgsConstructor +@AllArgsConstructor +public class DatasourceContextIdentifierCE { + + protected String datasourceId; + protected String environmentId; + + @Override + public boolean equals(Object obj) { + if (obj == this) { + return true; + } + + if (!(obj instanceof DatasourceContextIdentifierCE)) { + return false; + } + + DatasourceContextIdentifierCE keyObj = (DatasourceContextIdentifierCE) obj; + boolean areBothEnvironmentIdSameOrNull = hasLength(this.getEnvironmentId()) ? + this.getEnvironmentId().equals(keyObj.getEnvironmentId()) : !hasLength(keyObj.getEnvironmentId()); + + // if datasourceId is null for either of the objects then the keys can't be equal + return hasLength(this.getDatasourceId()) + && this.getDatasourceId().equals(keyObj.getDatasourceId()) && + areBothEnvironmentIdSameOrNull; + } + + @Override + public int hashCode() { + int result = 0; + result = hasLength(this.getDatasourceId()) ? this.getDatasourceId().hashCode() : result; + result = hasLength(this.getDatasourceId()) ? result*31 + this.getDatasourceId().hashCode() : result; + return result; + } + + public boolean isKeyValid() { + return hasLength(this.getDatasourceId()); + } + + +} diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/DatasourceContextServiceCE.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/DatasourceContextServiceCE.java index d1a857581fc2..5ffcb9949c74 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/DatasourceContextServiceCE.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/DatasourceContextServiceCE.java @@ -1,27 +1,38 @@ package com.appsmith.server.services.ce; import com.appsmith.external.models.Datasource; +import com.appsmith.external.models.BaseDomain; import com.appsmith.server.domains.DatasourceContext; +import com.appsmith.server.domains.DatasourceContextIdentifier; import com.appsmith.server.domains.Plugin; import reactor.core.publisher.Mono; import java.util.function.Function; +import java.util.Map; public interface DatasourceContextServiceCE { /** * This function is responsible for returning the datasource context stored - * against the datasource id. In case the datasourceId is not found in the + * against the DatasourceContextIdentifier object, + * which stores datasourceId in CE and environmentId as well in EE. + * In case the datasourceId is not found in the * map, create a new datasource context and return that. - * + * The environmentMap parameter is not being Used in the CE version. it's specific to EE version * @param datasource + * @param datasourceContextIdentifier + * @param environmentMap * @return DatasourceContext */ - Mono<DatasourceContext<?>> getDatasourceContext(Datasource datasource); + Mono<DatasourceContext<?>> getDatasourceContext(Datasource datasource, DatasourceContextIdentifier datasourceContextIdentifier, + Map<String, BaseDomain> environmentMap); Mono<DatasourceContext<?>> getRemoteDatasourceContext(Plugin plugin, Datasource datasource); - <T> Mono<T> retryOnce(Datasource datasource, Function<DatasourceContext<?>, Mono<T>> task); + <T> Mono<T> retryOnce(Datasource datasource, DatasourceContextIdentifier datasourceContextIdentifier, + Map<String, BaseDomain> environmentMap, Function<DatasourceContext<?>, Mono<T>> task); - Mono<DatasourceContext<?>> deleteDatasourceContext(String datasourceId); + Mono<DatasourceContext<?>> deleteDatasourceContext(DatasourceContextIdentifier datasourceContextIdentifier); + + DatasourceContextIdentifier createDsContextIdentifier(Datasource datasource); } 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 f2f1115073c3..066a419496cb 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,10 +3,12 @@ import com.appsmith.external.dtos.DatasourceDTO; import com.appsmith.external.dtos.ExecutePluginDTO; import com.appsmith.external.exceptions.pluginExceptions.StaleConnectionException; +import com.appsmith.external.models.BaseDomain; import com.appsmith.external.models.Datasource; import com.appsmith.external.models.UpdatableConnection; import com.appsmith.external.plugins.PluginExecutor; import com.appsmith.server.domains.DatasourceContext; +import com.appsmith.server.domains.DatasourceContextIdentifier; import com.appsmith.server.domains.Plugin; import com.appsmith.server.helpers.PluginExecutorHelper; import com.appsmith.server.services.ConfigService; @@ -23,15 +25,14 @@ import java.util.concurrent.ConcurrentHashMap; import java.util.function.Function; -import static com.appsmith.server.acl.AclPermission.EXECUTE_DATASOURCES; @Slf4j public class DatasourceContextServiceCEImpl implements DatasourceContextServiceCE { - //This is DatasourceId mapped to the DatasourceContext - private final Map<String, Mono<? extends DatasourceContext<?>>> datasourceContextMonoMap; - private final Map<String, Object> datasourceContextSynchronizationMonitorMap; - private final Map<String, DatasourceContext<?>> datasourceContextMap; + //DatasourceContextIdentifier contains datasourceId & environmentId which is mapped to DatasourceContext + protected final Map<DatasourceContextIdentifier, Mono<? extends DatasourceContext<?>>> datasourceContextMonoMap; + protected final Map<DatasourceContextIdentifier, Object> datasourceContextSynchronizationMonitorMap; + protected final Map<DatasourceContextIdentifier, DatasourceContext<?>> datasourceContextMap; private final DatasourceService datasourceService; private final PluginService pluginService; private final PluginExecutorHelper pluginExecutorHelper; @@ -67,18 +68,19 @@ public DatasourceContextServiceCEImpl(@Lazy DatasourceService datasourceService, * @param datasource - datasource for which a new datasource context / connection needs to be created * @param pluginExecutor - plugin executor associated with the datasource's plugin * @param monitor - unique monitor object per datasource id. Lock is acquired on this monitor object. + * @param datasourceContextIdentifier - key for the datasourceContextMaps. * @return a cached source publisher which upon subscription produces / returns the latest datasource context / * connection. */ public Mono<? extends DatasourceContext<?>> getCachedDatasourceContextMono(Datasource datasource, PluginExecutor<Object> pluginExecutor, - Object monitor) { + Object monitor, + DatasourceContextIdentifier datasourceContextIdentifier) { synchronized (monitor) { /* Destroy any stale connection to free up resource */ - String datasourceId = datasource.getId(); - final boolean isStale = getIsStale(datasource); + final boolean isStale = getIsStale(datasource, datasourceContextIdentifier); if (isStale) { - final Object connection = datasourceContextMap.get(datasourceId).getConnection(); + final Object connection = datasourceContextMap.get(datasourceContextIdentifier).getConnection(); if (connection != null) { try { // Basically remove entry from both cache maps @@ -87,8 +89,8 @@ public Mono<? extends DatasourceContext<?>> getCachedDatasourceContextMono(Datas log.info("Error destroying stale datasource connection", e); } } - datasourceContextMonoMap.remove(datasourceId); - datasourceContextMap.remove(datasourceId); + datasourceContextMonoMap.remove(datasourceContextIdentifier); + datasourceContextMap.remove(datasourceContextIdentifier); } /* @@ -96,64 +98,70 @@ public Mono<? extends DatasourceContext<?>> getCachedDatasourceContextMono(Datas * evaluated multiple times the actual datasource creation will only happen once and get cached and the same * value would directly be returned to further evaluations / subscriptions. */ - if (datasourceId != null && datasourceContextMonoMap.get(datasourceId) != null) { + if (datasourceContextIdentifier.getDatasourceId() != null && datasourceContextMonoMap.get(datasourceContextIdentifier) != null) { log.debug("Cached resource context mono exists. Returning the same."); - return datasourceContextMonoMap.get(datasourceId); + return datasourceContextMonoMap.get(datasourceContextIdentifier); } /* Create a fresh datasource context */ - DatasourceContext<Object> datasourceContext = new DatasourceContext<Object>(); - if (datasourceId != null) { + DatasourceContext<Object> datasourceContext = new DatasourceContext<>(); + if (datasourceContextIdentifier.isKeyValid()) { /* For this datasource, either the context doesn't exist, or the context is stale. Replace (or add) with the new connection in the context map. */ - datasourceContextMap.put(datasourceId, datasourceContext); + datasourceContextMap.put(datasourceContextIdentifier, datasourceContext); } Mono<Object> connectionMono = pluginExecutor.datasourceCreate(datasource.getDatasourceConfiguration()).cache(); Mono<DatasourceContext<Object>> datasourceContextMonoCache = connectionMono - .flatMap(connection -> { - Mono<Datasource> datasourceMono1 = Mono.just(datasource); - if (connection instanceof UpdatableConnection) { - datasource.setUpdatedAt(Instant.now()); - datasource - .getDatasourceConfiguration() - .setAuthentication( - ((UpdatableConnection) connection).getAuthenticationDTO( - datasource.getDatasourceConfiguration().getAuthentication())); - datasourceMono1 = datasourceService.update(datasource.getId(), datasource); - } - return datasourceMono1.thenReturn(connection); - }) + .flatMap(connection -> updateDatasourceAndSetAuthentication(connection, datasource, datasourceContextIdentifier)) .map(connection -> { /* When a connection object exists and makes sense for the plugin, we put it in the - context. Example, DB plugins. */ + context. Example, DB plugins. */ datasourceContext.setConnection(connection); return datasourceContext; }) .defaultIfEmpty( - /* When a connection object doesn't make sense for the plugin, we get an empty mono and we - just return the context object as is. */ - datasourceContext - ) + /* When a connection object doesn't make sense for the plugin, we get an empty mono + and we just return the context object as is. */ + datasourceContext) .cache(); /* Cache the value so that further evaluations don't result in new connections */ - if (datasourceId != null) { - datasourceContextMonoMap.put(datasourceId, datasourceContextMonoCache); + + if (datasourceContextIdentifier.isKeyValid()) { + datasourceContextMonoMap.put(datasourceContextIdentifier, datasourceContextMonoCache); } return datasourceContextMonoCache; } } - Mono<DatasourceContext<?>> createNewDatasourceContext(Datasource datasource) { - log.debug("Datasource context doesn't exist. Creating connection."); + public Mono<Object> updateDatasourceAndSetAuthentication(Object connection, Datasource datasource, + DatasourceContextIdentifier datasourceContextIdentifier) { + // this will have override in EE + Mono<Datasource> datasourceMono1 = Mono.just(datasource); + if (connection instanceof UpdatableConnection) { + datasource.setUpdatedAt(Instant.now()); + datasource + .getDatasourceConfiguration() + .setAuthentication( + ((UpdatableConnection) connection).getAuthenticationDTO( + datasource.getDatasourceConfiguration().getAuthentication())); + datasourceMono1 = datasourceService.update(datasource.getId(), datasource); + } + return datasourceMono1.thenReturn(connection); + } - String datasourceId = datasource.getId(); - Mono<Datasource> datasourceMono; - if (datasource.getId() != null) { - datasourceMono = datasourceService.findById(datasourceId, datasourcePermission.getExecutePermission()); + Mono<Datasource> retrieveDatasourceFromDB( Datasource datasource, DatasourceContextIdentifier datasourceContextIdentifier) { + if (datasourceContextIdentifier.isKeyValid()) { + return datasourceService.findById(datasourceContextIdentifier.getDatasourceId(), + datasourcePermission.getExecutePermission()); } else { - datasourceMono = Mono.just(datasource); + return Mono.just(datasource); } + } + + protected Mono<DatasourceContext<?>> createNewDatasourceContext(Datasource datasource, DatasourceContextIdentifier datasourceContextIdentifier) { + log.debug("Datasource context doesn't exist. Creating connection."); + Mono<Datasource> datasourceMono = retrieveDatasourceFromDB(datasource, datasourceContextIdentifier); return datasourceMono .zipWhen(datasource1 -> { @@ -176,76 +184,79 @@ Mono<DatasourceContext<?>> createNewDatasourceContext(Datasource datasource) { * synchronized. */ Object monitor = new Object(); - if (datasourceId != null) { - if (datasourceContextSynchronizationMonitorMap.get(datasourceId) == null) { + if (datasourceContextIdentifier.isKeyValid()) { + if (datasourceContextSynchronizationMonitorMap.get(datasourceContextIdentifier) == null) { synchronized (this) { - if (datasourceContextSynchronizationMonitorMap.get(datasourceId) == null) { - datasourceContextSynchronizationMonitorMap.put(datasourceId, new Object()); + if (datasourceContextSynchronizationMonitorMap.get(datasourceContextIdentifier) == null) { + datasourceContextSynchronizationMonitorMap.put(datasourceContextIdentifier, new Object()); } } } - monitor = datasourceContextSynchronizationMonitorMap.get(datasourceId); + monitor = datasourceContextSynchronizationMonitorMap.get(datasourceContextIdentifier); } - return getCachedDatasourceContextMono(datasource1, pluginExecutor, monitor); + return getCachedDatasourceContextMono(datasource1, pluginExecutor, monitor, datasourceContextIdentifier); }); } - public boolean getIsStale(Datasource datasource) { + public boolean getIsStale(Datasource datasource, DatasourceContextIdentifier datasourceContextIdentifier) { String datasourceId = datasource.getId(); return datasourceId != null - && datasourceContextMap.get(datasourceId) != null + && datasourceContextMap.get(datasourceContextIdentifier) != null && datasource.getUpdatedAt() != null - && datasource.getUpdatedAt().isAfter(datasourceContextMap.get(datasourceId).getCreationTime()); + && datasource.getUpdatedAt().isAfter(datasourceContextMap.get(datasourceContextIdentifier).getCreationTime()); } - boolean isValidDatasourceContextAvailable(Datasource datasource) { - String datasourceId = datasource.getId(); - boolean isStale = getIsStale(datasource); - return datasourceContextMap.get(datasourceId) != null + protected boolean isValidDatasourceContextAvailable(Datasource datasource, DatasourceContextIdentifier datasourceContextIdentifier) { + boolean isStale = getIsStale(datasource, datasourceContextIdentifier); + return datasourceContextMap.get(datasourceContextIdentifier) != null // The following condition happens when there's a timeout in the middle of destroying a connection and // the reactive flow interrupts, resulting in the destroy operation not completing. - && datasourceContextMap.get(datasourceId).getConnection() != null + && datasourceContextMap.get(datasourceContextIdentifier).getConnection() != null && !isStale; } @Override - public Mono<DatasourceContext<?>> getDatasourceContext(Datasource datasource) { + public Mono<DatasourceContext<?>> getDatasourceContext(Datasource datasource, DatasourceContextIdentifier datasourceContextIdentifier, + Map<String, BaseDomain> environmentMap) { String datasourceId = datasource.getId(); if (datasourceId == null) { log.debug("This is a dry run or an embedded datasource. The datasource context would not exist in this " + "scenario"); - } else if (isValidDatasourceContextAvailable(datasource)) { + } else if (isValidDatasourceContextAvailable(datasource, datasourceContextIdentifier)) { log.debug("Resource context exists. Returning the same."); - return Mono.just(datasourceContextMap.get(datasourceId)); + return Mono.just(datasourceContextMap.get(datasourceContextIdentifier)); } - - return createNewDatasourceContext(datasource); + return createNewDatasourceContext(datasource, datasourceContextIdentifier); } @Override - public <T> Mono<T> retryOnce(Datasource datasource, Function<DatasourceContext<?>, Mono<T>> task) { + public <T> Mono<T> retryOnce(Datasource datasource, DatasourceContextIdentifier datasourceContextIdentifier, + Map<String, BaseDomain> environmentMap, Function<DatasourceContext<?>, Mono<T>> task) { + final Mono<T> taskRunnerMono = Mono.justOrEmpty(datasource) - .flatMap(this::getDatasourceContext) + .flatMap(datasource1 -> getDatasourceContext(datasource1, datasourceContextIdentifier, environmentMap)) // Now that we have the context (connection details), call the task. .flatMap(task); return taskRunnerMono .onErrorResume(StaleConnectionException.class, error -> { log.info("Looks like the connection is stale. Retrying with a fresh context."); - return deleteDatasourceContext(datasource.getId()) + return deleteDatasourceContext(datasourceContextIdentifier) .then(taskRunnerMono); }); } @Override - public Mono<DatasourceContext<?>> deleteDatasourceContext(String datasourceId) { - if (datasourceId == null) { + public Mono<DatasourceContext<?>> deleteDatasourceContext(DatasourceContextIdentifier datasourceContextIdentifier) { + + String datasourceId = datasourceContextIdentifier.getDatasourceId(); + if (!datasourceContextIdentifier.isKeyValid()) { return Mono.empty(); } - DatasourceContext<?> datasourceContext = datasourceContextMap.get(datasourceId); + DatasourceContext<?> datasourceContext = datasourceContextMap.get(datasourceContextIdentifier); if (datasourceContext == null) { // No resource context exists for this resource. Return void. return Mono.empty(); @@ -261,8 +272,8 @@ public Mono<DatasourceContext<?>> deleteDatasourceContext(String datasourceId) { final PluginExecutor<Object> pluginExecutor = tuple.getT2(); log.info("Clearing datasource context for datasource ID {}.", datasource.getId()); pluginExecutor.datasourceDestroy(datasourceContext.getConnection()); - datasourceContextMonoMap.remove(datasourceId); - return datasourceContextMap.remove(datasourceId); + datasourceContextMonoMap.remove(datasourceContextIdentifier); + return datasourceContextMap.remove(datasourceContextIdentifier); }); } @@ -283,4 +294,18 @@ public Mono<DatasourceContext<?>> getRemoteDatasourceContext(Plugin plugin, Data return datasourceContext; }); } + + + /** + * Generates the custom key that is used in: + * datasourceContextMap + * datasourceContextMonoMap + * datasourceContextSynchronizationMonitorMap + * @param datasource + * @return an DatasourceContextIdentifier object + */ + @Override + public DatasourceContextIdentifier createDsContextIdentifier(Datasource datasource) { + return new DatasourceContextIdentifier(datasource.getId(), null); + } } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/DatasourceServiceCE.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/DatasourceServiceCE.java index bdc2ce1be41b..aa0b7bb009a7 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/DatasourceServiceCE.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/DatasourceServiceCE.java @@ -1,15 +1,19 @@ package com.appsmith.server.services.ce; import com.appsmith.external.models.ActionDTO; +import com.appsmith.external.models.BaseDomain; import com.appsmith.external.models.Datasource; import com.appsmith.external.models.DatasourceTestResult; import com.appsmith.external.models.MustacheBindingToken; import com.appsmith.server.acl.AclPermission; +import com.appsmith.server.domains.DatasourceContextIdentifier; import com.appsmith.server.services.CrudService; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; +import reactor.util.function.Tuple3; import java.util.List; +import java.util.Map; import java.util.Optional; import java.util.Set; @@ -45,4 +49,7 @@ public interface DatasourceServiceCE extends CrudService<Datasource, String> { Mono<Datasource> createWithoutPermissions(Datasource datasource); + Mono<Tuple3<Datasource, DatasourceContextIdentifier, Map<String, BaseDomain>>> + getEvaluatedDSAndDsContextKeyWithEnvMap(Datasource datasource, String environmentName); + } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/DatasourceServiceCEImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/DatasourceServiceCEImpl.java index 94d51a1195f7..da1854fab184 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/DatasourceServiceCEImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/DatasourceServiceCEImpl.java @@ -3,7 +3,7 @@ import com.appsmith.external.helpers.AppsmithBeanUtils; import com.appsmith.external.helpers.MustacheHelper; import com.appsmith.external.models.ActionDTO; -import com.appsmith.external.models.AuthenticationDTO; +import com.appsmith.external.models.BaseDomain; import com.appsmith.external.models.Datasource; import com.appsmith.external.models.DatasourceConfiguration; import com.appsmith.external.models.DatasourceTestResult; @@ -16,6 +16,7 @@ import com.appsmith.server.acl.AclPermission; import com.appsmith.server.acl.PolicyGenerator; import com.appsmith.server.constants.FieldName; +import com.appsmith.server.domains.DatasourceContextIdentifier; import com.appsmith.server.domains.Plugin; import com.appsmith.server.domains.User; import com.appsmith.server.domains.Workspace; @@ -46,6 +47,7 @@ import reactor.core.publisher.Mono; import reactor.core.scheduler.Scheduler; import reactor.util.function.Tuple2; +import reactor.util.function.Tuple3; import reactor.util.function.Tuples; import jakarta.validation.Validator; @@ -482,7 +484,7 @@ public Mono<Datasource> archiveById(String id) { return Mono.just(objects.getT1()); }) .flatMap(toDelete -> { - return datasourceContextService.deleteDatasourceContext(toDelete.getId()) + return datasourceContextService.deleteDatasourceContext(datasourceContextService.createDsContextIdentifier(toDelete)) .then(repository.archive(toDelete)) .thenReturn(toDelete); }) @@ -553,4 +555,23 @@ private void markRecentlyUsed(List<Datasource> datasourceList, int recentlyUsedC datasource.setIsRecentlyCreated(true); } } + + /** + * This is a composite method for retrieving datasource, datasourceContextIdentifier and environmentMap + * See EE override for complete usage + * @param datasource + * @param environmentName + * @return + */ + @Override + public Mono<Tuple3<Datasource, DatasourceContextIdentifier, Map<String, BaseDomain>>> + getEvaluatedDSAndDsContextKeyWithEnvMap(Datasource datasource, String environmentName) { + // see EE override for complete usage. + Mono<DatasourceContextIdentifier> datasourceContextIdentifierMono = Mono.just(datasourceContextService.createDsContextIdentifier(datasource)); + + // see EE override for complete usage, + // Here just returning an empty map, this map is not used here + Mono<Map<String, BaseDomain>> environmentMapMono = Mono.just(new HashMap<>()); + return Mono.zip(Mono.just(datasource), datasourceContextIdentifierMono, environmentMapMono); + } } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/NewActionServiceCEImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/NewActionServiceCEImpl.java index bcfc40540cc3..b9f5c154ac75 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/NewActionServiceCEImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/NewActionServiceCEImpl.java @@ -24,6 +24,7 @@ import com.appsmith.external.models.Property; import com.appsmith.external.models.Provider; import com.appsmith.external.models.RequestParamDTO; +import com.appsmith.external.models.BaseDomain; import com.appsmith.external.plugins.PluginExecutor; import com.appsmith.server.acl.AclPermission; import com.appsmith.server.acl.PolicyGenerator; @@ -32,6 +33,7 @@ import com.appsmith.server.domains.Application; import com.appsmith.server.domains.ApplicationMode; import com.appsmith.server.domains.DatasourceContext; +import com.appsmith.server.domains.DatasourceContextIdentifier; import com.appsmith.server.domains.NewAction; import com.appsmith.server.domains.NewPage; import com.appsmith.server.domains.Page; @@ -84,6 +86,7 @@ import reactor.core.publisher.Mono; import reactor.core.scheduler.Scheduler; import reactor.util.function.Tuple2; +import reactor.util.function.Tuple3; import reactor.util.function.Tuple5; import javax.lang.model.SourceVersion; @@ -702,7 +705,6 @@ protected Mono<Datasource> getCachedDatasourceForActionExecution(Mono<ActionDTO> /** * fetches and caches plugin by pluginId after checking datasource for invalids(issues) - * * @param datasourceMono * @param actionId * @return pluginMono if datasource has no issues and plugin is find, else throws error @@ -764,45 +766,80 @@ protected Mono<ActionExecutionResult> verifyDatasourceAndMakeRequest(ExecuteActi Plugin plugin, PluginExecutor pluginExecutor, String environmentName) { - // This method will be overridden in EE branch to make use of environmentName. - Mono<Datasource> validatedDatasourceMono = getValidatedDatasourceForActionExecution(datasource, environmentName); - - Mono<ActionExecutionResult> executionMono = validatedDatasourceMono - .flatMap(datasource1 -> getDatasourceContextFromValidatedDatasourceForActionExecution(datasource1, - plugin, - environmentName)) - // Now that we have the context (connection details), execute the action. - .flatMap(resourceContext -> validatedDatasourceMono - .flatMap(datasource1 -> { - final Instant requestedAt = Instant.now(); - return ((Mono<ActionExecutionResult>) pluginExecutor. - executeParameterized(resourceContext.getConnection(), - executeActionDTO, - datasource1.getDatasourceConfiguration(), - actionDTO.getActionConfiguration())) - .map(actionExecutionResult -> { - ActionExecutionRequest actionExecutionRequest = actionExecutionResult.getRequest(); - if (actionExecutionRequest == null) { - actionExecutionRequest = new ActionExecutionRequest(); - } - actionExecutionRequest.setActionId(executeActionDTO.getActionId()); - actionExecutionRequest.setRequestedAt(requestedAt); - - actionExecutionResult.setRequest(actionExecutionRequest); - return actionExecutionResult; + + DatasourceContextIdentifier dsContextIdentifier = new DatasourceContextIdentifier(); + + Mono<ActionExecutionResult> executionMono = + datasourceService.getEvaluatedDSAndDsContextKeyWithEnvMap(datasource, environmentName) + .flatMap( tuple3 -> { + Datasource datasource1 = tuple3.getT1(); + DatasourceContextIdentifier datasourceContextIdentifier = tuple3.getT2(); + Map<String, BaseDomain> environmentMap = tuple3.getT3(); + + dsContextIdentifier.setDatasourceId(datasourceContextIdentifier.getDatasourceId()); + dsContextIdentifier.setEnvironmentId(datasourceContextIdentifier.getEnvironmentId()); + + return getValidatedDatasourceForActionExecution(datasource1, environmentName) + .zipWhen(validatedDatasource -> getDsContextForActionExecution(validatedDatasource, + plugin, datasourceContextIdentifier, + environmentMap)) + .flatMap(tuple2 -> { + Datasource validatedDatasource = tuple2.getT1(); + DatasourceContext<?> resourceContext = tuple2.getT2(); + // Now that we have the context (connection details), execute the action. + + Instant requestedAt = Instant.now(); + return ((Mono<ActionExecutionResult>) + pluginExecutor.executeParameterized(resourceContext.getConnection(), + executeActionDTO, + validatedDatasource.getDatasourceConfiguration(), + actionDTO.getActionConfiguration())) + .map(actionExecutionResult -> { + ActionExecutionRequest actionExecutionRequest = actionExecutionResult.getRequest(); + if (actionExecutionRequest == null) { + actionExecutionRequest = new ActionExecutionRequest(); + } + + actionExecutionRequest.setActionId(executeActionDTO.getActionId()); + actionExecutionRequest.setRequestedAt(requestedAt); + + actionExecutionResult.setRequest(actionExecutionRequest); + return actionExecutionResult; + }); }); - })); + }); return executionMono.onErrorResume(StaleConnectionException.class, error -> { log.info("Looks like the connection is stale. Retrying with a fresh context."); - return deleteDatasourceContextForRetry(datasource, environmentName) - .then(executionMono); + return deleteDatasourceContextForRetry(dsContextIdentifier).then(executionMono); }); } + /** + * This is a composite method for fetching authenticated datasource, datasourceContextIdentifier, and environmentMap + * @param datasource + * @param environmentName + * @return + */ + protected Mono<Tuple3 <Datasource, DatasourceContextIdentifier, Map<String, BaseDomain>>> + getValidatedDatasourceWithDsContextKeyAndEnvMap(Datasource datasource, String environmentName) { + // see EE override for complete usage. + return datasourceService.getEvaluatedDSAndDsContextKeyWithEnvMap(datasource, environmentName) + .flatMap(tuple3 -> { + Datasource datasource1 = tuple3.getT1(); + DatasourceContextIdentifier datasourceContextIdentifier = tuple3.getT2(); + Map<String, BaseDomain> environmentMap = tuple3.getT3(); + + return getValidatedDatasourceForActionExecution(datasource1, environmentName) + .flatMap(datasource2 -> Mono.zip(Mono.just(datasource2), + Mono.just(datasourceContextIdentifier), + Mono.just(environmentMap)) + ); + }); + } + /** * Validates the datasource for further execution - * * @param datasource * @return */ @@ -817,31 +854,28 @@ protected Mono<Datasource> getValidatedDatasourceForActionExecution(Datasource d * * @param validatedDatasource * @param plugin - * @param environmentName + * @param datasourceContextIdentifier + * @param environmentMap * @return datasourceContextMono */ - protected Mono<DatasourceContext<?>> getDatasourceContextFromValidatedDatasourceForActionExecution - (Datasource validatedDatasource, Plugin plugin, String environmentName) { - // the environmentName argument is not consumed over here - // See EE override for usage of variable + protected Mono<DatasourceContext<?>> getDsContextForActionExecution (Datasource validatedDatasource, Plugin plugin, + DatasourceContextIdentifier datasourceContextIdentifier, + Map<String, BaseDomain> environmentMap) { if (plugin.isRemotePlugin()) { return datasourceContextService.getRemoteDatasourceContext(plugin, validatedDatasource); } - return datasourceContextService.getDatasourceContext(validatedDatasource); - + return datasourceContextService.getDatasourceContext(validatedDatasource, datasourceContextIdentifier, environmentMap); } /** * Deletes the datasourceContext for the given datasource - * - * @param datasource - * @param environmentName + * @param datasourceContextIdentifier * @return datasourceContextMono */ - protected Mono<DatasourceContext<?>> deleteDatasourceContextForRetry(Datasource datasource, String environmentName) { + protected Mono<DatasourceContext<?>> deleteDatasourceContextForRetry(DatasourceContextIdentifier datasourceContextIdentifier) { // the environmentName argument is not consumed over here // See EE override for usage of variable - return datasourceContextService.deleteDatasourceContext(datasource.getId()); + return datasourceContextService.deleteDatasourceContext(datasourceContextIdentifier); } protected Mono<ActionExecutionResult> handleExecutionErrors(Mono<ActionExecutionResult> actionExecutionResultMono, 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 215250a5f109..b4153bd6b359 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 @@ -5,11 +5,13 @@ import com.appsmith.external.exceptions.pluginExceptions.StaleConnectionException; import com.appsmith.external.models.ActionExecutionResult; import com.appsmith.external.models.AuthenticationDTO; +import com.appsmith.external.models.BaseDomain; import com.appsmith.external.models.Datasource; import com.appsmith.external.models.DatasourceStructure; import com.appsmith.external.models.Property; import com.appsmith.external.plugins.PluginExecutor; import com.appsmith.server.constants.FieldName; +import com.appsmith.server.domains.DatasourceContextIdentifier; import com.appsmith.server.exceptions.AppsmithError; import com.appsmith.server.exceptions.AppsmithException; import com.appsmith.server.helpers.PluginExecutorHelper; @@ -26,6 +28,7 @@ import java.time.Duration; import java.util.List; +import java.util.Map; import java.util.concurrent.TimeoutException; @RequiredArgsConstructor @@ -84,13 +87,18 @@ public Mono<DatasourceStructure> getStructure(Datasource datasource, boolean ign return pluginExecutorHelper .getPluginExecutor(pluginService.findById(datasource.getPluginId())) .switchIfEmpty(Mono.error(new AppsmithException(AppsmithError.NO_RESOURCE_FOUND, FieldName.PLUGIN, datasource.getPluginId()))) - .flatMap(pluginExecutor -> datasourceContextService - .retryOnce( - datasource, - resourceContext -> ((PluginExecutor<Object>) pluginExecutor) - .getStructure(resourceContext.getConnection(), datasource.getDatasourceConfiguration()) - ) - ) + .flatMap(pluginExecutor -> datasourceService + .getEvaluatedDSAndDsContextKeyWithEnvMap(datasource, null) + .flatMap(tuple3 -> { + Datasource datasource2 = tuple3.getT1(); + DatasourceContextIdentifier datasourceContextIdentifier = tuple3.getT2(); + Map<String, BaseDomain> environmentMap = tuple3.getT3(); + return datasourceContextService + .retryOnce(datasource2, datasourceContextIdentifier, environmentMap, + resourceContext -> ((PluginExecutor<Object>) pluginExecutor) + .getStructure(resourceContext.getConnection(), + datasource.getDatasourceConfiguration())); + })) .timeout(Duration.ofSeconds(GET_STRUCTURE_TIMEOUT_SECONDS)) .onErrorMap( TimeoutException.class, diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ce/DatasourceTriggerSolutionCEImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ce/DatasourceTriggerSolutionCEImpl.java index deb5d8106a91..626e800757ca 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ce/DatasourceTriggerSolutionCEImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ce/DatasourceTriggerSolutionCEImpl.java @@ -1,11 +1,13 @@ package com.appsmith.server.solutions.ce; +import com.appsmith.external.models.BaseDomain; import com.appsmith.external.models.ClientDataDisplayType; import com.appsmith.external.models.Datasource; import com.appsmith.external.models.DatasourceStructure; import com.appsmith.external.models.TriggerRequestDTO; import com.appsmith.external.models.TriggerResultDTO; import com.appsmith.external.plugins.PluginExecutor; +import com.appsmith.server.domains.DatasourceContextIdentifier; import com.appsmith.server.domains.Plugin; import com.appsmith.server.exceptions.AppsmithError; import com.appsmith.server.exceptions.AppsmithException; @@ -28,7 +30,6 @@ import java.util.Optional; import java.util.Set; -import static com.appsmith.server.acl.AclPermission.READ_DATASOURCES; import static com.appsmith.server.constants.FieldName.DISPLAY_TYPE; import static com.appsmith.server.constants.FieldName.REQUEST_TYPE; @@ -86,7 +87,14 @@ public Mono<TriggerResultDTO> trigger(String datasourceId, TriggerRequestDTO tri if (plugin.isRemotePlugin()) { return datasourceContextService.getRemoteDatasourceContext(plugin, datasource1); } else { - return datasourceContextService.getDatasourceContext(datasource1); + return datasourceService.getEvaluatedDSAndDsContextKeyWithEnvMap(datasource1, null) + .flatMap(tuple3 -> { + Datasource datasource2 = tuple3.getT1(); + DatasourceContextIdentifier datasourceContextIdentifier = tuple3.getT2(); + Map<String, BaseDomain> environmentMap = tuple3.getT3(); + return datasourceContextService.getDatasourceContext(datasource2, datasourceContextIdentifier, + environmentMap); + }); } }) // Now that we have the context (connection details), execute the action. diff --git a/app/server/appsmith-server/src/test/java/com/appsmith/server/services/DatasourceContextServiceTest.java b/app/server/appsmith-server/src/test/java/com/appsmith/server/services/DatasourceContextServiceTest.java index 58cfc1b817aa..a8dc3eeeac68 100644 --- a/app/server/appsmith-server/src/test/java/com/appsmith/server/services/DatasourceContextServiceTest.java +++ b/app/server/appsmith-server/src/test/java/com/appsmith/server/services/DatasourceContextServiceTest.java @@ -8,6 +8,7 @@ import com.appsmith.external.models.UpdatableConnection; import com.appsmith.external.services.EncryptionService; import com.appsmith.server.domains.DatasourceContext; +import com.appsmith.server.domains.DatasourceContextIdentifier; import com.appsmith.server.domains.Plugin; import com.appsmith.server.domains.User; import com.appsmith.server.domains.Workspace; @@ -18,6 +19,7 @@ import com.appsmith.server.repositories.WorkspaceRepository; import com.appsmith.server.solutions.DatasourcePermission; import lombok.extern.slf4j.Slf4j; +import org.bson.types.ObjectId; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mockito; @@ -31,6 +33,7 @@ import reactor.test.StepVerifier; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertTrue; @@ -80,7 +83,7 @@ public class DatasourceContextServiceTest { @WithUserDetails(value = "api_user") public void testDatasourceCache_afterDatasourceDeleted_doesNotReturnOldConnection() { // Never require the datasource connectin to be stale - doReturn(false).doReturn(false).when(datasourceContextService).getIsStale(any()); + doReturn(false).doReturn(false).when(datasourceContextService).getIsStale(any(), any()); MockPluginExecutor mockPluginExecutor = new MockPluginExecutor(); MockPluginExecutor spyMockPluginExecutor = spy(mockPluginExecutor); @@ -94,10 +97,12 @@ public void testDatasourceCache_afterDatasourceDeleted_doesNotReturnOldConnectio datasource.setDatasourceConfiguration(new DatasourceConfiguration()); datasource.setWorkspaceId("workspaceId"); + DatasourceContextIdentifier datasourceContextIdentifier = new DatasourceContextIdentifier(datasource.getId(), null); + Object monitor = new Object(); // Create one instance of datasource connection Mono<DatasourceContext<?>> dsContextMono1 = datasourceContextService.getCachedDatasourceContextMono(datasource, - spyMockPluginExecutor, monitor); + spyMockPluginExecutor, monitor, datasourceContextIdentifier); doReturn(Mono.just(datasource)).when(datasourceRepository).findById("id1", datasourcePermission.getDeletePermission()); doReturn(Mono.just(datasource)).when(datasourceRepository).findById("id1", datasourcePermission.getExecutePermission()); @@ -108,7 +113,7 @@ public void testDatasourceCache_afterDatasourceDeleted_doesNotReturnOldConnectio // Now delete the datasource and check if the cache retains the same instance of connection Mono<DatasourceContext<?>> dsContextMono2 = datasourceService.archiveById("id1") .flatMap(deleted -> datasourceContextService.getCachedDatasourceContextMono(datasource, - spyMockPluginExecutor, monitor)); + spyMockPluginExecutor, monitor, datasourceContextIdentifier)); StepVerifier.create(dsContextMono1) .assertNext(dsContext1 -> { @@ -223,7 +228,7 @@ public void checkDecryptionOfAuthenticationDTONullPassword() { @Test @WithUserDetails(value = "api_user") public void testCachedDatasourceCreate() { - doReturn(false).doReturn(false).when(datasourceContextService).getIsStale(any()); + doReturn(false).doReturn(false).when(datasourceContextService).getIsStale(any(), any()); MockPluginExecutor mockPluginExecutor = new MockPluginExecutor(); MockPluginExecutor spyMockPluginExecutor = spy(mockPluginExecutor); @@ -234,12 +239,14 @@ public void testCachedDatasourceCreate() { datasource.setId("id2"); datasource.setDatasourceConfiguration(new DatasourceConfiguration()); + DatasourceContextIdentifier datasourceContextIdentifier = new DatasourceContextIdentifier(datasource.getId(), "envId"); + Object monitor = new Object(); DatasourceContext<?> dsContext1 = (DatasourceContext<?>) datasourceContextService - .getCachedDatasourceContextMono(datasource, spyMockPluginExecutor, monitor) + .getCachedDatasourceContextMono(datasource, spyMockPluginExecutor, monitor, datasourceContextIdentifier) .block(); DatasourceContext<?> dsContext2 = (DatasourceContext<?>) datasourceContextService - .getCachedDatasourceContextMono(datasource, spyMockPluginExecutor, monitor) + .getCachedDatasourceContextMono(datasource, spyMockPluginExecutor, monitor, datasourceContextIdentifier) .block(); /* They can only be equal if the `datasourceCreate` method was called only once */ @@ -294,18 +301,45 @@ public void testDatasourceCreate_withUpdatableConnection_recreatesConnectionAlwa assert createdDatasource != null; + DatasourceContextIdentifier datasourceContextIdentifier = new DatasourceContextIdentifier(createdDatasource.getId(), "envId"); + Object monitor = new Object(); final DatasourceContext<?> dsc1 = (DatasourceContext) datasourceContextService.getCachedDatasourceContextMono(createdDatasource, - spyMockPluginExecutor, monitor).block(); + spyMockPluginExecutor, monitor, datasourceContextIdentifier).block(); assertNotNull(dsc1); assertTrue(dsc1.getConnection() instanceof UpdatableConnection); assertTrue(((UpdatableConnection) dsc1.getConnection()).getAuthenticationDTO(new ApiKeyAuth()) instanceof DBAuth); final DatasourceContext<?> dsc2 = (DatasourceContext) datasourceContextService.getCachedDatasourceContextMono(createdDatasource, - spyMockPluginExecutor, monitor).block(); + spyMockPluginExecutor, monitor, datasourceContextIdentifier).block(); assertNotNull(dsc2); assertTrue(dsc2.getConnection() instanceof UpdatableConnection); assertTrue(((UpdatableConnection) dsc2.getConnection()).getAuthenticationDTO(new ApiKeyAuth()) instanceof BasicAuth); } + + @Test + public void verifyDsMapKeyEquality() { + String dsId = new ObjectId().toHexString(); + DatasourceContextIdentifier keyObj = new DatasourceContextIdentifier(dsId, null); + DatasourceContextIdentifier keyObj1 = new DatasourceContextIdentifier(dsId, null); + assertEquals(keyObj,keyObj1); + } + + @Test + public void verifyDsMapKeyNotEqual() { + String dsId = new ObjectId().toHexString(); + String dsId1 = new ObjectId().toHexString(); + DatasourceContextIdentifier keyObj = new DatasourceContextIdentifier(dsId, null); + DatasourceContextIdentifier keyObj1 = new DatasourceContextIdentifier(dsId1, null); + assertNotEquals(keyObj,keyObj1); + } + + @Test + public void verifyDsMapKeyNotEqualWhenBothDatasourceIdNull() { + String envId = new ObjectId().toHexString(); + DatasourceContextIdentifier keyObj = new DatasourceContextIdentifier(null, envId); + DatasourceContextIdentifier keyObj1 = new DatasourceContextIdentifier(null, envId); + assertNotEquals(keyObj, keyObj1); + } }
36239d82cd5eb5b9cd3c1396ec94638ea3d6d4a9
2023-05-11 10:55:13
Aswath K
feat: Auto Layout editor for everyone (#23005)
false
Auto Layout editor for everyone (#23005)
feat
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 ff6d3734f211..bd7958ea3728 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 @@ -82,12 +82,12 @@ ff4j: - uid: AUTO_LAYOUT enable: true - description: Enable auto layout editor by email domain of user. + description: Enable auto layout editor for everyone flipstrategy: - class: com.appsmith.server.featureflags.strategies.EmailBasedRolloutStrategy + class: org.ff4j.strategy.PonderationStrategy param: - - name: emailDomains - value: appsmith.com,moolya.com + - name: weight + value: 1 # Put EE flags below this line, to avoid conflicts.
90a275a502dec49534b9a58051f1f2f217090e58
2021-09-23 14:17:09
Rishabh Rathod
fix: On connect Tab Switch error (#7740)
false
On connect Tab Switch error (#7740)
fix
diff --git a/app/client/src/actions/applicationActions.ts b/app/client/src/actions/applicationActions.ts index c7d0b403bc6f..486ef763b790 100644 --- a/app/client/src/actions/applicationActions.ts +++ b/app/client/src/actions/applicationActions.ts @@ -217,7 +217,7 @@ export const getSSHKeyPairSuccess = ( export const getSSHKeyPairError = (payload: { error: string; - show?: boolean; + show: boolean; }) => { return { type: ReduxActionErrorTypes.FETCH_SSH_KEY_PAIR_ERROR, diff --git a/app/client/src/actions/gitSyncActions.ts b/app/client/src/actions/gitSyncActions.ts index 5b828ed1721b..ad875c1faf9b 100644 --- a/app/client/src/actions/gitSyncActions.ts +++ b/app/client/src/actions/gitSyncActions.ts @@ -33,7 +33,7 @@ export const pushToRepoSuccess = () => ({ }); export type ConnectToGitResponse = { - gitApplicationMetaData: GitApplicationMetadata; + gitApplicationMetadata: GitApplicationMetadata; }; type ConnectToGitRequestParams = { @@ -92,12 +92,12 @@ export const setIsImportAppViaGitModalOpen = (payload: { }); export const updateGlobalGitConfigInit = (payload: GitConfig) => ({ - type: ReduxActionTypes.UPDATE_GIT_CONFIG_INIT, + type: ReduxActionTypes.UPDATE_GLOBAL_GIT_CONFIG_INIT, payload, }); export const updateGlobalGitConfigSuccess = (payload: GitConfig) => ({ - type: ReduxActionTypes.UPDATE_GIT_CONFIG_SUCCESS, + type: ReduxActionTypes.UPDATE_GLOBAL_GIT_CONFIG_SUCCESS, payload, }); @@ -109,3 +109,23 @@ export const fetchGlobalGitConfigSuccess = (payload: GitConfig) => ({ type: ReduxActionTypes.FETCH_GLOBAL_GIT_CONFIG_SUCCESS, payload, }); + +// Local Git config is repo level +export const updateLocalGitConfigInit = (payload: GitConfig) => ({ + type: ReduxActionTypes.UPDATE_LOCAL_GIT_CONFIG_INIT, + payload, +}); + +export const updateLocalGitConfigSuccess = (payload: GitConfig) => ({ + type: ReduxActionTypes.UPDATE_LOCAL_GIT_CONFIG_SUCCESS, + payload, +}); + +export const fetchLocalGitConfigInit = () => ({ + type: ReduxActionTypes.FETCH_LOCAL_GIT_CONFIG_INIT, +}); + +export const fetchLocalGitConfigSuccess = (payload: GitConfig) => ({ + type: ReduxActionTypes.FETCH_LOCAL_GIT_CONFIG_SUCCESS, + payload, +}); diff --git a/app/client/src/api/GitSyncAPI.tsx b/app/client/src/api/GitSyncAPI.tsx index 087bc58bb187..1ab1ab727b0c 100644 --- a/app/client/src/api/GitSyncAPI.tsx +++ b/app/client/src/api/GitSyncAPI.tsx @@ -52,6 +52,14 @@ class GitSyncAPI extends Api { static setGlobalConfig(payload: GitConfig) { return Api.post(`${GitSyncAPI.baseURL}/config/save`, payload); } + + static getLocalConfig(applicationId: string) { + return Api.get(`${GitSyncAPI.baseURL}/config/${applicationId}`); + } + + static setLocalConfig(payload: GitConfig, applicationId: string) { + return Api.put(`${GitSyncAPI.baseURL}/config/${applicationId}`, payload); + } } export default GitSyncAPI; diff --git a/app/client/src/constants/ReduxActionConstants.tsx b/app/client/src/constants/ReduxActionConstants.tsx index 29339921c3d4..af0ce91f3b52 100644 --- a/app/client/src/constants/ReduxActionConstants.tsx +++ b/app/client/src/constants/ReduxActionConstants.tsx @@ -15,8 +15,12 @@ export const ReduxActionTypes = { SET_IS_IMPORT_APP_VIA_GIT_MODAL_OPEN: "SET_IS_IMPORT_APP_VIA_GIT_MODAL_OPEN", FETCH_GLOBAL_GIT_CONFIG_INIT: "FETCH_GLOBAL_GIT_CONFIG_INIT", FETCH_GLOBAL_GIT_CONFIG_SUCCESS: "FETCH_GLOBAL_GIT_CONFIG_SUCCESS", - UPDATE_GIT_CONFIG_INIT: "UPDATE_GIT_CONFIG_INIT", - UPDATE_GIT_CONFIG_SUCCESS: "UPDATE_GIT_CONFIG_SUCCESS", + UPDATE_GLOBAL_GIT_CONFIG_INIT: "UPDATE_GLOBAL_GIT_CONFIG_INIT", + UPDATE_GLOBAL_GIT_CONFIG_SUCCESS: "UPDATE_GLOBAL_GIT_CONFIG_SUCCESS", + FETCH_LOCAL_GIT_CONFIG_INIT: "FETCH_LOCAL_GIT_CONFIG_INIT", + FETCH_LOCAL_GIT_CONFIG_SUCCESS: "FETCH_LOCAL_GIT_CONFIG_SUCCESS", + UPDATE_LOCAL_GIT_CONFIG_INIT: "UPDATE_LOCAL_GIT_CONFIG_INIT", + UPDATE_LOCAL_GIT_CONFIG_SUCCESS: "UPDATE_LOCAL_GIT_CONFIG_SUCCESS", SHOW_CREATE_GIT_BRANCH_POPUP: "SHOW_CREATE_GIT_BRANCH_POPUP", SHOW_ERROR_POPUP: "SHOW_ERROR_POPUP", CONNECT_TO_GIT_INIT: "CONNECT_TO_GIT_INIT", @@ -591,6 +595,8 @@ export const ReduxActionTypes = { export type ReduxActionType = typeof ReduxActionTypes[keyof typeof ReduxActionTypes]; export const ReduxActionErrorTypes = { + FETCH_LOCAL_GIT_CONFIG_ERROR: "FETCH_LOCAL_GIT_CONFIG_ERROR", + UPDATE_LOCAL_GIT_CONFIG_ERROR: "UPDATE_LOCAL_GIT_CONFIG_ERROR", PUSH_TO_GIT_ERROR: "PUSH_TO_GIT_ERROR", FETCH_SSH_KEY_PAIR_ERROR: "FETCH_SSH_KEY_PAIR_ERROR", UPDATE_GLOBAL_GIT_CONFIG_ERROR: "UPDATE_GLOBAL_GIT_CONFIG_ERROR", diff --git a/app/client/src/pages/AppViewer/index.tsx b/app/client/src/pages/AppViewer/index.tsx index 7e043d1491db..2b38bdc51b58 100644 --- a/app/client/src/pages/AppViewer/index.tsx +++ b/app/client/src/pages/AppViewer/index.tsx @@ -25,7 +25,6 @@ import { } from "actions/metaActions"; import { editorInitializer } from "utils/EditorUtils"; import * as Sentry from "@sentry/react"; -import log from "loglevel"; import { getViewModePageList } from "selectors/editorSelectors"; import AppComments from "comments/AppComments/AppComments"; import AddCommentTourComponent from "comments/tour/AddCommentTourComponent"; @@ -91,7 +90,6 @@ class AppViewer extends Component< this.setState({ registered: true }); }); const { applicationId, pageId } = this.props.match.params; - log.debug({ applicationId, pageId }); if (applicationId) { this.props.initializeAppViewer(applicationId, pageId); } diff --git a/app/client/src/pages/Editor/gitSync/GitSyncModal.tsx b/app/client/src/pages/Editor/gitSync/GitSyncModal.tsx index 6b2a1f6cd733..cfb26c93eadd 100644 --- a/app/client/src/pages/Editor/gitSync/GitSyncModal.tsx +++ b/app/client/src/pages/Editor/gitSync/GitSyncModal.tsx @@ -16,9 +16,9 @@ import GitConnection from "./Tabs/GitConnection"; import Icon from "components/ads/Icon"; import { Colors } from "constants/Colors"; import { Classes } from "./constants"; -import { useIsGitConnected } from "./hooks"; import GitErrorPopup from "./components/GitErrorPopup"; +import { getCurrentAppGitMetaData } from "selectors/applicationSelectors"; const Container = styled.div` height: 600px; @@ -78,10 +78,12 @@ function GitSyncModal() { const activeTabIndex = useSelector(getActiveGitSyncModalTab); const setActiveTabIndex = (index: number) => dispatch(setIsGitSyncModalOpen({ isOpen: true, tab: index })); - const isGitConnected = useIsGitConnected(); + const gitMetaData = useSelector(getCurrentAppGitMetaData); + const remoteUrlInStore = gitMetaData?.remoteUrl; let initialTabIndex = 0; let menuOptions: Array<{ key: MENU_ITEM; title: string }> = []; - if (!isGitConnected) { + + if (!remoteUrlInStore) { menuOptions = [MENU_ITEMS_MAP.GIT_CONNECTION]; } else { menuOptions = allMenuOptions; @@ -106,7 +108,9 @@ function GitSyncModal() { : MENU_ITEMS_MAP.GIT_CONNECTION.key; const BodyComponent = ComponentsByTab[activeMenuItemKey]; - const showDeployTab = () => setActiveTabIndex(1); + const showDeployTab = () => { + setActiveTabIndex(1); + }; return ( <> <Dialog diff --git a/app/client/src/pages/Editor/gitSync/Tabs/Deploy.tsx b/app/client/src/pages/Editor/gitSync/Tabs/Deploy.tsx index 3d3309b02d6a..ae0c81ac7d15 100644 --- a/app/client/src/pages/Editor/gitSync/Tabs/Deploy.tsx +++ b/app/client/src/pages/Editor/gitSync/Tabs/Deploy.tsx @@ -86,7 +86,7 @@ const Commit = withTheme(function Commit({ theme }: { theme: Theme }) { if (isCommitSuccessful) { if (pushImmediately) { - commitButtonText = createMessage(PUSHED_SUCCESSFULLY); + commitButtonText = createMessage(COMMITTED_SUCCESSFULLY); } else { commitButtonText = createMessage(COMMITTED_SUCCESSFULLY); } diff --git a/app/client/src/pages/Editor/gitSync/Tabs/GitConnection.tsx b/app/client/src/pages/Editor/gitSync/Tabs/GitConnection.tsx index 3a7188022cb6..95d923ef6429 100644 --- a/app/client/src/pages/Editor/gitSync/Tabs/GitConnection.tsx +++ b/app/client/src/pages/Editor/gitSync/Tabs/GitConnection.tsx @@ -28,8 +28,13 @@ import { getCurrentAppGitMetaData } from "selectors/applicationSelectors"; import Toggle from "components/ads/Toggle"; import Text, { TextType } from "components/ads/Text"; import { getGlobalGitConfig } from "selectors/gitSyncSelectors"; -import { fetchGlobalGitConfigInit } from "actions/gitSyncActions"; +import { + fetchGlobalGitConfigInit, + fetchLocalGitConfigInit, +} from "actions/gitSyncActions"; import DirectDeploy from "../components/DirectDeploy"; +import TooltipComponent from "components/ads/Tooltip"; +// import { Classes } from "@blueprintjs/core"; export const UrlOptionContainer = styled.div` display: flex; @@ -138,6 +143,14 @@ const Container = styled.div` flex-direction: column; `; +// const TooltipWrapper = styled.div` +// &&&& .${Classes.POPOVER_WRAPPER} { +// display: flex; +// justify-content: center; +// align-items: center; +// } +// `; + const Section = styled.div``; // v1 only support SSH @@ -154,19 +167,47 @@ function GitConnection({ isImport, onSuccess }: Props) { useSelector(getCurrentAppGitMetaData) || ({} as any); const [remoteUrl, setRemoteUrl] = useState<string>(remoteUrlInStore); - // const [isValidRemoteUrl, setIsValidRemoteUrl] = useState(true); + + const isGitConnected = !!remoteUrlInStore; const currentUser = useSelector(getCurrentUser); const globalGitConfig = useSelector(getGlobalGitConfig); + const localGitConfig = useSelector(getGlobalGitConfig); + const dispatch = useDispatch(); + const getInitGitConfig = () => { + let initialAuthInfo = { + authorName: currentUser?.name || "", + authorEmail: currentUser?.email || "", + }; + + if (globalGitConfig.authorEmail || globalGitConfig.authorName) { + initialAuthInfo = { + authorName: globalGitConfig.authorName || "", + authorEmail: globalGitConfig.authorEmail || "", + }; + } + + if (localGitConfig.authorEmail || localGitConfig.authorName) { + initialAuthInfo = { + authorName: localGitConfig.authorName || "", + authorEmail: localGitConfig.authorEmail || "", + }; + } + // TODO: fetch local config + return initialAuthInfo; + }; + + const initialAuthorInfoRef = useRef(getInitGitConfig()); + const [authorInfo, setAuthorInfo] = useState<{ authorName: string; authorEmail: string; }>({ - authorName: currentUser?.name || "", - authorEmail: currentUser?.email || "", + authorName: initialAuthorInfoRef.current.authorName, + authorEmail: initialAuthorInfoRef.current.authorEmail, }); const [useGlobalConfig, setUseGlobalConfig] = useState(false); @@ -175,7 +216,7 @@ function GitConnection({ isImport, onSuccess }: Props) { const { deployKeyDocUrl, - failedGeneratingSSHKey, + // failedGeneratingSSHKey, fetchingSSHKeyPair, fetchSSHKeyPair, generateSSHKey, @@ -185,7 +226,7 @@ function GitConnection({ isImport, onSuccess }: Props) { const { connectToGit, - failedConnectingToGit, + // failedConnectingToGit, isConnectingToGit, } = useGitConnect({ onSuccess }); @@ -219,13 +260,19 @@ function GitConnection({ isImport, onSuccess }: Props) { const placeholderText = "Paste Your Git SSH URL"; - const gitConnectionRequest = () => { - connectToGit({ - remoteUrl, - gitProfile: authorInfo, - isImport, - isDefaultProfile: useGlobalConfig, - }); + const onSubmit = () => { + // Also check if isDefaultProfile switch is changed + // For this we will need to store `isDefaultProfile` in backend + if (isGitConnected && remoteUrl === remoteUrlInStore) { + // just update local config + } else { + connectToGit({ + remoteUrl, + gitProfile: authorInfo, + isImport, + isDefaultProfile: useGlobalConfig, + }); + } }; useEffect(() => { @@ -235,22 +282,13 @@ function GitConnection({ isImport, onSuccess }: Props) { } }, [SSHKeyPair]); - useEffect(() => { - if (failedGeneratingSSHKey || failedConnectingToGit) { - Toaster.show({ - text: "Something Went Wrong", - variant: Variant.danger, - }); - } - }, [failedGeneratingSSHKey, failedConnectingToGit]); - const remoteUrlChangeHandler = (value: string) => { setRemoteUrl(value); }; const remoteUrlIsValid = (value: string) => value.startsWith(HTTP_LITERAL); - const connectButtonDisabled = + const submitButtonDisabled = !authorInfo.authorEmail || !authorInfo.authorName; const isGlobalConfigDefined = !!( @@ -258,14 +296,21 @@ function GitConnection({ isImport, onSuccess }: Props) { ); useEffect(() => { - // when user has a git connected - if (remoteUrl && SSHKeyPair && !isGlobalConfigDefined && false) { - dispatch(fetchGlobalGitConfigInit()); - } - }, [isGlobalConfigDefined]); + dispatch(fetchGlobalGitConfigInit()); + dispatch(fetchLocalGitConfigInit()); + }, []); const showDirectDeployOption = !SSHKeyPair && !remoteUrl; + const toggleHandler = () => { + if (!useGlobalConfig) { + setAuthorInfo(globalGitConfig); + } else { + setAuthorInfo(localGitConfig); + } + setUseGlobalConfig(!useGlobalConfig); + }; + return ( <Container> <Section> @@ -291,14 +336,16 @@ function GitConnection({ isImport, onSuccess }: Props) { value={remoteUrl} /> </UrlInputContainer> - <Icon - color={Colors.DARK_GRAY} - hoverColor={Colors.GRAY2} - onClick={() => setRemoteUrl("")} - size="22px" - > - <LinkSvg /> - </Icon> + <TooltipComponent content="Unlink"> + <Icon + color={Colors.DARK_GRAY} + hoverColor={Colors.GRAY2} + onClick={() => setRemoteUrl("")} + size="22px" + > + <LinkSvg /> + </Icon> + </TooltipComponent> </UrlContainer> {!SSHKeyPair ? ( @@ -350,6 +397,10 @@ function GitConnection({ isImport, onSuccess }: Props) { <CopySvg /> </Icon> )} + {/* + <TooltipComponent content="Copy Key"> + </TooltipComponent> + */} </FlexRow> <span> {createMessage(DEPLOY_KEY_USAGE_GUIDE_MESSAGE)} @@ -371,10 +422,7 @@ function GitConnection({ isImport, onSuccess }: Props) { Use Default Config </Text> <Space horizontal size={2} /> - <Toggle - onToggle={() => setUseGlobalConfig(!useGlobalConfig)} - value={useGlobalConfig} - /> + <Toggle onToggle={toggleHandler} value={useGlobalConfig} /> </FlexRow> </> ) : null} @@ -388,12 +436,12 @@ function GitConnection({ isImport, onSuccess }: Props) { /> <ButtonContainer topMargin={11}> <Button - disabled={connectButtonDisabled} + disabled={submitButtonDisabled} isLoading={isConnectingToGit} - onClick={gitConnectionRequest} + onClick={onSubmit} size={Size.large} tag="button" - text="CONNECT" + text={isGitConnected ? "UPDATE" : "CONNECT"} /> {/* <Text className="" type={TextType.P3}> // Show message when user config if modified diff --git a/app/client/src/pages/Editor/gitSync/components/UserGitProfileSettings/index.tsx b/app/client/src/pages/Editor/gitSync/components/UserGitProfileSettings/index.tsx index 882f8acc7db9..414b610da284 100644 --- a/app/client/src/pages/Editor/gitSync/components/UserGitProfileSettings/index.tsx +++ b/app/client/src/pages/Editor/gitSync/components/UserGitProfileSettings/index.tsx @@ -7,7 +7,7 @@ import { AUTHOR_EMAIL, } from "constants/messages"; import styled from "styled-components"; -import TextInput from "components/ads/TextInput"; +import TextInput, { emailValidator } from "components/ads/TextInput"; import { Classes as GitSyncClasses } from "../../constants"; const LabelContainer = styled.div` @@ -112,12 +112,13 @@ function UserGitProfileSettings({ <InputContainer> <TextInput dataType="email" + defaultValue={authorInfo.authorEmail} disabled={disabled} fill onChange={(value) => setAuthorState(AUTHOR_INFO_LABEL.EMAIL, value) } - value={authorInfo.authorEmail} + validator={emailValidator} /> </InputContainer> </> diff --git a/app/client/src/pages/Editor/gitSync/hooks.ts b/app/client/src/pages/Editor/gitSync/hooks.ts index dee21fd24a91..de5da9f836d4 100644 --- a/app/client/src/pages/Editor/gitSync/hooks.ts +++ b/app/client/src/pages/Editor/gitSync/hooks.ts @@ -3,10 +3,7 @@ import { useState, useCallback, useEffect } from "react"; import { generateSSHKeyPair, getSSHKeyPair } from "actions/applicationActions"; import { connectToGitInit } from "actions/gitSyncActions"; import { ConnectToGitPayload } from "api/GitSyncAPI"; -import { - getCurrentAppGitMetaData, - getCurrentApplication, -} from "selectors/applicationSelectors"; +import { getCurrentApplication } from "selectors/applicationSelectors"; import { DOCS_BASE_URL } from "constants/ThirdPartyConstants"; export const useSSHKeyPair = () => { @@ -84,7 +81,6 @@ export const useGitConnect = ({ onSuccess }: { onSuccess: () => void }) => { const onGitConnectSuccess = useCallback(() => { setIsConnectingToGit(false); - onSuccess(); }, [setIsConnectingToGit]); @@ -116,10 +112,3 @@ export const useGitConnect = ({ onSuccess }: { onSuccess: () => void }) => { connectToGit, }; }; - -export const useIsGitConnected = () => { - // if remoteUrl is stored in gitApplicationMetaData it means application was connected to git successfully - const gitMetaData = useSelector(getCurrentAppGitMetaData); - const remoteUrlInStore = gitMetaData?.remoteUrl; - return !!remoteUrlInStore; -}; diff --git a/app/client/src/reducers/uiReducers/applicationsReducer.tsx b/app/client/src/reducers/uiReducers/applicationsReducer.tsx index f48a8893dd23..7c61c1184c0b 100644 --- a/app/client/src/reducers/uiReducers/applicationsReducer.tsx +++ b/app/client/src/reducers/uiReducers/applicationsReducer.tsx @@ -399,7 +399,7 @@ const applicationsReducer = createReducer(initialState, { ...state, currentApplication: { ...state.currentApplication, - gitApplicationMetaData: action.payload.gitApplicationMetaData, + gitApplicationMetadata: action.payload.gitApplicationMetadata, }, }; }, diff --git a/app/client/src/reducers/uiReducers/gitSyncReducer.ts b/app/client/src/reducers/uiReducers/gitSyncReducer.ts index b7b00001e19f..b2e7ea3aae79 100644 --- a/app/client/src/reducers/uiReducers/gitSyncReducer.ts +++ b/app/client/src/reducers/uiReducers/gitSyncReducer.ts @@ -20,6 +20,7 @@ const initialState: GitSyncReducerState = { `, isImportAppViaGitModalOpen: false, globalGitConfig: { authorEmail: "", authorName: "" }, + localGitConfig: { authorEmail: "", authorName: "" }, }; const gitSyncReducer = createReducer(initialState, { @@ -91,7 +92,9 @@ const gitSyncReducer = createReducer(initialState, { ...state, isFetchingGitConfig: true, }), - [ReduxActionTypes.UPDATE_GIT_CONFIG_INIT]: (state: GitSyncReducerState) => ({ + [ReduxActionTypes.UPDATE_GLOBAL_GIT_CONFIG_INIT]: ( + state: GitSyncReducerState, + ) => ({ ...state, isFetchingGitConfig: true, }), @@ -103,7 +106,7 @@ const gitSyncReducer = createReducer(initialState, { globalGitConfig: action.payload, isFetchingGitConfig: false, }), - [ReduxActionTypes.UPDATE_GIT_CONFIG_SUCCESS]: ( + [ReduxActionTypes.UPDATE_GLOBAL_GIT_CONFIG_SUCCESS]: ( state: GitSyncReducerState, action: ReduxAction<GitConfig>, ) => ({ @@ -123,6 +126,47 @@ const gitSyncReducer = createReducer(initialState, { ...state, isFetchingGitConfig: false, }), + + [ReduxActionTypes.FETCH_LOCAL_GIT_CONFIG_INIT]: ( + state: GitSyncReducerState, + ) => ({ + ...state, + isFetchingLocalGitConfig: true, + }), + [ReduxActionTypes.UPDATE_LOCAL_GIT_CONFIG_INIT]: ( + state: GitSyncReducerState, + ) => ({ + ...state, + isFetchingLocalGitConfig: true, + }), + [ReduxActionTypes.FETCH_LOCAL_GIT_CONFIG_SUCCESS]: ( + state: GitSyncReducerState, + action: ReduxAction<GitConfig>, + ) => ({ + ...state, + localGitConfig: action.payload, + isFetchingLocalGitConfig: false, + }), + [ReduxActionTypes.UPDATE_LOCAL_GIT_CONFIG_SUCCESS]: ( + state: GitSyncReducerState, + action: ReduxAction<GitConfig>, + ) => ({ + ...state, + localGitConfig: action.payload, + isFetchingLocalGitConfig: false, + }), + [ReduxActionErrorTypes.UPDATE_LOCAL_GIT_CONFIG_ERROR]: ( + state: GitSyncReducerState, + ) => ({ + ...state, + isFetchingLocalGitConfig: false, + }), + [ReduxActionErrorTypes.FETCH_LOCAL_GIT_CONFIG_ERROR]: ( + state: GitSyncReducerState, + ) => ({ + ...state, + isFetchingLocalGitConfig: false, + }), }); export type GitSyncReducerState = { @@ -138,6 +182,9 @@ export type GitSyncReducerState = { gitError?: string; globalGitConfig: GitConfig; isFetchingGitConfig?: boolean; + + isFetchingLocalGitConfig?: boolean; + localGitConfig: GitConfig; }; export default gitSyncReducer; diff --git a/app/client/src/sagas/GitSyncSagas.ts b/app/client/src/sagas/GitSyncSagas.ts index 190dbdd64da5..c8a2b96654cc 100644 --- a/app/client/src/sagas/GitSyncSagas.ts +++ b/app/client/src/sagas/GitSyncSagas.ts @@ -13,6 +13,8 @@ import { fetchGlobalGitConfigSuccess, updateGlobalGitConfigSuccess, pushToRepoSuccess, + fetchLocalGitConfigSuccess, + updateLocalGitConfigSuccess, } from "actions/gitSyncActions"; import { connectToGitSuccess, @@ -84,7 +86,7 @@ function* connectToGitSaga(action: ConnectToGitReduxAction) { function* fetchGlobalGitConfig() { try { const response: ApiResponse = yield GitSyncAPI.getGlobalConfig(); - const isValidResponse: boolean = yield validateResponse(response); + const isValidResponse: boolean = yield validateResponse(response, false); if (isValidResponse) { yield put(fetchGlobalGitConfigSuccess(response.data)); @@ -119,6 +121,49 @@ function* updateGlobalGitConfig(action: ReduxAction<GitConfig>) { } } +function* fetchLocalGitConfig() { + try { + const applicationId: string = yield select(getCurrentApplicationId); + const response: ApiResponse = yield GitSyncAPI.getLocalConfig( + applicationId, + ); + const isValidResponse: boolean = yield validateResponse(response, false); + + if (isValidResponse) { + yield put(fetchLocalGitConfigSuccess(response.data)); + } + } catch (error) { + yield put({ + type: ReduxActionErrorTypes.FETCH_LOCAL_GIT_CONFIG_ERROR, + payload: { error, logToSentry: true, show: false }, + }); + } +} + +function* updateLocalGitConfig(action: ReduxAction<GitConfig>) { + try { + const applicationId: string = yield select(getCurrentApplicationId); + const response: ApiResponse = yield GitSyncAPI.setLocalConfig( + action.payload, + applicationId, + ); + const isValidResponse: boolean = yield validateResponse(response); + + if (isValidResponse) { + yield put(updateLocalGitConfigSuccess(response.data)); + Toaster.show({ + text: createMessage(GIT_USER_UPDATED_SUCCESSFULLY), + variant: Variant.success, + }); + } + } catch (error) { + yield put({ + type: ReduxActionErrorTypes.UPDATE_LOCAL_GIT_CONFIG_ERROR, + payload: { error, logToSentry: true }, + }); + } +} + function* pushToGitRepoSaga() { try { const applicationId: string = yield select(getCurrentApplicationId); @@ -151,6 +196,17 @@ export default function* gitSyncSagas() { ReduxActionTypes.FETCH_GLOBAL_GIT_CONFIG_INIT, fetchGlobalGitConfig, ), - takeLatest(ReduxActionTypes.UPDATE_GIT_CONFIG_INIT, updateGlobalGitConfig), + takeLatest( + ReduxActionTypes.UPDATE_GLOBAL_GIT_CONFIG_INIT, + updateGlobalGitConfig, + ), + takeLatest( + ReduxActionTypes.FETCH_LOCAL_GIT_CONFIG_INIT, + fetchLocalGitConfig, + ), + takeLatest( + ReduxActionTypes.UPDATE_LOCAL_GIT_CONFIG_INIT, + updateLocalGitConfig, + ), ]); } diff --git a/app/client/src/selectors/gitSyncSelectors.tsx b/app/client/src/selectors/gitSyncSelectors.tsx index 3ab0d1cd29cc..250c7cc25821 100644 --- a/app/client/src/selectors/gitSyncSelectors.tsx +++ b/app/client/src/selectors/gitSyncSelectors.tsx @@ -47,5 +47,10 @@ export const getOrganizationIdForImport = (state: AppState) => export const getGlobalGitConfig = (state: AppState) => state.ui.gitSync.globalGitConfig; +export const getLocalGitConfig = createSelector( + getGitSyncState, + (gitSync) => gitSync.localGitConfig, +); + export const getIsFetchingGlobalGitConfig = (state: AppState) => state.ui.gitSync.isFetchingGitConfig;
d38e4b0b38cbbaee87a27e8fef710cfb25974593
2024-04-29 18:30:15
Ashok Kumar M
fix: WDS widgets not showing up in Air gapped instances. (#33035)
false
WDS widgets not showing up in Air gapped instances. (#33035)
fix
diff --git a/app/client/src/WidgetProvider/factory/index.tsx b/app/client/src/WidgetProvider/factory/index.tsx index 346a03e0a566..04facdf369e5 100644 --- a/app/client/src/WidgetProvider/factory/index.tsx +++ b/app/client/src/WidgetProvider/factory/index.tsx @@ -80,7 +80,7 @@ class WidgetFactory { private static configureWidget(widget: typeof BaseWidget) { const config = widget.getConfig(); - + const { IconCmp } = widget.getMethods(); const features = widget.getFeatures(); let enhancedFeatures: Record<string, unknown> = {}; @@ -103,7 +103,7 @@ class WidgetFactory { ...enhancedFeatures, searchTags: config.searchTags, tags: config.tags, - hideCard: !!config.hideCard || !config.iconSVG, + hideCard: !!config.hideCard || !(config.iconSVG || IconCmp), isDeprecated: !!config.isDeprecated, replacement: config.replacement, displayName: config.name, diff --git a/app/client/src/selectors/editorSelectors.tsx b/app/client/src/selectors/editorSelectors.tsx index bd894a0a50db..ec497749cf32 100644 --- a/app/client/src/selectors/editorSelectors.tsx +++ b/app/client/src/selectors/editorSelectors.tsx @@ -309,25 +309,20 @@ export const getWidgetCards = createSelector( getIsAnvilLayout, (isAutoLayout, isAnvilLayout) => { const widgetConfigs = WidgetFactory.getConfigs(); - - const cards = Object.values(widgetConfigs).filter((config) => { - // if anvil is not enabled, hide all wds widgets - if ( - Object.values(WDS_V2_WIDGET_MAP).includes(config.type) && - !isAnvilLayout - ) { - return false; + const widgetConfigsArray = Object.values(widgetConfigs); + const layoutSystemBasesWidgets = widgetConfigsArray.filter((config) => { + const isAnvilWidget = Object.values(WDS_V2_WIDGET_MAP).includes( + config.type, + ); + if (isAnvilLayout) { + return isAnvilWidget; } - + return !isAnvilWidget; + }); + const cards = layoutSystemBasesWidgets.filter((config) => { if (isAirgapped()) { return config.widgetName !== "Map" && !config.hideCard; } - - // if anvil is enabled, only show the wds widgets - if (isAnvilLayout) { - return Object.values(WDS_V2_WIDGET_MAP).includes(config.type); - } - return !config.hideCard; });
c173086868436d2ee0f4432dad72c73bc5aef9a2
2023-05-11 13:16:38
Mohammad Hammad
fix: #23026, Changed type correctly to Re-enter password (#23145)
false
#23026, Changed type correctly to Re-enter password (#23145)
fix
diff --git a/app/client/src/pages/setup/DetailsForm.tsx b/app/client/src/pages/setup/DetailsForm.tsx index 1472115e9d01..d518704cb139 100644 --- a/app/client/src/pages/setup/DetailsForm.tsx +++ b/app/client/src/pages/setup/DetailsForm.tsx @@ -98,7 +98,7 @@ export default function DetailsForm( <FormTextField data-testid="verifyPassword" name="verifyPassword" - placeholder="Type correctly" + placeholder="Re-enter Password" type="password" /> </StyledFormGroup>
379596d5fa208a279dd5de0c8e5e92ee4a31965c
2024-06-26 16:24:53
Rishabh Rathod
chore: Add KeyPairAuth as snowflake auth type document (#34466)
false
Add KeyPairAuth as snowflake auth type document (#34466)
chore
diff --git a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/constants/Authentication.java b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/constants/Authentication.java index 28c2b92a2b1a..17abf29c1ed8 100644 --- a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/constants/Authentication.java +++ b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/constants/Authentication.java @@ -10,6 +10,7 @@ public class Authentication { public static final String API_KEY_AUTH_TYPE_QUERY_PARAMS = "queryParams"; public static final String API_KEY_AUTH_TYPE_HEADER = "header"; public static final String BEARER_TOKEN = "bearerToken"; + public static final String SNOWFLAKE_KEY_PAIR_AUTH = "snowflakeKeyPairAuth"; // Request parameter names public static final String CLIENT_ID = "client_id"; diff --git a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/AuthenticationDTO.java b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/AuthenticationDTO.java index f42a01686cdb..862f85e9c925 100644 --- a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/AuthenticationDTO.java +++ b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/AuthenticationDTO.java @@ -23,7 +23,8 @@ @JsonSubTypes.Type(value = OAuth2.class, name = Authentication.OAUTH2), @JsonSubTypes.Type(value = BasicAuth.class, name = Authentication.BASIC), @JsonSubTypes.Type(value = ApiKeyAuth.class, name = Authentication.API_KEY), - @JsonSubTypes.Type(value = BearerTokenAuth.class, name = Authentication.BEARER_TOKEN) + @JsonSubTypes.Type(value = BearerTokenAuth.class, name = Authentication.BEARER_TOKEN), + @JsonSubTypes.Type(value = KeyPairAuth.class, name = Authentication.SNOWFLAKE_KEY_PAIR_AUTH) }) @FieldNameConstants public class AuthenticationDTO implements AppsmithDomain { 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 new file mode 100644 index 000000000000..2f610961d6e0 --- /dev/null +++ b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/KeyPairAuth.java @@ -0,0 +1,33 @@ +package com.appsmith.external.models; + +import com.appsmith.external.annotations.documenttype.DocumentType; +import com.appsmith.external.annotations.encryption.Encrypted; +import com.appsmith.external.constants.Authentication; +import com.appsmith.external.views.FromRequest; +import com.appsmith.external.views.Views; +import com.fasterxml.jackson.annotation.JsonView; +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.Setter; +import lombok.ToString; + +@Builder +@Getter +@Setter +@ToString +@NoArgsConstructor +@AllArgsConstructor +@DocumentType(Authentication.SNOWFLAKE_KEY_PAIR_AUTH) +public class KeyPairAuth extends AuthenticationDTO { + + @JsonView({Views.Public.class, FromRequest.class}) + String username; + + @JsonView({Views.Public.class, FromRequest.class}) + UploadedFile privateKey; + + @JsonView({Views.Public.class, FromRequest.class}) + @Encrypted String passphrase; +}
ef89f3fee41121815e37d5b6f4ad09b9bfc88a36
2022-03-04 12:15:50
Aswath K
feat: Make icon selector keyboard accessible (#10460)
false
Make icon selector keyboard accessible (#10460)
feat
diff --git a/app/client/src/components/propertyControls/IconSelectControl.test.tsx b/app/client/src/components/propertyControls/IconSelectControl.test.tsx new file mode 100644 index 000000000000..7b0810ddaaf4 --- /dev/null +++ b/app/client/src/components/propertyControls/IconSelectControl.test.tsx @@ -0,0 +1,244 @@ +import React from "react"; +import "@testing-library/jest-dom"; +import { + render, + screen, + waitFor, + waitForElementToBeRemoved, +} from "@testing-library/react"; +import IconSelectControl from "./IconSelectControl"; +import userEvent from "@testing-library/user-event"; +import { noop } from "lodash"; +import { EditorTheme } from "components/editorComponents/CodeEditor/EditorConfig"; + +describe("<IconSelectControl /> - Keyboard navigation", () => { + const getTestComponent = ( + onPropertyChange: ( + propertyName: string, + propertyValue: string, + ) => void = noop, + ) => ( + <IconSelectControl + additionalDynamicData={{ + dummy: { + dummy: 1, + }, + }} + controlType="add" + deleteProperties={noop} + evaluatedValue={undefined} + isBindProperty={false} + isTriggerProperty={false} + label="Icon" + onPropertyChange={onPropertyChange} + openNextPanel={noop} + parentPropertyName="iconName" + parentPropertyValue="add" + propertyName="iconName" + theme={EditorTheme.LIGHT} + widgetProperties={undefined} + /> + ); + + it("Pressing tab should focus the component", () => { + render(getTestComponent()); + userEvent.tab(); + expect(screen.getByRole("button")).toHaveFocus(); + }); + + it.each(["{Enter}", " ", "{ArrowDown}", "{ArrowUp}"])( + "Pressing '%s' should open the icon selector", + async (key) => { + render(getTestComponent()); + userEvent.tab(); + expect(screen.queryByRole("list")).toBeNull(); + userEvent.keyboard(key); + expect(screen.queryByRole("list")).toBeInTheDocument(); + + // Makes sure search bar is having focus + await waitFor(() => { + expect(screen.queryByRole("textbox")).toHaveFocus(); + }); + }, + ); + + it("Pressing '{Escape}' should close the icon selector", async () => { + render(getTestComponent()); + userEvent.tab(); + expect(screen.queryByRole("list")).toBeNull(); + userEvent.keyboard("{Enter}"); + expect(screen.queryByRole("list")).toBeInTheDocument(); + userEvent.keyboard("{Escape}"); + await waitForElementToBeRemoved(screen.getAllByRole("list")); + }); + + it("Pressing '{ArrowDown}' while search is in focus should remove the focus", async () => { + render(getTestComponent()); + userEvent.tab(); + userEvent.keyboard("{Enter}"); + expect(screen.queryByRole("list")).toBeInTheDocument(); + await waitFor(() => { + expect(screen.queryByRole("textbox")).toHaveFocus(); + }); + userEvent.keyboard("{ArrowDown}"); + expect(screen.queryByRole("textbox")).not.toHaveFocus(); + }); + + it("Pressing '{Shift} + {ArrowUp}' while search is not in focus should focus search box", async () => { + render(getTestComponent()); + userEvent.tab(); + userEvent.keyboard("{Enter}"); + expect(screen.queryByRole("list")).toBeInTheDocument(); + await waitFor(() => { + expect(screen.queryByRole("textbox")).toHaveFocus(); + }); + userEvent.keyboard("{ArrowDown}"); + expect(screen.queryByRole("textbox")).not.toHaveFocus(); + userEvent.keyboard("{Shift}{ArrowUp}"); + await waitFor(() => { + expect(screen.queryByRole("textbox")).toHaveFocus(); + }); + }); + + /* + Icon Arrangement + + (none) add add-column-left add-column-right + add-row-bottom add-row-top add-to-artifact add-to-folder + airplane align-center align-justify align-left + */ + it("Pressing '{ArrowDown}' should navigate the icon selection downwards", async () => { + render(getTestComponent()); + userEvent.tab(); + userEvent.keyboard("{Enter}"); + await waitFor(() => { + expect(screen.queryByRole("textbox")).toHaveFocus(); + }); + expect(document.querySelector("a.bp3-active")?.children[0]).toHaveClass( + "bp3-icon-(none)", + ); + // used to shift the focus from search + userEvent.keyboard("{ArrowDown}"); + + userEvent.keyboard("{ArrowDown}"); + expect(document.querySelector("a.bp3-active")?.children[0]).toHaveClass( + "bp3-icon-add-row-bottom", + ); + }); + + it("Pressing '{ArrowUp}' should navigate the icon selection upwards", async () => { + render(getTestComponent()); + userEvent.tab(); + userEvent.keyboard("{Enter}"); + await waitFor(() => { + expect(screen.queryByRole("textbox")).toHaveFocus(); + }); + expect(document.querySelector("a.bp3-active")?.children[0]).toHaveClass( + "bp3-icon-(none)", + ); + // used to shift the focus from search + userEvent.keyboard("{ArrowDown}"); + + userEvent.keyboard("{ArrowDown}"); + userEvent.keyboard("{ArrowDown}"); + userEvent.keyboard("{ArrowDown}"); + expect(document.querySelector("a.bp3-active")?.children[0]).toHaveClass( + "bp3-icon-align-right", + ); + + userEvent.keyboard("{ArrowUp}"); + expect(document.querySelector("a.bp3-active")?.children[0]).toHaveClass( + "bp3-icon-airplane", + ); + }); + + it("Pressing '{ArrowRight}' should navigate the icon selection towards right", async () => { + render(getTestComponent()); + userEvent.tab(); + userEvent.keyboard("{Enter}"); + await waitFor(() => { + expect(screen.queryByRole("textbox")).toHaveFocus(); + }); + expect(document.querySelector("a.bp3-active")?.children[0]).toHaveClass( + "bp3-icon-(none)", + ); + // used to shift the focus from search + userEvent.keyboard("{ArrowDown}"); + + userEvent.keyboard("{ArrowRight}"); + expect(document.querySelector("a.bp3-active")?.children[0]).toHaveClass( + "bp3-icon-add", + ); + }); + + it("Pressing '{ArrowLeft}' should navigate the icon selection towards left", async () => { + render(getTestComponent()); + userEvent.tab(); + userEvent.keyboard("{Enter}"); + await waitFor(() => { + expect(screen.queryByRole("textbox")).toHaveFocus(); + }); + expect(document.querySelector("a.bp3-active")?.children[0]).toHaveClass( + "bp3-icon-(none)", + ); + // used to shift the focus from search + userEvent.keyboard("{ArrowDown}"); + + userEvent.keyboard("{ArrowRight}"); + userEvent.keyboard("{ArrowRight}"); + userEvent.keyboard("{ArrowRight}"); + expect(document.querySelector("a.bp3-active")?.children[0]).toHaveClass( + "bp3-icon-add-column-right", + ); + + userEvent.keyboard("{ArrowLeft}"); + expect(document.querySelector("a.bp3-active")?.children[0]).toHaveClass( + "bp3-icon-add-column-left", + ); + }); + + it("Pressing '{Enter}' or ' ' should select the icon", async () => { + const handleOnSelect = jest.fn(); + render(getTestComponent(handleOnSelect)); + userEvent.tab(); + expect(screen.queryByRole("button")?.textContent).toEqual( + "(none)caret-down", + ); + userEvent.keyboard("{Enter}"); + await waitFor(() => { + expect(screen.queryByRole("textbox")).toHaveFocus(); + }); + expect(document.querySelector("a.bp3-active")?.children[0]).toHaveClass( + "bp3-icon-(none)", + ); + // used to shift the focus from search + userEvent.keyboard("{ArrowDown}"); + + userEvent.keyboard("{ArrowDown}"); + userEvent.keyboard("{ArrowRight}"); + expect(document.querySelector("a.bp3-active")?.children[0]).toHaveClass( + "bp3-icon-add-row-top", + ); + userEvent.keyboard(" "); + expect(handleOnSelect).toHaveBeenCalledTimes(1); + expect(handleOnSelect).toHaveBeenLastCalledWith("iconName", "add-row-top"); + await waitForElementToBeRemoved(screen.getByRole("list")); + + userEvent.keyboard("{Enter}"); + expect(screen.queryByRole("list")).toBeInTheDocument(); + await waitFor(() => { + expect(screen.queryByRole("textbox")).toHaveFocus(); + }); + expect(document.querySelector("a.bp3-active")?.children[0]).toHaveClass( + "bp3-icon-add-row-top", + ); + userEvent.keyboard("{ArrowDown}"); + userEvent.keyboard("{ArrowRight}"); + userEvent.keyboard(" "); + expect(handleOnSelect).toHaveBeenCalledTimes(2); + expect(handleOnSelect).toHaveBeenLastCalledWith( + "iconName", + "add-to-artifact", + ); + }); +}); diff --git a/app/client/src/components/propertyControls/IconSelectControl.tsx b/app/client/src/components/propertyControls/IconSelectControl.tsx index 3761b5becdf4..98b97be61592 100644 --- a/app/client/src/components/propertyControls/IconSelectControl.tsx +++ b/app/client/src/components/propertyControls/IconSelectControl.tsx @@ -1,13 +1,19 @@ import * as React from "react"; import styled, { createGlobalStyle } from "styled-components"; -import { Alignment, Button, Classes, Menu, MenuItem } from "@blueprintjs/core"; +import { Alignment, Button, Classes, MenuItem } from "@blueprintjs/core"; import { IconName, IconNames } from "@blueprintjs/icons"; import { ItemListRenderer, ItemRenderer, Select } from "@blueprintjs/select"; +import { + GridListProps, + VirtuosoGrid, + VirtuosoGridHandle, +} from "react-virtuoso"; import BaseControl, { ControlProps } from "./BaseControl"; import TooltipComponent from "components/ads/Tooltip"; import { Colors } from "constants/Colors"; import { replayHighlightClass } from "globalStyles/portals"; +import _ from "lodash"; const IconSelectContainerStyles = createGlobalStyle<{ targetWidth: number | undefined; @@ -37,7 +43,7 @@ const StyledButton = styled(Button)` } `; -const StyledMenu = styled(Menu)` +const StyledMenu = styled.ul<GridListProps>` display: grid; grid-template-columns: repeat(4, 1fr); grid-auto-rows: minmax(50px, auto); @@ -54,6 +60,9 @@ const StyledMenu = styled(Menu)` -webkit-box-shadow: inset 0 0 6px rgba(0, 0, 0, 0.3); background-color: #939090; } + & li { + list-style: none; + } `; const StyledMenuItem = styled(MenuItem)` @@ -82,7 +91,9 @@ export interface IconSelectControlProps extends ControlProps { } export interface IconSelectControlState { + activeIcon: IconType; popoverTargetWidth: number | undefined; + isOpen: boolean; } const NONE = "(none)"; @@ -99,14 +110,44 @@ class IconSelectControl extends BaseControl< IconSelectControlState > { private iconSelectTargetRef: React.RefObject<HTMLButtonElement>; + private virtuosoRef: React.RefObject<VirtuosoGridHandle>; + private initialItemIndex: number; + private filteredItems: Array<IconType>; + private searchInput: React.RefObject<HTMLInputElement>; private timer?: number; constructor(props: IconSelectControlProps) { super(props); this.iconSelectTargetRef = React.createRef(); - this.state = { popoverTargetWidth: 0 }; + this.virtuosoRef = React.createRef(); + this.searchInput = React.createRef(); + this.initialItemIndex = 0; + this.filteredItems = []; + this.state = { + activeIcon: props.propertyValue ?? NONE, + popoverTargetWidth: 0, + isOpen: false, + }; } + // debouncedSetState is used to fix the following bug: + // https://github.com/appsmithorg/appsmith/pull/10460#issuecomment-1022895174 + private debouncedSetState = _.debounce( + (obj: any, callback?: () => void) => { + this.setState((prevState: IconSelectControlState) => { + return { + ...prevState, + ...obj, + }; + }, callback); + }, + 300, + { + leading: true, + trailing: false, + }, + ); + componentDidMount() { this.timer = setTimeout(() => { const iconSelectTargetElement = this.iconSelectTargetRef.current; @@ -118,30 +159,49 @@ class IconSelectControl extends BaseControl< }; }); }, 0); + // keydown event is attached to body so that it will not interfere with the keydown handler in GlobalHotKeys + document.body.addEventListener("keydown", this.handleKeydown); } componentWillUnmount() { if (this.timer) { clearTimeout(this.timer); } + document.body.removeEventListener("keydown", this.handleKeydown); } + private handleQueryChange = _.debounce(() => { + if (this.filteredItems.length === 2) + this.setState({ activeIcon: this.filteredItems[1] }); + }, 50); + public render() { const { defaultIconName, propertyValue: iconName } = this.props; - const { popoverTargetWidth } = this.state; + const { activeIcon, popoverTargetWidth } = this.state; return ( <> <IconSelectContainerStyles targetWidth={popoverTargetWidth} /> <TypedSelect - activeItem={iconName || defaultIconName || NONE} + activeItem={activeIcon || defaultIconName || NONE} className="icon-select-container" + inputProps={{ + inputRef: this.searchInput, + }} itemListRenderer={this.renderMenu} itemPredicate={this.filterIconName} itemRenderer={this.renderIconItem} items={ICON_NAMES} - noResults={<MenuItem disabled text="No results" />} onItemSelect={this.handleIconChange} - popoverProps={{ minimal: true }} + onQueryChange={this.handleQueryChange} + popoverProps={{ + enforceFocus: false, + minimal: true, + isOpen: this.state.isOpen, + onInteraction: (state) => { + if (this.state.isOpen !== state) + this.debouncedSetState({ isOpen: state }); + }, + }} > <StyledButton alignText={Alignment.LEFT} @@ -151,6 +211,7 @@ class IconSelectControl extends BaseControl< elementRef={this.iconSelectTargetRef} fill icon={iconName || defaultIconName} + onClick={this.handleButtonClick} rightIcon="caret-down" text={iconName || defaultIconName || NONE} /> @@ -159,14 +220,142 @@ class IconSelectControl extends BaseControl< ); } + private setActiveIcon(iconIndex: number) { + this.setState( + { + activeIcon: this.filteredItems[iconIndex], + }, + () => { + if (this.virtuosoRef.current) { + this.virtuosoRef.current.scrollToIndex(iconIndex); + } + }, + ); + } + + private handleKeydown = (e: KeyboardEvent) => { + if (this.state.isOpen) { + switch (e.key) { + case "Tab": + e.preventDefault(); + this.setState({ + isOpen: false, + activeIcon: this.props.propertyValue ?? NONE, + }); + break; + case "ArrowDown": + case "Down": { + if (document.activeElement === this.searchInput.current) { + (document.activeElement as HTMLElement).blur(); + if (this.initialItemIndex < 0) this.initialItemIndex = -4; + else break; + } + const nextIndex = this.initialItemIndex + 4; + if (nextIndex < this.filteredItems.length) + this.setActiveIcon(nextIndex); + e.preventDefault(); + break; + } + case "ArrowUp": + case "Up": { + if (document.activeElement === this.searchInput.current) { + break; + } else if ( + (e.shiftKey || + (this.initialItemIndex >= 0 && this.initialItemIndex < 4)) && + this.searchInput.current + ) { + this.searchInput.current.focus(); + break; + } + const nextIndex = this.initialItemIndex - 4; + if (nextIndex >= 0) this.setActiveIcon(nextIndex); + e.preventDefault(); + break; + } + case "ArrowRight": + case "Right": { + if (document.activeElement === this.searchInput.current) { + break; + } + const nextIndex = this.initialItemIndex + 1; + if (nextIndex < this.filteredItems.length) + this.setActiveIcon(nextIndex); + e.preventDefault(); + break; + } + case "ArrowLeft": + case "Left": { + if (document.activeElement === this.searchInput.current) { + break; + } + const nextIndex = this.initialItemIndex - 1; + if (nextIndex >= 0) this.setActiveIcon(nextIndex); + e.preventDefault(); + break; + } + case " ": + case "Enter": { + if ( + this.searchInput.current === document.activeElement && + this.filteredItems.length !== 2 + ) + break; + this.handleIconChange(this.filteredItems[this.initialItemIndex]); + this.debouncedSetState({ isOpen: false }); + e.preventDefault(); + e.stopPropagation(); + break; + } + case "Escape": { + this.setState({ + isOpen: false, + activeIcon: this.props.propertyValue ?? NONE, + }); + e.stopPropagation(); + } + } + } else if ( + this.iconSelectTargetRef.current === document.activeElement && + (e.key === "ArrowUp" || + e.key === "Up" || + e.key === "ArrowDown" || + e.key === "Down") + ) { + this.debouncedSetState({ isOpen: true }, this.handleButtonClick); + } + }; + + private handleButtonClick = () => { + setTimeout(() => { + if (this.virtuosoRef.current) { + this.virtuosoRef.current.scrollToIndex(this.initialItemIndex); + } + }, 0); + }; + private renderMenu: ItemListRenderer<IconType> = ({ - items, - itemsParentRef, + activeItem, + filteredItems, renderItem, }) => { - const renderedItems = items.map(renderItem).filter((item) => item != null); + this.filteredItems = filteredItems; + this.initialItemIndex = filteredItems.findIndex((x) => x === activeItem); - return <StyledMenu ulRef={itemsParentRef}>{renderedItems}</StyledMenu>; + return ( + <VirtuosoGrid + components={{ + List: StyledMenu, + }} + computeItemKey={(index) => filteredItems[index]} + initialItemCount={16} + itemContent={(index) => renderItem(filteredItems[index], index)} + ref={this.virtuosoRef} + style={{ height: "165px" }} + tabIndex={-1} + totalCount={filteredItems.length} + /> + ); }; private renderIconItem: ItemRenderer<IconName | typeof NONE> = ( @@ -184,6 +373,7 @@ class IconSelectControl extends BaseControl< key={icon} onClick={handleClick} text={icon === NONE ? NONE : undefined} + textClassName={icon === NONE ? "bp3-icon-(none)" : ""} /> </TooltipComponent> ); @@ -199,11 +389,13 @@ class IconSelectControl extends BaseControl< return iconName.toLowerCase().indexOf(query.toLowerCase()) >= 0; }; - private handleIconChange = (icon: IconType) => + private handleIconChange = (icon: IconType) => { + this.setState({ activeIcon: icon }); this.updateProperty( this.props.propertyName, icon === NONE ? undefined : icon, ); + }; static getControlType() { return "ICON_SELECT";
82489a3ecdf24ff308f954ee52f807e134ca6fdf
2022-12-16 12:07:40
Anagh Hegde
fix: Add error message for protected branch (#18737)
false
Add error message for protected branch (#18737)
fix
diff --git a/app/client/src/actions/gitSyncActions.ts b/app/client/src/actions/gitSyncActions.ts index 8f7e3bcd34ac..6d8143978bfb 100644 --- a/app/client/src/actions/gitSyncActions.ts +++ b/app/client/src/actions/gitSyncActions.ts @@ -42,6 +42,10 @@ export const clearCommitSuccessfulState = () => ({ type: ReduxActionTypes.CLEAR_COMMIT_SUCCESSFUL_STATE, }); +export const clearCommitErrorState = () => ({ + type: ReduxActionTypes.CLEAR_COMMIT_ERROR_STATE, +}); + export type ConnectToGitResponse = { gitApplicationMetadata: GitApplicationMetadata; }; diff --git a/app/client/src/ce/constants/ReduxActionConstants.tsx b/app/client/src/ce/constants/ReduxActionConstants.tsx index 28a9f60c626b..cc0a792c8a47 100644 --- a/app/client/src/ce/constants/ReduxActionConstants.tsx +++ b/app/client/src/ce/constants/ReduxActionConstants.tsx @@ -53,6 +53,7 @@ export const ReduxActionTypes = { GIT_PULL_INIT: "GIT_PULL_INIT", GIT_PULL_SUCCESS: "GIT_PULL_SUCCESS", SET_APP_VERSION_ON_WORKER: "SET_APP_VERSION_ON_WORKER", + CLEAR_COMMIT_ERROR_STATE: "CLEAR_COMMIT_ERROR_STATE", CLEAR_COMMIT_SUCCESSFUL_STATE: "CLEAR_COMMIT_SUCCESSFUL_STATE", FETCH_MERGE_STATUS_INIT: "FETCH_MERGE_STATUS_INIT", FETCH_MERGE_STATUS_SUCCESS: "FETCH_MERGE_STATUS_SUCCESS", diff --git a/app/client/src/pages/Editor/gitSync/Tabs/Deploy.tsx b/app/client/src/pages/Editor/gitSync/Tabs/Deploy.tsx index e627dc7b8918..84af229825e3 100644 --- a/app/client/src/pages/Editor/gitSync/Tabs/Deploy.tsx +++ b/app/client/src/pages/Editor/gitSync/Tabs/Deploy.tsx @@ -19,9 +19,16 @@ import { Button, Category, getTypographyByKey, + Icon, + IconSize, LabelContainer, + ScrollIndicator, Size, + Text, TextInput, + TextType, + TooltipComponent as Tooltip, + Variant, } from "design-system"; import { getConflictFoundDocUrlDeploy, @@ -43,6 +50,7 @@ import { Theme } from "constants/DefaultTheme"; import { getCurrentAppGitMetaData } from "selectors/applicationSelectors"; import DeployPreview from "../components/DeployPreview"; import { + clearCommitErrorState, clearCommitSuccessfulState, commitToRepoInit, discardChanges, @@ -54,15 +62,6 @@ import Statusbar, { StatusbarWrapper, } from "pages/Editor/gitSync/components/Statusbar"; import GitChangesList from "../components/GitChangesList"; -import { - Icon, - IconSize, - ScrollIndicator, - Text, - TextType, - TooltipComponent as Tooltip, - Variant, -} from "design-system"; import InfoWrapper from "../components/InfoWrapper"; import Link from "../components/Link"; import ConflictInfo from "../components/ConflictInfo"; @@ -79,6 +78,7 @@ import { Space, Title } from "../components/StyledComponents"; import DiscardChangesWarning from "../components/DiscardChangesWarning"; import { changeInfoSinceLastCommit } from "../utils"; import { GitStatusData } from "reducers/uiReducers/gitSyncReducer"; +import PushFailedWarning from "../components/PushFailedWarning"; const Section = styled.div` margin-top: 0; @@ -314,6 +314,11 @@ function Deploy() { !isFetchingGitStatus && ((pullRequired && !isConflicting) || (gitStatus?.behindCount > 0 && gitStatus?.isClean)); + + function handleCommitAndPushErrorClose() { + dispatch(clearCommitErrorState()); + } + return ( <Container data-testid={"t--deploy-tab-container"} ref={scrollWrapperRef}> <Title>{createMessage(DEPLOY_YOUR_APPLICATION)}</Title> @@ -446,6 +451,13 @@ function Deploy() { learnMoreLink={gitConflictDocumentUrl} /> )} + {commitAndPushError && ( + <PushFailedWarning + closeHandler={handleCommitAndPushErrorClose} + error={commitAndPushError} + /> + )} + {isCommitting && !isDiscarding && ( <StatusbarWrapper> <Statusbar diff --git a/app/client/src/pages/Editor/gitSync/components/PushFailedWarning.tsx b/app/client/src/pages/Editor/gitSync/components/PushFailedWarning.tsx new file mode 100644 index 000000000000..f0d5f8bda78e --- /dev/null +++ b/app/client/src/pages/Editor/gitSync/components/PushFailedWarning.tsx @@ -0,0 +1,35 @@ +import { + NotificationBanner, + NotificationBannerProps, + NotificationVariant, + Text, + TextType, +} from "design-system"; +import React from "react"; +import styled from "styled-components"; + +const Container = styled.div` + margin: 8px 0 16px; +`; + +export default function PushFailedWarning({ closeHandler, error }: any) { + const notificationBannerOptions: NotificationBannerProps = { + canClose: true, + className: "error", + icon: "warning-line", + onClose: () => closeHandler(), + variant: NotificationVariant.error, + learnMoreClickHandler: null, + }; + return ( + <Container> + <NotificationBanner {...notificationBannerOptions}> + <> + <Text type={TextType.H5}>{error.errorType}</Text> + <br /> + <Text type={TextType.P3}>{error.message}</Text> + </> + </NotificationBanner> + </Container> + ); +} diff --git a/app/client/src/reducers/uiReducers/gitSyncReducer.ts b/app/client/src/reducers/uiReducers/gitSyncReducer.ts index 2417e6cb67ce..1e8c53dcbf00 100644 --- a/app/client/src/reducers/uiReducers/gitSyncReducer.ts +++ b/app/client/src/reducers/uiReducers/gitSyncReducer.ts @@ -81,6 +81,12 @@ const gitSyncReducer = createReducer(initialState, { isCommitting: false, commitAndPushError: action.payload, }), + [ReduxActionTypes.CLEAR_COMMIT_ERROR_STATE]: ( + state: GitSyncReducerState, + ) => ({ + ...state, + commitAndPushError: null, + }), [ReduxActionTypes.CLEAR_COMMIT_SUCCESSFUL_STATE]: ( state: GitSyncReducerState, ) => ({ @@ -230,7 +236,6 @@ const gitSyncReducer = createReducer(initialState, { ...state, isFetchingGitStatus: true, connectError: null, - commitAndPushError: null, pullError: null, mergeError: null, }), diff --git a/app/client/src/sagas/GitSyncSagas.ts b/app/client/src/sagas/GitSyncSagas.ts index d93d3dbbd54b..ee122afaa8e0 100644 --- a/app/client/src/sagas/GitSyncSagas.ts +++ b/app/client/src/sagas/GitSyncSagas.ts @@ -49,6 +49,7 @@ import { getSSHKeyPairSuccess, GetSSHKeyResponseData, gitPullSuccess, + importAppViaGitStatusReset, importAppViaGitSuccess, mergeBranchSuccess, setIsDisconnectGitModalOpen, @@ -57,7 +58,6 @@ import { setShowRepoLimitErrorModal, switchGitBranchInit, updateLocalGitConfigSuccess, - importAppViaGitStatusReset, } from "actions/gitSyncActions"; import { showReconnectDatasourceModal } from "actions/applicationActions"; @@ -146,6 +146,14 @@ function* commitToGitRepoSaga( }); } yield put(fetchGitStatusInit()); + } else { + yield put({ + type: ReduxActionErrorTypes.COMMIT_TO_GIT_REPO_ERROR, + payload: { + error: response?.responseMeta?.error, + show: true, + }, + }); } } catch (error) { const isRepoLimitReachedError: boolean = yield call( @@ -159,9 +167,13 @@ function* commitToGitRepoSaga( type: ReduxActionErrorTypes.COMMIT_TO_GIT_REPO_ERROR, payload: { error: response?.responseMeta?.error, - show: false, + show: true, }, }); + yield put({ + type: ReduxActionTypes.FETCH_GIT_STATUS_INIT, + }); + // yield call(fetchGitStatusSaga); } else { throw error; } @@ -871,9 +883,17 @@ function* discardChanges() { localStorage.setItem("GIT_DISCARD_CHANGES", "success"); const branch = response.data.gitApplicationMetadata.branchName; window.open(builderURL({ pageId, branch }), "_self"); + } else { + yield put( + discardChangesFailure({ + error: response?.responseMeta?.error?.message, + show: true, + }), + ); + localStorage.setItem("GIT_DISCARD_CHANGES", "failure"); } } catch (error) { - yield put(discardChangesFailure({ error })); + yield put(discardChangesFailure({ error, show: true })); localStorage.setItem("GIT_DISCARD_CHANGES", "failure"); } } 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 69ae24a7bd07..1d732ce55f88 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 @@ -27,7 +27,11 @@ import org.eclipse.jgit.api.Status; import org.eclipse.jgit.api.TransportConfigCallback; import org.eclipse.jgit.api.errors.CheckoutConflictException; +import org.eclipse.jgit.api.errors.ConcurrentRefUpdateException; import org.eclipse.jgit.api.errors.GitAPIException; +import org.eclipse.jgit.api.errors.NoMessageException; +import org.eclipse.jgit.api.errors.UnmergedPathsException; +import org.eclipse.jgit.api.errors.WrongRepositoryStateException; import org.eclipse.jgit.lib.BranchTrackingStatus; import org.eclipse.jgit.lib.PersonIdent; import org.eclipse.jgit.lib.Ref; @@ -54,6 +58,7 @@ import java.util.Arrays; import java.util.Date; import java.util.HashSet; +import java.util.Iterator; import java.util.List; import java.util.Optional; import java.util.Set; @@ -207,7 +212,12 @@ public Mono<String> pushApplication(Path repoSuffix, .call() .forEach(pushResult -> pushResult.getRemoteUpdates() - .forEach(remoteRefUpdate -> result.append(remoteRefUpdate.getStatus().name()).append(",")) + .forEach(remoteRefUpdate -> { + result.append(remoteRefUpdate.getStatus()).append(","); + if (!StringUtils.isEmptyOrNull(remoteRefUpdate.getMessage())) { + result.append(remoteRefUpdate.getMessage()).append(","); + } + }) ); // We can support username and password in future if needed // pushCommand.setCredentialsProvider(new UsernamePasswordCredentialsProvider("username", "password")); @@ -736,4 +746,17 @@ public Mono<Boolean> resetToLastCommit(Path repoSuffix, String branchName) throw }); } } + + public Mono<Boolean> resetHard(Path repoSuffix, String branchName) { + return this.checkoutToBranch(repoSuffix, branchName) + .flatMap(aBoolean -> { + try (Git git = Git.open(createRepoPath(repoSuffix).toFile())) { + Ref ref = git.reset().setMode(ResetCommand.ResetType.HARD).setRef("HEAD~1").call(); + return Mono.just(true); + } catch (GitAPIException | IOException e) { + log.error("Error while resetting the commit, {}", e.getMessage()); + } + return Mono.just(false); + }); + } } diff --git a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/git/GitExecutor.java b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/git/GitExecutor.java index 6248c06c4abb..aeab3167d5ec 100644 --- a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/git/GitExecutor.java +++ b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/git/GitExecutor.java @@ -173,4 +173,6 @@ Mono<List<GitBranchDTO>> listBranches(Path repoSuffix, * @return boolean if the connection can be established with the given keys */ Mono<Boolean> testConnection(String publicKey, String privateKey, String remoteUrl); + + Mono<Boolean> resetHard(Path repoSuffix, String branchName); } 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 2afcf35b5219..ca04049d2244 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 @@ -939,7 +939,7 @@ private Mono<String> pushApplication(String applicationId, boolean doPublish) { .flatMap(tuple -> { String pushResult = tuple.getT1(); Application application = tuple.getT2(); - if (pushResult.contains("REJECTED")) { + if (pushResult.contains("REJECTED_NONFASTFORWARD")) { return addAnalyticsForGitOperation( AnalyticsEvents.GIT_PUSH.getEventName(), @@ -947,8 +947,17 @@ private Mono<String> pushApplication(String applicationId, boolean doPublish) { AppsmithError.GIT_UPSTREAM_CHANGES.getErrorType(), AppsmithError.GIT_UPSTREAM_CHANGES.getMessage(), application.getGitApplicationMetadata().getIsRepoPrivate() - ) - .flatMap(application1 -> Mono.error(new AppsmithException(AppsmithError.GIT_UPSTREAM_CHANGES))); + ).flatMap(application1 -> Mono.error(new AppsmithException(AppsmithError.GIT_UPSTREAM_CHANGES))); + } else if (pushResult.contains("REJECTED_OTHERREASON") || pushResult.contains("pre-receive hook declined")) { + // Mostly happens when the remote branch is protected or any specific rules in place on the branch + // Since the users will be in a bad state where the changes are committed locally but they are not able to + // push them changes or revert the changes either. + // TODO Support protected branch flow within Appsmith + Path path = Paths.get(application.getWorkspaceId(), application.getGitApplicationMetadata().getDefaultApplicationId(), application.getGitApplicationMetadata().getRepoName()); + return gitExecutor.resetHard(path, application.getGitApplicationMetadata().getBranchName()) + .then(Mono.error(new AppsmithException(AppsmithError.GIT_ACTION_FAILED, "push", + "Unable to push changes as pre-receive hook declined. Please make sure that you don't have any rules enabled on the branch " + + application.getGitApplicationMetadata().getBranchName()))); } return Mono.just(pushResult).zipWith(Mono.just(tuple.getT2())); }) 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 57c871f0ce68..6e319d7d7bda 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 @@ -1837,6 +1837,37 @@ public void commitApplication_pushFails_verifyAppNotPublished_throwUpstreamChang .verifyComplete(); } + @Test + @WithUserDetails(value = "api_user") + public void commitApplication_protectedBranch_pushFails() throws GitAPIException, IOException { + // Create and fetch the application state before adding new page + Application testApplication = createApplicationConnectedToGit("commitApplication_protectedBranch_pushFails", DEFAULT_BRANCH); + Application preCommitApplication = applicationService.getApplicationByDefaultApplicationIdAndDefaultBranch(testApplication.getId()).block(); + + // Creating a new page to commit to git + PageDTO testPage = new PageDTO(); + testPage.setName("GitServiceTestPageGitPushFail"); + testPage.setApplicationId(preCommitApplication.getId()); + PageDTO createdPage = applicationPageService.createPage(testPage).block(); + + GitCommitDTO commitDTO = new GitCommitDTO(); + commitDTO.setDoPush(true); + commitDTO.setCommitMessage("New page added"); + Mono<String> commitMono = gitService.commitApplication(commitDTO, preCommitApplication.getId(), DEFAULT_BRANCH); + + // Mocking a git push failure + Mockito.when(gitExecutor.pushApplication(Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any())) + .thenReturn(Mono.just("REJECTED_OTHERREASON, pre-receive hook declined")); + Mockito.when(gitExecutor.resetHard(Mockito.any(Path.class), Mockito.anyString())) + .thenReturn(Mono.just(true)); + + StepVerifier + .create(commitMono) + .expectErrorMatches(throwable -> throwable instanceof AppsmithException && + throwable.getMessage().contains((new AppsmithException(AppsmithError.GIT_ACTION_FAILED, "push", "Unable to push changes as pre-receive hook declined. Please make sure that you don't have any rules enabled on the branch ")).getMessage())) + .verify(); + } + @Test @WithUserDetails(value = "api_user") public void createBranch_branchWithOriginPrefix_throwUnsupportedException() {
cd26aedb978b574b0bc79319f788e301b40448d6
2024-10-25 15:15:57
Ankita Kinger
chore: Updating types for support on EE (#37077)
false
Updating types for support on EE (#37077)
chore
diff --git a/app/client/src/ce/pages/common/PackageSearchItem.tsx b/app/client/src/ce/pages/common/PackageSearchItem.tsx index f87efbdc0af0..9ce611b81720 100644 --- a/app/client/src/ce/pages/common/PackageSearchItem.tsx +++ b/app/client/src/ce/pages/common/PackageSearchItem.tsx @@ -1,10 +1,10 @@ -interface Props { - // TODO: Fix this the next time the file is edited - // eslint-disable-next-line @typescript-eslint/no-explicit-any - searchedPackages: any; +import type { Package } from "ee/constants/PackageConstants"; + +export interface PackageSearchItemProps { + searchedPackages: Package[]; } -const PackageSearchItem = (props: Props) => { +const PackageSearchItem = (props: PackageSearchItemProps) => { // eslint-disable-next-line const { searchedPackages } = props; diff --git a/app/client/src/ce/pages/common/WorkflowSearchItem.tsx b/app/client/src/ce/pages/common/WorkflowSearchItem.tsx index 57da1d52da9d..888824d71533 100644 --- a/app/client/src/ce/pages/common/WorkflowSearchItem.tsx +++ b/app/client/src/ce/pages/common/WorkflowSearchItem.tsx @@ -1,10 +1,10 @@ import type { Workflow } from "ee/constants/WorkflowConstants"; -interface Props { +export interface WorkflowSearchItemProps { workflowsList: Workflow[]; } -const WorkflowSearchItem = (props: Props) => { +const WorkflowSearchItem = (props: WorkflowSearchItemProps) => { // eslint-disable-next-line const { workflowsList } = props;
31a0d0e1c9c4614fc56987463b92f63057b6e6bc
2024-09-13 16:32:47
Goutham Pratapa
fix: add depot token to dp ci (#36313)
false
add depot token to dp ci (#36313)
fix
diff --git a/.github/workflows/on-demand-build-docker-image-deploy-preview.yml b/.github/workflows/on-demand-build-docker-image-deploy-preview.yml index 5f0d28daeab6..44cce790ba30 100644 --- a/.github/workflows/on-demand-build-docker-image-deploy-preview.yml +++ b/.github/workflows/on-demand-build-docker-image-deploy-preview.yml @@ -118,6 +118,10 @@ jobs: push-image: needs: [client-build, rts-build, server-build] runs-on: ubuntu-latest + permissions: + contents: read + id-token: write + if: success() steps: # Check out merge commit
29729b239c3c641f0676712a060a247f2291a7fd
2022-02-17 11:32:43
allcontributors[bot]
docs: add prsidhu as a contributor for code, bug (#11227)
false
add prsidhu as a contributor for code, bug (#11227)
docs
diff --git a/.all-contributorsrc b/.all-contributorsrc index 910152d3e2fe..7de94c98297e 100644 --- a/.all-contributorsrc +++ b/.all-contributorsrc @@ -400,6 +400,16 @@ "code", "ideas" ] + }, + { + "login": "prsidhu", + "name": "Preet Sidhu", + "avatar_url": "https://avatars.githubusercontent.com/u/5424788?v=4", + "profile": "https://github.com/prsidhu", + "contributions": [ + "code", + "bug" + ] } ], "contributorsPerLine": 7, diff --git a/README.md b/README.md index 4714c3cd7bfc..a8f562ba6d67 100644 --- a/README.md +++ b/README.md @@ -194,6 +194,9 @@ We love our contributors! We're committed to fostering an open and welcoming env <td align="center"><a href="https://www.rafaaudibert.dev"><img src="https://avatars.githubusercontent.com/u/32079912?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Rafael Baldasso Audibert</b></sub></a><br /><a href="https://github.com/appsmithorg/appsmith/commits?author=rafaeelaudibert" title="Code">💻</a></td> <td align="center"><a href="https://github.com/yaldram"><img src="https://avatars.githubusercontent.com/u/13429535?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Arsalan Yaldram</b></sub></a><br /><a href="https://github.com/appsmithorg/appsmith/commits?author=yaldram" title="Code">💻</a> <a href="#ideas-yaldram" title="Ideas, Planning, & Feedback">🤔</a></td> </tr> + <tr> + <td align="center"><a href="https://github.com/prsidhu"><img src="https://avatars.githubusercontent.com/u/5424788?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Preet Sidhu</b></sub></a><br /><a href="https://github.com/appsmithorg/appsmith/commits?author=prsidhu" title="Code">💻</a> <a href="https://github.com/appsmithorg/appsmith/issues?q=author%3Aprsidhu" title="Bug reports">🐛</a></td> + </tr> </table> <!-- markdownlint-restore -->
4807e5826789547a96768374817a0a7172de6bcc
2021-10-13 15:13:16
Ashok Kumar M
fix: Switching back from comment mode the selection canvas doesn't work. (#8328)
false
Switching back from comment mode the selection canvas doesn't work. (#8328)
fix
diff --git a/app/client/src/pages/common/CanvasSelectionArena.tsx b/app/client/src/pages/common/CanvasSelectionArena.tsx index 10d93570a8ec..598677ff45f9 100644 --- a/app/client/src/pages/common/CanvasSelectionArena.tsx +++ b/app/client/src/pages/common/CanvasSelectionArena.tsx @@ -436,6 +436,7 @@ export function CanvasSelectionArena({ mainContainer, isDragging, isResizing, + isCommentMode, snapRows, snapColumnSpace, snapRowSpace,
88eaa666cd97eb0d36d98eeb8e6053b42a20db94
2024-01-09 16:22:38
Saroj
ci: Schedule TBP workflow to run 4 times a day with 3hrs interval (#30081)
false
Schedule TBP workflow to run 4 times a day with 3hrs interval (#30081)
ci
diff --git a/.github/workflows/test-build-docker-image.yml b/.github/workflows/test-build-docker-image.yml index f0c261efa2bb..c93b10b3d843 100644 --- a/.github/workflows/test-build-docker-image.yml +++ b/.github/workflows/test-build-docker-image.yml @@ -1,9 +1,9 @@ name: Test, build and push Docker Image on: - # This workflow will run everyday at 06:00 AM IST (12:30 AM UTC) on weekdays + # This workflow will run everyday at 7:00AM, 10:00AM, 1:00PM, 4:00PM IST on weekdays schedule: - - cron: "30 00 * * 1-5" + - cron: "30 1-12/3 * * 1-5" # This line enables manual triggering of this workflow. workflow_dispatch: inputs: @@ -86,7 +86,7 @@ jobs: ci-test: needs: [setup, build-docker-image] # Only run if the build step is successful - if: success() + if: success() && ( github.event_name != 'push' || github.ref == 'refs/heads/master' ) name: ci-test uses: ./.github/workflows/ci-test-custom-script.yml secrets: inherit @@ -98,6 +98,7 @@ jobs: server-unit-tests: name: server-unit-tests needs: [build-docker-image] + if: success() && ( github.event_name != 'push' || github.ref == 'refs/heads/master' ) uses: ./.github/workflows/server-build.yml secrets: inherit with: @@ -107,6 +108,7 @@ jobs: client-unit-tests: name: client-unit-tests needs: [build-docker-image] + if: success() && ( github.event_name != 'push' || github.ref == 'refs/heads/master' ) uses: ./.github/workflows/client-unit-tests.yml secrets: inherit with: @@ -116,8 +118,8 @@ jobs: needs: [ci-test, client-unit-tests, server-unit-tests] if: always() && (github.event_name == 'workflow_dispatch' || - github.event_name == 'push' || github.event_name == 'schedule' || + ( github.event_name != 'push' || github.ref == 'refs/heads/master' ) || (github.event_name == 'pull_request_review' && github.event.review.state == 'approved' && github.event.pull_request.head.repo.full_name == github.repository))
78379d4718e802f150ae5dcab1187e18a17558a0
2022-08-10 10:50:08
Rishabh Rathod
fix: update def on widget property name update (#15490)
false
update def on widget property name update (#15490)
fix
diff --git a/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/BugTests/Autocomplete_Spec.ts b/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/BugTests/Autocomplete_Spec.ts index d02656822691..846dc36fe9c8 100644 --- a/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/BugTests/Autocomplete_Spec.ts +++ b/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/BugTests/Autocomplete_Spec.ts @@ -1,14 +1,16 @@ +import { WIDGET } from "../../../../locators/WidgetLocators"; import { ObjectsRegistry } from "../../../../support/Objects/Registry"; - -let agHelper = ObjectsRegistry.AggregateHelper, - ee = ObjectsRegistry.EntityExplorer, - locator = ObjectsRegistry.CommonLocators, - propPane = ObjectsRegistry.PropertyPane; +const { + AggregateHelper: agHelper, + CommonLocators: locator, + EntityExplorer: ee, + PropertyPane: propPane, +} = ObjectsRegistry; describe("Autocomplete bug fixes", function() { it("1. Bug #12790 Verifies if selectedRow is in best match", function() { - ee.DragDropWidgetNVerify("tablewidgetv2", 200, 200); - ee.DragDropWidgetNVerify("textwidget", 200, 600); + ee.DragDropWidgetNVerify(WIDGET.TABLE, 200, 200); + ee.DragDropWidgetNVerify(WIDGET.TEXT, 200, 600); ee.SelectEntityByName("Text1"); propPane.TypeTextIntoField("Text", "{{Table1."); agHelper.AssertElementExist(locator._hints); @@ -23,10 +25,26 @@ describe("Autocomplete bug fixes", function() { propPane.TypeTextIntoField("Text", "{{Te"); agHelper.AssertElementExist(locator._hints); agHelper.AssertElementText(locator._hints, "Best Match"); - agHelper.AssertElementText( - locator._hints, - "Text1Copy.text", - 1, - ); + agHelper.AssertElementText(locator._hints, "Text1Copy.text", 1); + }); + + it("3. Bug #14100 Custom columns name label change should reflect in autocomplete", function() { + // select table widget + ee.SelectEntityByName("Table1"); + // add new column + cy.get(".t--add-column-btn").click(); + // edit column name + cy.get( + "[data-rbd-draggable-id='customColumn1'] .t--edit-column-btn", + ).click(); + + propPane.UpdatePropertyFieldValue("Property name", "columnAlias"); + cy.wait(500); + // select text widget + ee.SelectEntityByName("Text1"); + + // type {{Table1.selectedRow. and check for autocompletion suggestion having edited column name + propPane.TypeTextIntoField("Text", "{{Table1.selectedRow."); + agHelper.AssertElementText(locator._hints, "columnAlias", 1); }); }); diff --git a/app/client/cypress/locators/WidgetLocators.ts b/app/client/cypress/locators/WidgetLocators.ts index e1d4e7222aef..ebedf1836049 100644 --- a/app/client/cypress/locators/WidgetLocators.ts +++ b/app/client/cypress/locators/WidgetLocators.ts @@ -21,14 +21,17 @@ export const WIDGET = { AUDIORECORDER: "audiorecorderwidget", PHONEINPUT: "phoneinputwidget", CAMERA: "camerawidget", - FILEPICKER: "filepickerwidgetv2" + FILEPICKER: "filepickerwidgetv2", } as const; +// property pane element selector are maintained here export const PROPERTY_SELECTOR = { + // input onClick: ".t--property-control-onclick", onSubmit: ".t--property-control-onsubmit", text: ".t--property-control-text", defaultValue: ".t--property-control-defaultvalue", + propertyName: ".t--property-control-propertyname", }; type ValueOf<T> = T[keyof T]; diff --git a/app/client/src/sagas/PostEvaluationSagas.ts b/app/client/src/sagas/PostEvaluationSagas.ts index b78b27b8cc22..77d658c42394 100644 --- a/app/client/src/sagas/PostEvaluationSagas.ts +++ b/app/client/src/sagas/PostEvaluationSagas.ts @@ -47,6 +47,7 @@ import TernServer from "utils/autocomplete/TernServer"; import { selectFeatureFlags } from "selectors/usersSelectors"; import FeatureFlags from "entities/FeatureFlags"; import { JSAction } from "entities/JSCollection"; +import { isWidgetPropertyNamePath } from "utils/widgetEvalUtils"; const getDebuggerErrors = (state: AppState) => state.ui.debugger.errors; @@ -362,10 +363,25 @@ export function* updateTernDefinitions( } else { // Only when new field is added or deleted, we want to re-create the def shouldUpdate = some(updates, (update) => { - return ( + if ( update.event === DataTreeDiffEvent.NEW || update.event === DataTreeDiffEvent.DELETE - ); + ) { + return true; + } + + if (update.event === DataTreeDiffEvent.NOOP) { + const { entityName } = getEntityNameAndPropertyPath( + update.payload.propertyPath, + ); + const entity = dataTree[entityName]; + if (entity && isWidget(entity)) { + // if widget property name is modified then update tern def + return isWidgetPropertyNamePath(entity, update.payload.propertyPath); + } + } + + return false; }); } if (shouldUpdate) { diff --git a/app/client/src/utils/widgetEvalUtils.ts b/app/client/src/utils/widgetEvalUtils.ts new file mode 100644 index 000000000000..404f9e8c51f6 --- /dev/null +++ b/app/client/src/utils/widgetEvalUtils.ts @@ -0,0 +1,59 @@ +import { DataTreeWidget } from "entities/DataTree/dataTreeFactory"; + +/** + * PropertyName examples + * - `TableWidget`: column propertyName + * - `JSONForm`: field accessor name + * - `ButtonGroup`: button label name + * - `MenuButton`: button label name + * @param widgetEntity + * @param propertyPath + * @returns + */ +export const isWidgetPropertyNamePath = ( + widgetEntity: DataTreeWidget, + fullPath: string, +) => { + switch (widgetEntity.type) { + case "TABLE_WIDGET": + case "TABLE_WIDGET_V2": { + // TableWidget: Table1.primaryColumns.customColumn1.alias + const subPaths = fullPath.split("."); + if (subPaths.length === 4) { + return subPaths[1] === "primaryColumns" && subPaths[3] === "alias"; + } + return false; + } + case "BUTTON_GROUP_WIDGET": { + // buttonGroup: ButtonGroup1.groupButtons.groupButton8osb9mezmx.label + const subPaths = fullPath.split("."); + if (subPaths.length === 4) { + return subPaths[1] === "groupButtons" && subPaths[3] === "label"; + } + return false; + } + case "JSON_FORM_WIDGET": { + // JSONForm1.schema.__root_schema__.children.customField1.accessor + const subPaths = fullPath.split("."); + if (subPaths.length === 6) { + return ( + subPaths[1] === "schema" && + subPaths[3] === "children" && + subPaths[5] === "accessor" + ); + } + return false; + } + case "MENU_BUTTON_WIDGET": { + // MenuButton1.menuItems.menuItemdcoc16pgml.label + const subPaths = fullPath.split("."); + if (subPaths.length === 4) { + return subPaths[1] === "menuItems" && subPaths[3] === "label"; + } + return false; + } + + default: + return false; + } +}; diff --git a/app/client/src/workers/evaluationUtils.test.ts b/app/client/src/workers/evaluationUtils.test.ts index 2c5ec64fa600..20977296ee85 100644 --- a/app/client/src/workers/evaluationUtils.test.ts +++ b/app/client/src/workers/evaluationUtils.test.ts @@ -409,7 +409,7 @@ describe("translateDiffEvent", () => { }, { payload: { - propertyPath: "", + propertyPath: "Widget2.name", value: "", }, event: DataTreeDiffEvent.NOOP, @@ -436,7 +436,7 @@ describe("translateDiffEvent", () => { const expectedTranslations: DataTreeDiff[] = [ { payload: { - propertyPath: "", + propertyPath: "Widget2.name", value: "", }, event: DataTreeDiffEvent.NOOP, @@ -446,7 +446,6 @@ describe("translateDiffEvent", () => { const actualTranslations = flatten( diffs.map((diff) => translateDiffEventToDataTreeDiffEvent(diff, {})), ); - expect(expectedTranslations).toStrictEqual(actualTranslations); }); diff --git a/app/client/src/workers/evaluationUtils.ts b/app/client/src/workers/evaluationUtils.ts index 727e3a934aa2..31a38d871ab9 100644 --- a/app/client/src/workers/evaluationUtils.ts +++ b/app/client/src/workers/evaluationUtils.ts @@ -118,8 +118,14 @@ export const translateDiffEventToDataTreeDiffEvent = ( if (!difference.path) { return result; } - const propertyPath = convertPathToString(difference.path); + + // add propertyPath to NOOP event + result.payload = { + propertyPath, + value: "", + }; + //we do not need evaluate these paths coz these are internal paths const isUninterestingPathForUpdateTree = isUninterestingChangeForDependencyUpdate( propertyPath,
e29bbed556415bacf60f573fbd529104993ac76d
2023-11-21 13:35:02
Anagh Hegde
chore: Add error handling for the community template upload flow (#28948)
false
Add error handling for the community template upload flow (#28948)
chore
diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/ApplicationTemplateServiceCEImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/ApplicationTemplateServiceCEImpl.java index 176dcb6f90bf..f070ea002d86 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/ApplicationTemplateServiceCEImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/ApplicationTemplateServiceCEImpl.java @@ -349,7 +349,9 @@ private Mono<ApplicationTemplate> uploadCommunityTemplateToCS(CommunityTemplateU .accept(MediaType.APPLICATION_JSON) .body(BodyInserters.fromValue(payload)) .retrieve() - .bodyToMono(ApplicationTemplate.class); + .bodyToMono(ApplicationTemplate.class) + .onErrorResume(error -> Mono.error(new AppsmithException( + AppsmithError.CLOUD_SERVICES_ERROR, "while publishing template" + error.getMessage()))); } private Mono<Application> updateApplicationFlags(String applicationId, String branchId) { diff --git a/app/server/appsmith-server/src/test/java/com/appsmith/server/services/ce/ApplicationTemplateServicePublishTemplateTest.java b/app/server/appsmith-server/src/test/java/com/appsmith/server/services/ce/ApplicationTemplateServicePublishTemplateTest.java new file mode 100644 index 000000000000..0aee9ad0f104 --- /dev/null +++ b/app/server/appsmith-server/src/test/java/com/appsmith/server/services/ce/ApplicationTemplateServicePublishTemplateTest.java @@ -0,0 +1,124 @@ +package com.appsmith.server.services.ce; + +import com.appsmith.server.configurations.CloudServicesConfig; +import com.appsmith.server.domains.Application; +import com.appsmith.server.domains.GitApplicationMetadata; +import com.appsmith.server.domains.Workspace; +import com.appsmith.server.dtos.CommunityTemplateDTO; +import com.appsmith.server.exceptions.AppsmithException; +import com.appsmith.server.services.ApplicationPageService; +import com.appsmith.server.services.ApplicationTemplateService; +import com.appsmith.server.services.WorkspaceService; +import lombok.extern.slf4j.Slf4j; +import mockwebserver3.Dispatcher; +import mockwebserver3.MockResponse; +import mockwebserver3.MockWebServer; +import mockwebserver3.RecordedRequest; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.security.test.context.support.WithUserDetails; +import org.springframework.test.context.junit.jupiter.SpringExtension; +import reactor.test.StepVerifier; + +import java.io.IOException; +import java.time.Instant; +import java.util.List; + +@Slf4j +@ExtendWith(SpringExtension.class) +@SpringBootTest +public class ApplicationTemplateServicePublishTemplateTest { + private static MockWebServer mockCloudServices; + + @Autowired + ApplicationTemplateService applicationTemplateService; + + @Autowired + WorkspaceService workspaceService; + + @Autowired + ApplicationPageService applicationPageService; + + @Autowired + CloudServicesConfig cloudServicesConfig; + + static final Dispatcher dispatcher = new Dispatcher() { + @Override + public MockResponse dispatch(RecordedRequest request) throws InterruptedException { + + switch (request.getPath()) { + case "/api/v1/app-templates/upload-community-template": + return new MockResponse().setResponseCode(500).setBody("Error while uploading template"); + + default: + return new MockResponse() + .setHeader("x-header-name", "header-value") + .setResponseCode(200) + .setBody("response"); + } + } + }; + + @BeforeAll + public static void setUp() throws IOException { + mockCloudServices = new MockWebServer(); + mockCloudServices.setDispatcher(dispatcher); + mockCloudServices.start(); + } + + @AfterAll + public static void tearDown() throws IOException { + mockCloudServices.shutdown(); + } + + private Application setUpTestApplicationForWorkspace(String workspaceId) { + Application testApplication = new Application(); + testApplication.setName("Export-Application-Test-Application"); + testApplication.setWorkspaceId(workspaceId); + testApplication.setUpdatedAt(Instant.now()); + testApplication.setLastDeployedAt(Instant.now()); + testApplication.setModifiedBy("some-user"); + testApplication.setGitApplicationMetadata(new GitApplicationMetadata()); + + cloudServicesConfig.setBaseUrl(String.format("http://localhost:%s", mockCloudServices.getPort())); + + return applicationPageService + .createApplication(testApplication, workspaceId) + .block(); + } + + @Test + @WithUserDetails(value = "api_user") + public void test_application_published_as_community_template() { + // Create Workspace + Workspace workspace = new Workspace(); + workspace.setName("Import-Export-Test-Workspace"); + Workspace savedWorkspace = workspaceService.create(workspace).block(); + + Application testApp = setUpTestApplicationForWorkspace(savedWorkspace.getId()); + CommunityTemplateDTO communityTemplateDTO = new CommunityTemplateDTO(); + communityTemplateDTO.setApplicationId(testApp.getId()); + communityTemplateDTO.setWorkspaceId(testApp.getWorkspaceId()); + communityTemplateDTO.setTitle("Some title"); + communityTemplateDTO.setHeadline("Some headline"); + communityTemplateDTO.setDescription("Some description"); + communityTemplateDTO.setUseCases(List.of("uc1", "uc2")); + communityTemplateDTO.setAuthorEmail("[email protected]"); + + // make sure we've received the response returned by the mockCloudServices + StepVerifier.create(applicationTemplateService.publishAsCommunityTemplate(communityTemplateDTO)) + .expectErrorMatches(throwable -> throwable instanceof AppsmithException + && throwable + .getMessage() + .contains("Received error from cloud services while publishing template")) + .verify(); + + // Test cleanup + applicationPageService.deleteApplication(testApp.getId()).block(); + workspaceService.archiveById(savedWorkspace.getId()).block(); + } +}
a6b8a36d6c7f8214f941cc55272f92313c132db3
2024-05-15 17:17:36
Ankita Kinger
chore: Updating embed settings feature tag from Business to Enterprise (#33448)
false
Updating embed settings feature tag from Business to Enterprise (#33448)
chore
diff --git a/app/client/cypress/e2e/Regression/ClientSide/OtherUIFeatures/ExportApplication_spec.js b/app/client/cypress/e2e/Regression/ClientSide/OtherUIFeatures/ExportApplication_spec.js index 69b64124d17a..8e529c5c20af 100644 --- a/app/client/cypress/e2e/Regression/ClientSide/OtherUIFeatures/ExportApplication_spec.js +++ b/app/client/cypress/e2e/Regression/ClientSide/OtherUIFeatures/ExportApplication_spec.js @@ -8,7 +8,7 @@ import { describe( "Export application as a JSON file", - { tags: ["@tag.ExportApplication"] }, + { tags: ["@tag.ImportExport"] }, function () { let workspaceId, appid; diff --git a/app/client/cypress/e2e/Regression/ClientSide/ProductRamps/PrivateEmbedRamp_spec.ts b/app/client/cypress/e2e/Regression/ClientSide/ProductRamps/PrivateEmbedRamp_spec.ts index e5bb84db8fc6..bd8e9453ffe6 100644 --- a/app/client/cypress/e2e/Regression/ClientSide/ProductRamps/PrivateEmbedRamp_spec.ts +++ b/app/client/cypress/e2e/Regression/ClientSide/ProductRamps/PrivateEmbedRamp_spec.ts @@ -10,7 +10,7 @@ describe("Private embed in-app ramp", { tags: ["@tag.Settings"] }, () => { ); _.agHelper.GetNAssertElementText( _.inviteModal.locators._privateEmbedRampAppSettings, - "To embed private Appsmith apps and seamlessly authenticate users through SSO", + Cypress.env("MESSAGES").IN_APP_EMBED_SETTING.rampSubtextSidebar(), "contain.text", ); checkRampLink(); @@ -19,7 +19,7 @@ describe("Private embed in-app ramp", { tags: ["@tag.Settings"] }, () => { _.inviteModal.SelectEmbedTab(); _.agHelper.GetNAssertElementText( _.inviteModal.locators._privateEmbedRampAppSettings, - "Embed private Appsmith apps and seamlessly authenticate users through SSO in our Business Edition", + Cypress.env("MESSAGES").IN_APP_EMBED_SETTING.rampSubtextModal(), "contain.text", ); checkRampLink(); @@ -28,7 +28,7 @@ describe("Private embed in-app ramp", { tags: ["@tag.Settings"] }, () => { cy.get(_.inviteModal.locators._privateEmbedRampLink) .should("have.attr", "href") .then((href) => { - expect(href).to.include("customer.appsmith.com"); + expect(href).to.include("https://www.appsmith.com/pricing?"); }); } diff --git a/app/client/src/ce/constants/messages.ts b/app/client/src/ce/constants/messages.ts index 8c66f5452949..88a344494ffe 100644 --- a/app/client/src/ce/constants/messages.ts +++ b/app/client/src/ce/constants/messages.ts @@ -1923,13 +1923,13 @@ export const IN_APP_EMBED_SETTING = { "Make your app public by visiting the share settings, and easily embed your Appsmith app into legacy applications", privateAppsText: () => "Private apps", rampSubtextModal: () => - "Embed private Appsmith apps and seamlessly authenticate users through SSO in our Business Edition", + "Embed private Appsmith apps and seamlessly authenticate users through SSO in our Enterprise Edition", rampSubtextSidebar: () => "To embed private Appsmith apps and seamlessly authenticate users through SSO, try our ", - rampLinktext: () => "Try Business", - rampLinktextvariant2: () => "Business Edition", + rampLinktext: () => "Try Enterprise", + rampLinktextvariant2: () => "Enterprise Edition", upgradeContent: () => "Private embedding is now available in", - appsmithBusinessEdition: () => "Appsmith Business Edition.", + appsmithEnterpriseEdition: () => "Appsmith Enterprise Edition.", secondaryHeadingForAppSettings: () => "Make your app public to embed your Appsmith app into legacy applications", secondaryHeading: () => diff --git a/app/client/src/ce/selectors/rampSelectors.tsx b/app/client/src/ce/selectors/rampSelectors.tsx index 9c1ce8f1b747..21077ed82640 100644 --- a/app/client/src/ce/selectors/rampSelectors.tsx +++ b/app/client/src/ce/selectors/rampSelectors.tsx @@ -1,7 +1,10 @@ import { createSelector } from "reselect"; import type { AppState } from "@appsmith/reducers"; import { getAppsmithConfigs } from "@appsmith/configs"; -import { CUSTOMER_PORTAL_URL_WITH_PARAMS } from "constants/ThirdPartyConstants"; +import { + CUSTOMER_PORTAL_URL_WITH_PARAMS, + PRICING_PAGE_URL, +} from "constants/ThirdPartyConstants"; import { PRODUCT_RAMPS_LIST, RAMP_FOR_ROLES, @@ -12,27 +15,33 @@ import { PERMISSION_TYPE, } from "@appsmith/utils/permissionHelpers"; -const { cloudHosting, customerPortalUrl } = getAppsmithConfigs(); +const { cloudHosting, customerPortalUrl, pricingUrl } = getAppsmithConfigs(); const tenantState = (state: AppState) => state.tenant; const uiState = (state: AppState) => state.ui; export const getRampLink = ({ feature, + isBusinessFeature = true, section, }: { section: string; feature: string; + isBusinessFeature?: boolean; }) => createSelector(tenantState, (tenant) => { const instanceId = tenant?.instanceId; const source = cloudHosting ? "cloud" : "CE"; - const RAMP_LINK_TO = CUSTOMER_PORTAL_URL_WITH_PARAMS( - customerPortalUrl, - source, - instanceId, - ); - return `${RAMP_LINK_TO}&feature=${feature}&section=${section}`; + const RAMP_LINK_TO = isBusinessFeature + ? CUSTOMER_PORTAL_URL_WITH_PARAMS( + customerPortalUrl, + source, + instanceId, + feature, + section, + ) + : PRICING_PAGE_URL(pricingUrl, source, instanceId, feature, section); + return RAMP_LINK_TO; }); export const showProductRamps = ( diff --git a/app/client/src/components/utils/ReduxFormTextField.tsx b/app/client/src/components/utils/ReduxFormTextField.tsx index 261a70f123ee..ccf6f09a8d6d 100644 --- a/app/client/src/components/utils/ReduxFormTextField.tsx +++ b/app/client/src/components/utils/ReduxFormTextField.tsx @@ -14,7 +14,7 @@ const renderComponent = ( input: Partial<WrappedFieldInputProps>; }, ) => { - const value = componentProps.input.value || componentProps.defaultValue; + const value = componentProps.input.value || componentProps.defaultValue || ""; const showError = componentProps.meta.touched && !componentProps.meta.active; return componentProps.type === SettingSubtype.NUMBER ? ( <NumberInput diff --git a/app/client/src/pages/Applications/EmbedSnippet/PrivateEmbeddingContent.tsx b/app/client/src/pages/Applications/EmbedSnippet/PrivateEmbeddingContent.tsx index 88d4885f3788..b74014304875 100644 --- a/app/client/src/pages/Applications/EmbedSnippet/PrivateEmbeddingContent.tsx +++ b/app/client/src/pages/Applications/EmbedSnippet/PrivateEmbeddingContent.tsx @@ -18,9 +18,9 @@ import { getRampLink, showProductRamps, } from "@appsmith/selectors/rampSelectors"; -import BusinessTag from "components/BusinessTag"; import { FEATURE_FLAG } from "@appsmith/entities/FeatureFlag"; import { useFeatureFlag } from "utils/hooks/useFeatureFlag"; +import EnterpriseTag from "components/EnterpriseTag"; function PrivateEmbeddingContent(props: { userAppPermissions: any[]; @@ -51,6 +51,7 @@ export function PrivateEmbedRampModal() { const rampLinkSelector = getRampLink({ section: RampSection.ShareModal, feature: RampFeature.PrivateEmbeds, + isBusinessFeature: false, }); const rampLink = useSelector(rampLinkSelector); const isPrivateEmbedEnabled = useFeatureFlag( @@ -71,7 +72,7 @@ export function PrivateEmbedRampModal() { <Text kind="body-m"> {createMessage(IN_APP_EMBED_SETTING.privateAppsText)} </Text> - <BusinessTag classes="ml-1 mt-0.5" /> + <EnterpriseTag classes="ml-1 mt-0.5" /> </div> <Text className="w-7/10 block" @@ -99,6 +100,7 @@ export function PrivateEmbedRampSidebar() { const rampLinkSelector = getRampLink({ section: RampSection.AppSettings, feature: RampFeature.PrivateEmbeds, + isBusinessFeature: false, }); const rampLink = useSelector(rampLinkSelector); const isPrivateEmbedEnabled = useFeatureFlag(
20e2a64b9178c4bdf220e9c1ee2adb89e73fd682
2023-03-08 21:05:50
Shrikant Sharat Kandula
fix: Revert container-internal communication when using IPv6 (#21260)
false
Revert container-internal communication when using IPv6 (#21260)
fix
diff --git a/app/client/docker/templates/nginx-app-http.conf.template b/app/client/docker/templates/nginx-app-http.conf.template index a44f2b9d3c94..cc2e5b9600f5 100644 --- a/app/client/docker/templates/nginx-app-http.conf.template +++ b/app/client/docker/templates/nginx-app-http.conf.template @@ -1,6 +1,5 @@ server { listen 80; - listen [::]:80; server_name $APPSMITH_DOMAIN; client_max_body_size 150m; diff --git a/app/client/docker/templates/nginx-app-https.conf.template b/app/client/docker/templates/nginx-app-https.conf.template index 806ca5792403..dda83def235f 100644 --- a/app/client/docker/templates/nginx-app-https.conf.template +++ b/app/client/docker/templates/nginx-app-https.conf.template @@ -1,6 +1,5 @@ server { listen 80; - listen [::]:80; server_name $APPSMITH_DOMAIN; return 301 https://$host$request_uri; @@ -8,7 +7,6 @@ server { server { listen 443 ssl http2; - listen [::]:443 ssl http2; server_name _; ssl_certificate ${APPSMITH_SSL_CERT_PATH}; diff --git a/app/client/docker/templates/nginx-app.conf.template b/app/client/docker/templates/nginx-app.conf.template index 7ae01fb6d9c7..c63fd373fb24 100644 --- a/app/client/docker/templates/nginx-app.conf.template +++ b/app/client/docker/templates/nginx-app.conf.template @@ -1,6 +1,5 @@ server { listen 80; - listen [::]:80; server_name dev.appsmith.com; return 301 https://$host$request_uri; @@ -8,7 +7,6 @@ server { server { listen 443 ssl http2; - listen [::]:443 ssl http2; server_name dev.appsmith.com; client_max_body_size 150m; diff --git a/app/client/start-https.sh b/app/client/start-https.sh index ae2d1bbe4b18..67a6f3a9577b 100755 --- a/app/client/start-https.sh +++ b/app/client/start-https.sh @@ -233,7 +233,6 @@ http { $(if [[ $use_https == 1 ]]; then echo " server { listen $http_listen_port default_server; - listen [::]:$http_listen_port default_server; server_name $domain; return 301 https://\$host$(if [[ $https_listen_port != 443 ]]; then echo ":$https_listen_port"; fi)\$request_uri; } @@ -242,13 +241,11 @@ $(if [[ $use_https == 1 ]]; then echo " server { $(if [[ $use_https == 1 ]]; then echo " listen $https_listen_port ssl http2 default_server; - listen [::]:$https_listen_port ssl http2 default_server; server_name $domain; ssl_certificate '$cert_file'; ssl_certificate_key '$key_file'; "; else echo " listen $http_listen_port default_server; - listen [::]:$http_listen_port default_server; server_name _; "; fi) diff --git a/deploy/docker/templates/nginx/nginx-app-http.conf.template.sh b/deploy/docker/templates/nginx/nginx-app-http.conf.template.sh index a09d86d141ff..070dbe528796 100644 --- a/deploy/docker/templates/nginx/nginx-app-http.conf.template.sh +++ b/deploy/docker/templates/nginx/nginx-app-http.conf.template.sh @@ -24,7 +24,6 @@ access_log /dev/stdout; server { listen ${PORT:-80} default_server; - listen [::]:${PORT:-80} default_server; server_name $CUSTOM_DOMAIN; client_max_body_size 150m; diff --git a/deploy/docker/templates/nginx/nginx-app-https.conf.template.sh b/deploy/docker/templates/nginx/nginx-app-https.conf.template.sh index 9bba40812001..87dd877a78a1 100644 --- a/deploy/docker/templates/nginx/nginx-app-https.conf.template.sh +++ b/deploy/docker/templates/nginx/nginx-app-https.conf.template.sh @@ -30,7 +30,6 @@ access_log /dev/stdout; server { listen 80; - listen [::]:80; server_name $CUSTOM_DOMAIN; return 301 https://\$host\$request_uri; @@ -38,7 +37,6 @@ server { server { listen 443 ssl http2; - listen [::]:443 ssl http2; server_name _; ssl_certificate $SSL_CERT_PATH;
be76aeed6047ac6b8936935a6da1a2f218d85c9a
2024-06-12 12:38:25
Shrikant Sharat Kandula
chore: Make core encrypt/decrypt methods statically available (#34117)
false
Make core encrypt/decrypt methods statically available (#34117)
chore
diff --git a/app/server/appsmith-interfaces/pom.xml b/app/server/appsmith-interfaces/pom.xml index 17b89cc2d00d..83d43f4e569f 100644 --- a/app/server/appsmith-interfaces/pom.xml +++ b/app/server/appsmith-interfaces/pom.xml @@ -86,6 +86,11 @@ <scope>compile</scope> </dependency> + <dependency> + <groupId>org.springframework.security</groupId> + <artifactId>spring-security-crypto</artifactId> + </dependency> + <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> diff --git a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/annotations/encryption/EncryptionMongoEventListener.java b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/annotations/encryption/EncryptionMongoEventListener.java index 7e687582e950..a82397b94307 100644 --- a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/annotations/encryption/EncryptionMongoEventListener.java +++ b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/annotations/encryption/EncryptionMongoEventListener.java @@ -1,6 +1,6 @@ package com.appsmith.external.annotations.encryption; -import com.appsmith.external.services.EncryptionService; +import com.appsmith.external.helpers.EncryptionHelper; import lombok.extern.slf4j.Slf4j; import org.springframework.data.mongodb.core.mapping.event.AbstractMongoEventListener; import org.springframework.data.mongodb.core.mapping.event.AfterConvertEvent; @@ -9,13 +9,7 @@ @Slf4j public class EncryptionMongoEventListener<E> extends AbstractMongoEventListener<E> { - private final EncryptionService encryptionService; - EncryptionHandler encryptionHandler; - - public EncryptionMongoEventListener(EncryptionService encryptionService) { - encryptionHandler = new EncryptionHandler(); - this.encryptionService = encryptionService; - } + private final EncryptionHandler encryptionHandler = new EncryptionHandler(); // This lifecycle event is before we save a document into the DB, // and even before the mapper has converted the object into a document type @@ -23,7 +17,7 @@ public EncryptionMongoEventListener(EncryptionService encryptionService) { public void onBeforeConvert(BeforeConvertEvent<E> event) { E source = event.getSource(); - encryptionHandler.convertEncryption(source, encryptionService::encryptString); + encryptionHandler.convertEncryption(source, EncryptionHelper::encrypt); } // This lifecycle event is after we retrieve a document from the DB, @@ -32,6 +26,6 @@ public void onBeforeConvert(BeforeConvertEvent<E> event) { public void onAfterConvert(AfterConvertEvent<E> event) { E source = event.getSource(); - encryptionHandler.convertEncryption(source, encryptionService::decryptString); + encryptionHandler.convertEncryption(source, EncryptionHelper::decrypt); } } diff --git a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/helpers/EncryptionHelper.java b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/helpers/EncryptionHelper.java new file mode 100644 index 000000000000..2db97a9f4e90 --- /dev/null +++ b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/helpers/EncryptionHelper.java @@ -0,0 +1,41 @@ +package com.appsmith.external.helpers; + +import org.apache.commons.lang3.StringUtils; +import org.springframework.security.crypto.encrypt.Encryptors; +import org.springframework.security.crypto.encrypt.TextEncryptor; + +import java.util.HexFormat; + +public final class EncryptionHelper { + + private static final String salt = requireEnv("APPSMITH_ENCRYPTION_SALT"); + + private static final String password = requireEnv("APPSMITH_ENCRYPTION_PASSWORD"); + + private static final HexFormat hexFormat = HexFormat.of(); + + private static final TextEncryptor textEncryptor = makeTextEncryptor(); + + private EncryptionHelper() {} + + private static TextEncryptor makeTextEncryptor() { + final String saltInHex = hexFormat.formatHex(salt.getBytes()); + return Encryptors.delux(password, saltInHex); + } + + public static String encrypt(String plaintext) { + return textEncryptor.encrypt(plaintext); + } + + public static String decrypt(String encryptedText) { + return textEncryptor.decrypt(encryptedText); + } + + private static String requireEnv(String name) { + final String value = System.getenv(name); + if (StringUtils.isBlank(value)) { + throw new RuntimeException("Environment variable '%s' is required".formatted(name)); + } + return value; + } +} diff --git a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/services/EncryptionService.java b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/services/EncryptionService.java deleted file mode 100644 index 4abb39291b7b..000000000000 --- a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/services/EncryptionService.java +++ /dev/null @@ -1,5 +0,0 @@ -package com.appsmith.external.services; - -import com.appsmith.external.services.ce.EncryptionServiceCE; - -public interface EncryptionService extends EncryptionServiceCE {} diff --git a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/services/ce/EncryptionServiceCE.java b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/services/ce/EncryptionServiceCE.java deleted file mode 100644 index 6a7fa0f1e630..000000000000 --- a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/services/ce/EncryptionServiceCE.java +++ /dev/null @@ -1,8 +0,0 @@ -package com.appsmith.external.services.ce; - -public interface EncryptionServiceCE { - - String encryptString(String plaintext); - - String decryptString(String encryptedText); -} diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/configurations/EncryptionConfig.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/configurations/EncryptionConfig.java deleted file mode 100644 index 79be92c48cfb..000000000000 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/configurations/EncryptionConfig.java +++ /dev/null @@ -1,16 +0,0 @@ -package com.appsmith.server.configurations; - -import lombok.Getter; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.context.annotation.Configuration; - -@Configuration -@Getter -public class EncryptionConfig { - - @Value("${encrypt.salt}") - private String salt; - - @Value("${encrypt.password}") - private String password; -} diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/configurations/MongoConfig.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/configurations/MongoConfig.java index 29a7b7834ab7..6cbf63c2b70c 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/configurations/MongoConfig.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/configurations/MongoConfig.java @@ -3,7 +3,6 @@ import com.appsmith.external.annotations.documenttype.DocumentTypeMapper; import com.appsmith.external.annotations.encryption.EncryptionMongoEventListener; import com.appsmith.external.models.AuthenticationDTO; -import com.appsmith.external.services.EncryptionService; import com.appsmith.server.configurations.mongo.SoftDeleteMongoRepositoryFactoryBean; import com.appsmith.server.converters.StringToInstantConverter; import com.appsmith.server.repositories.BaseRepositoryImpl; @@ -266,8 +265,8 @@ public MappingMongoConverter mappingMongoConverter( } @Bean - public EncryptionMongoEventListener encryptionMongoEventListener(EncryptionService encryptionService) { - return new EncryptionMongoEventListener(encryptionService); + public EncryptionMongoEventListener encryptionMongoEventListener() { + return new EncryptionMongoEventListener(); } @Bean diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/EncryptionServiceImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/EncryptionServiceImpl.java deleted file mode 100644 index 5f4548bfe23f..000000000000 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/EncryptionServiceImpl.java +++ /dev/null @@ -1,14 +0,0 @@ -package com.appsmith.server.services; - -import com.appsmith.external.services.EncryptionService; -import com.appsmith.server.configurations.EncryptionConfig; -import com.appsmith.server.services.ce.EncryptionServiceCEImpl; -import org.springframework.stereotype.Service; - -@Service -public class EncryptionServiceImpl extends EncryptionServiceCEImpl implements EncryptionService { - - public EncryptionServiceImpl(EncryptionConfig encryptionConfig) { - super(encryptionConfig); - } -} diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/UserServiceImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/UserServiceImpl.java index f07cafeab4d9..bed86dbc475f 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/UserServiceImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/UserServiceImpl.java @@ -1,6 +1,5 @@ package com.appsmith.server.services; -import com.appsmith.external.services.EncryptionService; import com.appsmith.server.configurations.CommonConfig; import com.appsmith.server.configurations.EmailConfig; import com.appsmith.server.helpers.UserServiceHelper; @@ -35,7 +34,6 @@ public UserServiceImpl( PolicySolution policySolution, CommonConfig commonConfig, EmailConfig emailConfig, - EncryptionService encryptionService, UserDataService userDataService, TenantService tenantService, PermissionGroupService permissionGroupService, @@ -54,7 +52,6 @@ public UserServiceImpl( passwordResetTokenRepository, passwordEncoder, commonConfig, - encryptionService, userDataService, tenantService, userUtils, diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/EncryptionServiceCEImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/EncryptionServiceCEImpl.java deleted file mode 100644 index 0f7d61c5cdc1..000000000000 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/EncryptionServiceCEImpl.java +++ /dev/null @@ -1,32 +0,0 @@ -package com.appsmith.server.services.ce; - -import com.appsmith.external.services.ce.EncryptionServiceCE; -import com.appsmith.server.configurations.EncryptionConfig; -import org.apache.commons.codec.binary.Hex; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.security.crypto.encrypt.Encryptors; -import org.springframework.security.crypto.encrypt.TextEncryptor; - -public class EncryptionServiceCEImpl implements EncryptionServiceCE { - - private final EncryptionConfig encryptionConfig; - - private TextEncryptor textEncryptor; - - @Autowired - public EncryptionServiceCEImpl(EncryptionConfig encryptionConfig) { - this.encryptionConfig = encryptionConfig; - String saltInHex = Hex.encodeHexString(encryptionConfig.getSalt().getBytes()); - this.textEncryptor = Encryptors.delux(encryptionConfig.getPassword(), saltInHex); - } - - @Override - public String encryptString(String plaintext) { - return textEncryptor.encrypt(plaintext); - } - - @Override - public String decryptString(String encryptedText) { - return textEncryptor.decrypt(encryptedText); - } -} 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 afddfb233709..ca6cb2f60446 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 @@ -1,7 +1,7 @@ package com.appsmith.server.services.ce; import com.appsmith.external.helpers.AppsmithBeanUtils; -import com.appsmith.external.services.EncryptionService; +import com.appsmith.external.helpers.EncryptionHelper; import com.appsmith.server.acl.AclPermission; import com.appsmith.server.configurations.CommonConfig; import com.appsmith.server.constants.FieldName; @@ -96,7 +96,6 @@ public class UserServiceCEImpl extends BaseService<UserRepository, User, String> private final PasswordEncoder passwordEncoder; private final CommonConfig commonConfig; - private final EncryptionService encryptionService; private final UserDataService userDataService; private final TenantService tenantService; private final UserUtils userUtils; @@ -128,7 +127,6 @@ public UserServiceCEImpl( PasswordResetTokenRepository passwordResetTokenRepository, PasswordEncoder passwordEncoder, CommonConfig commonConfig, - EncryptionService encryptionService, UserDataService userDataService, TenantService tenantService, UserUtils userUtils, @@ -144,7 +142,6 @@ public UserServiceCEImpl( this.passwordResetTokenRepository = passwordResetTokenRepository; this.passwordEncoder = passwordEncoder; this.commonConfig = commonConfig; - this.encryptionService = encryptionService; this.userDataService = userDataService; this.tenantService = tenantService; this.userUtils = userUtils; @@ -225,7 +222,7 @@ public Mono<Boolean> forgotPasswordTokenGenerate(ResetUserPasswordDTO resetUserP String resetUrl = String.format( FORGOT_PASSWORD_CLIENT_URL_FORMAT, resetUserPasswordDTO.getBaseUrl(), - encryptionService.encryptString(urlParams)); + EncryptionHelper.encrypt(urlParams)); log.debug("Password reset url for email: {}: {}", passwordResetToken.getEmail(), resetUrl); @@ -695,7 +692,7 @@ public Mono<UserProfileDTO> buildUserProfileDTO(User user) { } private EmailTokenDTO parseValueFromEncryptedToken(String encryptedToken) { - String decryptString = encryptionService.decryptString(encryptedToken); + String decryptString = EncryptionHelper.decrypt(encryptedToken); List<NameValuePair> nameValuePairs = WWWFormCodec.parse(decryptString, StandardCharsets.UTF_8); Map<String, String> params = new HashMap<>(); @@ -780,7 +777,7 @@ public Mono<Boolean> resendEmailVerification( String verificationUrl = String.format( EMAIL_VERIFICATION_CLIENT_URL_FORMAT, resendEmailVerificationDTO.getBaseUrl(), - encryptionService.encryptString(urlParams), + EncryptionHelper.encrypt(urlParams), URLEncoder.encode(emailVerificationToken.getEmail(), StandardCharsets.UTF_8), redirectUrlCopy); diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce_compatible/UserServiceCECompatibleImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce_compatible/UserServiceCECompatibleImpl.java index 112ab57273bb..7589ceac4a88 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce_compatible/UserServiceCECompatibleImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce_compatible/UserServiceCECompatibleImpl.java @@ -1,6 +1,5 @@ package com.appsmith.server.services.ce_compatible; -import com.appsmith.external.services.EncryptionService; import com.appsmith.server.configurations.CommonConfig; import com.appsmith.server.helpers.UserServiceHelper; import com.appsmith.server.helpers.UserUtils; @@ -31,7 +30,6 @@ public UserServiceCECompatibleImpl( PasswordResetTokenRepository passwordResetTokenRepository, PasswordEncoder passwordEncoder, CommonConfig commonConfig, - EncryptionService encryptionService, UserDataService userDataService, TenantService tenantService, UserUtils userUtils, @@ -49,7 +47,6 @@ public UserServiceCECompatibleImpl( passwordResetTokenRepository, passwordEncoder, commonConfig, - encryptionService, userDataService, tenantService, userUtils, diff --git a/app/server/appsmith-server/src/main/resources/application.properties b/app/server/appsmith-server/src/main/resources/application.properties index fcd07b99ea4a..58281832ee54 100644 --- a/app/server/appsmith-server/src/main/resources/application.properties +++ b/app/server/appsmith-server/src/main/resources/application.properties @@ -87,11 +87,6 @@ appsmith.cloud_services.signature_base_url = ${APPSMITH_CLOUD_SERVICES_SIGNATURE appsmith.cloud_services.template_upload_auth_header = ${APPSMITH_CLOUD_SERVICES_TEMPLATE_UPLOAD_AUTH:} github_repo = ${APPSMITH_GITHUB_REPO:} -# MANDATORY!! No default properties are being provided for encryption password and salt for security. -# The server would not come up without these values provided through the environment variables. -encrypt.password=${APPSMITH_ENCRYPTION_PASSWORD:} -encrypt.salt=${APPSMITH_ENCRYPTION_SALT:} - # The following configurations are to help support prometheus scraping for monitoring management.endpoints.web.exposure.include=prometheus,metrics management.tracing.enabled=${APPSMITH_TRACING_ENABLED:false} diff --git a/app/server/appsmith-server/src/test/java/com/appsmith/server/services/DatasourceContextServiceTest.java b/app/server/appsmith-server/src/test/java/com/appsmith/server/services/DatasourceContextServiceTest.java index d813c3da1556..d0cc18c2d2c5 100644 --- a/app/server/appsmith-server/src/test/java/com/appsmith/server/services/DatasourceContextServiceTest.java +++ b/app/server/appsmith-server/src/test/java/com/appsmith/server/services/DatasourceContextServiceTest.java @@ -1,6 +1,7 @@ package com.appsmith.server.services; import com.appsmith.external.constants.PluginConstants; +import com.appsmith.external.helpers.EncryptionHelper; import com.appsmith.external.helpers.restApiUtils.connections.APIConnection; import com.appsmith.external.helpers.restApiUtils.connections.APIConnectionFactory; import com.appsmith.external.helpers.restApiUtils.connections.BearerTokenAuthentication; @@ -17,7 +18,6 @@ import com.appsmith.external.models.OAuth2; import com.appsmith.external.models.UpdatableConnection; import com.appsmith.external.plugins.PluginExecutor; -import com.appsmith.external.services.EncryptionService; import com.appsmith.server.applications.base.ApplicationService; import com.appsmith.server.datasources.base.DatasourceService; import com.appsmith.server.datasourcestorages.base.DatasourceStorageService; @@ -73,9 +73,6 @@ @Slf4j public class DatasourceContextServiceTest { - @Autowired - EncryptionService encryptionService; - @Autowired WorkspaceRepository workspaceRepository; @@ -287,7 +284,7 @@ public void checkDecryptionOfAuthenticationDTOTest() { DBAuth encryptedAuthentication = (DBAuth) savedDatasourceStorageDTO .getDatasourceConfiguration() .getAuthentication(); - assertEquals(password, encryptionService.decryptString(encryptedAuthentication.getPassword())); + assertEquals(password, EncryptionHelper.decrypt(encryptedAuthentication.getPassword())); }) .verifyComplete(); } diff --git a/app/server/appsmith-server/src/test/java/com/appsmith/server/services/DatasourceServiceTest.java b/app/server/appsmith-server/src/test/java/com/appsmith/server/services/DatasourceServiceTest.java index 5744932c5d0f..c23d8aa2fbf3 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 @@ -1,5 +1,6 @@ package com.appsmith.server.services; +import com.appsmith.external.helpers.EncryptionHelper; import com.appsmith.external.models.ActionConfiguration; import com.appsmith.external.models.ActionDTO; import com.appsmith.external.models.Connection; @@ -14,7 +15,6 @@ import com.appsmith.external.models.Policy; import com.appsmith.external.models.SSLDetails; import com.appsmith.external.models.UploadedFile; -import com.appsmith.external.services.EncryptionService; import com.appsmith.server.acl.AclPermission; import com.appsmith.server.applications.base.ApplicationService; import com.appsmith.server.constants.FieldName; @@ -103,9 +103,6 @@ public class DatasourceServiceTest { @Autowired ApplicationPageService applicationPageService; - @Autowired - EncryptionService encryptionService; - @Autowired LayoutActionService layoutActionService; @@ -1095,7 +1092,7 @@ public void checkEncryptionOfAuthenticationDTOTest() { DBAuth authentication = (DBAuth) datasourceStorageDTO.getDatasourceConfiguration().getAuthentication(); assertThat(authentication.getUsername()).isEqualTo(username); - assertThat(encryptionService.decryptString(authentication.getPassword())) + assertThat(EncryptionHelper.decrypt(authentication.getPassword())) .isEqualTo(password); }) .verifyComplete(); @@ -1226,7 +1223,7 @@ public void checkEncryptionOfAuthenticationDTOAfterUpdate() { datasourceStorageDTO.getDatasourceConfiguration().getAuthentication(); assertThat(authentication.getUsername()).isEqualTo(username); - assertThat(password).isEqualTo(encryptionService.decryptString(authentication.getPassword())); + assertThat(password).isEqualTo(EncryptionHelper.decrypt(authentication.getPassword())); }) .verifyComplete(); } 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 0478ddb85226..bde3812eaeba 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 @@ -1,7 +1,7 @@ package com.appsmith.server.services; +import com.appsmith.external.helpers.EncryptionHelper; import com.appsmith.external.models.Policy; -import com.appsmith.external.services.EncryptionService; import com.appsmith.server.applications.base.ApplicationService; import com.appsmith.server.configurations.CommonConfig; import com.appsmith.server.configurations.WithMockAppsmithUser; @@ -92,9 +92,6 @@ public class UserServiceTest { @Autowired PasswordEncoder passwordEncoder; - @Autowired - EncryptionService encryptionService; - @Autowired UserDataService userDataService; @@ -552,7 +549,7 @@ private String getEncodedToken(String emailAddress, String token) { nameValuePairs.add(new BasicNameValuePair("email", emailAddress)); nameValuePairs.add(new BasicNameValuePair("token", token)); String urlParams = WWWFormCodec.format(nameValuePairs, StandardCharsets.UTF_8); - return encryptionService.encryptString(urlParams); + return EncryptionHelper.encrypt(urlParams); } @Test
ed23046dedc0b4ca962873450217436643676be3
2024-04-08 14:34:53
Aman Agarwal
fix: self signed certificates value set in the props (#32474)
false
self signed certificates value set in the props (#32474)
fix
diff --git a/app/client/src/pages/Editor/DataSourceEditor/RestAPIDatasourceForm.tsx b/app/client/src/pages/Editor/DataSourceEditor/RestAPIDatasourceForm.tsx index 1f92ee01531e..58246322cb2e 100644 --- a/app/client/src/pages/Editor/DataSourceEditor/RestAPIDatasourceForm.tsx +++ b/app/client/src/pages/Editor/DataSourceEditor/RestAPIDatasourceForm.tsx @@ -751,7 +751,9 @@ class DatasourceRestAPIEditor extends React.Component<Props> { </FormInputContainer> )} {isConnectSelfSigned && ( - <FormInputContainer data-location-id={btoa("selfsignedcert")}> + <FormInputContainer + data-location-id={btoa("authentication.useSelfSignedCert")} + > {this.renderCheckboxViaFormControl( "authentication.useSelfSignedCert", "Use Self-Signed Certificate for Authorization requests", diff --git a/app/client/src/transformers/RestAPIDatasourceFormTransformer.ts b/app/client/src/transformers/RestAPIDatasourceFormTransformer.ts index 6149cd1b0881..9274983ef0e0 100644 --- a/app/client/src/transformers/RestAPIDatasourceFormTransformer.ts +++ b/app/client/src/transformers/RestAPIDatasourceFormTransformer.ts @@ -259,6 +259,7 @@ const datasourceToFormAuthentication = ( authentication.sendScopeWithRefreshToken || false, refreshTokenClientCredentialsLocation: authentication.refreshTokenClientCredentialsLocation || "BODY", + useSelfSignedCert: authentication.useSelfSignedCert, }; if (isClientCredentials(authType, authentication)) { return {
6b003179e3c7fbb0992ca2cf96e2d857715cbac0
2023-04-03 13:58:03
akash-codemonk
fix: editor header border style (#21942)
false
editor header border style (#21942)
fix
diff --git a/app/client/src/pages/Editor/EditorHeader.tsx b/app/client/src/pages/Editor/EditorHeader.tsx index 667eb9c91cfd..8ad590542bf7 100644 --- a/app/client/src/pages/Editor/EditorHeader.tsx +++ b/app/client/src/pages/Editor/EditorHeader.tsx @@ -371,7 +371,7 @@ export function EditorHeader(props: EditorHeaderProps) { return ( <ThemeProvider theme={theme}> <HeaderWrapper - className="pl-1 pr-1" + className="pl-1 pr-1 overflow-hidden" data-testid="t--appsmith-editor-header" > <HeaderSection className="space-x-2">
db9d5724248be618f25de2e8b99dcdef9ab99af2
2024-08-16 19:53:57
Valera Melnikov
chore: use ads icons (#35633)
false
use ads icons (#35633)
chore
diff --git a/app/client/cypress/locators/HomePage.js b/app/client/cypress/locators/HomePage.js index 87b2178b1433..bbb0675551f4 100644 --- a/app/client/cypress/locators/HomePage.js +++ b/app/client/cypress/locators/HomePage.js @@ -86,7 +86,7 @@ export default { shareUserIcons: ".t--workspace-share-user-icons", toastMessage: "div.Toastify__toast", uploadLogo: "//div/form/input", - removeLogo: ".remove-button a span", + removeLogo: "[data-testid=t--remove-logo]", generalTab: "//li//span[text()='General']", membersTab: "//li//span[text()='Members']", cancelBtn: "//span[text()='Cancel']", @@ -105,5 +105,5 @@ export default { noEntityFound:".no-search-results", initialWorkspace:"[data-testid^='Untitled workspace']", initialApplication:"[data-testid^='Untitled application']", - _entitySearchBar:"[data-testid='t--application-search-input']"; + _entitySearchBar:"[data-testid='t--application-search-input']" }; diff --git a/app/client/packages/design-system/ads-old/create_story.sh b/app/client/packages/design-system/ads-old/create_story.sh deleted file mode 100755 index f878b5c58cc8..000000000000 --- a/app/client/packages/design-system/ads-old/create_story.sh +++ /dev/null @@ -1,10 +0,0 @@ -# usage ./create_story.sh -f <Folder name under src fodler> -while getopts f: flag -do - case "${flag}" in - f) folder=${OPTARG};; - esac -done - -echo "Creating story for folder: $folder" -cat story_template.txt >> src/$folder/$folder.stories.tsx diff --git a/app/client/packages/design-system/ads-old/package.json b/app/client/packages/design-system/ads-old/package.json index a5617c98bcae..1d9aa8be14f1 100644 --- a/app/client/packages/design-system/ads-old/package.json +++ b/app/client/packages/design-system/ads-old/package.json @@ -5,10 +5,8 @@ "main": "src/index.ts", "sideEffects": false, "scripts": { - "create-story": "./create_story.sh", "lint": "yarn g:lint", - "prettier": "yarn g:prettier", - "test:unit": "yarn g:jest" + "prettier": "yarn g:prettier" }, "contributors": [ "Albin <[email protected]>", diff --git a/app/client/packages/design-system/ads-old/src/AppIcon/index.tsx b/app/client/packages/design-system/ads-old/src/AppIcon/index.tsx index 664db42a9e57..f5819af08045 100644 --- a/app/client/packages/design-system/ads-old/src/AppIcon/index.tsx +++ b/app/client/packages/design-system/ads-old/src/AppIcon/index.tsx @@ -272,7 +272,7 @@ const ServerLineIcon = importRemixIcon( async () => import("remixicon-react/ServerLineIcon"), ); -enum Size { +export enum Size { xxs = "xxs", xs = "xs", small = "small", diff --git a/app/client/packages/design-system/ads-old/src/Breadcrumbs/index.tsx b/app/client/packages/design-system/ads-old/src/Breadcrumbs/index.tsx deleted file mode 100644 index f2a41f46365e..000000000000 --- a/app/client/packages/design-system/ads-old/src/Breadcrumbs/index.tsx +++ /dev/null @@ -1,118 +0,0 @@ -// TODO: In Phase 2, add a warn when this component doesn't have a <Router> component in it's ancestors -import type { ReactNode } from "react"; -import React from "react"; -import { Link, useLocation } from "react-router-dom"; -import styled from "styled-components"; -import Icon from "../Icon"; - -export interface BreadcrumbsProps { - items: { - href: string; - text: string; - }[]; -} -export interface BreadcrumbProps { - children: ReactNode; -} - -export const StyledBreadcrumbList = styled.ol` - list-style: none; - display: flex; - align-items: center; - font-size: 16px; - color: var(--ads-breadcrumbs-list-text-color); - margin-bottom: 23px; - - .breadcrumb-separator { - color: var(--ads-breadcrumbs-separator-text-color); - margin: auto 6px; - user-select: none; - } - - .t--breadcrumb-item { - &.active { - color: var(--ads-breadcrumbs-active-text-color); - font-size: 20px; - } - } -`; - -function BreadcrumbSeparator({ children, ...props }: { children: ReactNode }) { - return ( - <li className="breadcrumb-separator" {...props}> - {children} - </li> - ); -} - -function BreadcrumbItem({ children, ...props }: { children: ReactNode }) { - return ( - <li className="breadcrumb-item" {...props}> - {children} - </li> - ); -} - -function BreadcrumbList(props: BreadcrumbProps) { - let children = React.Children.toArray(props.children); - - children = children.map((child, index) => ( - <BreadcrumbItem key={`breadcrumb_item${index}`}>{child}</BreadcrumbItem> - )); - - const lastIndex = children.length - 1; - - const childrenNew = children.reduce((acc: ReactNode[], child, index) => { - const notLast = index < lastIndex; - - if (notLast) { - acc.push( - child, - <BreadcrumbSeparator key={`breadcrumb_sep${index}`}> - <Icon name="right-arrow-2" /> - </BreadcrumbSeparator>, - ); - } else { - acc.push(child); - } - return acc; - }, []); - - return ( - <StyledBreadcrumbList className="t--breadcrumb-list"> - {childrenNew} - </StyledBreadcrumbList> - ); -} - -function Breadcrumbs(props: BreadcrumbsProps) { - const { pathname } = useLocation(); - return ( - <BreadcrumbList> - {props.items.map(({ href, text }) => - href === pathname ? ( - <span - className={`t--breadcrumb-item ${ - href === pathname ? `active` : `` - }`} - key={href} - > - {text} - </span> - ) : ( - <Link - className={`t--breadcrumb-item ${ - href === pathname ? `active` : `` - }`} - key={href} - to={href} - > - {text} - </Link> - ), - )} - </BreadcrumbList> - ); -} - -export default Breadcrumbs; diff --git a/app/client/packages/design-system/ads-old/src/Button/Button.test.tsx b/app/client/packages/design-system/ads-old/src/Button/Button.test.tsx deleted file mode 100644 index db0dd798888d..000000000000 --- a/app/client/packages/design-system/ads-old/src/Button/Button.test.tsx +++ /dev/null @@ -1,46 +0,0 @@ -import React from "react"; -import "@testing-library/jest-dom"; -import { render, screen } from "@testing-library/react"; -import Button, { Size } from "./index"; -import { create } from "react-test-renderer"; - -describe("<Button /> component - render", () => { - it("renders the button component with text passed as input", () => { - render(<Button size={Size.medium} tag="button" text="Run" />); - expect(screen.getByRole("button")).toHaveTextContent("Run"); - }); -}); - -describe("<Button /> component - loading behaviour", () => { - it("calls the onclick handler when not in loading state", () => { - const fn = jest.fn(); - const tree = create( - <Button - isLoading={false} - onClick={fn} - size={Size.medium} - tag="button" - text="Run" - />, - ); - const button = tree.root.findByType("button"); - button.props.onClick(); - expect(fn.mock.calls.length).toBe(1); - }); - - it("does not call the onclick handler when in loading state", () => { - const fn = jest.fn(); - const tree = create( - <Button - isLoading - onClick={fn} - size={Size.medium} - tag="button" - text="Run" - />, - ); - const button = tree.root.findByType("button"); - button.props.onClick(); - expect(fn.mock.calls.length).toBe(0); - }); -}); diff --git a/app/client/packages/design-system/ads-old/src/Button/index.tsx b/app/client/packages/design-system/ads-old/src/Button/index.tsx deleted file mode 100644 index 2cb2f9278055..000000000000 --- a/app/client/packages/design-system/ads-old/src/Button/index.tsx +++ /dev/null @@ -1,581 +0,0 @@ -import React from "react"; -import _ from "lodash"; -import styled, { css } from "styled-components"; -import { Variant } from "../constants/variants"; -import type { CommonComponentProps } from "../types/common"; -import { Classes } from "../constants/classes"; -import type { IconName } from "../Icon"; -import Icon, { IconSize } from "../Icon"; -import Spinner from "../Spinner"; -import { typography } from "../constants/typography"; - -const smallButton = css` - font-size: ${typography.btnSmall.fontSize}px; - font-weight: ${typography.btnSmall.fontWeight}; - line-height: ${typography.btnSmall.lineHeight}px; - letter-spacing: ${typography.btnSmall.letterSpacing}px; -`; - -const mediumButton = css` - font-size: ${typography.btnMedium.fontSize}px; - font-weight: ${typography.btnMedium.fontWeight}; - line-height: ${typography.btnMedium.lineHeight}px; - letter-spacing: ${typography.btnMedium.letterSpacing}px; -`; - -const largeButton = css` - font-size: ${typography.btnLarge.fontSize}px; - font-weight: ${typography.btnLarge.fontWeight}; - line-height: ${typography.btnLarge.lineHeight}px; - letter-spacing: ${typography.btnLarge.letterSpacing}px; -`; - -export enum Category { - primary = "primary", - secondary = "secondary", - tertiary = "tertiary", -} - -export enum Size { - xxs = "xxs", - xs = "xs", - small = "small", - medium = "medium", - large = "large", -} - -interface stateStyleType { - bgColorPrimary: string; - borderColorPrimary: string; - txtColorPrimary: string; - bgColorSecondary: string; - borderColorSecondary: string; - txtColorSecondary: string; - bgColorTertiary: string; - borderColorTertiary: string; - txtColorTertiary: string; -} - -interface BtnColorType { - bgColor: string; - txtColor: string; - border: string; - outline: string; -} - -interface BtnFontType { - buttonFont: any; - padding: string; - height: number; -} - -export enum IconPositions { - left = "left", - right = "right", -} - -export type ButtonProps = CommonComponentProps & { - onClick?: (event: React.MouseEvent<HTMLElement>) => void; - text?: string; - category?: Category; - variant?: Variant; - className?: string; - icon?: IconName; - size?: Size; - fill?: boolean; - href?: string; - tabIndex?: number; - tag?: "a" | "button"; - type?: "submit" | "reset" | "button"; - target?: string; - height?: string; - width?: string; - iconPosition?: IconPositions; -}; - -const defaultProps = { - category: Category.primary, - variant: Variant.info, - size: Size.small, - isLoading: false, - disabled: false, - fill: undefined, - tag: "a", -}; - -interface buttonVariant { - main: string; - light: string; - dark: string; - darker: string; - darkest: string; -} - -interface ButtonColorType { - [index: string]: buttonVariant; -} - -const ButtonColors: ButtonColorType = { - info: { - main: "var(--ads-color-brand)", - light: "var(--ads-old-color-hot-cinnamon)", - dark: "var(--ads-color-brand-hover)", - darker: "var(--ads-color-brand-disabled)", - darkest: "var(--ads-old-color-pot-pourri)", - }, - success: { - main: "var(--ads-old-color-jade)", - light: "var(--ads-old-color-fun-green)", - dark: "var(--ads-old-color-fun-green-2)", - darker: "var(--ads-old-color-granny-apple)", - darkest: "var(--ads-old-color-foam)", - }, - warning: { - main: "var(--ads-old-color-sun)", - light: "var(--ads-old-color-yellow-sea)", - dark: "var(--ads-old-color-yellow-sea)", - darker: "var(--ads-old-color-champagne)", - darkest: "var(--ads-old-color-early-dawn)", - }, - danger: { - main: "var(--ads-old-color-pomegranate)", - light: "var(--ads-old-color-milano-red)", - dark: "var(--ads-old-color-milano-red-2)", - darker: "var(--ads-old-color-cinderella)", - darkest: "var(--ads-old-color-fair-pink)", - }, - secondary: { - main: "var(--ads-old-color-mid-gray)", - light: "var(--ads-old-color-gray-10)", - dark: "var(--ads-color-black-5)", - darker: "var(--ads-old-color-gallery)", - darkest: "var(--ads-color-black-450)", - }, - tertiary: { - main: "var(--ads-old-color-mid-gray)", - light: "var(--ads-old-color-gray-10)", - dark: "var(--ads-color-black-5)", - darker: "var(--ads-old-color-gallery)", - darkest: "var(--ads-color-black-450)", - }, -}; - -const WhiteTextVariants = [Variant.danger, Variant.warning, Variant.success]; - -const getDisabledStyles = (props: ButtonProps) => { - const variant = props.variant ?? defaultProps.variant; - const category = props.category ?? defaultProps.category; - - const stylesByCategory = { - [Category.primary]: { - txtColorPrimary: "var(--ads-old-color-gray-7)", - bgColorPrimary: ButtonColors[variant].darker, - borderColorPrimary: ButtonColors[variant].darker, - }, - [Category.secondary]: { - txtColorSecondary: "var(--ads-color-black-500)", - bgColorSecondary: "var(--ads-color-black-50)", - borderColorSecondary: "var(--ads-color-black-300)", - }, - [Category.tertiary]: { - txtColorTertiary: "var(--ads-color-black-500)", - bgColorTertiary: "var(--ads-color-black-0)", - borderColorTertiary: "transparent", - }, - }; - - return stylesByCategory[category]; -}; - -const getMainStateStyles = (props: ButtonProps) => { - const variant = props.variant ?? defaultProps.variant; - const category = props.category ?? defaultProps.category; - - const stylesByCategory = { - [Category.primary]: { - bgColorPrimary: ButtonColors[variant].main, - borderColorPrimary: ButtonColors[variant].main, - txtColorPrimary: - WhiteTextVariants.indexOf(variant) === -1 - ? "var(--ads-color-brand-text)" - : "var(--ads-color-black-0)", - }, - [Category.secondary]: { - bgColorSecondary: "var(--ads-color-black-0)", - borderColorSecondary: "var(--ads-color-black-300)", - txtColorSecondary: "var(--ads-color-black-700)", - }, - [Category.tertiary]: { - bgColorTertiary: "var(--ads-color-black-0)", - borderColorTertiary: "transparent", - txtColorTertiary: "var(--ads-color-black-700)", - }, - }; - - return stylesByCategory[category]; -}; - -const getHoverStateStyles = (props: ButtonProps) => { - const variant = props.variant ?? defaultProps.variant; - const category = props.category ?? defaultProps.category; - - const stylesByCategory = { - [Category.primary]: { - bgColorPrimary: ButtonColors[variant].dark, - txtColorPrimary: - WhiteTextVariants.indexOf(variant) === -1 - ? "var(--ads-color-brand-text)" - : "var(--ads-color-black-0)", - borderColorPrimary: ButtonColors[variant].dark, - }, - [Category.secondary]: { - bgColorSecondary: "var(--ads-color-black-50)", - txtColorSecondary: "var(--ads-color-black-700)", - borderColorSecondary: "var(--ads-color-black-300)", - }, - [Category.tertiary]: { - bgColorTertiary: "var(--ads-color-black-100)", - txtColorTertiary: "var(--ads-color-black-700)", - borderColorTertiary: "transparent", - }, - }; - - return stylesByCategory[category]; -}; - -const getActiveStateStyles = (props: ButtonProps) => { - const variant = props.variant ?? defaultProps.variant; - const category = props.category ?? defaultProps.category; - - const stylesByCategory = { - [Category.primary]: { - bgColorPrimary: ButtonColors[variant].dark, - borderColorPrimary: ButtonColors[variant].main, - txtColorPrimary: - WhiteTextVariants.indexOf(variant) === -1 - ? "var(--ads-color-brand-text)" - : "var(--ads-color-black-0)", - }, - [Category.secondary]: { - bgColorSecondary: "var(--ads-color-black-100)", - borderColorSecondary: "var(--ads-color-black-600)", - txtColorSecondary: "var(--ads-color-black-800)", - }, - [Category.tertiary]: { - bgColorTertiary: "var(--ads-color-black-200)", - borderColorTertiary: "transparent", - txtColorTertiary: "var(--ads-color-black-800)", - }, - }; - - return stylesByCategory[category]; -}; - -const stateStyles = (props: ButtonProps, stateArg: string): stateStyleType => { - const styles = { - bgColorPrimary: "", - borderColorPrimary: "", - txtColorPrimary: "", - bgColorSecondary: "", - borderColorSecondary: "", - txtColorSecondary: "", - bgColorTertiary: "", - borderColorTertiary: "", - txtColorTertiary: "", - }; - const state = - props.isLoading || props.disabled - ? "disabled" - : (stateArg as keyof typeof stylesByState); - const stylesByState = { - disabled: getDisabledStyles(props), - main: getMainStateStyles(props), - hover: getHoverStateStyles(props), - active: getActiveStateStyles(props), - }; - - return { - ...styles, - ...stylesByState[state], - }; -}; - -const btnColorStyles = (props: ButtonProps, state: string): BtnColorType => { - let bgColor = "", - txtColor = "", - border = "", - outline = ""; - switch (props.category) { - case Category.primary: - bgColor = stateStyles(props, state).bgColorPrimary; - txtColor = stateStyles(props, state).txtColorPrimary; - border = `1.2px solid ${stateStyles(props, state).borderColorPrimary}`; - break; - case Category.secondary: - bgColor = stateStyles(props, state).bgColorSecondary; - txtColor = stateStyles(props, state).txtColorSecondary; - border = `1.2px solid ${stateStyles(props, state).borderColorSecondary}`; - outline = "2px solid var(--ads-color-blue-150)"; - break; - case Category.tertiary: - bgColor = stateStyles(props, state).bgColorTertiary; - txtColor = stateStyles(props, state).txtColorTertiary; - border = `1.2px solid ${stateStyles(props, state).borderColorTertiary}`; - outline = "2px solid var(--ads-color-blue-150)"; - break; - } - return { bgColor, txtColor, border, outline }; -}; - -const getPaddingBySize = (props: ButtonProps) => { - const paddingBySize = { - [Size.small]: `0px var(--ads-spaces-3)`, - [Size.medium]: `0px var(--ads-spaces-7)`, - [Size.large]: `0px 26px`, - }; - const paddingBySizeForJustIcon = { - [Size.small]: `0px var(--ads-spaces-1)`, - [Size.medium]: `0px var(--ads-spaces-2)`, - [Size.large]: `0px var(--ads-spaces-3)`, - }; - - const isIconOnly = !props.text && props.icon; - const paddingConfig = isIconOnly ? paddingBySizeForJustIcon : paddingBySize; - - const iSizeInConfig = - // @ts-expect-error fix this the next time the file is edited - Object.keys(paddingConfig).indexOf(props.size != null || "") !== -1; - const size: any = - props.size != null && iSizeInConfig ? props.size : Size.small; - - return paddingConfig[size as keyof typeof paddingConfig]; -}; - -const getHeightBySize = (props: ButtonProps) => { - const heightBySize = { - [Size.small]: 20, - [Size.medium]: 30, - [Size.large]: 38, - }; - - const iSizeInConfig = - // @ts-expect-error fix this the next time the file is edited - Object.keys(heightBySize).indexOf(props.size != null || "") !== -1; - const size: any = - props.size != null && iSizeInConfig ? props.size : Size.small; - - return heightBySize[size as keyof typeof heightBySize]; -}; - -const getBtnFontBySize = (props: ButtonProps) => { - const fontBySize = { - [Size.small]: smallButton, - [Size.medium]: mediumButton, - [Size.large]: largeButton, - }; - - const iSizeInConfig = - // @ts-expect-error fix this the next time the file is edited - Object.keys(fontBySize).indexOf(props.size != null || "") !== -1; - const size: any = - props.size != null && iSizeInConfig ? props.size : Size.small; - - return fontBySize[size as keyof typeof fontBySize]; -}; - -const btnFontStyles = (props: ButtonProps): BtnFontType => { - const padding = getPaddingBySize(props); - const height = getHeightBySize(props); - const buttonFont = getBtnFontBySize(props); - - return { buttonFont, padding, height }; -}; - -const ButtonStyles = css<ButtonProps>` - user-select: none; - width: ${(props) => - props.width ? props.width : props.fill ? "100%" : "auto"}; - height: ${(props) => props.height || btnFontStyles(props).height}px; - border: none; - text-decoration: none; - outline: none; - text-transform: uppercase; - background-color: ${(props) => btnColorStyles(props, "main").bgColor}; - color: ${(props) => btnColorStyles(props, "main").txtColor}; - border: ${(props) => btnColorStyles(props, "main").border}; - border-radius: 0; - ${(props) => btnFontStyles(props).buttonFont}; - padding: ${(props: ButtonProps) => btnFontStyles(props).padding}; - .${Classes.ICON}:not([name="no-response"]) { - svg { - fill: ${(props: ButtonProps) => btnColorStyles(props, "main").txtColor}; - } - } - &, - & * { - cursor: ${(props) => - props.isLoading || props.disabled ? `not-allowed` : `pointer`}; - } - &:hover { - text-decoration: none; - background-color: ${(props: ButtonProps) => - btnColorStyles(props, "hover").bgColor}; - color: ${(props: ButtonProps) => btnColorStyles(props, "hover").txtColor}; - border: ${(props: ButtonProps) => btnColorStyles(props, "hover").border}; - .${Classes.ICON} { - fill: ${(props: ButtonProps) => btnColorStyles(props, "hover").txtColor}; - } - } - &:focus-visible { - outline: ${(props: ButtonProps) => btnColorStyles(props, "active").outline}; - outline-offset: 0px; - } - font-style: normal; - &:active { - background-color: ${(props: ButtonProps) => - btnColorStyles(props, "active").bgColor}; - color: ${(props: ButtonProps) => btnColorStyles(props, "active").txtColor}; - border: ${(props: ButtonProps) => btnColorStyles(props, "active").border}; - .${Classes.ICON} { - fill: ${(props: ButtonProps) => btnColorStyles(props, "active").txtColor}; - } - } - display: flex; - align-items: center; - justify-content: center; - position: relative; - .${Classes.SPINNER} { - position: absolute; - left: 0; - right: 0; - margin-left: auto; - margin-right: auto; - circle { - stroke: var(--ads-old-color-gray-7); - } - } - .t--right-icon { - margin-left: var(--ads-spaces-1); - } - .t--left-icon { - margin-right: var(--ads-spaces-1); - } -`; - -export const StyledButton = styled("button")` - ${ButtonStyles} -`; - -const StyledLinkButton = styled("a")` - ${ButtonStyles} -`; - -export const VisibilityWrapper = styled.div` - visibility: hidden; -`; - -const IconSizeProp = (size?: Size) => { - const sizeMapping = { - [Size.xxs]: IconSize.XXS, - [Size.xs]: IconSize.XS, - [Size.small]: IconSize.SMALL, - [Size.medium]: IconSize.MEDIUM, - [Size.large]: IconSize.LARGE, - }; - - return size != null ? sizeMapping[size] : IconSize.SMALL; -}; - -function TextLoadingState({ text }: { text?: string }) { - return <VisibilityWrapper>{text}</VisibilityWrapper>; -} - -function IconLoadingState({ icon, size }: { size?: Size; icon?: IconName }) { - return <Icon invisible name={icon} size={IconSizeProp(size)} />; -} - -const getIconContent = (props: ButtonProps, rightPosFlag = false) => - props.icon ? ( - props.isLoading ? ( - <IconLoadingState {...props} /> - ) : ( - <Icon - className={rightPosFlag ? "t--right-icon" : "t--left-icon"} - name={props.icon} - size={IconSizeProp(props.size)} - /> - ) - ) : null; - -const getTextContent = (props: ButtonProps) => - props.text ? ( - props.isLoading ? ( - <TextLoadingState text={props.text} /> - ) : ( - props.text - ) - ) : null; - -const getButtonContent = (props: ButtonProps) => { - const iconPos = - props.iconPosition != null - ? props.iconPosition - : props.tag === "a" - ? IconPositions.right - : IconPositions.left; - return ( - <> - {iconPos === IconPositions.left && getIconContent(props)} - <span>{getTextContent(props)}</span> - {iconPos === IconPositions.right && getIconContent(props, true)} - {props.isLoading ? <Spinner size={IconSizeProp(props.size)} /> : null} - </> - ); -}; - -function ButtonComponent(props: ButtonProps) { - const { className, cypressSelector, isLoading, onClick } = props; - const filteredProps = _.omit(props, ["fill"]); - return ( - <StyledButton - className={className} - data-cy={cypressSelector} - {...filteredProps} - onClick={(e: React.MouseEvent<HTMLElement>) => - onClick && !isLoading && onClick(e) - } - > - {getButtonContent(props)} - </StyledButton> - ); -} - -function LinkButtonComponent(props: ButtonProps) { - const { className, cypressSelector, href, onClick } = props; - const filteredProps = _.omit(props, ["fill"]); - return ( - <StyledLinkButton - className={className} - data-cy={cypressSelector} - href={href} - {...filteredProps} - onClick={(e: React.MouseEvent<HTMLElement>) => - !props.disabled && onClick && onClick(e) - } - > - {getButtonContent(props)} - </StyledLinkButton> - ); -} - -function Button(props: ButtonProps) { - return props.tag === "button" ? ( - <ButtonComponent {...props} /> - ) : ( - <LinkButtonComponent {...props} /> - ); -} - -export default Button; - -Button.defaultProps = defaultProps; diff --git a/app/client/packages/design-system/ads-old/src/DialogComponent/index.tsx b/app/client/packages/design-system/ads-old/src/DialogComponent/index.tsx index dd6110ef9fea..1b20c25ce132 100644 --- a/app/client/packages/design-system/ads-old/src/DialogComponent/index.tsx +++ b/app/client/packages/design-system/ads-old/src/DialogComponent/index.tsx @@ -2,8 +2,8 @@ import type { ReactNode, PropsWithChildren } from "react"; import React, { useState, useEffect } from "react"; import styled from "styled-components"; import { Dialog, Classes } from "@blueprintjs/core"; -import type { IconName } from "../Icon"; -import Icon, { IconSize } from "../Icon"; +import type { IconNames } from "@appsmith/ads"; +import { Icon } from "@appsmith/ads"; import { typography } from "../constants/typography"; type DialogProps = PropsWithChildren<{ @@ -115,7 +115,7 @@ interface DialogComponentProps { title?: string; headerIcon?: { clickable?: boolean; - name: IconName; + name: IconNames; fillColor?: string; hoverColor?: string; bgColor?: string; @@ -156,11 +156,9 @@ export function DialogComponent(props: DialogComponentProps) { const headerIcon = props.headerIcon ? ( <HeaderIconWrapper bgColor={props.headerIcon.bgColor}> <Icon - clickable={props.headerIcon?.clickable} - fillColor={props.headerIcon.fillColor} - hoverFillColor={props.headerIcon.hoverColor} + color={props.headerIcon.fillColor} name={props.headerIcon.name} - size={IconSize.XL} + size="lg" /> </HeaderIconWrapper> ) : null; diff --git a/app/client/packages/design-system/ads-old/src/DisplayImageUpload/index.tsx b/app/client/packages/design-system/ads-old/src/DisplayImageUpload/index.tsx index d15803695406..670c851a312f 100644 --- a/app/client/packages/design-system/ads-old/src/DisplayImageUpload/index.tsx +++ b/app/client/packages/design-system/ads-old/src/DisplayImageUpload/index.tsx @@ -12,7 +12,7 @@ import { getTypographyByKey } from "../constants/typography"; // eslint-disable-next-line @typescript-eslint/no-restricted-imports import { ReactComponent as ProfileImagePlaceholder } from "../assets/icons/others/profile-placeholder.svg"; -import Icon, { IconSize } from "../Icon"; +import { Spinner } from "@appsmith/ads"; interface Props { onChange: (file: File) => void; @@ -241,7 +241,7 @@ export default function DisplayImageUpload({ <Suspense fallback={ <SpinnerContainer> - <Icon name={"loader"} size={IconSize.XL} /> + <Spinner size="lg" /> </SpinnerContainer> } > diff --git a/app/client/packages/design-system/ads-old/src/Dropdown/index.tsx b/app/client/packages/design-system/ads-old/src/Dropdown/index.tsx index c3a9afc096cd..ee498018b2d2 100644 --- a/app/client/packages/design-system/ads-old/src/Dropdown/index.tsx +++ b/app/client/packages/design-system/ads-old/src/Dropdown/index.tsx @@ -1,27 +1,5 @@ -import type { ReactElement } from "react"; -import React, { useState, useEffect, useCallback, useRef } from "react"; -import type { IconName } from "../Icon"; -import Icon, { IconSize } from "../Icon"; -import type { CommonComponentProps } from "../types/common"; -import { SubTextPosition, DSEventTypes, emitDSEvent } from "../types/common"; -import { Classes, replayHighlightClass } from "../constants/classes"; -import type { TextProps } from "../Text"; -import Text, { TextType } from "../Text"; -import type { PopperBoundary } from "@blueprintjs/core"; -import { Popover, Position } from "@blueprintjs/core"; -import { typography } from "../constants/typography"; -import styled from "styled-components"; -import SearchComponent from "../SearchComponent"; -import Spinner from "../Spinner"; -import Tooltip from "../Tooltip"; -import SegmentHeader from "../ListSegmentHeader"; -import { debounce, isArray } from "lodash"; -import "./styles.css"; -import { importSvg } from "../utils/icon-loadables"; - -const Check = importSvg( - async () => import("../assets/icons/control/checkmark.svg"), -); +import type { IconSizes, IconNames } from "@appsmith/ads"; +import type { SubTextPosition } from "../types/common"; export type DropdownOnSelect = ( value?: string, @@ -33,12 +11,12 @@ export interface DropdownOption { label?: string; value?: string; id?: string; - icon?: IconName; + icon?: IconNames; leftElement?: string; searchText?: string; subText?: string; subTextPosition?: SubTextPosition; - iconSize?: IconSize; + iconSize?: IconSizes; iconColor?: string; onSelect?: DropdownOnSelect; data?: any; @@ -49,13 +27,6 @@ export interface DropdownOption { link?: string; } -export interface DropdownSearchProps { - enableSearch?: boolean; - searchPlaceholder?: string; - onSearch?: (value: any) => void; - searchAutoFocus?: boolean; -} - export interface RenderDropdownOptionType { index?: number; option: DropdownOption | DropdownOption[]; @@ -66,1315 +37,3 @@ export interface RenderDropdownOptionType { optionWidth: string; isHighlighted?: boolean; } - -export type RenderOption = ({ - hasError, - index, - option, - optionClickHandler, - optionWidth, -}: RenderDropdownOptionType) => ReactElement<any, any>; - -export type DropdownProps = CommonComponentProps & - DropdownSearchProps & { - options: DropdownOption[]; - selected: DropdownOption | DropdownOption[]; - onSelect?: DropdownOnSelect; - isMultiSelect?: boolean; - width?: string; - height?: string; - showLabelOnly?: boolean; - labelRenderer?: (selected: Partial<DropdownOption>[]) => JSX.Element; - optionWidth?: string; - dropdownHeight?: string; - dropdownMaxHeight?: string; - showDropIcon?: boolean; - closeOnSpace?: boolean; - dropdownTriggerIcon?: React.ReactNode; - containerClassName?: string; - headerLabel?: string; - SelectedValueNode?: typeof DefaultDropDownValueNode; - bgColor?: string; - renderOption?: RenderOption; - isLoading?: boolean; - hasError?: boolean; // should be displayed as error status without error message - errorMsg?: string; // If errorMsg is defined, we show dropDown's error state with the message. - placeholder?: string; - helperText?: string; - wrapperBgColor?: string; - /** - * if fillOptions is true, - * dropdown popover width will be same as dropdown width - * @type {boolean} - */ - fillOptions?: boolean; - dontUsePortal?: boolean; - hideSubText?: boolean; - removeSelectedOption?: DropdownOnSelect; - boundary?: PopperBoundary; - defaultIcon?: IconName; - allowDeselection?: boolean; //prevents de-selection of the selected option - truncateOption?: boolean; // enabled wrapping and adding tooltip on option item of dropdown menu - portalClassName?: string; - portalContainer?: HTMLElement; - customBadge?: JSX.Element; - selectedHighlightBg?: string; - showEmptyOptions?: boolean; - }; -export interface DefaultDropDownValueNodeProps { - selected: DropdownOption | DropdownOption[]; - showLabelOnly?: boolean; - labelRenderer?: (selected: Partial<DropdownOption>[]) => JSX.Element; - isMultiSelect?: boolean; - isOpen?: boolean; - hasError?: boolean; - renderNode?: RenderOption; - removeSelectedOptionClickHandler?: (option: DropdownOption) => void; - placeholder?: string; - showDropIcon?: boolean; - optionWidth: string; - hideSubText?: boolean; -} - -export interface RenderDropdownOptionType { - option: DropdownOption | DropdownOption[]; - optionClickHandler?: (dropdownOption: DropdownOption) => void; -} - -/** - * checks if ellipsis is active - * this function is meant for checking the existence of ellipsis by CSS. - * Since ellipsis by CSS are not part of DOM, we are checking with scroll width\height and offsetidth\height. - * ScrollWidth\ScrollHeight is always greater than the offsetWidth\OffsetHeight when ellipsis made by CSS is active. - * Using clientWidth to fix this https://stackoverflow.com/a/21064102/8692954 - * @param element - */ -const isEllipsisActive = (element: HTMLElement | null) => { - return element && element.clientWidth < element.scrollWidth; -}; - -const DropdownTriggerWrapper = styled.div<{ - isOpen: boolean; - disabled?: boolean; -}>` - height: 100%; - display: flex; - align-items: center; - justify-content: space-between; - cursor: pointer; - ${(props) => - props.isOpen && !props.disabled - ? ` - box-sizing: border-box; - border: 1px solid var(--ads-dropdown-default-dropdown-trigger-border-color); - ` - : null}; - .${Classes.TEXT} { - ${(props) => - props.disabled - ? `color: var(--ads-dropdown-disabled-header-text-color)` - : `color: var(--ads-dropdown-default-header-text-color)`}; - } -`; - -const StyledIcon = styled(Icon)` - width: 18px; - height: 18px; - &:hover { - background-color: var(--ads-dropdown-default-close-hover-background-color); - } -`; -const SquareBox = styled.div<{ - checked: boolean; - backgroundColor?: string; - borderColor?: string; -}>` - width: 16px; - height: 16px; - box-sizing: border-box; - margin-right: 10px; - background-color: ${(props) => { - if (props.backgroundColor) return props.backgroundColor; - props.checked ? "var(--ads-color-black-900)" : "var(--ads-color-black-0)"; - }}; - border: 1.4px solid; - border-color: ${(props) => { - if (props.borderColor) return props.borderColor; - props.checked ? "var(--ads-color-black-900)" : "var(--ads-color-black-400)"; - }}; - flex: 0 0 auto; - & svg { - display: ${(props) => (props.checked ? "block" : "none")}; - width: 14px; - height: 14px; - - & path { - fill: var(--ads-color-brand-text); - } - } -`; - -const Selected = styled.div<{ - isOpen: boolean; - disabled?: boolean; - height: string; - bgColor?: string; - hasError?: boolean; - selected?: boolean; - isLoading?: boolean; - isMultiSelect?: boolean; -}>` - padding: var(--ads-spaces-2) var(--ads-spaces-3); - background: ${(props) => { - if (props.disabled) { - return "var(--ads-dropdown-disabled-header-background-color)"; - } else if (props.hasError) { - return "var(--ads-old-color-fair-pink)"; - } - return props.bgColor || "var(--ads-color-black-0)"; - }}; - pointer-events: ${(props) => (props.disabled ? "none" : "auto")}; - box-sizing: border-box; - display: flex; - align-items: center; - justify-content: space-between; - width: 100%; - min-height: ${(props) => props.height}; - ${(props) => - props.isMultiSelect && - ` - min-height: 36px; - padding: 4px 8px; - `} - cursor: ${(props) => - props.disabled || props.isLoading ? "not-allowed" : "pointer"}; - ${(props) => - props.hasError - ? `.sub-text { - color: var(--ads-danger-main) !important; - }` - : ""} - ${(props) => - props.hasError - ? `border: 1px solid var(--ads-danger-main)` - : props.isOpen - ? `border: 1px solid ${ - !!props.bgColor - ? props.bgColor - : "var(--appsmith-input-focus-border-color)" - }` - : props.disabled - ? `border: 1px solid var(--ads-dropdown-disabled-header-background-color)` - : `border: 1px solid ${ - !!props.bgColor ? props.bgColor : "var(--ads-color-black-250)" - }`}; - .${Classes.TEXT} { - text-overflow: ellipsis; - white-space: nowrap; - overflow: hidden; - width: calc(100% - 10px); - ${(props) => - props.disabled - ? `color: var(--ads-dropdown-disabled-header-text-color)` - : `color: ${ - !!props.bgColor - ? "var(--ads-color-black-0)" - : props.selected - ? "var(--ads-dropdown-selected-header-text-color)" - : "var(--ads-dropdown-default-header-text-color)" - }`}; - } - &:hover { - background: ${(props) => - !props.isMultiSelect - ? props.hasError - ? "var(--ads-old-color-fair-pink)" - : "var(--ads-dropdown-hover-background-color)" - : "var(--ads-color-black-0)"}; - } -`; - -export const DropdownContainer = styled.div<{ - disabled?: boolean; - width: string; - height?: string; -}>` - width: ${(props) => props.width}; - height: ${(props) => props.height || `auto`}; - position: relative; - ${({ disabled }) => (disabled ? "cursor: not-allowed;" : "")} - span.bp3-popover-target { - display: inline-block; - width: 100%; - height: 100%; - } - span.bp3-popover-target div { - height: 100%; - } - span.bp3-popover-wrapper { - width: 100%; - } - &:focus ${Selected} { - ${({ disabled }) => - !disabled - ? "border: 1px solid var(--appsmith-input-focus-border-color);" - : ""}; - } - - ${({ disabled }) => { - if (disabled) { - return ` - &:focus { - outline: none; - } - `; - } - }} -`; - -const DropdownSelect = styled.div``; - -export const DropdownWrapper = styled.div<{ - width: string; - isOpen: boolean; - wrapperBgColor?: string; -}>` - width: ${(props) => props.width}; - z-index: 1; - background-color: ${(props) => - props.wrapperBgColor ? props.wrapperBgColor : "var(--ads-color-black-0)"}; - border: 1px solid var(--ads-dropdown-default-menu-border-color); - overflow: hidden; - overflow-y: auto; - box-shadow: - 0px 12px 16px -4px rgba(0, 0, 0, 0.1), - 0px 4px 6px -2px rgba(0, 0, 0, 0.05); - display: ${(props) => (props.isOpen ? "inline-block" : "none")}; - .dropdown-search { - width: 100%; - input { - height: 32px; - font-size: 14px !important; - color: var(--ads-old-color-gray-10) !important; - padding-left: 36px !important; - border: 1.2px solid var(--ads-color-black-200); - &:hover { - background: var(--ads-color-black-50); - } - &:focus { - color: var(--ads-color-black-900); - border: 1.2px solid var(--ads-color-black-900); - } - } - .bp3-icon-search { - width: 32px; - height: 32px; - margin: 0px; - display: flex; - align-items: center; - justify-content: center; - svg { - width: 14px; - path { - fill: var(--ads-color-black-700); - } - } - } - } -`; - -const SearchComponentWrapper = styled.div` - padding: 8px; -`; - -const DropdownOptionsWrapper = styled.div<{ - maxHeight?: string; - height: string; -}>` - display: flex; - flex-direction: column; - height: ${(props) => props.height}; - max-height: ${(props) => props.maxHeight}; - overflow-y: auto; - overflow-x: hidden; - .ds--dropdown-tooltip > span { - width: 100%; - &:focus { - outline: none; - } - & > .t--dropdown-option:focus { - outline: none; - } - } - .ds--dropdown-tooltip { - &:focus { - outline: none; - } - } -`; - -const StyledSubText = styled(Text)<{ - showDropIcon?: boolean; - subTextPosition?: SubTextPosition; -}>` - ${(props) => - props.subTextPosition === SubTextPosition.BOTTOM - ? "margin-top: 3px" - : "margin-left: auto"}; - &&& { - color: var(--ads-dropdown-default-menu-subtext-text-color); - } - &.sub-text { - color: var(--ads-dropdown-selected-menu-subtext-text-color); - text-align: end; - margin-right: var(--ads-spaces-4); - } -`; - -const OptionWrapper = styled.div<{ - disabled?: boolean; - selected: boolean; - subTextPosition?: SubTextPosition; - selectedHighlightBg?: string; -}>` - padding: calc(var(--ads-spaces-3) + 1px) var(--ads-spaces-5); - ${(props) => (!props.disabled ? "cursor: pointer" : "")}; - display: flex; - width: 100%; - min-height: 36px; - flex-direction: ${(props) => - props.subTextPosition === SubTextPosition.BOTTOM ? "column" : "row"}; - align-items: ${(props) => - props.subTextPosition === SubTextPosition.BOTTOM ? "flex-start" : "center"}; - background-color: ${(props) => - props.selected - ? props.selectedHighlightBg || `var(--ads-color-black-200)` - : "var(--ads-color-black-0)"}; - &&& svg { - rect { - fill: var(--ads-color-black-250); - } - } - .bp3-popover-wrapper { - width: 100%; - } - .${Classes.TEXT} { - color: ${(props) => - props.disabled - ? "var(--ads-color-black-470)" - : props.selected - ? "var(--ads-dropdown-default-menu-hover-text-color)" - : "var(--ads-dropdown-default-menu-text-color)"}; - } - .${Classes.ICON} { - margin-right: var(--ads-spaces-5); - svg { - path { - ${(props) => - props.selected - ? `fill: var(--ads-dropdown-default-icon-selected-fill-color)` - : `fill: var(--ads-dropdown-default-icon-default-fill-color)`}; - } - } - } - &:hover, - &.highlight-option { - background-color: ${(props) => - props.selectedHighlightBg || - "var(--ads-dropdown-default-menu-hover-background-color)"}; - &&& svg { - rect { - fill: var(--ads-text-color-on-dark-background); - } - } - .${Classes.TEXT} { - color: var(--ads-dropdown-default-menu-hover-text-color); - } - ${StyledSubText} { - color: var(--ads-dropdown-default-menu-subtext-text-color); - } - .${Classes.ICON} { - svg { - path { - fill: var(--ads-dropdown-default-icon-hover-fill-color); - } - } - } - } -`; - -const LabelWrapper = styled.div<{ label?: string }>` - display: flex; - flex-direction: column; - align-items: flex-start; - span:last-child { - margin-top: calc(var(--ads-spaces-2) - 1px); - } - &:hover { - .${Classes.TEXT} { - color: var(--ads-dropdown-selected-text-color); - } - } -`; - -const LeftIconWrapper = styled.span` - font-size: 20px; - line-height: 19px; - margin-right: 10px; - height: 100%; - position: relative; - top: 1px; -`; - -const HeaderWrapper = styled.div` - color: var(--ads-old-color-dove-gray); - font-size: 10px; - padding: 0px 7px 7px 7px; -`; - -const SelectedDropDownHolder = styled.div<{ enableScroll?: boolean }>` - display: flex; - align-items: center; - min-width: 0; - max-width: 100%; - overflow: ${(props) => (props.enableScroll ? "auto" : "hidden")}; - width: 100%; - & ${Text} { - max-width: 100%; - overflow: hidden; - text-overflow: ellipsis; - } - &.custom-render-option > * { - // below if to override any custom margin and padding added in the render option - // because the above container already comes with a padding - // which will result broken UI - margin: 0 !important; - padding: 0 !important; - & > *:hover { - background-color: initial; - background: initial; - } - } -`; - -const SelectedIcon = styled(Icon)` - margin-right: 6px; - & > div:first-child { - height: 18px; - width: 18px; - svg { - height: 18px; - width: 18px; - rect { - fill: var(--ads-dropdown-default-icon-background-color); - rx: 0; - } - path { - fill: var(--ads-property-pane-default-label-fill-color); - } - } - } - svg { - path { - fill: ${(props) => - props.fillColor - ? props.fillColor - : "var(--ads-dropdown-default-icon-selected-fill-color)"}; - } - } -`; - -const DropdownIcon = styled(Icon)` - svg { - fill: ${(props) => - props.fillColor - ? props.fillColor - : "var(--ads-dropdown-default-icon-fill-color)"}; - } -`; - -const ErrorMsg = styled.span` - font-weight: ${typography["p3"].fontWeight}; - font-size: ${typography["p3"].fontSize}px; - line-height: ${typography["p3"].lineHeight}px; - letter-spacing: ${typography["p3"].letterSpacing}px; - color: var(--ads-old-color-pomegranate); - margin-top: var(--ads-spaces-3); -`; - -const HelperMsg = styled.span` - font-weight: ${typography["p3"].fontWeight}; - font-size: ${typography["p3"].fontSize}px; - line-height: ${typography["p3"].lineHeight}px; - letter-spacing: ${typography["p3"].letterSpacing}px; - color: var(--ads-dropdown-default-menu-subtext-text-color); - margin: 6px 0px 10px; -`; - -const ErrorLabel = styled.span` - font-weight: ${typography["p1"].fontWeight}; - font-size: ${typography["p1"].fontSize}px; - line-height: ${typography["p1"].lineHeight}px; - letter-spacing: ${typography["p1"].letterSpacing}px; - color: var(--ads-old-color-pomegranate); -`; - -const StyledText = styled(Text)` - overflow: hidden; - text-overflow: ellipsis; - white-space: nowrap; -`; - -const ChipsWrapper = styled.div` - display: flex; -`; - -const Chips = styled.div` - display: flex; - height: 24px; - align-items: center; - padding: 4px; - margin-right: 8px; - background-color: var(--ads-color-black-100); - & > span[type="p2"] { - margin-right: 4px; - } -`; - -const EmptyStateWrapper = styled.div` - padding: 8px; - background-color: var(--ads-color-black-100); - display: flex; - flex-direction: column; - justify-content: center; - & > span { - color: var(--ads-color-black-500); - } -`; - -const scrollIntoViewOptions: ScrollIntoViewOptions = { - block: "nearest", -}; - -function emitKeyPressEvent(element: HTMLDivElement | null, key: string) { - emitDSEvent(element, { - component: "Dropdown", - event: DSEventTypes.KEYPRESS, - meta: { - key, - }, - }); -} - -function TooltipWrappedText( - props: TextProps & { - label: string; - }, -) { - const { label, ...textProps } = props; - const targetRef = useRef<HTMLDivElement | null>(null); - return ( - <Tooltip - boundary="window" - content={label} - disabled={!isEllipsisActive(targetRef.current)} - position="top" - > - <StyledText ref={targetRef} {...textProps}> - {label} - </StyledText> - </Tooltip> - ); -} - -function DefaultDropDownValueNode({ - hasError, - hideSubText, - isMultiSelect, - labelRenderer, - optionWidth, - placeholder, - removeSelectedOptionClickHandler, - renderNode, - selected, - showDropIcon, - showLabelOnly, -}: DefaultDropDownValueNodeProps) { - const LabelText = - !Array.isArray(selected) && selected - ? showLabelOnly - ? selected.label - : selected.value - : placeholder - ? placeholder - : "Please select an option."; - - function Label() { - if (isMultiSelect && Array.isArray(selected) && selected.length) { - return !labelRenderer ? ( - <ChipsWrapper> - {selected?.map((s: DropdownOption) => { - return ( - <Chips key={s.value}> - <Text type={TextType.P2}>{s.label}</Text> - <StyledIcon - className={`t--remove-option-${s.label}`} - fillColor="var(--ads-old-color-gray-7)" - name="close-x" - onClick={(event: any) => { - event.stopPropagation(); - if (removeSelectedOptionClickHandler) { - removeSelectedOptionClickHandler(s as DropdownOption); - } - }} - size={IconSize.XXL} - /> - </Chips> - ); - })} - </ChipsWrapper> - ) : ( - labelRenderer(selected) - ); - } else - return hasError ? ( - <ErrorLabel>{LabelText}</ErrorLabel> - ) : ( - <span style={{ width: "100%", height: "24px", display: "flex" }}> - <Text - style={{ - display: "flex", - alignItems: "center", - }} - type={TextType.P1} - > - {LabelText} - </Text> - </span> - ); - } - - return ( - <SelectedDropDownHolder - className={renderNode ? "custom-render-option" : ""} - enableScroll={isMultiSelect} - > - {renderNode ? ( - renderNode({ - isSelectedNode: true, - option: selected, - hasError, - optionWidth, - }) - ) : isMultiSelect && Array.isArray(selected) ? ( - <Label /> - ) : ( - !Array.isArray(selected) && ( - <> - {selected?.icon ? ( - <SelectedIcon - fillColor={ - hasError - ? "var(--ads-old-color-pomegranate)" - : selected?.iconColor - } - hoverFillColor={ - hasError - ? "var(--ads-old-color-pomegranate)" - : selected?.iconColor - } - name={selected.icon} - size={selected.iconSize ?? IconSize.XL} - /> - ) : null} - {selected?.leftElement && ( - <LeftIconWrapper className="left-icon-wrapper"> - {selected.leftElement} - </LeftIconWrapper> - )} - <Label /> - {selected?.subText && !hideSubText ? ( - <StyledSubText - className="sub-text" - showDropIcon={showDropIcon} - type={TextType.P1} - > - {selected.subText} - </StyledSubText> - ) : null} - </> - ) - )} - </SelectedDropDownHolder> - ); -} - -interface DropdownOptionsProps extends DropdownProps, DropdownSearchProps { - optionClickHandler: (option: DropdownOption) => void; - removeSelectedOptionClickHandler: (option: DropdownOption) => void; - renderOption?: RenderOption; - headerLabel?: string; - highlightIndex?: number; - selected: DropdownOption | DropdownOption[]; - optionWidth: string; - wrapperBgColor?: string; - isMultiSelect?: boolean; - allowDeselection?: boolean; - isOpen: boolean; // dropdown popover options flashes when closed, this prop helps to make sure it never happens again. - showEmptyOptions?: boolean; -} - -export function RenderDropdownOptions(props: DropdownOptionsProps) { - const { onSearch, optionClickHandler, optionWidth, renderOption } = props; - const [options, setOptions] = useState<Array<DropdownOption>>(props.options); - const [searchValue, setSearchValue] = useState<string>(""); - const onOptionSearch = (searchStr: string) => { - const search = searchStr.toLocaleUpperCase(); - const filteredOptions: Array<DropdownOption> = props.options.filter( - (option: DropdownOption) => { - return ( - option.label?.toLocaleUpperCase().includes(search) || - option.searchText?.toLocaleUpperCase().includes(search) - ); - }, - ); - setSearchValue(searchStr); - setOptions(filteredOptions); - onSearch && onSearch(searchStr); - }; - - function EmptyState() { - return ( - <EmptyStateWrapper> - <Text type={TextType.P1}>No results found</Text> - {props.enableSearch && ( - <Text type={TextType.P2}>Try to search a different keyword</Text> - )} - </EmptyStateWrapper> - ); - } - - return ( - <DropdownWrapper - className="ads-dropdown-options-wrapper" - data-cy="dropdown-options-wrapper" - data-testid="dropdown-options-wrapper" - isOpen={props.isOpen} - width={optionWidth} - wrapperBgColor={props.wrapperBgColor} - > - {props.enableSearch && ( - <SearchComponentWrapper className="dropdown-search"> - <SearchComponent - autoFocus={props.searchAutoFocus} - onSearch={onOptionSearch} - placeholder={props.searchPlaceholder || ""} - value={searchValue} - /> - </SearchComponentWrapper> - )} - {props.headerLabel && <HeaderWrapper>{props.headerLabel}</HeaderWrapper>} - <DropdownOptionsWrapper - height={props.dropdownHeight || "100%"} - id="ds--dropdown-options" - maxHeight={props.dropdownMaxHeight || "auto"} - > - {options.map((option: DropdownOption, index: number) => { - let isSelected = false; - if ( - props.isMultiSelect && - Array.isArray(props.selected) && - props.selected.length - ) { - isSelected = !!props.selected.find( - (selectedOption) => selectedOption.value === option.value, - ); - } else { - isSelected = - (props.selected as DropdownOption).value === option.value; - } - if (renderOption) { - return renderOption({ - option, - index, - optionClickHandler, - optionWidth, - isSelectedNode: isSelected, - isHighlighted: index === props.highlightIndex, - }); - } - return !option.isSectionHeader ? ( - <Tooltip - className="ds--dropdown-tooltip" - content={ - !!option.disabledTooltipText - ? option.disabledTooltipText - : "Action not supported" - } - disabled={!option.disabled} - key={`tootltip-${index}`} - styles={{ - width: "100%", - }} - > - <OptionWrapper - aria-selected={isSelected} - className={`t--dropdown-option ${ - isSelected ? "selected" : "" - } ${props.highlightIndex === index ? "highlight-option" : ""}`} - data-cy={`t--dropdown-option-${option?.label}`} - disabled={option.disabled} - key={index} - onClick={ - // users should be able to unselect a selected option by clicking the option again. - isSelected && props.allowDeselection - ? () => props.removeSelectedOptionClickHandler(option) - : () => props.optionClickHandler(option) - } - role="option" - selected={ - props.isMultiSelect - ? props.highlightIndex === index - : isSelected - } - selectedHighlightBg={props.selectedHighlightBg} - subTextPosition={option.subTextPosition ?? SubTextPosition.LEFT} - > - {option.leftElement && ( - <LeftIconWrapper className="left-icon-wrapper"> - {option.leftElement} - </LeftIconWrapper> - )} - {option.icon ? ( - <SelectedIcon - fillColor={option?.iconColor} - hoverFillColor={option?.iconColor} - name={option.icon} - size={option.iconSize ?? IconSize.XL} - /> - ) : null} - {props.isMultiSelect ? ( - isSelected ? ( - <SquareBox - backgroundColor="var(--ads-color-brand)" - borderColor="var(--ads-color-brand)" - checked={isSelected} - > - <Check /> - </SquareBox> - ) : ( - <SquareBox borderColor="#a9a7a7" checked={isSelected} /> - ) - ) : null} - {props.showLabelOnly ? ( - props.truncateOption ? ( - <> - <TooltipWrappedText - label={option.label || ""} - type={TextType.P1} - /> - {option.hasCustomBadge && props.customBadge} - </> - ) : ( - <> - <Text type={TextType.P1}>{option.label}</Text> - {option.hasCustomBadge && props.customBadge} - </> - ) - ) : option.label && option.value ? ( - <LabelWrapper className="label-container"> - <Text type={TextType.H5}>{option.value}</Text> - <Text type={TextType.P1}>{option.label}</Text> - </LabelWrapper> - ) : props.truncateOption ? ( - <TooltipWrappedText - label={option.value || ""} - type={TextType.P1} - /> - ) : ( - <Text type={TextType.P1}>{option.value}</Text> - )} - {option.subText ? ( - <StyledSubText - subTextPosition={option.subTextPosition} - type={TextType.P3} - > - {option.subText} - </StyledSubText> - ) : null} - </OptionWrapper> - </Tooltip> - ) : ( - <SegmentHeader - style={{ paddingRight: "var(--ads-spaces-5)" }} - title={option.label || ""} - /> - ); - })} - {!options.length && <EmptyState />} - </DropdownOptionsWrapper> - </DropdownWrapper> - ); -} - -export default function Dropdown(props: DropdownProps) { - const { - closeOnSpace = true, - errorMsg = "", - hasError, - helperText, - isLoading = false, - onSelect, - placeholder, - removeSelectedOption, - renderOption, - SelectedValueNode = DefaultDropDownValueNode, - showDropIcon = true, - wrapperBgColor, - } = { ...props }; - const [isOpen, setIsOpen] = useState<boolean>(false); - const [selected, setSelected] = useState<DropdownOption | DropdownOption[]>( - props.selected, - ); - const [highlight, setHighlight] = useState(-1); - const dropdownWrapperRef = useRef<HTMLDivElement>(null); - - const closeIfOpen = () => { - if (isOpen && !props.isMultiSelect) { - setIsOpen(false); - } - }; - - useEffect(() => { - setSelected(props.selected); - if (!props.isMultiSelect) closeIfOpen(); - }, [props.selected]); - - const optionClickHandler = useCallback( - (option: DropdownOption, isUpdatedViaKeyboard?: boolean) => { - if (option.disabled) { - return; - } - - if (props.isMultiSelect) { - // Multi select -> typeof selected is array of objects - if (isArray(selected) && selected.length < 1) { - setSelected([option]); - } else if ( - (selected as DropdownOption[]) - .map((x) => x.value) - .findIndex((x) => option.value === x) - ) { - const newOptions: DropdownOption[] = [ - ...(selected as DropdownOption[]), - option, - ]; - setSelected(newOptions); - setIsOpen(true); - } - } else { - // Single select -> typeof selected is object - setSelected(option); - setIsOpen(false); - } - onSelect && onSelect(option.value, option, isUpdatedViaKeyboard); - option.onSelect && option.onSelect(option.value, option); - }, - [onSelect], - ); - - //Removes selected option, should be called when allowDeselection=true - const removeSelectedOptionClickHandler = useCallback( - (optionToBeRemoved: DropdownOption) => { - let selectedOptions: DropdownOption | DropdownOption[] = []; - if (props.isMultiSelect) { - setIsOpen(true); - } else { - setIsOpen(false); - } - if (!Array.isArray(selected)) { - if (optionToBeRemoved.value === selected.value) { - selectedOptions = optionToBeRemoved; - } - } else { - selectedOptions = selected.filter( - (option: DropdownOption) => option.value !== optionToBeRemoved.value, - ); - } - setSelected(selectedOptions); - removeSelectedOption && - removeSelectedOption(optionToBeRemoved.value, optionToBeRemoved); - }, - [removeSelectedOption], - ); - - const errorFlag = hasError || errorMsg.length > 0; - const disabled = props.disabled || isLoading; - const downIconColor = errorFlag - ? "var(--ads-old-color-pomegranate)" - : "var(--ads-color-black-450)"; - - const onClickHandler = () => { - if (!props.disabled) { - setIsOpen(!isOpen); - } - }; - - const handleKeydown = useCallback( - (e: React.KeyboardEvent) => { - const elementList = document.getElementById( - "ds--dropdown-options", - )?.children; - if (!elementList || elementList?.length === 0) { - setHighlight(-1); - } - switch (e.key) { - case "Escape": - emitKeyPressEvent(dropdownWrapperRef.current, e.key); - if (isOpen) { - setSelected((prevSelected) => { - if (prevSelected != props.selected) return props.selected; - return prevSelected; - }); - setIsOpen(false); - e.nativeEvent.stopImmediatePropagation(); - } - break; - case " ": - if (!isOpen) { - emitKeyPressEvent(dropdownWrapperRef.current, e.key); - onClickHandler(); - break; - } - if (!props.enableSearch) { - emitKeyPressEvent(dropdownWrapperRef.current, e.key); - if (closeOnSpace) { - e.preventDefault(); - if (isOpen) { - if (highlight !== -1 && elementList) { - const optionElement = elementList[highlight] as HTMLElement; - const dropdownOptionElement = optionElement.querySelector( - ".t--dropdown-option", - ) as HTMLElement; - dropdownOptionElement && - typeof dropdownOptionElement.click === "function" - ? dropdownOptionElement.click() - : optionElement.click(); - } - } else { - onClickHandler(); - } - } - } - break; - case "Enter": - emitKeyPressEvent(dropdownWrapperRef.current, e.key); - e.preventDefault(); - if (isOpen) { - if (highlight !== -1 && elementList) { - const optionElement = elementList[highlight] as HTMLElement; - const dropdownOptionElement = optionElement.querySelector( - ".t--dropdown-option", - ) as HTMLElement; - dropdownOptionElement && - typeof dropdownOptionElement.click === "function" - ? dropdownOptionElement.click() - : optionElement.click(); - } - } else { - onClickHandler(); - } - break; - case "ArrowUp": - if (!isOpen) { - emitKeyPressEvent(dropdownWrapperRef.current, e.key); - onClickHandler(); - break; - } - if (elementList) { - emitKeyPressEvent(dropdownWrapperRef.current, e.key); - e.preventDefault(); - if (highlight === -1) { - setHighlight(elementList.length - 1); - } else { - setHighlight((x) => { - const index = x - 1 < 0 ? elementList.length - 1 : x - 1; - elementList[index]?.scrollIntoView(scrollIntoViewOptions); - return index; - }); - } - } - break; - case "ArrowDown": - if (!isOpen) { - emitKeyPressEvent(dropdownWrapperRef.current, e.key); - onClickHandler(); - break; - } - if (elementList) { - emitKeyPressEvent(dropdownWrapperRef.current, e.key); - e.preventDefault(); - if (highlight === -1) { - setHighlight(0); - } else { - setHighlight((x) => { - const index = x + 1 > elementList.length - 1 ? 0 : x + 1; - elementList[index]?.scrollIntoView(scrollIntoViewOptions); - return index; - }); - } - } - break; - case "Tab": - emitKeyPressEvent( - dropdownWrapperRef.current, - `${e.shiftKey ? "Shift+" : ""}${e.key}`, - ); - if (isOpen) { - setIsOpen(false); - } - break; - } - }, - [isOpen, props.options, props.selected, selected, highlight], - ); - - const [dropdownWrapperWidth, setDropdownWrapperWidth] = - useState<string>("100%"); - - const prevWidth = useRef(0); - - const onParentResize = useCallback( - debounce((entries) => { - requestAnimationFrame(() => { - if (dropdownWrapperRef.current) { - const width = entries[0].borderBoxSize?.[0].inlineSize; - if (typeof width === "number" && width !== prevWidth.current) { - prevWidth.current = width; - setDropdownWrapperWidth(`${width}px`); - } - } - }); - }, 300), - [dropdownWrapperRef.current], - ); - - useEffect(() => { - const resizeObserver = new ResizeObserver(onParentResize); - if (dropdownWrapperRef.current && props.fillOptions) - resizeObserver.observe(dropdownWrapperRef.current); - - return () => { - resizeObserver.disconnect(); - }; - }, [dropdownWrapperRef.current, props.fillOptions]); - - let dropdownHeight = props.isMultiSelect ? "auto" : "36px"; - if (props.height) { - dropdownHeight = props.height; - } - - const dropdownOptionWidth = props.fillOptions - ? dropdownWrapperWidth - : props.optionWidth || "260px"; - - const dropdownTrigger = props.dropdownTriggerIcon ? ( - <DropdownTriggerWrapper - disabled={props.disabled} - isOpen={isOpen} - onClick={onClickHandler} - ref={dropdownWrapperRef} - > - {props.dropdownTriggerIcon} - </DropdownTriggerWrapper> - ) : ( - <DropdownSelect ref={dropdownWrapperRef}> - <Selected - bgColor={props.bgColor} - className={props.className} - disabled={props.disabled} - hasError={errorFlag} - height={dropdownHeight} - isMultiSelect={props.isMultiSelect} - isOpen={isOpen} - onClick={() => setIsOpen(!isOpen)} - selected={!!selected} - > - <SelectedValueNode - hasError={errorFlag} - hideSubText={props.hideSubText} - isMultiSelect={props.isMultiSelect} - labelRenderer={props.labelRenderer} - optionWidth={dropdownOptionWidth} - placeholder={placeholder} - removeSelectedOptionClickHandler={removeSelectedOptionClickHandler} - renderNode={renderOption} - selected={selected} - showDropIcon={showDropIcon} - showLabelOnly={props.showLabelOnly} - /> - {isLoading ? ( - <Spinner size={IconSize.LARGE} /> - ) : ( - showDropIcon && ( - <DropdownIcon - fillColor={downIconColor} - hoverFillColor={downIconColor} - name={props.defaultIcon || "expand-more"} - size={IconSize.XXL} - /> - ) - )} - </Selected> - {errorMsg && ( - <ErrorMsg className="ads-dropdown-errorMsg">{errorMsg}</ErrorMsg> - )} - {helperText && !isOpen && !errorMsg && ( - <HelperMsg>{helperText}</HelperMsg> - )} - </DropdownSelect> - ); - - const dropdownWidth = props.width || "260px"; - - return ( - <DropdownContainer - className={props.containerClassName + " " + replayHighlightClass} - data-cy={props.cypressSelector} - disabled={disabled} - height={dropdownHeight} - onKeyDown={handleKeydown} - role="listbox" - tabIndex={0} - width={dropdownWidth} - > - <Popover - boundary={props.boundary || "scrollParent"} - isOpen={isOpen && !disabled} - minimal - modifiers={{ arrow: { enabled: true } }} - onInteraction={(state) => !disabled && setIsOpen(state)} - popoverClassName={`${props.className} none-shadow-popover ds--dropdown-popover`} - portalClassName={props.portalClassName} - portalContainer={props.portalContainer} - position={Position.BOTTOM_LEFT} - usePortal={!props.dontUsePortal} - > - {dropdownTrigger} - <RenderDropdownOptions - {...props} - allowDeselection={props.allowDeselection} - highlightIndex={highlight} - isMultiSelect={props.isMultiSelect} - isOpen={isOpen} - optionClickHandler={optionClickHandler} - optionWidth={dropdownOptionWidth} - removeSelectedOptionClickHandler={removeSelectedOptionClickHandler} - searchAutoFocus={props.enableSearch} - selected={selected ? selected : { id: undefined, value: undefined }} - wrapperBgColor={wrapperBgColor} - /> - </Popover> - </DropdownContainer> - ); -} diff --git a/app/client/packages/design-system/ads-old/src/EditableTextSubComponent/index.tsx b/app/client/packages/design-system/ads-old/src/EditableTextSubComponent/index.tsx index a54a7e40a944..7dc18944b16c 100644 --- a/app/client/packages/design-system/ads-old/src/EditableTextSubComponent/index.tsx +++ b/app/client/packages/design-system/ads-old/src/EditableTextSubComponent/index.tsx @@ -5,7 +5,8 @@ import { } from "@blueprintjs/core"; import styled from "styled-components"; import type { noop } from "lodash"; -import { Icon, IconSize, Text, TextType } from "../index"; +import { Spinner } from "@appsmith/ads"; +import { Text, TextType } from "../index"; import type { CommonComponentProps } from "../types/common"; export enum EditInteractionKind { @@ -116,14 +117,6 @@ const TextContainer = styled.div<{ } `; -const IconWrapper = styled.div` - width: var(--ads-spaces-15); - padding-right: var(--ads-spaces-5); - display: flex; - align-items: center; - justify-content: flex-end; -`; - export const EditableTextSubComponent = React.forwardRef( (props: EditableTextSubComponentProps, ref: any) => { const { @@ -224,17 +217,6 @@ export const EditableTextSubComponent = React.forwardRef( [inputValidation, onTextChanged], ); - const iconName = - !isEditing && - savingState === SavingState.NOT_STARTED && - !props.hideEditIcon - ? "pencil-line" - : !isEditing && savingState === SavingState.SUCCESS - ? "success" - : savingState === SavingState.ERROR || (isEditing && !!isInvalid) - ? "error" - : undefined; - return ( <> <TextContainer @@ -258,19 +240,7 @@ export const EditableTextSubComponent = React.forwardRef( value={value} /> - {savingState === SavingState.STARTED ? ( - <IconWrapper className="icon-wrapper"> - <Icon name={"loader"} size={IconSize.XL} /> - </IconWrapper> - ) : value && !props.hideEditIcon ? ( - <IconWrapper className="icon-wrapper"> - <Icon - fillColor="var(--ads-v2-color-fg)" - name={iconName} - size={IconSize.XL} - /> - </IconWrapper> - ) : null} + {savingState === SavingState.STARTED ? <Spinner size="md" /> : null} </TextContainer> {isEditing && !!isInvalid ? ( <Text className="error-message" type={TextType.P2}> diff --git a/app/client/packages/design-system/ads-old/src/FilePickerV2/index.tsx b/app/client/packages/design-system/ads-old/src/FilePickerV2/index.tsx index 7b43cf5f2c2f..f1b22282ecc8 100644 --- a/app/client/packages/design-system/ads-old/src/FilePickerV2/index.tsx +++ b/app/client/packages/design-system/ads-old/src/FilePickerV2/index.tsx @@ -3,9 +3,9 @@ import styled from "styled-components"; import type { DropTargetMonitor } from "react-dnd"; import { DndProvider, useDrop } from "react-dnd"; import HTML5Backend, { NativeTypes } from "react-dnd-html5-backend"; -import Button, { Category, IconPositions, Size } from "../Button"; -import type { IconName } from "../Icon"; -import Icon, { IconSize } from "../Icon"; +import { Button } from "@appsmith/ads"; +import type { IconNames } from "@appsmith/ads"; +import { Icon } from "@appsmith/ads"; import Text, { TextType } from "../Text"; import { toast } from "@appsmith/ads"; import TooltipComponent from "../Tooltip"; @@ -14,7 +14,6 @@ import { ERROR_FILE_TOO_LARGE, REMOVE_FILE_TOOL_TIP, } from "../constants/messages"; -import { Classes } from "../constants/classes"; import { importSvg } from "../utils/icon-loadables"; const UploadSuccessIcon = importSvg( @@ -51,7 +50,7 @@ export interface FilePickerProps { logoUploadError?: string; fileType: FileType; delayedUpload?: boolean; - uploadIcon?: IconName; + uploadIcon?: IconNames; title?: string; description?: string; containerClickable?: boolean; // when container is clicked, it'll work as button @@ -172,20 +171,10 @@ export const ContainerDiv = styled.div<{ bottom: 0; border-radius: 0 0 var(--ads-v2-border-radius) var(--ads-v2-border-radius); } - a { + .ads-v2-button { width: 110px; margin: var(--ads-spaces-13) var(--ads-spaces-3) var(--ads-spaces-3) auto; - color: var(--ads-v2-color-fg); - border-radius: var(--ads-v2-border-radius); - border-color: var(--ads-v2-color-border); - text-transform: capitalize; - background: var(--ads-v2-color-bg); - .${Classes.ICON} { - margin-right: calc(var(--ads-spaces-2) - 1px); - } - &:hover { - background: var(--ads-v2-color-bg-subtle); - } + display: flex; } } @@ -407,7 +396,7 @@ function FilePickerComponent(props: FilePickerProps) { <div className="button-wrapper" ref={fileContainerRef}> <UploadIconWrapper> <Icon - fillColor={ + color={ props.iconFillColor || "var(--ads-file-picker-v2-upload-icon-fill-color)" } @@ -434,12 +423,13 @@ function FilePickerComponent(props: FilePickerProps) { /> {!props.containerClickable && ( <Button - category={Category.secondary} className="browse-button" + kind="secondary" onClick={(el: React.MouseEvent<HTMLElement>) => ButtonClick(el)} - size={Size.medium} - text="Browse" - /> + size="sm" + > + Browse + </Button> )} </form> </div> @@ -466,13 +456,14 @@ function FilePickerComponent(props: FilePickerProps) { <div className="remove-button"> <div className="overlay" /> <Button - category={Category.secondary} - icon="delete" - iconPosition={IconPositions.left} + data-testid="t--remove-logo" + kind="secondary" onClick={() => removeFile()} - size={Size.medium} - text="Remove" - /> + size="sm" + startIcon="delete" + > + Remove + </Button> </div> </> ); @@ -493,7 +484,7 @@ function FilePickerComponent(props: FilePickerProps) { </Text> <TooltipComponent content={REMOVE_FILE_TOOL_TIP()} position="top"> <IconWrapper className="icon-wrapper" onClick={() => removeFile()}> - <Icon name="close" size={IconSize.XL} /> + <Icon name="close" size="lg" /> </IconWrapper> </TooltipComponent> </div> diff --git a/app/client/packages/design-system/ads-old/src/GifPlayer/index.tsx b/app/client/packages/design-system/ads-old/src/GifPlayer/index.tsx index 91d8b9c9f621..7c0b7e81fc8c 100644 --- a/app/client/packages/design-system/ads-old/src/GifPlayer/index.tsx +++ b/app/client/packages/design-system/ads-old/src/GifPlayer/index.tsx @@ -1,6 +1,6 @@ import React, { useState } from "react"; import styled from "styled-components"; -import Icon, { IconSize } from "../Icon"; +import { Icon } from "@appsmith/ads"; import Text, { TextType } from "../Text"; import { Classes } from "../constants/classes"; @@ -60,7 +60,7 @@ function GifPlayer(props: GifPlayerProps) { <Overlay /> <img src={props.thumbnail} /> <PlayButton> - <Icon name="play" size={IconSize.XXXL} /> + <Icon name="play" size="lg" /> <Text color={"var(--ads-v2-color-fg)"} type={TextType.P3}> Click to play </Text> diff --git a/app/client/packages/design-system/ads-old/src/Icon/index.tsx b/app/client/packages/design-system/ads-old/src/Icon/index.tsx deleted file mode 100644 index 3fa4c31f067a..000000000000 --- a/app/client/packages/design-system/ads-old/src/Icon/index.tsx +++ /dev/null @@ -1,982 +0,0 @@ -import type { Ref } from "react"; -import React, { forwardRef } from "react"; -import styled from "styled-components"; -import type { CommonComponentProps } from "../types/common"; -import { Classes } from "../constants/classes"; -import { noop } from "lodash"; -import Spinner from "../Spinner"; -import { ControlIcons } from "../ControlIcons"; -import { importRemixIcon, importSvg } from "../utils/icon-loadables"; -const ClearInterval = importSvg( - async () => import("../assets/icons/action/clearInterval.svg"), -); -const ClearStore = importSvg( - async () => import("../assets/icons/action/clearStore.svg"), -); -const CopyToClipboard = importSvg( - async () => import("../assets/icons/action/copyToClipboard.svg"), -); -const DownloadAction = importSvg( - async () => import("../assets/icons/action/download.svg"), -); -const ExecuteJs = importSvg( - async () => import("../assets/icons/action/executeJs.svg"), -); -const ExecuteQuery = importSvg( - async () => import("../assets/icons/action/executeQuery.svg"), -); -const GetGeolocation = importSvg( - async () => import("../assets/icons/action/getGeolocation.svg"), -); -const Modal = importSvg(async () => import("../assets/icons/action/modal.svg")); -const NavigateTo = importSvg( - async () => import("../assets/icons/action/navigateTo.svg"), -); -const RemoveStore = importSvg( - async () => import("../assets/icons/action/removeStore.svg"), -); -const ResetWidget = importSvg( - async () => import("../assets/icons/action/resetWidget.svg"), -); -const SetInterval = importSvg( - async () => import("../assets/icons/action/setInterval.svg"), -); -const ShowAlert = importSvg( - async () => import("../assets/icons/action/showAlert.svg"), -); -const StopWatchGeolocation = importSvg( - async () => import("../assets/icons/action/stopWatchGeolocation.svg"), -); -const StoreValue = importSvg( - async () => import("../assets/icons/action/storeValue.svg"), -); -const WatchGeolocation = importSvg( - async () => import("../assets/icons/action/watchGeolocation.svg"), -); -const RunAPI = importSvg( - async () => import("../assets/icons/action/runApi.svg"), -); -const PostMessage = importSvg( - async () => import("../assets/icons/action/postMessage.svg"), -); -const NoAction = importSvg( - async () => import("../assets/icons/action/noAction.svg"), -); -const BookLineIcon = importSvg( - async () => import("../assets/icons/ads/book-open-line.svg"), -); -const BugIcon = importSvg(async () => import("../assets/icons/ads/bug.svg")); -const CancelIcon = importSvg( - async () => import("../assets/icons/ads/cancel.svg"), -); -const CrossIcon = importSvg( - async () => import("../assets/icons/ads/cross.svg"), -); -const Fork2Icon = importSvg( - async () => import("../assets/icons/ads/fork-2.svg"), -); -const OpenIcon = importSvg(async () => import("../assets/icons/ads/open.svg")); -const UserIcon = importSvg(async () => import("../assets/icons/ads/user.svg")); -const GeneralIcon = importSvg( - async () => import("../assets/icons/ads/general.svg"), -); -const BillingIcon = importSvg( - async () => import("../assets/icons/ads/billing.svg"), -); -const ErrorIcon = importSvg( - async () => import("../assets/icons/ads/error.svg"), -); -const ShineIcon = importSvg( - async () => import("../assets/icons/ads/shine.svg"), -); -const SuccessIcon = importSvg( - async () => import("../assets/icons/ads/success.svg"), -); -const CloseIcon = importSvg( - async () => import("../assets/icons/ads/close.svg"), -); -const WarningTriangleIcon = importSvg( - async () => import("../assets/icons/ads/warning-triangle.svg"), -); -const ShareIcon2 = importSvg( - async () => import("../assets/icons/ads/share-2.svg"), -); -const InviteUserIcon = importSvg( - async () => import("../assets/icons/ads/invite-users.svg"), -); -const ManageIcon = importSvg( - async () => import("../assets/icons/ads/manage.svg"), -); -const ArrowLeft = importSvg( - async () => import("../assets/icons/ads/arrow-left.svg"), -); -const ChevronLeft = importSvg( - async () => import("../assets/icons/ads/chevron_left.svg"), -); -const LinkIcon = importSvg(async () => import("../assets/icons/ads/link.svg")); -const NoResponseIcon = importSvg( - async () => import("../assets/icons/ads/no-response.svg"), -); -const LightningIcon = importSvg( - async () => import("../assets/icons/ads/lightning.svg"), -); -const TrendingFlat = importSvg( - async () => import("../assets/icons/ads/trending-flat.svg"), -); -const PlayIcon = importSvg(async () => import("../assets/icons/ads/play.svg")); -const DesktopIcon = importSvg( - async () => import("../assets/icons/ads/desktop.svg"), -); -const WandIcon = importSvg(async () => import("../assets/icons/ads/wand.svg")); -const MobileIcon = importSvg( - async () => import("../assets/icons/ads/mobile.svg"), -); -const TabletIcon = importSvg( - async () => import("../assets/icons/ads/tablet.svg"), -); -const TabletLandscapeIcon = importSvg( - async () => import("../assets/icons/ads/tablet-landscape.svg"), -); -const FluidIcon = importSvg( - async () => import("../assets/icons/ads/fluid.svg"), -); -const CardContextMenu = importSvg( - async () => import("../assets/icons/ads/card-context-menu.svg"), -); -const SendButton = importSvg( - async () => import("../assets/icons/comments/send-button.svg"), -); -const Pin = importSvg(async () => import("../assets/icons/comments/pin.svg")); -const TrashOutline = importSvg( - async () => import("../assets/icons/form/trash.svg"), -); -const ReadPin = importSvg( - async () => import("../assets/icons/comments/read-pin.svg"), -); -const UnreadPin = importSvg( - async () => import("../assets/icons/comments/unread-pin.svg"), -); -const Chat = importSvg(async () => import("../assets/icons/comments/chat.svg")); -const Unpin = importSvg( - async () => import("../assets/icons/comments/unpinIcon.svg"), -); -const Reaction = importSvg( - async () => import("../assets/icons/comments/reaction.svg"), -); -const Reaction2 = importSvg( - async () => import("../assets/icons/comments/reaction-2.svg"), -); -const Upload = importSvg(async () => import("../assets/icons/ads/upload.svg")); -const ArrowForwardIcon = importSvg( - async () => import("../assets/icons/control/arrow_forward.svg"), -); -const DoubleArrowRightIcon = importSvg( - async () => import("../assets/icons/ads/double-arrow-right.svg"), -); -const CapSolidIcon = importSvg( - async () => import("../assets/icons/control/cap_solid.svg"), -); -const CapDotIcon = importSvg( - async () => import("../assets/icons/control/cap_dot.svg"), -); -const LineDottedIcon = importSvg( - async () => import("../assets/icons/control/line_dotted.svg"), -); -const LineDashedIcon = importSvg( - async () => import("../assets/icons/control/line_dashed.svg"), -); -const TableIcon = importSvg( - async () => import("../assets/icons/ads/tables.svg"), -); -const ColumnIcon = importSvg( - async () => import("../assets/icons/ads/column.svg"), -); -const GearIcon = importSvg(async () => import("../assets/icons/ads/gear.svg")); -const UserV2Icon = importSvg( - async () => import("../assets/icons/ads/user-v2.svg"), -); -const SupportIcon = importSvg( - async () => import("../assets/icons/ads/support.svg"), -); -const Snippet = importSvg( - async () => import("../assets/icons/ads/snippet.svg"), -); -const WorkspaceIcon = importSvg( - async () => import("../assets/icons/ads/workspaceIcon.svg"), -); -const SettingIcon = importSvg( - async () => import("../assets/icons/control/settings.svg"), -); -const DropdownIcon = importSvg( - async () => import("../assets/icons/ads/dropdown.svg"), -); -const ChatIcon = importSvg( - async () => import("../assets/icons/ads/app-icons/chat.svg"), -); -const JsIcon = importSvg(async () => import("../assets/icons/ads/js.svg")); -const ExecuteIcon = importSvg( - async () => import("../assets/icons/ads/execute.svg"), -); -const PackageIcon = importSvg( - async () => import("../assets/icons/ads/package.svg"), -); - -const DevicesIcon = importSvg( - async () => import("../assets/icons/ads/devices.svg"), -); -const GridIcon = importSvg(async () => import("../assets/icons/ads/grid.svg")); -const HistoryLineIcon = importSvg( - async () => import("../assets/icons/ads/history-line.svg"), -); -const SuccessLineIcon = importSvg( - async () => import("../assets/icons/ads/success-line.svg"), -); -const ErrorLineIcon = importSvg( - async () => import("../assets/icons/ads/error-line.svg"), -); -const UpdatesIcon = importSvg( - async () => import("../assets/icons/help/updates.svg"), -); - -// remix icons -const AddMoreIcon = importRemixIcon( - async () => import("remixicon-react/AddCircleLineIcon"), -); -const AddMoreFillIcon = importRemixIcon( - async () => import("remixicon-react/AddCircleFillIcon"), -); -const ArrowLeftRightIcon = importRemixIcon( - async () => import("remixicon-react/ArrowLeftRightLineIcon"), -); -const ArrowDownLineIcon = importRemixIcon( - async () => import("remixicon-react/ArrowDownLineIcon"), -); -const BookIcon = importRemixIcon( - async () => import("remixicon-react/BookOpenLineIcon"), -); -const BugLineIcon = importRemixIcon( - async () => import("remixicon-react/BugLineIcon"), -); -const ChevronRight = importRemixIcon( - async () => import("remixicon-react/ArrowRightSFillIcon"), -); -const CheckLineIcon = importRemixIcon( - async () => import("remixicon-react/CheckLineIcon"), -); -const CloseLineIcon = importRemixIcon( - async () => import("remixicon-react/CloseLineIcon"), -); -const CloseCircleIcon = importRemixIcon( - async () => import("remixicon-react/CloseCircleFillIcon"), -); -const CloseCircleLineIcon = importRemixIcon( - async () => import("remixicon-react/CloseCircleLineIcon"), -); -const CloudOfflineIcon = importRemixIcon( - async () => import("remixicon-react/CloudOffLineIcon"), -); -const CommentContextMenu = importRemixIcon( - async () => import("remixicon-react/More2FillIcon"), -); -const More2FillIcon = importRemixIcon( - async () => import("remixicon-react/More2FillIcon"), -); -const CompassesLine = importRemixIcon( - async () => import("remixicon-react/CompassesLineIcon"), -); -const ContextMenuIcon = importRemixIcon( - async () => import("remixicon-react/MoreFillIcon"), -); -const CreateNewIcon = importRemixIcon( - async () => import("remixicon-react/AddLineIcon"), -); -const Database2Line = importRemixIcon( - async () => import("remixicon-react/Database2LineIcon"), -); -const DatasourceIcon = importRemixIcon( - async () => import("remixicon-react/CloudFillIcon"), -); -const DeleteBin7 = importRemixIcon( - async () => import("remixicon-react/DeleteBin7LineIcon"), -); -const DiscordIcon = importRemixIcon( - async () => import("remixicon-react/DiscordLineIcon"), -); -const DownArrow = importRemixIcon( - async () => import("remixicon-react/ArrowDownSFillIcon"), -); -const Download = importRemixIcon( - async () => import("remixicon-react/DownloadCloud2LineIcon"), -); -const DuplicateIcon = importRemixIcon( - async () => import("remixicon-react/FileCopyLineIcon"), -); -const EditIcon = importRemixIcon( - async () => import("remixicon-react/PencilFillIcon"), -); -const EditLineIcon = importRemixIcon( - async () => import("remixicon-react/EditLineIcon"), -); -const EditUnderlineIcon = importRemixIcon( - async () => import("remixicon-react/EditLineIcon"), -); -const Emoji = importRemixIcon( - async () => import("remixicon-react/EmotionLineIcon"), -); -const ExpandMore = importRemixIcon( - async () => import("remixicon-react/ArrowDownSLineIcon"), -); -const DownArrowIcon = importRemixIcon( - async () => import("remixicon-react/ArrowDownSLineIcon"), -); -const ExpandLess = importRemixIcon( - async () => import("remixicon-react/ArrowUpSLineIcon"), -); -const EyeOn = importRemixIcon( - async () => import("remixicon-react/EyeLineIcon"), -); -const EyeOff = importRemixIcon( - async () => import("remixicon-react/EyeOffLineIcon"), -); -const FileTransfer = importRemixIcon( - async () => import("remixicon-react/FileTransferLineIcon"), -); -const FileLine = importRemixIcon( - async () => import("remixicon-react/FileLineIcon"), -); -const Filter = importRemixIcon( - async () => import("remixicon-react/Filter2FillIcon"), -); -const ForbidLineIcon = importRemixIcon( - async () => import("remixicon-react/ForbidLineIcon"), -); -const GitMerge = importRemixIcon( - async () => import("remixicon-react/GitMergeLineIcon"), -); -const GitCommit = importRemixIcon( - async () => import("remixicon-react/GitCommitLineIcon"), -); -const GitPullRequst = importRemixIcon( - async () => import("remixicon-react/GitPullRequestLineIcon"), -); -const GlobalLineIcon = importRemixIcon( - async () => import("remixicon-react/GlobalLineIcon"), -); -const GuideIcon = importRemixIcon( - async () => import("remixicon-react/GuideFillIcon"), -); -const HelpIcon = importRemixIcon( - async () => import("remixicon-react/QuestionMarkIcon"), -); -const LightbulbFlashLine = importRemixIcon( - async () => import("remixicon-react/LightbulbFlashLineIcon"), -); -const LinksLineIcon = importRemixIcon( - async () => import("remixicon-react/LinksLineIcon"), -); -const InfoIcon = importRemixIcon( - async () => import("remixicon-react/InformationLineIcon"), -); -const KeyIcon = importRemixIcon( - async () => import("remixicon-react/Key2LineIcon"), -); -const LeftArrowIcon2 = importRemixIcon( - async () => import("remixicon-react/ArrowLeftSLineIcon"), -); -const Link2 = importRemixIcon(async () => import("remixicon-react/LinkIcon")); -const LeftArrowIcon = importRemixIcon( - async () => import("remixicon-react/ArrowLeftLineIcon"), -); -const NewsPaperLine = importRemixIcon( - async () => import("remixicon-react/NewspaperLineIcon"), -); -const OvalCheck = importRemixIcon( - async () => import("remixicon-react/CheckboxCircleLineIcon"), -); -const OvalCheckFill = importRemixIcon( - async () => import("remixicon-react/CheckboxCircleFillIcon"), -); -const Pin3 = importRemixIcon( - async () => import("remixicon-react/Pushpin2FillIcon"), -); -const PlayCircleLineIcon = importRemixIcon( - async () => import("remixicon-react/PlayCircleLineIcon"), -); -const QueryIcon = importRemixIcon( - async () => import("remixicon-react/CodeSSlashLineIcon"), -); -const RemoveIcon = importRemixIcon( - async () => import("remixicon-react/SubtractLineIcon"), -); -const RightArrowIcon = importRemixIcon( - async () => import("remixicon-react/ArrowRightLineIcon"), -); -const RightArrowIcon2 = importRemixIcon( - async () => import("remixicon-react/ArrowRightSLineIcon"), -); -const RocketIcon = importRemixIcon( - async () => import("remixicon-react/RocketLineIcon"), -); -const SearchIcon = importRemixIcon( - async () => import("remixicon-react/SearchLineIcon"), -); -const SortAscIcon = importRemixIcon( - async () => import("remixicon-react/SortAscIcon"), -); -const SortDescIcon = importRemixIcon( - async () => import("remixicon-react/SortDescIcon"), -); -const ShareBoxLineIcon = importRemixIcon( - async () => import("remixicon-react/ShareBoxLineIcon"), -); -const ShareBoxFillIcon = importRemixIcon( - async () => import("remixicon-react/ShareBoxFillIcon"), -); -const ShareForwardIcon = importRemixIcon( - async () => import("remixicon-react/ShareForwardFillIcon"), -); -const Trash = importRemixIcon( - async () => import("remixicon-react/DeleteBinLineIcon"), -); -const UpArrow = importRemixIcon( - async () => import("remixicon-react/ArrowUpSFillIcon"), -); -const WarningIcon = importRemixIcon( - async () => import("remixicon-react/ErrorWarningFillIcon"), -); -const WarningLineIcon = importRemixIcon( - async () => import("remixicon-react/ErrorWarningLineIcon"), -); -const LoginIcon = importRemixIcon( - async () => import("remixicon-react/LoginBoxLineIcon"), -); -const LogoutIcon = importRemixIcon( - async () => import("remixicon-react/LogoutBoxRLineIcon"), -); -const ShareLineIcon = importRemixIcon( - async () => import("remixicon-react/ShareLineIcon"), -); -const LoaderLineIcon = importRemixIcon( - async () => import("remixicon-react/LoaderLineIcon"), -); -const WidgetIcon = importRemixIcon( - async () => import("remixicon-react/FunctionLineIcon"), -); -const RefreshLineIcon = importRemixIcon( - async () => import("remixicon-react/RefreshLineIcon"), -); -const GitBranchLineIcon = importRemixIcon( - async () => import("remixicon-react/GitBranchLineIcon"), -); -const EditBoxLineIcon = importRemixIcon( - async () => import("remixicon-react/EditBoxLineIcon"), -); -const StarLineIcon = importRemixIcon( - async () => import("remixicon-react/StarLineIcon"), -); -const StarFillIcon = importRemixIcon( - async () => import("remixicon-react/StarFillIcon"), -); -const Settings2LineIcon = importRemixIcon( - async () => import("remixicon-react/Settings2LineIcon"), -); -const DownloadIcon = importRemixIcon( - async () => import("remixicon-react/DownloadLineIcon"), -); -const UploadCloud2LineIcon = importRemixIcon( - async () => import("remixicon-react/UploadCloud2LineIcon"), -); -const DownloadLineIcon = importRemixIcon( - async () => import("remixicon-react/DownloadLineIcon"), -); -const UploadLineIcon = importRemixIcon( - async () => import("remixicon-react/UploadLineIcon"), -); -const FileListLineIcon = importRemixIcon( - async () => import("remixicon-react/FileListLineIcon"), -); -const HamburgerIcon = importRemixIcon( - async () => import("remixicon-react/MenuLineIcon"), -); -const MagicLineIcon = importRemixIcon( - async () => import("remixicon-react/MagicLineIcon"), -); -const UserHeartLineIcon = importRemixIcon( - async () => import("remixicon-react/UserHeartLineIcon"), -); -const DvdLineIcon = importRemixIcon( - async () => import("remixicon-react/DvdLineIcon"), -); -const Group2LineIcon = importRemixIcon( - async () => import("remixicon-react/Group2LineIcon"), -); -const CodeViewIcon = importRemixIcon( - async () => import("remixicon-react/CodeViewIcon"), -); -const GroupLineIcon = importRemixIcon( - async () => import("remixicon-react/GroupLineIcon"), -); -const ArrowRightUpLineIcon = importRemixIcon( - async () => import("remixicon-react/ArrowRightUpLineIcon"), -); -const MailCheckLineIcon = importRemixIcon( - async () => import("remixicon-react/MailCheckLineIcon"), -); -const UserFollowLineIcon = importRemixIcon( - async () => import("remixicon-react/UserFollowLineIcon"), -); -const AddBoxLineIcon = importRemixIcon( - async () => import("remixicon-react/AddBoxLineIcon"), -); -const ArrowRightSFillIcon = importRemixIcon( - async () => import("remixicon-react/ArrowRightSFillIcon"), -); -const ArrowDownSFillIcon = importRemixIcon( - async () => import("remixicon-react/ArrowDownSFillIcon"), -); -const MailLineIcon = importRemixIcon( - async () => import("remixicon-react/MailLineIcon"), -); -const LockPasswordLineIcon = importRemixIcon( - async () => import("remixicon-react/LockPasswordLineIcon"), -); -const Timer2LineIcon = importRemixIcon( - async () => import("remixicon-react/Timer2LineIcon"), -); -const MapPin2LineIcon = importRemixIcon( - async () => import("remixicon-react/MapPin2LineIcon"), -); -const User3LineIcon = importRemixIcon( - async () => import("remixicon-react/User3LineIcon"), -); -const User2LineIcon = importRemixIcon( - async () => import("remixicon-react/User2LineIcon"), -); -const Key2LineIcon = importRemixIcon( - async () => import("remixicon-react/Key2LineIcon"), -); -const FileList2LineIcon = importRemixIcon( - async () => import("remixicon-react/FileList2LineIcon"), -); -const Lock2LineIcon = importRemixIcon( - async () => import("remixicon-react/Lock2LineIcon"), -); -const SearchEyeLineIcon = importRemixIcon( - async () => import("remixicon-react/SearchEyeLineIcon"), -); -const AlertLineIcon = importRemixIcon( - async () => import("remixicon-react/AlertLineIcon"), -); -const SettingsLineIcon = importRemixIcon( - async () => import("remixicon-react/SettingsLineIcon"), -); -const LockUnlockLineIcon = importRemixIcon( - async () => import("remixicon-react/LockUnlockLineIcon"), -); -const PantoneLineIcon = importRemixIcon( - async () => import("remixicon-react/PantoneLineIcon"), -); -const QuestionFillIcon = importRemixIcon( - async () => import("remixicon-react/QuestionFillIcon"), -); -const QuestionLineIcon = importRemixIcon( - async () => import("remixicon-react/QuestionLineIcon"), -); -const UserSharedLineIcon = importRemixIcon( - async () => import("remixicon-react/UserSharedLineIcon"), -); -const UserReceived2LineIcon = importRemixIcon( - async () => import("remixicon-react/UserReceived2LineIcon"), -); -const UserAddLineIcon = importRemixIcon( - async () => import("remixicon-react/UserAddLineIcon"), -); -const UserUnfollowLineIcon = importRemixIcon( - async () => import("remixicon-react/UserUnfollowLineIcon"), -); -const DeleteRowIcon = importRemixIcon( - async () => import("remixicon-react/DeleteRowIcon"), -); -const ArrowUpLineIcon = importRemixIcon( - async () => import("remixicon-react/ArrowUpLineIcon"), -); -const MoneyDollarCircleLineIcon = importRemixIcon( - async () => import("remixicon-react/MoneyDollarCircleLineIcon"), -); -const ExternalLinkLineIcon = importRemixIcon( - async () => import("remixicon-react/ExternalLinkLineIcon"), -); -const PencilLineIcon = importRemixIcon( - async () => import("remixicon-react/PencilLineIcon"), -); - -export enum IconSize { - XXS = "extraExtraSmall", - XS = "extraSmall", - SMALL = "small", - MEDIUM = "medium", - LARGE = "large", - XL = "extraLarge", - XXL = "extraExtraLarge", - XXXL = "extraExtraExtraLarge", - XXXXL = "extraExtraExtraExtraLarge", -} - -const ICON_SIZE_LOOKUP = { - [IconSize.XXS]: 8, - [IconSize.XS]: 10, - [IconSize.SMALL]: 12, - [IconSize.MEDIUM]: 14, - [IconSize.LARGE]: 15, - [IconSize.XL]: 16, - [IconSize.XXL]: 18, - [IconSize.XXXL]: 20, - [IconSize.XXXXL]: 22, - undefined: 12, -}; - -export const sizeHandler = (size?: IconSize): number => { - return ( - ICON_SIZE_LOOKUP[size as keyof typeof ICON_SIZE_LOOKUP] || - ICON_SIZE_LOOKUP[IconSize.SMALL] - ); -}; - -export const IconWrapper = styled.span<IconProps>` - &:focus { - outline: none; - } - - display: flex; - align-items: center; - cursor: ${(props) => - props.disabled ? "not-allowed" : props.clickable ? "pointer" : "default"}; - ${(props) => - props.withWrapper && - ` - min-width: ${sizeHandler(props.size) * 2}px; - height: ${sizeHandler(props.size) * 2}px; - border-radius: 9999px; - justify-content: center; - background-color: ${props.wrapperColor || "rgba(0, 0, 0, 0.1)"}; - `} - svg { - width: ${(props) => sizeHandler(props.size)}px; - height: ${(props) => sizeHandler(props.size)}px; - ${(props) => - !props.keepColors - ? ` - fill: ${props.fillColor || ""}; - circle { - fill: ${props.fillColor || ""}; - } - path { - fill: ${props.fillColor || ""}; - } - ` - : ""}; - ${(props) => (props.invisible ? `visibility: hidden;` : null)}; - - &:hover { - ${(props) => - !props.keepColors - ? ` - fill: ${props.hoverFillColor || ""}; - path { - fill: ${props.hoverFillColor || ""}; - } - ` - : ""} - } - } -`; - -function getControlIcon(iconName: string) { - const ControlIcon = ControlIcons[iconName]; - return <ControlIcon height={24} width={24} />; -} - -const ICON_LOOKUP = { - undefined: null, - HEADING_ONE: getControlIcon("HEADING_ONE"), - HEADING_THREE: getControlIcon("HEADING_THREE"), - HEADING_TWO: getControlIcon("HEADING_TWO"), - PARAGRAPH: getControlIcon("PARAGRAPH"), - PARAGRAPH_TWO: getControlIcon("PARAGRAPH_TWO"), - "add-box-line": <AddBoxLineIcon />, - "add-more": <AddMoreIcon />, - "add-more-fill": <AddMoreFillIcon />, - "alert-line": <AlertLineIcon />, - "arrow-down-s-fill": <ArrowDownSFillIcon />, - "arrow-forward": <ArrowForwardIcon />, - "arrow-left": <ArrowLeft />, - "arrow-right-s-fill": <ArrowRightSFillIcon />, - "arrow-right-up-line": <ArrowRightUpLineIcon />, - "arrow-up-line": <ArrowUpLineIcon />, - "book-line": <BookLineIcon />, - "bug-line": <BugLineIcon />, - "cap-dot": <CapDotIcon />, - "cap-solid": <CapSolidIcon />, - "card-context-menu": <CardContextMenu />, - "chat-help": <ChatIcon />, - "check-line": <CheckLineIcon />, - "chevron-left": <ChevronLeft />, - "chevron-right": <ChevronRight />, - "close-circle": <CloseCircleIcon />, - "close-circle-line": <CloseCircleLineIcon />, - "close-modal": <CloseLineIcon />, - "close-x": <CloseLineIcon />, - "cloud-off-line": <CloudOfflineIcon />, - "comment-context-menu": <CommentContextMenu />, - "compasses-line": <CompassesLine />, - "context-menu": <ContextMenuIcon />, - "database-2-line": <Database2Line />, - "delete-blank": <DeleteBin7 />, - "delete-row": <DeleteRowIcon />, - "double-arrow-right": <DoubleArrowRightIcon />, - "down-arrow": <DownArrowIcon />, - "down-arrow-2": <ArrowDownLineIcon />, - "download-line": <DownloadLineIcon />, - "edit-box-line": <EditBoxLineIcon />, - "edit-line": <EditLineIcon />, - "edit-underline": <EditUnderlineIcon />, - "expand-less": <ExpandLess />, - "expand-more": <ExpandMore />, - "external-link-line": <ExternalLinkLineIcon />, - "eye-off": <EyeOff />, - "eye-on": <EyeOn />, - "file-line": <FileLine />, - "file-list-2-line": <FileList2LineIcon />, - "file-list-line": <FileListLineIcon />, - "file-transfer": <FileTransfer />, - "fork-2": <Fork2Icon />, - "forbid-line": <ForbidLineIcon />, - "git-branch": <GitBranchLineIcon />, - "git-commit": <GitCommit />, - "git-pull-request": <GitPullRequst />, - "global-line": <GlobalLineIcon />, - "group-2-line": <Group2LineIcon />, - "group-line": <GroupLineIcon />, - "invite-user": <InviteUserIcon />, - "key-2-line": <Key2LineIcon />, - "left-arrow-2": <LeftArrowIcon2 />, - "lightbulb-flash-line": <LightbulbFlashLine />, - "line-dashed": <LineDashedIcon />, - "line-dotted": <LineDottedIcon />, - "link-2": <Link2 />, - "links-line": <LinksLineIcon />, - "lock-2-line": <Lock2LineIcon />, - "lock-password-line": <LockPasswordLineIcon />, - "lock-unlock-line": <LockUnlockLineIcon />, - "magic-line": <MagicLineIcon />, - "mail-check-line": <MailCheckLineIcon />, - "mail-line": <MailLineIcon />, - "map-pin-2-line": <MapPin2LineIcon />, - "more-2-fill": <More2FillIcon />, - "news-paper": <NewsPaperLine />, - "no-response": <NoResponseIcon />, - "oval-check": <OvalCheck />, - "oval-check-fill": <OvalCheckFill />, - "pin-3": <Pin3 />, - "play-circle-line": <PlayCircleLineIcon />, - "question-fill": <QuestionFillIcon />, - "question-line": <QuestionLineIcon />, - "reaction-2": <Reaction2 />, - "read-pin": <ReadPin />, - "right-arrow": <RightArrowIcon />, - "right-arrow-2": <RightArrowIcon2 />, - "search-eye-line": <SearchEyeLineIcon />, - "send-button": <SendButton />, - "settings-2-line": <Settings2LineIcon />, - "settings-line": <SettingsLineIcon />, - "share-2": <ShareIcon2 />, - "share-box": <ShareBoxFillIcon />, - "share-box-line": <ShareBoxLineIcon />, - "share-line": <ShareLineIcon />, - "sort-asc": <SortAscIcon />, - "sort-desc": <SortDescIcon />, - "star-fill": <StarFillIcon />, - "star-line": <StarLineIcon />, - "swap-horizontal": <ArrowLeftRightIcon />, - "timer-2-line": <Timer2LineIcon />, - "trash-outline": <TrashOutline />, - "trending-flat": <TrendingFlat />, - "unread-pin": <UnreadPin />, - "upload-cloud": <UploadCloud2LineIcon />, - "upload-line": <UploadLineIcon />, - "user-2": <UserV2Icon />, - "user-2-line": <User2LineIcon />, - "user-3-line": <User3LineIcon />, - "user-add-line": <UserAddLineIcon />, - "user-follow-line": <UserFollowLineIcon />, - "user-heart-line": <UserHeartLineIcon />, - "user-received-2-line": <UserReceived2LineIcon />, - "user-shared-line": <UserSharedLineIcon />, - "user-unfollow-line": <UserUnfollowLineIcon />, - "view-all": <RightArrowIcon />, - "view-less": <LeftArrowIcon />, - "warning-line": <WarningLineIcon />, - "warning-triangle": <WarningTriangleIcon />, - "money-dollar-circle-line": <MoneyDollarCircleLineIcon />, - "success-line": <SuccessLineIcon />, - "error-line": <ErrorLineIcon />, - "history-line": <HistoryLineIcon />, - billing: <BillingIcon />, - book: <BookIcon />, - bug: <BugIcon />, - cancel: <CancelIcon />, - chat: <Chat />, - close: <CloseIcon />, - code: <CodeViewIcon />, - column: <ColumnIcon />, - cross: <CrossIcon />, - danger: <ErrorIcon />, - datasource: <DatasourceIcon />, - delete: <Trash />, - desktop: <DesktopIcon />, - discord: <DiscordIcon />, - downArrow: <DownArrow />, - download2: <DownloadIcon />, - download: <Download />, - dropdown: <DropdownIcon />, - duplicate: <DuplicateIcon />, - edit: <EditIcon />, - emoji: <Emoji />, - enterprise: <MagicLineIcon />, - error: <ErrorIcon />, - execute: <ExecuteIcon />, - filter: <Filter />, - fluid: <FluidIcon />, - fork: <GitMerge />, - gear: <GearIcon />, - general: <GeneralIcon />, - guide: <GuideIcon />, - hamburger: <HamburgerIcon />, - help: <HelpIcon />, - info: <InfoIcon />, - js: <JsIcon />, - key: <KeyIcon />, - lightning: <LightningIcon />, - link: <LinkIcon />, - loader: <LoaderLineIcon />, - login: <LoginIcon />, - logout: <LogoutIcon />, - manage: <ManageIcon />, - member: <UserHeartLineIcon />, - minus: <RemoveIcon />, - mobile: <MobileIcon />, - open: <OpenIcon />, - pantone: <PantoneLineIcon />, - pin: <Pin />, - play: <PlayIcon />, - plus: <CreateNewIcon />, - query: <QueryIcon />, - reaction: <Reaction />, - refresh: <RefreshLineIcon />, - rocket: <RocketIcon />, - search: <SearchIcon />, - setting: <SettingIcon />, - share: <ShareForwardIcon />, - shine: <ShineIcon />, - snippet: <Snippet />, - success: <SuccessIcon />, - support: <SupportIcon />, - tables: <TableIcon />, - tablet: <TabletIcon />, - tabletLandscape: <TabletLandscapeIcon />, - trash: <Trash />, - unpin: <Unpin />, - upArrow: <UpArrow />, - upgrade: <DvdLineIcon />, - upload: <Upload />, - user: <UserIcon />, - wand: <WandIcon />, - warning: <WarningIcon />, - widget: <WidgetIcon />, - workspace: <WorkspaceIcon />, - "clear-interval": <ClearInterval />, - "clear-store": <ClearStore />, - "copy-to-clipboard": <CopyToClipboard />, - "download-action": <DownloadAction />, - "execute-js": <ExecuteJs />, - "execute-query": <ExecuteQuery />, - "get-geolocation": <GetGeolocation />, - modal: <Modal />, - "navigate-to": <NavigateTo />, - "remove-store": <RemoveStore />, - "reset-widget": <ResetWidget />, - "set-interval": <SetInterval />, - "show-alert": <ShowAlert />, - "stop-watch-geolocation": <StopWatchGeolocation />, - "store-value": <StoreValue />, - "watch-geolocation": <WatchGeolocation />, - "run-api": <RunAPI />, - "post-message": <PostMessage />, - "no-action": <NoAction />, - package: <PackageIcon />, - devices: <DevicesIcon />, - grid: <GridIcon />, - updates: <UpdatesIcon />, - "pencil-line": <PencilLineIcon />, -}; - -export const IconCollection = Object.keys(ICON_LOOKUP); - -export type IconName = (typeof IconCollection)[number]; - -export interface IconProps { - size?: IconSize; - name?: IconName; - invisible?: boolean; - className?: string; - onClick?: (e: React.MouseEvent) => void; - fillColor?: string; - hoverFillColor?: string; - keepColors?: boolean; - loaderWithIconWrapper?: boolean; - clickable?: boolean; - disabled?: boolean; - withWrapper?: boolean; - wrapperColor?: string; -} - -const Icon = forwardRef( - ( - { onClick, ...props }: IconProps & CommonComponentProps, - ref: Ref<HTMLSpanElement>, - ) => { - const iconName = props.name; - const returnIcon = - ICON_LOOKUP[iconName as keyof typeof ICON_LOOKUP] || null; - - const clickable = props.clickable === undefined ? true : props.clickable; - - let loader = <Spinner size={props.size} />; - if (props.loaderWithIconWrapper) { - loader = ( - <IconWrapper className={Classes.ICON} clickable={clickable} {...props}> - <Spinner size={props.size} /> - </IconWrapper> - ); - } - - return returnIcon && !props.isLoading ? ( - <IconWrapper - className={`${Classes.ICON} ${props.className}`} - clickable={clickable} - data-cy={props.cypressSelector} - onClick={props.disabled ? noop : onClick} - ref={ref} - {...props} - > - {returnIcon} - </IconWrapper> - ) : props.isLoading ? ( - loader - ) : null; - }, -); - -Icon.displayName = "Icon"; - -export default React.memo(Icon); diff --git a/app/client/packages/design-system/ads-old/src/IconSelector/index.tsx b/app/client/packages/design-system/ads-old/src/IconSelector/index.tsx index 8431cd949db8..d24bb6f305b0 100644 --- a/app/client/packages/design-system/ads-old/src/IconSelector/index.tsx +++ b/app/client/packages/design-system/ads-old/src/IconSelector/index.tsx @@ -2,7 +2,7 @@ import React, { useState, useEffect, useRef } from "react"; import styled from "styled-components"; import type { AppIconName } from "../AppIcon"; import AppIcon, { AppIconCollection } from "../AppIcon"; -import { Size } from "../Button"; +import { Size } from "../AppIcon"; import type { CommonComponentProps } from "../types/common"; import { Classes } from "../constants/classes"; diff --git a/app/client/packages/design-system/ads-old/src/MenuItem/index.tsx b/app/client/packages/design-system/ads-old/src/MenuItem/index.tsx index 16dc3f46b2f9..ffe22f6815e7 100644 --- a/app/client/packages/design-system/ads-old/src/MenuItem/index.tsx +++ b/app/client/packages/design-system/ads-old/src/MenuItem/index.tsx @@ -3,15 +3,15 @@ import React, { forwardRef } from "react"; import type { CommonComponentProps } from "../types/common"; import { Classes } from "../constants/classes"; import styled from "styled-components"; -import type { IconName } from "../Icon"; -import Icon, { IconSize } from "../Icon"; +import type { IconNames } from "@appsmith/ads"; +import { Icon } from "@appsmith/ads"; import TooltipComponent from "../Tooltip"; import Text, { TextType, FontWeight } from "../Text"; // eslint-disable-next-line @typescript-eslint/no-restricted-imports import type { PopoverPosition } from "@blueprintjs/core/lib/esnext/components/popover/popoverSharedProps"; export type MenuItemProps = CommonComponentProps & { - icon?: IconName; + icon?: IconNames; text: string; label?: ReactNode; href?: string; @@ -98,14 +98,7 @@ const MenuItemContent = forwardRef( type={props.type} > <IconContainer className={props.containerClassName}> - {props.icon ? ( - <Icon - isLoading={props.isLoading} - loaderWithIconWrapper - name={props.icon} - size={IconSize.LARGE} - /> - ) : null} + {props.icon ? <Icon name={props.icon} size="md" /> : null} {props.text && ( <Text type={TextType.H5} weight={FontWeight.NORMAL}> {props.ellipsize diff --git a/app/client/packages/design-system/ads-old/src/Spinner/index.tsx b/app/client/packages/design-system/ads-old/src/Spinner/index.tsx deleted file mode 100644 index 3e787ac0d306..000000000000 --- a/app/client/packages/design-system/ads-old/src/Spinner/index.tsx +++ /dev/null @@ -1,59 +0,0 @@ -import React from "react"; -import styled, { keyframes } from "styled-components"; -import type { IconSize } from "../Icon"; -import { sizeHandler } from "../Icon"; -import { Classes } from "../constants/classes"; - -const rotate = keyframes` - 100% { - transform: rotate(360deg); - } -`; - -const dash = keyframes` - 0% { - stroke-dasharray: 1, 150; - stroke-dashoffset: 0; - } - 50% { - stroke-dasharray: 90, 150; - stroke-dashoffset: -35; - } - 100% { - stroke-dasharray: 90, 150; - stroke-dashoffset: -124; - } -`; - -const SvgContainer = styled.svg<SpinnerProp>` - animation: ${rotate} 2s linear infinite; - width: ${(props) => sizeHandler(props.size)}px; - height: ${(props) => sizeHandler(props.size)}px; -`; - -const SvgCircle = styled.circle` - stroke: var(--ads-v2-color-fg-subtle); - stroke-linecap: round; - animation: ${dash} 1.5s ease-in-out infinite; - stroke-width: var(--ads-spaces-1); -`; - -export interface SpinnerProp { - size?: IconSize; -} - -Spinner.defaultProp = { - size: "small", -}; - -export default function Spinner(props: SpinnerProp) { - return ( - <SvgContainer - className={Classes.SPINNER} - size={props.size} - viewBox="0 0 50 50" - > - <SvgCircle cx="25" cy="25" fill="none" r="20" /> - </SvgContainer> - ); -} diff --git a/app/client/packages/design-system/ads-old/src/Table/index.tsx b/app/client/packages/design-system/ads-old/src/Table/index.tsx index 56999474600b..e18d6c2c84ac 100644 --- a/app/client/packages/design-system/ads-old/src/Table/index.tsx +++ b/app/client/packages/design-system/ads-old/src/Table/index.tsx @@ -3,8 +3,7 @@ import React from "react"; import styled from "styled-components"; import { Classes } from "../constants/classes"; import { typography } from "../constants/typography"; -import Spinner from "../Spinner"; -import { IconSize } from "../Icon"; +import { Spinner } from "@appsmith/ads"; import { importSvg } from "../utils/icon-loadables"; const DownArrow = importSvg( @@ -192,11 +191,7 @@ function Table(props: TableProps) { <tr className="no-hover"> <td className="no-border" colSpan={columns?.length}> <CentralizedWrapper> - {loaderComponent ? ( - loaderComponent - ) : ( - <Spinner size={IconSize.XXL} /> - )} + {loaderComponent ? loaderComponent : <Spinner size="lg" />} </CentralizedWrapper> </td> </tr> diff --git a/app/client/packages/design-system/ads-old/src/Tabs/index.tsx b/app/client/packages/design-system/ads-old/src/Tabs/index.tsx deleted file mode 100644 index 040bedf11710..000000000000 --- a/app/client/packages/design-system/ads-old/src/Tabs/index.tsx +++ /dev/null @@ -1,426 +0,0 @@ -import type { RefObject } from "react"; -import React, { useCallback, useState, useEffect } from "react"; -import { Tab, Tabs, TabList, TabPanel } from "react-tabs"; -import "react-tabs/style/react-tabs.css"; -import styled from "styled-components"; -import type { IconName } from "../Icon"; -import Icon, { IconSize } from "../Icon"; -import { useResizeObserver } from "../hooks"; -import { Classes } from "../constants/classes"; -import type { CommonComponentProps } from "../types/common"; -import { typography } from "../constants/typography"; - -export const TAB_MIN_HEIGHT = `36px`; - -export interface TabProp { - key: string; - title: string; - count?: number; - panelComponent?: JSX.Element; - icon?: IconName; - iconSize?: IconSize; -} - -const TabsWrapper = styled.div<{ - shouldOverflow?: boolean; - vertical?: boolean; - responseViewer?: boolean; -}>` - border-radius: 0px; - height: 100%; - overflow: hidden; - .react-tabs { - height: 100%; - } - .react-tabs__tab-panel { - height: calc(100% - ${TAB_MIN_HEIGHT}); - overflow: auto; - } - .react-tabs__tab-list { - margin: 0px; - display: flex; - flex-direction: ${(props) => (!!props.vertical ? "column" : "row")}; - align-items: ${(props) => (!!props.vertical ? "stretch" : "center")}; - border-bottom: none; - color: var(--ads-tabs-default-tab-list-text-color); - path { - fill: var(--ads-tabs-default-tab-list-svg-fill-color); - } - ${(props) => - props.shouldOverflow && - ` - overflow-y: hidden; - overflow-x: auto; - white-space: nowrap; - `} - - ${(props) => - props.responseViewer && - ` - margin-left: 30px; - display: flex; - align-items: center; - height: 24px; - background-color: var(--ads-tabs-default-tab-list-response-viewer-background-color) !important; - width: fit-content; - padding-left: 1px; - margin-top: 10px !important; - margin-bottom: 10px !important; - `} - } - .react-tabs__tab { - align-items: center; - text-align: center; - display: inline-flex; - justify-content: center; - border-color: transparent; - position: relative; - - padding: 0px 3px; - margin-right: ${(props) => - !props.vertical ? `calc(var(--ads-spaces-12) - 3px)` : 0}; - } - - .react-tabs__tab, - .react-tabs__tab:focus { - box-shadow: none; - border: none; - &:after { - content: none; - } - - ${(props) => - props.responseViewer && - ` - display: flex; - align-items: center; - cursor: pointer; - height: 22px; - padding: 0 12px; - border: 1px solid var(--ads-tabs-default-tab-focus-response-viewer-border-color); - margin-right: -1px; - margin-left: -1px; - margin-top: -2px; - height: 100%; - `} - } - - .react-tabs__tab--selected { - background-color: transparent; - path { - fill: var(--ads-tabs-tab-selected-svg-fill-color); - } - - ${(props) => - props.responseViewer && - ` - background-color: var(--ads-tabs-tab-selected-response-viewer-background-color); - border: 1px solid var(--ads-tabs-tab-selected-response-viewer-border-color); - border-radius: 0px; - font-weight: normal; - `} - } -`; - -export const TabTitle = styled.span<{ responseViewer?: boolean }>` - font-size: ${typography.h5.fontSize}px; - font-weight: var(--ads-font-weight-bold); - line-height: var(--ads-spaces-6); - letter-spacing: ${typography.h5.letterSpacing}px; - margin: 0; - display: flex; - align-items: center; - - ${(props) => - props.responseViewer && - ` - font-size: 12px; - font-weight: normal; - line-height: 16px; - letter-spacing: normal; - text-transform: uppercase; - color: var(--ads-tabs-tab-title-response-viewer-text-color); - `} -`; - -export const TabCount = styled.div` - background-color: var(--ads-tabs-count-background-color); - border-radius: 8px; - min-width: 17px; - height: 17px; - font-size: 9px; - margin-left: 4px; - display: flex; - align-items: center; - justify-content: center; - padding: 0 2px; -`; - -const TabTitleWrapper = styled.div<{ - selected: boolean; - vertical: boolean; - responseViewer?: boolean; -}>` - display: flex; - align-items: center; - width: 100%; - padding: calc(var(--ads-spaces-3) - 1px) - ${(props) => (props.vertical ? `calc(var(--ads-spaces-4) - 1px)` : 0)} - calc(var(--ads-spaces-4) - 1px) - ${(props) => (props.vertical ? `calc(var(--ads-spaces-4) - 1px)` : 0)}; - color: var(--ads-tabs-title-wrapper-text-color); - &:hover { - color: var(--ads-tabs-title-wrapper-hover-text-color); - .${Classes.ICON} { - svg { - fill: var(--ads-tabs-title-wrapper-hover-text-color); - path { - fill: var(--ads-tabs-title-wrapper-hover-text-color); - } - } - } - } - - ${(props) => - props.responseViewer && - ` - padding: 0px; - `} - - .${Classes.ICON} { - margin-right: var(--ads-spaces-1); - border-radius: 50%; - svg { - width: 16px; - height: 16px; - margin: auto; - fill: var(--ads-tabs-title-wrapper-icon-fill-color); - path { - fill: var(--ads-tabs-title-wrapper-icon-fill-color); - } - } - } - - ${(props) => - props.selected - ? ` - background-color: transparent; - color: var(--ads-color-black-900); - .${Classes.ICON} { - svg { - path { - fill: var(--ads-color-black-900) - } - } - } - - .tab-title { - ${ - props.responseViewer && - ` - font-weight: normal; - ` - } - } - - &::after { - content: ""; - position: absolute; - width: ${props.vertical ? `calc(var(--ads-spaces-1) - 2px)` : "100%"}; - bottom: ${props.vertical ? "0%" : `calc(var(--ads-spaces-0) - 1px)`}; - top: ${ - props.vertical ? `calc(var(--ads-spaces-0) - 1px)` : "calc(100% - 2px)" - }; - left: var(--ads-spaces-0); - height: ${props.vertical ? "100%" : `calc(var(--ads-spaces-1) - 2px)`}; - background-color: var(--ads-color-brand); - z-index: var(--ads-z-index-3); - - ${ - props.responseViewer && - ` - display: none; - ` - } - } - ` - : ""} -`; - -const CollapseIconWrapper = styled.div` - position: absolute; - right: 14px; - top: calc(var(--ads-spaces-3) - 1px); - cursor: pointer; -`; - -export interface TabItemProps { - tab: TabProp; - selected: boolean; - vertical: boolean; - responseViewer?: boolean; -} - -function DefaultTabItem(props: TabItemProps) { - const { responseViewer, selected, tab, vertical } = props; - return ( - <TabTitleWrapper - responseViewer={responseViewer} - selected={selected} - vertical={vertical} - > - {tab.icon ? ( - <Icon - name={tab.icon} - size={tab.iconSize != null ? tab.iconSize : IconSize.XXXL} - /> - ) : null} - <TabTitle className="tab-title" responseViewer={responseViewer}> - {tab.title} - </TabTitle> - {tab.count && tab.count > 0 ? ( - <TabCount data-testid="t--tab-count">{tab.count}</TabCount> - ) : null} - </TabTitleWrapper> - ); -} - -export type TabbedViewComponentType = CommonComponentProps & { - tabs: Array<TabProp>; - selectedIndex?: number; - onSelect?: (tabIndex: number) => void; - overflow?: boolean; - vertical?: boolean; - tabItemComponent?: (props: TabItemProps) => JSX.Element; - responseViewer?: boolean; - canCollapse?: boolean; - // Reference to container for collapsing or expanding content - containerRef?: RefObject<HTMLElement>; - // height of container when expanded - expandedHeight?: string; -}; - -// Props required to support a collapsible (foldable) tab component -export interface CollapsibleTabProps { - // Reference to container for collapsing or expanding content - containerRef: RefObject<HTMLDivElement>; - // height of container when expanded( usually the default height of the tab component) - expandedHeight: string; -} - -export type CollapsibleTabbedViewComponentType = TabbedViewComponentType & - CollapsibleTabProps; - -export const collapsibleTabRequiredPropKeys: Array<keyof CollapsibleTabProps> = - ["containerRef", "expandedHeight"]; - -// Tab is considered collapsible only when all required collapsible props are present -export const isCollapsibleTabComponent = ( - props: TabbedViewComponentType | CollapsibleTabbedViewComponentType, -): props is CollapsibleTabbedViewComponentType => - collapsibleTabRequiredPropKeys.every((key) => key in props); - -export function TabComponent( - props: TabbedViewComponentType | CollapsibleTabbedViewComponentType, -) { - const { onSelect, tabItemComponent } = props; - const TabItem = tabItemComponent || DefaultTabItem; - // for setting selected state of an uncontrolled component - const [selectedIndex, setSelectedIndex] = useState(props.selectedIndex || 0); - const [isExpanded, setIsExpanded] = useState(true); - - useEffect(() => { - if (typeof props.selectedIndex === "number") - setSelectedIndex(props.selectedIndex); - }, [props.selectedIndex]); - - const toggleCollapse = () => { - if (!isCollapsibleTabComponent(props)) return; - const { containerRef, expandedHeight } = props; - if (containerRef?.current && expandedHeight) { - containerRef.current.style.height = isExpanded - ? TAB_MIN_HEIGHT - : expandedHeight; - } - setIsExpanded((prev) => !prev); - }; - - const resizeCallback = useCallback( - (entries: ResizeObserverEntry[]) => { - if (entries && entries.length) { - const { - contentRect: { height }, - } = entries[0]; - if (height > Number(TAB_MIN_HEIGHT.replace("px", "")) + 6) { - !isExpanded && setIsExpanded(true); - } else { - isExpanded && setIsExpanded(false); - } - } - }, - [isExpanded], - ); - - useResizeObserver( - isCollapsibleTabComponent(props) ? props.containerRef?.current : null, - resizeCallback, - ); - - useEffect(() => { - if (!isCollapsibleTabComponent(props)) return; - const { containerRef } = props; - if (!isExpanded && containerRef.current) { - containerRef.current.style.height = TAB_MIN_HEIGHT; - } - }, [isExpanded]); - - return ( - <TabsWrapper - className={props.className} - data-cy={props.cypressSelector} - responseViewer={props.responseViewer} - shouldOverflow={props.overflow} - vertical={props.vertical} - > - {isCollapsibleTabComponent(props) && ( - <CollapseIconWrapper className="t--tabs-collapse-icon"> - <Icon - name={isExpanded ? "expand-more" : "expand-less"} - onClick={toggleCollapse} - size={IconSize.XXXXL} - /> - </CollapseIconWrapper> - )} - - <Tabs - onSelect={(index: number) => { - onSelect ? onSelect(index) : setSelectedIndex(index); - !isExpanded && toggleCollapse(); - }} - selectedIndex={props.selectedIndex} - > - <TabList> - {props.tabs.map((tab, index) => ( - <Tab - data-cy={`t--tab-${tab.key}`} - data-replay-id={tab.key} - key={tab.key} - > - <TabItem - responseViewer={props.responseViewer} - selected={ - index === props.selectedIndex || index === selectedIndex - } - tab={tab} - vertical={!!props.vertical} - /> - </Tab> - ))} - </TabList> - {props.tabs.map((tab) => ( - <TabPanel key={tab.key}>{tab.panelComponent}</TabPanel> - ))} - </Tabs> - </TabsWrapper> - ); -} diff --git a/app/client/packages/design-system/ads-old/src/TextInput/index.tsx b/app/client/packages/design-system/ads-old/src/TextInput/index.tsx deleted file mode 100644 index 9e5cc06337c2..000000000000 --- a/app/client/packages/design-system/ads-old/src/TextInput/index.tsx +++ /dev/null @@ -1,475 +0,0 @@ -import type { EventHandler, FocusEvent, Ref } from "react"; -import React, { - forwardRef, - useCallback, - useEffect, - useMemo, - useState, -} from "react"; -import type { CommonComponentProps } from "../types/common"; -import { Classes } from "../constants/classes"; -import { typography } from "../constants/typography"; -import { Classes as BlueprintClasses } from "@blueprintjs/core"; -import styled from "styled-components"; -import Text, { TextType } from "../Text"; -import { - ERROR_MESSAGE_NAME_EMPTY, - createMessage, - FORM_VALIDATION_INVALID_EMAIL, -} from "../constants/messages"; -import type { IconName } from "../Icon"; -import Icon, { IconCollection, IconSize } from "../Icon"; -import { AsyncControllableInput } from "@blueprintjs/core/lib/esm/components/forms/asyncControllableInput"; -import _ from "lodash"; -import { replayHighlightClass } from "../constants/classes"; -import { hexToRgba } from "../utils/colors"; - -export type InputType = "text" | "password" | "number" | "email" | "tel"; - -export type Validator = (value: string) => { - isValid: boolean; - message: string; -}; - -// TODO (abhinav): Use a regex which adheres to standards RFC5322 -const isEmail = (value: string) => { - const re = - /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; - return re.test(value); -}; - -export function emailValidator(email: string) { - let isValid = true; - if (email) { - isValid = isEmail(email); - } - return { - isValid: isValid, - message: !isValid ? createMessage(FORM_VALIDATION_INVALID_EMAIL) : "", - }; -} - -export function notEmptyValidator(value: string) { - const isValid = !!value; - return { - isValid: isValid, - message: !isValid ? createMessage(ERROR_MESSAGE_NAME_EMPTY) : "", - }; -} - -export type TextInputProps = CommonComponentProps & { - autoFocus?: boolean; - placeholder?: string; - fill?: boolean; - defaultValue?: string; - value?: string; - validator?: (value: string) => { isValid: boolean; message: string }; - onChange?: (value: string) => void; - readOnly?: boolean; - dataType?: string; - leftIcon?: IconName; - prefix?: string; - helperText?: string; - rightSideComponent?: React.ReactNode; - width?: string; - height?: string; - noBorder?: boolean; - noCaret?: boolean; - onBlur?: EventHandler<FocusEvent<any>>; - onFocus?: EventHandler<FocusEvent<any>>; - errorMsg?: string; - trimValue?: boolean; - $padding?: string; - useTextArea?: boolean; - isCopy?: boolean; - border?: boolean; - style?: any; - tabIndex?: number; -}; - -interface boxReturnType { - bgColor: string; - color: string; - borderColor: string; -} - -const boxStyles = (props: TextInputProps, isValid: boolean): boxReturnType => { - let bgColor = "var(--ads-text-input-text-box-default-background-color)"; - let color = "var(--ads-text-input-text-box-default-text-color)"; - let borderColor = "var(--ads-text-input-text-box-default-border-color)"; - - if (props.disabled) { - bgColor = "var(--ads-text-input-text-box-disabled-background-color)"; - color = "var(--ads-text-input-text-box-disabled-text-color)"; - borderColor = "var(--ads-text-input-text-box-disabled-border-color)"; - } - if (props.readOnly) { - bgColor = "var(--ads-text-input-text-box-read-only-background-color)"; - color = "var(--ads-text-input-text-box-read-only-text-color)"; - borderColor = "var(--ads-text-input-text-box-read-only-border-color)"; - } - if (!isValid) { - bgColor = hexToRgba("var(--ads-danger-main)", 0.1); - color = "var(--ads-danger-main)"; - borderColor = "var(--ads-danger-main)"; - } - return { bgColor, color, borderColor }; -}; - -const InputLoader = styled.div<{ - $value?: string; - $noBorder?: boolean; - $isFocused?: boolean; - $isLoading?: boolean; - $height?: string; -}>` - display: ${(props) => (props.$isLoading ? "static" : "none")}; - border-radius: 0; - width: ${(props) => - props.$value && !props.$noBorder && props.$isFocused - ? "calc(100% - 50px)" - : "100%"}; - - height: ${(props) => props.$height || "36px"}; -`; - -const StyledInput = styled((props) => { - // we are removing non input related props before passing them in the components - // eslint-disable @typescript-eslint/no-unused-vars - const { dataType, inputRef, ...inputProps } = props; - - const omitProps = [ - "hasLeftIcon", - "inputStyle", - "rightSideComponentWidth", - "validator", - "isValid", - "cypressSelector", - "leftIcon", - "helperText", - "rightSideComponent", - "noBorder", - "isLoading", - "noCaret", - "fill", - "errorMsg", - "useTextArea", - "border", - "asyncControl", - "handleCopy", - "prefix", - ]; - - const HtmlTag = props.useTextArea ? "textarea" : "input"; - - return props.asyncControl ? ( - <AsyncControllableInput - {..._.omit(inputProps, omitProps)} - datatype={dataType} - inputRef={inputRef} - /> - ) : ( - <HtmlTag ref={inputRef} {..._.omit(inputProps, omitProps)} /> - ); -})< - TextInputProps & { - inputStyle: boxReturnType; - isValid: boolean; - rightSideComponentWidth: number; - hasLeftIcon: boolean; - $isLoading?: boolean; - } ->` - display: ${(props) => (props.$isLoading ? "none" : "static")}; - ${(props) => (props.noCaret ? "caret-color: white;" : null)}; - color: ${(props) => props.inputStyle.color}; - width: ${(props) => - props.value && !props.noBorder && props.isFocused - ? "calc(100% - 50px)" - : "100%"}; - border-radius: 0; - outline: 0; - box-shadow: none; - border: none; - padding: 0px var(--ads-spaces-6); - ${(props) => (props.$padding ? `padding: ${props.$padding}` : "")}; - padding-right: ${(props) => - `calc(${props.rightSideComponentWidth}px + var(--ads-spaces-6))`}; - background-color: transparent; - font-size: ${typography.p1.fontSize}px; - font-weight: ${typography.p1.fontWeight}; - line-height: ${typography.p1.lineHeight}px; - letter-spacing: ${typography.p1.letterSpacing}px; - text-overflow: ellipsis; - height: 100%; - - &::placeholder { - color: var(--ads-text-input-placeholder-text-color); - } - &:disabled { - cursor: not-allowed; - } -`; - -export const InputWrapper = styled.div<{ - value?: string; - isFocused: boolean; - fill?: number; - noBorder?: boolean; - height?: string; - width?: string; - inputStyle: boxReturnType; - isValid?: boolean; - disabled?: boolean; - $isLoading?: boolean; - readOnly?: boolean; -}>` - position: relative; - display: flex; - align-items: center; - width: ${(props) => - props.fill ? "100%" : props.width ? props.width : "260px"}; - height: ${(props) => props.height || "36px"}; - border: 1.2px solid - ${(props) => - props.noBorder ? "transparent" : props.inputStyle.borderColor}; - background-color: ${(props) => props.inputStyle.bgColor}; - color: ${(props) => props.inputStyle.color}; - ${(props) => - props.isFocused && !props.noBorder && !props.disabled && !props.readOnly - ? ` - border: 1.2px solid - ${ - props.isValid - ? "var(--appsmith-input-focus-border-color)" - : "var(--ads-danger-main)" - }; - ` - : null} - - .${Classes.TEXT} { - color: var(--ads-danger-main); - } - .helper { - .${Classes.TEXT} { - color: var(--ads-text-input-helper-text-text-color); - } - } - &:hover { - background-color: ${(props) => - props.disabled || props.readOnly - ? props.inputStyle.bgColor - : "var(--ads-text-input-text-box-hover-background-color)"}; - } - ${(props) => (props.disabled ? "cursor: not-allowed;" : null)} -`; - -const MsgWrapper = styled.div` - position: absolute; - bottom: -20px; - left: 0px; - &.helper { - .${Classes.TEXT} { - color: var(--ads-text-input-helper-text-text-color); - } - } -`; - -const RightSideContainer = styled.div` - position: absolute; - right: var(--ads-spaces-6); - bottom: 0; - top: 0; - display: flex; - align-items: center; -`; - -const IconWrapper = styled.div` - .${Classes.ICON} { - margin-right: var(--ads-spaces-5); - } -`; - -const PrefixWrapper = styled.div` - .${Classes.TEXT} { - padding-left: var(--ads-spaces-2); - color: var(--ads-color-black-400); - } -`; - -const initialValidation = (props: TextInputProps) => { - let validationObj = { isValid: true, message: "" }; - if (props.defaultValue && props.validator) { - validationObj = props.validator(props.defaultValue); - } - return validationObj; -}; - -const TextInput = forwardRef( - (props: TextInputProps, ref: Ref<HTMLInputElement>) => { - // - const [validation, setValidation] = useState<{ - isValid: boolean; - message: string; - }>(initialValidation(props)); - - const [rightSideComponentWidth, setRightSideComponentWidth] = useState(0); - const [isFocused, setIsFocused] = useState(false); - const [inputValue, setInputValue] = useState(props.defaultValue); - - const { trimValue = false } = props; - - const setRightSideRef = useCallback((ref: HTMLDivElement) => { - if (ref) { - const { width } = ref.getBoundingClientRect(); - setRightSideComponentWidth(width); - } - }, []); - - const inputStyle = useMemo( - () => boxStyles(props, validation?.isValid), - [props, validation?.isValid], - ); - - // set the default value - useEffect(() => { - if (props.defaultValue) { - const inputValue = props.defaultValue; - setInputValue(inputValue); - checkValidator(inputValue); - props.onChange && props.onChange(inputValue); - } - }, [props.defaultValue]); - - const checkValidator = (inputValue: string) => { - const inputValueValidation = - props.validator && props.validator(inputValue); - if (inputValueValidation) { - props.validator && setValidation(inputValueValidation); - } - }; - - const memoizedChangeHandler = useCallback( - (el) => { - const inputValue: string = trimValue - ? el.target.value.trim() - : el.target.value; - setInputValue(inputValue); - checkValidator(inputValue); - return props.onChange && props.onChange(inputValue); - }, - [props.onChange, setValidation, trimValue], - ); - - const onBlurHandler = useCallback( - (e: React.FocusEvent<any>) => { - setIsFocused(false); - if (props.onBlur) props.onBlur(e); - }, - [setIsFocused, props.onBlur], - ); - - const onFocusHandler = useCallback((e: React.FocusEvent<any>) => { - setIsFocused(true); - if (props.onFocus) props.onFocus(e); - }, []); - - const ErrorMessage = ( - <MsgWrapper> - <Text type={TextType.P3}> - {props.errorMsg ? props.errorMsg : validation?.message} - </Text> - </MsgWrapper> - ); - - const HelperMessage = ( - <MsgWrapper className="helper"> - <Text type={TextType.P3}>* {props.helperText}</Text> - </MsgWrapper> - ); - - const iconColor = !validation?.isValid - ? "var(--ads-danger-main)" - : "var(--ads-text-input-icon-path-color)"; - - const hasLeftIcon = props.leftIcon - ? IconCollection.includes(props.leftIcon) - : false; - - return ( - <InputWrapper - $isLoading={props.isLoading} - className={replayHighlightClass} - disabled={props.disabled} - fill={props.fill ? 1 : 0} - height={props.height || undefined} - inputStyle={inputStyle} - isFocused={isFocused} - isValid={validation?.isValid} - noBorder={props.noBorder} - readOnly={props.readOnly} - value={inputValue} - width={props.width || undefined} - > - {props.leftIcon && ( - <IconWrapper className="left-icon"> - <Icon - fillColor={iconColor} - name={props.leftIcon} - size={IconSize.MEDIUM} - /> - </IconWrapper> - )} - - {props.prefix && ( - <PrefixWrapper className="prefix"> - <Text type={TextType.P1}>{props.prefix}</Text> - </PrefixWrapper> - )} - - <InputLoader - $height={props.height} - $isFocused={isFocused} - $isLoading={props.isLoading} - $noBorder={props.noBorder} - $value={props.value} - className={BlueprintClasses.SKELETON} - /> - - <StyledInput - $isLoading={props.isLoading} - autoFocus={props.autoFocus} - defaultValue={props.defaultValue} - inputStyle={inputStyle} - isValid={validation?.isValid} - ref={ref} - type={props.dataType || "text"} - {...props} - data-cy={props.cypressSelector} - hasLeftIcon={hasLeftIcon} - inputRef={ref} - name={props?.name} - onBlur={onBlurHandler} - onChange={memoizedChangeHandler} - onFocus={onFocusHandler} - placeholder={props.placeholder} - readOnly={props.readOnly} - rightSideComponentWidth={rightSideComponentWidth} - tabIndex={props.tabIndex ?? 0} - /> - {validation?.isValid && - props.helperText && - props.helperText.length > 0 && - HelperMessage} - {ErrorMessage} - <RightSideContainer className="right-icon" ref={setRightSideRef}> - {props.rightSideComponent} - </RightSideContainer> - </InputWrapper> - ); - }, -); - -TextInput.displayName = "TextInput"; - -export default TextInput; diff --git a/app/client/packages/design-system/ads-old/src/TreeDropdown/index.tsx b/app/client/packages/design-system/ads-old/src/TreeDropdown/index.tsx index e7c9ebfcdfe4..0a5c6a3322e5 100644 --- a/app/client/packages/design-system/ads-old/src/TreeDropdown/index.tsx +++ b/app/client/packages/design-system/ads-old/src/TreeDropdown/index.tsx @@ -18,7 +18,7 @@ import { Classes, } from "@blueprintjs/core"; import styled from "styled-components"; -import Icon, { IconSize } from "../Icon"; +import { Icon } from "@appsmith/ads"; import { replayHighlightClass } from "../constants/classes"; import useDSEvent from "../hooks/useDSEvent"; import { DSEventTypes } from "../types/common"; @@ -626,7 +626,7 @@ function TreeDropdown(props: TreeDropdownProps) { }`} elementRef={buttonRef} onKeyDown={handleKeydown} - rightIcon={<Icon name="down-arrow" size={IconSize.XXL} />} + rightIcon={<Icon name="down-arrow" size="md" />} text={ selectedLabelModifier ? selectedLabelModifier(selectedOptionFromProps, displayValue) diff --git a/app/client/packages/design-system/ads-old/src/constants/classes.ts b/app/client/packages/design-system/ads-old/src/constants/classes.ts index 193150fc03f8..e49de106d7ca 100644 --- a/app/client/packages/design-system/ads-old/src/constants/classes.ts +++ b/app/client/packages/design-system/ads-old/src/constants/classes.ts @@ -1,5 +1,5 @@ export enum Classes { - ICON = "cs-icon", + ICON = "ads-v2-icon", APP_ICON = "cs-app-icon", TEXT = "cs-text", BP3_POPOVER_ARROW_BORDER = "bp3-popover-arrow-border", diff --git a/app/client/packages/design-system/ads-old/src/index.ts b/app/client/packages/design-system/ads-old/src/index.ts index 7359c6e804f0..b7ca23f274fe 100644 --- a/app/client/packages/design-system/ads-old/src/index.ts +++ b/app/client/packages/design-system/ads-old/src/index.ts @@ -3,12 +3,6 @@ export { default as AppIcon } from "./AppIcon"; export * from "./AppIcon"; -export { default as Breadcrumbs } from "./Breadcrumbs"; -export * from "./Breadcrumbs"; - -export { default as Button } from "./Button"; -export * from "./Button"; - export { default as Checkbox } from "./Checkbox"; export * from "./Checkbox"; @@ -26,8 +20,11 @@ export * from "./DisplayImageUpload"; export { default as DraggableList } from "./DraggableList"; export * from "./DraggableList"; -export { default as Dropdown } from "./Dropdown"; -export * from "./Dropdown"; +export type { + DropdownOption, + DropdownOnSelect, + RenderDropdownOptionType, +} from "./Dropdown"; export { default as EditableText } from "./EditableText"; export * from "./EditableText"; @@ -48,9 +45,6 @@ export * from "./GifPlayer"; export * from "./HighlightText"; -export { default as Icon } from "./Icon"; -export * from "./Icon"; - export { default as IconSelector } from "./IconSelector"; export * from "./IconSelector"; @@ -69,9 +63,6 @@ export * from "./RectangularSwitcher"; export { default as SearchComponent } from "./SearchComponent"; export * from "./SearchComponent"; -export { default as Spinner } from "./Spinner"; -export * from "./Spinner"; - export { default as Statusbar } from "./Statusbar"; export * from "./Statusbar"; @@ -81,8 +72,6 @@ export * from "./Switch"; export { default as Switcher } from "./Switcher"; export * from "./Switcher"; -export * from "./Tabs"; - export { default as Table } from "./Table"; export * from "./Table"; @@ -92,9 +81,6 @@ export * from "./TagInput"; export { default as Text } from "./Text"; export * from "./Text"; -export { default as TextInput } from "./TextInput"; -export * from "./TextInput"; - export { default as TooltipComponent } from "./Tooltip"; export * from "./Tooltip"; @@ -108,3 +94,5 @@ export * from "./constants/variants"; export * from "./types/common"; export * from "./utils/colors"; export * from "./utils/icon-loadables"; +export * from "./utils/emailValidator"; +export * from "./utils/notEmptyValidator"; diff --git a/app/client/packages/design-system/ads-old/src/utils/emailValidator.ts b/app/client/packages/design-system/ads-old/src/utils/emailValidator.ts new file mode 100644 index 000000000000..311dda4e13b1 --- /dev/null +++ b/app/client/packages/design-system/ads-old/src/utils/emailValidator.ts @@ -0,0 +1,21 @@ +import { + createMessage, + FORM_VALIDATION_INVALID_EMAIL, +} from "../constants/messages"; + +const isEmail = (value: string) => { + const re = + /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; + return re.test(value); +}; + +export function emailValidator(email: string) { + let isValid = true; + if (email) { + isValid = isEmail(email); + } + return { + isValid: isValid, + message: !isValid ? createMessage(FORM_VALIDATION_INVALID_EMAIL) : "", + }; +} diff --git a/app/client/packages/design-system/ads-old/src/utils/notEmptyValidator.ts b/app/client/packages/design-system/ads-old/src/utils/notEmptyValidator.ts new file mode 100644 index 000000000000..8eb246599437 --- /dev/null +++ b/app/client/packages/design-system/ads-old/src/utils/notEmptyValidator.ts @@ -0,0 +1,9 @@ +import { createMessage, ERROR_MESSAGE_NAME_EMPTY } from "../constants/messages"; + +export function notEmptyValidator(value: string) { + const isValid = !!value; + return { + isValid: isValid, + message: !isValid ? createMessage(ERROR_MESSAGE_NAME_EMPTY) : "", + }; +} diff --git a/app/client/packages/design-system/ads/src/Icon/index.ts b/app/client/packages/design-system/ads/src/Icon/index.ts index cc3bea131993..849fe2047976 100644 --- a/app/client/packages/design-system/ads/src/Icon/index.ts +++ b/app/client/packages/design-system/ads/src/Icon/index.ts @@ -1,2 +1,3 @@ export * from "./Icon"; export * from "./Icon.types"; +export { IconCollection } from "./Icon.provider"; diff --git a/app/client/src/components/TabItemBackgroundFill.tsx b/app/client/src/components/TabItemBackgroundFill.tsx index b3f68e1c4a6c..ba218e791d04 100644 --- a/app/client/src/components/TabItemBackgroundFill.tsx +++ b/app/client/src/components/TabItemBackgroundFill.tsx @@ -1,6 +1,5 @@ import React from "react"; import styled from "styled-components"; -import type { TabProp } from "@appsmith/ads-old"; import { getTypographyByKey } from "@appsmith/ads-old"; import type { Theme } from "constants/DefaultTheme"; @@ -40,7 +39,9 @@ const Wrapper = styled.div<WrapperProps>` `; export default function TabItemBackgroundFill(props: { - tab: TabProp; + tab: { + title: string; + }; selected: boolean; vertical: boolean; }) { diff --git a/app/client/src/components/editorComponents/ActionCreator/types.ts b/app/client/src/components/editorComponents/ActionCreator/types.ts index 6ff13ef0695d..f59b3d68f96e 100644 --- a/app/client/src/components/editorComponents/ActionCreator/types.ts +++ b/app/client/src/components/editorComponents/ActionCreator/types.ts @@ -1,8 +1,5 @@ -import type { - SwitcherProps, - TreeDropdownOption, - IconName, -} from "@appsmith/ads-old"; +import type { SwitcherProps, TreeDropdownOption } from "@appsmith/ads-old"; +import type { IconNames } from "@appsmith/ads"; import type { EntityTypeValue, MetaArgs } from "ee/entities/DataTree/types"; import type React from "react"; import type { AdditionalDynamicDataTree } from "utils/autocomplete/customTreeTypeDefCreator"; @@ -177,7 +174,7 @@ export interface FieldGroupValueType { defaultParams: string; value?: string; children?: TreeDropdownOption[]; - icon?: IconName; + icon?: IconNames; } export interface FieldGroupConfig { diff --git a/app/client/src/components/editorComponents/EntityBottomTabs.tsx b/app/client/src/components/editorComponents/EntityBottomTabs.tsx index df4a388112cd..002b0f262044 100644 --- a/app/client/src/components/editorComponents/EntityBottomTabs.tsx +++ b/app/client/src/components/editorComponents/EntityBottomTabs.tsx @@ -1,10 +1,10 @@ import React from "react"; -import type { CollapsibleTabProps } from "@appsmith/ads-old"; import AnalyticsUtil from "ee/utils/AnalyticsUtil"; import { DEBUGGER_TAB_KEYS } from "./Debugger/helpers"; import { Tab, TabPanel, Tabs, TabsList } from "@appsmith/ads"; import styled from "styled-components"; import { LIST_HEADER_HEIGHT, FOOTER_MARGIN } from "./Debugger/DebuggerLogs"; +import type { RefObject } from "react"; const TabPanelWrapper = styled(TabPanel)` margin-top: 0; @@ -40,8 +40,12 @@ interface EntityBottomTabsProps { isCollapsed?: boolean; } -type CollapsibleEntityBottomTabsProps = EntityBottomTabsProps & - CollapsibleTabProps; +type CollapsibleEntityBottomTabsProps = EntityBottomTabsProps & { + // Reference to container for collapsing or expanding content + containerRef: RefObject<HTMLDivElement>; + // height of container when expanded( usually the default height of the tab component) + expandedHeight: string; +}; // Using this if there are debugger related tabs function EntityBottomTabs( @@ -60,23 +64,6 @@ function EntityBottomTabs( } }; - // if (props.isCollapsed) { - // return ( - // <Flex alignItems="center" gap="spaces-3" height="100%" pl="spaces-5"> - // {props.tabs.map((tab) => ( - // <Button - // key={tab.key} - // kind="tertiary" - // onClick={() => onTabSelect(tab.key)} - // size="md" - // > - // {tab.title} - // </Button> - // ))} - // </Flex> - // ); - // } - return ( <Tabs className="h-full" diff --git a/app/client/src/components/editorComponents/PartialImportExport/PartialImportModal/index.tsx b/app/client/src/components/editorComponents/PartialImportExport/PartialImportModal/index.tsx index 526eeff28572..29c0269d85b6 100644 --- a/app/client/src/components/editorComponents/PartialImportExport/PartialImportModal/index.tsx +++ b/app/client/src/components/editorComponents/PartialImportExport/PartialImportModal/index.tsx @@ -66,7 +66,7 @@ const FileImportCard = styled.div<{ fillCardWidth: boolean }>` height: 100%; justify-content: flex-start; - .cs-icon { + .ads-v2-icon { border-radius: 50%; width: ${(props) => props.theme.spaces[12] + 2}px; height: ${(props) => props.theme.spaces[12] + 2}px; @@ -113,7 +113,7 @@ const StatusbarWrapper = styled.div` align-items: center; justify-content: center; - .cs-icon { + .ads-v2-icon { margin: auto; border-radius: var(--ads-v2-border-radius-circle); width: 32px; diff --git a/app/client/src/components/editorComponents/form/fields/NumberField.tsx b/app/client/src/components/editorComponents/form/fields/NumberField.tsx deleted file mode 100644 index 9e7c1550371b..000000000000 --- a/app/client/src/components/editorComponents/form/fields/NumberField.tsx +++ /dev/null @@ -1,41 +0,0 @@ -import React from "react"; -import type { BaseFieldProps } from "redux-form"; -import { Field } from "redux-form"; -import type { TextInputProps } from "@appsmith/ads-old"; -import { TextInput } from "@appsmith/ads-old"; - -type RenderComponentProps = TextInputProps & { - input?: { - onChange?: (value: number) => void; - value?: number; - }; -}; - -function RenderComponent(props: RenderComponentProps) { - const onChangeHandler = (value: number) => { - props.input && props.input.onChange && props.input.onChange(value); - }; - - return ( - <TextInput - dataType={props.dataType} - defaultValue={props.input?.value?.toString()} - onChange={(value: string) => onChangeHandler(Number(value))} - /> - ); -} - -class NumberField extends React.Component<BaseFieldProps & TextInputProps> { - render() { - return ( - <Field - component={RenderComponent} - {...this.props} - disabled={this.props.disabled} - noValidate - /> - ); - } -} - -export default NumberField; diff --git a/app/client/src/components/formControls/InputNumberControl.tsx b/app/client/src/components/formControls/InputNumberControl.tsx deleted file mode 100644 index e77b2c9167fb..000000000000 --- a/app/client/src/components/formControls/InputNumberControl.tsx +++ /dev/null @@ -1,61 +0,0 @@ -import React from "react"; -import type { ControlProps } from "./BaseControl"; -import BaseControl from "./BaseControl"; -import type { ControlType } from "constants/PropertyControlConstants"; -import NumberField from "components/editorComponents/form/fields/NumberField"; -import { Classes, Text, TextType } from "@appsmith/ads-old"; -import styled from "styled-components"; - -const FormGroup = styled.div` - display: flex; - align-items: center; - - .${Classes.TEXT} { - color: ${(props) => props.theme.colors.apiPane.settings.textColor}; - margin-right: ${(props) => props.theme.spaces[12]}px; - } -`; - -export function InputText(props: { - label: string; - value: string; - placeholder?: string; - dataType?: string; - name: string; -}) { - const { dataType, label, name, placeholder } = props; - - return ( - <FormGroup data-testid={name}> - <Text type={TextType.P1}>{label}</Text> - <NumberField dataType={dataType} name={name} placeholder={placeholder} /> - </FormGroup> - ); -} - -class InputNumberControl extends BaseControl<InputControlProps> { - render() { - const { configProperty, dataType, label, placeholderText, propertyValue } = - this.props; - - return ( - <InputText - dataType={dataType} - label={label} - name={configProperty} - placeholder={placeholderText} - value={propertyValue} - /> - ); - } - - getControlType(): ControlType { - return "NUMBER_INPUT"; - } -} - -export interface InputControlProps extends ControlProps { - placeholderText: string; -} - -export default InputNumberControl; diff --git a/app/client/src/components/propertyControls/StyledControls.tsx b/app/client/src/components/propertyControls/StyledControls.tsx index 2c242443938d..836d6516582c 100644 --- a/app/client/src/components/propertyControls/StyledControls.tsx +++ b/app/client/src/components/propertyControls/StyledControls.tsx @@ -1,6 +1,5 @@ import * as React from "react"; import styled from "styled-components"; -import type { TextInputProps } from "@appsmith/ads-old"; import type { ContainerOrientation } from "constants/WidgetConstants"; import { Input, Icon } from "@appsmith/ads"; import useInteractionAnalyticsEvent from "utils/hooks/useInteractionAnalyticsEvent"; @@ -90,7 +89,21 @@ export const StyledNavigateToFieldsContainer = styled.div` width: 95%; `; -export const InputGroup = React.forwardRef((props: TextInputProps, ref) => { +interface InputGroupProps { + autoFocus?: boolean; + className?: string; + dataType?: string; + onBlur?: () => void; + onFocus?: () => void; + placeholder?: string; + value?: string; + width?: string; + onChange?: (value: string) => void; + defaultValue?: string; + tabIndex?: number; +} + +export const InputGroup = React.forwardRef((props: InputGroupProps, ref) => { let inputRef = React.useRef<HTMLInputElement>(null); const wrapperRef = React.useRef<HTMLInputElement>(null); const { dispatchInteractionAnalyticsEvent } = diff --git a/app/client/src/components/utils/ReduxFormTextField.tsx b/app/client/src/components/utils/ReduxFormTextField.tsx index e62af752574b..7201d1ff5092 100644 --- a/app/client/src/components/utils/ReduxFormTextField.tsx +++ b/app/client/src/components/utils/ReduxFormTextField.tsx @@ -1,7 +1,6 @@ import React from "react"; import type { WrappedFieldMetaProps, WrappedFieldInputProps } from "redux-form"; import { Field } from "redux-form"; -import type { InputType } from "@appsmith/ads-old"; import { Input, NumberInput } from "@appsmith/ads"; import type { Intent } from "constants/DefaultTheme"; @@ -48,7 +47,7 @@ export interface FormTextFieldProps { name: string; placeholder: string; description?: string; - type?: InputType; + type?: "text" | "password" | "number" | "email" | "tel"; label?: React.ReactNode; intent?: Intent; disabled?: boolean; diff --git a/app/client/src/components/utils/helperComponents.tsx b/app/client/src/components/utils/helperComponents.tsx index 95a49683dc49..9e11f0b3fbff 100644 --- a/app/client/src/components/utils/helperComponents.tsx +++ b/app/client/src/components/utils/helperComponents.tsx @@ -7,7 +7,7 @@ import { Link, Text } from "@appsmith/ads"; export const HelpPopoverStyle = createGlobalStyle` .bp3-portal { .delete-menu-item { - .cs-icon, .cs-text { + .ads-v2-icon, .cs-text { color: var(--appsmith-color-red-500) !important; svg { path { diff --git a/app/client/src/constants/AppConstants.ts b/app/client/src/constants/AppConstants.ts index 4701738de8cf..8af037a86a97 100644 --- a/app/client/src/constants/AppConstants.ts +++ b/app/client/src/constants/AppConstants.ts @@ -2,14 +2,10 @@ import localStorage from "utils/localStorage"; import { GridDefaults } from "./WidgetConstants"; import { APP_MAX_WIDTH, type AppMaxWidth } from "@appsmith/wds-theming"; -export const CANVAS_DEFAULT_HEIGHT_PX = 1292; export const CANVAS_DEFAULT_MIN_HEIGHT_PX = 380; -export const CANVAS_DEFAULT_GRID_HEIGHT_PX = 1; -export const CANVAS_DEFAULT_GRID_WIDTH_PX = 1; export const CANVAS_DEFAULT_MIN_ROWS = Math.ceil( CANVAS_DEFAULT_MIN_HEIGHT_PX / GridDefaults.DEFAULT_GRID_ROW_HEIGHT, ); -export const CANVAS_BACKGROUND_COLOR = "#FFFFFF"; export const DEFAULT_ENTITY_EXPLORER_WIDTH = 256; export const DEFAULT_PROPERTY_PANE_WIDTH = 288; export const APP_SETTINGS_PANE_WIDTH = 525; @@ -40,7 +36,6 @@ export const getPersistentAppStore = (appId: string, branch?: string) => { return store; }; -export const TOOLTIP_HOVER_ON_DELAY = 1000; export const TOOLTIP_HOVER_ON_DELAY_IN_S = 1; export const MOBILE_MAX_WIDTH = 767; @@ -63,11 +58,6 @@ export const NAVIGATION_SETTINGS = { STATIC: "static", STICKY: "sticky", }, - ITEM_STYLE: { - TEXT_ICON: "textIcon", - TEXT: "text", - ICON: "icon", - }, COLOR_STYLE: { LIGHT: "light", THEME: "theme", @@ -87,7 +77,6 @@ export interface NavigationSetting { orientation: (typeof NAVIGATION_SETTINGS.ORIENTATION)[keyof typeof NAVIGATION_SETTINGS.ORIENTATION]; navStyle: (typeof NAVIGATION_SETTINGS.NAV_STYLE)[keyof typeof NAVIGATION_SETTINGS.NAV_STYLE]; position: (typeof NAVIGATION_SETTINGS.POSITION)[keyof typeof NAVIGATION_SETTINGS.POSITION]; - itemStyle: (typeof NAVIGATION_SETTINGS.ITEM_STYLE)[keyof typeof NAVIGATION_SETTINGS.ITEM_STYLE]; colorStyle: (typeof NAVIGATION_SETTINGS.COLOR_STYLE)[keyof typeof NAVIGATION_SETTINGS.COLOR_STYLE]; logoAssetId: string; logoConfiguration: (typeof NAVIGATION_SETTINGS.LOGO_CONFIGURATION)[keyof typeof NAVIGATION_SETTINGS.LOGO_CONFIGURATION]; @@ -127,7 +116,6 @@ export const defaultNavigationSetting = { orientation: NAVIGATION_SETTINGS.ORIENTATION.TOP, navStyle: NAVIGATION_SETTINGS.NAV_STYLE.STACKED, position: NAVIGATION_SETTINGS.POSITION.STATIC, - itemStyle: NAVIGATION_SETTINGS.ITEM_STYLE.TEXT, colorStyle: NAVIGATION_SETTINGS.COLOR_STYLE.LIGHT, logoAssetId: NAVIGATION_SETTINGS.LOGO_ASSET_ID, logoConfiguration: diff --git a/app/client/src/pages/AdminSettings/SettingsBreadcrumbs.tsx b/app/client/src/pages/AdminSettings/SettingsBreadcrumbs.tsx deleted file mode 100644 index ebc84a865823..000000000000 --- a/app/client/src/pages/AdminSettings/SettingsBreadcrumbs.tsx +++ /dev/null @@ -1,26 +0,0 @@ -import React from "react"; -import { Breadcrumbs } from "@appsmith/ads-old"; -import { BreadcrumbCategories } from "ee/pages/AdminSettings/BreadcrumbCategories"; - -export const getBreadcrumbList = (category: string, subCategory?: string) => { - const breadcrumbList = [ - BreadcrumbCategories.HOMEPAGE, - ...(subCategory - ? [BreadcrumbCategories[category], BreadcrumbCategories[subCategory]] - : [BreadcrumbCategories[category]]), - ]; - - return breadcrumbList; -}; - -function SettingsBreadcrumbs({ - category, - subCategory, -}: { - category: string; - subCategory?: string; -}) { - return <Breadcrumbs items={getBreadcrumbList(category, subCategory)} />; -} - -export default SettingsBreadcrumbs; diff --git a/app/client/src/pages/AppViewer/Navigation/Sidebar.tsx b/app/client/src/pages/AppViewer/Navigation/Sidebar.tsx index 1d2ef4322d95..cf012e47a28b 100644 --- a/app/client/src/pages/AppViewer/Navigation/Sidebar.tsx +++ b/app/client/src/pages/AppViewer/Navigation/Sidebar.tsx @@ -197,7 +197,6 @@ export function Sidebar(props: SidebarProps) { key={page.pageId} > <MenuItem - isMinimal={isMinimal} key={page.pageId} navigationSetting={ currentApplicationDetails?.applicationDetail diff --git a/app/client/src/pages/AppViewer/Navigation/TopInline.tsx b/app/client/src/pages/AppViewer/Navigation/TopInline.tsx index c8b2c9fb1c53..59f9b914db16 100644 --- a/app/client/src/pages/AppViewer/Navigation/TopInline.tsx +++ b/app/client/src/pages/AppViewer/Navigation/TopInline.tsx @@ -1,14 +1,10 @@ import { useLocation } from "react-router-dom"; import React, { useEffect, useLayoutEffect, useRef, useState } from "react"; -// import { get } from "lodash"; -// import { useSelector } from "react-redux"; import type { ApplicationPayload, Page, } from "ee/constants/ReduxActionConstants"; -// import { NAVIGATION_SETTINGS } from "constants/AppConstants"; import { useWindowSizeHooks } from "utils/hooks/dragResizeHooks"; -// import { getSelectedAppTheme } from "selectors/appThemingSelectors"; import MenuItem from "./components/MenuItem"; import { Container } from "./TopInline.styled"; import MenuItemContainer from "./components/MenuItemContainer"; @@ -21,9 +17,6 @@ import { useSelector } from "react-redux"; import { getIsAppSettingsPaneWithNavigationTabOpen } from "selectors/appSettingsPaneSelectors"; import { throttle } from "lodash"; -// TODO - @Dhruvik - ImprovedAppNav -// Replace with NavigationProps if nothing changes -// appsmith/app/client/src/pages/AppViewer/Navigation/constants.ts interface TopInlineProps { currentApplicationDetails?: ApplicationPayload; pages: Page[]; @@ -31,15 +24,6 @@ interface TopInlineProps { export function TopInline(props: TopInlineProps) { const { currentApplicationDetails, pages } = props; - // const selectedTheme = useSelector(getSelectedAppTheme); - // const navColorStyle = - // currentApplicationDetails?.applicationDetail?.navigationSetting?.colorStyle || - // NAVIGATION_SETTINGS.COLOR_STYLE.LIGHT; - // const primaryColor = get( - // selectedTheme, - // "properties.colors.primaryColor", - // "inherit", - // ); const location = useLocation(); const { pathname } = location; const [query, setQuery] = useState(""); diff --git a/app/client/src/pages/AppViewer/Navigation/components/MenuItem.tsx b/app/client/src/pages/AppViewer/Navigation/components/MenuItem.tsx index 69a55ee65e91..0416c5f5149c 100644 --- a/app/client/src/pages/AppViewer/Navigation/components/MenuItem.tsx +++ b/app/client/src/pages/AppViewer/Navigation/components/MenuItem.tsx @@ -10,9 +10,7 @@ import { builderURL, viewerURL } from "ee/RouteBuilder"; import { getAppMode } from "ee/selectors/applicationSelectors"; import { getSelectedAppTheme } from "selectors/appThemingSelectors"; import { trimQueryString } from "utils/helpers"; -import { Icon } from "@appsmith/ads-old"; import MenuText from "./MenuText"; -import classNames from "classnames"; import { StyledMenuItem } from "./MenuItem.styled"; import { NavigationMethod } from "utils/history"; @@ -20,15 +18,9 @@ interface MenuItemProps { page: Page; query: string; navigationSetting?: NavigationSetting; - isMinimal?: boolean; } -const MenuItem = ({ - isMinimal, - navigationSetting, - page, - query, -}: MenuItemProps) => { +const MenuItem = ({ navigationSetting, page, query }: MenuItemProps) => { const appMode = useSelector(getAppMode); const pageURL = useHref( appMode === APP_MODE.PUBLISHED ? viewerURL : builderURL, @@ -61,28 +53,11 @@ const MenuItem = ({ state: { invokedBy: NavigationMethod.AppNavigation }, }} > - {navigationSetting?.itemStyle !== NAVIGATION_SETTINGS.ITEM_STYLE.TEXT && ( - <Icon - className={classNames({ - "page-icon": true, - "mr-2": - navigationSetting?.itemStyle === - NAVIGATION_SETTINGS.ITEM_STYLE.TEXT_ICON && !isMinimal, - "mx-auto": isMinimal, - })} - name="file-line" - // @ts-expect-error Fix this the next time the file is edited - size="large" - /> - )} - {navigationSetting?.itemStyle !== NAVIGATION_SETTINGS.ITEM_STYLE.ICON && - !isMinimal && ( - <MenuText - name={page.pageName} - navColorStyle={navColorStyle} - primaryColor={primaryColor} - /> - )} + <MenuText + name={page.pageName} + navColorStyle={navColorStyle} + primaryColor={primaryColor} + /> </StyledMenuItem> ); }; diff --git a/app/client/src/pages/AppViewer/Navigation/components/MoreDropdownButton.tsx b/app/client/src/pages/AppViewer/Navigation/components/MoreDropdownButton.tsx index 9ef093650efe..807518785469 100644 --- a/app/client/src/pages/AppViewer/Navigation/components/MoreDropdownButton.tsx +++ b/app/client/src/pages/AppViewer/Navigation/components/MoreDropdownButton.tsx @@ -6,7 +6,6 @@ import { useSelector } from "react-redux"; import { getSelectedAppTheme } from "selectors/appThemingSelectors"; import { Icon } from "@appsmith/ads"; import MenuText from "./MenuText"; -import classNames from "classnames"; import { StyledMenuDropdownContainer, StyledMenuItemInDropdown, @@ -57,32 +56,14 @@ const MoreDropdownButton = ({ }} primaryColor={primaryColor} > - {navigationSetting?.itemStyle !== - NAVIGATION_SETTINGS.ITEM_STYLE.TEXT && ( - <Icon - className={classNames({ - "page-icon": true, - "mr-2": - navigationSetting?.itemStyle === - NAVIGATION_SETTINGS.ITEM_STYLE.TEXT_ICON, - })} - name="context-menu" - size="md" + <> + <MenuText + name="More" + navColorStyle={navColorStyle} + primaryColor={primaryColor} /> - )} - - {navigationSetting?.itemStyle !== - NAVIGATION_SETTINGS.ITEM_STYLE.ICON && ( - <> - <MenuText - name="More" - navColorStyle={navColorStyle} - primaryColor={primaryColor} - /> - {/*@ts-expect-error Fix this the next time the file is edited*/} - <Icon className="page-icon ml-2" name="expand-more" size="large" /> - </> - )} + <Icon className="page-icon ml-2" name="expand-more" size="md" /> + </> </StyleMoreDropdownButton> </div> ); @@ -124,25 +105,11 @@ const MoreDropdownButton = ({ state: { invokedBy: NavigationMethod.AppNavigation }, }} > - {navigationSetting?.itemStyle !== - NAVIGATION_SETTINGS.ITEM_STYLE.TEXT && ( - <Icon - className={classNames({ - "page-icon mr-2": true, - })} - name="file-line" - // @ts-expect-error Fix this the next time the file is edited - size="large" - /> - )} - {navigationSetting?.itemStyle !== - NAVIGATION_SETTINGS.ITEM_STYLE.ICON && ( - <MenuText - name={page.pageName} - navColorStyle={navColorStyle} - primaryColor={primaryColor} - /> - )} + <MenuText + name={page.pageName} + navColorStyle={navColorStyle} + primaryColor={primaryColor} + /> </StyledMenuItemInDropdown> ); })} diff --git a/app/client/src/pages/Editor/APIEditor/ApiRightPane.tsx b/app/client/src/pages/Editor/APIEditor/ApiRightPane.tsx index 0bd2e93cff0d..dd8169a2b167 100644 --- a/app/client/src/pages/Editor/APIEditor/ApiRightPane.tsx +++ b/app/client/src/pages/Editor/APIEditor/ApiRightPane.tsx @@ -97,7 +97,7 @@ const DatasourceCard = styled.div` opacity: 0; visibility: hidden; } - .cs-icon { + .ads-v2-icon { opacity: 0; transition: 0.3s all ease; } @@ -107,7 +107,7 @@ const DatasourceCard = styled.div` } &:hover { background-color: var(--ads-v2-color-bg-subtle); - .cs-icon { + .ads-v2-icon { opacity: 1; } } 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 e5204e386cd0..e17e972369ff 100644 --- a/app/client/src/pages/Editor/AppSettingsPane/AppSettings/NavigationSettings/index.tsx +++ b/app/client/src/pages/Editor/AppSettingsPane/AppSettings/NavigationSettings/index.tsx @@ -2,11 +2,6 @@ import React, { useCallback, useEffect, useState } from "react"; import { useDispatch, useSelector } from "react-redux"; import { getCurrentApplication } from "ee/selectors/applicationSelectors"; import { APP_NAVIGATION_SETTING, createMessage } from "ee/constants/messages"; -// import { ReactComponent as NavOrientationTopIcon } from "assets/icons/settings/nav-orientation-top.svg"; -// import { ReactComponent as NavOrientationSideIcon } from "assets/icons/settings/nav-orientation-side.svg"; -// import { ReactComponent as NavStyleInlineIcon } from "assets/icons/settings/nav-style-inline.svg"; -// import { ReactComponent as NavStyleStackedIcon } from "assets/icons/settings/nav-style-stacked.svg"; -// import { ReactComponent as NavStyleSidebarIcon } from "assets/icons/settings/nav-style-sidebar.svg"; import type { NavigationSetting } from "constants/AppConstants"; import { NAVIGATION_SETTINGS } from "constants/AppConstants"; import _, { debounce, isEmpty, isPlainObject } from "lodash"; @@ -22,15 +17,6 @@ import LogoInput from "pages/Editor/NavigationSettings/LogoInput"; import SwitchSettingForLogoConfiguration from "./SwitchSettingForLogoConfiguration"; import { selectFeatureFlags } from "ee/selectors/featureFlagsSelectors"; -/** - * TODO - @Dhruvik - ImprovedAppNav - * Revisit these imports in v1.1 - * https://www.notion.so/appsmith/Ship-Faster-33b32ed5b6334810a0b4f42e03db4a5b?pvs=4 - */ -// import { ReactComponent as NavPositionStickyIcon } from "assets/icons/settings/nav-position-sticky.svg"; -// import { ReactComponent as NavPositionStaticIcon } from "assets/icons/settings/nav-position-static.svg"; -// import { ReactComponent as NavStyleMinimalIcon } from "assets/icons/settings/nav-style-minimal.svg"; - export type UpdateSetting = ( key: keyof NavigationSetting, value: NavigationSetting[keyof NavigationSetting], @@ -158,32 +144,6 @@ function NavigationSettings() { : NAVIGATION_SETTINGS.NAV_STYLE.SIDEBAR; } - /** - * TODO - @Dhruvik - ImprovedAppNav - * Uncomment to change these settings automatically in v1.1 - * https://www.notion.so/appsmith/Ship-Faster-33b32ed5b6334810a0b4f42e03db4a5b - * - * When the orientation is side and nav style changes - - * 1. to minimal, change the item style to icon - * 1. to sidebar, change the item style to text + icon - */ - // if ( - // newSettings.orientation === - // NAVIGATION_SETTINGS.ORIENTATION.SIDE && - // navigationSetting.navStyle !== newSettings.navStyle - // ) { - // if ( - // newSettings.navStyle === NAVIGATION_SETTINGS.NAV_STYLE.MINIMAL - // ) { - // newSettings.itemStyle = NAVIGATION_SETTINGS.ITEM_STYLE.ICON; - // } else if ( - // newSettings.navStyle === NAVIGATION_SETTINGS.NAV_STYLE.SIDEBAR - // ) { - // newSettings.itemStyle = - // NAVIGATION_SETTINGS.ITEM_STYLE.TEXT_ICON; - // } - // } - payload.applicationDetail = { navigationSetting: newSettings, }; @@ -225,23 +185,15 @@ function NavigationSettings() { { label: _.startCase(NAVIGATION_SETTINGS.ORIENTATION.TOP), value: NAVIGATION_SETTINGS.ORIENTATION.TOP, - // startIcon:<NavOrientationTopIcon />, }, { label: _.startCase(NAVIGATION_SETTINGS.ORIENTATION.SIDE), value: NAVIGATION_SETTINGS.ORIENTATION.SIDE, - // startIcon:<NavOrientationSideIcon />, }, ]} updateSetting={updateSetting} /> - {/** - * TODO - @Dhruvik - ImprovedAppNav - * Remove check for orientation = top when adding sidebar minimal to show sidebar - * variants as well. - * https://www.notion.so/appsmith/Ship-Faster-33b32ed5b6334810a0b4f42e03db4a5b - */} {navigationSetting?.orientation === NAVIGATION_SETTINGS.ORIENTATION.TOP && ( <ButtonGroupSetting @@ -252,7 +204,6 @@ function NavigationSettings() { { label: _.startCase(NAVIGATION_SETTINGS.NAV_STYLE.STACKED), value: NAVIGATION_SETTINGS.NAV_STYLE.STACKED, - // startIcon:<NavStyleStackedIcon />, hidden: navigationSetting?.orientation === NAVIGATION_SETTINGS.ORIENTATION.SIDE, @@ -260,7 +211,6 @@ function NavigationSettings() { { label: _.startCase(NAVIGATION_SETTINGS.NAV_STYLE.INLINE), value: NAVIGATION_SETTINGS.NAV_STYLE.INLINE, - // startIcon:<NavStyleInlineIcon />, hidden: navigationSetting?.orientation === NAVIGATION_SETTINGS.ORIENTATION.SIDE, @@ -268,90 +218,15 @@ function NavigationSettings() { { label: _.startCase(NAVIGATION_SETTINGS.NAV_STYLE.SIDEBAR), value: NAVIGATION_SETTINGS.NAV_STYLE.SIDEBAR, - // startIcon:<NavStyleSidebarIcon />, hidden: navigationSetting?.orientation === NAVIGATION_SETTINGS.ORIENTATION.TOP, }, - /** - * TODO - @Dhruvik - ImprovedAppNav - * Hiding minimal sidebar for v1 - * https://www.notion.so/appsmith/Ship-Faster-33b32ed5b6334810a0b4f42e03db4a5b - */ - // { - // label: _.startCase(NAVIGATION_SETTINGS.NAV_STYLE.MINIMAL), - // value: NAVIGATION_SETTINGS.NAV_STYLE.MINIMAL, - // startIcon:<NavStyleMinimalIcon />, - // hidden: - // navigationSetting?.orientation === - // NAVIGATION_SETTINGS.ORIENTATION.TOP, - // }, ]} updateSetting={updateSetting} /> )} - {/** - * TODO - @Dhruvik - ImprovedAppNav - * Hiding position for v1 - * https://www.notion.so/appsmith/Logo-configuration-option-can-be-multiselect-2a436598539c4db99d1f030850fd8918?pvs=4 - */} - {/* <ButtonGroupSetting - heading={createMessage(APP_NAVIGATION_SETTING.positionLabel)} - keyName="position" - navigationSetting={navigationSetting} - options={[ - { - label: _.startCase(NAVIGATION_SETTINGS.POSITION.STATIC), - value: NAVIGATION_SETTINGS.POSITION.STATIC, - startIcon:<NavPositionStaticIcon />, - }, - { - label: _.startCase(NAVIGATION_SETTINGS.POSITION.STICKY), - value: NAVIGATION_SETTINGS.POSITION.STICKY, - startIcon:<NavPositionStickyIcon />, - }, - ]} - updateSetting={updateSetting} - /> */} - - {/** - * TODO - @Dhruvik - ImprovedAppNav - * Hiding item style for v1 - * https://www.notion.so/appsmith/Logo-configuration-option-can-be-multiselect-2a436598539c4db99d1f030850fd8918?pvs=4 - */} - {/* <ButtonGroupSetting - heading={createMessage(APP_NAVIGATION_SETTING.itemStyleLabel)} - keyName="itemStyle" - navigationSetting={navigationSetting} - options={[ - { - label: "Text + Icon", - value: NAVIGATION_SETTINGS.ITEM_STYLE.TEXT_ICON, - hidden: - navigationSetting?.navStyle === - NAVIGATION_SETTINGS.NAV_STYLE.MINIMAL, - }, - { - label: _.startCase(NAVIGATION_SETTINGS.ITEM_STYLE.TEXT), - value: NAVIGATION_SETTINGS.ITEM_STYLE.TEXT, - hidden: - navigationSetting?.navStyle === - NAVIGATION_SETTINGS.NAV_STYLE.MINIMAL, - }, - { - label: _.startCase(NAVIGATION_SETTINGS.ITEM_STYLE.ICON), - value: NAVIGATION_SETTINGS.ITEM_STYLE.ICON, - hidden: - navigationSetting?.orientation === - NAVIGATION_SETTINGS.ORIENTATION.SIDE && - navigationSetting?.navStyle === - NAVIGATION_SETTINGS.NAV_STYLE.SIDEBAR, - }, - ]} - updateSetting={updateSetting} - /> */} - <ButtonGroupSetting heading={createMessage(APP_NAVIGATION_SETTING.colorStyleLabel)} keyName="colorStyle" diff --git a/app/client/src/pages/Editor/DataSourceEditor/Collapsible.tsx b/app/client/src/pages/Editor/DataSourceEditor/Collapsible.tsx index a35c0b9646f9..ad45658544de 100644 --- a/app/client/src/pages/Editor/DataSourceEditor/Collapsible.tsx +++ b/app/client/src/pages/Editor/DataSourceEditor/Collapsible.tsx @@ -9,7 +9,7 @@ const SectionLabel = styled.div` letter-spacing: -0.17px; color: var(--ads-v2-color-fg); display: flex; - .cs-icon { + .ads-v2-icon { margin-left: ${(props) => props.theme.spaces[2]}px; } `; diff --git a/app/client/src/pages/Editor/EditorName/EditableName.tsx b/app/client/src/pages/Editor/EditorName/EditableName.tsx index 7c039b45fb4b..51d6aaae27eb 100644 --- a/app/client/src/pages/Editor/EditorName/EditableName.tsx +++ b/app/client/src/pages/Editor/EditorName/EditableName.tsx @@ -22,7 +22,6 @@ export type EditableAppNameProps = CommonComponentProps & { onBlur?: (value: string) => void; isEditingDefault?: boolean; inputValidation?: (value: string) => string | boolean; - hideEditIcon?: boolean; fill?: boolean; isError?: boolean; isEditing: boolean; diff --git a/app/client/src/pages/Editor/EditorName/index.tsx b/app/client/src/pages/Editor/EditorName/index.tsx index abb3fd5743de..161beb75f648 100644 --- a/app/client/src/pages/Editor/EditorName/index.tsx +++ b/app/client/src/pages/Editor/EditorName/index.tsx @@ -123,7 +123,6 @@ export function EditorName(props: EditorNameProps) { defaultValue={defaultValue} editInteractionKind={props.editInteractionKind} fill={props.fill} - hideEditIcon inputValidation={inputValidation} isEditing={isEditing} isEditingDefault={isEditingDefault} diff --git a/app/client/src/pages/Editor/Explorer/Libraries/Installer.tsx b/app/client/src/pages/Editor/Explorer/Libraries/Installer.tsx index b390c1ca1c3c..e451cbbe1463 100644 --- a/app/client/src/pages/Editor/Explorer/Libraries/Installer.tsx +++ b/app/client/src/pages/Editor/Explorer/Libraries/Installer.tsx @@ -52,7 +52,7 @@ const Wrapper = styled.div` margin-bottom: 16px; .left-icon { margin-left: 14px; - .cs-icon { + .ads-v2-icon { margin-right: 0; } } 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 63b98174e732..e57062a40933 100644 --- a/app/client/src/pages/Editor/GeneratePage/components/GeneratePageForm/GeneratePageForm.tsx +++ b/app/client/src/pages/Editor/GeneratePage/components/GeneratePageForm/GeneratePageForm.tsx @@ -372,7 +372,6 @@ function GeneratePageForm() { value: column.name, subText: column.type, icon: columnIcon, - // @ts-expect-error Fix this the next time the file is edited iconSize: "md", iconColor: "var(--ads-v2-color-fg)", }); @@ -448,8 +447,7 @@ function GeneratePageForm() { iconSize: "md", iconColor: "var(--ads-v2-color-fg)", })); - // @ts-expect-error Fix this the next time the file is edited - setSelectedDatasourceTableOptions(tables); + setSelectedDatasourceTableOptions(tables as DropdownOptions); } }, [bucketList, isS3Plugin, setSelectedDatasourceTableOptions]); @@ -482,8 +480,7 @@ function GeneratePageForm() { columns, }, })); - // @ts-expect-error Fix this the next time the file is edited - setSelectedDatasourceTableOptions(newTables); + setSelectedDatasourceTableOptions(newTables as DropdownOptions); } } } @@ -774,9 +771,7 @@ function GeneratePageForm() { <StyledIconWrapper> <Icon color={table?.iconColor} - // @ts-expect-error Fix this the next time the file is edited - name={table.icon} - // @ts-expect-error Fix this the next time the file is edited + name={table.icon as string} size={table.iconSize} /> </StyledIconWrapper> @@ -849,9 +844,7 @@ function GeneratePageForm() { <StyledIconWrapper> <Icon color={column?.iconColor} - // @ts-expect-error Fix this the next time the file is edited - name={column.icon} - // @ts-expect-error Fix this the next time the file is edited + name={column.icon as string} size={column.iconSize} /> </StyledIconWrapper> diff --git a/app/client/src/pages/Editor/IntegrationEditor/IntegrationsHomeScreen.tsx b/app/client/src/pages/Editor/IntegrationEditor/IntegrationsHomeScreen.tsx deleted file mode 100644 index 442aa8f3c60d..000000000000 --- a/app/client/src/pages/Editor/IntegrationEditor/IntegrationsHomeScreen.tsx +++ /dev/null @@ -1,403 +0,0 @@ -import React from "react"; -import { connect } from "react-redux"; -import type { InjectedFormProps } from "redux-form"; -import { reduxForm } from "redux-form"; -import styled from "styled-components"; -import type { AppState } from "ee/reducers"; -import { API_HOME_SCREEN_FORM } from "ee/constants/forms"; -import ActiveDataSources from "./ActiveDataSources"; -import { - getDatasources, - getMockDatasources, -} from "ee/selectors/entitiesSelector"; -import type { Datasource, MockDatasource } from "entities/Datasource"; -import type { TabProp } from "@appsmith/ads-old"; -import { IconSize } from "@appsmith/ads-old"; -import { INTEGRATION_TABS, INTEGRATION_EDITOR_MODES } from "constants/routes"; -import BackButton from "../DataSourceEditor/BackButton"; -import UnsupportedPluginDialog from "./UnsupportedPluginDialog"; -import { getQueryParams } from "utils/URLUtils"; -import { getIsGeneratePageInitiator } from "utils/GenerateCrudUtil"; -import { getCurrentApplicationId } from "selectors/editorSelectors"; -import { integrationEditorURL } from "ee/RouteBuilder"; -import { getCurrentAppWorkspace } from "ee/selectors/selectedWorkspaceSelectors"; - -import { Tab, TabPanel, Tabs, TabsList } from "@appsmith/ads"; -import Debugger, { - ResizerContentContainer, - ResizerMainContainer, -} from "../DataSourceEditor/Debugger"; -import { showDebuggerFlag } from "selectors/debuggerSelectors"; -import AnalyticsUtil from "ee/utils/AnalyticsUtil"; -import { DatasourceCreateEntryPoints } from "constants/Datasource"; -import { selectFeatureFlags } from "ee/selectors/featureFlagsSelectors"; -import { isGACEnabled } from "ee/utils/planHelpers"; -import { getHasCreateDatasourcePermission } from "ee/utils/BusinessFeatures/permissionPageHelpers"; -import CreateNewDatasourceTab from "./CreateNewDatasourceTab"; - -const HeaderFlex = styled.div` - font-size: 20px; - display: flex; - align-items: center; - color: var(--ads-v2-color-fg-emphasis-plus); - padding: 0 var(--ads-v2-spaces-7); -`; - -const ApiHomePage = styled.div` - display: flex; - flex-direction: column; - - padding-top: 20px; - /* margin-left: 10px; */ - flex: 1; - overflow: hidden !important; - .closeBtn { - position: absolute; - left: 70%; - } - .fontSize16 { - font-size: 16px; - } - .integrations-content-container { - padding: 0 var(--ads-v2-spaces-7); - } - .t--vertical-menu { - overflow: auto; - } -`; - -const MainTabsContainer = styled.div` - width: 100%; - height: 100%; - padding: 0 var(--ads-v2-spaces-7); - /* .react-tabs__tab-list { - margin: 2px; - } */ -`; - -const SectionGrid = styled.div<{ isActiveTab?: boolean }>` - margin-top: 16px; - display: grid; - grid-template-columns: 1fr; - grid-template-rows: auto minmax(0, 1fr); - gap: 10px 16px; - flex: 1; - min-height: 100%; -`; - -interface IntegrationsHomeScreenProps { - basePageId: string; - selectedTab: string; - location: { - search: string; - pathname: string; - }; - history: { - replace: (data: string) => void; - push: (data: string) => void; - }; - isCreating: boolean; - dataSources: Datasource[]; - mockDatasources: MockDatasource[]; - applicationId: string; - canCreateDatasource?: boolean; - showDebugger: boolean; -} - -interface IntegrationsHomeScreenState { - page: number; - activePrimaryMenuId: string; - activeSecondaryMenuId: number; - unsupportedPluginDialogVisible: boolean; -} - -type Props = IntegrationsHomeScreenProps & - InjectedFormProps<{ category: string }, IntegrationsHomeScreenProps>; - -const PRIMARY_MENU_IDS = { - ACTIVE: "ACTIVE", - CREATE_NEW: "CREATE_NEW", -}; - -const getSecondaryMenuIds = (hasActiveSources = false) => { - return { - API: 0 + (hasActiveSources ? 0 : 1), - DATABASE: 1 + (hasActiveSources ? 0 : 1), - MOCK_DATABASE: 2 - (hasActiveSources ? 0 : 2), - }; -}; - -const TERTIARY_MENU_IDS = { - ACTIVE_CONNECTIONS: 0, - MOCK_DATABASE: 1, -}; - -class IntegrationsHomeScreen extends React.Component< - Props, - IntegrationsHomeScreenState -> { - unsupportedPluginContinueAction: () => void; - - constructor(props: Props) { - super(props); - this.unsupportedPluginContinueAction = () => null; - this.state = { - page: 1, - activePrimaryMenuId: PRIMARY_MENU_IDS.CREATE_NEW, - activeSecondaryMenuId: getSecondaryMenuIds( - props.mockDatasources.length > 0, - ).API, - unsupportedPluginDialogVisible: false, - }; - } - - syncActivePrimaryMenu = () => { - // on mount/update if syncing the primary active menu. - const { selectedTab } = this.props; - if ( - (selectedTab === INTEGRATION_TABS.NEW && - this.state.activePrimaryMenuId !== PRIMARY_MENU_IDS.CREATE_NEW) || - (selectedTab === INTEGRATION_TABS.ACTIVE && - this.state.activePrimaryMenuId !== PRIMARY_MENU_IDS.ACTIVE) - ) { - this.setState({ - activePrimaryMenuId: - selectedTab === INTEGRATION_TABS.NEW - ? PRIMARY_MENU_IDS.CREATE_NEW - : PRIMARY_MENU_IDS.ACTIVE, - }); - } - }; - - componentDidMount() { - const { basePageId, dataSources, history } = this.props; - - const queryParams = getQueryParams(); - const redirectMode = queryParams.mode; - const isGeneratePageInitiator = getIsGeneratePageInitiator(); - if (isGeneratePageInitiator) { - if (redirectMode === INTEGRATION_EDITOR_MODES.AUTO) { - delete queryParams.mode; - delete queryParams.from; - history.replace( - integrationEditorURL({ - basePageId, - selectedTab: INTEGRATION_TABS.NEW, - params: queryParams, - }), - ); - } - } else if ( - dataSources.length > 0 && - redirectMode === INTEGRATION_EDITOR_MODES.AUTO - ) { - // User will be taken to active tab if there are datasources - history.replace( - integrationEditorURL({ - basePageId, - selectedTab: INTEGRATION_TABS.ACTIVE, - }), - ); - } else if (redirectMode === INTEGRATION_EDITOR_MODES.MOCK) { - // If there are no datasources -> new user - history.replace( - integrationEditorURL({ - basePageId, - selectedTab: INTEGRATION_TABS.NEW, - }), - ); - this.onSelectSecondaryMenu( - getSecondaryMenuIds(dataSources.length > 0).MOCK_DATABASE, - ); - } else { - this.syncActivePrimaryMenu(); - } - } - - componentDidUpdate(prevProps: Props) { - this.syncActivePrimaryMenu(); - const { basePageId, dataSources, history } = this.props; - if (dataSources.length === 0 && prevProps.dataSources.length > 0) { - history.replace( - integrationEditorURL({ - basePageId, - selectedTab: INTEGRATION_TABS.NEW, - }), - ); - this.onSelectSecondaryMenu( - getSecondaryMenuIds(dataSources.length > 0).MOCK_DATABASE, - ); - } - } - - onSelectPrimaryMenu = (activePrimaryMenuId: string) => { - const { basePageId, dataSources, history } = this.props; - if (activePrimaryMenuId === this.state.activePrimaryMenuId) { - return; - } - history.push( - integrationEditorURL({ - basePageId, - selectedTab: - activePrimaryMenuId === PRIMARY_MENU_IDS.ACTIVE - ? INTEGRATION_TABS.ACTIVE - : INTEGRATION_TABS.NEW, - }), - ); - this.setState({ - activeSecondaryMenuId: - activePrimaryMenuId === PRIMARY_MENU_IDS.ACTIVE - ? TERTIARY_MENU_IDS.ACTIVE_CONNECTIONS - : getSecondaryMenuIds(dataSources.length > 0).API, - }); - }; - - onSelectSecondaryMenu = (activeSecondaryMenuId: number) => { - this.setState({ activeSecondaryMenuId }); - }; - - render() { - const { - basePageId, - canCreateDatasource = false, - dataSources, - location, - showDebugger, - } = this.props; - const { unsupportedPluginDialogVisible } = this.state; - let currentScreen; - const { activePrimaryMenuId } = this.state; - - const PRIMARY_MENU: TabProp[] = [ - { - key: "ACTIVE", - title: "Active", - panelComponent: <div />, - }, - ...(canCreateDatasource - ? [ - { - key: "CREATE_NEW", - title: "Create new", - panelComponent: <div />, - icon: "plus", - iconSize: IconSize.XS, - }, - ] - : []), - ].filter(Boolean); - - const isGeneratePageInitiator = getIsGeneratePageInitiator(); - // Avoid user to switch tabs when in generate page flow by hiding the tabs itself. - const showTabs = !isGeneratePageInitiator; - - if (activePrimaryMenuId === PRIMARY_MENU_IDS.CREATE_NEW) { - currentScreen = <CreateNewDatasourceTab />; - } else { - currentScreen = ( - <ActiveDataSources - basePageId={basePageId} - dataSources={dataSources} - history={this.props.history} - location={location} - onCreateNew={() => { - this.onSelectPrimaryMenu(PRIMARY_MENU_IDS.CREATE_NEW); - // Event for datasource creation click - const entryPoint = DatasourceCreateEntryPoints.ACTIVE_DATASOURCE; - AnalyticsUtil.logEvent("NAVIGATE_TO_CREATE_NEW_DATASOURCE_PAGE", { - entryPoint, - }); - }} - /> - ); - } - return ( - <> - <BackButton /> - <UnsupportedPluginDialog - isModalOpen={unsupportedPluginDialogVisible} - onClose={() => - this.setState({ unsupportedPluginDialogVisible: false }) - } - onContinue={this.unsupportedPluginContinueAction} - /> - <ApiHomePage - className="t--integrationsHomePage" - style={{ overflow: "auto" }} - > - <HeaderFlex> - <p className="sectionHeadings">Datasources in your workspace</p> - </HeaderFlex> - <SectionGrid - isActiveTab={ - this.state.activePrimaryMenuId !== PRIMARY_MENU_IDS.ACTIVE - } - > - <MainTabsContainer> - {showTabs && ( - <Tabs - data-testid="t--datasource-tab" - onValueChange={this.onSelectPrimaryMenu} - value={this.state.activePrimaryMenuId} - > - <TabsList> - {PRIMARY_MENU.map((tab: TabProp) => ( - <Tab - data-testid={`t--tab-${tab.key}`} - key={tab.key} - value={tab.key} - > - {tab.title} - </Tab> - ))} - </TabsList> - {PRIMARY_MENU.map((tab: TabProp) => ( - <TabPanel key={tab.key} value={tab.key}> - {tab.panelComponent} - </TabPanel> - ))} - </Tabs> - )} - </MainTabsContainer> - <ResizerMainContainer> - <ResizerContentContainer className="integrations-content-container"> - {currentScreen} - </ResizerContentContainer> - {showDebugger && <Debugger />} - </ResizerMainContainer> - </SectionGrid> - </ApiHomePage> - </> - ); - } -} - -const mapStateToProps = (state: AppState) => { - // Debugger render flag - const showDebugger = showDebuggerFlag(state); - - const userWorkspacePermissions = - getCurrentAppWorkspace(state).userPermissions ?? []; - - const featureFlags = selectFeatureFlags(state); - const isFeatureEnabled = isGACEnabled(featureFlags); - - const canCreateDatasource = getHasCreateDatasourcePermission( - isFeatureEnabled, - userWorkspacePermissions, - ); - return { - dataSources: getDatasources(state), - mockDatasources: getMockDatasources(state), - isCreating: state.ui.apiPane.isCreating, - applicationId: getCurrentApplicationId(state), - canCreateDatasource, - showDebugger, - }; -}; - -export default connect(mapStateToProps)( - reduxForm<{ category: string }, IntegrationsHomeScreenProps>({ - form: API_HOME_SCREEN_FORM, - })(IntegrationsHomeScreen), -); diff --git a/app/client/src/pages/Editor/IntegrationEditor/index.tsx b/app/client/src/pages/Editor/IntegrationEditor/index.tsx deleted file mode 100644 index 346fa0e361ca..000000000000 --- a/app/client/src/pages/Editor/IntegrationEditor/index.tsx +++ /dev/null @@ -1,33 +0,0 @@ -import React from "react"; -import IntegrationsHomeScreen from "./IntegrationsHomeScreen"; -import type { RouteComponentProps } from "react-router"; -import * as Sentry from "@sentry/react"; - -type Props = RouteComponentProps<{ - basePageId: string; - selectedTab: string; -}>; - -const integrationsEditor = (props: Props) => { - const { history, location, match } = props; - - return ( - <div - style={{ - position: "relative", - height: "100%", - display: "flex", - flexDirection: "column", - }} - > - <IntegrationsHomeScreen - basePageId={match.params.basePageId} - history={history} - location={location} - selectedTab={match.params.selectedTab} - /> - </div> - ); -}; - -export default Sentry.withProfiler(integrationsEditor); diff --git a/app/client/src/pages/Editor/gitSync/components/DangerMenuItem.tsx b/app/client/src/pages/Editor/gitSync/components/DangerMenuItem.tsx deleted file mode 100644 index 6f0b24d3a5c1..000000000000 --- a/app/client/src/pages/Editor/gitSync/components/DangerMenuItem.tsx +++ /dev/null @@ -1,20 +0,0 @@ -import styled from "styled-components"; -import { MenuItem } from "@appsmith/ads-old"; -import { Colors } from "constants/Colors"; - -const DangerMenuItem = styled(MenuItem)` - &&, - && .cs-text { - color: ${Colors.DANGER_SOLID}; - } - - &&, - &&:hover { - svg, - svg path { - fill: ${Colors.DANGER_SOLID}; - } - } -`; - -export default DangerMenuItem; diff --git a/app/client/src/pages/Editor/gitSync/components/DatasourceListItem.tsx b/app/client/src/pages/Editor/gitSync/components/DatasourceListItem.tsx index 697159668784..bc13a8f43d02 100644 --- a/app/client/src/pages/Editor/gitSync/components/DatasourceListItem.tsx +++ b/app/client/src/pages/Editor/gitSync/components/DatasourceListItem.tsx @@ -50,7 +50,7 @@ const DsTitle = styled.div` text-overflow: ellipsis; padding-right: 4px; } - .cs-icon { + .ads-v2-icon { margin-left: ${(props) => props.theme.spaces[2]}px; } `; diff --git a/app/client/src/pages/Editor/gitSync/components/OptionSelector.tsx b/app/client/src/pages/Editor/gitSync/components/OptionSelector.tsx deleted file mode 100644 index c4e726246760..000000000000 --- a/app/client/src/pages/Editor/gitSync/components/OptionSelector.tsx +++ /dev/null @@ -1,73 +0,0 @@ -import React from "react"; -import type { - DefaultDropDownValueNodeProps, - DropdownOption, -} from "@appsmith/ads-old"; -import { - Dropdown, - DropdownWrapper, - DropdownContainer as DropdownComponentContainer, -} from "@appsmith/ads-old"; -import { Colors } from "constants/Colors"; -import styled from "styled-components"; -import { Classes as GitSyncClasses } from "pages/Editor/gitSync/constants"; -import { importSvg } from "@appsmith/ads-old"; - -const ChevronDown = importSvg( - async () => import("assets/icons/ads/chevron-down.svg"), -); - -const SelectedValueNodeContainer = styled.div` - color: ${Colors.CRUSTA}; - display: flex; - align-items: center; - & .label { - margin-right: ${(props) => props.theme.spaces[2]}px; - } -`; - -function SelectedValueNode(props: DefaultDropDownValueNodeProps) { - const { selected } = props; - return ( - <SelectedValueNodeContainer> - <span className="label">{(selected as DropdownOption).label}</span> - <ChevronDown /> - </SelectedValueNodeContainer> - ); -} - -const DropdownContainer = styled.div` - & ${DropdownComponentContainer} { - width: max-content; - } - &&&& ${DropdownWrapper} { - padding: 0; - } -`; - -interface OptionSelectorProps { - options: DropdownOption[]; - selected: DropdownOption; - // TODO: Fix this the next time the file is edited - // eslint-disable-next-line @typescript-eslint/no-explicit-any - onSelect?: (value?: string, dropdownOption?: any) => void; -} - -function OptionSelector({ onSelect, options, selected }: OptionSelectorProps) { - return ( - <DropdownContainer className={GitSyncClasses.OPTION_SELECTOR_WRAPPER}> - <Dropdown - SelectedValueNode={SelectedValueNode} - bgColor={"transparent"} - className="auth-type-dropdown" - onSelect={onSelect} - options={options} - selected={selected} - showDropIcon={false} - showLabelOnly - /> - </DropdownContainer> - ); -} - -export default OptionSelector; diff --git a/app/client/src/pages/Editor/gitSync/components/TabItem.tsx b/app/client/src/pages/Editor/gitSync/components/TabItem.tsx index 598e7d1fa53f..e4416e358d33 100644 --- a/app/client/src/pages/Editor/gitSync/components/TabItem.tsx +++ b/app/client/src/pages/Editor/gitSync/components/TabItem.tsx @@ -1,7 +1,6 @@ import React from "react"; import styled from "styled-components"; import type { Theme } from "constants/DefaultTheme"; -import type { TabProp } from "@appsmith/ads-old"; import { getTypographyByKey } from "@appsmith/ads-old"; import { Colors } from "constants/Colors"; @@ -40,7 +39,10 @@ const Wrapper = styled.div<WrapperProps>` `; export default function TabItem(props: { - tab: TabProp; + tab: { + key: string; + title: string; + }; selected: boolean; vertical: boolean; }) { diff --git a/app/client/src/pages/common/ImportModal.tsx b/app/client/src/pages/common/ImportModal.tsx index e5381f98ac27..2f6f9d43d8f6 100644 --- a/app/client/src/pages/common/ImportModal.tsx +++ b/app/client/src/pages/common/ImportModal.tsx @@ -75,7 +75,7 @@ const FileImportCard = styled.div<{ fillCardWidth: boolean }>` height: 100%; justify-content: flex-start; - .cs-icon { + .ads-v2-icon { border-radius: 50%; width: ${(props) => props.theme.spaces[12] + 2}px; height: ${(props) => props.theme.spaces[12] + 2}px; @@ -146,7 +146,7 @@ const StatusbarWrapper = styled.div` align-items: center; justify-content: center; - .cs-icon { + .ads-v2-icon { margin: auto; border-radius: var(--ads-v2-border-radius-circle); width: 32px; diff --git a/app/client/src/pages/common/MobileSidebar.tsx b/app/client/src/pages/common/MobileSidebar.tsx index 22bdb4c8ab35..299d98717267 100644 --- a/app/client/src/pages/common/MobileSidebar.tsx +++ b/app/client/src/pages/common/MobileSidebar.tsx @@ -62,7 +62,7 @@ const UserNameSection = styled.div` const StyledMenuItem = styled(MenuItem)` svg, - .cs-icon svg path { + .ads-v2-icon svg path { width: 18px; height: 18px; fill: var(--ads-v2-color-fg); diff --git a/app/client/src/pages/common/SearchBar/ApplicationSearchItem.tsx b/app/client/src/pages/common/SearchBar/ApplicationSearchItem.tsx index e5bc9a4ab3e5..791eebd9de8e 100644 --- a/app/client/src/pages/common/SearchBar/ApplicationSearchItem.tsx +++ b/app/client/src/pages/common/SearchBar/ApplicationSearchItem.tsx @@ -40,11 +40,9 @@ const ApplicationSearchItem = (props: Props) => { > <CircleAppIcon className="!mr-1" - color="var(--ads-v2-color-fg)" - // @ts-expect-error Fix this the next time the file is edited name={ - application?.icon || - (getApplicationIcon(application.id) as AppIconName) + (application?.icon || + getApplicationIcon(application.id)) as AppIconName } size={Size.xxs} /> diff --git a/app/client/src/pages/common/ThemeSwitcher.tsx b/app/client/src/pages/common/ThemeSwitcher.tsx deleted file mode 100644 index b069de87763b..000000000000 --- a/app/client/src/pages/common/ThemeSwitcher.tsx +++ /dev/null @@ -1,27 +0,0 @@ -import React, { useState } from "react"; -import { useDispatch, useSelector } from "react-redux"; -import { setThemeMode } from "actions/themeActions"; -import { MenuItem, RectangularSwitcher } from "@appsmith/ads-old"; -import { getCurrentThemeMode, ThemeMode } from "selectors/themeSelectors"; - -export default function ThemeSwitcher(props: { className?: string }) { - const dispatch = useDispatch(); - const themeMode = useSelector(getCurrentThemeMode); - const [switchedOn, setSwitchOn] = useState(themeMode === ThemeMode.DARK); - - return ( - <MenuItem - label={ - <RectangularSwitcher - className={props.className} - onSwitch={(value: boolean) => { - setSwitchOn(value); - dispatch(setThemeMode(value ? ThemeMode.DARK : ThemeMode.LIGHT)); - }} - value={switchedOn} - /> - } - text="Theme" - /> - ); -} diff --git a/app/client/src/widgets/WidgetUtils.ts b/app/client/src/widgets/WidgetUtils.ts index 77f02ab05147..99b510f0c8a8 100644 --- a/app/client/src/widgets/WidgetUtils.ts +++ b/app/client/src/widgets/WidgetUtils.ts @@ -1,5 +1,3 @@ -// import React, { JSXElementConstructor } from "react"; -// import { IconProps, IconWrapper } from "constants/IconConstants"; import type React from "react"; import { Alignment, Classes } from "@blueprintjs/core"; import { Classes as DTClasses } from "@blueprintjs/datetime"; @@ -112,7 +110,6 @@ export const hexToRgba = (color: string, alpha: number) => { }; const ALPHANUMERIC = "1234567890abcdefghijklmnopqrstuvwxyz"; -// const ALPHABET = "abcdefghijklmnopqrstuvwxyz"; export const generateReactKey = ({ prefix = "",
9d4aae44381fa6743010777b0f694f007c68ae61
2023-11-20 13:28:08
Hetu Nandu
fix: sidebar context switching (#28818)
false
sidebar context switching (#28818)
fix
diff --git a/app/client/src/actions/focusHistoryActions.ts b/app/client/src/actions/focusHistoryActions.ts index 27d2c20b05ee..4127df1e3f39 100644 --- a/app/client/src/actions/focusHistoryActions.ts +++ b/app/client/src/actions/focusHistoryActions.ts @@ -19,7 +19,7 @@ export const routeChanged = ( }; }; -export const setFocusHistory = (key: string, focusState: FocusState) => { +export const storeFocusHistory = (key: string, focusState: FocusState) => { return { type: ReduxActionTypes.SET_FOCUS_HISTORY, payload: { key, focusState }, diff --git a/app/client/src/navigation/FocusElements.ts b/app/client/src/navigation/FocusElements.ts index 353721112bd8..9ed487880ec2 100644 --- a/app/client/src/navigation/FocusElements.ts +++ b/app/client/src/navigation/FocusElements.ts @@ -67,8 +67,12 @@ import { setDebuggerContext } from "actions/debuggerActions"; import { DefaultDebuggerContext } from "reducers/uiReducers/debuggerReducer"; import { NavigationMethod } from "../utils/history"; import { JSEditorTab } from "../reducers/uiReducers/jsPaneReducer"; -import { getSelectedDatasourceId } from "./FocusSelectors"; -import { setSelectedDatasource } from "./FocusSetters"; +import { + getCurrentAppUrl, + getCurrentPageUrl, + getSelectedDatasourceId, +} from "./FocusSelectors"; +import { setSelectedDatasource, setPageUrl, setAppUrl } from "./FocusSetters"; import { getFirstDatasourceId } from "../selectors/datasourceSelectors"; export enum FocusElement { @@ -93,6 +97,8 @@ export enum FocusElement { SelectedWidgets = "SelectedWidgets", SubEntityCollapsibleState = "SubEntityCollapsibleState", InputField = "InputField", + PageUrl = "PageUrl", + AppUrl = "AppUrl", } export enum ConfigType { @@ -124,13 +130,20 @@ export type Config = ConfigRedux | ConfigURL; export const FocusElementsConfig: Record<FocusEntity, Config[]> = { [FocusEntity.NONE]: [], + [FocusEntity.APP_STATE]: [ + { + type: ConfigType.URL, + name: FocusElement.AppUrl, + selector: getCurrentAppUrl, + setter: setAppUrl, + }, + ], [FocusEntity.PAGE]: [ { - type: ConfigType.Redux, - name: FocusElement.CodeEditorHistory, - selector: getCodeEditorHistory, - setter: setCodeEditorHistory, - defaultValue: {}, + type: ConfigType.URL, + name: FocusElement.PageUrl, + selector: getCurrentPageUrl, + setter: setPageUrl, }, { type: ConfigType.Redux, @@ -167,6 +180,13 @@ export const FocusElementsConfig: Record<FocusEntity, Config[]> = { setter: setPanelPropertiesState, defaultValue: {}, }, + { + type: ConfigType.Redux, + name: FocusElement.CodeEditorHistory, + selector: getCodeEditorHistory, + setter: setCodeEditorHistory, + defaultValue: {}, + }, ], [FocusEntity.CANVAS]: [ { @@ -308,4 +328,6 @@ export const FocusElementsConfig: Record<FocusEntity, Config[]> = { defaultValue: DefaultDebuggerContext, }, ], + [FocusEntity.LIBRARY]: [], + [FocusEntity.SETTINGS]: [], }; diff --git a/app/client/src/navigation/FocusEntity.test.ts b/app/client/src/navigation/FocusEntity.test.ts index cfa8331b20ec..cfbc87f79c31 100644 --- a/app/client/src/navigation/FocusEntity.test.ts +++ b/app/client/src/navigation/FocusEntity.test.ts @@ -1,10 +1,16 @@ import { identifyEntityFromPath, FocusEntity } from "navigation/FocusEntity"; +import { AppState } from "../entities/IDE/constants"; describe("identifyEntityFromPath", () => { const oldUrlCases = [ { path: "/applications/myAppId/pages/myPageId/edit", - expected: { entity: FocusEntity.CANVAS, id: "", pageId: "myPageId" }, + expected: { + entity: FocusEntity.CANVAS, + id: "", + pageId: "myPageId", + appState: AppState.PAGES, + }, }, { path: "/applications/myAppId/pages/myPageId/edit/widgets/ryvc8i7oja", @@ -12,11 +18,17 @@ describe("identifyEntityFromPath", () => { entity: FocusEntity.PROPERTY_PANE, id: "ryvc8i7oja", pageId: "myPageId", + appState: AppState.PAGES, }, }, { path: "/applications/myAppId/pages/myPageId/edit/api/myApiId", - expected: { entity: FocusEntity.API, id: "myApiId", pageId: "myPageId" }, + expected: { + entity: FocusEntity.API, + id: "myApiId", + pageId: "myPageId", + appState: AppState.PAGES, + }, }, { path: "/applications/myAppId/pages/myPageId/edit/queries/myQueryId", @@ -24,13 +36,19 @@ describe("identifyEntityFromPath", () => { entity: FocusEntity.QUERY, id: "myQueryId", pageId: "myPageId", + appState: AppState.PAGES, }, }, ]; const pageSlugCases = [ { path: "/app/eval/page1-myPageId/edit", - expected: { entity: FocusEntity.CANVAS, id: "", pageId: "myPageId" }, + expected: { + entity: FocusEntity.CANVAS, + id: "", + pageId: "myPageId", + appState: AppState.PAGES, + }, }, { path: "/app/myAppId/page1-myPageId/edit/widgets/ryvc8i7oja", @@ -38,11 +56,17 @@ describe("identifyEntityFromPath", () => { entity: FocusEntity.PROPERTY_PANE, id: "ryvc8i7oja", pageId: "myPageId", + appState: AppState.PAGES, }, }, { path: "/app/eval/page1-myPageId/edit/api/myApiId", - expected: { entity: FocusEntity.API, id: "myApiId", pageId: "myPageId" }, + expected: { + entity: FocusEntity.API, + id: "myApiId", + pageId: "myPageId", + appState: AppState.PAGES, + }, }, { path: "/app/eval/page1-myPageId/edit/queries/myQueryId", @@ -50,13 +74,19 @@ describe("identifyEntityFromPath", () => { entity: FocusEntity.QUERY, id: "myQueryId", pageId: "myPageId", + appState: AppState.PAGES, }, }, ]; const customSlugCases = [ { path: "/app/myCustomSlug-myPageId/edit", - expected: { entity: FocusEntity.CANVAS, id: "", pageId: "myPageId" }, + expected: { + entity: FocusEntity.CANVAS, + id: "", + pageId: "myPageId", + appState: AppState.PAGES, + }, }, { path: "/app/myCustomSlug-myPageId/edit/widgets/ryvc8i7oja", @@ -64,11 +94,17 @@ describe("identifyEntityFromPath", () => { entity: FocusEntity.PROPERTY_PANE, id: "ryvc8i7oja", pageId: "myPageId", + appState: AppState.PAGES, }, }, { path: "/app/myCustomSlug-myPageId/edit/api/myApiId", - expected: { entity: FocusEntity.API, id: "myApiId", pageId: "myPageId" }, + expected: { + entity: FocusEntity.API, + id: "myApiId", + pageId: "myPageId", + appState: AppState.PAGES, + }, }, { path: "/app/myCustomSlug-myPageId/edit/queries/myQueryId", @@ -76,6 +112,7 @@ describe("identifyEntityFromPath", () => { entity: FocusEntity.QUERY, id: "myQueryId", pageId: "myPageId", + appState: AppState.PAGES, }, }, ]; diff --git a/app/client/src/navigation/FocusEntity.ts b/app/client/src/navigation/FocusEntity.ts index cc957ccbaaa5..a7cd68625186 100644 --- a/app/client/src/navigation/FocusEntity.ts +++ b/app/client/src/navigation/FocusEntity.ts @@ -10,10 +10,12 @@ import { QUERIES_EDITOR_ID_PATH, WIDGETS_EDITOR_ID_PATH, } from "constants/routes"; -import { SAAS_EDITOR_DATASOURCE_ID_PATH } from "pages/Editor/SaaSEditor/constants"; -import { SAAS_EDITOR_API_ID_PATH } from "pages/Editor/SaaSEditor/constants"; -import { getQueryParamsFromString } from "utils/getQueryParamsObject"; +import { + SAAS_EDITOR_API_ID_PATH, + SAAS_EDITOR_DATASOURCE_ID_PATH, +} from "pages/Editor/SaaSEditor/constants"; import { TEMP_DATASOURCE_ID } from "constants/Datasource"; +import { AppState } from "../entities/IDE/constants"; export enum FocusEntity { PAGE = "PAGE", @@ -26,6 +28,9 @@ export enum FocusEntity { JS_OBJECT = "JS_OBJECT", PROPERTY_PANE = "PROPERTY_PANE", NONE = "NONE", + APP_STATE = "APP_STATE", + LIBRARY = "LIBRARY", + SETTINGS = "SETTINGS", } export const FocusStoreHierarchy: Partial<Record<FocusEntity, FocusEntity>> = { @@ -36,56 +41,10 @@ export const FocusStoreHierarchy: Partial<Record<FocusEntity, FocusEntity>> = { export interface FocusEntityInfo { entity: FocusEntity; id: string; + appState: AppState; pageId?: string; } -/** - * Method to indicate if the URL is of type API, Query etc., - * and not anything else - * @param path - * @returns - */ -export function shouldStoreURLForFocus(path: string) { - const entityTypesToStore = [ - FocusEntity.QUERY, - FocusEntity.API, - FocusEntity.JS_OBJECT, - FocusEntity.DATASOURCE, - ]; - - const entity = identifyEntityFromPath(path)?.entity; - - return entityTypesToStore.indexOf(entity) >= 0; -} - -/** - * parse search string and get branch - * @param searchString - * @returns - */ -const fetchGitBranch = (searchString: string | undefined) => { - const existingParams = - getQueryParamsFromString(searchString?.substring(1)) || {}; - - return existingParams.branch; -}; - -/** - * Compare if both the params are on same branch - * @param previousParamString - * @param currentParamStaring - * @returns - */ -export function isSameBranch( - previousParamString: string, - currentParamStaring: string, -) { - const previousBranch = fetchGitBranch(previousParamString); - const currentBranch = fetchGitBranch(currentParamStaring); - - return previousBranch === currentBranch; -} - export function identifyEntityFromPath(path: string): FocusEntityInfo { const match = matchPath<{ apiId?: string; @@ -133,7 +92,12 @@ export function identifyEntityFromPath(path: string): FocusEntityInfo { exact: true, }); if (!match) { - return { entity: FocusEntity.NONE, id: "", pageId: "" }; + return { + entity: FocusEntity.NONE, + id: "", + pageId: "", + appState: AppState.PAGES, + }; } if (match.params.apiId) { if (match.params.pluginPackageName) { @@ -141,29 +105,39 @@ export function identifyEntityFromPath(path: string): FocusEntityInfo { entity: FocusEntity.QUERY, id: match.params.apiId, pageId: match.params.pageId, + appState: AppState.PAGES, }; } return { entity: FocusEntity.API, id: match.params.apiId, pageId: match.params.pageId, + appState: AppState.PAGES, }; } - if ( - match.params.datasourceId && - match.params.datasourceId !== TEMP_DATASOURCE_ID - ) { - return { - entity: FocusEntity.DATASOURCE, - id: match.params.datasourceId, - pageId: match.params.pageId, - }; + if (match.params.datasourceId) { + if (match.params.datasourceId == TEMP_DATASOURCE_ID) { + return { + entity: FocusEntity.NONE, + id: match.params.datasourceId, + pageId: match.params.pageId, + appState: AppState.DATA, + }; + } else { + return { + entity: FocusEntity.DATASOURCE, + id: match.params.datasourceId, + pageId: match.params.pageId, + appState: AppState.DATA, + }; + } } if (match.params.selectedTab) { return { entity: FocusEntity.DATASOURCE, id: match.params.selectedTab, pageId: match.params.pageId, + appState: AppState.DATA, }; } if (match.params.entity === "datasource") { @@ -171,6 +145,7 @@ export function identifyEntityFromPath(path: string): FocusEntityInfo { entity: FocusEntity.DATASOURCE_LIST, id: "", pageId: match.params.pageId, + appState: AppState.DATA, }; } if (match.params.queryId) { @@ -178,6 +153,7 @@ export function identifyEntityFromPath(path: string): FocusEntityInfo { entity: FocusEntity.QUERY, id: match.params.queryId, pageId: match.params.pageId, + appState: AppState.PAGES, }; } if (match.params.collectionId) { @@ -185,6 +161,7 @@ export function identifyEntityFromPath(path: string): FocusEntityInfo { entity: FocusEntity.JS_OBJECT, id: match.params.collectionId, pageId: match.params.pageId, + appState: AppState.PAGES, }; } if (match.params.widgetIds) { @@ -192,7 +169,31 @@ export function identifyEntityFromPath(path: string): FocusEntityInfo { entity: FocusEntity.PROPERTY_PANE, id: match.params.widgetIds, pageId: match.params.pageId, + appState: AppState.PAGES, }; } - return { entity: FocusEntity.CANVAS, id: "", pageId: match.params.pageId }; + if (match.params.entity) { + if (match.params.entity === "libraries") { + return { + entity: FocusEntity.LIBRARY, + id: "", + appState: AppState.LIBRARIES, + pageId: match.params.pageId, + }; + } + if (match.params.entity === "settings") { + return { + entity: FocusEntity.SETTINGS, + id: "", + appState: AppState.SETTINGS, + pageId: match.params.pageId, + }; + } + } + return { + entity: FocusEntity.CANVAS, + id: "", + pageId: match.params.pageId, + appState: AppState.PAGES, + }; } diff --git a/app/client/src/navigation/FocusSelectors.ts b/app/client/src/navigation/FocusSelectors.ts index 612569d6c6aa..77646c595314 100644 --- a/app/client/src/navigation/FocusSelectors.ts +++ b/app/client/src/navigation/FocusSelectors.ts @@ -6,6 +6,8 @@ import { DATA_SOURCES_EDITOR_ID_PATH, SAAS_GSHEET_EDITOR_ID_PATH, } from "../constants/routes"; +import { shouldStorePageURLForFocus } from "./FocusUtils"; +import { FocusEntity, identifyEntityFromPath } from "./FocusEntity"; export const getSelectedDatasourceId = (path: string): string | undefined => { const match = matchPath<{ datasourceId?: string }>(path, [ @@ -19,3 +21,16 @@ export const getSelectedDatasourceId = (path: string): string | undefined => { if (!match) return undefined; return match.params.datasourceId; }; + +export const getCurrentPageUrl = (path: string): string | undefined => { + if (shouldStorePageURLForFocus(path)) { + return path; + } +}; + +export const getCurrentAppUrl = (path: string): string | undefined => { + const focusInfo = identifyEntityFromPath(path); + if (focusInfo.entity !== FocusEntity.NONE) { + return path; + } +}; diff --git a/app/client/src/navigation/FocusSetters.ts b/app/client/src/navigation/FocusSetters.ts index 3b5c4568dd9d..1d8607c3c107 100644 --- a/app/client/src/navigation/FocusSetters.ts +++ b/app/client/src/navigation/FocusSetters.ts @@ -10,3 +10,17 @@ export function setSelectedDatasource(id: string | undefined) { ); } } + +export function setPageUrl(path: string | undefined) { + if (path) { + const params = history.location.search; + history.push(`${path}${params}`); + } +} + +export function setAppUrl(path: string | undefined) { + if (path) { + const params = history.location.search; + history.push(`${path}${params}`); + } +} diff --git a/app/client/src/navigation/FocusUtils.ts b/app/client/src/navigation/FocusUtils.ts new file mode 100644 index 000000000000..85d018e8277c --- /dev/null +++ b/app/client/src/navigation/FocusUtils.ts @@ -0,0 +1,49 @@ +import type { FocusEntityInfo } from "./FocusEntity"; +import { FocusEntity, identifyEntityFromPath } from "./FocusEntity"; +import { builderURL, datasourcesEditorURL } from "@appsmith/RouteBuilder"; + +export const getEntityParentUrl = ( + entityInfo: FocusEntityInfo, + parentEntity: FocusEntity, +): string => { + if (parentEntity === FocusEntity.CANVAS) { + const canvasUrl = builderURL({ pageId: entityInfo.pageId ?? "" }); + return canvasUrl.split("?")[0]; + } + if (parentEntity === FocusEntity.DATASOURCE_LIST) { + return datasourcesEditorURL({ pageId: entityInfo.pageId }); + } + return ""; +}; +export const isPageChange = (prevPath: string, currentPath: string) => { + const prevFocusEntityInfo = identifyEntityFromPath(prevPath); + const currFocusEntityInfo = identifyEntityFromPath(currentPath); + if (prevFocusEntityInfo.pageId === "" || currFocusEntityInfo.pageId === "") { + return false; + } + return prevFocusEntityInfo.pageId !== currFocusEntityInfo.pageId; +}; + +export const isAppStateChange = (prevPath: string, currentPath: string) => { + const prevFocusEntityInfo = identifyEntityFromPath(prevPath); + const currFocusEntityInfo = identifyEntityFromPath(currentPath); + return prevFocusEntityInfo.appState !== currFocusEntityInfo.appState; +}; + +/** + * Method to indicate if the URL is of type API, Query etc., + * and not anything else + * @param path + * @returns + */ +export function shouldStorePageURLForFocus(path: string) { + const entityTypesToStore = [ + FocusEntity.QUERY, + FocusEntity.API, + FocusEntity.JS_OBJECT, + ]; + + const entity = identifyEntityFromPath(path)?.entity; + + return entityTypesToStore.indexOf(entity) >= 0; +} diff --git a/app/client/src/sagas/ContextSwitchingSaga.ts b/app/client/src/sagas/ContextSwitchingSaga.ts index e24d069f35c3..b27f981f1b7a 100644 --- a/app/client/src/sagas/ContextSwitchingSaga.ts +++ b/app/client/src/sagas/ContextSwitchingSaga.ts @@ -11,20 +11,25 @@ import { FocusEntity, FocusStoreHierarchy, identifyEntityFromPath, - shouldStoreURLForFocus, } from "navigation/FocusEntity"; import type { Config } from "navigation/FocusElements"; import { ConfigType, FocusElementsConfig } from "navigation/FocusElements"; -import { setFocusHistory } from "actions/focusHistoryActions"; -import { builderURL, datasourcesEditorURL } from "@appsmith/RouteBuilder"; +import { storeFocusHistory } from "actions/focusHistoryActions"; import type { AppsmithLocationState } from "utils/history"; -import history, { NavigationMethod } from "utils/history"; +import { NavigationMethod } from "utils/history"; import { ReduxActionTypes } from "@appsmith/constants/ReduxActionConstants"; import type { Action } from "entities/Action"; import { getAction, getPlugin } from "@appsmith/selectors/entitiesSelector"; import type { Plugin } from "api/PluginApi"; import { getCurrentGitBranch } from "selectors/gitSyncSelectors"; -import { has } from "lodash"; +import { + getEntityParentUrl, + isAppStateChange, + isPageChange, +} from "../navigation/FocusUtils"; +import { AppState } from "../entities/IDE/constants"; +import { getCurrentApplicationId } from "../selectors/editorSelectors"; +import { get } from "lodash"; /** * Context switching works by restoring the states of ui elements to as they were @@ -72,10 +77,7 @@ export function* contextSwitchingSaga( function* waitForPathLoad(currentPath: string, previousPath?: string) { if (previousPath) { - const currentFocus = identifyEntityFromPath(currentPath); - const prevFocus = identifyEntityFromPath(previousPath); - - if (currentFocus.pageId !== prevFocus.pageId) { + if (isPageChange(previousPath, currentPath)) { yield take(ReduxActionTypes.FETCH_PAGE_SUCCESS); } } @@ -104,15 +106,8 @@ function* storeStateOfPath( for (const selectorInfo of selectors) { state[selectorInfo.name] = yield call(getState, selectorInfo, fromPath); } - if (entityInfo.entity === FocusEntity.PAGE) { - if (shouldStoreURLForFocus(fromPath)) { - if (fromPath) { - state._routingURL = fromPath; - } - } - } yield put( - setFocusHistory(key, { + storeFocusHistory(key, { entityInfo, state, }), @@ -128,12 +123,6 @@ function* setStateOfPath(key: string, entityInfo: FocusEntityInfo) { for (const selectorInfo of selectors) { yield call(setState, selectorInfo, focusHistory.state[selectorInfo.name]); } - if (entityInfo.entity === FocusEntity.PAGE) { - if (focusHistory.state._routingURL) { - const params = history.location.search; - history.push(`${focusHistory.state._routingURL}${params ?? ""}`); - } - } } else { const subType: string | undefined = yield call( getEntitySubType, @@ -201,33 +190,21 @@ function shouldSetState( ); } -const getEntityParentUrl = ( - entityInfo: FocusEntityInfo, - parentEntity: FocusEntity, -): string => { - if (parentEntity === FocusEntity.CANVAS) { - const canvasUrl = builderURL({ pageId: entityInfo.pageId ?? "" }); - return canvasUrl.split("?")[0]; - } - if (parentEntity === FocusEntity.DATASOURCE_LIST) { - return datasourcesEditorURL({ pageId: entityInfo.pageId }); - } - return ""; -}; - -const isPageChange = (prevPath: string, currentPath: string) => { - const prevFocusEntityInfo = identifyEntityFromPath(prevPath); - const currFocusEntityInfo = identifyEntityFromPath(currentPath); - if (prevFocusEntityInfo.pageId === "" || currFocusEntityInfo.pageId === "") { - return false; - } - return prevFocusEntityInfo.pageId !== currFocusEntityInfo.pageId; -}; - function* getEntitiesForStore(previousPath: string, currentPath: string) { const branch: string | undefined = yield select(getCurrentGitBranch); const entities: Array<{ entityInfo: FocusEntityInfo; key: string }> = []; const prevFocusEntityInfo = identifyEntityFromPath(previousPath); + if (isAppStateChange(previousPath, currentPath)) { + const currentAppId: string = yield select(getCurrentApplicationId); + entities.push({ + key: `${prevFocusEntityInfo.appState}.${currentAppId}#${branch}`, + entityInfo: { + entity: FocusEntity.APP_STATE, + id: prevFocusEntityInfo.appState, + appState: prevFocusEntityInfo.appState, + }, + }); + } if (isPageChange(previousPath, currentPath)) { if (prevFocusEntityInfo.pageId) { entities.push({ @@ -235,6 +212,7 @@ function* getEntitiesForStore(previousPath: string, currentPath: string) { entityInfo: { entity: FocusEntity.PAGE, id: prevFocusEntityInfo.pageId, + appState: AppState.PAGES, }, }); } @@ -249,6 +227,7 @@ function* getEntitiesForStore(previousPath: string, currentPath: string) { entity: parentEntity, id: "", pageId: prevFocusEntityInfo.pageId, + appState: prevFocusEntityInfo.appState, }, key: `${parentPath}#${branch}`, }); @@ -268,7 +247,7 @@ function* getEntitiesForStore(previousPath: string, currentPath: string) { function* getEntitiesForSet( previousPath: string, currentPath: string, - state: AppsmithLocationState, + state?: AppsmithLocationState, ) { if (!shouldSetState(previousPath, currentPath, state)) { return []; @@ -276,21 +255,38 @@ function* getEntitiesForSet( const branch: string | undefined = yield select(getCurrentGitBranch); const entities: Array<{ entityInfo: FocusEntityInfo; key: string }> = []; const currentEntityInfo = identifyEntityFromPath(currentPath); + if ( + isAppStateChange(previousPath, currentPath) && + state?.invokedBy === NavigationMethod.AppSidebar + ) { + const currentAppId: string = yield select(getCurrentApplicationId); + const key = `${currentEntityInfo.appState}.${currentAppId}#${branch}`; + entities.push({ + key, + entityInfo: { + entity: FocusEntity.APP_STATE, + id: currentEntityInfo.appState, + appState: currentEntityInfo.appState, + }, + }); + const focusHistory: FocusState = yield select(getCurrentFocusInfo, key); + if (get(focusHistory, "state.AppUrl")) { + return entities; + } + } if (isPageChange(previousPath, currentPath)) { + const key = `${currentEntityInfo.pageId}#${branch}`; if (currentEntityInfo.pageId) { entities.push({ - key: `${currentEntityInfo.pageId}#${branch}`, + key, entityInfo: { entity: FocusEntity.PAGE, id: currentEntityInfo.pageId, + appState: AppState.PAGES, }, }); - - const focusHistory: FocusState = yield select( - getCurrentFocusInfo, - `${currentEntityInfo.pageId}#${branch}`, - ); - if (has(focusHistory, "state._routingURL")) { + const focusHistory: FocusState = yield select(getCurrentFocusInfo, key); + if (get(focusHistory, "state.PageUrl")) { return entities; } }
a1c8cb69f0abbfd43ba728548cc2afcf331866e6
2024-11-28 10:58:56
Shrikant Sharat Kandula
chore: Remove socket-io and websocket connections (#37784)
false
Remove socket-io and websocket connections (#37784)
chore
diff --git a/app/client/package.json b/app/client/package.json index f0e2adb9c8ba..f56c83dafbaa 100644 --- a/app/client/package.json +++ b/app/client/package.json @@ -218,7 +218,6 @@ "showdown": "^1.9.1", "simplebar-react": "^2.4.3", "smartlook-client": "^8.0.0", - "socket.io-client": "^4.5.4", "sql-formatter": "12.2.0", "styled-components": "^5.3.6", "tailwindcss": "^3.3.3", diff --git a/app/client/src/actions/appCollabActions.ts b/app/client/src/actions/appCollabActions.ts deleted file mode 100644 index c9f432017a4c..000000000000 --- a/app/client/src/actions/appCollabActions.ts +++ /dev/null @@ -1,78 +0,0 @@ -import { - appLevelWebsocketWriteEvent, - pageLevelWebsocketWriteEvent, -} from "./websocketActions"; -import { ReduxActionTypes } from "ee/constants/ReduxActionConstants"; -import { PAGE_LEVEL_SOCKET_EVENTS } from "sagas/WebsocketSagas/socketEvents"; - -// App Editors presence Socket actions -export const collabStartEditingAppEvent = (appId: string) => - appLevelWebsocketWriteEvent({ - type: PAGE_LEVEL_SOCKET_EVENTS.START_EDITING_APP, - payload: appId, - }); - -export const collabStopEditingAppEvent = (appId: string) => - appLevelWebsocketWriteEvent({ - type: PAGE_LEVEL_SOCKET_EVENTS.STOP_EDITING_APP, - payload: appId, - }); - -// App Editor presence Redux actions -// TODO: Fix this the next time the file is edited -// eslint-disable-next-line @typescript-eslint/no-explicit-any -export const collabSetAppEditors = (payload: any) => ({ - type: ReduxActionTypes.APP_COLLAB_LIST_EDITORS, - payload, -}); - -export const collabResetAppEditors = () => ({ - type: ReduxActionTypes.APP_COLLAB_RESET_EDITORS, -}); - -// Pointer Sharing Socket Events -export const collabStartSharingPointerEvent = (pageId: string) => - pageLevelWebsocketWriteEvent({ - type: PAGE_LEVEL_SOCKET_EVENTS.START_EDITING_APP, - payload: pageId, - }); - -export const collabStopSharingPointerEvent = (pageId?: string) => - pageLevelWebsocketWriteEvent({ - type: PAGE_LEVEL_SOCKET_EVENTS.STOP_EDITING_APP, - payload: pageId, - }); - -// TODO: Fix this the next time the file is edited -// eslint-disable-next-line @typescript-eslint/no-explicit-any -export const collabShareUserPointerEvent = (payload: any) => - pageLevelWebsocketWriteEvent({ - type: PAGE_LEVEL_SOCKET_EVENTS.SHARE_USER_POINTER, - payload, - }); - -// Pointer Sharing Redux actions -// TODO: Fix this the next time the file is edited -// eslint-disable-next-line @typescript-eslint/no-explicit-any -export const collabSetEditorsPointersData = (payload: any) => ({ - type: ReduxActionTypes.APP_COLLAB_SET_EDITORS_POINTER_DATA, - payload, -}); - -// TODO: Fix this the next time the file is edited -// eslint-disable-next-line @typescript-eslint/no-explicit-any -export const collabUnsetEditorsPointersData = (payload: any) => ({ - type: ReduxActionTypes.APP_COLLAB_UNSET_EDITORS_POINTER_DATA, - payload, -}); - -export const collabResetEditorsPointersData = () => ({ - type: ReduxActionTypes.APP_COLLAB_RESET_EDITORS_POINTER_DATA, -}); - -// TODO: Fix this the next time the file is edited -// eslint-disable-next-line @typescript-eslint/no-explicit-any -export const collabConcurrentPageEditorsData = (payload: any) => ({ - type: ReduxActionTypes.APP_COLLAB_SET_CONCURRENT_PAGE_EDITORS, - payload, -}); diff --git a/app/client/src/actions/pageVisibilityActions.ts b/app/client/src/actions/pageVisibilityActions.ts deleted file mode 100644 index 7823b73ab2e6..000000000000 --- a/app/client/src/actions/pageVisibilityActions.ts +++ /dev/null @@ -1,8 +0,0 @@ -import { appLevelWebsocketWriteEvent } from "./websocketActions"; -import { APP_LEVEL_SOCKET_EVENTS } from "sagas/WebsocketSagas/socketEvents"; - -export const pageVisibilityAppEvent = (visibility: DocumentVisibilityState) => - appLevelWebsocketWriteEvent({ - type: APP_LEVEL_SOCKET_EVENTS.PAGE_VISIBILITY, - payload: visibility, - }); diff --git a/app/client/src/actions/websocketActions.ts b/app/client/src/actions/websocketActions.ts deleted file mode 100644 index 299f7dd4d4b0..000000000000 --- a/app/client/src/actions/websocketActions.ts +++ /dev/null @@ -1,44 +0,0 @@ -import { ReduxActionTypes } from "ee/constants/ReduxActionConstants"; -import { reconnectWebsocketEvent } from "constants/WebsocketConstants"; - -export const setIsAppLevelWebsocketConnected = (payload: boolean) => ({ - type: ReduxActionTypes.SET_IS_APP_LEVEL_WEBSOCKET_CONNECTED, - payload, -}); -export const setIsPageLevelWebsocketConnected = (payload: boolean) => ({ - type: ReduxActionTypes.SET_IS_PAGE_LEVEL_WEBSOCKET_CONNECTED, - payload, -}); - -export const appLevelWebsocketWriteEvent = (payload: { - type: string; - // TODO: Fix this the next time the file is edited - // eslint-disable-next-line @typescript-eslint/no-explicit-any - payload?: any; -}) => ({ - type: ReduxActionTypes.WEBSOCKET_APP_LEVEL_WRITE_CHANNEL, - payload, -}); -export const pageLevelWebsocketWriteEvent = (payload: { - type: string; - // TODO: Fix this the next time the file is edited - // eslint-disable-next-line @typescript-eslint/no-explicit-any - payload?: any; -}) => ({ - type: ReduxActionTypes.WEBSOCKET_PAGE_LEVEL_WRITE_CHANNEL, - payload, -}); - -export const reconnectAppLevelWebsocket = () => - appLevelWebsocketWriteEvent(reconnectWebsocketEvent()); - -export const initAppLevelSocketConnection = () => ({ - type: ReduxActionTypes.INIT_APP_LEVEL_SOCKET_CONNECTION, -}); - -export const reconnectPageLevelWebsocket = () => - pageLevelWebsocketWriteEvent(reconnectWebsocketEvent()); - -export const initPageLevelSocketConnection = () => ({ - type: ReduxActionTypes.INIT_PAGE_LEVEL_SOCKET_CONNECTION, -}); diff --git a/app/client/src/ce/constants/ReduxActionConstants.tsx b/app/client/src/ce/constants/ReduxActionConstants.tsx index 0ecaa63d846e..4aaae0ba18c0 100644 --- a/app/client/src/ce/constants/ReduxActionConstants.tsx +++ b/app/client/src/ce/constants/ReduxActionConstants.tsx @@ -1,16 +1,6 @@ import type { ERROR_CODES } from "ee/constants/ApiConstants"; import type { AffectedJSObjects } from "sagas/EvaluationsSagaUtils"; -const WebsocketActions = { - WEBSOCKET_APP_LEVEL_WRITE_CHANNEL: "WEBSOCKET_APP_LEVEL_WRITE_CHANNEL", - WEBSOCKET_PAGE_LEVEL_WRITE_CHANNEL: "WEBSOCKET_PAGE_LEVEL_WRITE_CHANNEL", - INIT_APP_LEVEL_SOCKET_CONNECTION: "INIT_APP_LEVEL_SOCKET_CONNECTION", - INIT_PAGE_LEVEL_SOCKET_CONNECTION: "INIT_PAGE_LEVEL_SOCKET_CONNECTION", - SET_IS_APP_LEVEL_WEBSOCKET_CONNECTED: "SET_IS_APP_LEVEL_WEBSOCKET_CONNECTED", - SET_IS_PAGE_LEVEL_WEBSOCKET_CONNECTED: - "SET_IS_PAGE_LEVEL_WEBSOCKET_CONNECTED", -}; - const ActionSelectorReduxActionTypes = { EVALUATE_ACTION_SELECTOR_FIELD: "EVALUATE_ACTION_SELECTOR_FIELD", SET_EVALUATED_ACTION_SELECTOR_FIELD: "SET_EVALUATED_ACTION_SELECTOR_FIELD", @@ -307,18 +297,6 @@ const EvaluationActionErrorTypes = { FAILED_CORRECTING_BINDING_PATHS: "FAILED_CORRECTING_BINDING_PATHS", }; -const AppCollabActionTypes = { - APP_COLLAB_SET_CONCURRENT_PAGE_EDITORS: - "APP_COLLAB_SET_CONCURRENT_PAGE_EDITORS", - APP_COLLAB_LIST_EDITORS: "APP_COLLAB_LIST_EDITORS", - APP_COLLAB_RESET_EDITORS: "APP_COLLAB_RESET_EDITORS", - APP_COLLAB_SET_EDITORS_POINTER_DATA: "APP_COLLAB_SET_EDITORS_POINTER_DATA", - APP_COLLAB_UNSET_EDITORS_POINTER_DATA: - "APP_COLLAB_UNSET_EDITORS_POINTER_DATA", - APP_COLLAB_RESET_EDITORS_POINTER_DATA: - "APP_COLLAB_RESET_EDITORS_POINTER_DATA", -}; - const OmniSearchActionTypes = { SET_SEARCH_FILTER_CONTEXT: "SET_SEARCH_FILTER_CONTEXT", SET_GLOBAL_SEARCH_QUERY: "SET_GLOBAL_SEARCH_QUERY", @@ -1280,7 +1258,6 @@ export const ReduxActionTypes = { ...AdminSettingsActionTypes, ...AnalyticsActionTypes, ...AIActionTypes, - ...AppCollabActionTypes, ...ApplicationActionTypes, ...AppThemeActionsTypes, ...AppViewActionTypes, @@ -1316,7 +1293,6 @@ export const ReduxActionTypes = { ...ThemeActionTypes, ...UserAuthActionTypes, ...UserProfileActionTypes, - ...WebsocketActions, ...WidgetCanvasActionTypes, ...WidgetOperationsActionTypes, ...WorkspaceActionTypes, diff --git a/app/client/src/ce/reducers/index.tsx b/app/client/src/ce/reducers/index.tsx index 66d367063fe9..90790e6fe4bf 100644 --- a/app/client/src/ce/reducers/index.tsx +++ b/app/client/src/ce/reducers/index.tsx @@ -36,7 +36,6 @@ import type { GlobalSearchReduxState } from "reducers/uiReducers/globalSearchRed import type { ActionSelectorReduxState } from "reducers/uiReducers/actionSelectorReducer"; import type { ReleasesState } from "reducers/uiReducers/releasesReducer"; import type { LoadingEntitiesState } from "reducers/evaluationReducers/loadingEntitiesReducer"; -import type { WebsocketReducerState } from "reducers/uiReducers/websocketReducer"; import type { DebuggerReduxState } from "reducers/uiReducers/debuggerReducer"; import type { TourReducerState } from "reducers/uiReducers/tourReducer"; import type { TableFilterPaneReduxState } from "reducers/uiReducers/tableFilterPaneReducer"; @@ -45,7 +44,6 @@ import type { JSCollectionDataState } from "ee/reducers/entityReducers/jsActions import type { CanvasSelectionState } from "reducers/uiReducers/canvasSelectionReducer"; import type { JSObjectNameReduxState } from "reducers/uiReducers/jsObjectNameReducer"; import type { GitSyncReducerState } from "reducers/uiReducers/gitSyncReducer"; -import type { AppCollabReducerState } from "reducers/uiReducers/appCollabReducer"; import type { CrudInfoModalReduxState } from "reducers/uiReducers/crudInfoModalReducer"; import type { FormEvaluationState } from "reducers/evaluationReducers/formEvaluationReducer"; import type { widgetReflow } from "reducers/uiReducers/reflowReducer"; @@ -121,14 +119,12 @@ export interface AppState { onBoarding: OnboardingState; globalSearch: GlobalSearchReduxState; releases: ReleasesState; - websocket: WebsocketReducerState; debugger: DebuggerReduxState; tour: TourReducerState; jsPane: JsPaneReduxState; canvasSelection: CanvasSelectionState; jsObjectName: JSObjectNameReduxState; gitSync: GitSyncReducerState; - appCollab: AppCollabReducerState; crudInfoModal: CrudInfoModalReduxState; widgetReflow: widgetReflow; appTheming: AppThemingState; diff --git a/app/client/src/ce/reducers/uiReducers/index.tsx b/app/client/src/ce/reducers/uiReducers/index.tsx index 35c9294b3969..3685e13afb75 100644 --- a/app/client/src/ce/reducers/uiReducers/index.tsx +++ b/app/client/src/ce/reducers/uiReducers/index.tsx @@ -23,12 +23,10 @@ import onBoardingReducer from "reducers/uiReducers/onBoardingReducer"; import globalSearchReducer from "reducers/uiReducers/globalSearchReducer"; import actionSelectorReducer from "reducers/uiReducers/actionSelectorReducer"; import releasesReducer from "reducers/uiReducers/releasesReducer"; -import websocketReducer from "reducers/uiReducers/websocketReducer"; import debuggerReducer from "reducers/uiReducers/debuggerReducer"; import tourReducer from "reducers/uiReducers/tourReducer"; import tableFilterPaneReducer from "reducers/uiReducers/tableFilterPaneReducer"; import jsPaneReducer from "reducers/uiReducers/jsPaneReducer"; -import appCollabReducer from "reducers/uiReducers/appCollabReducer"; import canvasSelectionReducer from "reducers/uiReducers/canvasSelectionReducer"; import gitSyncReducer from "reducers/uiReducers/gitSyncReducer"; import crudInfoModalReducer from "reducers/uiReducers/crudInfoModalReducer"; @@ -78,14 +76,12 @@ export const uiReducerObject = { onBoarding: onBoardingReducer, globalSearch: globalSearchReducer, releases: releasesReducer, - websocket: websocketReducer, debugger: debuggerReducer, tour: tourReducer, jsPane: jsPaneReducer, jsObjectName: jsObjectNameReducer, canvasSelection: canvasSelectionReducer, gitSync: gitSyncReducer, - appCollab: appCollabReducer, crudInfoModal: crudInfoModalReducer, widgetReflow: widgetReflowReducer, appTheming: appThemingReducer, diff --git a/app/client/src/ce/sagas/ApplicationSagas.tsx b/app/client/src/ce/sagas/ApplicationSagas.tsx index 342e72db3750..18a88bce38f8 100644 --- a/app/client/src/ce/sagas/ApplicationSagas.tsx +++ b/app/client/src/ce/sagas/ApplicationSagas.tsx @@ -73,10 +73,6 @@ import { deleteRecentAppEntities, getEnableStartSignposting, } from "utils/storage"; -import { - reconnectAppLevelWebsocket, - reconnectPageLevelWebsocket, -} from "actions/websocketActions"; import { getFetchedWorkspaces } from "ee/selectors/workspaceSelectors"; import { fetchPluginFormConfigs, fetchPlugins } from "actions/pluginActions"; @@ -648,12 +644,6 @@ export function* createApplicationSaga( basePageId: defaultPage?.baseId, }), ); - - // subscribe to newly created application - // users join rooms on connection, so reconnecting - // ensures user receives the updates in the app just created - yield put(reconnectAppLevelWebsocket()); - yield put(reconnectPageLevelWebsocket()); } } } catch (error) { diff --git a/app/client/src/ce/sagas/index.tsx b/app/client/src/ce/sagas/index.tsx index e18571b07905..844f9406af82 100644 --- a/app/client/src/ce/sagas/index.tsx +++ b/app/client/src/ce/sagas/index.tsx @@ -33,7 +33,6 @@ import LintingSaga from "sagas/LintingSagas"; import modalSagas from "sagas/ModalSagas"; import onboardingSagas from "sagas/OnboardingSagas"; import pageSagas from "ee/sagas/PageSagas"; -import PageVisibilitySaga from "sagas/PageVisibilitySagas"; import pluginSagas from "sagas/PluginSagas"; import queryPaneSagas from "sagas/QueryPaneSagas"; import replaySaga from "sagas/ReplaySaga"; @@ -42,7 +41,6 @@ import snapshotSagas from "sagas/SnapshotSagas"; import snipingModeSagas from "sagas/SnipingModeSagas"; import templateSagas from "sagas/TemplatesSagas"; import themeSagas from "sagas/ThemeSaga"; -import websocketSagas from "sagas/WebsocketSagas/WebsocketSagas"; import actionExecutionChangeListeners from "sagas/WidgetLoadingSaga"; import widgetOperationSagas from "sagas/WidgetOperationSagas"; import oneClickBindingSaga from "sagas/OneClickBindingSaga"; @@ -83,7 +81,6 @@ export const sagas = [ actionExecutionChangeListeners, formEvaluationChangeListener, globalSearchSagas, - websocketSagas, debuggerSagas, saaSPaneSagas, selectionCanvasSagas, @@ -94,7 +91,6 @@ export const sagas = [ appThemingSaga, NavigationSagas, editorContextSagas, - PageVisibilitySaga, AutoHeightSagas, tenantSagas, JSLibrarySaga, diff --git a/app/client/src/ce/sagas/userSagas.tsx b/app/client/src/ce/sagas/userSagas.tsx index 8daba706b682..132341739bb7 100644 --- a/app/client/src/ce/sagas/userSagas.tsx +++ b/app/client/src/ce/sagas/userSagas.tsx @@ -52,10 +52,6 @@ import { getCurrentUser, getFeatureFlagsFetched, } from "selectors/usersSelectors"; -import { - initAppLevelSocketConnection, - initPageLevelSocketConnection, -} from "actions/websocketActions"; import { getEnableStartSignposting, getFirstTimeUserOnboardingApplicationIds, @@ -181,9 +177,6 @@ export function* runUserSideEffectsSaga() { ); } - yield put(initAppLevelSocketConnection()); - yield put(initPageLevelSocketConnection()); - if (currentUser.emptyInstance) { history.replace(SETUP); } diff --git a/app/client/src/constants/WebsocketConstants.tsx b/app/client/src/constants/WebsocketConstants.tsx deleted file mode 100644 index d43807ece64a..000000000000 --- a/app/client/src/constants/WebsocketConstants.tsx +++ /dev/null @@ -1,22 +0,0 @@ -export const WEBSOCKET_EVENTS = { - RECONNECT: "RECONNECT", - DISCONNECTED: "DISCONNECTED", - CONNECTED: "CONNECTED", -}; - -export const reconnectWebsocketEvent = () => ({ - type: WEBSOCKET_EVENTS.RECONNECT, -}); - -export const websocketDisconnectedEvent = () => ({ - type: WEBSOCKET_EVENTS.DISCONNECTED, -}); - -export const websocketConnectedEvent = () => ({ - type: WEBSOCKET_EVENTS.CONNECTED, -}); - -export const RTS_BASE_PATH = "/rts"; -export const WEBSOCKET_NAMESPACE = { - PAGE_EDIT: "/page/edit", -}; diff --git a/app/client/src/constants/WidgetValidation.ts b/app/client/src/constants/WidgetValidation.ts index 1a321069187f..43d78d79e001 100644 --- a/app/client/src/constants/WidgetValidation.ts +++ b/app/client/src/constants/WidgetValidation.ts @@ -403,7 +403,6 @@ export const DEDICATED_WORKER_GLOBAL_SCOPE_IDENTIFIERS = { webkitRequestFileSystemSync: "webkitRequestFileSystemSync", webkitResolveLocalFileSystemSyncURL: "webkitResolveLocalFileSystemSyncURL", webkitResolveLocalFileSystemURL: "webkitResolveLocalFileSystemURL", - WebSocket: "WebSocket", WebTransport: "WebTransport", WebTransportBidirectionalStream: "WebTransportBidirectionalStream", WebTransportDatagramDuplexStream: "WebTransportDatagramDuplexStream", diff --git a/app/client/src/reducers/uiReducers/appCollabReducer.ts b/app/client/src/reducers/uiReducers/appCollabReducer.ts deleted file mode 100644 index 7bc8679439a5..000000000000 --- a/app/client/src/reducers/uiReducers/appCollabReducer.ts +++ /dev/null @@ -1,87 +0,0 @@ -import type { ReduxAction } from "ee/constants/ReduxActionConstants"; -import { ReduxActionTypes } from "ee/constants/ReduxActionConstants"; -import { createReducer } from "utils/ReducerUtils"; -import type { User } from "entities/AppCollab/CollabInterfaces"; -import { cloneDeep } from "lodash"; - -const initialState: AppCollabReducerState = { - editors: [], - pointerData: {}, - pageEditors: [], -}; - -const appCollabReducer = createReducer(initialState, { - [ReduxActionTypes.APP_COLLAB_LIST_EDITORS]: ( - state: AppCollabReducerState, - // TODO: Fix this the next time the file is edited - // eslint-disable-next-line @typescript-eslint/no-explicit-any - action: ReduxAction<any>, - ) => { - return { ...state, editors: action.payload.users }; - }, - [ReduxActionTypes.APP_COLLAB_RESET_EDITORS]: ( - state: AppCollabReducerState, - ) => { - return { ...state, editors: [] }; - }, - [ReduxActionTypes.APP_COLLAB_SET_EDITORS_POINTER_DATA]: ( - state: AppCollabReducerState, - // TODO: Fix this the next time the file is edited - // eslint-disable-next-line @typescript-eslint/no-explicit-any - action: ReduxAction<any>, - ) => { - return { - ...state, - pointerData: { - ...state.pointerData, - [action.payload.socketId]: action.payload, - }, - }; - }, - [ReduxActionTypes.APP_COLLAB_UNSET_EDITORS_POINTER_DATA]: ( - state: AppCollabReducerState, - // TODO: Fix this the next time the file is edited - // eslint-disable-next-line @typescript-eslint/no-explicit-any - action: ReduxAction<any>, - ) => { - const clonedPointerData = cloneDeep(state.pointerData); - - delete clonedPointerData[action.payload]; - - return { - ...state, - clonedPointerData, - }; - }, - [ReduxActionTypes.APP_COLLAB_RESET_EDITORS_POINTER_DATA]: ( - state: AppCollabReducerState, - ) => { - return { - ...state, - pointerData: {}, - }; - }, - [ReduxActionTypes.APP_COLLAB_SET_CONCURRENT_PAGE_EDITORS]: ( - state: AppCollabReducerState, - // TODO: Fix this the next time the file is edited - // eslint-disable-next-line @typescript-eslint/no-explicit-any - action: ReduxAction<any>, - ) => ({ - ...state, - pageEditors: action.payload, - }), -}); - -interface PointerDataType { - // TODO: Fix this the next time the file is edited - // eslint-disable-next-line @typescript-eslint/no-explicit-any - [s: string]: any; -} - -export interface AppCollabReducerState { - editors: User[]; - pointerData: PointerDataType; - pageEditors: User[]; -} - -export default appCollabReducer; diff --git a/app/client/src/reducers/uiReducers/websocketReducer.ts b/app/client/src/reducers/uiReducers/websocketReducer.ts deleted file mode 100644 index 44d96ac82382..000000000000 --- a/app/client/src/reducers/uiReducers/websocketReducer.ts +++ /dev/null @@ -1,30 +0,0 @@ -import { createReducer } from "utils/ReducerUtils"; -import type { ReduxAction } from "ee/constants/ReduxActionConstants"; -import { ReduxActionTypes } from "ee/constants/ReduxActionConstants"; - -const initialState: WebsocketReducerState = { - appLevelSocketConnected: false, - pageLevelSocketConnected: false, -}; - -const websocketReducer = createReducer(initialState, { - [ReduxActionTypes.SET_IS_APP_LEVEL_WEBSOCKET_CONNECTED]: ( - state: WebsocketReducerState, - action: ReduxAction<boolean>, - ) => { - return { ...state, appLevelSocketConnected: action.payload }; - }, - [ReduxActionTypes.SET_IS_PAGE_LEVEL_WEBSOCKET_CONNECTED]: ( - state: WebsocketReducerState, - action: ReduxAction<boolean>, - ) => { - return { ...state, pageLevelSocketConnected: action.payload }; - }, -}); - -export interface WebsocketReducerState { - appLevelSocketConnected: boolean; - pageLevelSocketConnected: boolean; -} - -export default websocketReducer; diff --git a/app/client/src/sagas/PageVisibilitySagas.ts b/app/client/src/sagas/PageVisibilitySagas.ts deleted file mode 100644 index 4c9125511197..000000000000 --- a/app/client/src/sagas/PageVisibilitySagas.ts +++ /dev/null @@ -1,35 +0,0 @@ -import type { EventChannel } from "redux-saga"; -import { eventChannel } from "redux-saga"; -import { call, fork, put, take } from "redux-saga/effects"; -import { pageVisibilityAppEvent } from "actions/pageVisibilityActions"; - -// Track page visibility -// https://developer.mozilla.org/en-US/docs/Web/API/Page_Visibility_API -function listenToVisibilityEvents() { - return eventChannel((emitter) => { - document.addEventListener("visibilitychange", emitter, false); - - return () => { - document.removeEventListener("visibilitychange", emitter, false); - }; - }); -} - -function* handleTabVisibilityConnection() { - const channel: EventChannel<unknown> = yield call(listenToVisibilityEvents); - - while (true) { - const event: { - target: { visibilityState: DocumentVisibilityState }; - } = yield take(channel); - - // Only invoke when page gets visible - if (event.target && event.target.visibilityState === "visible") { - yield put(pageVisibilityAppEvent(event.target.visibilityState)); - } - } -} - -export default function* rootSaga() { - yield fork(handleTabVisibilityConnection); -} diff --git a/app/client/src/sagas/WebsocketSagas/WebsocketSagas.ts b/app/client/src/sagas/WebsocketSagas/WebsocketSagas.ts deleted file mode 100644 index 2a02c23ae172..000000000000 --- a/app/client/src/sagas/WebsocketSagas/WebsocketSagas.ts +++ /dev/null @@ -1,214 +0,0 @@ -import type { Socket, ManagerOptions, SocketOptions } from "socket.io-client"; -import { io } from "socket.io-client"; -import type { EventChannel, Task } from "redux-saga"; -import { eventChannel } from "redux-saga"; -import { fork, take, call, cancel, put } from "redux-saga/effects"; -import { ReduxActionTypes } from "ee/constants/ReduxActionConstants"; -import { - WEBSOCKET_EVENTS, - RTS_BASE_PATH, - WEBSOCKET_NAMESPACE, - websocketDisconnectedEvent, - websocketConnectedEvent, -} from "constants/WebsocketConstants"; - -import { - setIsAppLevelWebsocketConnected, - setIsPageLevelWebsocketConnected, -} from "actions/websocketActions"; - -import handleAppLevelSocketEvents from "./handleAppLevelSocketEvents"; -import handlePageLevelSocketEvents from "./handlePageLevelSocketEvents"; -import * as Sentry from "@sentry/react"; -import { SOCKET_CONNECTION_EVENTS } from "./socketEvents"; - -async function connect(namespace?: string) { - const options: Partial<ManagerOptions & SocketOptions> = { - path: RTS_BASE_PATH, - // The default transports is ["polling", "websocket"], so polling is tried first. But polling - // needs sticky session to be turned on, in a clustered environment, even for it to upgrade to websockets. - // Ref: <https://github.com/socketio/socket.io/issues/2140>. - transports: ["websocket"], - reconnectionAttempts: 5, - reconnectionDelay: 3000, - }; - const socket = !!namespace ? io(namespace, options) : io(options); - - return new Promise((resolve) => { - socket.on(SOCKET_CONNECTION_EVENTS.CONNECT, () => { - socket.off(SOCKET_CONNECTION_EVENTS.CONNECT); - resolve(socket); - }); - }); -} - -function listenToSocket(socket: Socket) { - return eventChannel((emit) => { - // TODO: Fix this the next time the file is edited - // eslint-disable-next-line @typescript-eslint/no-explicit-any - socket.onAny((event: any, ...args: any) => { - emit({ - type: event, - payload: args, - }); - }); - socket.on(SOCKET_CONNECTION_EVENTS.DISCONNECT, () => { - emit(websocketDisconnectedEvent()); - }); - socket.on(SOCKET_CONNECTION_EVENTS.CONNECT, () => { - emit(websocketConnectedEvent()); - }); - - return () => { - socket.disconnect(); - }; - }); -} - -// TODO: Fix this the next time the file is edited -// eslint-disable-next-line @typescript-eslint/no-explicit-any -function* readFromAppSocket(socket: any) { - const channel: EventChannel<unknown> = yield call(listenToSocket, socket); - - while (true) { - const action: { type: keyof typeof WEBSOCKET_EVENTS } = yield take(channel); - - switch (action.type) { - case WEBSOCKET_EVENTS.DISCONNECTED: - yield put(setIsAppLevelWebsocketConnected(false)); - break; - case WEBSOCKET_EVENTS.CONNECTED: - yield put(setIsAppLevelWebsocketConnected(true)); - break; - default: { - yield call(handleAppLevelSocketEvents, action); - } - } - } -} - -// TODO: Fix this the next time the file is edited -// eslint-disable-next-line @typescript-eslint/no-explicit-any -function* writeToAppSocket(socket: any) { - while (true) { - const { payload } = yield take( - ReduxActionTypes.WEBSOCKET_APP_LEVEL_WRITE_CHANNEL, - ); - - // reconnect to reset connection at the server - try { - if (payload.type === WEBSOCKET_EVENTS.RECONNECT) { - yield put(setIsAppLevelWebsocketConnected(false)); - socket.disconnect().connect(); - } else { - socket.emit(payload.type, payload.payload); - } - } catch (e) { - Sentry.captureException(e); - } - } -} - -// TODO: Fix this the next time the file is edited -// eslint-disable-next-line @typescript-eslint/no-explicit-any -function* handleAppSocketIO(socket: any) { - yield fork(readFromAppSocket, socket); - yield fork(writeToAppSocket, socket); -} - -function* openAppLevelSocketConnection() { - while (true) { - yield take(ReduxActionTypes.INIT_APP_LEVEL_SOCKET_CONNECTION); - try { - /** - * Incase the socket is disconnected due to network latencies - * it reuses the same instance so we don't need to bind it again - * this is verified using the reconnect flow - * We only need to retry incase the socket connection isn't made - * in the first attempt itself - */ - const socket: Socket = yield call(connect); - const task: Task = yield fork(handleAppSocketIO, socket); - - yield put(setIsAppLevelWebsocketConnected(true)); - yield take([ReduxActionTypes.LOGOUT_USER_INIT]); - yield cancel(task); - socket?.disconnect(); - } catch (e) { - Sentry.captureException(e); - } - } -} - -// TODO: Fix this the next time the file is edited -// eslint-disable-next-line @typescript-eslint/no-explicit-any -function* readFromPageSocket(socket: any) { - const channel: EventChannel<unknown> = yield call(listenToSocket, socket); - - while (true) { - const action: { type: keyof typeof WEBSOCKET_EVENTS } = yield take(channel); - - switch (action.type) { - case WEBSOCKET_EVENTS.DISCONNECTED: - yield put(setIsPageLevelWebsocketConnected(false)); - break; - case WEBSOCKET_EVENTS.CONNECTED: - yield put(setIsPageLevelWebsocketConnected(true)); - break; - default: { - yield call(handlePageLevelSocketEvents, action, socket); - } - } - } -} - -// TODO: Fix this the next time the file is edited -// eslint-disable-next-line @typescript-eslint/no-explicit-any -function* writeToPageSocket(socket: any) { - while (true) { - const { payload } = yield take( - ReduxActionTypes.WEBSOCKET_PAGE_LEVEL_WRITE_CHANNEL, - ); - - // reconnect to reset connection at the server - try { - if (payload.type === WEBSOCKET_EVENTS.RECONNECT) { - yield put(setIsPageLevelWebsocketConnected(false)); - socket.disconnect().connect(); - } else { - socket.emit(payload.type, payload.payload); - } - } catch (e) { - Sentry.captureException(e); - } - } -} - -// TODO: Fix this the next time the file is edited -// eslint-disable-next-line @typescript-eslint/no-explicit-any -function* handlePageSocketIO(socket: any) { - yield fork(readFromPageSocket, socket); - yield fork(writeToPageSocket, socket); -} - -function* openPageLevelSocketConnection() { - while (true) { - yield take(ReduxActionTypes.INIT_PAGE_LEVEL_SOCKET_CONNECTION); - try { - const socket: Socket = yield call(connect, WEBSOCKET_NAMESPACE.PAGE_EDIT); - const task: Task = yield fork(handlePageSocketIO, socket); - - yield put(setIsPageLevelWebsocketConnected(true)); - yield take([ReduxActionTypes.LOGOUT_USER_INIT]); - yield cancel(task); - socket.disconnect(); - } catch (e) { - Sentry.captureException(e); - } - } -} - -export default function* rootSaga() { - yield fork(openAppLevelSocketConnection); - yield fork(openPageLevelSocketConnection); -} diff --git a/app/client/src/sagas/WebsocketSagas/handleAppLevelSocketEvents.tsx b/app/client/src/sagas/WebsocketSagas/handleAppLevelSocketEvents.tsx deleted file mode 100644 index c5cf5d863d0d..000000000000 --- a/app/client/src/sagas/WebsocketSagas/handleAppLevelSocketEvents.tsx +++ /dev/null @@ -1,17 +0,0 @@ -import { put } from "redux-saga/effects"; -import { APP_LEVEL_SOCKET_EVENTS } from "./socketEvents"; - -import { collabSetAppEditors } from "actions/appCollabActions"; - -// TODO: Fix this the next time the file is edited -// eslint-disable-next-line @typescript-eslint/no-explicit-any -export default function* handleAppLevelSocketEvents(event: any) { - switch (event.type) { - // Collab V2 - Realtime Editing - case APP_LEVEL_SOCKET_EVENTS.LIST_ONLINE_APP_EDITORS: { - yield put(collabSetAppEditors(event.payload[0])); - - return; - } - } -} diff --git a/app/client/src/sagas/WebsocketSagas/handlePageLevelSocketEvents.ts b/app/client/src/sagas/WebsocketSagas/handlePageLevelSocketEvents.ts deleted file mode 100644 index aafd0310ed13..000000000000 --- a/app/client/src/sagas/WebsocketSagas/handlePageLevelSocketEvents.ts +++ /dev/null @@ -1,37 +0,0 @@ -import { put } from "redux-saga/effects"; -import { PAGE_LEVEL_SOCKET_EVENTS } from "./socketEvents"; -import { - collabSetEditorsPointersData, - collabUnsetEditorsPointersData, - collabConcurrentPageEditorsData, -} from "actions/appCollabActions"; -import * as Sentry from "@sentry/react"; - -// TODO: Fix this the next time the file is edited -// eslint-disable-next-line @typescript-eslint/no-explicit-any -export default function* handlePageLevelSocketEvents(event: any, socket: any) { - try { - switch (event.type) { - case PAGE_LEVEL_SOCKET_EVENTS.SHARE_USER_POINTER: { - if (socket.id !== event.payload[0].socketId) { - yield put(collabSetEditorsPointersData(event.payload[0])); - } - - return; - } - case PAGE_LEVEL_SOCKET_EVENTS.STOP_EDITING_APP: { - yield put(collabUnsetEditorsPointersData(event.payload[0])); - - return; - } - - case PAGE_LEVEL_SOCKET_EVENTS.LIST_ONLINE_PAGE_EDITORS: { - yield put(collabConcurrentPageEditorsData(event.payload[0]?.users)); - - return; - } - } - } catch (e) { - Sentry.captureException(e); - } -} diff --git a/app/client/src/sagas/WebsocketSagas/socketEvents.ts b/app/client/src/sagas/WebsocketSagas/socketEvents.ts deleted file mode 100644 index 0dacc84ba107..000000000000 --- a/app/client/src/sagas/WebsocketSagas/socketEvents.ts +++ /dev/null @@ -1,22 +0,0 @@ -export const SOCKET_CONNECTION_EVENTS = { - CONNECT: "connect", - DISCONNECT: "disconnect", -}; - -export const APP_LEVEL_SOCKET_EVENTS = { - // notification events - INSERT_NOTIFICATION: "insert:notification", - - LIST_ONLINE_APP_EDITORS: "collab:online_editors", // user presence - - RELEASE_VERSION_NOTIFICATION: "info:release_version", // release version - - PAGE_VISIBILITY: "info:page_visibility", // is the page/tab visible to the user -}; - -export const PAGE_LEVEL_SOCKET_EVENTS = { - START_EDITING_APP: "collab:start_edit", - STOP_EDITING_APP: "collab:leave_edit", - LIST_ONLINE_PAGE_EDITORS: "collab:online_editors", - SHARE_USER_POINTER: "collab:mouse_pointer", // multi pointer -}; diff --git a/app/client/test/sagas.ts b/app/client/test/sagas.ts index fcdf46d64a9d..602f10fbcf6d 100644 --- a/app/client/test/sagas.ts +++ b/app/client/test/sagas.ts @@ -24,7 +24,6 @@ import queryPaneSagas from "../src/sagas/QueryPaneSagas"; import saaSPaneSagas from "../src/sagas/SaaSPaneSagas"; import snipingModeSagas from "../src/sagas/SnipingModeSagas"; import themeSagas from "../src/sagas/ThemeSaga"; -import websocketSagas from "../src/sagas/WebsocketSagas/WebsocketSagas"; import actionExecutionChangeListeners from "../src/sagas/WidgetLoadingSaga"; import widgetOperationSagas from "../src/sagas/WidgetOperationSagas"; import NavigationSagas from "../src/ee/sagas/NavigationSagas"; @@ -51,7 +50,6 @@ export const sagasToRunForTests = [ formEvaluationChangeListener, saaSPaneSagas, globalSearchSagas, - websocketSagas, debuggerSagas, watchJSActionSagas, selectionCanvasSagas, diff --git a/app/client/yarn.lock b/app/client/yarn.lock index a53246450b44..883016fcedae 100644 --- a/app/client/yarn.lock +++ b/app/client/yarn.lock @@ -12983,7 +12983,6 @@ __metadata: showdown: ^1.9.1 simplebar-react: ^2.4.3 smartlook-client: ^8.0.0 - socket.io-client: ^4.5.4 sql-formatter: 12.2.0 styled-components: ^5.3.6 tailwindcss: ^3.3.3 @@ -17398,26 +17397,6 @@ __metadata: languageName: node linkType: hard -"engine.io-client@npm:~6.2.3": - version: 6.2.3 - resolution: "engine.io-client@npm:6.2.3" - dependencies: - "@socket.io/component-emitter": ~3.1.0 - debug: ~4.3.1 - engine.io-parser: ~5.0.3 - ws: ~8.2.3 - xmlhttprequest-ssl: ~2.0.0 - checksum: c09fb6429503a4a8a599ec1c4f67f100202e6e06588b67b81d386a4ebf8e81160cf7501ad6770ffe0a04575f41868f0a4cbf330b85de3f7cd24ebcf2bf9fc660 - languageName: node - linkType: hard - -"engine.io-parser@npm:~5.0.3": - version: 5.0.4 - resolution: "engine.io-parser@npm:5.0.4" - checksum: d4ad0cef6ff63c350e35696da9bb3dbd180f67b56e93e90375010cc40393e6c0639b780d5680807e1d93a7e2e3d7b4a1c3b27cf75db28eb8cbf605bc1497da03 - languageName: node - linkType: hard - "engine.io-parser@npm:~5.2.1": version: 5.2.2 resolution: "engine.io-parser@npm:5.2.2" @@ -31137,19 +31116,7 @@ __metadata: languageName: node linkType: hard -"socket.io-client@npm:^4.5.4": - version: 4.5.4 - resolution: "socket.io-client@npm:4.5.4" - dependencies: - "@socket.io/component-emitter": ~3.1.0 - debug: ~4.3.2 - engine.io-client: ~6.2.3 - socket.io-parser: ~4.2.1 - checksum: 8320ce4a96e9c28318b17037e412746b1d612cfba653c3c321c0e49042f0be9aeb8de67d5861e45e9aad32407bb4dd204bfe199565d78d5320aaf65253371b7f - languageName: node - linkType: hard - -"socket.io-parser@npm:~4.2.1, socket.io-parser@npm:~4.2.4": +"socket.io-parser@npm:~4.2.4": version: 4.2.4 resolution: "socket.io-parser@npm:4.2.4" dependencies: @@ -34839,21 +34806,6 @@ __metadata: languageName: node linkType: hard -"ws@npm:~8.2.3": - version: 8.2.3 - resolution: "ws@npm:8.2.3" - peerDependencies: - bufferutil: ^4.0.1 - utf-8-validate: ^5.0.2 - peerDependenciesMeta: - bufferutil: - optional: true - utf-8-validate: - optional: true - checksum: c869296ccb45f218ac6d32f8f614cd85b50a21fd434caf11646008eef92173be53490810c5c23aea31bc527902261fbfd7b062197eea341b26128d4be56a85e4 - languageName: node - linkType: hard - "xlsx@https://cdn.sheetjs.com/xlsx-0.19.3/xlsx-0.19.3.tgz": version: 0.19.3 resolution: "xlsx@https://cdn.sheetjs.com/xlsx-0.19.3/xlsx-0.19.3.tgz" @@ -34898,13 +34850,6 @@ __metadata: languageName: node linkType: hard -"xmlhttprequest-ssl@npm:~2.0.0": - version: 2.0.0 - resolution: "xmlhttprequest-ssl@npm:2.0.0" - checksum: 1e98df67f004fec15754392a131343ea92e6ab5ac4d77e842378c5c4e4fd5b6a9134b169d96842cc19422d77b1606b8df84a5685562b3b698cb68441636f827e - languageName: node - linkType: hard - "xtend@npm:^4.0.0, xtend@npm:^4.0.1, xtend@npm:^4.0.2, xtend@npm:~4.0.1": version: 4.0.2 resolution: "xtend@npm:4.0.2"
59023009d762858f3a18a40bfe6481616d183c6e
2023-11-23 16:44:57
yatinappsmith
ci: Add retry for JUnit failures in the CI workflow (#29048)
false
Add retry for JUnit failures in the CI workflow (#29048)
ci
diff --git a/.github/workflows/server-build.yml b/.github/workflows/server-build.yml index 12d14c5c6728..6fc653755384 100644 --- a/.github/workflows/server-build.yml +++ b/.github/workflows/server-build.yml @@ -145,7 +145,8 @@ jobs: mvn --batch-mode versions:set \ -DnewVersion=${{ steps.vars.outputs.version }} \ -DgenerateBackupPoms=false \ - -DprocessAllModules=true + -DprocessAllModules=true \ + -Dsurefire.rerunFailingTestsCount=3 -Dsurefire.outputFile="./junit-report.xml" ./build.sh $args # Restore the previous built bundle if present. If not push the newly built into the cache diff --git a/app/server/pom.xml b/app/server/pom.xml index ec8817d88755..124b63cde3f4 100644 --- a/app/server/pom.xml +++ b/app/server/pom.xml @@ -78,6 +78,7 @@ <artifactId>maven-surefire-plugin</artifactId> <version>3.0.0-M5</version> <configuration> + <printSummary>true</printSummary> <!-- Allow JUnit to access the test classes --> <argLine>--add-opens java.base/java.lang=ALL-UNNAMED --add-opens java.base/java.time=ALL-UNNAMED
f51da7019dcdf309dc57db14836fcbb96ae76c59
2022-03-31 19:02:54
Trisha Anand
chore: Adding delete endpoint in ConfigService (#12450)
false
Adding delete endpoint in ConfigService (#12450)
chore
diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/ConfigServiceCE.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/ConfigServiceCE.java index f2c4e7167009..e562b81a60ad 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/ConfigServiceCE.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/ConfigServiceCE.java @@ -26,4 +26,5 @@ public interface ConfigServiceCE { Flux<Datasource> getTemplateDatasources(); + Mono<Void> delete(String name); } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/ConfigServiceCEImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/ConfigServiceCEImpl.java index 3a01b6002945..6ece92cb70e5 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/ConfigServiceCEImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/ConfigServiceCEImpl.java @@ -9,10 +9,8 @@ import com.appsmith.server.repositories.ApplicationRepository; import com.appsmith.server.repositories.ConfigRepository; import com.appsmith.server.repositories.DatasourceRepository; -import com.appsmith.server.services.ConfigService; import lombok.extern.slf4j.Slf4j; import net.minidev.json.JSONObject; -import org.springframework.stereotype.Service; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; @@ -122,4 +120,11 @@ public Flux<Datasource> getTemplateDatasources() { .flatMapMany(datasourceRepository::findByIdIn); } + @Override + public Mono<Void> delete(String name) { + return repository.findByName(name) + .switchIfEmpty(Mono.error(new AppsmithException(AppsmithError.NO_RESOURCE_FOUND, FieldName.CONFIG, name))) + .flatMap(repository::delete); + } + }
b76e78e006a2178be03ad78906eb08dd06ec331e
2023-09-19 21:21:34
Shrikant Sharat Kandula
fix: Postgres permission error in creating the stats folder (#27454)
false
Postgres permission error in creating the stats folder (#27454)
fix
diff --git a/deploy/docker/fs/opt/appsmith/run-postgres.sh b/deploy/docker/fs/opt/appsmith/run-postgres.sh index 5d3084012b62..427fa4a677d7 100755 --- a/deploy/docker/fs/opt/appsmith/run-postgres.sh +++ b/deploy/docker/fs/opt/appsmith/run-postgres.sh @@ -1,5 +1,4 @@ #!/bin/bash rm -f /appsmith-stacks/data/postgres/main/core.* -mkdir -p "$TMP/postgres-stats" -exec /usr/lib/postgresql/13/bin/postgres -D "/appsmith-stacks/data/postgres/main" -c listen_addresses=127.0.0.1 -c stats_temp_directory="$TMP/postgres-stats" +exec /usr/lib/postgresql/13/bin/postgres -D "/appsmith-stacks/data/postgres/main" -c listen_addresses=127.0.0.1
e6fccb8341dc260893b10d513b967c69faefb71d
2023-06-14 13:24:24
albinAppsmith
fix: Property pane dropdown alignment when icon is present (#24289)
false
Property pane dropdown alignment when icon is present (#24289)
fix
diff --git a/app/client/cypress/e2e/Regression/ClientSide/Widgets/ListV2/Listv2_dataIdentifierProperty_spec.js b/app/client/cypress/e2e/Regression/ClientSide/Widgets/ListV2/Listv2_dataIdentifierProperty_spec.js index baa74e1c0aa3..00e63fe6efae 100644 --- a/app/client/cypress/e2e/Regression/ClientSide/Widgets/ListV2/Listv2_dataIdentifierProperty_spec.js +++ b/app/client/cypress/e2e/Regression/ClientSide/Widgets/ListV2/Listv2_dataIdentifierProperty_spec.js @@ -71,7 +71,7 @@ describe("List v2 - Data Identifier property", () => { cy.wait(250); // check if all the keys are present - cy.get(".rc-select-item-option-content > span") + cy.get(".rc-select-item-option-content > div > span") .should("have.length", 3) .then(($el) => { // we get a list of jQuery elements diff --git a/app/client/src/components/propertyControls/DropDownControl.tsx b/app/client/src/components/propertyControls/DropDownControl.tsx index e64117eedd52..701bf8204097 100644 --- a/app/client/src/components/propertyControls/DropDownControl.tsx +++ b/app/client/src/components/propertyControls/DropDownControl.tsx @@ -117,34 +117,36 @@ class DropDownControl extends BaseControl<DropDownControlProps> { label={option.label} value={option.value} > - {/* Show Flag if present */} - {option.leftElement && ( - <FlagWrapper>{option.leftElement}</FlagWrapper> - )} - - {/* Show icon if present */} - {option.icon && ( - <Icon className="mr-1" name={option.icon} size="md" /> - )} - - {option.subText ? ( - this.props.hideSubText ? ( - // Show subText below the main text eg - DatePicker control - <div className="w-full flex flex-col"> - <Text kind="action-m">{option.label}</Text> - <Text kind="action-s">{option.subText}</Text> - </div> + <div className="flex flex-row w-full"> + {/* Show Flag if present */} + {option.leftElement && ( + <FlagWrapper>{option.leftElement}</FlagWrapper> + )} + + {/* Show icon if present */} + {option.icon && ( + <Icon className="mr-1" name={option.icon} size="md" /> + )} + + {option.subText ? ( + this.props.hideSubText ? ( + // Show subText below the main text eg - DatePicker control + <div className="w-full flex flex-col"> + <Text kind="action-m">{option.label}</Text> + <Text kind="action-s">{option.subText}</Text> + </div> + ) : ( + // Show subText to the right side eg - Label fontsize control + <div className="w-full flex justify-between items-end"> + <Text kind="action-m">{option.label}</Text> + <Text kind="action-s">{option.subText}</Text> + </div> + ) ) : ( - // Show subText to the right side eg - Label fontsize control - <div className="w-full flex justify-between items-end"> - <Text kind="action-m">{option.label}</Text> - <Text kind="action-s">{option.subText}</Text> - </div> - ) - ) : ( - // Only show the label eg - Auto height control - <Text kind="action-m">{option.label}</Text> - )} + // Only show the label eg - Auto height control + <Text kind="action-m">{option.label}</Text> + )} + </div> </Option> ))} </Select>
7ccc541fbf81e5c596e494792232dcacdb49a7db
2022-05-20 10:41:58
Maulik
fix: update placeholder for phone input widget (#13635)
false
update placeholder for phone input widget (#13635)
fix
diff --git a/app/client/src/widgets/PhoneInputWidget/widget/index.tsx b/app/client/src/widgets/PhoneInputWidget/widget/index.tsx index 6c387e6d0d0a..2b4c22a398c5 100644 --- a/app/client/src/widgets/PhoneInputWidget/widget/index.tsx +++ b/app/client/src/widgets/PhoneInputWidget/widget/index.tsx @@ -106,7 +106,7 @@ class PhoneInputWidget extends BaseInputWidget< propertyName: "defaultText", label: "Default Text", controlType: "INPUT_TEXT", - placeholderText: "John Doe", + placeholderText: "(000) 000-0000", isBindProperty: true, isTriggerProperty: false, validation: { @@ -115,7 +115,7 @@ class PhoneInputWidget extends BaseInputWidget< fn: defaultValueValidation, expected: { type: "string", - example: `000 0000`, + example: `(000) 000-0000`, autocompleteDataType: AutocompleteDataType.STRING, }, },
3ef40bfcc61af4dad8cffccde2776540d63ff661
2024-04-19 13:09:20
Pawan Kumar
fix: property navigation spec (#32782)
false
property navigation spec (#32782)
fix
diff --git a/app/client/cypress/e2e/Regression/ClientSide/Debugger/Widget_property_navigation_spec.ts b/app/client/cypress/e2e/Regression/ClientSide/Debugger/Widget_property_navigation_spec.ts index 24ecf19fc159..1f9699579c2c 100644 --- a/app/client/cypress/e2e/Regression/ClientSide/Debugger/Widget_property_navigation_spec.ts +++ b/app/client/cypress/e2e/Regression/ClientSide/Debugger/Widget_property_navigation_spec.ts @@ -50,7 +50,7 @@ describe( _.propPane.NavigateBackToPropertyPane(); _.debuggerHelper.ClickDebuggerIcon(); _.debuggerHelper.ClicklogEntityLink(); - _.agHelper.GetNAssertContains(_.propPane._paneTitle, "Menu Item 1"); + _.agHelper.GetNAssertContains(_.propPane._paneTitle, "Menu Item"); _.propPane.AssertIfPropertyIsVisible("icon"); _.debuggerHelper.CloseBottomBar(); EditorNavigation.SelectEntityByName("ButtonGroup1", EntityType.Widget);
943e7f2b0c6b77620026bd2cc622119d1cacc9ea
2025-03-06 13:22:24
Ankita Kinger
chore: Refactoring code by taking out the common logic for re-using it on other IDEs (#39577)
false
Refactoring code by taking out the common logic for re-using it on other IDEs (#39577)
chore
diff --git a/app/client/src/sagas/getNextEntityAfterRemove.test.ts b/app/client/src/IDE/utils/getNextEntityAfterRemove.test.ts similarity index 94% rename from app/client/src/sagas/getNextEntityAfterRemove.test.ts rename to app/client/src/IDE/utils/getNextEntityAfterRemove.test.ts index 77ad93bfd417..ec9120b5ff09 100644 --- a/app/client/src/sagas/getNextEntityAfterRemove.test.ts +++ b/app/client/src/IDE/utils/getNextEntityAfterRemove.test.ts @@ -1,7 +1,10 @@ import { EditorState } from "IDE/enums"; import { PluginType } from "entities/Plugin"; import * as FocusEntityObj from "navigation/FocusEntity"; -import { RedirectAction, getNextEntityAfterRemove } from "./IDESaga"; +import { + RedirectAction, + getNextEntityAfterRemove, +} from "./getNextEntityAfterRemove"; import { FocusEntity } from "navigation/FocusEntity"; import type { EntityItem } from "ee/IDE/Interfaces/EntityItem"; diff --git a/app/client/src/IDE/utils/getNextEntityAfterRemove.ts b/app/client/src/IDE/utils/getNextEntityAfterRemove.ts new file mode 100644 index 000000000000..2843b7d0ff11 --- /dev/null +++ b/app/client/src/IDE/utils/getNextEntityAfterRemove.ts @@ -0,0 +1,66 @@ +import type { EntityItem } from "ee/IDE/Interfaces/EntityItem"; +import { identifyEntityFromPath } from "navigation/FocusEntity"; + +/** + * Adds custom redirect logic to redirect after an item is deleted + * 1. Do not navigate if the deleted item is not selected + * 2. If it was the only item, navigate to the list url, to show the blank state + * 3. If there are other items, navigate to an item close to the current one + * **/ + +export enum RedirectAction { + NA = "NA", // No action is needed + LIST = "LIST", // Navigate to a creation URL + ITEM = "ITEM", // Navigate to this item +} + +interface RedirectActionDescription<T> { + action: RedirectAction; + payload?: T; +} + +export function getNextEntityAfterRemove<T extends EntityItem>( + removedId: string, + tabs: T[], +): RedirectActionDescription<T> { + const currentSelectedEntity = identifyEntityFromPath( + window.location.pathname, + ); + const isSelectedActionRemoved = currentSelectedEntity.id === removedId; + + // If removed item is not currently selected, don't redirect + if (!isSelectedActionRemoved) { + return { + action: RedirectAction.NA, + }; + } + + const indexOfTab = tabs.findIndex((item) => item.key === removedId); + + switch (indexOfTab) { + case -1: + // If no other action is remaining, navigate to the creation url + return { + action: RedirectAction.LIST, + }; + case 0: + // if the removed item is first item, then if tabs present, tabs + 1 + // else otherItems[0] -> TODO: consider changing this logic after discussion with + // design team. May be new listing UI for side by side + if (tabs.length > 1) { + return { + action: RedirectAction.ITEM, + payload: tabs[1], + }; + } else { + return { + action: RedirectAction.LIST, + }; + } + default: + return { + action: RedirectAction.ITEM, + payload: tabs[indexOfTab - 1], + }; + } +} diff --git a/app/client/src/IDE/utils/getUpdatedTabs.ts b/app/client/src/IDE/utils/getUpdatedTabs.ts new file mode 100644 index 000000000000..e2f201ec2145 --- /dev/null +++ b/app/client/src/IDE/utils/getUpdatedTabs.ts @@ -0,0 +1,7 @@ +export function getUpdatedTabs(newId: string, currentTabs: string[]) { + if (currentTabs.includes(newId)) return currentTabs; + + const newTabs = [...currentTabs, newId]; + + return newTabs; +} diff --git a/app/client/src/IDE/utils/groupAndSortEntitySegmentList.ts b/app/client/src/IDE/utils/groupAndSortEntitySegmentList.ts index 0c661cc82f25..9fa3cb40d5dc 100644 --- a/app/client/src/IDE/utils/groupAndSortEntitySegmentList.ts +++ b/app/client/src/IDE/utils/groupAndSortEntitySegmentList.ts @@ -1,14 +1,14 @@ -import { groupBy, sortBy } from "lodash"; import type { EntityItem } from "ee/IDE/Interfaces/EntityItem"; +import { groupBy, sortBy } from "lodash"; -export type EditorSegmentList = Array<{ +export type EditorSegmentList<T> = Array<{ group: string | "NA"; - items: EntityItem[]; + items: T[]; }>; -export const groupAndSortEntitySegmentList = ( - items: EntityItem[], -): EditorSegmentList => { +export const groupAndSortEntitySegmentList = <T extends EntityItem>( + items: T[], +): EditorSegmentList<T> => { const groups = groupBy(items, (item) => { if (item.group) return item.group; diff --git a/app/client/src/ce/PluginActionEditor/hooks/useBlockExecution.ts b/app/client/src/ce/PluginActionEditor/hooks/useBlockExecution.ts index e1ee5994c5f6..08cc042793cd 100644 --- a/app/client/src/ce/PluginActionEditor/hooks/useBlockExecution.ts +++ b/app/client/src/ce/PluginActionEditor/hooks/useBlockExecution.ts @@ -21,7 +21,7 @@ const useBlockExecution = () => { // this gets the url of the current action's datasource const actionDatasourceUrl = action.datasource.datasourceConfiguration?.url || ""; - const actionDatasourceUrlPath = action.actionConfiguration.path || ""; + const actionDatasourceUrlPath = action.actionConfiguration?.path || ""; // this gets the name of the current action's datasource const actionDatasourceName = action.datasource.name || ""; diff --git a/app/client/src/sagas/IDESaga.tsx b/app/client/src/sagas/IDESaga.tsx index 0f312ad3c977..42cf5866b480 100644 --- a/app/client/src/sagas/IDESaga.tsx +++ b/app/client/src/sagas/IDESaga.tsx @@ -1,5 +1,5 @@ import type { FocusEntityInfo } from "navigation/FocusEntity"; -import { FocusEntity, identifyEntityFromPath } from "navigation/FocusEntity"; +import { FocusEntity } from "navigation/FocusEntity"; import { all, call, put, select, takeEvery } from "redux-saga/effects"; import { getJSTabs, getQueryTabs } from "selectors/ideSelectors"; import { @@ -27,6 +27,11 @@ import { selectQuerySegmentEditorTabs, } from "ee/selectors/appIDESelectors"; import { getCurrentBasePageId } from "selectors/editorSelectors"; +import { + getNextEntityAfterRemove, + RedirectAction, +} from "IDE/utils/getNextEntityAfterRemove"; +import { getUpdatedTabs } from "IDE/utils/getUpdatedTabs"; export function* updateIDETabsOnRouteChangeSaga(entityInfo: FocusEntityInfo) { const { entity, id, params } = entityInfo; @@ -54,14 +59,6 @@ export function* updateIDETabsOnRouteChangeSaga(entityInfo: FocusEntityInfo) { } } -function* getUpdatedTabs(newId: string, currentTabs: string[]) { - if (currentTabs.includes(newId)) return currentTabs; - - const newTabs = [...currentTabs, newId]; - - return newTabs; -} - export function* handleJSEntityRedirect(deletedId: string) { const basePageId: string = yield select(getCurrentBasePageId); const jsTabs: EntityItem[] = yield select(selectJSSegmentEditorTabs); @@ -108,70 +105,6 @@ export function* handleQueryEntityRedirect(deletedId: string) { } } -/** - * Adds custom redirect logic to redirect after an item is deleted - * 1. Do not navigate if the deleted item is not selected - * 2. If it was the only item, navigate to the list url, to show the blank state - * 3. If there are other items, navigate to an item close to the current one - * **/ - -export enum RedirectAction { - NA = "NA", // No action is needed - LIST = "LIST", // Navigate to a creation URL - ITEM = "ITEM", // Navigate to this item -} - -interface RedirectActionDescription { - action: RedirectAction; - payload?: EntityItem; -} - -export function getNextEntityAfterRemove( - removedId: string, - tabs: EntityItem[], -): RedirectActionDescription { - const currentSelectedEntity = identifyEntityFromPath( - window.location.pathname, - ); - const isSelectedActionRemoved = currentSelectedEntity.id === removedId; - - // If removed item is not currently selected, don't redirect - if (!isSelectedActionRemoved) { - return { - action: RedirectAction.NA, - }; - } - - const indexOfTab = tabs.findIndex((item) => item.key === removedId); - - switch (indexOfTab) { - case -1: - // If no other action is remaining, navigate to the creation url - return { - action: RedirectAction.LIST, - }; - case 0: - // if the removed item is first item, then if tabs present, tabs + 1 - // else otherItems[0] -> TODO: consider changing this logic after discussion with - // design team. May be new listing UI for side by side - if (tabs.length > 1) { - return { - action: RedirectAction.ITEM, - payload: tabs[1], - }; - } else { - return { - action: RedirectAction.LIST, - }; - } - default: - return { - action: RedirectAction.ITEM, - payload: tabs[indexOfTab - 1], - }; - } -} - function* storeIDEViewChangeSaga( action: ReduxAction<{ view: EditorViewMode }>, ) {
d22b63277daed16ad1f69baf2e5c24bb25db2dc5
2024-02-09 10:00:04
Jacques Ikot
feat: starter building blocks for all users (#30909)
false
starter building blocks for all users (#30909)
feat
diff --git a/app/client/cypress/e2e/Regression/ClientSide/Templates/BuildingBlocks/StarterBuildingBlocksOnCanvas_spec.ts b/app/client/cypress/e2e/Regression/ClientSide/Templates/BuildingBlocks/StarterBuildingBlocksOnCanvas_spec.ts new file mode 100644 index 000000000000..ec8c9cb68757 --- /dev/null +++ b/app/client/cypress/e2e/Regression/ClientSide/Templates/BuildingBlocks/StarterBuildingBlocksOnCanvas_spec.ts @@ -0,0 +1,68 @@ +import template from "../../../../../locators/TemplatesLocators.json"; +import { featureFlagIntercept } from "../../../../../support/Objects/FeatureFlags"; +import { + agHelper, + dataSources, + onboarding, + templates, +} from "../../../../../support/Objects/ObjectsCore"; +import { + AppSidebar, + AppSidebarButton, +} from "../../../../../support/Pages/EditorNavigation"; +import PageList from "../../../../../support/Pages/PageList"; + +describe( + "Starter building blocks on canvas", + { tags: ["@tag.excludeForAirgap", "@tag.Templates"] }, + function () { + beforeEach(() => { + PageList.AddNewPage("New blank page"); + featureFlagIntercept({ + ab_show_templates_instead_of_blank_canvas_enabled: true, + }); + }); + + it("1. `Connect your data` pop up should come up when we fork a building block from canvas.", function () { + agHelper.GetNClick(templates.locators._buildingBlockCardOnCanvas); + + agHelper.WaitUntilEleDisappear("Importing template"); + agHelper.AssertElementVisibility( + templates.locators._datasourceConnectPromptSubmitBtn, + ); + agHelper.GetNClick(templates.locators._datasourceConnectPromptSubmitBtn); + cy.url().should("include", "datasources/NEW"); + }); + + it("2. `See more` functionality should filter `Building blocks` in add a page from templates modal", function () { + agHelper.GetNClick(onboarding.locators.seeMoreButtonOnCanvas, 0, true); + + agHelper.AssertElementVisibility(template.templateDialogBox); + + const filterItemWrapper = agHelper.GetElement(".filter-wrapper"); + + const templateFilterItemSelectedIcon = filterItemWrapper.find( + templates.locators._templateFilterItemSelectedIcon, + ); + templateFilterItemSelectedIcon.should("have.length", 1); + templateFilterItemSelectedIcon + .first() + .prev() + .should("have.text", "Building Blocks"); + }); + + it("3. `Connect your data` pop up should NOT come up when user already has a datasource.", function () { + dataSources.CreateMockDB("Users"); + AppSidebar.navigate(AppSidebarButton.Editor); + + agHelper.GetNClick(templates.locators._buildingBlockCardOnCanvas, 0); + + agHelper.WaitUntilEleDisappear("Importing template"); + + agHelper.AssertElementAbsence( + templates.locators._datasourceConnectPromptSubmitBtn, + 4000, + ); + }); + }, +); diff --git a/app/client/src/ce/utils/signupHelpers.ts b/app/client/src/ce/utils/signupHelpers.ts index 6204f3f83c23..f06437b01c95 100644 --- a/app/client/src/ce/utils/signupHelpers.ts +++ b/app/client/src/ce/utils/signupHelpers.ts @@ -14,14 +14,12 @@ import { error } from "loglevel"; import { matchPath } from "react-router"; import { getIsSafeRedirectURL } from "utils/helpers"; import history from "utils/history"; -import { setUsersFirstApplicationId } from "utils/storage"; export const redirectUserAfterSignup = ( redirectUrl: string, shouldEnableFirstTimeUserOnboarding: string | null, _validLicense?: boolean, dispatch?: any, - showStarterTemplatesInsteadofBlankCanvas: boolean = false, isEnabledForCreateNew?: boolean, ): any => { if (redirectUrl) { @@ -49,9 +47,6 @@ export const redirectUserAfterSignup = ( }); const { applicationId, pageId } = match?.params || {}; if (applicationId || pageId) { - showStarterTemplatesInsteadofBlankCanvas && - applicationId && - setUsersFirstApplicationId(applicationId); if (isEnabledForCreateNew) { dispatch( setCurrentApplicationIdForCreateNewApp(applicationId as string), diff --git a/app/client/src/layoutSystems/common/dropTarget/DropTargetComponent.tsx b/app/client/src/layoutSystems/common/dropTarget/DropTargetComponent.tsx index 131dba27eb80..41b63f7c8e2e 100644 --- a/app/client/src/layoutSystems/common/dropTarget/DropTargetComponent.tsx +++ b/app/client/src/layoutSystems/common/dropTarget/DropTargetComponent.tsx @@ -11,7 +11,6 @@ import React, { useEffect, useMemo, useRef, - useState, } from "react"; import { useSelector } from "react-redux"; import styled from "styled-components"; @@ -33,14 +32,12 @@ import { useShowPropertyPane } from "utils/hooks/dragResizeHooks"; import { useWidgetSelection } from "utils/hooks/useWidgetSelection"; import { calculateDropTargetRows } from "./DropTargetUtils"; +import { EditorState as IDEAppState } from "@appsmith/entities/IDE/constants"; +import { isAirgapped } from "@appsmith/utils/airgapHelpers"; import { LayoutSystemTypes } from "layoutSystems/types"; +import { useCurrentAppState } from "pages/Editor/IDE/hooks"; import { getIsAppSettingsPaneWithNavigationTabOpen } from "selectors/appSettingsPaneSelectors"; import { getLayoutSystemType } from "selectors/layoutSystemSelectors"; -import { getCurrentUser } from "selectors/usersSelectors"; -import { - getUsersFirstApplicationId, - isUserSignedUpFlagSet, -} from "utils/storage"; import { isAutoHeightEnabledForWidget, isAutoHeightEnabledForWidgetWithLimits, @@ -49,9 +46,6 @@ import DragLayerComponent from "./DragLayerComponent"; import StarterBuildingBlocks from "./starterBuildingBlocks"; import { useFeatureFlag } from "utils/hooks/useFeatureFlag"; import { FEATURE_FLAG } from "@appsmith/entities/FeatureFlag"; -import { useCurrentAppState } from "pages/Editor/IDE/hooks"; -import { EditorState as IDEAppState } from "@appsmith/entities/IDE/constants"; -import { isAirgapped } from "@appsmith/utils/airgapHelpers"; export type DropTargetComponentProps = PropsWithChildren<{ snapColumnSpace: number; @@ -76,40 +70,21 @@ const StyledDropTarget = styled.div` `; function Onboarding() { - const [isUsersFirstApp, setIsUsersFirstApp] = useState(false); const isMobileCanvas = useSelector(getIsMobileCanvasLayout); const appState = useCurrentAppState(); - const user = useSelector(getCurrentUser); - const showStarterTemplatesInsteadofBlankCanvas = useFeatureFlag( - FEATURE_FLAG.ab_show_templates_instead_of_blank_canvas_enabled, - ); const isAirgappedInstance = isAirgapped(); - const currentApplicationId = useSelector( - (state: AppState) => state.ui.applications.currentApplication?.id, + const showStarterTemplatesInsteadofBlankCanvas = useFeatureFlag( + FEATURE_FLAG.ab_show_templates_instead_of_blank_canvas_enabled, ); const shouldShowStarterTemplates = useMemo( () => showStarterTemplatesInsteadofBlankCanvas && !isMobileCanvas && - isUsersFirstApp && !isAirgappedInstance, - [ - isMobileCanvas, - isUsersFirstApp, - showStarterTemplatesInsteadofBlankCanvas, - isAirgappedInstance, - ], + [isMobileCanvas, isAirgappedInstance], ); - useEffect(() => { - (async () => { - const firstApplicationId = await getUsersFirstApplicationId(); - const isNew = !!user && (await isUserSignedUpFlagSet(user.email)); - const isFirstApp = firstApplicationId === currentApplicationId; - setIsUsersFirstApp(isNew && isFirstApp); - })(); - }, [user, currentApplicationId]); if (shouldShowStarterTemplates && appState === IDEAppState.EDITOR) return <StarterBuildingBlocks />; diff --git a/app/client/src/pages/setup/SignupSuccess.tsx b/app/client/src/pages/setup/SignupSuccess.tsx index 9ebd5e8af42e..9d3cd9bc74f4 100644 --- a/app/client/src/pages/setup/SignupSuccess.tsx +++ b/app/client/src/pages/setup/SignupSuccess.tsx @@ -27,9 +27,6 @@ export function SignupSuccess() { ); const validLicense = useSelector(isValidLicense); const user = useSelector(getCurrentUser); - const showStarterTemplatesInsteadofBlankCanvas = useFeatureFlag( - FEATURE_FLAG.ab_show_templates_instead_of_blank_canvas_enabled, - ); const isEnabledForCreateNew = useFeatureFlag( FEATURE_FLAG.ab_create_new_apps_enabled, ); @@ -48,7 +45,6 @@ export function SignupSuccess() { shouldEnableFirstTimeUserOnboarding, validLicense, dispatch, - showStarterTemplatesInsteadofBlankCanvas, isNonInvitedUser && isEnabledForCreateNew, ), [], diff --git a/app/client/src/utils/storage.ts b/app/client/src/utils/storage.ts index 291e503fa20c..3cd12ad82b5c 100644 --- a/app/client/src/utils/storage.ts +++ b/app/client/src/utils/storage.ts @@ -856,25 +856,3 @@ export const getPartnerProgramCalloutShown = async () => { log.error(error); } }; - -export const setUsersFirstApplicationId = async (appId: string) => { - try { - await store.setItem(STORAGE_KEYS.USERS_FIRST_APPLICATION_ID, appId); - return true; - } catch (error) { - log.error("An error occurred while setting USERS_FIRST_APPLICATION_ID"); - log.error(error); - } -}; - -export const getUsersFirstApplicationId = async () => { - try { - const firstApplicationId: string | null = await store.getItem( - STORAGE_KEYS.USERS_FIRST_APPLICATION_ID, - ); - return firstApplicationId; - } catch (error) { - log.error("An error occurred while fetching USERS_FIRST_APPLICATION_ID"); - log.error(error); - } -};
7a2d8d84f35358f32c256adc038594be8dc736be
2023-11-08 14:35:52
Hetu Nandu
feat: Show generate page on Datasource Page (#28686)
false
Show generate page on Datasource Page (#28686)
feat
diff --git a/app/client/src/pages/Editor/DataSourceEditor/DSFormHeader.tsx b/app/client/src/pages/Editor/DataSourceEditor/DSFormHeader.tsx index ae25a0594d5a..101d2089ac6f 100644 --- a/app/client/src/pages/Editor/DataSourceEditor/DSFormHeader.tsx +++ b/app/client/src/pages/Editor/DataSourceEditor/DSFormHeader.tsx @@ -9,9 +9,10 @@ import { CONTEXT_DELETE, EDIT, createMessage, + GENERATE_NEW_PAGE_BUTTON_TEXT, } from "@appsmith/constants/messages"; import AnalyticsUtil from "utils/AnalyticsUtil"; -import { useDispatch } from "react-redux"; +import { useDispatch, useSelector } from "react-redux"; import { deleteDatasource } from "actions/datasourceActions"; import { debounce } from "lodash"; import type { ApiDatasourceForm } from "entities/Datasource/RestAPIForm"; @@ -19,6 +20,10 @@ import { MenuWrapper, StyledMenu } from "components/utils/formComponents"; import styled from "styled-components"; import { Button, MenuContent, MenuItem, MenuTrigger } from "design-system"; import { DatasourceEditEntryPoints } from "constants/Datasource"; +import { useShowPageGenerationOnHeader } from "./hooks"; +import { generateTemplateFormURL } from "@appsmith/RouteBuilder"; +import { getCurrentPageId } from "selectors/editorSelectors"; +import history from "utils/history"; export const ActionWrapper = styled.div` display: flex; @@ -108,6 +113,8 @@ export const DSFormHeader = (props: DSFormHeaderProps) => { const [confirmDelete, setConfirmDelete] = useState(false); const dispatch = useDispatch(); + const pageId = useSelector(getCurrentPageId); + const deleteAction = () => { if (isDeleting) return; AnalyticsUtil.logEvent("DATASOURCE_CARD_DELETE_ACTION"); @@ -116,6 +123,10 @@ export const DSFormHeader = (props: DSFormHeaderProps) => { const onCloseMenu = debounce(() => setConfirmDelete(false), 20); + const showGenerateButton = useShowPageGenerationOnHeader( + datasource as Datasource, + ); + const renderMenuOptions = () => { return [ <MenuItem @@ -142,6 +153,23 @@ export const DSFormHeader = (props: DSFormHeaderProps) => { ]; }; + const routeToGeneratePage = () => { + if (!showGenerateButton) { + // disable button when it doesn't support page generation + return; + } + AnalyticsUtil.logEvent("DATASOURCE_CARD_GEN_CRUD_PAGE_ACTION"); + history.push( + generateTemplateFormURL({ + pageId, + params: { + datasourceId: (datasource as Datasource).id, + new_page: true, + }, + }), + ); + }; + return ( <Header noBottomBorder={!!noBottomBorder}> <FormTitleContainer> @@ -200,6 +228,20 @@ export const DSFormHeader = (props: DSFormHeaderProps) => { eventFrom="datasource-pane" pluginType={pluginType} /> + {showGenerateButton && ( + <Button + className={"t--generate-template"} + kind="secondary" + onClick={(e: any) => { + e.stopPropagation(); + e.preventDefault(); + routeToGeneratePage(); + }} + size="md" + > + {createMessage(GENERATE_NEW_PAGE_BUTTON_TEXT)} + </Button> + )} </ActionWrapper> )} </Header> diff --git a/app/client/src/pages/Editor/DataSourceEditor/hooks.ts b/app/client/src/pages/Editor/DataSourceEditor/hooks.ts index 2a9d2ddb9c55..4deddac24437 100644 --- a/app/client/src/pages/Editor/DataSourceEditor/hooks.ts +++ b/app/client/src/pages/Editor/DataSourceEditor/hooks.ts @@ -1,8 +1,28 @@ import { executeDatasourceQuery } from "actions/datasourceActions"; -import type { QueryTemplate } from "entities/Datasource"; +import type { Datasource, QueryTemplate } from "entities/Datasource"; import { useState, useCallback } from "react"; -import { useDispatch } from "react-redux"; import AnalyticsUtil from "utils/AnalyticsUtil"; +import { useDispatch, useSelector } from "react-redux"; +import { useFeatureFlag } from "utils/hooks/useFeatureFlag"; +import { PluginName } from "entities/Action"; +import { isGoogleSheetPluginDS } from "utils/editorContextUtils"; +import { + getHasCreatePagePermission, + hasCreateDSActionPermissionInApp, +} from "@appsmith/utils/BusinessFeatures/permissionPageHelpers"; +import type { GenerateCRUDEnabledPluginMap } from "api/PluginApi"; +import { DATASOURCES_ALLOWED_FOR_PREVIEW_MODE } from "constants/QueryEditorConstants"; +import { + getGenerateCRUDEnabledPluginMap, + getPlugin, +} from "@appsmith/selectors/entitiesSelector"; +import { FEATURE_FLAG } from "@appsmith/entities/FeatureFlag"; +import type { AppState } from "@appsmith/reducers"; +import { + getCurrentApplication, + getPagePermissions, +} from "selectors/editorSelectors"; +import { get } from "lodash"; interface FetchPreviewData { datasourceId: string; @@ -83,3 +103,64 @@ export const useDatasourceQuery = ({ failedFetchingPreviewData, }; }; + +export const useShowPageGenerationOnHeader = ( + datasource: Datasource, +): boolean => { + const pluginId = get(datasource, "pluginId", ""); + const plugin = useSelector((state: AppState) => getPlugin(state, pluginId)); + const userAppPermissions = useSelector( + (state: AppState) => getCurrentApplication(state)?.userPermissions ?? [], + ); + + const pagePermissions = useSelector(getPagePermissions); + + const datasourcePermissions = datasource?.userPermissions || []; + + const isGACEnabled = useFeatureFlag(FEATURE_FLAG.license_gac_enabled); + + const isGoogleSheetPlugin = isGoogleSheetPluginDS(plugin?.packageName); + + // A/B feature flag for datasource view mode preview data. + let isEnabledForDSViewModeSchema = useFeatureFlag( + FEATURE_FLAG.ab_gsheet_schema_enabled, + ); + + const isEnabledForMockMongoSchema = useFeatureFlag( + FEATURE_FLAG.ab_mock_mongo_schema_enabled, + ); + + // for mongoDB, the feature flag should be based on ab_mock_mongo_schema_enabled. + if (plugin?.name === PluginName.MONGO) { + isEnabledForDSViewModeSchema = isEnabledForMockMongoSchema; + } + + const isPluginAllowedToPreviewData = isEnabledForDSViewModeSchema + ? DATASOURCES_ALLOWED_FOR_PREVIEW_MODE.includes(plugin?.name || "") || + (plugin?.name === PluginName.MONGO && + !!(datasource as Datasource)?.isMock) || + isGoogleSheetPlugin + : false; + + const generateCRUDSupportedPlugin: GenerateCRUDEnabledPluginMap = useSelector( + getGenerateCRUDEnabledPluginMap, + ); + + const canCreatePages = getHasCreatePagePermission( + isGACEnabled, + userAppPermissions, + ); + const canCreateDatasourceActions = hasCreateDSActionPermissionInApp( + isGACEnabled, + datasourcePermissions, + pagePermissions, + ); + + const canGeneratePage = canCreateDatasourceActions && canCreatePages; + + const supportTemplateGeneration = + !isPluginAllowedToPreviewData && + !!generateCRUDSupportedPlugin[(datasource as Datasource).pluginId]; + + return supportTemplateGeneration && canGeneratePage; +};
420dc9b4c442a70c7616622086a6617ca87a6f76
2024-09-04 12:35:23
Saicharan Pabbathi
fix: fixed back button to redirect to applications page (#35900)
false
fixed back button to redirect to applications page (#35900)
fix
diff --git a/app/client/src/pages/UserProfile/index.test.tsx b/app/client/src/pages/UserProfile/index.test.tsx index f9e6ffe3653d..aa57ee2d919a 100644 --- a/app/client/src/pages/UserProfile/index.test.tsx +++ b/app/client/src/pages/UserProfile/index.test.tsx @@ -1,6 +1,6 @@ import "@testing-library/jest-dom/extend-expect"; import React from "react"; -import { render } from "@testing-library/react"; +import { render, screen, fireEvent } from "@testing-library/react"; import { Provider } from "react-redux"; import configureStore from "redux-mock-store"; import { lightTheme } from "selectors/themeSelectors"; @@ -87,6 +87,15 @@ jest.mock("actions/gitSyncActions", () => ({ fetchGlobalGitConfigInit: jest.fn(), })); +const mockHistoryPush = jest.fn(); + +jest.mock("react-router-dom", () => ({ + ...jest.requireActual("react-router-dom"), + useHistory: () => ({ + push: mockHistoryPush, + }), +})); + const mockStore = configureStore([]); describe("Git config ", () => { // TODO: Fix this the next time the file is edited @@ -128,6 +137,22 @@ describe("Git config ", () => { expect(getAllByText("Sign in to your account")).toBeInTheDocument; }); + it("should call history push when user goes back to applications", () => { + store = mockStore(defaultStoreState); + render( + <Provider store={store}> + <ThemeProvider theme={lightTheme}> + <Router> + <UserProfile /> + </Router> + </ThemeProvider> + </Provider>, + ); + const backButton = screen.getByText("Back"); + fireEvent.click(backButton); + expect(mockHistoryPush).toHaveBeenCalledWith("/applications"); + }); + afterAll(() => { jest.clearAllMocks(); store.clearActions(); diff --git a/app/client/src/pages/UserProfile/index.tsx b/app/client/src/pages/UserProfile/index.tsx index 2cfb2fee9fb3..bf7de701ef78 100644 --- a/app/client/src/pages/UserProfile/index.tsx +++ b/app/client/src/pages/UserProfile/index.tsx @@ -56,7 +56,7 @@ function UserProfile() { return ( <PageWrapper displayName={"Profile"}> <ProfileWrapper> - <BackButton /> + <BackButton goTo="/applications" /> <Tabs defaultValue={selectedTab} onValueChange={setSelectedTab}> <TabsList> {tabs.map((tab) => { diff --git a/app/client/src/pages/workspace/__tests__/settings.test.tsx b/app/client/src/pages/workspace/__tests__/settings.test.tsx index fdcbea9eb15e..3e488f3fb4c4 100644 --- a/app/client/src/pages/workspace/__tests__/settings.test.tsx +++ b/app/client/src/pages/workspace/__tests__/settings.test.tsx @@ -1,9 +1,17 @@ import React from "react"; import "@testing-library/jest-dom"; import Router from "react-router-dom"; +import { BrowserRouter } from "react-router-dom"; import { render, screen } from "test/testUtils"; +import { + render as testRender, + screen as testScreen, +} from "@testing-library/react"; +import { fireEvent } from "@testing-library/react"; import Settings from "../settings"; import * as reactRedux from "react-redux"; +import configureStore from "redux-mock-store"; +import { Provider } from "react-redux"; // TODO: Fix this the next time the file is edited // eslint-disable-next-line @typescript-eslint/no-explicit-any @@ -151,9 +159,16 @@ const mockWorkspaceData = { new: false, }; +const mockHistoryPush = jest.fn(); + +const mockStore = configureStore([]); + jest.mock("react-router-dom", () => ({ ...jest.requireActual("react-router-dom"), useParams: jest.fn(), + useHistory: () => ({ + push: mockHistoryPush, + }), })); function renderComponent() { @@ -190,4 +205,19 @@ describe("<Settings />", () => { expect(tabList.length).toBeGreaterThanOrEqual(2); expect(tabList.length).toBeLessThanOrEqual(3); }); + + it("should redirect to workspace page if user wants to go back", () => { + testRender( + <BrowserRouter> + <Provider store={mockStore(mockWorkspaceData)}> + <Settings /> + </Provider> + </BrowserRouter>, + ); + const backBtn = testScreen.getByText("Back"); + fireEvent.click(backBtn); + expect(mockHistoryPush).toHaveBeenCalledWith( + `/applications?workspaceId=${mockWorkspaceData.id}`, + ); + }); }); diff --git a/app/client/src/pages/workspace/settings.tsx b/app/client/src/pages/workspace/settings.tsx index 0d4567c9325d..1c5ab878d554 100644 --- a/app/client/src/pages/workspace/settings.tsx +++ b/app/client/src/pages/workspace/settings.tsx @@ -127,7 +127,7 @@ export default function Settings() { <> <SettingsWrapper data-testid="t--settings-wrapper" isMobile={isMobile}> <StyledStickyHeader isMobile={isMobile}> - <BackButton /> + <BackButton goTo={`/applications?workspaceId=${workspaceId}`} /> <SettingsPageHeader buttonText="Add users" onButtonClick={onButtonClick}
6c58b40d0e231660bf28a269421f7709817ef256
2024-03-28 15:57:50
Vemparala Surya Vamsi
chore: Capture telemetry around diff and serialise operation (#32124)
false
Capture telemetry around diff and serialise operation (#32124)
chore
diff --git a/app/client/src/workers/Evaluation/handlers/evalTree.ts b/app/client/src/workers/Evaluation/handlers/evalTree.ts index 53651e3e15d4..de653f969640 100644 --- a/app/client/src/workers/Evaluation/handlers/evalTree.ts +++ b/app/client/src/workers/Evaluation/handlers/evalTree.ts @@ -239,32 +239,40 @@ export function evalTree(request: EvalWorkerSyncRequest) { const jsVarsCreatedEvent = getJSVariableCreatedEvents(jsUpdates); - let updates; - if (isNewTree) { - try { - //for new tree send the whole thing, don't diff at all - updates = serialiseToBigInt([{ kind: "newTree", rhs: dataTree }]); - dataTreeEvaluator?.setPrevState(dataTree); - } catch (e) { - updates = "[]"; - } - isNewTree = false; - } else { - const allUnevalUpdates = unEvalUpdates.map( - (update) => update.payload.propertyPath, - ); + const updates = profileFn( + "diffAndGenerateSerializeUpdates", + undefined, + webworkerTelemetry, + () => { + let updates; + if (isNewTree) { + try { + //for new tree send the whole thing, don't diff at all + updates = serialiseToBigInt([{ kind: "newTree", rhs: dataTree }]); + dataTreeEvaluator?.setPrevState(dataTree); + } catch (e) { + updates = "[]"; + } + isNewTree = false; + } else { + const allUnevalUpdates = unEvalUpdates.map( + (update) => update.payload.propertyPath, + ); - const completeEvalOrder = uniqueOrderUpdatePaths([ - ...allUnevalUpdates, - ...evalOrder, - ]); + const completeEvalOrder = uniqueOrderUpdatePaths([ + ...allUnevalUpdates, + ...evalOrder, + ]); - updates = generateOptimisedUpdatesAndSetPrevState( - dataTree, - dataTreeEvaluator, - completeEvalOrder, - ); - } + updates = generateOptimisedUpdatesAndSetPrevState( + dataTree, + dataTreeEvaluator, + completeEvalOrder, + ); + } + return updates; + }, + ); const evalTreeResponse: EvalTreeResponseData = { updates,
78ce45a190dc3af8d31bf224157c893849367a49
2022-06-02 11:47:13
Abhijeet
chore: Remove client subscription for delete branch (#14152)
false
Remove client subscription for delete branch (#14152)
chore
diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/GitServiceCEImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/GitServiceCEImpl.java index 2a3495b724d4..ee737e296506 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 @@ -2077,7 +2077,7 @@ public Mono<Boolean> testConnection(String defaultApplicationId) { @Override public Mono<Application> deleteBranch(String defaultApplicationId, String branchName) { - return getApplicationById(defaultApplicationId) + Mono<Application> deleteBranchMono = getApplicationById(defaultApplicationId) .flatMap(application -> { GitApplicationMetadata gitApplicationMetadata = application.getGitApplicationMetadata(); Path repoPath = Paths.get(application.getOrganizationId(), defaultApplicationId, gitApplicationMetadata.getRepoName()); @@ -2117,6 +2117,10 @@ public Mono<Application> deleteBranch(String defaultApplicationId, String branch }) .flatMap(application -> addAnalyticsForGitOperation(AnalyticsEvents.GIT_DELETE_BRANCH.getEventName(), application, application.getGitApplicationMetadata().getIsRepoPrivate())) .map(responseUtils::updateApplicationWithDefaultResources); + + return Mono.create(sink -> deleteBranchMono + .subscribe(sink::success, sink::error, null, sink.currentContext()) + ); } @Override 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 f014d43adb81..8eaf16f2802c 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 @@ -20,8 +20,8 @@ import com.appsmith.server.domains.Layout; import com.appsmith.server.domains.NewAction; import com.appsmith.server.domains.NewPage; -import com.appsmith.server.domains.Workspace; import com.appsmith.server.domains.PluginType; +import com.appsmith.server.domains.Workspace; import com.appsmith.server.dtos.ActionCollectionDTO; import com.appsmith.server.dtos.ActionDTO; import com.appsmith.server.dtos.ApplicationImportDTO; @@ -38,8 +38,8 @@ import com.appsmith.server.helpers.MockPluginExecutor; import com.appsmith.server.helpers.PluginExecutorHelper; import com.appsmith.server.migrations.JsonSchemaVersions; -import com.appsmith.server.repositories.WorkspaceRepository; import com.appsmith.server.repositories.PluginRepository; +import com.appsmith.server.repositories.WorkspaceRepository; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; @@ -82,9 +82,12 @@ import java.time.Instant; import java.util.ArrayList; import java.util.HashMap; +import java.util.HashSet; import java.util.List; import java.util.Map; +import java.util.Set; +import static com.appsmith.server.acl.AclPermission.MANAGE_APPLICATIONS; import static com.appsmith.server.acl.AclPermission.READ_ACTIONS; import static com.appsmith.server.acl.AclPermission.READ_APPLICATIONS; import static com.appsmith.server.acl.AclPermission.READ_PAGES; @@ -2741,4 +2744,50 @@ public void discardChanges_cancelledMidway_discardSuccess() throws IOException, }) .verifyComplete(); } + + @Test + @WithUserDetails(value = "api_user") + public void deleteBranch_cancelledMidway_success() throws GitAPIException, IOException { + + final String DEFAULT_BRANCH = "master", TO_BE_DELETED_BRANCH = "deleteBranch"; + Application application = createApplicationConnectedToGit("deleteBranch_defaultBranchUpdated_Success", DEFAULT_BRANCH); + application.getGitApplicationMetadata().setDefaultBranchName(DEFAULT_BRANCH); + applicationService.save(application).block(); + + Application branchApp = createApplicationConnectedToGit("deleteBranch_defaultBranchUpdated_Success2", TO_BE_DELETED_BRANCH); + branchApp.getGitApplicationMetadata().setDefaultBranchName(DEFAULT_BRANCH); + branchApp.getGitApplicationMetadata().setDefaultApplicationId(application.getId()); + applicationService.save(branchApp).block(); + + Mockito.when(gitExecutor.deleteBranch(Mockito.any(Path.class), Mockito.anyString())) + .thenReturn(Mono.just(true)); + + gitService + .deleteBranch(application.getId(), TO_BE_DELETED_BRANCH) + .timeout(Duration.ofMillis(5)) + .subscribe(); + + // Wait for git delete branch to complete + Mono<List<Application>> applicationsFromDbMono = Mono.just(application) + .flatMapMany(DBApplication -> { + try { + // Before fetching the git connected application, sleep for 5 seconds to ensure that the delete + // completes + Thread.sleep(5000); + } catch (InterruptedException e) { + e.printStackTrace(); + } + return applicationService.findAllApplicationsByDefaultApplicationId(DBApplication.getId(), MANAGE_APPLICATIONS); + }) + .collectList(); + + StepVerifier + .create(applicationsFromDbMono) + .assertNext(applicationList -> { + Set<String> branchNames = new HashSet<>(); + applicationList.forEach(application1 -> branchNames.add(application1.getGitApplicationMetadata().getBranchName())); + assertThat(branchNames).doesNotContain(TO_BE_DELETED_BRANCH); + }) + .verifyComplete(); + } } \ No newline at end of file
0e54c57ead3c810119a2ee57992d020535e5b17e
2023-04-28 17:43:54
Sumit Kumar
feat: Oracle integration: Add support for DB schema and update error infra (#22634)
false
Oracle integration: Add support for DB schema and update error infra (#22634)
feat
diff --git a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/helpers/PluginUtils.java b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/helpers/PluginUtils.java index 4b034fdb9d3e..f71fb122aea3 100644 --- a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/helpers/PluginUtils.java +++ b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/helpers/PluginUtils.java @@ -11,13 +11,14 @@ import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import lombok.extern.slf4j.Slf4j; -import org.json.JSONObject; import org.json.JSONException; +import org.json.JSONObject; import org.springframework.util.CollectionUtils; import org.springframework.util.StringUtils; import java.io.IOException; import java.lang.reflect.Type; +import java.sql.Connection; import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.util.ArrayList; @@ -452,4 +453,15 @@ public static String replaceMappedColumnInStringValue(Map<String, String> mapped return propertyValue.toString(); } + + public static void safelyCloseSingleConnectionFromHikariCP(Connection connection, String logOnError) { + if (connection != null) { + try { + // Return the connection back to the pool + connection.close(); + } catch (SQLException e) { + log.debug(logOnError, e); + } + } + } } diff --git a/app/server/appsmith-plugins/oraclePlugin/pom.xml b/app/server/appsmith-plugins/oraclePlugin/pom.xml index fe667fbae682..31a388ac530f 100755 --- a/app/server/appsmith-plugins/oraclePlugin/pom.xml +++ b/app/server/appsmith-plugins/oraclePlugin/pom.xml @@ -23,33 +23,19 @@ </properties> <dependencies> - <dependency> - <groupId>org.pf4j</groupId> - <artifactId>pf4j-spring</artifactId> - <version>0.8.0</version> - <scope>provided</scope> + <dependency> + <groupId>com.zaxxer</groupId> + <artifactId>HikariCP</artifactId> + <version>5.0.1</version> <exclusions> <exclusion> - <artifactId>slf4j-reload4j</artifactId> <groupId>org.slf4j</groupId> + <artifactId>slf4j-api</artifactId> </exclusion> </exclusions> - </dependency> + </dependency> - <dependency> - <groupId>com.appsmith</groupId> - <artifactId>interfaces</artifactId> - <version>1.0-SNAPSHOT</version> - <scope>provided</scope> - </dependency> - - <dependency> - <groupId>org.projectlombok</groupId> - <artifactId>lombok</artifactId> - <version>1.18.22</version> - <scope>provided</scope> - </dependency> - <!-- Test Dependencies --> + <!-- Test Dependencies --> <!-- https://mvnrepository.com/artifact/com.oracle.database.jdbc/ojdbc8 --> <dependency> <groupId>com.oracle.database.jdbc</groupId> @@ -67,17 +53,6 @@ <artifactId>jdbc-test</artifactId> <version>1.11.4</version> </dependency> - <dependency> - <groupId>com.zaxxer</groupId> - <artifactId>HikariCP</artifactId> - <version>5.0.1</version> - <exclusions> - <exclusion> - <groupId>org.slf4j</groupId> - <artifactId>slf4j-api</artifactId> - </exclusion> - </exclusions> - </dependency> </dependencies> <build> diff --git a/app/server/appsmith-plugins/oraclePlugin/src/main/java/com/external/plugins/OraclePlugin.java b/app/server/appsmith-plugins/oraclePlugin/src/main/java/com/external/plugins/OraclePlugin.java index e0558904bc9d..07442ed7642a 100644 --- a/app/server/appsmith-plugins/oraclePlugin/src/main/java/com/external/plugins/OraclePlugin.java +++ b/app/server/appsmith-plugins/oraclePlugin/src/main/java/com/external/plugins/OraclePlugin.java @@ -19,13 +19,12 @@ import com.appsmith.external.plugins.BasePlugin; import com.appsmith.external.plugins.PluginExecutor; import com.appsmith.external.plugins.SmartSubstitutionInterface; +import com.external.plugins.exceptions.OracleErrorMessages; +import com.external.plugins.exceptions.OraclePluginError; import com.external.plugins.utils.OracleDatasourceUtils; import com.external.plugins.utils.OracleSpecificDataTypes; import com.zaxxer.hikari.HikariDataSource; -import com.zaxxer.hikari.HikariPoolMXBean; -import com.zaxxer.hikari.pool.HikariProxyConnection; import lombok.extern.slf4j.Slf4j; -import oracle.jdbc.OraclePreparedStatement; import org.apache.commons.io.IOUtils; import org.pf4j.Extension; import org.pf4j.PluginWrapper; @@ -45,7 +44,7 @@ import java.sql.Time; import java.sql.Timestamp; import java.sql.Types; -import java.time.Duration; +import java.text.MessageFormat; import java.util.AbstractMap; import java.util.ArrayList; import java.util.HashMap; @@ -69,13 +68,14 @@ import static com.external.plugins.utils.OracleDatasourceUtils.JDBC_DRIVER; import static com.external.plugins.utils.OracleDatasourceUtils.createConnectionPool; import static com.external.plugins.utils.OracleDatasourceUtils.getConnectionFromConnectionPool; +import static com.external.plugins.utils.OracleDatasourceUtils.logHikariCPStatus; import static com.external.plugins.utils.OracleExecuteUtils.closeConnectionPostExecution; import static com.external.plugins.utils.OracleExecuteUtils.isPLSQL; import static com.external.plugins.utils.OracleExecuteUtils.populateRowsAndColumns; import static com.external.plugins.utils.OracleExecuteUtils.removeSemicolonFromQuery; import static java.lang.Boolean.FALSE; import static java.lang.Boolean.TRUE; -import static org.apache.commons.lang3.StringUtils.isEmpty; +import static org.apache.commons.lang3.StringUtils.isBlank; @Slf4j public class OraclePlugin extends BasePlugin { @@ -85,14 +85,15 @@ public OraclePlugin(PluginWrapper wrapper) { } @Extension public static class OraclePluginExecutor implements SmartSubstitutionInterface, PluginExecutor<HikariDataSource> { - private final Scheduler scheduler = Schedulers.boundedElastic(); + public static final Scheduler scheduler = Schedulers.boundedElastic(); @Override public Mono<HikariDataSource> datasourceCreate(DatasourceConfiguration datasourceConfiguration) { try { Class.forName(JDBC_DRIVER); } catch (ClassNotFoundException e) { - return Mono.error(new AppsmithPluginException(AppsmithPluginError.PLUGIN_ERROR, "Error loading Oracle JDBC Driver class.")); + return Mono.error(new AppsmithPluginException(OraclePluginError.ORACLE_PLUGIN_ERROR, + OracleErrorMessages.ORACLE_JDBC_DRIVER_LOADING_ERROR_MSG, e.getMessage())); } return Mono @@ -115,7 +116,8 @@ public Set<String> validateDatasource(DatasourceConfiguration datasourceConfigur @Override public Mono<ActionExecutionResult> execute(HikariDataSource connection, DatasourceConfiguration datasourceConfiguration, ActionConfiguration actionConfiguration) { - return Mono.error(new AppsmithPluginException(AppsmithPluginError.PLUGIN_ERROR, "Unsupported Operation")); + return Mono.error( + new AppsmithPluginException(OraclePluginError.QUERY_EXECUTION_FAILED, "Unsupported Operation")); } @Override @@ -123,10 +125,9 @@ public Mono<ActionExecutionResult> executeParameterized(HikariDataSource connect final Map<String, Object> formData = actionConfiguration.getFormData(); String query = getDataValueSafelyFromFormData(formData, BODY, STRING_TYPE, null); // Check for query parameter before performing the probably expensive fetch connection from the pool op. - if (isEmpty(query)) { - // Next TBD: update error based on new infra + if (isBlank(query)) { return Mono.error(new AppsmithPluginException(AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, - "Missing required parameter: Query.")); + OracleErrorMessages.MISSING_QUERY_ERROR_MSG)); } Boolean isPreparedStatement = TRUE; @@ -165,7 +166,7 @@ public Mono<ActionExecutionResult> executeParameterized(HikariDataSource connect mustacheKeysInOrder, executeActionDTO); } - private Mono<ActionExecutionResult> executeCommon(HikariDataSource connection, + private Mono<ActionExecutionResult> executeCommon(HikariDataSource connectionPool, DatasourceConfiguration datasourceConfiguration, ActionConfiguration actionConfiguration, Boolean preparedStatement, @@ -177,10 +178,9 @@ private Mono<ActionExecutionResult> executeCommon(HikariDataSource connection, final Map<String, Object> formData = actionConfiguration.getFormData(); String query = getDataValueSafelyFromFormData(formData, BODY, STRING_TYPE, null); - if (isEmpty(query)) { - // Next TBD: update error based on new error infra + if (isBlank(query)) { return Mono.error(new AppsmithPluginException(AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, - "Missing required parameter: Query.")); + OracleErrorMessages.MISSING_QUERY_ERROR_MSG)); } Map<String, Object> psParams = preparedStatement ? new LinkedHashMap<>() : null; @@ -191,8 +191,8 @@ private Mono<ActionExecutionResult> executeCommon(HikariDataSource connection, return Mono.fromCallable(() -> { Connection connectionFromPool; - try { - connectionFromPool = getConnectionFromConnectionPool(connection); + try { + connectionFromPool = getConnectionFromConnectionPool(connectionPool); } catch (SQLException | StaleConnectionException e) { // The function can throw either StaleConnectionException or SQLException. The underlying hikari // library throws SQLException in case the pool is closed or there is an issue initializing @@ -211,15 +211,10 @@ private Mono<ActionExecutionResult> executeCommon(HikariDataSource connection, PreparedStatement preparedQuery = null; boolean isResultSet; - HikariPoolMXBean poolProxy = connection.getHikariPoolMXBean(); + // Log HikariCP status + logHikariCPStatus(MessageFormat.format("Before executing Oracle query [{0}]", query), + connectionPool); - int idleConnections = poolProxy.getIdleConnections(); - int activeConnections = poolProxy.getActiveConnections(); - int totalConnections = poolProxy.getTotalConnections(); - int threadsAwaitingConnection = poolProxy.getThreadsAwaitingConnection(); - log.debug("Before executing Oracle query [{}] : Hikari Pool stats : active - {} , idle - {}, " + - "awaiting - {} , total - {}", query, activeConnections, idleConnections, - threadsAwaitingConnection, totalConnections); try { if (FALSE.equals(preparedStatement)) { statement = connectionFromPool.createStatement(); @@ -250,15 +245,13 @@ private Mono<ActionExecutionResult> executeCommon(HikariDataSource connection, } catch (SQLException e) { log.debug(Thread.currentThread().getName() + ": In the OraclePlugin, got action execution error"); log.debug(e.getMessage()); - return Mono.error(new AppsmithPluginException(AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, e.getMessage())); + return Mono.error(new AppsmithPluginException(OraclePluginError.QUERY_EXECUTION_FAILED, + OracleErrorMessages.QUERY_EXECUTION_FAILED_ERROR_MSG, e.getMessage(), + "SQLSTATE: " + e.getSQLState())); } finally { - idleConnections = poolProxy.getIdleConnections(); - activeConnections = poolProxy.getActiveConnections(); - totalConnections = poolProxy.getTotalConnections(); - threadsAwaitingConnection = poolProxy.getThreadsAwaitingConnection(); - log.debug("After executing Oracle query [{}] : Hikari Pool stats : active - {} , idle - " + - "{}, awaiting - {} , total - {}", query, activeConnections, idleConnections, - threadsAwaitingConnection, totalConnections); + // Log HikariCP status + logHikariCPStatus(MessageFormat.format("After executing Oracle query [{0}]", query), + connectionPool); closeConnectionPostExecution(resultSet, statement, preparedQuery, connectionFromPool); } @@ -389,6 +382,7 @@ public Object substituteValueInInput(int index, // the query. Ignore the exception } else { throw new AppsmithPluginException(AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, + String.format(OracleErrorMessages.QUERY_PREPARATION_FAILED_ERROR_MSG, value, binding), e.getMessage()); } } diff --git a/app/server/appsmith-plugins/oraclePlugin/src/main/java/com/external/plugins/exceptions/OracleErrorMessages.java b/app/server/appsmith-plugins/oraclePlugin/src/main/java/com/external/plugins/exceptions/OracleErrorMessages.java new file mode 100644 index 000000000000..50ff4874bc56 --- /dev/null +++ b/app/server/appsmith-plugins/oraclePlugin/src/main/java/com/external/plugins/exceptions/OracleErrorMessages.java @@ -0,0 +1,44 @@ +package com.external.plugins.exceptions; + +public class OracleErrorMessages { + private OracleErrorMessages() { + //Prevents instantiation + } + public static final String MISSING_QUERY_ERROR_MSG = "Missing required parameter: Query."; + + public static final String QUERY_EXECUTION_FAILED_ERROR_MSG = "Your Oracle query failed to execute."; + + public static final String ORACLE_JDBC_DRIVER_LOADING_ERROR_MSG = "Your Oracle query failed to execute."; + + public static final String GET_STRUCTURE_ERROR_MSG = "The Appsmith server has failed to fetch the structure of your schema."; + + public static final String QUERY_PREPARATION_FAILED_ERROR_MSG = "Query preparation failed while inserting value: %s" + + " for binding: {{%s}}."; + + public static final String SSL_CONFIGURATION_ERROR_MSG = "The Appsmith server has failed to fetch SSL configuration from datasource configuration form. "; + + public static final String INVALID_SSL_OPTION_ERROR_MSG = "The Appsmith server has found an unexpected SSL option: %s."; + + public static final String CONNECTION_POOL_CREATION_FAILED_ERROR_MSG = "An exception occurred while creating connection pool. One or more arguments in the datasource configuration may be invalid."; + + /* + ************************************************************************************************************************************************ + Error messages related to validation of datasource. + ************************************************************************************************************************************************ + */ + + public static final String DS_MISSING_ENDPOINT_ERROR_MSG = "Missing endpoint."; + + public static final String DS_MISSING_HOSTNAME_ERROR_MSG = "Missing hostname."; + + public static final String DS_INVALID_HOSTNAME_ERROR_MSG = "Host value cannot contain `/` or `:` characters. Found `%s`."; + + public static final String DS_MISSING_CONNECTION_MODE_ERROR_MSG = "Missing Connection Mode."; + + public static final String DS_MISSING_AUTHENTICATION_DETAILS_ERROR_MSG = "Missing authentication details."; + + public static final String DS_MISSING_USERNAME_ERROR_MSG = "Missing username for authentication."; + public static final String DS_MISSING_PASSWORD_ERROR_MSG = "Missing password for authentication."; + + public static final String DS_MISSING_SERVICE_NAME_ERROR_MSG = "Missing service name."; +} diff --git a/app/server/appsmith-plugins/oraclePlugin/src/main/java/com/external/plugins/exceptions/OraclePluginError.java b/app/server/appsmith-plugins/oraclePlugin/src/main/java/com/external/plugins/exceptions/OraclePluginError.java new file mode 100644 index 000000000000..a5be33da0ad4 --- /dev/null +++ b/app/server/appsmith-plugins/oraclePlugin/src/main/java/com/external/plugins/exceptions/OraclePluginError.java @@ -0,0 +1,79 @@ +package com.external.plugins.exceptions; + +import com.appsmith.external.exceptions.AppsmithErrorAction; +import com.appsmith.external.exceptions.pluginExceptions.BasePluginError; +import com.appsmith.external.models.ErrorType; +import lombok.Getter; + +import java.text.MessageFormat; + +@Getter +public enum OraclePluginError implements BasePluginError { + QUERY_EXECUTION_FAILED( + 500, + "PE-ORC-5000", + "{0}", + AppsmithErrorAction.LOG_EXTERNALLY, + "Query execution error", + ErrorType.INTERNAL_ERROR, + "{1}", + "{2}" + ), + ORACLE_PLUGIN_ERROR( + 500, + "PE-ORC-5001", + "{0}", + AppsmithErrorAction.LOG_EXTERNALLY, + "Query execution error", + ErrorType.INTERNAL_ERROR, + "{1}", + "{2}" + ), + RESPONSE_SIZE_TOO_LARGE( + 504, + "PE-ORC-5009", + "Response size exceeded the maximum supported size of {0} MB. Please use LIMIT to reduce the amount of data fetched.", + AppsmithErrorAction.DEFAULT, + "Large Result Set Not Supported", + ErrorType.INTERNAL_ERROR, + "{1}", + "{2}" + ), + ; + private final Integer httpErrorCode; + private final String appErrorCode; + private final String message; + private final String title; + private final AppsmithErrorAction errorAction; + private final ErrorType errorType; + + private final String downstreamErrorMessage; + + private final String downstreamErrorCode; + + OraclePluginError(Integer httpErrorCode, String appErrorCode, String message, AppsmithErrorAction errorAction, + String title, ErrorType errorType, String downstreamErrorMessage, String downstreamErrorCode) { + this.httpErrorCode = httpErrorCode; + this.appErrorCode = appErrorCode; + this.errorType = errorType; + this.errorAction = errorAction; + this.message = message; + this.title = title; + this.downstreamErrorMessage = downstreamErrorMessage; + this.downstreamErrorCode = downstreamErrorCode; + } + + public String getMessage(Object... args) { + return new MessageFormat(this.message).format(args); + } + + public String getErrorType() { return this.errorType.toString(); } + + public String getDownstreamErrorMessage(Object... args) { + return replacePlaceholderWithValue(this.downstreamErrorMessage, args); + } + + public String getDownstreamErrorCode(Object... args) { + return replacePlaceholderWithValue(this.downstreamErrorCode, args); + } +} diff --git a/app/server/appsmith-plugins/oraclePlugin/src/main/java/com/external/plugins/utils/OracleDatasourceUtils.java b/app/server/appsmith-plugins/oraclePlugin/src/main/java/com/external/plugins/utils/OracleDatasourceUtils.java index c9adb2d08c8a..bbef663399f8 100644 --- a/app/server/appsmith-plugins/oraclePlugin/src/main/java/com/external/plugins/utils/OracleDatasourceUtils.java +++ b/app/server/appsmith-plugins/oraclePlugin/src/main/java/com/external/plugins/utils/OracleDatasourceUtils.java @@ -8,21 +8,36 @@ import com.appsmith.external.models.DatasourceStructure; import com.appsmith.external.models.Endpoint; import com.appsmith.external.models.SSLDetails; +import com.external.plugins.exceptions.OracleErrorMessages; +import com.external.plugins.exceptions.OraclePluginError; import com.zaxxer.hikari.HikariConfig; import com.zaxxer.hikari.HikariDataSource; +import com.zaxxer.hikari.HikariPoolMXBean; import com.zaxxer.hikari.pool.HikariPool; +import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang.ObjectUtils; -import org.springframework.util.CollectionUtils; import reactor.core.publisher.Mono; +import java.sql.Connection; +import java.sql.ResultSet; import java.sql.SQLException; +import java.sql.Statement; +import java.text.MessageFormat; +import java.util.ArrayList; +import java.util.HashMap; import java.util.HashSet; +import java.util.LinkedHashMap; import java.util.List; +import java.util.Map; import java.util.Set; import java.util.stream.Collectors; +import static com.appsmith.external.helpers.PluginUtils.safelyCloseSingleConnectionFromHikariCP; +import static com.external.plugins.OraclePlugin.OraclePluginExecutor.scheduler; import static org.apache.commons.lang3.StringUtils.isBlank; +import static org.springframework.util.CollectionUtils.isEmpty; +@Slf4j public class OracleDatasourceUtils { public static final int MINIMUM_POOL_SIZE = 1; public static final int MAXIMUM_POOL_SIZE = 5; @@ -31,39 +46,92 @@ public class OracleDatasourceUtils { public static final String ORACLE_URL_PREFIX = "jdbc:oracle:thin:@tcp://"; public static final int ORACLE_URL_PREFIX_TCPS_OFFSET = 21; - public static void datasourceDestroy(HikariDataSource connection) { - if (connection != null) { - System.out.println(Thread.currentThread().getName() + ": Closing Oracle DB Connection Pool"); - connection.close(); + public static final String ORACLE_PRIMARY_KEY_INDICATOR = "P"; + + /** + * Example output: + * +------------+-----------+-----------------+ + * | TABLE_NAME |COLUMN_NAME| DATA_TYPE | + * +------------+-----------+-----------------+ + * | CLUB | ID | NUMBER | + * | STUDENTS | NAME | VARCHAR2 | + * +------------+-----------+-----------------+ + */ + public static final String ORACLE_SQL_QUERY_TO_GET_ALL_TABLE_COLUMN_TYPE = + "SELECT " + + "table_name, column_name, data_type " + + "FROM " + + "user_tab_cols"; + + /** + * Example output: + * +------------+-----------+-----------------+-----------------+-------------------+ + * | TABLE_NAME |COLUMN_NAME| CONSTRAINT_TYPE | CONSTRAINT_NAME | R_CONSTRAINT_NAME | + * +------------+-----------+-----------------+-----------------+-------------------+ + * | CLUB | ID | R | FK_STUDENTS_ID | PK_STUDENTS_ID | + * | STUDENTS | ID | P | SYS_C006397 | null | + * +------------+-----------+-----------------+-----------------+-------------------+ + */ + public static final String ORACLE_SQL_QUERY_TO_GET_ALL_TABLE_COLUMN_KEY_CONSTRAINTS = + "SELECT " + + " cols.table_name, " + + " cols.column_name, " + + " cons.constraint_type, " + + " cons.constraint_name, " + + " cons.r_constraint_name " + + "FROM " + + " all_cons_columns cols " + + " JOIN all_constraints cons " + + " ON cols.owner = cons.owner " + + " AND cols.constraint_name = cons.constraint_name " + + " JOIN all_tab_cols tab_cols " + + " ON cols.owner = tab_cols.owner " + + " AND cols.table_name = tab_cols.table_name " + + " AND cols.column_name = tab_cols.column_name " + + "WHERE " + + " cons.constraint_type IN ('P', 'R') " + + " AND cons.owner = 'ADMIN' " + + "ORDER BY " + + " cols.table_name, " + + " cols.position"; + + public static void datasourceDestroy(HikariDataSource connectionPool) { + if (connectionPool != null) { + log.debug(Thread.currentThread().getName() + ": Closing Oracle DB Connection Pool"); + connectionPool.close(); } } public static Set<String> validateDatasource(DatasourceConfiguration datasourceConfiguration) { Set<String> invalids = new HashSet<>(); - if (CollectionUtils.isEmpty(datasourceConfiguration.getEndpoints())) { - invalids.add("Missing endpoint."); + if (isEmpty(datasourceConfiguration.getEndpoints())) { + invalids.add(OracleErrorMessages.DS_MISSING_ENDPOINT_ERROR_MSG); } else { for (final Endpoint endpoint : datasourceConfiguration.getEndpoints()) { if (isBlank(endpoint.getHost())) { - invalids.add("Missing hostname."); + invalids.add(OracleErrorMessages.DS_MISSING_HOSTNAME_ERROR_MSG); } else if (endpoint.getHost().contains("/") || endpoint.getHost().contains(":")) { - invalids.add("Host value cannot contain `/` or `:` characters. Found `" + endpoint.getHost() + "`."); + invalids.add(String.format(OracleErrorMessages.DS_INVALID_HOSTNAME_ERROR_MSG, endpoint.getHost())); } } } if (datasourceConfiguration.getAuthentication() == null) { - invalids.add("Missing authentication details."); + invalids.add(OracleErrorMessages.DS_MISSING_AUTHENTICATION_DETAILS_ERROR_MSG); } else { DBAuth authentication = (DBAuth) datasourceConfiguration.getAuthentication(); if (isBlank(authentication.getUsername())) { - invalids.add("Missing username for authentication."); + invalids.add(OracleErrorMessages.DS_MISSING_USERNAME_ERROR_MSG); + } + + if (isBlank(authentication.getPassword())) { + invalids.add(OracleErrorMessages.DS_MISSING_PASSWORD_ERROR_MSG); } if (isBlank(authentication.getDatabaseName())) { - invalids.add("Missing database name."); + invalids.add(OracleErrorMessages.DS_MISSING_SERVICE_NAME_ERROR_MSG); } } @@ -73,17 +141,225 @@ public static Set<String> validateDatasource(DatasourceConfiguration datasourceC if (datasourceConfiguration.getConnection() == null || datasourceConfiguration.getConnection().getSsl() == null || datasourceConfiguration.getConnection().getSsl().getAuthType() == null) { - invalids.add("Appsmith server has failed to fetch SSL configuration from datasource configuration form. " + - "Please reach out to Appsmith customer support to resolve this."); + invalids.add(OracleErrorMessages.SSL_CONFIGURATION_ERROR_MSG); } return invalids; } - public static Mono<DatasourceStructure> getStructure(HikariDataSource connection, + public static Mono<DatasourceStructure> getStructure(HikariDataSource connectionPool, DatasourceConfiguration datasourceConfiguration) { - // Next TBD: fill it - return Mono.just(new DatasourceStructure()); + final DatasourceStructure structure = new DatasourceStructure(); + final Map<String, DatasourceStructure.Table> tableNameToTableMap = new LinkedHashMap<>(); + + return Mono.fromSupplier(() -> { + Connection connectionFromPool; + try { + connectionFromPool = getConnectionFromConnectionPool(connectionPool); + } catch (SQLException | StaleConnectionException e) { + // The function can throw either StaleConnectionException or SQLException. The + // underlying hikari library throws SQLException in case the pool is closed or there is an issue + // initializing the connection pool which can also be translated in our world to + // StaleConnectionException and should then trigger the destruction and recreation of the pool. + return Mono.error(e instanceof StaleConnectionException ? e : new StaleConnectionException()); + } + + logHikariCPStatus("Before getting Oracle DB schema", connectionPool); + + try (Statement statement = connectionFromPool.createStatement()) { + // Set table names. For each table set its column names and column types. + setTableNamesAndColumnNamesAndColumnTypes(statement, tableNameToTableMap); + + // Set primary key and foreign key constraints. + setPrimaryAndForeignKeyInfoInTables(statement, tableNameToTableMap); + + } catch (SQLException throwable) { + return Mono.error(new AppsmithPluginException( AppsmithPluginError.PLUGIN_GET_STRUCTURE_ERROR, + OracleErrorMessages.GET_STRUCTURE_ERROR_MSG, throwable.getCause(), + "SQLSTATE: " + throwable.getSQLState())); + } finally { + logHikariCPStatus("After getting Oracle DB schema", connectionPool); + safelyCloseSingleConnectionFromHikariCP(connectionFromPool, "Error returning Oracle connection to pool " + + "during get structure"); + } + + // Set SQL query templates + setSQLQueryTemplates(tableNameToTableMap); + + structure.setTables(new ArrayList<>(tableNameToTableMap.values())); + return structure; + }) + .map(resultStructure -> (DatasourceStructure) resultStructure) + .subscribeOn(scheduler); + } + + /** + * Run a SQL query to fetch all user accessible tables along with their column names and if the column is a + * primary or foreign key. Since the remote table relationship for a foreign key column is not explicitly defined + * we create a 1:1 map here for primary_key -> table, and foreign_key -> table so that we can find both the + * tables to which a foreign key is related to. + * Please check the SQL query macro definition to find a sample response as comment. + */ + private static void setPrimaryAndForeignKeyInfoInTables(Statement statement, Map<String, + DatasourceStructure.Table> tableNameToTableMap) throws SQLException { + Map<String, String> primaryKeyConstraintNameToTableNameMap = new HashMap<>(); + Map<String, String> primaryKeyConstraintNameToColumnNameMap = new HashMap<>(); + Map<String, String> foreignKeyConstraintNameToTableNameMap = new HashMap<>(); + Map<String, String> foreignKeyConstraintNameToColumnNameMap = new HashMap<>(); + Map<String, String> foreignKeyConstraintNameToRemoteConstraintNameMap = new HashMap<>(); + + try (ResultSet columnsResultSet = + statement.executeQuery(ORACLE_SQL_QUERY_TO_GET_ALL_TABLE_COLUMN_KEY_CONSTRAINTS)) { + while (columnsResultSet.next()) { + final String tableName = columnsResultSet.getString("TABLE_NAME"); + final String columnName = columnsResultSet.getString("COLUMN_NAME"); + final String constraintType = columnsResultSet.getString("CONSTRAINT_TYPE"); + final String constraintName = columnsResultSet.getString("CONSTRAINT_NAME"); + final String remoteConstraintName = columnsResultSet.getString("R_CONSTRAINT_NAME"); + + if (ORACLE_PRIMARY_KEY_INDICATOR.equalsIgnoreCase(constraintType)) { + primaryKeyConstraintNameToTableNameMap.put(constraintName, tableName); + primaryKeyConstraintNameToColumnNameMap.put(constraintName, columnName); + } + else { + foreignKeyConstraintNameToTableNameMap.put(constraintName, tableName); + foreignKeyConstraintNameToColumnNameMap.put(constraintName, columnName); + foreignKeyConstraintNameToRemoteConstraintNameMap.put(constraintName, remoteConstraintName); + } + } + + primaryKeyConstraintNameToColumnNameMap.keySet().stream() + .filter(constraintName -> { + String tableName = primaryKeyConstraintNameToTableNameMap.get(constraintName); + return tableNameToTableMap.keySet().contains(tableName); + }) + .forEach(constraintName -> { + String tableName = primaryKeyConstraintNameToTableNameMap.get(constraintName); + DatasourceStructure.Table table = tableNameToTableMap.get(tableName); + String columnName = primaryKeyConstraintNameToColumnNameMap.get(constraintName); + table.getKeys().add(new DatasourceStructure.PrimaryKey(constraintName, + List.of(columnName))); + }); + + foreignKeyConstraintNameToColumnNameMap.keySet().stream() + .filter(constraintName -> { + String tableName = foreignKeyConstraintNameToTableNameMap.get(constraintName); + return tableNameToTableMap.keySet().contains(tableName); + }) + .forEach(constraintName -> { + String tableName = foreignKeyConstraintNameToTableNameMap.get(constraintName); + DatasourceStructure.Table table = tableNameToTableMap.get(tableName); + String columnName = foreignKeyConstraintNameToColumnNameMap.get(constraintName); + String remoteConstraintName = + foreignKeyConstraintNameToRemoteConstraintNameMap.get(constraintName); + String remoteColumn = primaryKeyConstraintNameToColumnNameMap.get(remoteConstraintName); + table.getKeys().add(new DatasourceStructure.ForeignKey(constraintName, + List.of(columnName), List.of(remoteColumn))); + }); + } + } + + /** + * Run a SQL query to fetch all tables accessible to user along with their columns and data type of each column. + * Then read the response and populate Appsmith's Table object with the same. + * Please check the SQL query macro definition to find a sample response as comment. + */ + private static void setTableNamesAndColumnNamesAndColumnTypes(Statement statement, Map<String, + DatasourceStructure.Table> tableNameToTableMap) throws SQLException { + try (ResultSet columnsResultSet = + statement.executeQuery(ORACLE_SQL_QUERY_TO_GET_ALL_TABLE_COLUMN_TYPE)) { + while (columnsResultSet.next()) { + final String tableName = columnsResultSet.getString("TABLE_NAME"); + if (!tableNameToTableMap.containsKey(tableName)) { + tableNameToTableMap.put(tableName, new DatasourceStructure.Table( + DatasourceStructure.TableType.TABLE, + "", + tableName, + new ArrayList<>(), + new ArrayList<>(), + new ArrayList<>())); + } + final DatasourceStructure.Table table = tableNameToTableMap.get(tableName); + table.getColumns().add(new DatasourceStructure.Column( + columnsResultSet.getString("COLUMN_NAME"), + columnsResultSet.getString("DATA_TYPE"), + null, + false)); + } + } + } + + private static void setSQLQueryTemplates(Map<String, DatasourceStructure.Table> tableNameToTableMap) { + tableNameToTableMap.values().stream() + .forEach(table -> { + LinkedHashMap<String, String> columnNameToSampleColumnDataMap = + new LinkedHashMap<>(); + table.getColumns().stream() + .forEach(column -> { + columnNameToSampleColumnDataMap.put(column.getName(), + getSampleColumnData(column.getType())); + }); + + String selectQueryTemplate = MessageFormat.format("SELECT * FROM {0} WHERE " + + "ROWNUM < 10", table.getName()); + String insertQueryTemplate = MessageFormat.format("INSERT INTO {0} ({1}) " + + "VALUES ({2})", table.getName(), + getSampleColumnNamesCSVString(columnNameToSampleColumnDataMap), + getSampleColumnDataCSVString(columnNameToSampleColumnDataMap)); + String updateQueryTemplate = MessageFormat.format("UPDATE {0} SET {1} WHERE " + + "1=0; -- Specify a valid condition here. Removing the condition may " + + "update every row in the table!", table.getName(), + getSampleOneColumnUpdateString(columnNameToSampleColumnDataMap)); + String deleteQueryTemplate = MessageFormat.format("DELETE FROM {0} WHERE 1=0;" + + " -- Specify a valid condition here. Removing the condition may " + + "delete everything in the table!", table.getName()); + + table.getTemplates().add(new DatasourceStructure.Template("SELECT", null, + Map.of("body", Map.of("data", selectQueryTemplate)))); + table.getTemplates().add(new DatasourceStructure.Template("INSERT", null, + Map.of("body", Map.of("data", insertQueryTemplate)))); + table.getTemplates().add(new DatasourceStructure.Template("UPDATE", null, + Map.of("body", Map.of("data", updateQueryTemplate)))); + table.getTemplates().add(new DatasourceStructure.Template("DELETE", null, + Map.of("body", Map.of("data", deleteQueryTemplate)))); + }); + } + + private static String getSampleOneColumnUpdateString(LinkedHashMap<String, String> columnNameToSampleColumnDataMap) { + return MessageFormat.format("{0}={1}", columnNameToSampleColumnDataMap.keySet().stream().findFirst().orElse( + "id"), columnNameToSampleColumnDataMap.values().stream().findFirst().orElse("'uid'")); + } + + private static String getSampleColumnNamesCSVString(LinkedHashMap<String, String> columnNameToSampleColumnDataMap) { + return String.join(", ", columnNameToSampleColumnDataMap.keySet()); + } + + private static String getSampleColumnDataCSVString(LinkedHashMap<String, String> columnNameToSampleColumnDataMap) { + return String.join(", ", columnNameToSampleColumnDataMap.values()); + } + + private static String getSampleColumnData(String type) { + if (type == null) { + return "NULL"; + } + + switch (type.toUpperCase()) { + case "NUMBER": + return "1"; + case "FLOAT": /* Fall through */ + case "DOUBLE": + return "1.0"; + case "CHAR": /* Fall through */ + case "NCHAR": /* Fall through */ + case "VARCHAR": /* Fall through */ + case "VARCHAR2":/* Fall through */ + case "NVARCHAR":/* Fall through */ + case "NVARCHAR2": + return "'text'"; + case "NULL": /* Fall through */ + default: + return "NULL"; + } } public static HikariDataSource createConnectionPool(DatasourceConfiguration datasourceConfiguration) throws AppsmithPluginException { @@ -124,11 +400,8 @@ public static HikariDataSource createConnectionPool(DatasourceConfiguration data if (datasourceConfiguration.getConnection() == null || datasourceConfiguration.getConnection().getSsl() == null || datasourceConfiguration.getConnection().getSsl().getAuthType() == null) { - throw new AppsmithPluginException( - AppsmithPluginError.PLUGIN_ERROR, - "Appsmith server has failed to fetch SSL configuration from datasource configuration form. " + - "Please reach out to Appsmith customer support to resolve this." - ); + throw new AppsmithPluginException(OraclePluginError.ORACLE_PLUGIN_ERROR, + OracleErrorMessages.SSL_CONFIGURATION_ERROR_MSG); } SSLDetails.AuthType sslAuthType = datasourceConfiguration.getConnection().getSsl().getAuthType(); @@ -143,11 +416,8 @@ public static HikariDataSource createConnectionPool(DatasourceConfiguration data break; default: - throw new AppsmithPluginException( - AppsmithPluginError.PLUGIN_ERROR, - "Appsmith server has found an unexpected SSL option: " + sslAuthType + ". Please reach out to" + - " Appsmith customer support to resolve this." - ); + throw new AppsmithPluginException(OraclePluginError.ORACLE_PLUGIN_ERROR, + String.format(OracleErrorMessages.INVALID_SSL_OPTION_ERROR_MSG, sslAuthType)); } String url = urlBuilder.toString(); @@ -162,10 +432,8 @@ public static HikariDataSource createConnectionPool(DatasourceConfiguration data try { datasource = new HikariDataSource(config); } catch (HikariPool.PoolInitializationException e) { - throw new AppsmithPluginException( - AppsmithPluginError.PLUGIN_DATASOURCE_ARGUMENT_ERROR, - e.getMessage() - ); + throw new AppsmithPluginException(AppsmithPluginError.PLUGIN_DATASOURCE_ARGUMENT_ERROR, + OracleErrorMessages.CONNECTION_POOL_CREATION_FAILED_ERROR_MSG, e.getMessage()); } return datasource; @@ -185,4 +453,14 @@ public static java.sql.Connection getConnectionFromConnectionPool(HikariDataSour return connectionPool.getConnection(); } + + public static void logHikariCPStatus(String logPrefix, HikariDataSource connectionPool) { + HikariPoolMXBean poolProxy = connectionPool.getHikariPoolMXBean(); + int idleConnections = poolProxy.getIdleConnections(); + int activeConnections = poolProxy.getActiveConnections(); + int totalConnections = poolProxy.getTotalConnections(); + int threadsAwaitingConnection = poolProxy.getThreadsAwaitingConnection(); + log.debug("{0}: Hikari Pool stats : active - {1} , idle - {2}, awaiting - {3} , total - {4}", logPrefix, + activeConnections, idleConnections, threadsAwaitingConnection, totalConnections); + } } diff --git a/app/server/appsmith-plugins/oraclePlugin/src/main/java/com/external/plugins/utils/OracleExecuteUtils.java b/app/server/appsmith-plugins/oraclePlugin/src/main/java/com/external/plugins/utils/OracleExecuteUtils.java index aa6c22663fd5..6dc8dfc54f99 100644 --- a/app/server/appsmith-plugins/oraclePlugin/src/main/java/com/external/plugins/utils/OracleExecuteUtils.java +++ b/app/server/appsmith-plugins/oraclePlugin/src/main/java/com/external/plugins/utils/OracleExecuteUtils.java @@ -1,8 +1,8 @@ package com.external.plugins.utils; -import com.appsmith.external.constants.DataType; import com.appsmith.external.plugins.SmartSubstitutionInterface; import oracle.jdbc.OracleArray; +import oracle.sql.CLOB; import oracle.sql.Datum; import org.apache.commons.lang.ObjectUtils; @@ -12,6 +12,7 @@ import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.sql.Statement; +import java.text.MessageFormat; import java.time.LocalDateTime; import java.time.OffsetDateTime; import java.time.format.DateTimeFormatter; @@ -21,22 +22,17 @@ import java.util.regex.Pattern; import static com.appsmith.external.helpers.PluginUtils.getColumnsListForJdbcPlugin; +import static com.appsmith.external.helpers.PluginUtils.safelyCloseSingleConnectionFromHikariCP; import static java.lang.Boolean.FALSE; public class OracleExecuteUtils implements SmartSubstitutionInterface { public static final String DATE_COLUMN_TYPE_NAME = "date"; public static final String TIMESTAMP_TYPE_NAME = "timestamp"; public static final String TIMESTAMPTZ_TYPE_NAME = "TIMESTAMP WITH TIME ZONE"; - public static final String INTERVAL_TYPE_NAME = "interval"; + public static final String TIMESTAMPLTZ_TYPE_NAME = "TIMESTAMP WITH LOCAL TIME ZONE"; + public static final String CLOB_TYPE_NAME = "CLOB"; + public static final String NCLOB_TYPE_NAME = "NCLOB"; public static final String AFFECTED_ROWS_KEY = "affectedRows"; - public static final String INT8 = "int8"; - public static final String INT4 = "int4"; - public static final String DECIMAL = "decimal"; - public static final String VARCHAR = "varchar"; - public static final String BOOL = "bool"; - public static final String DATE = "date"; - public static final String TIME = "time"; - public static final String FLOAT8 = "float8"; /** * Every PL/SQL block must have `BEGIN` and `END` keywords to define the block. Apart from these they could also @@ -83,15 +79,8 @@ public static void closeConnectionPostExecution(ResultSet resultSet, Statement s } } - if (connectionFromPool != null) { - try { - // Return the connection back to the pool - connectionFromPool.close(); - } catch (SQLException e) { - System.out.println(Thread.currentThread().getName() + - ": Execute Error returning Oracle connection to pool" + e.getMessage()); - } - } + safelyCloseSingleConnectionFromHikariCP(connectionFromPool, MessageFormat.format("{0}: Execute Error returning " + + "Oracle connection to pool", Thread.currentThread().getName())); } /** @@ -155,27 +144,18 @@ public static void populateRowsAndColumns(List<Map<String, Object>> rowsList, Li ) ) + "Z"; - } else if (TIMESTAMPTZ_TYPE_NAME.equalsIgnoreCase(typeName)) { + } else if (TIMESTAMPTZ_TYPE_NAME.equalsIgnoreCase(typeName) || TIMESTAMPLTZ_TYPE_NAME.equalsIgnoreCase(typeName)) { value = DateTimeFormatter.ISO_DATE_TIME.format( resultSet.getObject(i, OffsetDateTime.class) ); - } else if (INTERVAL_TYPE_NAME.equalsIgnoreCase(typeName)) { - value = resultSet.getObject(i).toString(); - + } else if (CLOB_TYPE_NAME.equalsIgnoreCase(typeName) || NCLOB_TYPE_NAME.equals(typeName)) { + value = String.valueOf(((CLOB)resultSet.getObject(i)).getTarget().getPrefetchedData()); } else if (resultSet.getObject(i) instanceof OracleArray) { value = ((OracleArray)resultSet.getObject(i)).getArray(); } else { - value = resultSet.getObject(i); - - /** - * 'Datum' class is the root of Oracle native datatype hierarchy. - * Ref: https://docs.oracle.com/cd/A97329_03/web.902/q20224/oracle/sql/Datum.html - */ - if (value instanceof Datum) { - value = new String(((Datum) value).getBytes()); - } + value = resultSet.getObject(i).toString(); } row.put(metaData.getColumnName(i), value); @@ -185,30 +165,4 @@ public static void populateRowsAndColumns(List<Map<String, Object>> rowsList, Li } } } - - public static String toOraclePrimitiveTypeName(DataType type) { - switch (type) { - case LONG: - return INT8; - case INTEGER: - return INT4; - case FLOAT: - return DECIMAL; - case STRING: - return VARCHAR; - case BOOLEAN: - return BOOL; - case DATE: - return DATE; - case TIME: - return TIME; - case DOUBLE: - return FLOAT8; - case ARRAY: - throw new IllegalArgumentException("Array of Array datatype is not supported."); - default: - throw new IllegalArgumentException( - "Unable to map the computed data type to primitive Postgresql type"); - } - } } diff --git a/app/server/appsmith-plugins/oraclePlugin/src/main/resources/form.json b/app/server/appsmith-plugins/oraclePlugin/src/main/resources/form.json index 5547a9ac0e09..af499618f3bb 100755 --- a/app/server/appsmith-plugins/oraclePlugin/src/main/resources/form.json +++ b/app/server/appsmith-plugins/oraclePlugin/src/main/resources/form.json @@ -12,7 +12,8 @@ "configProperty": "datasourceConfiguration.endpoints[*].host", "controlType": "KEYVALUE_ARRAY", "validationMessage": "Please enter a valid host", - "validationRegex": "^((?![/:]).)*$" + "validationRegex": "^((?![/:]).)*$", + "isRequired": true }, { "label": "Port", @@ -23,11 +24,11 @@ ] }, { - "label": "Database Name", + "label": "Service Name", "configProperty": "datasourceConfiguration.authentication.databaseName", "controlType": "INPUT_TEXT", - "placeholderText": "Database name", - "initialValue": "admin" + "placeholderText": "gfb284db6bcee33_testdb_high.adb.oraclecloud.com", + "isRequired": true } ] }, @@ -42,15 +43,17 @@ "label": "Username", "configProperty": "datasourceConfiguration.authentication.username", "controlType": "INPUT_TEXT", - "placeholderText": "Username" + "placeholderText": "admin", + "isRequired": true }, { "label": "Password", "configProperty": "datasourceConfiguration.authentication.password", "dataType": "PASSWORD", "controlType": "INPUT_TEXT", - "placeholderText": "Password", - "encrypted": true + "placeholderText": "password", + "encrypted": true, + "isRequired": true } ] } @@ -64,14 +67,14 @@ "label": "SSL Mode", "configProperty": "datasourceConfiguration.connection.ssl.authType", "controlType": "DROP_DOWN", - "initialValue": "DISABLE", + "initialValue": "NO_VERIFY", "options": [ { "label": "Disable", "value": "DISABLE" }, { - "label": "No verify", + "label": "TLS", "value": "NO_VERIFY" } ] 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 02b45adeed4b..38503374c30e 100755 --- a/app/server/appsmith-plugins/oraclePlugin/src/main/resources/setting.json +++ b/app/server/appsmith-plugins/oraclePlugin/src/main/resources/setting.json @@ -8,24 +8,24 @@ "label": "Run query on page load", "configProperty": "executeOnLoad", "controlType": "SWITCH", - "info": "Will refresh data each time the page is loaded" + "subtitle": "Will refresh data each time the page is loaded" }, { "label": "Request confirmation before running query", "configProperty": "confirmBeforeExecute", "controlType": "SWITCH", - "info": "Ask confirmation from the user each time before refreshing data" + "subtitle": "Ask confirmation from the user each time before refreshing data" }, { "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.", + "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.", "configProperty": "actionConfiguration.formData.preparedStatement.data", "controlType": "SWITCH", "initialValue": true }, { "label": "Query timeout (in milliseconds)", - "info": "Maximum time after which the query will return", + "subtitle": "Maximum time after which the query will return", "configProperty": "actionConfiguration.timeoutInMillisecond", "controlType": "INPUT_TEXT", "dataType": "NUMBER" diff --git a/app/server/appsmith-plugins/oraclePlugin/src/main/resources/templates/DELETE.sql b/app/server/appsmith-plugins/oraclePlugin/src/main/resources/templates/DELETE.sql index e7014662d50a..c5000f4ee8ea 100755 --- a/app/server/appsmith-plugins/oraclePlugin/src/main/resources/templates/DELETE.sql +++ b/app/server/appsmith-plugins/oraclePlugin/src/main/resources/templates/DELETE.sql @@ -1 +1 @@ -DELETE FROM users WHERE id = -1; \ No newline at end of file +DELETE FROM users WHERE id = {{idInput.text}} \ No newline at end of file diff --git a/app/server/appsmith-plugins/oraclePlugin/src/main/resources/templates/CREATE.sql b/app/server/appsmith-plugins/oraclePlugin/src/main/resources/templates/INSERT.sql similarity index 97% rename from app/server/appsmith-plugins/oraclePlugin/src/main/resources/templates/CREATE.sql rename to app/server/appsmith-plugins/oraclePlugin/src/main/resources/templates/INSERT.sql index b5253c2bf8b2..f59768c5c550 100755 --- a/app/server/appsmith-plugins/oraclePlugin/src/main/resources/templates/CREATE.sql +++ b/app/server/appsmith-plugins/oraclePlugin/src/main/resources/templates/INSERT.sql @@ -5,4 +5,4 @@ VALUES {{ nameInput.text }}, {{ genderDropdown.selectedOptionValue }}, {{ emailInput.text }} - ); \ No newline at end of file + ) \ No newline at end of file diff --git a/app/server/appsmith-plugins/oraclePlugin/src/main/resources/templates/SELECT.sql b/app/server/appsmith-plugins/oraclePlugin/src/main/resources/templates/SELECT.sql index 8d4afd4c3b03..1001012697b6 100755 --- a/app/server/appsmith-plugins/oraclePlugin/src/main/resources/templates/SELECT.sql +++ b/app/server/appsmith-plugins/oraclePlugin/src/main/resources/templates/SELECT.sql @@ -1 +1 @@ -SELECT * FROM users where role = 'Admin' ORDER BY id LIMIT 10 +SELECT* FROM users WHERE ROWNUM < 10 diff --git a/app/server/appsmith-plugins/oraclePlugin/src/main/resources/templates/UPDATE.sql b/app/server/appsmith-plugins/oraclePlugin/src/main/resources/templates/UPDATE.sql index facf9fc3f9d6..1e8246500e01 100755 --- a/app/server/appsmith-plugins/oraclePlugin/src/main/resources/templates/UPDATE.sql +++ b/app/server/appsmith-plugins/oraclePlugin/src/main/resources/templates/UPDATE.sql @@ -1,3 +1 @@ -UPDATE users - SET status = 'APPROVED' - WHERE id = {{ usersTable.selectedRow.id }}; \ No newline at end of file +UPDATE users SET status = 'APPROVED' WHERE id = {{ usersTable.selectedRow.id }} \ No newline at end of file diff --git a/app/server/appsmith-plugins/oraclePlugin/src/main/resources/templates/meta.json b/app/server/appsmith-plugins/oraclePlugin/src/main/resources/templates/meta.json index b05a59284531..222e2f9f27de 100755 --- a/app/server/appsmith-plugins/oraclePlugin/src/main/resources/templates/meta.json +++ b/app/server/appsmith-plugins/oraclePlugin/src/main/resources/templates/meta.json @@ -1,10 +1,10 @@ { "templates": [ { - "file": "CREATE.sql" + "file": "SELECT.sql" }, { - "file": "SELECT.sql" + "file": "INSERT.sql" }, { "file": "UPDATE.sql" diff --git a/app/server/appsmith-plugins/oraclePlugin/src/test/java/com/external/plugins/OraclePluginTest.java b/app/server/appsmith-plugins/oraclePlugin/src/test/java/com/external/plugins/OraclePluginTest.java index 6b398c222a7f..1cb732ac9d1f 100755 --- a/app/server/appsmith-plugins/oraclePlugin/src/test/java/com/external/plugins/OraclePluginTest.java +++ b/app/server/appsmith-plugins/oraclePlugin/src/test/java/com/external/plugins/OraclePluginTest.java @@ -1,11 +1,24 @@ package com.external.plugins; +import com.external.plugins.exceptions.OraclePluginError; import lombok.extern.slf4j.Slf4j; +import org.junit.jupiter.api.Test; import org.testcontainers.junit.jupiter.Testcontainers; +import java.util.Arrays; +import java.util.stream.Collectors; + @Slf4j @Testcontainers public class OraclePluginTest { - // TODO: fill it + @Test + public void verifyUniquenessOfOraclePluginErrorCode() { + assert (Arrays.stream(OraclePluginError.values()).map(OraclePluginError::getAppErrorCode).distinct().count() == OraclePluginError.values().length); + + assert (Arrays.stream(OraclePluginError.values()).map(OraclePluginError::getAppErrorCode) + .filter(appErrorCode -> appErrorCode.length() != 11 || !appErrorCode.startsWith("PE-ORC")) + .collect(Collectors.toList()).size() == 0); + + } } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/migrations/DatabaseChangelog2.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/migrations/DatabaseChangelog2.java index e92bcce88972..8f3c31a5fc55 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/migrations/DatabaseChangelog2.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/migrations/DatabaseChangelog2.java @@ -2817,7 +2817,7 @@ public void addOraclePlugin(MongoTemplate mongoTemplate) { plugin.setPackageName("oracle-plugin"); plugin.setUiComponent("DbEditorForm"); plugin.setResponseType(Plugin.ResponseType.TABLE); - plugin.setIconLocation("https://s3.us-east-2.amazonaws.com/assets.appsmith.com/oracle.png"); + plugin.setIconLocation("https://s3.us-east-2.amazonaws.com/assets.appsmith.com/oracle.svg"); plugin.setDocumentationLink("https://docs.appsmith.com/datasource-reference/querying-oracle"); plugin.setDefaultInstall(true); try { @@ -2832,7 +2832,7 @@ public void addOraclePlugin(MongoTemplate mongoTemplate) { public void updateOraclePluginName(MongoTemplate mongoTemplate) { Plugin oraclePlugin = mongoTemplate.findOne(query(where("packageName").is("oracle-plugin")), Plugin.class); oraclePlugin.setName("Oracle"); - oraclePlugin.setIconLocation("https://s3.us-east-2.amazonaws.com/assets.appsmith.com/oracle.png"); + oraclePlugin.setIconLocation("https://s3.us-east-2.amazonaws.com/assets.appsmith.com/oracle.svg"); mongoTemplate.save(oraclePlugin); } } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/migrations/db/ce/Migration007UpdateOracleLogoToSVG.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/migrations/db/ce/Migration007UpdateOracleLogoToSVG.java new file mode 100644 index 000000000000..316fe8552ad8 --- /dev/null +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/migrations/db/ce/Migration007UpdateOracleLogoToSVG.java @@ -0,0 +1,41 @@ +package com.appsmith.server.migrations.db.ce; + +import com.appsmith.server.constants.FieldName; +import com.appsmith.server.domains.Plugin; +import io.mongock.api.annotations.ChangeUnit; +import io.mongock.api.annotations.Execution; +import io.mongock.api.annotations.RollbackExecution; +import org.springframework.data.mongodb.core.MongoTemplate; +import org.springframework.data.mongodb.core.query.Criteria; +import org.springframework.data.mongodb.core.query.Query; +import org.springframework.data.mongodb.core.query.Update; + +import java.util.List; +import java.util.Set; + +import static com.appsmith.external.constants.PluginConstants.PackageName.AMAZON_S3_PLUGIN; +import static com.appsmith.external.constants.PluginConstants.PackageName.DYNAMO_PLUGIN; +import static com.appsmith.external.constants.PluginConstants.PackageName.FIRESTORE_PLUGIN; +import static com.appsmith.external.constants.PluginConstants.PackageName.REDSHIFT_PLUGIN; +import static org.springframework.data.mongodb.core.query.Criteria.where; +import static org.springframework.data.mongodb.core.query.Query.query; + +@ChangeUnit(order = "007", id="update-oracle-logo-to-svg", author = " ") +public class Migration007UpdateOracleLogoToSVG { + private final MongoTemplate mongoTemplate; + + public Migration007UpdateOracleLogoToSVG(MongoTemplate mongoTemplate) { + this.mongoTemplate = mongoTemplate; + } + + @RollbackExecution + public void rollBackExecution() { + } + + @Execution + public void updateOracleLogoToSVG() { + Plugin oraclePlugin = mongoTemplate.findOne(query(where("packageName").is("oracle-plugin")), Plugin.class); + oraclePlugin.setIconLocation("https://s3.us-east-2.amazonaws.com/assets.appsmith.com/oracle.svg"); + mongoTemplate.save(oraclePlugin); + } +} 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 b209c9efa6c9..947dec126415 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 @@ -112,9 +112,9 @@ public Mono<? extends DatasourceContext<?>> getCachedDatasourceContextMono(Datas datasourceContextMap.put(datasourceContextIdentifier, datasourceContext); } - Mono<Object> connectionMono = pluginExecutor.datasourceCreate(datasource.getDatasourceConfiguration()).cache(); + Mono<Object> connectionMonoCache = pluginExecutor.datasourceCreate(datasource.getDatasourceConfiguration()).cache(); - Mono<DatasourceContext<Object>> datasourceContextMonoCache = connectionMono + Mono<DatasourceContext<Object>> datasourceContextMonoCache = connectionMonoCache .flatMap(connection -> updateDatasourceAndSetAuthentication(connection, datasource, datasourceContextIdentifier)) .map(connection -> {
a92b6804627960e0b07594c358957d410dda1a0f
2022-10-04 16:25:26
Rimil Dey
chore: Extract views into their own components (#17014)
false
Extract views into their own components (#17014)
chore
diff --git a/app/client/src/components/editorComponents/ActionCreator/Fields.tsx b/app/client/src/components/editorComponents/ActionCreator/Fields.tsx index 0e9454b2b260..782be9e0784a 100644 --- a/app/client/src/components/editorComponents/ActionCreator/Fields.tsx +++ b/app/client/src/components/editorComponents/ActionCreator/Fields.tsx @@ -1,23 +1,13 @@ import React from "react"; +import { TreeDropdownOption } from "design-system"; import { - TreeDropdown, - Setter, - TreeDropdownOption, - Switcher, -} from "design-system"; -import { - ControlWrapper, - FieldWrapper, StyledDividerContainer, StyledNavigateToFieldsContainer, StyledNavigateToFieldWrapper, } from "components/propertyControls/StyledControls"; -import { KeyValueComponent } from "components/propertyControls/KeyValueComponent"; -import { InputText } from "components/propertyControls/InputTextControl"; import HightlightedCode from "components/editorComponents/HighlightedCode"; import { Skin } from "constants/DefaultTheme"; import { DropdownOption } from "components/constants"; -import { AutocompleteDataType } from "utils/autocomplete/TernServer"; import DividerComponent from "widgets/DividerWidget/component"; import store from "store"; import { getPageList } from "selectors/entitiesSelector"; @@ -29,7 +19,6 @@ import { AppsmithFunction, FieldType, } from "./constants"; -import { PopoverPosition } from "@blueprintjs/core"; import { ACTION_TRIGGER_REGEX } from "./regex"; import { SwitchType, @@ -48,7 +37,11 @@ import { enumTypeSetter, enumTypeGetter, } from "./utils"; -import { ALERT_STYLE_OPTIONS } from "../../../ce/constants/messages"; +import { ALERT_STYLE_OPTIONS } from "@appsmith/constants/messages"; +import { SelectorView } from "./viewComponents/SelectorView"; +import { KeyValueView } from "./viewComponents/KeyValueView"; +import { TextView } from "./viewComponents/TextView"; +import { TabView } from "./viewComponents/TabView"; /** ******** Steps to add a new function ******* @@ -71,78 +64,14 @@ import { ALERT_STYLE_OPTIONS } from "../../../ce/constants/messages"; **/ const views = { - [ViewTypes.SELECTOR_VIEW]: function SelectorView(props: SelectorViewProps) { - return ( - <FieldWrapper> - <ControlWrapper isAction key={props.label}> - {props.label && <label>{props.label}</label>} - <TreeDropdown - 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} - /> - </ControlWrapper> - </FieldWrapper> - ); - }, - [ViewTypes.KEY_VALUE_VIEW]: function KeyValueView(props: KeyValueViewProps) { - return ( - <ControlWrapper isAction key={props.label}> - <KeyValueComponent - addLabel={"Query Params"} - pairs={props.get(props.value, false) as DropdownOption[]} - updatePairs={(pageParams: DropdownOption[]) => props.set(pageParams)} - /> - </ControlWrapper> - ); - }, - [ViewTypes.TEXT_VIEW]: function TextView(props: TextViewProps) { - return ( - <FieldWrapper> - <ControlWrapper isAction key={props.label}> - {props.label && <label>{props.label}</label>} - <InputText - additionalAutocomplete={props.additionalAutoComplete} - evaluatedValue={props.get(props.value, false) as string} - expected={{ - type: "string", - example: "showMessage('Hello World!', 'info')", - autocompleteDataType: AutocompleteDataType.STRING, - }} - label={props.label} - onChange={(event: any) => { - if (event.target) { - props.set(event.target.value, true); - } else { - props.set(event, true); - } - }} - value={props.get(props.value, props.index, false) as string} - /> - </ControlWrapper> - </FieldWrapper> - ); - }, - [ViewTypes.TAB_VIEW]: function TabView(props: TabViewProps) { - return ( - <FieldWrapper> - <ControlWrapper> - {props.label && <label>{props.label}</label>} - <Switcher activeObj={props.activeObj} switches={props.switches} /> - </ControlWrapper> - </FieldWrapper> - ); - }, + [ViewTypes.SELECTOR_VIEW]: (props: SelectorViewProps) => ( + <SelectorView {...props} /> + ), + [ViewTypes.KEY_VALUE_VIEW]: (props: KeyValueViewProps) => ( + <KeyValueView {...props} /> + ), + [ViewTypes.TEXT_VIEW]: (props: TextViewProps) => <TextView {...props} />, + [ViewTypes.TAB_VIEW]: (props: TabViewProps) => <TabView {...props} />, }; const fieldConfigs: FieldConfigs = { diff --git a/app/client/src/components/editorComponents/ActionCreator/viewComponents/KeyValueView/index.tsx b/app/client/src/components/editorComponents/ActionCreator/viewComponents/KeyValueView/index.tsx new file mode 100644 index 000000000000..986872358543 --- /dev/null +++ b/app/client/src/components/editorComponents/ActionCreator/viewComponents/KeyValueView/index.tsx @@ -0,0 +1,17 @@ +import { KeyValueViewProps } from "../../types"; +import { ControlWrapper } from "components/propertyControls/StyledControls"; +import { KeyValueComponent } from "components/propertyControls/KeyValueComponent"; +import { DropdownOption } from "../../../../constants"; +import React from "react"; + +export function KeyValueView(props: KeyValueViewProps) { + return ( + <ControlWrapper isAction key={props.label}> + <KeyValueComponent + addLabel={"Query Params"} + pairs={props.get(props.value, false) as DropdownOption[]} + updatePairs={(pageParams: DropdownOption[]) => props.set(pageParams)} + /> + </ControlWrapper> + ); +} diff --git a/app/client/src/components/editorComponents/ActionCreator/viewComponents/SelectorView/SelectorView.test.tsx b/app/client/src/components/editorComponents/ActionCreator/viewComponents/SelectorView/SelectorView.test.tsx new file mode 100644 index 000000000000..87d72ec50c3b --- /dev/null +++ b/app/client/src/components/editorComponents/ActionCreator/viewComponents/SelectorView/SelectorView.test.tsx @@ -0,0 +1,33 @@ +import React from "react"; +import "@testing-library/jest-dom"; +import { render, screen } from "test/testUtils"; +import { SelectorViewProps } from "../../types"; +import { SelectorView } from "./index"; + +describe("Selector view component", () => { + const props: SelectorViewProps = { + options: [ + { + label: "Page1", + id: "632c1d6244562f5051a7f36b", + value: "'Page1'", + }, + ], + label: "Choose Page", + value: "{{navigateTo('Page1', {}, 'SAME_WINDOW')}}", + defaultText: "Select Page", + displayValue: "", + get: () => { + return 1; + }, + set: () => { + return 1; + }, + }; + test("Renders selector view component correctly", () => { + render(<SelectorView {...props} />); + expect(screen.getByTestId("selector-view-label")).toHaveTextContent( + "Choose Page", + ); + }); +}); diff --git a/app/client/src/components/editorComponents/ActionCreator/viewComponents/SelectorView/index.tsx b/app/client/src/components/editorComponents/ActionCreator/viewComponents/SelectorView/index.tsx new file mode 100644 index 000000000000..084de89f029e --- /dev/null +++ b/app/client/src/components/editorComponents/ActionCreator/viewComponents/SelectorView/index.tsx @@ -0,0 +1,35 @@ +import { SelectorViewProps } from "../../types"; +import { + ControlWrapper, + FieldWrapper, +} from "components/propertyControls/StyledControls"; +import { Setter, TreeDropdown } from "design-system"; +import { PopoverPosition } from "@blueprintjs/core"; +import React from "react"; + +export function SelectorView(props: SelectorViewProps) { + return ( + <FieldWrapper> + <ControlWrapper isAction key={props.label}> + {props.label && ( + <label data-testid="selector-view-label">{props.label}</label> + )} + <TreeDropdown + 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} + /> + </ControlWrapper> + </FieldWrapper> + ); +} diff --git a/app/client/src/components/editorComponents/ActionCreator/viewComponents/TabView/TabView.test.tsx b/app/client/src/components/editorComponents/ActionCreator/viewComponents/TabView/TabView.test.tsx new file mode 100644 index 000000000000..0c143477e414 --- /dev/null +++ b/app/client/src/components/editorComponents/ActionCreator/viewComponents/TabView/TabView.test.tsx @@ -0,0 +1,39 @@ +import React from "react"; +import "@testing-library/jest-dom"; +import { render, screen } from "test/testUtils"; +import { TabView } from "./index"; +import { TabViewProps } from "../../types"; + +describe("Tab View component", () => { + const props: TabViewProps = { + label: "Type", + activeObj: { + id: "page-name", + text: "Page Name", + action: () => { + return 1; + }, + }, + switches: [ + { + id: "page-name", + text: "Page Name", + action: () => { + return 1; + }, + }, + { + id: "url", + text: "URL", + action: () => { + console.log("URL"); + }, + }, + ], + value: "{{navigateTo('Page1', {}, 'SAME_WINDOW'}}", + }; + test("Renders Tab view component correctly", () => { + render(<TabView {...props} />); + expect(screen.getByTestId("tabs-label")).toHaveTextContent("Type"); + }); +}); diff --git a/app/client/src/components/editorComponents/ActionCreator/viewComponents/TabView/index.tsx b/app/client/src/components/editorComponents/ActionCreator/viewComponents/TabView/index.tsx new file mode 100644 index 000000000000..382991e5720f --- /dev/null +++ b/app/client/src/components/editorComponents/ActionCreator/viewComponents/TabView/index.tsx @@ -0,0 +1,18 @@ +import { TabViewProps } from "../../types"; +import { + ControlWrapper, + FieldWrapper, +} from "components/propertyControls/StyledControls"; +import { Switcher } from "design-system"; +import React from "react"; + +export function TabView(props: TabViewProps) { + return ( + <FieldWrapper> + <ControlWrapper> + {props.label && <label data-testid="tabs-label">{props.label}</label>} + <Switcher activeObj={props.activeObj} switches={props.switches} /> + </ControlWrapper> + </FieldWrapper> + ); +} diff --git a/app/client/src/components/editorComponents/ActionCreator/viewComponents/TextView/TextView.test.tsx b/app/client/src/components/editorComponents/ActionCreator/viewComponents/TextView/TextView.test.tsx new file mode 100644 index 000000000000..2e47d2ae276a --- /dev/null +++ b/app/client/src/components/editorComponents/ActionCreator/viewComponents/TextView/TextView.test.tsx @@ -0,0 +1,22 @@ +import React from "react"; +import "@testing-library/jest-dom"; +import { render, screen } from "test/testUtils"; +import { TextView } from "./index"; +import { TextViewProps } from "../../types"; + +describe("Text view component", () => { + const props: TextViewProps = { + label: "Key", + value: "{{storeValue(,'1')}}", + get: () => { + return 1; + }, + set: () => { + return 1; + }, + }; + test("Renders Text view component correctly", () => { + render(<TextView {...props} />); + expect(screen.getByTestId("text-view-label")).toHaveTextContent("Key"); + }); +}); diff --git a/app/client/src/components/editorComponents/ActionCreator/viewComponents/TextView/index.tsx b/app/client/src/components/editorComponents/ActionCreator/viewComponents/TextView/index.tsx new file mode 100644 index 000000000000..7a861bfeb84f --- /dev/null +++ b/app/client/src/components/editorComponents/ActionCreator/viewComponents/TextView/index.tsx @@ -0,0 +1,38 @@ +import { TextViewProps } from "../../types"; +import { + ControlWrapper, + FieldWrapper, +} from "components/propertyControls/StyledControls"; +import { InputText } from "components/propertyControls/InputTextControl"; +import { AutocompleteDataType } from "utils/autocomplete/TernServer"; +import React from "react"; + +export function TextView(props: TextViewProps) { + return ( + <FieldWrapper> + <ControlWrapper isAction key={props.label}> + {props.label && ( + <label data-testid="text-view-label">{props.label}</label> + )} + <InputText + additionalAutocomplete={props.additionalAutoComplete} + evaluatedValue={props.get(props.value, false) as string} + expected={{ + type: "string", + example: "showMessage('Hello World!', 'info')", + autocompleteDataType: AutocompleteDataType.STRING, + }} + label={props.label} + onChange={(event: any) => { + if (event.target) { + props.set(event.target.value, true); + } else { + props.set(event, true); + } + }} + value={props.get(props.value, props.index, false) as string} + /> + </ControlWrapper> + </FieldWrapper> + ); +}
9cd134d62309b86a2aac638119064c337b04ce1d
2020-05-14 16:17:13
Tejaaswini
feat: Use mock response to display org and applications
false
Use mock response to display org and applications
feat
diff --git a/app/client/src/constants/ReduxActionConstants.tsx b/app/client/src/constants/ReduxActionConstants.tsx index 499b95a581da..13d2056eef8d 100644 --- a/app/client/src/constants/ReduxActionConstants.tsx +++ b/app/client/src/constants/ReduxActionConstants.tsx @@ -355,6 +355,7 @@ export type ApplicationPayload = { organizationId: string; pageCount: number; defaultPageId?: string; + userPermissions?: string[]; }; // export interface LoadAPIResponsePayload extends ExecuteActionResponse {} diff --git a/app/client/src/mockResponses/OrganisationListResponse.tsx b/app/client/src/mockResponses/OrganisationListResponse.tsx new file mode 100644 index 000000000000..2e850f1376aa --- /dev/null +++ b/app/client/src/mockResponses/OrganisationListResponse.tsx @@ -0,0 +1,164 @@ +const organizationList = [ + { + organization: { + id: "5eb2eda5ba4ce1723926cf37", + createdBy: null, + modifiedBy: null, + deletedAt: null, + userPermissions: ["read:organizations", "manage:orgApplications"], + domain: "appsmith-another-test.com", + name: "Another Test Organization", + website: "appsmith.com", + organizationSettings: null, + plugins: [ + { + id: null, + createdBy: null, + modifiedBy: null, + deletedAt: null, + userPermissions: [], + pluginId: "5eb2eda5ba4ce1723926cf30", + status: null, + new: true, + }, + ], + slug: "another-test-organization", + new: false, + }, + applications: [ + { + id: "5eb2eda8ba4ce1723926cf49", + createdBy: null, + modifiedBy: null, + deletedAt: null, + userPermissions: ["manage:applications"], + name: "ApplicationServiceTest TestApp", + organizationId: "5eb2eda5ba4ce1723926cf37", + pages: [ + { + id: "5eb2eda8ba4ce1723926cf4b", + isDefault: true, + }, + ], + new: false, + }, + { + id: "5eb2eda8ba4ce1723926cf4c", + createdBy: null, + modifiedBy: null, + deletedAt: null, + userPermissions: ["manage:applications", "read:applications"], + name: "NewValidUpdateApplication-Test", + organizationId: "5eb2eda5ba4ce1723926cf37", + pages: [ + { + id: "5eb2eda8ba4ce1723926cf4e", + isDefault: true, + }, + ], + new: false, + }, + { + id: "5eb2eda8ba4ce1723926cf4f", + createdBy: null, + modifiedBy: null, + deletedAt: null, + userPermissions: ["manage:applications", "read:applications"], + name: "validGetApplicationByName-Test", + organizationId: "5eb2eda5ba4ce1723926cf37", + pages: [ + { + id: "5eb2eda8ba4ce1723926cf51", + isDefault: true, + }, + ], + new: false, + }, + { + id: "5ebasdsadsaf", + createdBy: null, + modifiedBy: null, + deletedAt: null, + userPermissions: ["read:applications"], + name: "fourth", + organizationId: "dfsdfdcf37", + pages: [ + { + id: "5eb2eda8ba4ce17sdd23926cf51", + isDefault: true, + }, + ], + new: false, + }, + ], + }, + { + organization: { + id: "5eb2eda5ba4ce1723926cf36", + createdBy: null, + modifiedBy: null, + deletedAt: null, + userPermissions: ["read:organizations", "manage:orgApplications"], + domain: "appsmith-spring-test.com", + name: "Spring Test Organization", + website: "appsmith.com", + organizationSettings: null, + plugins: [ + { + id: null, + createdBy: null, + modifiedBy: null, + deletedAt: null, + userPermissions: [], + pluginId: "5eb2eda5ba4ce1723926cf30", + status: null, + new: true, + }, + ], + slug: "spring-test-organization", + new: false, + }, + applications: [ + { + id: "5eb2eda5ba4ce1723926cf3a", + createdBy: null, + modifiedBy: null, + deletedAt: null, + userPermissions: ["manage:applications", "read:applications"], + name: "Another TestApplications", + organizationId: "5eb2eda5ba4ce1723926cf36", + pages: [ + { + id: "5eb2eda8ba4ce17sdd23926cf51", + isDefault: true, + }, + ], + new: false, + }, + { + id: "5eb2eda5ba4ce1723926cf38", + createdBy: null, + modifiedBy: null, + deletedAt: null, + userPermissions: ["manage:applications", "read:applications"], + name: "LayoutServiceTest TestApplications", + organizationId: "5eb2eda5ba4ce1723926cf36", + pages: null, + new: false, + }, + { + id: "5eb2eda5ba4ce1723926cf39", + createdBy: null, + modifiedBy: null, + deletedAt: null, + userPermissions: ["manage:applications", "read:applications"], + name: "TestApplications", + organizationId: "5eb2eda5ba4ce1723926cf36", + pages: null, + new: false, + }, + ], + }, +]; + +export default organizationList; diff --git a/app/client/src/pages/Applications/ApplicationCard.tsx b/app/client/src/pages/Applications/ApplicationCard.tsx index e7f16e279ca9..c3b19680b441 100644 --- a/app/client/src/pages/Applications/ApplicationCard.tsx +++ b/app/client/src/pages/Applications/ApplicationCard.tsx @@ -12,13 +12,14 @@ import { theme, getBorderCSSShorthand, getColorWithOpacity, + Theme, } from "constants/DefaultTheme"; import ContextDropdown, { ContextDropdownOption, } from "components/editorComponents/ContextDropdown"; import { Colors } from "constants/Colors"; -const Wrapper = styled(Card)` +const Wrapper = styled(Card)<{ hasReadPermission?: boolean }>` display: flex; flex-direction: column; justify-content: center; @@ -35,9 +36,12 @@ const Wrapper = styled(Card)` top: 0; height: calc(100% - ${props => props.theme.card.titleHeight}px); width: 100%; + ${props => !props.hasReadPermission && `pointer-events: none;`} } a:hover { - text-decoration: none; + ${props => + props.hasReadPermission && + `text-decoration: none; &:after { left: 0; top: 0; @@ -49,13 +53,15 @@ const Wrapper = styled(Card)` & .control { display: block; z-index: 1; - } + }`} & div.image-container { background: ${props => - getColorWithOpacity( - props.theme.card.hoverBG, - props.theme.card.hoverBGOpacity, - )}; + props.hasReadPermission + ? getColorWithOpacity( + props.theme.card.hoverBG, + props.theme.card.hoverBGOpacity, + ) + : null}; } } `; @@ -132,6 +138,12 @@ type ApplicationCardProps = { }; export const ApplicationCard = (props: ApplicationCardProps) => { + const hasEditPermission = props.application.userPermissions?.includes( + "manage:applications", + ); + const hasReadPermission = props.application.userPermissions?.includes( + "read:applications", + ); const duplicateApp = () => { props.duplicate && props.duplicate(props.application.id); }; @@ -173,19 +185,22 @@ export const ApplicationCard = (props: ApplicationCardProps) => { props.application.id, props.application.defaultPageId, ); + return ( - <Wrapper key={props.application.id}> + <Wrapper key={props.application.id} hasReadPermission={hasReadPermission}> <ApplicationTitle className={props.loading ? Classes.SKELETON : undefined} > <span>{props.application.name}</span> - <Link to={editApplicationURL} className="t--application-edit-link"> - <Control className="control"> - <Tooltip content="Edit" hoverOpenDelay={500}> - {<Icon icon={"edit"} iconSize={14} color={Colors.HIT_GRAY} />} - </Tooltip> - </Control> - </Link> + {hasEditPermission && ( + <Link to={editApplicationURL} className="t--application-edit-link"> + <Control className="control"> + <Tooltip content="Edit" hoverOpenDelay={500}> + {<Icon icon={"edit"} iconSize={14} color={Colors.HIT_GRAY} />} + </Tooltip> + </Control> + </Link> + )} <ContextDropdown options={moreActionItems} toggle={{ diff --git a/app/client/src/pages/Applications/index.tsx b/app/client/src/pages/Applications/index.tsx index dcad4eeb5c2c..3d520b10df26 100644 --- a/app/client/src/pages/Applications/index.tsx +++ b/app/client/src/pages/Applications/index.tsx @@ -2,6 +2,7 @@ import React, { Component } from "react"; import styled from "styled-components"; import { connect } from "react-redux"; import { AppState } from "reducers"; +import { Card, Icon } from "@blueprintjs/core"; import { getApplicationList, getIsFetchingApplications, @@ -23,6 +24,8 @@ import { CREATE_APPLICATION_FORM_NAME } from "constants/forms"; import { DELETING_APPLICATION } from "constants/messages"; import { AppToaster } from "components/editorComponents/ToastComponent"; import AnalyticsUtil from "utils/AnalyticsUtil"; +import FormDialogComponent from "components/editorComponents/form/FormDialogComponent"; +import OrganizationListMockResponse from "mockResponses/OrganisationListResponse"; const ApplicationCardsWrapper = styled.div` display: flex; @@ -31,6 +34,30 @@ const ApplicationCardsWrapper = styled.div` align-items: space-evenly; `; +const Wrapper = styled(Card)` + display: flex; + flex-direction: column; + justify-content: center; + align-items: center; + width: ${props => props.theme.card.minWidth}px; + height: ${props => props.theme.card.minHeight}px; + position: relative; + border-radius: ${props => props.theme.radii[1]}px; + margin: ${props => props.theme.spaces[5]}px + ${props => props.theme.spaces[5]}px; + a { + display: block; + position: absolute; + left: 0; + top: 0; + height: calc(100% - ${props => props.theme.card.titleHeight}px); + width: 100%; + } + :hover { + cursor: pointer; + } +`; + type ApplicationProps = { applicationList: ApplicationPayload[]; fetchApplications: () => void; @@ -75,7 +102,53 @@ class Applications extends Component<ApplicationProps> { }} /> <PageSectionDivider /> - <ApplicationCardsWrapper> + {OrganizationListMockResponse.map((organizationObject: any) => { + const { organization, applications } = organizationObject; + const hasCreateApplicationPemission = organization.userPermissions.includes( + "manage:orgApplications", + ); + + return ( + <> + <p>{organization.name}</p> + <ApplicationCardsWrapper key={organization.id}> + {hasCreateApplicationPemission && ( + <FormDialogComponent + trigger={ + <Wrapper> + <Icon + icon="plus" + iconSize={20} + className="createIcon" + /> + </Wrapper> + } + Form={CreateApplicationForm} + title={"Create Application"} + /> + )} + {applications.map((application: any) => { + return ( + application.pages?.length > 0 && ( + <ApplicationCard + key={application.id} + loading={this.props.isFetchingApplications} + application={application} + delete={this.props.deleteApplication} + /> + ) + ); + })} + </ApplicationCardsWrapper> + </> + ); + })} + {/* <ApplicationCardsWrapper> + <FormDialogComponent + trigger={<Wrapper>Hello</Wrapper>} + Form={CreateApplicationForm} + title={"Create Application"} + /> {applicationList.map((application: ApplicationPayload) => { return ( application.pageCount > 0 && ( @@ -88,7 +161,7 @@ class Applications extends Component<ApplicationProps> { ) ); })} - </ApplicationCardsWrapper> + </ApplicationCardsWrapper> */} </PageWrapper> ); }
e9f079ea0350ab0587814bdca8fff0a35567e022
2021-09-08 12:20:21
arunvjn
fix: snippets meta and short title (#7216)
false
snippets meta and short title (#7216)
fix
diff --git a/app/client/src/components/editorComponents/GlobalSearch/SearchResults.tsx b/app/client/src/components/editorComponents/GlobalSearch/SearchResults.tsx index 73b6918f7f99..bbdf1d796c3c 100644 --- a/app/client/src/components/editorComponents/GlobalSearch/SearchResults.tsx +++ b/app/client/src/components/editorComponents/GlobalSearch/SearchResults.tsx @@ -369,10 +369,10 @@ function CategoryItem({ function SnippetItem({ item: { - body: { title }, + body: { shortTitle, title }, }, }: any) { - return <span>{title}</span>; + return <span>{shortTitle || title}</span>; } const SearchItemByType = { diff --git a/app/client/src/components/editorComponents/GlobalSearch/SnippetRefinements.tsx b/app/client/src/components/editorComponents/GlobalSearch/SnippetRefinements.tsx index 166b8d501d1c..72c5f8e3ca38 100644 --- a/app/client/src/components/editorComponents/GlobalSearch/SnippetRefinements.tsx +++ b/app/client/src/components/editorComponents/GlobalSearch/SnippetRefinements.tsx @@ -2,6 +2,7 @@ import React from "react"; import { connectCurrentRefinements } from "react-instantsearch-dom"; import styled from "styled-components"; import { ReactComponent as CloseIcon } from "assets/icons/help/close_blue.svg"; +import { getSnippetFilterLabel } from "./utils"; const RefinementListContainer = styled.div` background: ${(props) => props.theme.colors.globalSearch.primaryBgColor}; @@ -41,7 +42,7 @@ const RefinementListContainer = styled.div` function RefinementPill({ item, refine }: any) { return ( <div className="refinement-pill"> - <span>{item.label}</span> + <span>{getSnippetFilterLabel(item.label)}</span> <CloseIcon onClick={(event) => { event.preventDefault(); diff --git a/app/client/src/components/editorComponents/GlobalSearch/SnippetsDescription.tsx b/app/client/src/components/editorComponents/GlobalSearch/SnippetsDescription.tsx index b9728a4455ff..2bf5ed28dc83 100644 --- a/app/client/src/components/editorComponents/GlobalSearch/SnippetsDescription.tsx +++ b/app/client/src/components/editorComponents/GlobalSearch/SnippetsDescription.tsx @@ -168,15 +168,7 @@ export const getSnippet = (snippet: string, args: any) => { export default function SnippetDescription({ item }: { item: Snippet }) { const { - body: { - additionalInfo, - args, - isTrigger, - snippet, - summary, - template, - title, - }, + body: { args, isTrigger, snippet, snippetMeta, summary, template, title }, dataType, language, } = item; @@ -276,16 +268,26 @@ export default function SnippetDescription({ item }: { item: Snippet }) { key: "Snippet", title: "Snippet", panelComponent: ( - <div className="snippet-container"> - <SyntaxHighlighter language={language} style={prism}> - {js_beautify(snippet, { indent_size: 2 })} - </SyntaxHighlighter> - <div className="action-icons"> - <CopyIcon - onClick={() => handleCopy(`{{ ${getSnippet(snippet, {})} }}`)} - /> + <> + {snippetMeta && ( + <div className="snippet-group"> + <div + className="content" + dangerouslySetInnerHTML={{ __html: snippetMeta }} + /> + </div> + )} + <div className="snippet-container"> + <SyntaxHighlighter language={language} style={prism}> + {js_beautify(snippet, { indent_size: 2 })} + </SyntaxHighlighter> + <div className="action-icons"> + <CopyIcon + onClick={() => handleCopy(`{{ ${getSnippet(snippet, {})} }}`)} + /> + </div> </div> - </div> + </> ), }, ]; @@ -391,13 +393,6 @@ export default function SnippetDescription({ item }: { item: Snippet }) { tabs={tabs} /> </TabbedViewContainer> - {additionalInfo && - additionalInfo.map(({ content, header }) => ( - <div className="snippet-group" key={header}> - <div className="header">{header}</div> - <div className="content">{content}</div> - </div> - ))} </SnippetContainer> ); } diff --git a/app/client/src/components/editorComponents/GlobalSearch/SnippetsFilter.tsx b/app/client/src/components/editorComponents/GlobalSearch/SnippetsFilter.tsx index a7ed6d822388..4aa650680021 100644 --- a/app/client/src/components/editorComponents/GlobalSearch/SnippetsFilter.tsx +++ b/app/client/src/components/editorComponents/GlobalSearch/SnippetsFilter.tsx @@ -4,6 +4,7 @@ import styled from "styled-components"; import { ReactComponent as FilterIcon } from "assets/icons/menu/filter.svg"; import { ReactComponent as CloseFilterIcon } from "assets/icons/menu/close-filter.svg"; import AnalyticsUtil from "utils/AnalyticsUtil"; +import { getSnippetFilterLabel } from "./utils"; const SnippetsFilterContainer = styled.div<{ showFilter: boolean; @@ -172,6 +173,12 @@ function SnippetsFilter({ refinements, snippetsEmpty }: any) { <RefinementList attribute="entities" defaultRefinement={refinements.entities || []} + transformItems={(items: any) => + items.map((item: any) => ({ + ...item, + label: getSnippetFilterLabel(item.label), + })) + } /> </div> {showSnippetFilter && ( diff --git a/app/client/src/components/editorComponents/GlobalSearch/utils.tsx b/app/client/src/components/editorComponents/GlobalSearch/utils.tsx index ab732a6650de..f99ab51fc936 100644 --- a/app/client/src/components/editorComponents/GlobalSearch/utils.tsx +++ b/app/client/src/components/editorComponents/GlobalSearch/utils.tsx @@ -11,6 +11,8 @@ import { useEffect, useState } from "react"; import { fetchRawGithubContentList } from "./githubHelper"; import getFeatureFlags from "utils/featureFlags"; import { modText } from "./HelpBar"; +import { WidgetType } from "constants/WidgetConstants"; +import { ENTITY_TYPE } from "entities/DataTree/dataTreeFactory"; export type SelectEvent = | React.MouseEvent @@ -76,12 +78,26 @@ export type SnippetBody = { args: [SnippetArgument]; summary: string; template: string; - additionalInfo?: [ - { - header: string; - content: string; - }, - ]; + snippetMeta?: string; + shortTitle?: string; +}; + +export type FilterEntity = WidgetType | ENTITY_TYPE; + +//holds custom labels for snippet filters. +export const SnippetFilterLabel: Partial<Record<FilterEntity, string>> = { + DROP_DOWN_WIDGET: "Dropdown", +}; + +export const getSnippetFilterLabel = (label: string) => { + return ( + SnippetFilterLabel[label as FilterEntity] || + label + .toLowerCase() + .replace("_widget", "") + .replace("-plugin", "") + .replaceAll(/_|-/g, " ") + ); }; export type SnippetArgument = { diff --git a/app/client/src/sagas/ActionSagas.ts b/app/client/src/sagas/ActionSagas.ts index 9d781632085e..687ee52d74f9 100644 --- a/app/client/src/sagas/ActionSagas.ts +++ b/app/client/src/sagas/ActionSagas.ts @@ -112,6 +112,7 @@ import { onQueryEditor, } from "components/editorComponents/Debugger/helpers"; import { Plugin } from "api/PluginApi"; +import { FlattenedWidgetProps } from "reducers/entityReducers/canvasWidgetsReducer"; export function* createActionSaga( actionPayload: ReduxAction< @@ -785,27 +786,21 @@ function* buildMetaForSnippets( .pop(); fieldMeta.fields = `${relevantField}<score=2>`; } - let currentEntity, type; if (entityType === ENTITY_TYPE.ACTION && entityId) { - currentEntity = yield select(getActionById, { + const currentEntity: Action = yield select(getActionById, { match: { params: { apiId: entityId } }, }); - const plugin = yield select(getPlugin, currentEntity.pluginId); - type = (plugin.packageName || "") - .toLowerCase() - .replace("-plugin", "") - .split("-") - .join(" "); - refinements.entities = [entityType.toLowerCase()].concat(type); + const plugin: Plugin = yield select(getPlugin, currentEntity.pluginId); + const type: string = plugin.packageName || ""; + refinements.entities = [entityType, type]; } if (entityType === ENTITY_TYPE.WIDGET && entityId) { - currentEntity = yield select(getWidgetById, entityId); - type = (currentEntity.type || "") - .replace("_WIDGET", "") - .toLowerCase() - .split("_") - .join(""); - refinements.entities = [type]; + const currentEntity: FlattenedWidgetProps = yield select( + getWidgetById, + entityId, + ); + const type: string = currentEntity.type || ""; + refinements.entities = [entityType, type]; } return { refinements, fieldMeta }; } @@ -822,11 +817,11 @@ function* getCurrentEntity( onQueryEditor(applicationId, pageId) ) { const id = params.apiId || params.queryId; - const action = yield select(getAction, id); - entityId = action.actionId; + const action: Action = yield select(getAction, id); + entityId = action.id; entityType = ENTITY_TYPE.ACTION; } else { - const widget = yield select(getSelectedWidget); + const widget: FlattenedWidgetProps = yield select(getSelectedWidget); entityId = widget.widgetId; entityType = ENTITY_TYPE.WIDGET; } @@ -840,8 +835,8 @@ function* executeCommand( args: any; }>, ) { - const pageId = yield select(getCurrentPageId); - const applicationId = yield select(getCurrentApplicationId); + const pageId: string = yield select(getCurrentPageId); + const applicationId: string = yield select(getCurrentApplicationId); const params = getQueryParams(); switch (actionPayload.payload.actionType) { case "NEW_SNIPPET": @@ -850,11 +845,10 @@ function* executeCommand( // Entity is derived using the dataTreePath property. // Fallback to find current entity when dataTreePath property value is empty (Eg. trigger fields) if (!entityId) { - const currentEntity = yield getCurrentEntity( - applicationId, - pageId, - params, - ); + const currentEntity: { + entityId: string; + entityType: string; + } = yield getCurrentEntity(applicationId, pageId, params); entityId = currentEntity.entityId; entityType = currentEntity.entityType; } diff --git a/app/client/src/sagas/js_snippets.json b/app/client/src/sagas/js_snippets.json index 7f5996e9a032..ee893dadea47 100644 --- a/app/client/src/sagas/js_snippets.json +++ b/app/client/src/sagas/js_snippets.json @@ -1,12 +1,15 @@ [ { "entities": [ - "list", - "table" + "LIST_WIDGET", + "TABLE_WIDGET" ], "language": "javascript", "dataType": "ARRAY", + "fields": [], "body": { + "snippetMeta": "", + "shortTitle": "", "title": "Filter data based on a particular value when binding data from an array", "snippet": "let data = [{\"hero\": \"Iron Man\",\"team\": \"Avengers\",\"skills\": \"Superhuman strength\"}, {\"hero\": \"Bat Man\", \"team\": \"Justice League\", \"skills\": \"Gadgets\" }, {\"hero\": \"Aqua Man\", \"team\": \"Justice League\", \"skills\": \"endurance\" }, {\"hero\": \"Captain America\", \"team\": \"Avengers\", \"skills\": \"endurance\" }]; filtered_data = data.filter((item) => { return item[\"team\"] == \"Avengers\"; });", "template": "{{data}}.filter((item) => {return item[{{key}}] === {{value}};});", @@ -25,23 +28,20 @@ "type": "VAR" } ], - "summary": "Merge data from two entities into a single response", - "additionalInfo": [ - { - "title": "", - "content": "" - } - ] + "summary": "Merge data from two entities into a single response" } }, { "entities": [ - "list", - "table" + "LIST_WIDGET", + "TABLE_WIDGET" ], "language": "javascript", "dataType": "STRING", + "fields": [], "body": { + "snippetMeta": "", + "shortTitle": "", "title": "Access attributes from a nested data", "template": "{{your_object}}.{{key}}", "args": [ @@ -56,23 +56,20 @@ ], "isTrigger": false, "summary": "When you have objects or arrays nested inside each other, you can use the dot operator to access items inside them and return them onto the table or list widget.", - "additionalInfo": [ - { - "title": "", - "content": "" - } - ], "snippet": "let nested_data = {\"data\": {\"heros_data\": [{\"hero\": \"Iron Man\", \"team\": \"Avengers\", \"skills\": \"Superhuman strength\" }, {\"hero\": \"Bat Man\", \"team\": \"Justice League\", \"skills\": \"Gadgets\" }, {\"hero\": \"Aqua Man\",\"team\": \"Justice League\", \"skills\": \"endurance\" }, {\"hero\": \"Captain America\", \"team\": \"Avengers\", \"skills\": \"endurance\" }] }}heros_data = nested_data.data.heros_data;" } }, { "entities": [ - "list", - "table" + "LIST_WIDGET", + "TABLE_WIDGET" ], "language": "javascript", "dataType": "STRING", + "fields": [], "body": { + "snippetMeta": "", + "shortTitle": "", "title": "Add colours to data inside table columns based on certain conditions", "template": "(function columnColor() { let colors = { {{columnValue1}}: {{color1}}, {{columnValue2}}: {{color2}}, }; return colors[{{tableName}}.selectedRow[{{columnName}}]]; })()", "isTrigger": false, @@ -103,23 +100,20 @@ } ], "summary": "You can have custom styles such as colours and backgrounds in your table widget on a particular column. Choose the column you want, open the column settings and use the following snippet in Cell Background or Text Color property.", - "additionalInfo": [ - { - "title": "", - "content": "" - } - ], "snippet": "//Javascript for Cell Background or Text Color property\n(function columnColor() {let colors = {\"True\": \"green\",\"False\": \"Red\"};return colors[currentRow[\"status\"]];})()" } }, { "entities": [ - "list", - "table" + "LIST_WIDGET", + "TABLE_WIDGET" ], "language": "javascript", "dataType": "ARRAY", + "fields": [], "body": { + "snippetMeta": "", + "shortTitle": "", "title": "Merge multiple objects from queries into a single array", "template": "{{your_array}}.concat({{Obj1}}, {{Obj2}});", "args": [ @@ -138,44 +132,38 @@ ], "isTrigger": false, "summary": "If you have multiple objects from Queries with the same key\"s and want to bind them in a list or table widget, you can use the concat() method.", - "additionalInfo": [ - { - "title": "", - "content": "" - } - ], "snippet": "/* Query #1 Data: Avengers\n [ { hero: \"Bat Man\", team: \"Justice League\", skills: \"Gadgets\", }, { hero: \"Aqua Man\", team: \"Justice League\", skills: \"endurance\", }, ] \nQuery #2 Data: justice_league\n [ { hero: \"Iron Man\", team: \"Avengers\", skills: \"Superhuman strength\", }, { hero: \"Captain America\", team: \"Avengers\", skills: \"endurance\", }, ] */let heros = avengers.concat(justice_league);" } }, { "entities": [ - "list", - "table" + "LIST_WIDGET", + "TABLE_WIDGET" ], "language": "javascript", "dataType": "STRING", + "fields": [], "body": { + "snippetMeta": "", + "shortTitle": "", "title": "Parsing through nested JSON data inside an array of objects", "template": "currentRow.columnName.{{key}}.{{key}}", "isTrigger": false, "summary": "If the values in the data are dense JSON, you could parse them into your columns inside the Table widget or bind them onto the List widget. For this, you\"ll have to open the property pane on the Table widget and go to the column settings and update the ComputedValue. Similarly, on the list widget, you could use the currentItem property and parse through JSON.", - "additionalInfo": [ - { - "title": "", - "content": "" - } - ], "snippet": "// When using Notion API, to bind title from a Notion table,\n// the following has to be used inside the Title computed Value.\ncurrentRow.Title.title[0].plain_text" } }, { "entities": [ - "list", - "table" + "LIST_WIDGET", + "TABLE_WIDGET" ], "language": "javascript", "dataType": "ARRAY", + "fields": [], "body": { + "snippetMeta": "", + "shortTitle": "", "title": "Removing duplicate values from an array", "template": "(function(){let JSONObject = {{your_array}}.map(JSON.stringify);let uniqueSet = new Set(JSONObject);let uniqueArray = Array.from(uniqueSet).map(JSON.parse);return uniqueArray;})()", "isTrigger": false, @@ -186,22 +174,19 @@ } ], "summary": "When binding array data into a table widget or list widget, you may encounter duplicate values. You can use the following snippet to only bind unique values.", - "additionalInfo": [ - { - "title": "", - "content": "" - } - ], "snippet": "(function(){let heroes = [{ hero: \"Iron Man\", team: \"Avengers\", skills: \"Superhuman strength\", }, { hero: \"Bat Man\", team: \"Justice League\", skills: \"Gadgets\", }, { hero: \"Iron Man\", team: \"Avengers\", skills: \"Superhuman strength\", }, { hero: \"Bat Man\", team: \"Justice League\", skills: \"Gadgets\", }, { hero: \"Aqua Man\", team: \"Justice League\", skills: \"endurance\" }, { hero: \"Captain America\", team: \"Avengers\", skills: \"endurance\", }]; let JSONObject = heroes.map(JSON.stringify); let uniqueSet = new Set(JSONObject); let uniqueArray = Array.from(uniqueSet).map(JSON.parse); return uniqueArray; })()" } }, { "entities": [ - "dropdown" + "DROP_DOWN_WIDGET" ], "language": "javascript", "dataType": "ARRAY", + "fields": [], "body": { + "snippetMeta": "", + "shortTitle": "", "title": "Creating a select widget options list from a query", "template": "{{queryData}}.map((item) => { return { label: item.{{attribute1}}, value: item.{{attribute2}} }; });", "isTrigger": false, @@ -220,23 +205,20 @@ } ], "summary": "When you want to create an option list from an API or DB Query, which contains an array of object\"s you can use the `map()` function and return the options in an array in the following format:`Array<{ label: string, value: string }>`", - "additionalInfo": [ - { - "title": "", - "content": "" - } - ], "snippet": "(function () {let skills = [\"strength\",\"speed\",\"durability\",\"agility\",\"reflexes\"];let options_list = skills.map((item) => {return { label: item, value: item, };});return options_list;})()" } }, { "entities": [ - "dropdown", + "DROP_DOWN_WIDGET", "workflow" ], "language": "javascript", "dataType": "FUNCTION", + "fields": [], "body": { + "snippetMeta": "", + "shortTitle": "", "title": "Updating queries when options are changed from the select widget", "template": "{{selectBox}}.selectedOptionValue === {{value}} ? {{QueryOne}}.run() : {{QueryTwo}}.run()", "args": [ @@ -259,22 +241,19 @@ ], "isTrigger": false, "summary": "Based on the updated option on the select widget, you can call or execute an API. For this, you\"ll need to define a workflow in the onOptionChange property with JavaScript.", - "additionalInfo": [ - { - "title": "", - "content": "" - } - ], "snippet": "/* If the selected option in the Select widget is User then fetch_users query is executed, else fetch_products query is executed. */\nSelect1.selectedOptionValue === \"User\" ? fetch_users.run() : fetch_products.run()" } }, { "entities": [ - "checkbox" + "CHECKBOX_WIDGET" ], "language": "javascript", "dataType": "STRING", + "fields": [], "body": { + "snippetMeta": "", + "shortTitle": "", "title": "Setting default value of checkbox based on a query", "template": "{{query}}.{{key}}", "isTrigger": false, @@ -289,29 +268,20 @@ } ], "summary": "To configure the default value of the checkbox widget with a particular query, you can use javascript and return the state of the checkbox.", - "additionalInfo": [ - { - "title": "", - "content": "" - } - ], "snippet": "function() {let iron_man = { hero: \"Iron Man\", team: \"Avengers\", skills: \"Superhuman strength\", status: true, };return iron_man.status; }()" } }, { "entities": [ - "datepicker" + "DATEPICKER_WIDGET" ], "language": "javascript", "dataType": "STRING", + "fields": [], "body": { + "snippetMeta": "", + "shortTitle": "", "title": "Select current date in the date picker widget", - "additionalInfo": [ - { - "title": "", - "content": "" - } - ], "snippet": "moment.now()", "isTrigger": false, "summary": "By default, if you want to assign the date picker value to the current date, you can use moment.now() method. " @@ -319,11 +289,14 @@ }, { "entities": [ - "datepicker" + "DATEPICKER_WIDGET" ], "language": "javascript", "dataType": "STRING", + "fields": [], "body": { + "snippetMeta": "", + "shortTitle": "", "title": "Formatting date inside the data picker widget", "template": "moment({{date}}).format({{dateFormat}})", "args": [ @@ -338,29 +311,20 @@ ], "isTrigger": false, "summary": "If you want to change the format of the date object from a query, you can use moment.javascript and covert it into the desired format.", - "additionalInfo": [ - { - "title": "", - "content": "" - } - ], "snippet": "moment(\"2021-06-28 12:28:33 PM\").format(\"LL\")" } }, { "entities": [ - "text" + "TEXT_WIDGET" ], "language": "javascript", "dataType": "STRING", + "fields": [], "body": { + "snippetMeta": "", + "shortTitle": "", "title": "Binding current time in the text widget", - "additionalInfo": [ - { - "title": "", - "content": "" - } - ], "snippet": "moment.now()", "isTrigger": false, "summary": "Sometimes, you need to display time when building UI, especially when building dashboards. On Appsmith, you can utilise the moment.javascript library to either display the current time or format any date-time type from a query." @@ -368,11 +332,14 @@ }, { "entities": [ - "text" + "TEXT_WIDGET" ], "language": "javascript", "dataType": "STRING", + "fields": [], "body": { + "snippetMeta": "", + "shortTitle": "", "title": "Binding an object onto the text widget", "template": "(function() { let my_object = {{my_object}};let my_string = Object.entries(my_object).map( ([key, value]) => `${key}: ${value}`).join(\"\\n\");return my_string;})()", "isTrigger": false, @@ -383,42 +350,36 @@ } ], "summary": "Text Widget allows you to bind data from the APIs. When they are strings, we could directly bind them using the dot operator, but when you need the entire object with key-value pairs listed on the text widget you\"ll need to use the Object.entries method.", - "additionalInfo": [ - { - "title": "", - "content": "" - } - ], "snippet": "(function(){let my_object = {\"AC\": \"True\", \"Parking\": \"True\", \"WiFi\": \"False\"};let my_string = Object.entries(my_object).map( ([key, value]) => `${key}: ${value}`).join(\"\\n\");return my_string;})()" } }, { "entities": [ - "text" + "TEXT_WIDGET" ], "language": "javascript", "dataType": "STRING", + "fields": [], "body": { + "snippetMeta": "", + "shortTitle": "", "title": "Bind a variable dynamically on the text widget", "isTrigger": false, "summary": "When you want any variable onto the text widget, you can use the snippets literals in JavaScript.", - "additionalInfo": [ - { - "title": "", - "content": "" - } - ], "snippet": "(function(){let invoice_total = 120;let text = `The total amount on the invoice is ${invoice_total}`;return text;})()" } }, { "entities": [ - "button", + "BUTTON_WIDGET", "workflow" ], "language": "javascript", "dataType": "FUNCTION", + "fields": [], "body": { + "snippetMeta": "", + "shortTitle": "", "title": "Configuring multiple actions on button click", "template": "{{query1}}.run(() => {showAlert({{successMessage}}, \"info\");storeValue({{key}}, {{queryData}});navigateTo({{pageName}});});", "isTrigger": true, @@ -445,12 +406,6 @@ } ], "summary": "You can configure multiple actions for buttons in Appsmith. For this, you\"ll need to use javascript in the onClick property and use the necessary methods. The following snippet does the following when clicked.", - "additionalInfo": [ - { - "title": "", - "content": "" - } - ], "snippet": "getUsers.run(() => {showAlert(\"Query Executed\", \"info\");storeValue(\"name\", getUsers.data[0].name);navigateTo(\"#Page2\"));});" } }, @@ -461,7 +416,10 @@ ], "language": "javascript", "dataType": "FUNCTION", + "fields": [], "body": { + "snippetMeta": "", + "shortTitle": "", "title": "Open a modal and run a query on button click", "template": "showModal({{modalName}});{{query}}.run();", "isTrigger": true, @@ -476,12 +434,6 @@ } ], "summary": "To open a new Modal on button click and run a query, you can use javascript in the onClick property. This can be handy when you want to render any data on the Modal.", - "additionalInfo": [ - { - "title": "", - "content": "" - } - ], "snippet": "showModal('Modal1');getUsers.run()" } }, @@ -492,7 +444,10 @@ ], "language": "javascript", "dataType": "FUNCTION", + "fields": [], "body": { + "snippetMeta": "", + "shortTitle": "", "title": "Run an API, close modal and show alert", "template": "{{query}}.run(() => {closeModal({{modalName}});showAlert({{alertMessage}});})", "isTrigger": true, @@ -511,24 +466,21 @@ } ], "summary": "", - "additionalInfo": [ - { - "title": "", - "content": "" - } - ], "snippet": "getUsers.run(() => {closeModal(\"Modal1\");showAlert(\"Success\");})" } }, { "entities": [ "action", - "button", + "BUTTON_WIDGET", "workflow" ], "language": "javascript", "dataType": "FUNCTION", + "fields": [], "body": { + "snippetMeta": "", + "shortTitle": "", "title": "Running multiple queries in series", "template": "{{query1}}.run(() => {{query2}}.run(() => {{query3}}.run()));", "isTrigger": true, @@ -547,24 +499,21 @@ } ], "summary": "If you want to run two APIs in series on button click, page-load or any other actions, you can use javascript to define a workflow. For this, you\"ll need to update the properties with javascript.", - "additionalInfo": [ - { - "title": "", - "content": "" - } - ], "snippet": "getAvengers.run(() => getLeague.run(() => getRangers.run()));" } }, { "entities": [ "action", - "button", + "BUTTON_WIDGET", "workflow" ], "language": "javascript", "dataType": "FUNCTION", + "fields": [], "body": { + "snippetMeta": "", + "shortTitle": "", "title": "Running multiple queries in parallel", "template": "{{query1}}.run();{{query2}}.run();", "isTrigger": true, @@ -579,12 +528,6 @@ } ], "summary": "If you want to run two APIs in parallel on button click, page-load or any other actions, you can use javascript to define a workflow. For this, you\"ll need to update the properties with javascript.", - "additionalInfo": [ - { - "title": "", - "content": "" - } - ], "snippet": "getAvengers.run(); getLeague.run();" } }, @@ -595,7 +538,10 @@ ], "language": "javascript", "dataType": "FUNCTION", + "fields": [], "body": { + "snippetMeta": "", + "shortTitle": "", "title": "Displaying alerts for workflows", "template": "{{query1}}.run(() => {{{query2}}.run(() => {showAlert({{successMessage}}); },() => showAlert({{errorMessage}}) );},() => showAlert({{errorMessage}}, \"error\"));", "isTrigger": true, @@ -618,12 +564,6 @@ } ], "summary": "You might often want to notify users with alerts, after executing queries or when performing certain actions on Appsmith. To do this, you can use showAlert method with javascript.", - "additionalInfo": [ - { - "title": "", - "content": "" - } - ], "snippet": "updateUsers.run(() => {fetchUsers.run(() => {showAlert(\"User Updated\"); },() => showAlert(\"Fetch Users Failed\") );},() => showAlert(\"Update User Failed\", \"error\"));" } }, @@ -634,14 +574,11 @@ ], "language": "sql", "dataType": "STRING", + "fields": [], "body": { + "snippetMeta": "", + "shortTitle": "", "title": "Query data from Postgres table", - "additionalInfo": [ - { - "title": "", - "content": "" - } - ], "snippet": "SELECT * FROM table_name", "isTrigger": false, "args": [ @@ -660,14 +597,11 @@ ], "language": "sql", "dataType": "STRING", + "fields": [], "body": { + "snippetMeta": "", + "shortTitle": "", "title": "PostgreSQL SELECT statement to query data from multiple columns", - "additionalInfo": [ - { - "title": "", - "content": "" - } - ], "snippet": "SELECT column1, column2, column3 FROM table_name", "isTrigger": false, "args": [ @@ -698,14 +632,11 @@ ], "language": "sql", "dataType": "STRING", + "fields": [], "body": { + "snippetMeta": "", + "shortTitle": "", "title": "PostgreSQL SELECT statement to query data from one column", - "additionalInfo": [ - { - "title": "", - "content": "" - } - ], "snippet": "SELECT column_name FROM table_name", "isTrigger": false, "args": [ @@ -728,14 +659,11 @@ ], "language": "sql", "dataType": "STRING", + "fields": [], "body": { + "snippetMeta": "", + "shortTitle": "", "title": "Ordering table data in ascending order", - "additionalInfo": [ - { - "title": "", - "content": "" - } - ], "snippet": "SELECT column1, column2 FROM table_name ORDER BY column1 ASC;", "examples": [ { @@ -769,14 +697,11 @@ ], "language": "sql", "dataType": "STRING", + "fields": [], "body": { + "snippetMeta": "", + "shortTitle": "", "title": "Ordering table data in descending order", - "additionalInfo": [ - { - "title": "", - "content": "" - } - ], "snippet": "SELECT column1, column2 FROM table_name ORDER BY column1 DESC;", "examples": [ { @@ -810,14 +735,11 @@ ], "language": "sql", "dataType": "STRING", + "fields": [], "body": { + "snippetMeta": "", + "shortTitle": "", "title": "Ordering table data based on the length of column value", - "additionalInfo": [ - { - "title": "", - "content": "" - } - ], "snippet": "SELECT column1, LENGTH(column1) len FROM table_name ORDER BY len DESC;", "examples": [ {
e5e6989c0a3f4812fde999c27c0a516db3c15156
2024-10-18 01:52:58
pewpewXD
fix: edit and launch button fail on keeping mouse over while reload (#36954)
false
edit and launch button fail on keeping mouse over while reload (#36954)
fix
diff --git a/app/client/src/components/common/Card.tsx b/app/client/src/components/common/Card.tsx index cb77fd8d7ed2..bc6e4a8d05bf 100644 --- a/app/client/src/components/common/Card.tsx +++ b/app/client/src/components/common/Card.tsx @@ -336,14 +336,14 @@ function Card({ className={testId} hasReadPermission={hasReadPermission} isContextMenuOpen={isContextMenuOpen} - onMouseEnter={() => { - !isFetching && setShowOverlay(true); - }} onMouseLeave={() => { // If the menu is not open, then setOverlay false // Set overlay false on outside click. !isContextMenuOpen && setShowOverlay(false); }} + onMouseOver={() => { + !isFetching && setShowOverlay(true); + }} showOverlay={showOverlay} testId={testId} >
9979d241a2d7ac8e886896e2afae67a7b34e8919
2024-07-15 15:34:59
NandanAnantharamu
test: fixed failing GitImport test (#34589)
false
fixed failing GitImport test (#34589)
test
diff --git a/app/client/cypress/e2e/Regression/ClientSide/Git/GitImport/GitImport_spec.js b/app/client/cypress/e2e/Regression/ClientSide/Git/GitImport/GitImport_spec.js index a8c658419161..80f564b873ed 100644 --- a/app/client/cypress/e2e/Regression/ClientSide/Git/GitImport/GitImport_spec.js +++ b/app/client/cypress/e2e/Regression/ClientSide/Git/GitImport/GitImport_spec.js @@ -54,8 +54,7 @@ describe("Git import flow ", { tags: ["@tag.Git"] }, function () { cy.wait(1000); dataSources.FillMongoDSForm(); cy.testDatasource(true); - agHelper.GetNClick(dataSources._saveDs); - cy.wait(2000); + dataSources.SaveDatasource(true); cy.wait("@getWorkspace"); cy.get(reconnectDatasourceModal.ImportSuccessModal).should("be.visible"); cy.get(reconnectDatasourceModal.ImportSuccessModalCloseBtn).click({ @@ -118,7 +117,7 @@ describe("Git import flow ", { tags: ["@tag.Git"] }, function () { cy.wait(3000); //for uncommited changes to appear if any! cy.get("body").then(($body) => { if ($body.find(gitSyncLocators.gitPullCount).length > 0) { - cy.commitAndPush(); + gitSync.CommitAndPush(); } }); }); @@ -170,8 +169,7 @@ describe("Git import flow ", { tags: ["@tag.Git"] }, function () { agHelper.AssertElementExist(gitSync._bottomBarPull); cy.get(gitSyncLocators.closeGitSyncModal).click(); cy.wait(2000); - cy.merge(mainBranch); - cy.get(gitSyncLocators.closeGitSyncModal).click(); + gitSync.MergeToMaster(); cy.wait(2000); cy.latestDeployPreview(); table.AssertTableLoaded(); @@ -211,7 +209,7 @@ describe("Git import flow ", { tags: ["@tag.Git"] }, function () { cy.wait(2000); // wait for transition cy.dragAndDropToCanvas("buttonwidget", { x: 300, y: 600 }); cy.wait(3000); - cy.commitAndPush(); + gitSync.CommitAndPush(); cy.merge(newBranch); cy.get(gitSyncLocators.closeGitSyncModal).click(); cy.wait(2000);
3e0749c82f3c8205f4898d7b2b37337d2e166e9f
2022-01-25 15:15:52
ankurrsinghal
fix: hover highlight for menu item (#10610)
false
hover highlight for menu item (#10610)
fix
diff --git a/app/client/src/components/ads/TreeDropdown.tsx b/app/client/src/components/ads/TreeDropdown.tsx index 8538c94d04ed..1e5f37a5314e 100644 --- a/app/client/src/components/ads/TreeDropdown.tsx +++ b/app/client/src/components/ads/TreeDropdown.tsx @@ -87,7 +87,7 @@ const StyledMenu = styled(Menu)` } } - &:hover :not(.t--apiFormDeleteBtn) { + &:hover:not(.t--apiFormDeleteBtn) { background-color: ${Colors.GREY_3}; color: ${Colors.GREY_10}; .${Classes.ICON} > svg:not([fill]) {
5f1e4d1ba8fca10e959a856eac730e2fccca798c
2023-04-10 17:41:14
Aishwarya-U-R
test: Cypress - flaky fix + Git comment improve (#22169)
false
Cypress - flaky fix + Git comment improve (#22169)
test
diff --git a/.github/workflows/integration-tests-command.yml b/.github/workflows/integration-tests-command.yml index 492e0876f598..06ea450fca45 100644 --- a/.github/workflows/integration-tests-command.yml +++ b/.github/workflows/integration-tests-command.yml @@ -168,7 +168,18 @@ jobs: Workflow run: <${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}>. Commit: `${{ github.event.client_payload.slash_command.args.named.sha }}`. The following are new failures, please fix them before merging the PR: ${{env.new_failed_spec_env}} - <a href="#" onclick='window.open("https://app.appsmith.com/applications/613868bedd7786286ddd4a6a/pages/63ec710e8e503f763651791a");return false;'>Identified Flaky tests</a> + <a href="https://app.appsmith.com/applications/613868bedd7786286ddd4a6a/pages/63ec710e8e503f763651791a" target="_blank">Identified Flaky tests</a> + + - name: Add a comment on the PR when ci-test is success + if: needs.ci-test.result == 'success' + uses: peter-evans/create-or-update-comment@v1 + with: + issue-number: ${{ github.event.client_payload.pull_request.number }} + body: | + Workflow run: <${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}>. + Commit: `${{ github.event.client_payload.slash_command.args.named.sha }}`. + All cypress tests have passed 🎉 + # Update check run called "ci-test-result" - name: Mark ci-test-result job as complete diff --git a/app/client/cypress/integration/Regression_TestSuite/ClientSideTests/Linting/BasicLint_spec.ts b/app/client/cypress/integration/Regression_TestSuite/ClientSideTests/Linting/BasicLint_spec.ts index 3b72bbbba92d..7f207e5d7023 100644 --- a/app/client/cypress/integration/Regression_TestSuite/ClientSideTests/Linting/BasicLint_spec.ts +++ b/app/client/cypress/integration/Regression_TestSuite/ClientSideTests/Linting/BasicLint_spec.ts @@ -35,6 +35,7 @@ const clickButtonAndAssertLintError = ( //Reload and Check for presence/ absence of lint error agHelper.RefreshPage(); + agHelper.AssertElementVisible(locator._visibleTextDiv("Explorer")); ee.SelectEntityByName("Button1", "Widgets"); shouldExist ? agHelper.AssertElementExist(locator._lintErrorElement) diff --git a/app/client/cypress/integration/Regression_TestSuite/ServerSideTests/Datasources/Firestore_Basic_Spec.ts b/app/client/cypress/integration/Regression_TestSuite/ServerSideTests/Datasources/Firestore_Basic_Spec.ts index 5e44734652ed..3163d6407383 100644 --- a/app/client/cypress/integration/Regression_TestSuite/ServerSideTests/Datasources/Firestore_Basic_Spec.ts +++ b/app/client/cypress/integration/Regression_TestSuite/ServerSideTests/Datasources/Firestore_Basic_Spec.ts @@ -1,6 +1,6 @@ import * as _ from "../../../../support/Objects/ObjectsCore"; -let dsName: any, cities: any, losAngelesPath: any, insertedRecordId: any; +let dsName: any, cities: any, losAngelesPath: any; describe("Validate Firestore DS", () => { before("Create a new Firestore DS", () => { _.dataSources.CreateDataSource("Firestore"); @@ -28,6 +28,14 @@ describe("Validate Firestore DS", () => { directInput: false, inputFieldName: "Collection Name", }); + _.agHelper.TypeDynamicInputValueNValidate( + "name", + _.dataSources._nestedWhereClauseKey(0), + ); + _.agHelper.TypeDynamicInputValueNValidate( + "San Francisco", + _.dataSources._nestedWhereClauseValue(0), + ); _.dataSources.RunQuery(); cy.get("@postExecute").then((resObj: any) => { cities = JSON.parse(JSON.stringify(resObj.response.body.data.body)); @@ -35,9 +43,10 @@ describe("Validate Firestore DS", () => { cy.wrap(cities) .should("be.an", "array") .its(0) - .should("have.property", "name", "San Francisco"); //making sure inserted record is returned + .should("have.property", "name", "San Francisco"); //making sure already inserted record is returned }); + _.agHelper.GetNClick(_.dataSources._whereDelete(0)); //removign where clause, add new _.agHelper.TypeDynamicInputValueNValidate( "capital", _.dataSources._nestedWhereClauseKey(0), @@ -201,7 +210,6 @@ describe("Validate Firestore DS", () => { directInput: false, inputFieldName: "Collection Name", }); - _.agHelper.EnterValue('["population"]', { propFieldName: "", directInput: false,
1afd223e10a61db916c3c91ddd73daf10ada02d8
2023-10-16 13:32:27
arunvjn
fix: Race condition in JS object mutation (#28083)
false
Race condition in JS object mutation (#28083)
fix
diff --git a/app/client/cypress/e2e/Regression/ClientSide/JSObject/JSObjectMutation_spec.ts b/app/client/cypress/e2e/Regression/ClientSide/JSObject/JSObjectMutation_spec.ts index 3488d7a6e5a0..52b60ccbf0fa 100644 --- a/app/client/cypress/e2e/Regression/ClientSide/JSObject/JSObjectMutation_spec.ts +++ b/app/client/cypress/e2e/Regression/ClientSide/JSObject/JSObjectMutation_spec.ts @@ -90,4 +90,52 @@ describe("JSObject testing", () => { expect($label).contains("[]"); }); }); + + it("6. Bug 27978 Check assignment should not get overridden by evaluation", () => { + _.entityExplorer.DragNDropWidget(_.draggableWidgets.TEXT, 400, 400); + _.propPane.TypeTextIntoField( + "Text", + `{{JSObject1.data.length ? 'id-' + JSObject1.data[0].id : 'Not Set' }}`, + true, + false, + ); + _.entityExplorer.NavigateToSwitcher("Explorer"); + _.apiPage.CreateAndFillApi( + _.dataManager.dsValues[_.dataManager.defaultEnviorment].mockApiUrl, + ); + const JS_OBJECT_BODY = `export default { + data: [], + async getData() { + await Api1.run() + return Api1.data + }, + async myFun1() { + this.data = await this.getData(); + console.log(this.data); + }, + async myFun2() { + const data = await this.getData(); + data.push({ name: "test123" }) + this.data = data; + console.log(this.data); + }, + }`; + _.jsEditor.CreateJSObject(JS_OBJECT_BODY, { + paste: true, + completeReplace: true, + toRun: false, + shouldCreateNewJSObj: true, + }); + _.jsEditor.SelectFunctionDropdown("myFun1"); + _.jsEditor.RunJSObj(); + _.entityExplorer.SelectEntityByName("Text2", "Widgets"); + _.agHelper.AssertContains("id-1"); + cy.reload(); + _.agHelper.AssertContains("Not Set"); + _.entityExplorer.SelectEntityByName("JSObject1", "Queries/JS"); + _.jsEditor.SelectFunctionDropdown("myFun2"); + _.jsEditor.RunJSObj(); + _.entityExplorer.SelectEntityByName("Text2", "Widgets"); + _.agHelper.AssertContains("id-1"); + }); }); diff --git a/app/client/src/ce/actions/evaluationActions.ts b/app/client/src/ce/actions/evaluationActions.ts index 2504d7b1be94..8bb299de5467 100644 --- a/app/client/src/ce/actions/evaluationActions.ts +++ b/app/client/src/ce/actions/evaluationActions.ts @@ -66,8 +66,6 @@ export const EVALUATE_REDUX_ACTIONS = [ ReduxActionTypes.MOVE_ACTION_SUCCESS, ReduxActionTypes.RUN_ACTION_SUCCESS, ReduxActionErrorTypes.RUN_ACTION_ERROR, - ReduxActionTypes.EXECUTE_PLUGIN_ACTION_SUCCESS, - ReduxActionErrorTypes.EXECUTE_PLUGIN_ACTION_ERROR, ReduxActionTypes.CLEAR_ACTION_RESPONSE, // JS Actions ReduxActionTypes.CREATE_JS_ACTION_SUCCESS, diff --git a/app/client/src/workers/Evaluation/JSObject/Collection.ts b/app/client/src/workers/Evaluation/JSObject/Collection.ts index df62aedeb596..d2874a2f0b08 100644 --- a/app/client/src/workers/Evaluation/JSObject/Collection.ts +++ b/app/client/src/workers/Evaluation/JSObject/Collection.ts @@ -1,6 +1,20 @@ import { getEntityNameAndPropertyPath } from "@appsmith/workers/Evaluation/evaluationUtils"; import { klona } from "klona/full"; import { get, set } from "lodash"; +import TriggerEmitter, { BatchKey } from "../fns/utils/TriggerEmitter"; +import ExecutionMetaData from "../fns/utils/ExecutionMetaData"; +import type { JSActionEntity } from "@appsmith/entities/DataTree/types"; + +export enum PatchType { + "SET" = "SET", + "GET" = "GET", +} + +export interface Patch { + path: string; + method: PatchType; + value?: unknown; +} export type VariableState = Record<string, Record<string, any>>; @@ -61,6 +75,7 @@ export default class JSObjectCollection { const newVarState = { ...this.variableState[entityName] }; newVarState[propertyPath] = variableValue; this.variableState[entityName] = newVarState; + JSObjectCollection.clearCachedVariablesForEvaluationContext(entityName); } static getVariableState( @@ -77,6 +92,53 @@ export default class JSObjectCollection { delete jsObject[propertyPath]; } + /**Map<JSObjectName, Map<variableName, variableValue> */ + static cachedJSVariablesByEntityName: Record<string, JSActionEntity> = {}; + + /**Computes Map<JSObjectName, Map<variableName, variableValue> with getters & setters to track JS mutations + * We cache and reuse this map. We recreate only when the JSObject's content changes or when any of the variables + * gets evaluated + */ + static getVariablesForEvaluationContext(entityName: string) { + if (JSObjectCollection.cachedJSVariablesByEntityName[entityName]) + return JSObjectCollection.cachedJSVariablesByEntityName[entityName]; + const varState = JSObjectCollection.getVariableState(entityName); + const variables = Object.entries(varState); + const newJSObject = {} as JSActionEntity; + + for (const [varName, varValue] of variables) { + let variable = varValue; + Object.defineProperty(newJSObject, varName, { + enumerable: true, + configurable: true, + get() { + TriggerEmitter.emit(BatchKey.process_js_variable_updates, { + path: `${entityName}.${varName}`, + method: PatchType.GET, + }); + return variable; + }, + set(value) { + TriggerEmitter.emit(BatchKey.process_js_variable_updates, { + path: `${entityName}.${varName}`, + method: PatchType.SET, + value, + }); + variable = value; + }, + }); + } + ExecutionMetaData.setExecutionMetaData({ + enableJSVarUpdateTracking: true, + }); + JSObjectCollection.cachedJSVariablesByEntityName[entityName] = newJSObject; + return JSObjectCollection.cachedJSVariablesByEntityName[entityName]; + } + + static clearCachedVariablesForEvaluationContext(entityName: string) { + delete JSObjectCollection.cachedJSVariablesByEntityName[entityName]; + } + static clear() { this.variableState = {}; this.unEvalState = {}; diff --git a/app/client/src/workers/Evaluation/JSObject/JSVariableFactory.ts b/app/client/src/workers/Evaluation/JSObject/JSVariableFactory.ts deleted file mode 100644 index 1922f98a6399..000000000000 --- a/app/client/src/workers/Evaluation/JSObject/JSVariableFactory.ts +++ /dev/null @@ -1,52 +0,0 @@ -import { PatchType } from "./JSVariableUpdates"; -import ExecutionMetaData from "../fns/utils/ExecutionMetaData"; -import type { JSActionEntity } from "@appsmith/entities/DataTree/types"; -import TriggerEmitter, { BatchKey } from "../fns/utils/TriggerEmitter"; - -class JSFactory { - static create( - jsObjectName: string, - varState: Record<string, unknown> = {}, - ): JSActionEntity { - const newJSObject: any = {}; - - const variables = Object.entries(varState); - - for (const [varName, varValue] of variables) { - let variable = varValue; - Object.defineProperty(newJSObject, varName, { - enumerable: true, - configurable: true, - get() { - TriggerEmitter.emit(BatchKey.process_js_variable_updates, { - path: `${jsObjectName}.${varName}`, - method: PatchType.GET, - }); - return variable; - }, - set(value) { - TriggerEmitter.emit(BatchKey.process_js_variable_updates, { - path: `${jsObjectName}.${varName}`, - method: PatchType.SET, - value, - }); - variable = value; - }, - }); - - ExecutionMetaData.setExecutionMetaData({ - enableJSVarUpdateTracking: false, - }); - - newJSObject[varName] = varValue; - - ExecutionMetaData.setExecutionMetaData({ - enableJSVarUpdateTracking: true, - }); - } - - return newJSObject; - } -} - -export default JSFactory; diff --git a/app/client/src/workers/Evaluation/JSObject/JSVariableUpdates.ts b/app/client/src/workers/Evaluation/JSObject/JSVariableUpdates.ts index d15265aeaf22..3d2638abba81 100644 --- a/app/client/src/workers/Evaluation/JSObject/JSVariableUpdates.ts +++ b/app/client/src/workers/Evaluation/JSObject/JSVariableUpdates.ts @@ -5,17 +5,8 @@ import { evalTreeWithChanges } from "../evalTreeWithChanges"; import { get } from "lodash"; import { isJSObjectVariable } from "./utils"; import isDeepEqualES6 from "fast-deep-equal/es6"; - -export enum PatchType { - "SET" = "SET", - "GET" = "GET", -} - -export interface Patch { - path: string; - method: PatchType; - value?: unknown; -} +import type { Patch } from "./Collection"; +import { PatchType } from "./Collection"; export type UpdatedPathsMap = Record<string, Patch>; diff --git a/app/client/src/workers/Evaluation/JSObject/__test__/JSVariableFactory.test.ts b/app/client/src/workers/Evaluation/JSObject/__test__/JSVariableFactory.test.ts index f7e0355b7076..80191e1c6d11 100644 --- a/app/client/src/workers/Evaluation/JSObject/__test__/JSVariableFactory.test.ts +++ b/app/client/src/workers/Evaluation/JSObject/__test__/JSVariableFactory.test.ts @@ -1,9 +1,9 @@ -import JSFactory from "../JSVariableFactory"; import ExecutionMetaData from "workers/Evaluation/fns/utils/ExecutionMetaData"; import type { JSActionEntity } from "@appsmith/entities/DataTree/types"; import TriggerEmitter, { jsVariableUpdatesHandlerWrapper, } from "workers/Evaluation/fns/utils/TriggerEmitter"; +import JSObjectCollection from "../Collection"; const applyJSVariableUpdatesToEvalTreeMock = jest.fn(); jest.mock("../JSVariableUpdates.ts", () => ({ @@ -36,7 +36,12 @@ describe("JSVariableFactory", () => { weakSet: new WeakSet(), } as unknown as JSActionEntity; - const proxiedJSObject = JSFactory.create("JSObject1", jsObject); + Object.entries(jsObject).forEach(([k, v]) => + JSObjectCollection.setVariableValue(v, `JSObject1.${k}`), + ); + + const proxiedJSObject = + JSObjectCollection.getVariablesForEvaluationContext("JSObject1"); ExecutionMetaData.setExecutionMetaData({ enableJSVarUpdateTracking: true, @@ -96,7 +101,12 @@ describe("JSVariableFactory", () => { weakSet: new WeakSet(), } as unknown as JSActionEntity; - const proxiedJSObject = JSFactory.create("JSObject1", jsObject); + Object.entries(jsObject).forEach(([k, v]) => + JSObjectCollection.setVariableValue(v, `JSObject1.${k}`), + ); + + const proxiedJSObject = + JSObjectCollection.getVariablesForEvaluationContext("JSObject1"); ExecutionMetaData.setExecutionMetaData({ enableJSVarUpdateTracking: false, @@ -125,7 +135,12 @@ describe("JSVariableFactory", () => { weakSet: new WeakSet(), } as unknown as JSActionEntity; - const proxiedJSObject = JSFactory.create("JSObject1", jsObject); + Object.entries(jsObject).forEach(([k, v]) => + JSObjectCollection.setVariableValue(v, `JSObject1.${k}`), + ); + + const proxiedJSObject = + JSObjectCollection.getVariablesForEvaluationContext("JSObject1"); ExecutionMetaData.setExecutionMetaData({ enableJSVarUpdateTracking: true, diff --git a/app/client/src/workers/Evaluation/JSObject/index.ts b/app/client/src/workers/Evaluation/JSObject/index.ts index a1af115b2a4e..56ac11224f5f 100644 --- a/app/client/src/workers/Evaluation/JSObject/index.ts +++ b/app/client/src/workers/Evaluation/JSObject/index.ts @@ -92,6 +92,7 @@ export function saveResolvedFunctionsAndJSUpdates( try { JSObjectCollection.deleteResolvedFunction(entityName); JSObjectCollection.deleteUnEvalState(entityName); + JSObjectCollection.clearCachedVariablesForEvaluationContext(entityName); const parseStartTime = performance.now(); const { parsedObject, success } = parseJSObject(entity.body); diff --git a/app/client/src/workers/Evaluation/fns/utils/TriggerEmitter.ts b/app/client/src/workers/Evaluation/fns/utils/TriggerEmitter.ts index 7d50754db0c8..95ba119c3612 100644 --- a/app/client/src/workers/Evaluation/fns/utils/TriggerEmitter.ts +++ b/app/client/src/workers/Evaluation/fns/utils/TriggerEmitter.ts @@ -1,10 +1,7 @@ import { EventEmitter } from "events"; import { MAIN_THREAD_ACTION } from "@appsmith/workers/Evaluation/evalWorkerActions"; import { WorkerMessenger } from "workers/Evaluation/fns/utils/Messenger"; -import type { - Patch, - UpdatedPathsMap, -} from "workers/Evaluation/JSObject/JSVariableUpdates"; +import type { UpdatedPathsMap } from "workers/Evaluation/JSObject/JSVariableUpdates"; import { applyJSVariableUpdatesToEvalTree } from "workers/Evaluation/JSObject/JSVariableUpdates"; import ExecutionMetaData from "./ExecutionMetaData"; import { get } from "lodash"; @@ -18,6 +15,7 @@ import type { import type { UpdateActionProps } from "workers/Evaluation/handlers/updateActionData"; import { handleActionsDataUpdate } from "workers/Evaluation/handlers/updateActionData"; import { getEntityNameAndPropertyPath } from "@appsmith/workers/Evaluation/evaluationUtils"; +import type { Patch } from "workers/Evaluation/JSObject/Collection"; const _internalSetTimeout = self.setTimeout; const _internalClearTimeout = self.clearTimeout; diff --git a/app/client/src/workers/Evaluation/getEntityForContext.ts b/app/client/src/workers/Evaluation/getEntityForContext.ts index 35b5bc46dbed..8037878d7666 100644 --- a/app/client/src/workers/Evaluation/getEntityForContext.ts +++ b/app/client/src/workers/Evaluation/getEntityForContext.ts @@ -2,7 +2,6 @@ import type { JSActionEntity } from "@appsmith/entities/DataTree/types"; import type { DataTreeEntity } from "entities/DataTree/dataTreeTypes"; import { ENTITY_TYPE_VALUE } from "entities/DataTree/dataTreeFactory"; import JSObjectCollection from "./JSObject/Collection"; -import JSFactory from "./JSObject/JSVariableFactory"; import { jsObjectFunctionFactory } from "./fns/utils/jsObjectFnFactory"; import { isObject } from "lodash"; @@ -53,7 +52,8 @@ export function getEntityForEvalContext( return Object.assign({}, jsObject, fns); } - jsObjectForEval = JSFactory.create(entityName, jsObjectForEval); + jsObjectForEval = + JSObjectCollection.getVariablesForEvaluationContext(entityName); return Object.assign(jsObjectForEval, fns); } }
df626137092a35db04a3a1ff38144b84ea3842d7
2023-03-22 19:49:27
PiyushPushkar02
chore: JUnit TC For Many Form Update (#21671)
false
JUnit TC For Many Form Update (#21671)
chore
diff --git a/app/server/appsmith-plugins/mongoPlugin/src/test/java/com/external/plugins/MongoPluginFormsTest.java b/app/server/appsmith-plugins/mongoPlugin/src/test/java/com/external/plugins/MongoPluginFormsTest.java index 0762244e53aa..164cc99b464a 100644 --- a/app/server/appsmith-plugins/mongoPlugin/src/test/java/com/external/plugins/MongoPluginFormsTest.java +++ b/app/server/appsmith-plugins/mongoPlugin/src/test/java/com/external/plugins/MongoPluginFormsTest.java @@ -495,6 +495,69 @@ public void testUpdateManyFormCommand() { } @Test + public void testUpdateManyFormCommandWithArrayInput() { + ActionConfiguration actionConfiguration = new ActionConfiguration(); + + Map<String, Object> configMap = new HashMap<>(); + setDataValueSafelyInFormData(configMap, SMART_SUBSTITUTION, Boolean.FALSE); + setDataValueSafelyInFormData(configMap, COMMAND, "UPDATE"); + setDataValueSafelyInFormData(configMap, COLLECTION, "users"); + // Query for all the documents in the collection + setDataValueSafelyInFormData(configMap, UPDATE_QUERY, "{}"); + setDataValueSafelyInFormData(configMap, UPDATE_OPERATION, "[{ \"$set\": { \"department\": \"app\" } }" + + ",{ \"$set\": { \"department\": \"design\" } }]"); + setDataValueSafelyInFormData(configMap, UPDATE_LIMIT, "ALL"); + + actionConfiguration.setFormData(configMap); + + DatasourceConfiguration dsConfig = createDatasourceConfiguration(); + Mono<MongoClient> dsConnectionMono = pluginExecutor.datasourceCreate(dsConfig); + Mono<Object> executeMono = dsConnectionMono.flatMap(conn -> pluginExecutor.executeParameterized(conn, + new ExecuteActionDTO(), dsConfig, actionConfiguration)); + StepVerifier.create(executeMono) + .assertNext(obj -> { + ActionExecutionResult result = (ActionExecutionResult) obj; + assertNotNull(result); + assertTrue(result.getIsExecutionSuccess()); + assertNotNull(result.getBody()); + JsonNode value = ((ObjectNode) result.getBody()).get("nModified"); + assertEquals("3", value.asText()); + assertEquals( + List.of(new ParsedDataType(JSON), new ParsedDataType(RAW)) + .toString(), + result.getDataTypes().toString()); + }) + .verifyComplete(); + + //After update fetching to document to verify if the value is updated properly + ActionConfiguration actionConfiguration1 = new ActionConfiguration(); + Map<String, Object> configMap1 = new HashMap<>(); + setDataValueSafelyInFormData(configMap1, SMART_SUBSTITUTION, Boolean.FALSE); + setDataValueSafelyInFormData(configMap1, COMMAND, "FIND"); + setDataValueSafelyInFormData(configMap1, COLLECTION, "users"); + // Query for all the documents in the collection + setDataValueSafelyInFormData(configMap1, FIND_QUERY, "{\"department\":\"design\"}"); + actionConfiguration1.setFormData(configMap1); + Mono<Object> executeMono1 = dsConnectionMono.flatMap(conn -> pluginExecutor.executeParameterized(conn, + new ExecuteActionDTO(), dsConfig, actionConfiguration1)); + StepVerifier.create(executeMono1) + .assertNext(obj -> { + ActionExecutionResult result = (ActionExecutionResult) obj; + assertNotNull(result); + assertTrue(result.getIsExecutionSuccess()); + assertNotNull(result.getBody()); + int value =((ArrayNode)result.getBody()).size(); + assertEquals(3, value); + assertEquals( + List.of(new ParsedDataType(JSON), new ParsedDataType(RAW)) + .toString(), + result.getDataTypes().toString()); + }) + .verifyComplete(); + } + + + @Test public void testDeleteFormCommandSingleDocument() { DatasourceConfiguration dsConfig = createDatasourceConfiguration(); Mono<MongoClient> dsConnectionMono = pluginExecutor.datasourceCreate(dsConfig);
f4bcb69589451adb0fcd10ae4571bb196090a718
2022-01-06 22:07:51
haojin111
fix: issue with merge button not visible after switching branches post merge, handle merge error (#10141)
false
issue with merge button not visible after switching branches post merge, handle merge error (#10141)
fix
diff --git a/app/client/src/pages/Editor/gitSync/Tabs/Merge.tsx b/app/client/src/pages/Editor/gitSync/Tabs/Merge.tsx index a081d9c0d2f7..4824c072ca02 100644 --- a/app/client/src/pages/Editor/gitSync/Tabs/Merge.tsx +++ b/app/client/src/pages/Editor/gitSync/Tabs/Merge.tsx @@ -22,6 +22,7 @@ import { getGitBranches, getGitStatus, getIsFetchingGitStatus, + getMergeError, getMergeStatus, } from "selectors/gitSyncSelectors"; import { DropdownOptions } from "../../GeneratePage/components/constants"; @@ -87,6 +88,7 @@ export default function Merge() { const isFetchingMergeStatus = useSelector(getIsFetchingMergeStatus); const mergeStatus = useSelector(getMergeStatus); const gitStatus: any = useSelector(getGitStatus); + const mergeError = useSelector(getMergeError); const isMergeAble = mergeStatus?.isMergeAble && gitStatus?.isClean; const isFetchingGitStatus = useSelector(getIsFetchingGitStatus); let mergeStatusMessage = !gitStatus?.isClean @@ -191,6 +193,7 @@ export default function Merge() { destinationBranch: selectedBranchOption.value, }), ); + setShowMergeSuccessIndicator(false); } }, [currentBranch, selectedBranchOption.value, dispatch]); @@ -212,10 +215,15 @@ export default function Merge() { status = MERGE_STATUS_STATE.MERGEABLE; } else if (mergeStatus && !mergeStatus?.isMergeAble) { status = MERGE_STATUS_STATE.NOT_MERGEABLE; + } else if (mergeError) { + status = MERGE_STATUS_STATE.ERROR; + mergeStatusMessage = mergeError.error.message; } + // should check after added error code for conflicting const isConflicting = (mergeStatus?.conflictingFiles?.length || 0) > 0; - const showMergeButton = !isConflicting && !isFetchingGitStatus && !isMerging; + const showMergeButton = + !isConflicting && !mergeError && !isFetchingGitStatus && !isMerging; return ( <> diff --git a/app/client/src/pages/Editor/gitSync/components/BranchList.tsx b/app/client/src/pages/Editor/gitSync/components/BranchList.tsx index 0140d4663eed..43999e0d1e71 100644 --- a/app/client/src/pages/Editor/gitSync/components/BranchList.tsx +++ b/app/client/src/pages/Editor/gitSync/components/BranchList.tsx @@ -158,7 +158,7 @@ function CreateNewBranch({ onClick={onClick} style={{ alignItems: "flex-start", - cursor: "pointer", + cursor: isCreatingNewBranch ? "not-allowed" : "pointer", display: "flex", background: hovered ? Colors.GREY_3 : "unset", padding: get(theme, "spaces[5]"), @@ -411,6 +411,7 @@ export default function BranchList(props: { const [isCreatingNewBranch, setIsCreatingNewBranch] = useState(false); const handleCreateNewBranch = () => { + if (isCreatingNewBranch) return; const branch = searchText; setIsCreatingNewBranch(true); dispatch( diff --git a/app/client/src/pages/Editor/gitSync/components/MergeStatus.tsx b/app/client/src/pages/Editor/gitSync/components/MergeStatus.tsx index aab80550f04d..3c716d4d4273 100644 --- a/app/client/src/pages/Editor/gitSync/components/MergeStatus.tsx +++ b/app/client/src/pages/Editor/gitSync/components/MergeStatus.tsx @@ -15,6 +15,7 @@ export const MERGE_STATUS_STATE = { MERGEABLE: "MERGEABLE", NOT_MERGEABLE: "NOT_MERGEABLE", NONE: "NONE", + ERROR: "ERROR", }; const Wrapper = styled.div` @@ -54,6 +55,7 @@ function MergeStatus({ </Flex> ); case MERGE_STATUS_STATE.NOT_MERGEABLE: + case MERGE_STATUS_STATE.ERROR: return ( <Flex> <Wrapper> diff --git a/app/client/src/reducers/uiReducers/gitSyncReducer.ts b/app/client/src/reducers/uiReducers/gitSyncReducer.ts index b6fc3877de37..5128dfe16c7f 100644 --- a/app/client/src/reducers/uiReducers/gitSyncReducer.ts +++ b/app/client/src/reducers/uiReducers/gitSyncReducer.ts @@ -273,6 +273,7 @@ const gitSyncReducer = createReducer(initialState, { isFetchingMergeStatus: true, connectError: null, commitAndPushError: null, + mergeStatus: null, pullError: null, mergeError: null, }), @@ -324,10 +325,12 @@ const gitSyncReducer = createReducer(initialState, { [ReduxActionTypes.MERGE_BRANCH_INIT]: (state: GitSyncReducerState) => ({ ...state, isMerging: true, + mergeError: null, }), [ReduxActionTypes.MERGE_BRANCH_SUCCESS]: (state: GitSyncReducerState) => ({ ...state, isMerging: false, + mergeError: null, }), [ReduxActionErrorTypes.MERGE_BRANCH_ERROR]: ( state: GitSyncReducerState, diff --git a/app/client/src/selectors/gitSyncSelectors.tsx b/app/client/src/selectors/gitSyncSelectors.tsx index 658a4ffc31ae..c0c2feed5c20 100644 --- a/app/client/src/selectors/gitSyncSelectors.tsx +++ b/app/client/src/selectors/gitSyncSelectors.tsx @@ -122,6 +122,8 @@ export const getIsMergeInProgress = (state: AppState) => export const getTempRemoteUrl = (state: AppState) => state.ui.gitSync.tempRemoteUrl; +export const getMergeError = (state: AppState) => state.ui.gitSync.mergeError; + export const getCountOfChangesToCommit = (state: AppState) => { const gitStatus = getGitStatus(state); const { modifiedPages = 0, modifiedQueries = 0 } = gitStatus || {};
c59a1179445acf9fdb8663b14e90e52f1120dc56
2024-03-05 10:35:26
Apeksha Bhosale
fix: small modification for unavailable jsArguments on EE while importing JS module instance (#31469)
false
small modification for unavailable jsArguments on EE while importing JS module instance (#31469)
fix
diff --git a/app/client/src/ce/entities/DataTree/dataTreeJSAction.ts b/app/client/src/ce/entities/DataTree/dataTreeJSAction.ts index cc2744344098..e5be318cf22f 100644 --- a/app/client/src/ce/entities/DataTree/dataTreeJSAction.ts +++ b/app/client/src/ce/entities/DataTree/dataTreeJSAction.ts @@ -44,7 +44,7 @@ export const generateDataTreeJSAction = ( for (let i = 0; i < actions.length; i++) { const action = actions[i]; meta[action.name] = { - arguments: action.actionConfiguration.jsArguments, + arguments: action.actionConfiguration?.jsArguments, confirmBeforeExecute: !!action.confirmBeforeExecute, }; bindingPaths[action.name] = EvaluationSubstitutionType.SMART_SUBSTITUTE;
d9fa049578222574ef87e9a975a06d1773331730
2021-09-27 12:00:04
Aswath K
fix: Button variant validation (#7699)
false
Button variant validation (#7699)
fix
diff --git a/app/client/src/widgets/ButtonWidget/widget/index.tsx b/app/client/src/widgets/ButtonWidget/widget/index.tsx index 266c34f6d058..cd97c3cca328 100644 --- a/app/client/src/widgets/ButtonWidget/widget/index.tsx +++ b/app/client/src/widgets/ButtonWidget/widget/index.tsx @@ -12,6 +12,7 @@ import { ButtonBorderRadius, ButtonBorderRadiusTypes, ButtonVariant, + ButtonVariantTypes, } from "components/constants"; class ButtonWidget extends BaseWidget<ButtonWidgetProps, ButtonWidgetState> { @@ -147,12 +148,13 @@ class ButtonWidget extends BaseWidget<ButtonWidgetProps, ButtonWidgetState> { }, ], isJSConvertible: true, - isBindProperty: false, + isBindProperty: true, isTriggerProperty: false, validation: { type: ValidationTypes.TEXT, params: { - allowedVAlues: ["SOLID", "OUTLINE", "GHOST"], + default: ButtonVariantTypes.SOLID, + allowedValues: ["SOLID", "OUTLINE", "GHOST"], }, }, }, diff --git a/app/client/src/widgets/MenuButtonWidget/widget/index.tsx b/app/client/src/widgets/MenuButtonWidget/widget/index.tsx index 1eb957f09ae2..a851361d578c 100644 --- a/app/client/src/widgets/MenuButtonWidget/widget/index.tsx +++ b/app/client/src/widgets/MenuButtonWidget/widget/index.tsx @@ -9,6 +9,7 @@ import { ButtonBorderRadius, ButtonBoxShadow, ButtonVariant, + ButtonVariantTypes, } from "components/constants"; import { IconName } from "@blueprintjs/icons"; export interface MenuButtonWidgetProps extends WidgetProps { @@ -245,12 +246,13 @@ class MenuButtonWidget extends BaseWidget<MenuButtonWidgetProps, WidgetState> { }, ], isJSConvertible: true, - isBindProperty: false, + isBindProperty: true, isTriggerProperty: false, validation: { type: ValidationTypes.TEXT, params: { - allowedVAlues: ["SOLID", "OUTLINE", "GHOST"], + default: ButtonVariantTypes.SOLID, + allowedValues: ["SOLID", "OUTLINE", "GHOST"], }, }, },
e2c2996bc28c1747029ec0de0253c72552efa1d7
2023-03-03 13:43:17
Hetu Nandu
fix: Optimise Modal open performance (#21103)
false
Optimise Modal open performance (#21103)
fix
diff --git a/app/client/src/pages/Editor/WidgetsEditor/index.tsx b/app/client/src/pages/Editor/WidgetsEditor/index.tsx index 8ccbe6f3e6aa..6b907a62aff4 100644 --- a/app/client/src/pages/Editor/WidgetsEditor/index.tsx +++ b/app/client/src/pages/Editor/WidgetsEditor/index.tsx @@ -4,7 +4,6 @@ import { useDispatch, useSelector } from "react-redux"; import { getCurrentPageId, getCurrentPageName, - getIsFetchingPage, } from "selectors/editorSelectors"; import PageTabs from "./PageTabs"; import PerformanceTracker, { @@ -12,7 +11,6 @@ import PerformanceTracker, { } from "utils/PerformanceTracker"; import AnalyticsUtil from "utils/AnalyticsUtil"; import CanvasContainer from "./CanvasContainer"; -import { quickScrollToWidget } from "utils/helpers"; import Debugger from "components/editorComponents/Debugger"; import OnboardingTasks from "../FirstTimeUserOnboarding/Tasks"; import CrudInfoModal from "../GeneratePage/components/CrudInfoModal"; @@ -31,20 +29,16 @@ import PropertyPaneContainer from "./PropertyPaneContainer"; import CanvasTopSection from "./EmptyCanvasSection"; import { useAutoHeightUIState } from "utils/hooks/autoHeightUIHooks"; import { isMultiPaneActive } from "selectors/multiPaneSelectors"; -import { getCanvasWidgets } from "selectors/entitiesSelector"; -/* eslint-disable react/display-name */ function WidgetsEditor() { - const { deselectAll, focusWidget, selectWidget } = useWidgetSelection(); + const { deselectAll, focusWidget } = useWidgetSelection(); const dispatch = useDispatch(); const currentPageId = useSelector(getCurrentPageId); const currentPageName = useSelector(getCurrentPageName); const currentApp = useSelector(getCurrentApplication); - const isFetchingPage = useSelector(getIsFetchingPage); const showOnboardingTasks = useSelector(getIsOnboardingTasksView); const guidedTourEnabled = useSelector(inGuidedTour); const isMultiPane = useSelector(isMultiPaneActive); - const canvasWidgets = useSelector(getCanvasWidgets); useEffect(() => { PerformanceTracker.stopTracking(PerformanceTransactionName.CLOSE_SIDE_PANE); @@ -62,18 +56,6 @@ function WidgetsEditor() { } }, [currentPageName, currentPageId]); - // navigate to widget - useEffect(() => { - if ( - !isFetchingPage && - window.location.hash.length > 0 && - !guidedTourEnabled - ) { - const widgetIdFromURLHash = window.location.hash.slice(1); - quickScrollToWidget(widgetIdFromURLHash, canvasWidgets); - } - }, [isFetchingPage, selectWidget, guidedTourEnabled]); - const allowDragToSelect = useAllowEditorDragToSelect(); const { isAutoHeightWithLimitsChanging } = useAutoHeightUIState(); diff --git a/app/client/src/pages/common/CanvasArenas/hooks/useCanvasDragging.ts b/app/client/src/pages/common/CanvasArenas/hooks/useCanvasDragging.ts index caa08fe79db1..8a07b65652a1 100644 --- a/app/client/src/pages/common/CanvasArenas/hooks/useCanvasDragging.ts +++ b/app/client/src/pages/common/CanvasArenas/hooks/useCanvasDragging.ts @@ -574,7 +574,7 @@ export const useCanvasDragging = ( resetCanvasState(); } } - }, [isDragging, isResizing, blocksToDraw, snapRows, canExtend, scale]); + }, [isDragging, isResizing, blocksToDraw, snapRows, canExtend]); return { showCanvas: isDragging && !isResizing, }; diff --git a/app/client/src/sagas/WidgetSelectionSagas.ts b/app/client/src/sagas/WidgetSelectionSagas.ts index c8ee50345cd6..aeace15e12f5 100644 --- a/app/client/src/sagas/WidgetSelectionSagas.ts +++ b/app/client/src/sagas/WidgetSelectionSagas.ts @@ -50,7 +50,7 @@ import { shiftSelectWidgets, unselectWidget, } from "sagas/WidgetSelectUtils"; -import { flashElementsById, quickScrollToWidget } from "utils/helpers"; +import { quickScrollToWidget } from "utils/helpers"; import { areArraysEqual } from "utils/AppsmithUtils"; import { APP_MODE } from "entities/App"; @@ -272,13 +272,7 @@ function* focusOnWidgetSaga(action: ReduxAction<{ widgetIds: string[] }>) { } const allWidgets: CanvasWidgetsReduxState = yield select(getCanvasWidgets); if (widgetId) { - setTimeout(() => { - // Scrolling will hide some part of the content at the top during guided tour. To avoid that - // we skip scrolling altogether during guided tour as we don't have - // too many widgets during the same - flashElementsById(widgetId); - quickScrollToWidget(widgetId, allWidgets); - }, 0); + quickScrollToWidget(widgetId, allWidgets); } } diff --git a/app/client/src/utils/helpers.tsx b/app/client/src/utils/helpers.tsx index 91720af1cc81..b30c41e7b7a1 100644 --- a/app/client/src/utils/helpers.tsx +++ b/app/client/src/utils/helpers.tsx @@ -230,8 +230,7 @@ export const quickScrollToWidget = ( canvasWidgets: CanvasWidgetsReduxState, ) => { if (!widgetId || widgetId === "") return; - - setTimeout(() => { + window.requestIdleCallback(() => { const el = document.getElementById(widgetId); const canvas = document.getElementById("canvas-viewport"); @@ -245,7 +244,7 @@ export const quickScrollToWidget = ( }); } } - }, 200); + }); }; // Checks if the element in a container is visible or not. @@ -276,7 +275,9 @@ function getWidgetElementToScroll( const parentId = widget.parentId || ""; const containerId = getContainerIdForCanvas(parentId); if (containerId === MAIN_CONTAINER_WIDGET_ID) { - return document.getElementById(widgetId); + if (widget.type !== "MODAL_WIDGET") { + return document.getElementById(widgetId); + } } const containerWidget = canvasWidgets[containerId] as ContainerWidgetProps< WidgetProps
75b297201acd15347d509ad1a82aae0d2671c272
2023-07-21 11:23:17
Ayush Pahwa
chore: code splitting for multiple env feature (#25479)
false
code splitting for multiple env feature (#25479)
chore
diff --git a/app/client/cypress/e2e/Regression/Apps/PromisesApp_spec.js b/app/client/cypress/e2e/Regression/Apps/PromisesApp_spec.js index 395c85384c9f..2517cf8f439f 100644 --- a/app/client/cypress/e2e/Regression/Apps/PromisesApp_spec.js +++ b/app/client/cypress/e2e/Regression/Apps/PromisesApp_spec.js @@ -13,7 +13,10 @@ describe("JSEditor tests", function () { }); it("1. Testing promises with resetWidget, storeValue action and API call", () => { - apiPage.CreateAndFillApi(tedTestConfig.mockApiUrl, "TC1api"); + apiPage.CreateAndFillApi( + tedTestConfig.dsValues[tedTestConfig.defaultEnviorment].mockApiUrl, + "TC1api", + ); apiPage.RunAPI(); jsEditor.CreateJSObject( `export default { 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 35c7409395e8..e4c72bea8420 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 @@ -173,7 +173,9 @@ describe("Autocomplete tests", () => { }); it("5. Api data with array of object autocompletion test", () => { - apiPage.CreateAndFillApi(tedTestConfig.mockApiUrl); + apiPage.CreateAndFillApi( + tedTestConfig.dsValues[tedTestConfig.defaultEnviorment].mockApiUrl, + ); agHelper.Sleep(2000); apiPage.RunAPI(); // Using same js object diff --git a/app/client/cypress/e2e/Regression/ClientSide/Binding/JSObjectToListWidget_Spec.ts b/app/client/cypress/e2e/Regression/ClientSide/Binding/JSObjectToListWidget_Spec.ts index 1c575764a6dd..cd0fb039f548 100644 --- a/app/client/cypress/e2e/Regression/ClientSide/Binding/JSObjectToListWidget_Spec.ts +++ b/app/client/cypress/e2e/Regression/ClientSide/Binding/JSObjectToListWidget_Spec.ts @@ -7,7 +7,9 @@ describe("Validate JSObj binding to Table widget", () => { }); it("1. Add users api and bind to JSObject", () => { - _.apiPage.CreateAndFillApi(_.tedTestConfig.mockApiUrl); + _.apiPage.CreateAndFillApi( + _.tedTestConfig.dsValues[_.tedTestConfig.defaultEnviorment].mockApiUrl, + ); _.apiPage.RunAPI(); _.agHelper.GetNClick(_.dataSources._queryResponse("JSON")); _.apiPage.ReadApiResponsebyKey("name"); diff --git a/app/client/cypress/e2e/Regression/ClientSide/BugTests/ApiBugs_Spec.ts b/app/client/cypress/e2e/Regression/ClientSide/BugTests/ApiBugs_Spec.ts index 6f0bfd64fa95..85d575c4c275 100644 --- a/app/client/cypress/e2e/Regression/ClientSide/BugTests/ApiBugs_Spec.ts +++ b/app/client/cypress/e2e/Regression/ClientSide/BugTests/ApiBugs_Spec.ts @@ -26,7 +26,10 @@ describe("API Bugs", function () { agHelper.RefreshPage(); }); it("1. Bug 14037: User gets an error even when table widget is added from the API page successfully", function () { - apiPage.CreateAndFillApi(tedTestConfig.mockApiUrl, "Api1"); + apiPage.CreateAndFillApi( + tedTestConfig.dsValues[tedTestConfig.defaultEnviorment].mockApiUrl, + "Api1", + ); apiPage.RunAPI(); dataSources.AddSuggesstedWidget(Widgets.Table); @@ -54,7 +57,7 @@ describe("API Bugs", function () { it("3. Bug 18876 Ensures application does not crash when saving datasource", () => { apiPage.CreateAndFillApi( - tedTestConfig.mockApiUrl, + tedTestConfig.dsValues[tedTestConfig.defaultEnviorment].mockApiUrl, "FirstAPI", 10000, "POST", diff --git a/app/client/cypress/e2e/Regression/ClientSide/BugTests/Bug15056_Spec.ts b/app/client/cypress/e2e/Regression/ClientSide/BugTests/Bug15056_Spec.ts index ea93903ff528..113b19740265 100644 --- a/app/client/cypress/e2e/Regression/ClientSide/BugTests/Bug15056_Spec.ts +++ b/app/client/cypress/e2e/Regression/ClientSide/BugTests/Bug15056_Spec.ts @@ -12,7 +12,10 @@ describe("JS data update on button click", function () { }); it("1. Populates js function data when triggered via button click", function () { - apiPage.CreateAndFillApi(tedTestConfig.mockApiUrl, "Api1"); + apiPage.CreateAndFillApi( + tedTestConfig.dsValues[tedTestConfig.defaultEnviorment].mockApiUrl, + "Api1", + ); const jsObjectString = `export default { myVar1: [], diff --git a/app/client/cypress/e2e/Regression/ClientSide/BugTests/Bug16702_Spec.ts b/app/client/cypress/e2e/Regression/ClientSide/BugTests/Bug16702_Spec.ts index 1e0896d7754f..d495963b93dd 100644 --- a/app/client/cypress/e2e/Regression/ClientSide/BugTests/Bug16702_Spec.ts +++ b/app/client/cypress/e2e/Regression/ClientSide/BugTests/Bug16702_Spec.ts @@ -30,7 +30,10 @@ describe("Binding Expressions should not be truncated in Url and path extraction shouldCreateNewJSObj: true, }); - _.apiPage.CreateAndFillGraphqlApi(_.tedTestConfig.GraphqlApiUrl_TED); + _.apiPage.CreateAndFillGraphqlApi( + _.tedTestConfig.dsValues[_.tedTestConfig.defaultEnviorment] + .GraphqlApiUrl_TED, + ); _.dataSources.UpdateGraphqlQueryAndVariable({ query: GRAPHQL_LIMIT_QUERY, }); diff --git a/app/client/cypress/e2e/Regression/ClientSide/BugTests/Bug18035_Spec.ts b/app/client/cypress/e2e/Regression/ClientSide/BugTests/Bug18035_Spec.ts index c7b3426f8e88..453518f6163a 100644 --- a/app/client/cypress/e2e/Regression/ClientSide/BugTests/Bug18035_Spec.ts +++ b/app/client/cypress/e2e/Regression/ClientSide/BugTests/Bug18035_Spec.ts @@ -20,6 +20,8 @@ describe( //Create any other datasource, click on back button, discard popup should contain save dataSources.NavigateToDSCreateNew(); dataSources.CreatePlugIn("PostgreSQL"); + // Need to add values since without that, going back won't show any popup + dataSources.FillPostgresDSForm(); agHelper.GoBack(); agHelper.AssertContains( "Save", @@ -33,6 +35,7 @@ describe( dataSources.NavigateToDSCreateNew(); dataSources.CreatePlugIn("S3"); dataSources.TestDatasource(false); + dataSources.FillS3DSForm(); dataSources.SaveDSFromDialog(false); }); }, diff --git a/app/client/cypress/e2e/Regression/ClientSide/BugTests/Bug21734_Spec.ts b/app/client/cypress/e2e/Regression/ClientSide/BugTests/Bug21734_Spec.ts index 71663c9def2a..1eab4b0c889e 100644 --- a/app/client/cypress/e2e/Regression/ClientSide/BugTests/Bug21734_Spec.ts +++ b/app/client/cypress/e2e/Regression/ClientSide/BugTests/Bug21734_Spec.ts @@ -8,6 +8,8 @@ describe("Bug 21734: On exiting from the Datasources page without saving changes it("1. Navigating from intermediary datasource to new page", function () { dataSources.NavigateToDSCreateNew(); dataSources.CreatePlugIn("Mongo"); + // Have to fill form since modal won't show for empty ds + dataSources.FillMongoDSForm(); ee.AddNewPage(); @@ -27,6 +29,8 @@ describe("Bug 21734: On exiting from the Datasources page without saving changes it("2. Navigating from intermediary datasource to an existing page", function () { dataSources.NavigateToDSCreateNew(); dataSources.CreatePlugIn("PostgreSQL"); + // Have to fill form since modal won't show for empty ds + dataSources.FillPostgresDSForm(); ee.SelectEntityByName("Page1"); agHelper.AssertContains( diff --git a/app/client/cypress/e2e/Regression/ClientSide/BugTests/CatchBlock_Spec.ts b/app/client/cypress/e2e/Regression/ClientSide/BugTests/CatchBlock_Spec.ts index 9b4e0648feeb..90900a8918de 100644 --- a/app/client/cypress/e2e/Regression/ClientSide/BugTests/CatchBlock_Spec.ts +++ b/app/client/cypress/e2e/Regression/ClientSide/BugTests/CatchBlock_Spec.ts @@ -9,7 +9,10 @@ import { describe("Bug #15372 Catch block was not triggering in Safari/firefox", () => { it("1. Triggers the catch block when the API hits a 404", () => { - apiPage.CreateAndFillApi(tedTestConfig.mockHttpCodeUrl + "404"); + apiPage.CreateAndFillApi( + tedTestConfig.dsValues[tedTestConfig.defaultEnviorment].mockHttpCodeUrl + + "404", + ); jsEditor.CreateJSObject( `export default { fun: async () => { diff --git a/app/client/cypress/e2e/Regression/ClientSide/BugTests/DatasourceSchema_spec.ts b/app/client/cypress/e2e/Regression/ClientSide/BugTests/DatasourceSchema_spec.ts index 5c0399bb3542..a8069a24aea0 100644 --- a/app/client/cypress/e2e/Regression/ClientSide/BugTests/DatasourceSchema_spec.ts +++ b/app/client/cypress/e2e/Regression/ClientSide/BugTests/DatasourceSchema_spec.ts @@ -17,7 +17,12 @@ describe("Datasource form related tests", function () { dataSources.NavigateToDSCreateNew(); dataSources.CreatePlugIn("PostgreSQL"); agHelper.RenameWithInPane(dataSourceName, false); - dataSources.FillPostgresDSForm(false, "docker", "wrongPassword"); + dataSources.FillPostgresDSForm( + "production", + false, + "docker", + "wrongPassword", + ); dataSources.VerifySchema( dataSourceName, "An exception occurred while creating connection pool.", diff --git a/app/client/cypress/e2e/Regression/ClientSide/BugTests/GitBugs_Spec.ts b/app/client/cypress/e2e/Regression/ClientSide/BugTests/GitBugs_Spec.ts index 0002a863ae47..87b3cd1bb752 100644 --- a/app/client/cypress/e2e/Regression/ClientSide/BugTests/GitBugs_Spec.ts +++ b/app/client/cypress/e2e/Regression/ClientSide/BugTests/GitBugs_Spec.ts @@ -16,7 +16,10 @@ describe("Git Bugs", function () { it("1. Bug 16248, When GitSync modal is open, block shortcut action execution", function () { const modifierKey = Cypress.platform === "darwin" ? "meta" : "ctrl"; - _.apiPage.CreateAndFillApi(_.tedTestConfig.mockApiUrl, "GitSyncTest"); + _.apiPage.CreateAndFillApi( + _.tedTestConfig.dsValues[_.tedTestConfig.defaultEnviorment].mockApiUrl, + "GitSyncTest", + ); _.gitSync.OpenGitSyncModal(); cy.get("body").type(`{${modifierKey}}{enter}`); cy.get("@postExecute").should("not.exist"); @@ -33,6 +36,7 @@ describe("Git Bugs", function () { tempBranch = branchName; _.dataSources.NavigateToDSCreateNew(); _.dataSources.CreatePlugIn("PostgreSQL"); + _.dataSources.FillPostgresDSForm(); _.dataSources.SaveDSFromDialog(false); _.agHelper.AssertElementVisible(_.gitSync._branchButton); cy.get("@gitRepoName").then((repName) => { diff --git a/app/client/cypress/e2e/Regression/ClientSide/BugTests/InputTruncateCheck_Spec.ts b/app/client/cypress/e2e/Regression/ClientSide/BugTests/InputTruncateCheck_Spec.ts index ba212e5b5e6b..94055aa9e5a2 100644 --- a/app/client/cypress/e2e/Regression/ClientSide/BugTests/InputTruncateCheck_Spec.ts +++ b/app/client/cypress/e2e/Regression/ClientSide/BugTests/InputTruncateCheck_Spec.ts @@ -80,7 +80,10 @@ const widgetsToTest = { }; function configureApi() { - apiPage.CreateAndFillApi(tedTestConfig.mockApiUrl, "FirstAPI"); + apiPage.CreateAndFillApi( + tedTestConfig.dsValues[tedTestConfig.defaultEnviorment].mockApiUrl, + "FirstAPI", + ); apiPage.EnterHeader("value", "{{this.params.value}}"); } 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 d60465513de5..609511be4b1d 100644 --- a/app/client/cypress/e2e/Regression/ClientSide/Linting/BasicLint_spec.ts +++ b/app/client/cypress/e2e/Regression/ClientSide/Linting/BasicLint_spec.ts @@ -80,7 +80,9 @@ describe("Linting", () => { clickButtonAndAssertLintError(true); // create Api1 - apiPage.CreateAndFillApi(tedTestConfig.mockApiUrl); + apiPage.CreateAndFillApi( + tedTestConfig.dsValues[tedTestConfig.defaultEnviorment].mockApiUrl, + ); clickButtonAndAssertLintError(false); @@ -94,7 +96,9 @@ describe("Linting", () => { clickButtonAndAssertLintError(true); // Re-create Api1 - apiPage.CreateAndFillApi(tedTestConfig.mockApiUrl); + apiPage.CreateAndFillApi( + tedTestConfig.dsValues[tedTestConfig.defaultEnviorment].mockApiUrl, + ); clickButtonAndAssertLintError(false); }); @@ -295,7 +299,9 @@ describe("Linting", () => { shouldCreateNewJSObj: true, }, ); - apiPage.CreateAndFillApi(tedTestConfig.mockApiUrl); + apiPage.CreateAndFillApi( + tedTestConfig.dsValues[tedTestConfig.defaultEnviorment].mockApiUrl, + ); createMySQLDatasourceQuery(); agHelper.RefreshPage(); //Since this seems failing a bit diff --git a/app/client/cypress/e2e/Regression/ClientSide/Linting/EntityPropertiesLint_spec.ts b/app/client/cypress/e2e/Regression/ClientSide/Linting/EntityPropertiesLint_spec.ts index 6e48294d7188..667925cea46a 100644 --- a/app/client/cypress/e2e/Regression/ClientSide/Linting/EntityPropertiesLint_spec.ts +++ b/app/client/cypress/e2e/Regression/ClientSide/Linting/EntityPropertiesLint_spec.ts @@ -19,7 +19,9 @@ describe("Linting of entity properties", () => { it("1. Shows correct lint error when wrong Api property is binded", () => { const invalidProperty = "unknownProperty"; // create Api1 - apiPage.CreateAndFillApi(tedTestConfig.mockApiUrl); + apiPage.CreateAndFillApi( + tedTestConfig.dsValues[tedTestConfig.defaultEnviorment].mockApiUrl, + ); // Edit Button onclick property entityExplorer.SelectEntityByName("Button1", "Widgets"); propPane.EnterJSContext( diff --git a/app/client/cypress/e2e/Regression/ClientSide/MobileResponsiveTests/ConversionAlgorithm_FixedLayout_Mobile_Validation_Spec.js b/app/client/cypress/e2e/Regression/ClientSide/MobileResponsiveTests/ConversionAlgorithm_FixedLayout_Mobile_Validation_Spec.js index 8cea9a926893..a0ebb981c18e 100644 --- a/app/client/cypress/e2e/Regression/ClientSide/MobileResponsiveTests/ConversionAlgorithm_FixedLayout_Mobile_Validation_Spec.js +++ b/app/client/cypress/e2e/Regression/ClientSide/MobileResponsiveTests/ConversionAlgorithm_FixedLayout_Mobile_Validation_Spec.js @@ -1,5 +1,4 @@ import { agHelper, autoLayout } from "../../../../support/Objects/ObjectsCore"; - let testHeight; describe("Auto conversion algorithm usecases for fixed Layout", function () { diff --git a/app/client/cypress/e2e/Regression/ClientSide/OtherUIFeatures/EntityBottomBar_spec.ts b/app/client/cypress/e2e/Regression/ClientSide/OtherUIFeatures/EntityBottomBar_spec.ts index 7c3f20e81bef..59c9cb32061b 100644 --- a/app/client/cypress/e2e/Regression/ClientSide/OtherUIFeatures/EntityBottomBar_spec.ts +++ b/app/client/cypress/e2e/Regression/ClientSide/OtherUIFeatures/EntityBottomBar_spec.ts @@ -38,7 +38,9 @@ describe("Entity bottom bar", () => { it("3. Api bottom pane should be collapsable", () => { _.entityExplorer.NavigateToSwitcher("Explorer"); - _.apiPage.CreateAndFillApi(_.tedTestConfig.mockApiUrl); + _.apiPage.CreateAndFillApi( + _.tedTestConfig.dsValues[_.tedTestConfig.defaultEnviorment].mockApiUrl, + ); //Verify if bottom bar opens on clicking debugger icon in api page. _.debuggerHelper.ClickDebuggerIcon(); _.debuggerHelper.AssertOpen(PageType.API); diff --git a/app/client/cypress/e2e/Regression/ClientSide/OtherUIFeatures/Replay_Editor_spec.js b/app/client/cypress/e2e/Regression/ClientSide/OtherUIFeatures/Replay_Editor_spec.js index 687c2453d0e3..fac5fa6f7dde 100644 --- a/app/client/cypress/e2e/Regression/ClientSide/OtherUIFeatures/Replay_Editor_spec.js +++ b/app/client/cypress/e2e/Regression/ClientSide/OtherUIFeatures/Replay_Editor_spec.js @@ -32,6 +32,7 @@ describe("Undo/Redo functionality", function () { cy.get(datasourceEditor.username).type( datasourceFormData["postgres-username"], ); + cy.wait(500); cy.get(datasourceEditor.password).type( datasourceFormData["postgres-password"], ); diff --git a/app/client/cypress/e2e/Regression/ClientSide/PeekOverlay/PeekOverlay_Spec.ts b/app/client/cypress/e2e/Regression/ClientSide/PeekOverlay/PeekOverlay_Spec.ts index ccfb238e0f75..03da31ff63af 100644 --- a/app/client/cypress/e2e/Regression/ClientSide/PeekOverlay/PeekOverlay_Spec.ts +++ b/app/client/cypress/e2e/Regression/ClientSide/PeekOverlay/PeekOverlay_Spec.ts @@ -14,10 +14,14 @@ describe("Peek overlay", () => { entityExplorer.DragDropWidgetNVerify("tablewidgetv2", 500, 100); entityExplorer.NavigateToSwitcher("Explorer"); table.AddSampleTableData(); - apiPage.CreateAndFillApi(tedTestConfig.mockApiUrl); + apiPage.CreateAndFillApi( + tedTestConfig.dsValues[tedTestConfig.defaultEnviorment].mockApiUrl, + ); agHelper.Sleep(2000); apiPage.RunAPI(); - apiPage.CreateAndFillApi(tedTestConfig.mockApiUrl); + apiPage.CreateAndFillApi( + tedTestConfig.dsValues[tedTestConfig.defaultEnviorment].mockApiUrl, + ); agHelper.Sleep(2000); jsEditor.CreateJSObject(JsObjectContent, { diff --git a/app/client/cypress/e2e/Regression/ClientSide/PublishedApps/PublishedModeToastToggle_Spec.ts b/app/client/cypress/e2e/Regression/ClientSide/PublishedApps/PublishedModeToastToggle_Spec.ts index 97bc8e8a982b..8cbf86dc8596 100644 --- a/app/client/cypress/e2e/Regression/ClientSide/PublishedApps/PublishedModeToastToggle_Spec.ts +++ b/app/client/cypress/e2e/Regression/ClientSide/PublishedApps/PublishedModeToastToggle_Spec.ts @@ -15,10 +15,15 @@ describe("Published mode toggle toast with debug flag in the url", function () { }); it("1. Should not show any application related toasts", function () { - _.apiPage.CreateAndFillApi(_.tedTestConfig.mockApiUrl, "Correct_users"); + _.apiPage.CreateAndFillApi( + _.tedTestConfig.dsValues[_.tedTestConfig.defaultEnviorment].mockApiUrl, + "Correct_users", + ); _.apiPage.ToggleOnPageLoadRun(true); _.apiPage.CreateAndFillApi( - _.tedTestConfig.mockApiUrl.replace("mock-api", "mock-api2err"), + _.tedTestConfig.dsValues[ + _.tedTestConfig.defaultEnviorment + ].mockApiUrl.replace("mock-api", "mock-api2err"), "Incorrect_users", ); _.apiPage.ToggleOnPageLoadRun(true); diff --git a/app/client/cypress/e2e/Regression/ClientSide/Refactoring/Refactoring_spec.ts b/app/client/cypress/e2e/Regression/ClientSide/Refactoring/Refactoring_spec.ts index 79f598de3450..5bf93bf803a4 100644 --- a/app/client/cypress/e2e/Regression/ClientSide/Refactoring/Refactoring_spec.ts +++ b/app/client/cypress/e2e/Regression/ClientSide/Refactoring/Refactoring_spec.ts @@ -53,7 +53,7 @@ describe("Validate JS Object Refactoring does not affect the comments & variable ); //Creating query from EE overlay //Initialize new API entity with custom header apiPage.CreateAndFillApi( - tedTestConfig.mockApiUrl, + tedTestConfig.dsValues[tedTestConfig.defaultEnviorment].mockApiUrl, refactorInput.api.oldName, ); apiPage.EnterHeader("key1", `{{\tJSObject1.myVar1}}`); 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 447391d5b823..cc3480a199b3 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 @@ -39,7 +39,10 @@ describe("File picker widget v2", () => { ".t--property-control-text", `{{FilePicker1.files[0].name}}`, ); - cy.createAndFillApi(_.tedTestConfig.mockApiUrl, ""); + cy.createAndFillApi( + _.tedTestConfig.dsValues[_.tedTestConfig.defaultEnviorment].mockApiUrl, + "", + ); cy.updateCodeInput( "[class*='t--actionConfiguration']", "{{FilePicker1.files}}", diff --git a/app/client/cypress/e2e/Regression/ClientSide/Widgets/ListV2/Listv2_defaultSelectedItem_spec.js b/app/client/cypress/e2e/Regression/ClientSide/Widgets/ListV2/Listv2_defaultSelectedItem_spec.js index a33cd73d755a..9297cacc0ef0 100644 --- a/app/client/cypress/e2e/Regression/ClientSide/Widgets/ListV2/Listv2_defaultSelectedItem_spec.js +++ b/app/client/cypress/e2e/Regression/ClientSide/Widgets/ListV2/Listv2_defaultSelectedItem_spec.js @@ -44,7 +44,10 @@ const verifyDefaultItem = () => { }; function setUpDataSource() { - _.apiPage.CreateAndFillApi(_.tedTestConfig.mockApiUrl + "0"); + _.apiPage.CreateAndFillApi( + _.tedTestConfig.dsValues[_.tedTestConfig.defaultEnviorment].mockApiUrl + + "0", + ); cy.RunAPI(); _.entityExplorer.SelectEntityByName("List1"); cy.wait(200); diff --git a/app/client/cypress/e2e/Regression/ServerSide/ApiTests/API_EvaluatedValue_spec.ts b/app/client/cypress/e2e/Regression/ServerSide/ApiTests/API_EvaluatedValue_spec.ts index 22f913c0fb1a..7f01e7406d6d 100644 --- a/app/client/cypress/e2e/Regression/ServerSide/ApiTests/API_EvaluatedValue_spec.ts +++ b/app/client/cypress/e2e/Regression/ServerSide/ApiTests/API_EvaluatedValue_spec.ts @@ -13,8 +13,10 @@ describe("Validate API URL Evaluated value", () => { it("2. Check if path field strings have not been JSON.stringified - #24696", () => { apiPage.CreateApi("SecondAPI"); apiPage.EnterURL( - tedTestConfig.mockApiUrl + `/{{SecondAPI.isLoading}}`, - tedTestConfig.mockApiUrl + `/false`, + tedTestConfig.dsValues[tedTestConfig.defaultEnviorment].mockApiUrl + + `/{{SecondAPI.isLoading}}`, + tedTestConfig.dsValues[tedTestConfig.defaultEnviorment].mockApiUrl + + `/false`, ); }); }); diff --git a/app/client/cypress/e2e/Regression/ServerSide/ApiTests/API_TestExecuteWithDynamicBindingInUrl_spec.ts b/app/client/cypress/e2e/Regression/ServerSide/ApiTests/API_TestExecuteWithDynamicBindingInUrl_spec.ts index d97bb30fa490..87b1b2801b82 100644 --- a/app/client/cypress/e2e/Regression/ServerSide/ApiTests/API_TestExecuteWithDynamicBindingInUrl_spec.ts +++ b/app/client/cypress/e2e/Regression/ServerSide/ApiTests/API_TestExecuteWithDynamicBindingInUrl_spec.ts @@ -14,7 +14,9 @@ describe("Test API execution with dynamic binding in URL - Bug #24218", () => { myVar1: [], myVar2: {}, myFun1 () { - storeValue("api_url", "${tedTestConfig.mockApiUrl}"); + storeValue("api_url", "${ + tedTestConfig.dsValues[tedTestConfig.defaultEnviorment].mockApiUrl + }"); }, myFun2: async function() { } diff --git a/app/client/cypress/e2e/Regression/ServerSide/ApiTests/CurlImportFlow_spec.js b/app/client/cypress/e2e/Regression/ServerSide/ApiTests/CurlImportFlow_spec.js index 7485b6864ba7..b18f79d51fed 100644 --- a/app/client/cypress/e2e/Regression/ServerSide/ApiTests/CurlImportFlow_spec.js +++ b/app/client/cypress/e2e/Regression/ServerSide/ApiTests/CurlImportFlow_spec.js @@ -16,7 +16,10 @@ describe("Test curl import flow", function () { cy.NavigateToApiEditor(); dataSources.NavigateToDSCreateNew(); cy.get(ApiEditor.curlImage).click({ force: true }); - cy.get("textarea").type("curl -X GET " + tedTestConfig.mockApiUrl); + cy.get("textarea").type( + "curl -X GET " + + tedTestConfig.dsValues[tedTestConfig.defaultEnviorment].mockApiUrl, + ); cy.importCurl(); cy.get("@curlImport").then((response) => { expect(response.response.body.responseMeta.success).to.eq(true); diff --git a/app/client/cypress/e2e/Regression/ServerSide/JsFunctionExecution/PlatformFn_spec.ts b/app/client/cypress/e2e/Regression/ServerSide/JsFunctionExecution/PlatformFn_spec.ts index d65e9a4787fd..3b89af28baa6 100644 --- a/app/client/cypress/e2e/Regression/ServerSide/JsFunctionExecution/PlatformFn_spec.ts +++ b/app/client/cypress/e2e/Regression/ServerSide/JsFunctionExecution/PlatformFn_spec.ts @@ -10,7 +10,10 @@ import { describe("Tests functionality of platform function", () => { it("1. Tests access to outer variable", () => { - apiPage.CreateAndFillApi(tedTestConfig.mockApiUrl, "getAllUsers"); + apiPage.CreateAndFillApi( + tedTestConfig.dsValues[tedTestConfig.defaultEnviorment].mockApiUrl, + "getAllUsers", + ); jsEditor.CreateJSObject( `export default { myFun1: () => { diff --git a/app/client/cypress/e2e/Regression/ServerSide/JsFunctionExecution/SetTimeout_spec.ts b/app/client/cypress/e2e/Regression/ServerSide/JsFunctionExecution/SetTimeout_spec.ts index ed00b97f5245..a50e2ce30754 100644 --- a/app/client/cypress/e2e/Regression/ServerSide/JsFunctionExecution/SetTimeout_spec.ts +++ b/app/client/cypress/e2e/Regression/ServerSide/JsFunctionExecution/SetTimeout_spec.ts @@ -147,7 +147,9 @@ describe("Tests setTimeout API", function () { }); it("6. Access to args passed into success/error callback functions in API.run when using setTimeout", () => { - apiPage.CreateAndFillApi(tedTestConfig.mockApiUrl); + apiPage.CreateAndFillApi( + tedTestConfig.dsValues[tedTestConfig.defaultEnviorment].mockApiUrl, + ); jsEditor.CreateJSObject( `export default { myVar1: [], diff --git a/app/client/cypress/e2e/Regression/ServerSide/OnLoadTests/PostgresConnections_spec.ts b/app/client/cypress/e2e/Regression/ServerSide/OnLoadTests/PostgresConnections_spec.ts index 2fa496c1adfe..eebd936e545f 100644 --- a/app/client/cypress/e2e/Regression/ServerSide/OnLoadTests/PostgresConnections_spec.ts +++ b/app/client/cypress/e2e/Regression/ServerSide/OnLoadTests/PostgresConnections_spec.ts @@ -49,7 +49,7 @@ describe("Test Postgres number of connections on page load + Bug 11572, Bug 1120 dataSources.CreatePlugIn("PostgreSQL"); agHelper.RenameWithInPane("Postgres_2_" + guid, false); const userName = "test_conn_user_" + guid; - dataSources.FillPostgresDSForm(false, userName, "password"); + dataSources.FillPostgresDSForm("production", false, userName, "password"); dataSources.TestSaveDatasource(); cy.wrap("Postgres_2_" + guid).as("dsName_2"); diff --git a/app/client/cypress/e2e/Regression/ServerSide/QueryPane/EmptyDataSource_spec.js b/app/client/cypress/e2e/Regression/ServerSide/QueryPane/EmptyDataSource_spec.js index 344e62679b7c..1222cb503544 100644 --- a/app/client/cypress/e2e/Regression/ServerSide/QueryPane/EmptyDataSource_spec.js +++ b/app/client/cypress/e2e/Regression/ServerSide/QueryPane/EmptyDataSource_spec.js @@ -12,11 +12,13 @@ describe("Create a query with a empty datasource, run, save the query", function it("1. Create a empty datasource", function () { dataSources.NavigateToDSCreateNew(); dataSources.CreatePlugIn("PostgreSQL"); + cy.get(dataSources._databaseName).type("admin1"); dataSources.SaveDatasource(); //Create a query for empty/incorrect datasource and validate dataSources.CreateQueryAfterDSSaved("select * from users limit 10"); dataSources.RunQuery({ toValidateResponse: false }); + cy.wait(500); cy.get("[data-testid=t--query-error]").contains( "[Missing endpoint., Missing username for authentication.]", ); diff --git a/app/client/cypress/e2e/Sanity/Datasources/Airtable_Basic_Spec.ts b/app/client/cypress/e2e/Sanity/Datasources/Airtable_Basic_Spec.ts index 3c4cb5f7758d..9d13200d5a81 100644 --- a/app/client/cypress/e2e/Sanity/Datasources/Airtable_Basic_Spec.ts +++ b/app/client/cypress/e2e/Sanity/Datasources/Airtable_Basic_Spec.ts @@ -27,16 +27,22 @@ describe.skip("excludeForAirgap", "Validate Airtable Ds", () => { "List records", ); - agHelper.EnterValue(tedTestConfig.AirtableBase, { - propFieldName: "", - directInput: false, - inputFieldName: "Base ID ", - }); - agHelper.EnterValue(tedTestConfig.AirtableTable, { - propFieldName: "", - directInput: false, - inputFieldName: "Table name", - }); + agHelper.EnterValue( + tedTestConfig.dsValues[tedTestConfig.defaultEnviorment].AirtableBase, + { + propFieldName: "", + directInput: false, + inputFieldName: "Base ID ", + }, + ); + agHelper.EnterValue( + tedTestConfig.dsValues[tedTestConfig.defaultEnviorment].AirtableTable, + { + propFieldName: "", + directInput: false, + inputFieldName: "Table name", + }, + ); dataSources.RunQuery(); cy.get("@postExecute").then((resObj: any) => { diff --git a/app/client/cypress/e2e/Sanity/Datasources/ArangoDataSourceStub_spec.js b/app/client/cypress/e2e/Sanity/Datasources/ArangoDataSourceStub_spec.js index 4ab6c4bab161..321ab0c34863 100644 --- a/app/client/cypress/e2e/Sanity/Datasources/ArangoDataSourceStub_spec.js +++ b/app/client/cypress/e2e/Sanity/Datasources/ArangoDataSourceStub_spec.js @@ -39,6 +39,7 @@ describe("Arango datasource test cases", function () { it("4. Arango Default name change", () => { dataSources.NavigateToDSCreateNew(); dataSources.CreatePlugIn("ArangoDB"); + dataSources.FillArangoDSForm(); agHelper .GetText(dataSources._databaseName, "val") .then(($dbName) => expect($dbName).to.eq("_system")); diff --git a/app/client/cypress/e2e/Sanity/Datasources/Arango_Basic_Spec.ts b/app/client/cypress/e2e/Sanity/Datasources/Arango_Basic_Spec.ts index 023c3cb708ed..386f3becb17d 100644 --- a/app/client/cypress/e2e/Sanity/Datasources/Arango_Basic_Spec.ts +++ b/app/client/cypress/e2e/Sanity/Datasources/Arango_Basic_Spec.ts @@ -11,7 +11,7 @@ describe("Validate Arango & CURL Import Datasources", () => { containerName = "arangodb"; before("Create a new Arango DS", () => { dataSources.StartContainerNVerify("Arango", containerName, 20000); - dataSources.CreateDataSource("Arango"); + dataSources.CreateDataSource("ArangoDB"); cy.get("@dsName").then(($dsName) => { dsName = $dsName; }); @@ -314,7 +314,7 @@ describe("Validate Arango & CURL Import Datasources", () => { }); //needed for the deltion of ds to reflect agHelper.AssertElementVisible(dataSources._noSchemaAvailable(dsName)); //Deleting datasource finally - dataSources.DeleteDatasouceFromWinthinDS(dsName); + dataSources.DeleteDatasouceFromActiveTab(dsName); }); dataSources.StopNDeleteContainer(containerName); diff --git a/app/client/cypress/e2e/Sanity/Datasources/DSAutosaveImprovements_spec.ts b/app/client/cypress/e2e/Sanity/Datasources/DSAutosaveImprovements_spec.ts index 0ef0dba02a99..8e6b3b35ca44 100644 --- a/app/client/cypress/e2e/Sanity/Datasources/DSAutosaveImprovements_spec.ts +++ b/app/client/cypress/e2e/Sanity/Datasources/DSAutosaveImprovements_spec.ts @@ -52,7 +52,12 @@ describe("Datasource Autosave Improvements Tests", function () { agHelper.AssertElementEnabledDisabled(dataSources._saveDs, 0); // Make new changes and check state of datasource - dataSources.FillPostgresDSForm(false, "username", "password"); + dataSources.FillPostgresDSForm( + "production", + false, + "username", + "password", + ); agHelper.AssertElementEnabledDisabled(dataSources._saveDs, 0, false); dataSources.UpdateDatasource(); diff --git a/app/client/cypress/e2e/Sanity/Datasources/Port_Number_Placeholder_Spec.ts b/app/client/cypress/e2e/Sanity/Datasources/Port_Number_Placeholder_Spec.ts index 853f5b5a5fb7..2b2256d35571 100644 --- a/app/client/cypress/e2e/Sanity/Datasources/Port_Number_Placeholder_Spec.ts +++ b/app/client/cypress/e2e/Sanity/Datasources/Port_Number_Placeholder_Spec.ts @@ -12,7 +12,7 @@ describe("Test placeholder value for port number for all datasources - tests #24 "placeholder", expectedPlaceholderValue, ); - dataSources.SaveDSFromDialog(false); + agHelper.GoBack(); // Oracle dataSources.NavigateToDSCreateNew(); @@ -24,7 +24,7 @@ describe("Test placeholder value for port number for all datasources - tests #24 "placeholder", expectedPlaceholderValue, ); - dataSources.SaveDSFromDialog(false); + agHelper.GoBack(); // SMTP dataSources.NavigateToDSCreateNew(); @@ -36,7 +36,7 @@ describe("Test placeholder value for port number for all datasources - tests #24 "placeholder", expectedPlaceholderValue, ); - dataSources.SaveDSFromDialog(false); + agHelper.GoBack(); // MySQL dataSources.NavigateToDSCreateNew(); @@ -48,7 +48,7 @@ describe("Test placeholder value for port number for all datasources - tests #24 "placeholder", expectedPlaceholderValue, ); - dataSources.SaveDSFromDialog(false); + agHelper.GoBack(); // Postgres dataSources.NavigateToDSCreateNew(); @@ -60,7 +60,7 @@ describe("Test placeholder value for port number for all datasources - tests #24 "placeholder", expectedPlaceholderValue, ); - dataSources.SaveDSFromDialog(false); + agHelper.GoBack(); // MongoDB dataSources.NavigateToDSCreateNew(); @@ -72,7 +72,7 @@ describe("Test placeholder value for port number for all datasources - tests #24 "placeholder", expectedPlaceholderValue, ); - dataSources.SaveDSFromDialog(false); + agHelper.GoBack(); // Elasticsearch dataSources.NavigateToDSCreateNew(); @@ -84,7 +84,7 @@ describe("Test placeholder value for port number for all datasources - tests #24 "placeholder", expectedPlaceholderValue, ); - dataSources.SaveDSFromDialog(false); + agHelper.GoBack(); // Redis dataSources.NavigateToDSCreateNew(); @@ -96,7 +96,7 @@ describe("Test placeholder value for port number for all datasources - tests #24 "placeholder", expectedPlaceholderValue, ); - dataSources.SaveDSFromDialog(false); + agHelper.GoBack(); // Redshift dataSources.NavigateToDSCreateNew(); @@ -108,7 +108,7 @@ describe("Test placeholder value for port number for all datasources - tests #24 "placeholder", expectedPlaceholderValue, ); - dataSources.SaveDSFromDialog(false); + agHelper.GoBack(); // ArangoDB dataSources.NavigateToDSCreateNew(); @@ -120,6 +120,6 @@ describe("Test placeholder value for port number for all datasources - tests #24 "placeholder", expectedPlaceholderValue, ); - dataSources.SaveDSFromDialog(false); + agHelper.GoBack(); }); }); diff --git a/app/client/cypress/support/Objects/CommonLocators.ts b/app/client/cypress/support/Objects/CommonLocators.ts index baaf490ce50f..3554c9b8c8c9 100644 --- a/app/client/cypress/support/Objects/CommonLocators.ts +++ b/app/client/cypress/support/Objects/CommonLocators.ts @@ -14,6 +14,7 @@ export class CommonLocators { _emptyCanvasCta = "[data-testid='canvas-ctas']"; _dsName = ".t--edit-datasource-name span"; _dsNameTxt = ".t--edit-datasource-name input"; + _tableRecordsContainer = ".show-page-items"; _widgetName = (widgetName: string) => ".editable-text-container:contains('" + widgetName + @@ -259,4 +260,7 @@ export class CommonLocators { _controlOption = ".t--property-control-options"; _canvasBody = "[data-testid='div-selection-0']"; _svg = "svg"; + + public ds_editor_env_filter = (envName: string) => + `[data-cy="t--ds-data-filter-${envName}"]`; } diff --git a/app/client/cypress/support/Objects/TestConfigs.ts b/app/client/cypress/support/Objects/TestConfigs.ts index 4dc1a600c1dd..bb3c9cf780c1 100644 --- a/app/client/cypress/support/Objects/TestConfigs.ts +++ b/app/client/cypress/support/Objects/TestConfigs.ts @@ -1,105 +1,227 @@ export class TEDTestConfigs { - mongo_authenticationAuthtype = "SCRAM-SHA-1"; - mongo_host = "host.docker.internal"; - mongo_port = 28017; - mongo_databaseName = "mongo_samples"; - mongo_uri = `mongodb://${this.mongo_host}:${this.mongo_port}/${this.mongo_databaseName}`; - - postgres_host = "host.docker.internal"; - postgres_port = 5432; - postgres_databaseName = "fakeapi"; - postgres_username = "docker"; - postgres_password = "docker"; - - mysql_host = "host.docker.internal"; - mysql_port = 3306; - mysql_databaseName = "fakeapi"; - mysql_username = "root"; - mysql_password = "root"; - - mssql_host = "host.docker.internal"; - mssql_port = 1433; - mssql_databaseName = "fakeapi"; - mssql_username = "SA"; - mssql_password = "Root@123"; - mssql_docker = (containerName: string) => - `docker run --name=${containerName} -e "ACCEPT_EULA=Y" -e "SA_PASSWORD=${ - this.mssql_password - }" -p ${this.mssql_port.toString()}:${this.mssql_port.toString()} -d mcr.microsoft.com/azure-sql-edge`; - - arango_host = "host.docker.internal"; - arango_port = 8529; - arango_databaseName = "_system"; - arango_username = "root"; - arango_password = "Arango"; - arango_docker = (containerName: string) => - `docker run --name ${containerName} -e ARANGO_USERNAME=${ - this.arango_username - } -e ARANGO_ROOT_PASSWORD=${ - this.arango_password - } -p ${this.arango_port.toString()}:${this.arango_port.toString()} -d arangodb`; - - elastic_host = "http://host.docker.internal"; - elastic_port = 9200; - elastic_username = "elastic"; - elastic_password = "docker"; - elastic_docker = (containerName: string) => - `docker run --name ${containerName} -d -p ${this.elastic_port.toString()}:${this.elastic_port.toString()} -e "discovery.type=single-node" -e "ELASTIC_USERNAME=${ - this.elastic_username - }" -e "ELASTIC_PASSWORD=${ - this.elastic_password - }" -e "xpack.security.enabled=true" docker.elastic.co/elasticsearch/elasticsearch:7.16.2`; - - redshift_host = "localhost"; - redshift_port = 543; - redshift_databaseName = "fakeapi"; - redshift_username = "root"; - redshift_password = "Redshift$123"; - - smtp_host = "host.docker.internal"; - smtp_port = "25"; - smtp_username = "root"; - smtp_password = "root"; - - oracle_host = "random-data"; - oracle_port = 40; - oracle_name = "random-name"; - oracle_username = "random-username"; - oracle_password = "random-password"; - - redis_host = "host.docker.internal"; - redis_port = "6379"; - - OAuth_Username = "[email protected]"; - OAuth_Host = "http://localhost:6001"; - OAuth_ApiUrl = "http://host.docker.internal:6001"; - OAUth_AccessTokenUrl = "http://host.docker.internal:6001/oauth/token"; - OAuth_AuthUrl = "http://localhost:6001/oauth/authorize"; - OAuth_RedirectUrl = "http://localhost/api/v1/datasources/authorize"; - - AirtableBase = "appubHrVbovcudwN6"; - AirtableTable = "tblsFCQSskVFf7xNd"; - - mockApiUrl = "http://host.docker.internal:5001/v1/mock-api?records=10"; - echoApiUrl = "http://host.docker.internal:5001/v1/mock-api/echo"; - randomCatfactUrl = "http://host.docker.internal:5001/v1/catfact/random"; - mockHttpCodeUrl = "http://host.docker.internal:5001/v1/mock-http-codes/"; - - firestore_database_url = "https://appsmith-22e8b.firebaseio.com"; - firestore_projectID = "appsmith-22e8b"; - - restapi_url = "https://my-json-server.typicode.com/typicode/demo/posts"; - connection_type = "Replica set"; - - mockHostAddress = "fake_api.cvuydmurdlas.us-east-1.rds.amazonaws.com"; - mockDatabaseName = "fakeapi"; - mockDatabaseUsername = "fakeapi"; - mockDatabasePassword = "LimitedAccess123#"; - readonly = "readonly"; - authenticatedApiUrl = "https://fakeapi.com"; - - GraphqlApiUrl_TED = "http://host.docker.internal:5000/graphql"; + environments = ["production", "staging"]; + defaultEnviorment = this.environments[0]; GITEA_API_BASE_TED = "localhost"; GITEA_API_PORT_TED = "3001"; GITEA_API_URL_TED = "[email protected]:Cypress"; + + dsValues: Record<string, any> = { + production: { + mongo_authenticationAuthtype: "SCRAM-SHA-1", + mongo_host: "host.docker.internal", + mongo_port: 28017, + mongo_databaseName: "mongo_samples", + + postgres_host: "host.docker.internal", + postgres_port: 5432, + postgres_databaseName: "fakeapi", + postgres_username: "docker", + postgres_password: "docker", + + mysql_host: "host.docker.internal", + mysql_port: 3306, + mysql_databaseName: "fakeapi", + mysql_username: "root", + mysql_password: "root", + + mssql_host: "host.docker.internal", + mssql_port: 1433, + mssql_databaseName: "fakeapi", + mssql_username: "SA", + mssql_password: "Root@123", + + arango_host: "host.docker.internal", + arango_port: 8529, + arango_databaseName: "_system", + arango_username: "root", + arango_password: "Arango", + + elastic_host: "http://host.docker.internal", + elastic_port: 9200, + elastic_username: "elastic", + elastic_password: "docker", + + redshift_host: "localhost", + redshift_port: 543, + redshift_databaseName: "fakeapi", + redshift_username: "root", + redshift_password: "Redshift$123", + + smtp_host: "host.docker.internal", + smtp_port: "25", + smtp_username: "root", + smtp_password: "root", + + oracle_host: "random-data", + oracle_port: 40, + oracle_name: "random-name", + oracle_username: "random-username", + oracle_password: "random-password", + + redis_host: "host.docker.internal", + redis_port: "6379", + + OAuth_Username: "[email protected]", + OAuth_Host: "http://localhost:6001", + OAuth_ApiUrl: "http://host.docker.internal:6001", + OAUth_AccessTokenUrl: "http://host.docker.internal:6001/oauth/token", + OAuth_AuthUrl: "http://localhost:6001/oauth/authorize", + OAuth_RedirectUrl: "http://localhost/api/v1/datasources/authorize", + + AirtableBase: "appubHrVbovcudwN6", + AirtableTable: "tblsFCQSskVFf7xNd", + + mockApiUrl: "http://host.docker.internal:5001/v1/mock-api?records=10", + echoApiUrl: "http://host.docker.internal:5001/v1/mock-api/echo", + randomCatfactUrl: "http://host.docker.internal:5001/v1/catfact/random", + mockHttpCodeUrl: "http://host.docker.internal:5001/v1/mock-http-codes/", + AirtableBaseForME: "appubHrVbovcudwN6", + AirtableTableForME: "tblsFCQSskVFf7xNd", + + firestore_database_url: "https://appsmith-22e8b.firebaseio.com", + firestore_projectID: "appsmith-22e8b", + + restapi_url: "https://my-json-server.typicode.com/typicode/demo/posts", + connection_type: "Replica set", + + mockHostAddress: "fake_api.cvuydmurdlas.us-east-1.rds.amazonaws.com", + mockDatabaseName: "fakeapi", + mockDatabaseUsername: "fakeapi", + mockDatabasePassword: "LimitedAccess123#", + readonly: "readonly", + authenticatedApiUrl: "https://fakeapi.com", + + GraphqlApiUrl_TED: "http://host.docker.internal:5000/graphql", + }, + + staging: { + mongo_authenticationAuthtype: "SCRAM-SHA-1", + mongo_host: "host.docker.internal", + mongo_port: 28017, + mongo_databaseName: "mongo_samples", + + postgres_host: "host.docker.internal", + postgres_port: 5432, + postgres_databaseName: "fakeapitest", + postgres_username: "docker", + postgres_password: "docker", + + mysql_host: "host.docker.internal", + mysql_port: 3306, + mysql_databaseName: "fakeapi", + mysql_username: "root", + mysql_password: "root", + + mssql_host: "host.docker.internal", + mssql_port: 1433, + mssql_databaseName: "fakeapi", + mssql_username: "SA", + mssql_password: "Root@123", + + arango_host: "host.docker.internal", + arango_port: 8529, + arango_databaseName: "_system", + arango_username: "root", + arango_password: "Arango", + + elastic_host: "http://host.docker.internal", + elastic_port: 9200, + elastic_username: "elastic", + elastic_password: "docker", + + redshift_host: "localhost", + redshift_port: 543, + redshift_databaseName: "fakeapi", + redshift_username: "root", + redshift_password: "Redshift$123", + + smtp_host: "host.docker.internal", + smtp_port: "25", + smtp_username: "root", + smtp_password: "root", + + oracle_host: "random-data", + oracle_port: 40, + oracle_name: "random-name", + oracle_username: "random-username", + oracle_password: "random-password", + + redis_host: "host.docker.internal", + redis_port: "6379", + + OAuth_Username: "[email protected]", + OAuth_Host: "http://localhost:6001", + OAuth_ApiUrl: "http://host.docker.internal:6001", + OAUth_AccessTokenUrl: "http://host.docker.internal:6001/oauth/token", + OAuth_AuthUrl: "http://localhost:6001/oauth/authorize", + OAuth_RedirectUrl: "http://localhost/api/v1/datasources/authorize", + + AirtableBase: "appubHrVbovcudwN6", + AirtableTable: "tblsFCQSskVFf7xNd", + + mockApiUrl: "http://host.docker.internal:5001/v1/mock-api?records=10", + echoApiUrl: "http://host.docker.internal:5001/v1/mock-api/echo", + randomCatfactUrl: "http://host.docker.internal:5001/v1/catfact/random", + mockHttpCodeUrl: "http://host.docker.internal:5001/v1/mock-http-codes/", + AirtableBaseForME: "appubHrVbovcudwN6", + AirtableTableForME: "tblsFCQSskVFf7xNd", + + firestore_database_url: "https://appsmith-22e8b.firebaseio.com", + firestore_projectID: "appsmith-22e8b", + + restapi_url: "https://my-json-server.typicode.com/typicode/demo/posts", + connection_type: "Replica set", + + mockHostAddress: "fake_api.cvuydmurdlas.us-east-1.rds.amazonaws.com", + mockDatabaseName: "fakeapi", + mockDatabaseUsername: "fakeapi", + mockDatabasePassword: "LimitedAccess123#", + readonly: "readonly", + authenticatedApiUrl: "https://fakeapi.com", + + GraphqlApiUrl_TED: "http://host.docker.internal:5000/graphql", + }, + }; + + mongo_uri = (environment = this.defaultEnviorment) => { + return `mongodb://${this.dsValues[environment].mongo_host}:${this.dsValues[environment].mongo_port}/${this.dsValues[environment].mongo_databaseName}`; + }; + mssql_docker = ( + containerName: string, + environment = this.defaultEnviorment, + ) => { + return `docker run --name=${containerName} -e "ACCEPT_EULA=Y" -e "SA_PASSWORD=${ + this.dsValues[environment].mssql_password + }" -p ${this.dsValues[environment].mssql_port.toString()}:${this.dsValues[ + environment + ].mssql_port.toString()} -d mcr.microsoft.com/azure-sql-edge`; + }; + + arango_docker = ( + containerName: string, + environment = this.defaultEnviorment, + ) => { + return `docker run --name ${containerName} -e ARANGO_USERNAME=${ + this.dsValues[environment].arango_username + } -e ARANGO_ROOT_PASSWORD=${ + this.dsValues[environment].arango_password + } -p ${this.dsValues[environment].arango_port.toString()}:${this.dsValues[ + environment + ].arango_port.toString()} -d arangodb`; + }; + + elastic_docker = ( + containerName: string, + environment = this.defaultEnviorment, + ) => { + return `docker run --name ${containerName} -d -p ${this.dsValues[ + environment + ].elastic_port.toString()}:${this.dsValues[ + environment + ].elastic_port.toString()} -e "discovery.type=single-node" -e "ELASTIC_USERNAME=${ + this.dsValues[environment].elastic_username + }" -e "ELASTIC_PASSWORD=${ + this.dsValues[environment].elastic_password + }" -e "xpack.security.enabled=true" docker.elastic.co/elasticsearch/elasticsearch:7.16.2`; + }; } diff --git a/app/client/cypress/support/Pages/AggregateHelper.ts b/app/client/cypress/support/Pages/AggregateHelper.ts index c2e6334e65aa..5a808971c954 100644 --- a/app/client/cypress/support/Pages/AggregateHelper.ts +++ b/app/client/cypress/support/Pages/AggregateHelper.ts @@ -607,6 +607,14 @@ export class AggregateHelper extends ReusableHelper { cy.get(`${alias}.all`).should("have.length", expectedNumberOfCalls); } + public GetNClickIfPresent(selector: string) { + cy.get("body").then(($body) => { + if ($body.find(selector).length > 0) { + cy.get(selector).click(); + } + }); + } + public GetNClick( selector: string, index = 0, diff --git a/app/client/cypress/support/Pages/DataSources.ts b/app/client/cypress/support/Pages/DataSources.ts index d5d413853cfd..6c41d7f888b8 100644 --- a/app/client/cypress/support/Pages/DataSources.ts +++ b/app/client/cypress/support/Pages/DataSources.ts @@ -9,7 +9,7 @@ const DataSourceKVP = { UnAuthenticatedGraphQL: "GraphQL API", MsSql: "Microsoft SQL Server", Airtable: "Airtable", - Arango: "ArangoDB", + ArangoDB: "ArangoDB", Firestore: "Firestore", Elasticsearch: "Elasticsearch", Redis: "Redis", @@ -52,9 +52,9 @@ export class DataSources { ".t--plugin-name:contains('" + pluginName + "')"; public _host = "input[name$='.datasourceConfiguration.endpoints[0].host']"; public _port = "input[name$='.datasourceConfiguration.endpoints[0].port']"; - _databaseName = + public _databaseName = "input[name$='.datasourceConfiguration.authentication.databaseName']"; - private _username = + public _username = "input[name$='.datasourceConfiguration.authentication.username']"; private _section = (name: string) => "//div[text()='" + name + "']/parent::div"; @@ -403,96 +403,117 @@ export class DataSources { } public FillPostgresDSForm( + environment = this.tedTestConfig.defaultEnviorment, shouldAddTrailingSpaces = false, username = "", password = "", ) { const hostAddress = shouldAddTrailingSpaces - ? this.tedTestConfig.postgres_host + " " - : this.tedTestConfig.postgres_host; + ? this.tedTestConfig.dsValues[environment].postgres_host + " " + : this.tedTestConfig.dsValues[environment].postgres_host; const databaseName = shouldAddTrailingSpaces - ? this.tedTestConfig.postgres_databaseName + " " - : this.tedTestConfig.postgres_databaseName; + ? this.tedTestConfig.dsValues[environment].postgres_databaseName + " " + : this.tedTestConfig.dsValues[environment].postgres_databaseName; this.agHelper.UpdateInputValue( this._port, - this.tedTestConfig.postgres_port.toString(), + this.tedTestConfig.dsValues[environment].postgres_port.toString(), ); this.agHelper.UpdateInputValue(this._host, hostAddress); cy.get(this._databaseName).clear().type(databaseName); cy.get(this._username).type( - username == "" ? this.tedTestConfig.postgres_username : username, + username == "" + ? this.tedTestConfig.dsValues[environment].postgres_username + : username, ); cy.get(this._password).type( - password == "" ? this.tedTestConfig.postgres_username : password, + password == "" + ? this.tedTestConfig.dsValues[environment].postgres_password + : password, ); this.ValidateNSelectDropdown("SSL mode", "Default"); } public FillOracleDSForm( + environment = this.tedTestConfig.defaultEnviorment, shouldAddTrailingSpaces = false, username = "", password = "", ) { const hostAddress = shouldAddTrailingSpaces - ? this.tedTestConfig.oracle_host + " " - : this.tedTestConfig.oracle_host; + ? this.tedTestConfig.dsValues[environment].oracle_host + " " + : this.tedTestConfig.dsValues[environment].oracle_host; const databaseName = shouldAddTrailingSpaces - ? this.tedTestConfig.oracle_name + " " - : this.tedTestConfig.oracle_name; + ? this.tedTestConfig.dsValues[environment].oracle_name + " " + : this.tedTestConfig.dsValues[environment].oracle_name; this.agHelper.UpdateInputValue(this._host, hostAddress); this.agHelper.UpdateInputValue( this._port, - this.tedTestConfig.oracle_port.toString(), + this.tedTestConfig.dsValues[environment].oracle_port.toString(), ); cy.get(this._databaseName).clear().type(databaseName); cy.get(this._username).type( - username == "" ? this.tedTestConfig.oracle_username : username, + username == "" + ? this.tedTestConfig.dsValues[environment].oracle_username + : username, ); cy.get(this._password).type( - password == "" ? this.tedTestConfig.oracle_password : password, + password == "" + ? this.tedTestConfig.dsValues[environment].oracle_password + : password, ); } - public FillMongoDSForm(shouldAddTrailingSpaces = false) { + public FillMongoDSForm( + environment = this.tedTestConfig.defaultEnviorment, + shouldAddTrailingSpaces = false, + ) { const hostAddress = shouldAddTrailingSpaces - ? this.tedTestConfig.mongo_host + " " - : this.tedTestConfig.mongo_host; + ? this.tedTestConfig.dsValues[environment].mongo_host + " " + : this.tedTestConfig.dsValues[environment].mongo_host; this.agHelper.UpdateInputValue(this._host, hostAddress); this.agHelper.UpdateInputValue( this._port, - this.tedTestConfig.mongo_port.toString(), + this.tedTestConfig.dsValues[environment].mongo_port.toString(), ); cy.get(this._databaseName) .clear() - .type(this.tedTestConfig.mongo_databaseName); + .type(this.tedTestConfig.dsValues[environment].mongo_databaseName); } - public FillMySqlDSForm(shouldAddTrailingSpaces = false) { + public FillMySqlDSForm( + environment = this.tedTestConfig.defaultEnviorment, + shouldAddTrailingSpaces = false, + ) { const hostAddress = shouldAddTrailingSpaces - ? this.tedTestConfig.mysql_host + " " - : this.tedTestConfig.mysql_host; + ? this.tedTestConfig.dsValues[environment].mysql_host + " " + : this.tedTestConfig.dsValues[environment].mysql_host; const databaseName = shouldAddTrailingSpaces - ? this.tedTestConfig.mysql_databaseName + " " - : this.tedTestConfig.mysql_databaseName; + ? this.tedTestConfig.dsValues[environment].mysql_databaseName + " " + : this.tedTestConfig.dsValues[environment].mysql_databaseName; this.agHelper.UpdateInputValue(this._host, hostAddress); this.agHelper.UpdateInputValue( this._port, - this.tedTestConfig.mysql_port.toString(), + this.tedTestConfig.dsValues[environment].mysql_port.toString(), ); cy.get(this._databaseName).clear().type(databaseName); this.agHelper.UpdateInputValue( this._username, - this.tedTestConfig.mysql_username, + this.tedTestConfig.dsValues[environment].mysql_username, + ); + cy.get(this._password).type( + this.tedTestConfig.dsValues[environment].mysql_password, ); - cy.get(this._password).type(this.tedTestConfig.mysql_password); } - public FillMsSqlDSForm() { - this.agHelper.UpdateInputValue(this._host, this.tedTestConfig.mssql_host); + public FillMsSqlDSForm(environment = this.tedTestConfig.defaultEnviorment) { + this.agHelper.UpdateInputValue( + this._host, + this.tedTestConfig.dsValues[environment].mssql_host, + ); this.agHelper.UpdateInputValue( this._port, - this.tedTestConfig.mssql_port.toString(), + this.tedTestConfig.dsValues[environment].mssql_port.toString(), ); this.agHelper.ClearTextField(this._databaseName); // this.agHelper.UpdateInputValue( @@ -501,11 +522,11 @@ export class DataSources { // ); //Commenting until MsSQL is init loaded into container this.agHelper.UpdateInputValue( this._username, - this.tedTestConfig.mssql_username, + this.tedTestConfig.dsValues[environment].mssql_username, ); this.agHelper.UpdateInputValue( this._password, - this.tedTestConfig.mssql_password, + this.tedTestConfig.dsValues[environment].mssql_password, ); } @@ -522,11 +543,14 @@ export class DataSources { this.agHelper.Sleep(); } - public FillArangoDSForm() { - this.agHelper.UpdateInputValue(this._host, this.tedTestConfig.arango_host); + public FillArangoDSForm(environment = this.tedTestConfig.defaultEnviorment) { + this.agHelper.UpdateInputValue( + this._host, + this.tedTestConfig.dsValues[environment].arango_host, + ); this.agHelper.UpdateInputValue( this._port, - this.tedTestConfig.arango_port.toString(), + this.tedTestConfig.dsValues[environment].arango_port.toString(), ); //Validating db name is _system, currently unable to create DB via curl in Arango this.agHelper @@ -534,11 +558,11 @@ export class DataSources { .then(($dbName) => expect($dbName).to.eq("_system")); this.agHelper.UpdateInputValue( this._username, - this.tedTestConfig.arango_username, + this.tedTestConfig.dsValues[environment].arango_username, ); this.agHelper.UpdateInputValue( this._password, - this.tedTestConfig.arango_password, + this.tedTestConfig.dsValues[environment].arango_password, ); } @@ -555,14 +579,16 @@ export class DataSources { this.apiPage.RunAPI(); } - public FillFirestoreDSForm() { + public FillFirestoreDSForm( + environment = this.tedTestConfig.defaultEnviorment, + ) { this.agHelper.UpdateInput( this.locator._inputFieldByName("Database URL"), - this.tedTestConfig.firestore_database_url, + this.tedTestConfig.dsValues[environment].firestore_database_url, ); this.agHelper.UpdateInput( this.locator._inputFieldByName("Project Id"), - this.tedTestConfig.firestore_projectID, + this.tedTestConfig.dsValues[environment].firestore_projectID, ); // cy.fixture("firestore-ServiceAccCreds").then((json: any) => { // let ServiceAccCreds = JSON.parse( @@ -581,25 +607,34 @@ export class DataSources { //}); } - public FillElasticSearchDSForm() { - this.agHelper.UpdateInputValue(this._host, this.tedTestConfig.elastic_host); + public FillElasticSearchDSForm( + environment = this.tedTestConfig.defaultEnviorment, + ) { + this.agHelper.UpdateInputValue( + this._host, + this.tedTestConfig.dsValues[environment].elastic_host, + ); this.agHelper.UpdateInputValue( this._port, - this.tedTestConfig.elastic_port.toString(), + this.tedTestConfig.dsValues[environment].elastic_port.toString(), ); this.agHelper.UpdateInputValue( this._username, - this.tedTestConfig.elastic_username, + this.tedTestConfig.dsValues[environment].elastic_username, ); this.agHelper.UpdateInputValue( this._password, - this.tedTestConfig.elastic_password, + this.tedTestConfig.dsValues[environment].elastic_password, ); } - public FillUnAuthenticatedGraphQLDSForm() { + public FillUnAuthenticatedGraphQLDSForm( + environment = this.tedTestConfig.defaultEnviorment, + ) { this.agHelper.GetNClick(this._createBlankGraphQL); - this.apiPage.EnterURL(this.tedTestConfig.GraphqlApiUrl_TED); + this.apiPage.EnterURL( + this.tedTestConfig.dsValues[environment].GraphqlApiUrl_TED, + ); this.assertHelper.AssertNetworkStatus("@createNewApi", 201); } @@ -607,12 +642,13 @@ export class DataSources { dataSourceName: string, hKey: string, hValue: string, + environment = this.tedTestConfig.defaultEnviorment, ) { this.NavigateToDSCreateNew(); this.CreatePlugIn("Authenticated GraphQL API"); this.agHelper.UpdateInput( this.locator._inputFieldByName("URL"), - this.tedTestConfig.GraphqlApiUrl_TED, + this.tedTestConfig.dsValues[environment].GraphqlApiUrl_TED, ); this.agHelper.UpdateInputValue(this._graphQLHeaderKey, hKey); @@ -625,11 +661,14 @@ export class DataSources { }); } - public FillRedisDSForm() { - this.agHelper.UpdateInputValue(this._host, this.tedTestConfig.redis_host); + public FillRedisDSForm(environment = this.tedTestConfig.defaultEnviorment) { + this.agHelper.UpdateInputValue( + this._host, + this.tedTestConfig.dsValues[environment].redis_host, + ); this.agHelper.UpdateInputValue( this._port, - this.tedTestConfig.redis_port.toString(), + this.tedTestConfig.dsValues[environment].redis_port.toString(), ); } @@ -658,12 +697,13 @@ export class DataSources { } } - public SaveDatasource(isForkModal = false) { + public SaveDatasource(isForkModal = false, isSavingEnvInOldDS = false) { this.agHelper.Sleep(500); //bit of time for CI! this.agHelper.GetNClick(this._saveDs); if (!isForkModal) { this.assertHelper.AssertNetworkStatus("@saveDatasource", 201); - this.agHelper.AssertContains("datasource created"); + if (!isSavingEnvInOldDS) + this.agHelper.AssertContains("datasource created"); } else { this.assertHelper.AssertNetworkStatus("@updateDatasource", 200); } @@ -723,7 +763,7 @@ export class DataSources { public DeleteDSDirectly( expectedRes: number | number[] = 200 || 409 || [200 | 409], ) { - this.agHelper.GetNClick(this._cancelEditDatasourceButton, 0, false, 200); + this.agHelper.GetNClick(this._cancelEditDatasourceButton, 0, true, 200); cy.get(this._contextMenuDSReviewPage).click({ force: true }); this.agHelper.GetNClick(this._contextMenuDelete); this.agHelper.GetNClick(this.locator._visibleTextSpan("Are you sure?")); @@ -1043,7 +1083,7 @@ export class DataSources { | "UnAuthenticatedGraphQL" | "MsSql" | "Airtable" - | "Arango" + | "ArangoDB" | "Firestore" | "Elasticsearch" | "Redis" @@ -1051,6 +1091,8 @@ export class DataSources { | "S3", navigateToCreateNewDs = true, testNSave = true, + environment = this.tedTestConfig.defaultEnviorment, + assetEnvironmentSelected = false, ) { let guid: any; let dataSourceName = ""; @@ -1063,19 +1105,31 @@ export class DataSources { guid = uid; dataSourceName = dsType + " " + guid; this.agHelper.RenameWithInPane(dataSourceName, false); - if (DataSourceKVP[dsType] == "PostgreSQL") this.FillPostgresDSForm(); - else if (DataSourceKVP[dsType] == "Oracle") this.FillOracleDSForm(); - else if (DataSourceKVP[dsType] == "MySQL") this.FillMySqlDSForm(); - else if (DataSourceKVP[dsType] == "MongoDB") this.FillMongoDSForm(); + if (assetEnvironmentSelected) { + this.agHelper.AssertSelectedTab( + this.locator.ds_editor_env_filter(environment), + "true", + ); + } + if (DataSourceKVP[dsType] == "PostgreSQL") + this.FillPostgresDSForm(environment); + else if (DataSourceKVP[dsType] == "Oracle") + this.FillOracleDSForm(environment); + else if (DataSourceKVP[dsType] == "MySQL") + this.FillMySqlDSForm(environment); + else if (DataSourceKVP[dsType] == "MongoDB") + this.FillMongoDSForm(environment); else if (DataSourceKVP[dsType] == "Microsoft SQL Server") - this.FillMsSqlDSForm(); + this.FillMsSqlDSForm(environment); else if (DataSourceKVP[dsType] == "Airtable") this.FillAirtableDSForm(); - else if (DataSourceKVP[dsType] == "ArangoDB") this.FillArangoDSForm(); + else if (DataSourceKVP[dsType] == "ArangoDB") + this.FillArangoDSForm(environment); else if (DataSourceKVP[dsType] == "Firestore") - this.FillFirestoreDSForm(); + this.FillFirestoreDSForm(environment); else if (DataSourceKVP[dsType] == "Elasticsearch") - this.FillElasticSearchDSForm(); - else if (DataSourceKVP[dsType] == "Redis") this.FillRedisDSForm(); + this.FillElasticSearchDSForm(environment); + else if (DataSourceKVP[dsType] == "Redis") + this.FillRedisDSForm(environment); else if (DataSourceKVP[dsType] == "S3") this.FillS3DSForm(); if (testNSave) { @@ -1084,7 +1138,7 @@ export class DataSources { this.SaveDatasource(); } } else if (DataSourceKVP[dsType] == "GraphQL API") - this.FillUnAuthenticatedGraphQLDSForm(); + this.FillUnAuthenticatedGraphQLDSForm(environment); cy.wrap(dataSourceName).as("dsName"); }); } @@ -1257,10 +1311,10 @@ export class DataSources { return `[data-guided-tour-id="explorer-entity-${dSName}"]`; } - public FillAuthAPIUrl() { + public FillAuthAPIUrl(environment = this.tedTestConfig.defaultEnviorment) { this.agHelper.UpdateInput( this.locator._inputFieldByName("URL"), - this.tedTestConfig.authenticatedApiUrl, + this.tedTestConfig.dsValues[environment].authenticatedApiUrl, ); } @@ -1297,8 +1351,10 @@ export class DataSources { this.agHelper.GetNClick(this._editDatasourceFromActiveTab(dsName)); } - public FillMongoDatasourceFormWithURI() { - const uri = this.tedTestConfig.mongo_uri; + public FillMongoDatasourceFormWithURI( + environment = this.tedTestConfig.defaultEnviorment, + ) { + const uri = this.tedTestConfig.mongo_uri(environment); this.ValidateNSelectDropdown( "Use mongo connection string URI", "No", @@ -1310,45 +1366,58 @@ export class DataSources { ); } - public CreateOAuthClient(grantType: string) { + public CreateOAuthClient( + grantType: string, + environment = this.tedTestConfig.defaultEnviorment, + ) { let clientId, clientSecret; // Login to TED OAuth let formData = new FormData(); - formData.append("username", this.tedTestConfig.OAuth_Username); - cy.request("POST", this.tedTestConfig.OAuth_Host, formData).then( - (response) => { - expect(response.status).to.equal(200); - }, + formData.append( + "username", + this.tedTestConfig.dsValues[environment].OAuth_Username, ); + cy.request( + "POST", + this.tedTestConfig.dsValues[environment].OAuth_Host, + formData, + ).then((response) => { + expect(response.status).to.equal(200); + }); // Create client let clientData = new FormData(); clientData.append("client_name", "appsmith_cs_post"); clientData.append("client_uri", "http://localhost/"); clientData.append("scope", "profile"); - clientData.append("redirect_uri", this.tedTestConfig.OAuth_RedirectUrl); + clientData.append( + "redirect_uri", + this.tedTestConfig.dsValues[environment].OAuth_RedirectUrl, + ); clientData.append("grant_type", grantType); clientData.append("response_type", "code"); clientData.append("token_endpoint_auth_method", "client_secret_post"); cy.request( "POST", - this.tedTestConfig.OAuth_Host + "/create_client", + this.tedTestConfig.dsValues[environment].OAuth_Host + "/create_client", clientData, ).then((response) => { expect(response.status).to.equal(200); }); // Get Client Credentials - cy.request("GET", this.tedTestConfig.OAuth_Host).then((response) => { - clientId = response.body.split("client_id: </strong>"); - clientId = clientId[1].split("<strong>client_secret: </strong>"); - clientSecret = clientId[1].split("<strong>"); - clientSecret = clientSecret[0].trim(); - clientId = clientId[0].trim(); - cy.wrap(clientId).as("OAuthClientID"); - cy.wrap(clientSecret).as("OAuthClientSecret"); - }); + cy.request("GET", this.tedTestConfig.dsValues[environment].OAuth_Host).then( + (response) => { + clientId = response.body.split("client_id: </strong>"); + clientId = clientId[1].split("<strong>client_secret: </strong>"); + clientSecret = clientId[1].split("<strong>"); + clientSecret = clientSecret[0].trim(); + clientId = clientId[0].trim(); + cy.wrap(clientId).as("OAuthClientID"); + cy.wrap(clientSecret).as("OAuthClientSecret"); + }, + ); } public CreateOAuthDatasource( @@ -1379,12 +1448,13 @@ export class DataSources { grantType: "ClientCredentials" | "AuthCode", clientId: string, clientSecret: string, + environment = this.tedTestConfig.defaultEnviorment, ) { if (dsName) this.agHelper.RenameWithInPane(dsName, false); // Fill Auth Form this.agHelper.UpdateInput( this.locator._inputFieldByName("URL"), - this.tedTestConfig.OAuth_ApiUrl, + this.tedTestConfig.dsValues[environment].OAuth_ApiUrl, ); this.agHelper.GetNClick(this._authType); this.agHelper.GetNClick(this._oauth2); @@ -1396,7 +1466,7 @@ export class DataSources { this.agHelper.UpdateInput( this.locator._inputFieldByName("Access token URL"), - this.tedTestConfig.OAUth_AccessTokenUrl, + this.tedTestConfig.dsValues[environment].OAUth_AccessTokenUrl, ); this.agHelper.UpdateInput( @@ -1413,7 +1483,7 @@ export class DataSources { ); this.agHelper.UpdateInput( this.locator._inputFieldByName("Authorization URL"), - this.tedTestConfig.OAuth_AuthUrl, + this.tedTestConfig.dsValues[environment].OAuth_AuthUrl, ); } diff --git a/app/client/cypress/support/Pages/DeployModeHelper.ts b/app/client/cypress/support/Pages/DeployModeHelper.ts index 209e7235bf0c..b8a8d0d7e11c 100644 --- a/app/client/cypress/support/Pages/DeployModeHelper.ts +++ b/app/client/cypress/support/Pages/DeployModeHelper.ts @@ -24,6 +24,8 @@ export class DeployMode { private _backtoHome = ".t--app-viewer-navigation-header .t--app-viewer-back-to-apps-button"; private _homeAppsmithImage = "a.t--appsmith-logo"; + public envInfoModal = `[data-cy="t--env-info-modal"]`; + public envInfoModalDeployButton = `[data-cy="t--env-info-modal-deploy-button"]`; //refering PublishtheApp from command.js public DeployApp( @@ -31,6 +33,7 @@ export class DeployMode { toCheckFailureToast = true, toValidateSavedState = true, addDebugFlag = true, + assertEnvInfoModal = false, ) { //cy.intercept("POST", "/api/v1/applications/publish/*").as("publishAppli"); @@ -41,6 +44,11 @@ export class DeployMode { this.assertHelper.AssertDocumentReady(); this.StubbingDeployPage(addDebugFlag); this.agHelper.ClickButton("Deploy"); + if (assertEnvInfoModal) { + this.agHelper.WaitUntilEleAppear(this.envInfoModal); + this.agHelper.AssertElementExist(this.envInfoModal); + } + this.agHelper.GetNClickIfPresent(this.envInfoModalDeployButton); this.agHelper.AssertElementAbsence(this.locator._btnSpinner, 10000); //to make sure we have started navigation from Edit page //cy.get("@windowDeployStub").should("be.calledOnce"); this.assertHelper.AssertDocumentReady(); @@ -59,6 +67,7 @@ export class DeployMode { this.locator._specificToast("has failed"), ); //Validating bug - 14141 + 14252 this.agHelper.Sleep(2000); //for Depoy page to settle! + // }); } // Stubbing window.open to open in the same tab diff --git a/app/client/cypress/support/Pages/HomePage.ts b/app/client/cypress/support/Pages/HomePage.ts index 253d5f718c8d..d9781bc98dfd 100644 --- a/app/client/cypress/support/Pages/HomePage.ts +++ b/app/client/cypress/support/Pages/HomePage.ts @@ -111,6 +111,11 @@ export class HomePage { // '//span[text()="Rename application"]/ancestor::div[contains(@class,"rc-tooltip")]'; _appRenameTooltip = "span:contains('Rename application')"; _importFromGitBtn = "div.t--import-json-card + div"; + private signupUsername = "input[name='email']"; + private roleDropdown = ".setup-dropdown:first"; + private useCaseDropdown = ".setup-dropdown:last"; + private dropdownOption = ".rc-select-item-option:first"; + private roleUsecaseSubmit = ".t--get-started-button"; public SwitchToAppsTab() { this.agHelper.GetNClick(this._homeTab); @@ -331,6 +336,28 @@ export class HomePage { .should("be.enabled"); } + public SignUp(uname: string, pswd: string) { + this.agHelper.Sleep(); //waiting for window to load + cy.window().its("store").invoke("dispatch", { type: "LOGOUT_USER_INIT" }); + cy.wait("@postLogout"); + this.agHelper.VisitNAssert("/user/signup", "signUpLogin"); + cy.get(this.signupUsername).should("be.visible").type(uname); + cy.get(this._password).type(pswd, { log: false }); + cy.get(this._submitBtn).click(); + cy.wait(1000); + cy.get("body").then(($body) => { + if ($body.find(this.roleDropdown).length > 0) { + cy.get(this.roleDropdown).click(); + cy.get(this.dropdownOption).click(); + cy.get(this.useCaseDropdown).click(); + cy.get(this.dropdownOption).click(); + cy.get(this.roleUsecaseSubmit).click({ force: true }); + } + }); + cy.wait("@getMe"); + this.agHelper.Sleep(3000); + } + public FilterApplication(appName: string, workspaceId?: string) { cy.get(this._searchInput).type(appName, { force: true }); this.agHelper.Sleep(2000); diff --git a/app/client/cypress/support/ee/ObjectsCore_EE.ts b/app/client/cypress/support/ee/ObjectsCore_EE.ts new file mode 100644 index 000000000000..665041aec5cf --- /dev/null +++ b/app/client/cypress/support/ee/ObjectsCore_EE.ts @@ -0,0 +1 @@ +export * from "../Objects/ObjectsCore"; diff --git a/app/client/cypress/support/ee/Registry_EE.ts b/app/client/cypress/support/ee/Registry_EE.ts new file mode 100644 index 000000000000..d72fee6c9bab --- /dev/null +++ b/app/client/cypress/support/ee/Registry_EE.ts @@ -0,0 +1,5 @@ +export * from "../Objects/Registry"; + +import { ObjectsRegistry as CE_ObjectsRegistry } from "../Objects/Registry"; + +export class ObjectsRegistry extends CE_ObjectsRegistry {} diff --git a/app/client/src/actions/datasourceActions.ts b/app/client/src/actions/datasourceActions.ts index 5607a12d73a3..e8aedbf2e25b 100644 --- a/app/client/src/actions/datasourceActions.ts +++ b/app/client/src/actions/datasourceActions.ts @@ -40,17 +40,22 @@ export const createTempDatasourceFromForm = ( export const updateDatasource = ( payload: Datasource, + currEditingEnvId: string, onSuccess?: ReduxAction<unknown>, onError?: ReduxAction<unknown>, isInsideReconnectModal?: boolean, ): ReduxActionWithCallbacks< - Datasource & { isInsideReconnectModal: boolean }, + Datasource & { isInsideReconnectModal: boolean; currEditingEnvId?: string }, unknown, unknown > => { return { type: ReduxActionTypes.UPDATE_DATASOURCE_INIT, - payload: { ...payload, isInsideReconnectModal: !!isInsideReconnectModal }, + payload: { + ...payload, + isInsideReconnectModal: !!isInsideReconnectModal, + currEditingEnvId, + }, onSuccess, onError, }; @@ -234,13 +239,25 @@ export const deleteDatasource = ( }; }; -export const setDatasourceViewMode = (payload: boolean) => { +// sets viewMode flag along with clearing the datasource banner message +export const setDatasourceViewMode = (payload: { + datasourceId: string; + viewMode: boolean; +}) => { return { type: ReduxActionTypes.SET_DATASOURCE_EDITOR_MODE, payload, }; }; +// sets viewMode flag +export const setDatasourceViewModeFlag = (payload: boolean) => { + return { + type: ReduxActionTypes.SET_DATASOURCE_EDITOR_MODE_FLAG, + payload, + }; +}; + export const setAllDatasourceCollapsible = (payload: { [key: string]: boolean; }) => { @@ -469,6 +486,10 @@ export const datasourceDiscardAction = (pluginId: string) => { }; }; +export const softRefreshDatasourceStructure = () => ({ + type: ReduxActionTypes.SOFT_REFRESH_DATASOURCE_STRUCTURE, +}); + export default { fetchDatasources, initDatasourcePane, diff --git a/app/client/src/ce/actions/environmentAction.ts b/app/client/src/ce/actions/environmentAction.ts new file mode 100644 index 000000000000..6e283a7ef033 --- /dev/null +++ b/app/client/src/ce/actions/environmentAction.ts @@ -0,0 +1,2 @@ +// Redux action to show the environment info modal before deploy +export const showEnvironmentDeployInfoModal = () => ({}); diff --git a/app/client/src/ce/constants/ReduxActionConstants.tsx b/app/client/src/ce/constants/ReduxActionConstants.tsx index fd505b93ea66..8a2cb1ea9e22 100644 --- a/app/client/src/ce/constants/ReduxActionConstants.tsx +++ b/app/client/src/ce/constants/ReduxActionConstants.tsx @@ -245,6 +245,7 @@ const ActionTypes = { UPDATE_ACTION_SUCCESS: "UPDATE_ACTION_SUCCESS", DELETE_ACTION_INIT: "DELETE_ACTION_INIT", SET_DATASOURCE_EDITOR_MODE: "SET_DATASOURCE_EDITOR_MODE", + SET_DATASOURCE_EDITOR_MODE_FLAG: "SET_DATASOURCE_EDITOR_MODE_FLAG", SET_DATASOURCE_COLLAPSIBLE_STATE: "SET_DATASOURCE_COLLAPSIBLE_STATE", SET_ALL_DATASOURCE_COLLAPSIBLE_STATE: "SET_ALL_DATASOURCE_COLLAPSIBLE_STATE", DELETE_ACTION_SUCCESS: "DELETE_ACTION_SUCCESS", @@ -261,6 +262,7 @@ const ActionTypes = { FETCH_DATASOURCES_SUCCESS: "FETCH_DATASOURCES_SUCCESS", FETCH_MOCK_DATASOURCES_INIT: "FETCH_MOCK_DATASOURCES_INIT", FETCH_MOCK_DATASOURCES_SUCCESS: "FETCH_MOCK_DATASOURCES_SUCCESS", + SOFT_REFRESH_DATASOURCE_STRUCTURE: "SOFT_REFRESH_DATASOURCE_STRUCTURE", ADD_MOCK_DATASOURCES_INIT: "ADD_MOCK_DATASOURCES_INIT", ADD_MOCK_DATASOURCES_SUCCESS: "ADD_MOCK_DATASOURCES_SUCCESS", SAVE_DATASOURCE_NAME: "SAVE_DATASOURCE_NAME", @@ -299,6 +301,7 @@ const ActionTypes = { STORE_AS_DATASOURCE_INIT: "STORE_AS_DATASOURCE_INIT", STORE_AS_DATASOURCE_UPDATE: "STORE_AS_DATASOURCE_UPDATE", STORE_AS_DATASOURCE_COMPLETE: "STORE_AS_DATASOURCE_COMPLETE", + RESET_DATASOURCE_BANNER_MESSAGE: "RESET_DATASOURCE_BANNER_MESSAGE", PUBLISH_APPLICATION_INIT: "PUBLISH_APPLICATION_INIT", PUBLISH_APPLICATION_SUCCESS: "PUBLISH_APPLICATION_SUCCESS", CHANGE_APPVIEW_ACCESS_INIT: "CHANGE_APPVIEW_ACCESS_INIT", diff --git a/app/client/src/ce/constants/messages.ts b/app/client/src/ce/constants/messages.ts index 8d72e535dbe6..d87d89cdf99c 100644 --- a/app/client/src/ce/constants/messages.ts +++ b/app/client/src/ce/constants/messages.ts @@ -1868,3 +1868,18 @@ export const customJSLibraryMessages = { // Business Edition upgrade page export const MOVE_TO_BUSINESS_EDITION = (trailingChar: string) => `Move to Business edition${trailingChar ? trailingChar : ""}`; + +//Datasource environment +export const START_SWITCH_ENVIRONMENT = (environment: string) => + `...Switching your environment to ${environment}, and running all associated pageload actions`; +export const SWITCH_ENVIRONMENT_SUCCESS = (environment: string) => + `...Environment switched to ${environment} successfully`; + +export const TEST_DATASOURCE_SUCCESS = ( + datasourceName: string, + environmentName: string, +) => + `Test was successful, ${datasourceName} ${environmentName} environment is correctly configured.`; + +export const TEST_DATASOURCE_ERROR = () => + "Test failed, couldn't establish a connection"; diff --git a/app/client/src/ce/selectors/featureFlagsSelectors.ts b/app/client/src/ce/selectors/featureFlagsSelectors.ts index 004a15a8c005..e534163711e7 100644 --- a/app/client/src/ce/selectors/featureFlagsSelectors.ts +++ b/app/client/src/ce/selectors/featureFlagsSelectors.ts @@ -1,5 +1,6 @@ import type { AppState } from "@appsmith/reducers"; import type { FeatureFlag } from "@appsmith/entities/FeatureFlag"; +import { createSelector } from "reselect"; export const selectFeatureFlags = (state: AppState) => state.ui.users.featureFlag.data; @@ -15,3 +16,10 @@ export const selectFeatureFlagCheck = ( } return false; }; + +export const datasourceEnvEnabled = createSelector( + selectFeatureFlags, + (flags) => { + return !!flags.release_datasource_environments_enabled; + }, +); diff --git a/app/client/src/ce/utils/Environments/index.tsx b/app/client/src/ce/utils/Environments/index.tsx index 4853f491a77c..bf63303a7107 100644 --- a/app/client/src/ce/utils/Environments/index.tsx +++ b/app/client/src/ce/utils/Environments/index.tsx @@ -1,30 +1,27 @@ +import { PluginType } from "entities/Action"; import type { Datasource } from "entities/Datasource"; -export const ENVIRONMENT_QUERY_KEY = "environment"; -export const ENVIRONMENT_LOCAL_STORAGE_KEY = "currentEnvironment"; -export const ENVIRONMENT_ID_LOCAL_STORAGE_KEY = "currentEnvironmentId"; +export const DB_NOT_SUPPORTED = [PluginType.REMOTE, PluginType.SAAS]; -export const updateLocalStorage = (name: string, id: string) => { - // Set the values of currentEnv and currentEnvId in localStorage also - localStorage.setItem(ENVIRONMENT_LOCAL_STORAGE_KEY, name.toLowerCase()); - localStorage.setItem(ENVIRONMENT_ID_LOCAL_STORAGE_KEY, id); +export const getUserPreferenceFromStorage = () => { + return "true"; +}; + +export const getCurrentEditingEnvID = () => { + // Get the values of environment ID being edited + return getCurrentEnvironment(); }; // function to get the current environment from the URL export const getCurrentEnvironment = () => { - const localStorageEnv = localStorage.getItem(ENVIRONMENT_LOCAL_STORAGE_KEY); - //compare currentEnv with local storage and get currentEnvId from localstorage if true - - if (localStorageEnv && localStorageEnv.length > 0) { - const localStorageEnvId = localStorage.getItem( - ENVIRONMENT_ID_LOCAL_STORAGE_KEY, - ); - if (!!localStorageEnvId && localStorageEnvId?.length > 0) - return localStorageEnvId; - } return "unused_env"; }; +// function to get the current environment from the URL +export const getCurrentEnvName = () => { + return ""; +}; + // function to check if the datasource is configured for the current environment export const isEnvironmentConfigured = ( datasource: Datasource | null, @@ -51,6 +48,10 @@ export const isEnvironmentValid = ( return isValid ? isValid : false; }; +export const onUpdateFilterSuccess = (id: string) => { + return id; +}; + /* * Functiont to check get the datasource configuration for current ENV */ diff --git a/app/client/src/components/BottomBar/index.tsx b/app/client/src/components/BottomBar/index.tsx index fb1aef3a7375..742733dbe384 100644 --- a/app/client/src/components/BottomBar/index.tsx +++ b/app/client/src/components/BottomBar/index.tsx @@ -17,7 +17,6 @@ const Container = styled.div` background-color: ${(props) => props.theme.colors.editorBottomBar.background}; z-index: ${Layers.bottomBar}; border-top: solid 1px var(--ads-v2-color-border); - padding-left: ${(props) => props.theme.spaces[11]}px; `; const Wrapper = styled.div` @@ -26,26 +25,28 @@ const Wrapper = styled.div` justify-content: space-between; `; -export default function BottomBar(props: { className?: string }) { +export default function BottomBar({ viewMode }: { viewMode: boolean }) { return ( - <Container className={props.className ?? ""}> + <Container> <Wrapper> - <SwitchEnvironment /> - <QuickGitActions /> - </Wrapper> - <Wrapper> - <ManualUpgrades showTooltip> - <Button - className="t--upgrade" - isIconButton - kind="tertiary" - size="md" - startIcon="upgrade" - /> - </ManualUpgrades> - <DebuggerTrigger /> - <HelpButton /> + <SwitchEnvironment viewMode={viewMode} /> + {!viewMode && <QuickGitActions />} </Wrapper> + {!viewMode && ( + <Wrapper> + <ManualUpgrades showTooltip> + <Button + className="t--upgrade" + isIconButton + kind="tertiary" + size="md" + startIcon="upgrade" + /> + </ManualUpgrades> + <DebuggerTrigger /> + <HelpButton /> + </Wrapper> + )} </Container> ); } diff --git a/app/client/src/components/editorComponents/CodeEditor/index.tsx b/app/client/src/components/editorComponents/CodeEditor/index.tsx index 2c15b853a00f..016d0f4783ae 100644 --- a/app/client/src/components/editorComponents/CodeEditor/index.tsx +++ b/app/client/src/components/editorComponents/CodeEditor/index.tsx @@ -572,7 +572,7 @@ class CodeEditor extends Component<Props, State> { * and we check if they are different because the input value has changed * and not because the editor value has changed * */ - if (inputValue !== editorValue && inputValue !== previousInputValue) { + if (inputValue !== editorValue) { // If it is focused update it only if the identifier has changed // if not focused, can be updated if (this.state.isFocused) { diff --git a/app/client/src/components/editorComponents/Debugger/ErrorLogs/ErrorLogItem.tsx b/app/client/src/components/editorComponents/Debugger/ErrorLogs/ErrorLogItem.tsx index 389d9f238954..8253706681c9 100644 --- a/app/client/src/components/editorComponents/Debugger/ErrorLogs/ErrorLogItem.tsx +++ b/app/client/src/components/editorComponents/Debugger/ErrorLogs/ErrorLogItem.tsx @@ -159,6 +159,7 @@ export const getLogItemProps = (e: Log) => { collapsable: showToggleIcon(e), pluginErrorDetails: e.pluginErrorDetails, isExpanded: e.isExpanded, + environmentName: e.environmentName, }; }; @@ -180,6 +181,7 @@ export type LogItemProps = { messages?: Message[]; pluginErrorDetails?: PluginErrorDetails; isExpanded: boolean; + environmentName?: string; }; // Log item component @@ -242,6 +244,15 @@ const ErrorLogItem = (props: LogItemProps) => { startIcon={"expand-more"} /> )} + + {props.environmentName && ( + <LogAdditionalInfo + text={`${ + props.environmentName.charAt(0).toUpperCase() + + props.environmentName.slice(1) + }`} + /> + )} <div className={`debugger-error-type`}> {`${props.messages && props.messages[0].message.name}:`} </div> diff --git a/app/client/src/components/editorComponents/Debugger/index.tsx b/app/client/src/components/editorComponents/Debugger/index.tsx index ca0e9071f0d1..cc1d76786171 100644 --- a/app/client/src/components/editorComponents/Debugger/index.tsx +++ b/app/client/src/components/editorComponents/Debugger/index.tsx @@ -11,7 +11,6 @@ import { stopEventPropagation } from "utils/AppsmithUtils"; import { getDebuggerSelectedTab, getMessageCount, - hideDebuggerIconSelector, showDebuggerFlag, } from "selectors/debuggerSelectors"; import { DEBUGGER_TAB_KEYS } from "./helpers"; @@ -29,7 +28,6 @@ export function DebuggerTrigger() { const showDebugger = useSelector(showDebuggerFlag); const selectedTab = useSelector(getDebuggerSelectedTab); const messageCounters = useSelector(getMessageCount); - const hideDebuggerIcon = useSelector(hideDebuggerIconSelector); useEffect(() => { dispatch(setErrorCount(messageCounters.errors)); @@ -63,8 +61,6 @@ export function DebuggerTrigger() { }` : `No errors`; - if (hideDebuggerIcon) return null; - return ( <Tooltip content={tooltipContent}> <Button diff --git a/app/client/src/components/editorComponents/EditableText.tsx b/app/client/src/components/editorComponents/EditableText.tsx index 8c1c5c0e498a..a53c7217ae54 100644 --- a/app/client/src/components/editorComponents/EditableText.tsx +++ b/app/client/src/components/editorComponents/EditableText.tsx @@ -61,7 +61,6 @@ const EditableTextWrapper = styled.div<{ padding: ${(props) => (!props.minimal ? "5px 5px" : "0px")}; border-radius: var(--ads-v2-border-radius); text-transform: none; - flex: 1 0 100%; max-width: 100%; overflow: hidden; display: flex; diff --git a/app/client/src/components/editorComponents/StoreAsDatasource.tsx b/app/client/src/components/editorComponents/StoreAsDatasource.tsx index 334875faaa95..1fa4d2b5e15b 100644 --- a/app/client/src/components/editorComponents/StoreAsDatasource.tsx +++ b/app/client/src/components/editorComponents/StoreAsDatasource.tsx @@ -19,11 +19,17 @@ type storeDataSourceProps = { datasourceId?: string; enable: boolean; shouldSave: boolean; - setDatasourceViewMode: (viewMode: boolean) => void; + setDatasourceViewMode: (payload: { + datasourceId: string; + viewMode: boolean; + }) => void; }; interface ReduxDispatchProps { - setDatasourceViewMode: (viewMode: boolean) => void; + setDatasourceViewMode: (payload: { + datasourceId: string; + viewMode: boolean; + }) => void; } function StoreAsDatasource(props: storeDataSourceProps) { @@ -35,7 +41,10 @@ function StoreAsDatasource(props: storeDataSourceProps) { dispatch(storeAsDatasource()); } else { if (props.datasourceId) { - props.setDatasourceViewMode(false); + props.setDatasourceViewMode({ + datasourceId: props.datasourceId, + viewMode: false, + }); history.push( datasourcesEditorIdURL({ pageId, @@ -64,8 +73,16 @@ function StoreAsDatasource(props: storeDataSourceProps) { } const mapDispatchToProps = (dispatch: any): ReduxDispatchProps => ({ - setDatasourceViewMode: (viewMode: boolean) => - dispatch(setDatasourceViewMode(viewMode)), + setDatasourceViewMode: (payload: { + datasourceId: string; + viewMode: boolean; + }) => + dispatch( + setDatasourceViewMode({ + datasourceId: payload.datasourceId, + viewMode: payload.viewMode, + }), + ), }); export default connect(null, mapDispatchToProps)(StoreAsDatasource); diff --git a/app/client/src/components/editorComponents/WidgetQueryGeneratorForm/CommonControls/DatasourceDropdown/useDatasource.tsx b/app/client/src/components/editorComponents/WidgetQueryGeneratorForm/CommonControls/DatasourceDropdown/useDatasource.tsx index 923381123166..6936bedfc3f9 100644 --- a/app/client/src/components/editorComponents/WidgetQueryGeneratorForm/CommonControls/DatasourceDropdown/useDatasource.tsx +++ b/app/client/src/components/editorComponents/WidgetQueryGeneratorForm/CommonControls/DatasourceDropdown/useDatasource.tsx @@ -37,6 +37,7 @@ import type { AppState } from "@appsmith/reducers"; import { DatasourceCreateEntryPoints } from "constants/Datasource"; import { getCurrentWorkspaceId } from "@appsmith/selectors/workspaceSelectors"; import { + getCurrentEnvironment, getEnvironmentConfiguration, isEnvironmentValid, } from "@appsmith/utils/Environments"; @@ -145,11 +146,13 @@ export function useDatasource(searchText: string) { value: datasource.name, data: { pluginId: datasource.pluginId, - isValid: isEnvironmentValid(datasource), + isValid: isEnvironmentValid(datasource, getCurrentEnvironment()), pluginPackageName: pluginsPackageNamesMap[datasource.pluginId], isSample: false, - connectionMode: - getEnvironmentConfiguration(datasource)?.connection?.mode, + connectionMode: getEnvironmentConfiguration( + datasource, + getCurrentEnvironment(), + )?.connection?.mode, }, icon: ( <ImageWrapper> diff --git a/app/client/src/components/editorComponents/form/fields/EmbeddedDatasourcePathField.tsx b/app/client/src/components/editorComponents/form/fields/EmbeddedDatasourcePathField.tsx index 60b0fe72dea0..b0694a0c27b7 100644 --- a/app/client/src/components/editorComponents/form/fields/EmbeddedDatasourcePathField.tsx +++ b/app/client/src/components/editorComponents/form/fields/EmbeddedDatasourcePathField.tsx @@ -367,7 +367,10 @@ class EmbeddedDatasourcePathComponent extends React.Component< text: datasource.datasourceStorages[currentEnvironment] ?.datasourceConfiguration?.url, data: datasource, - className: !isEnvironmentValid(datasource) + className: !isEnvironmentValid( + datasource, + currentEnvironment, + ) ? "datasource-hint custom invalid" : "datasource-hint custom", render: (element: HTMLElement, self: any, data: any) => { diff --git a/app/client/src/components/formControls/DropDownControl.tsx b/app/client/src/components/formControls/DropDownControl.tsx index 0abdb5cb4fa0..d602e40fb469 100644 --- a/app/client/src/components/formControls/DropDownControl.tsx +++ b/app/client/src/components/formControls/DropDownControl.tsx @@ -23,7 +23,8 @@ const DropdownSelect = styled.div<{ width: string; }>` /* font-size: 14px; */ - width: ${(props) => (props?.width ? props?.width : "270px")}; + min-width: 380px; + max-width: 545px; `; class DropDownControl extends BaseControl<Props> { diff --git a/app/client/src/components/formControls/utils.ts b/app/client/src/components/formControls/utils.ts index b91ac74c7668..389fb6a667ce 100644 --- a/app/client/src/components/formControls/utils.ts +++ b/app/client/src/components/formControls/utils.ts @@ -19,6 +19,30 @@ import { createMessage, } from "@appsmith/constants/messages"; import { FEATURE_FLAG } from "@appsmith/entities/FeatureFlag"; +import { getCurrentEditingEnvID } from "@appsmith/utils/Environments"; + +// This function checks if the form is dirty +// We needed this in the cases where datasources are created from APIs and the initial value +// already has url set. If user presses back button, we need to show the confirmation dialog +export const getIsFormDirty = ( + isFormDirty: boolean, + formData: any, + isNewDatasource: boolean, + isRestPlugin: boolean, +) => { + const url = isRestPlugin + ? get( + formData, + `datastoreStorages.${getCurrentEditingEnvID}.datasourceConfiguration.url`, + "", + ) + : ""; + + if (!isFormDirty && isNewDatasource && isRestPlugin && url.length === 0) { + return true; + } + return isFormDirty; +}; export const getTrimmedData = (formData: any) => { const dataType = getType(formData); @@ -81,10 +105,19 @@ export const normalizeValues = ( export const validate = ( requiredFields: Record<string, FormConfigType>, values: any, + currentEnvId?: string, ) => { const errors = {} as any; Object.keys(requiredFields).forEach((fieldConfigProperty) => { + // Do not check for required fields if the field is not part of the current environment + if ( + !!currentEnvId && + currentEnvId.length > 0 && + !fieldConfigProperty.includes(currentEnvId) + ) { + return; + } const fieldConfig = requiredFields[fieldConfigProperty]; if (fieldConfig.controlType === "KEYVALUE_ARRAY") { const configProperty = (fieldConfig.configProperty as string).split( diff --git a/app/client/src/constants/routes/appRoutes.ts b/app/client/src/constants/routes/appRoutes.ts index 3d1d959f00fd..2fe3712b0e70 100644 --- a/app/client/src/constants/routes/appRoutes.ts +++ b/app/client/src/constants/routes/appRoutes.ts @@ -34,6 +34,7 @@ export const JS_COLLECTION_EDITOR_PATH = `/jsObjects`; export const JS_COLLECTION_ID_PATH = `${JS_COLLECTION_EDITOR_PATH}/:collectionId`; export const CURL_IMPORT_PAGE_PATH = `/api/curl/curl-import`; export const DATA_SOURCES_EDITOR_ID_PATH = `/datasource/:datasourceId`; +export const SAAS_GSHEET_EDITOR_ID_PATH = `/saas/google-sheets-plugin/datasources/:datasourceId`; export const PROVIDER_TEMPLATE_PATH = `/provider/:providerId`; export const GEN_TEMPLATE_URL = "generate-page"; export const GENERATE_TEMPLATE_PATH = `/${GEN_TEMPLATE_URL}`; @@ -50,9 +51,17 @@ export const VIEWER_PATCH_PATH = `/:applicationSlug/:pageSlug(.*\-):pageId`; export const matchApiBasePath = match(API_EDITOR_BASE_PATH); export const matchApiPath = match(API_EDITOR_ID_PATH); -export const matchDatasourcePath = match(DATA_SOURCES_EDITOR_ID_PATH); +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( + BUILDER_PATH + QUERIES_EDITOR_ID_PATH, +); export const matchBuilderPath = ( pathName: string, options?: { end?: boolean }, diff --git a/app/client/src/ee/actions/environmentAction.ts b/app/client/src/ee/actions/environmentAction.ts new file mode 100644 index 000000000000..86f8795db260 --- /dev/null +++ b/app/client/src/ee/actions/environmentAction.ts @@ -0,0 +1 @@ +export * from "ce/actions/environmentAction"; diff --git a/app/client/src/ee/components/DSDataFilter/index.tsx b/app/client/src/ee/components/DSDataFilter/index.tsx index b04460aadec6..3f8fc72e9731 100644 --- a/app/client/src/ee/components/DSDataFilter/index.tsx +++ b/app/client/src/ee/components/DSDataFilter/index.tsx @@ -1,13 +1,16 @@ type DSDataFilterProps = { + datasourceId: string; updateFilter: ( id: string, name: string, userPermissions: string[], showFilterPane: boolean, - ) => void; + ) => boolean; pluginType: string; + pluginName: string; isInsideReconnectModal: boolean; viewMode: boolean; + filterId: string; // id of the selected environment, used to keep the parent and child in sync }; function DSDataFilter({}: DSDataFilterProps) { diff --git a/app/client/src/ee/components/EnvConfigSection.tsx/index.tsx b/app/client/src/ee/components/EnvConfigSection.tsx/index.tsx new file mode 100644 index 000000000000..87bfba2728f8 --- /dev/null +++ b/app/client/src/ee/components/EnvConfigSection.tsx/index.tsx @@ -0,0 +1,18 @@ +import type { Datasource } from "entities/Datasource"; +import { renderDatasourceSection } from "pages/Editor/DataSourceEditor/DatasourceSection"; + +type Props = { + currentEnv: string; + config: any; + datasource: Datasource; + viewMode: boolean | undefined; +}; + +export function EnvConfigSection({ + config, + currentEnv, + datasource, + viewMode, +}: Props) { + return renderDatasourceSection(config, currentEnv, datasource, viewMode); +} diff --git a/app/client/src/ee/components/EnvInfoHeader/index.tsx b/app/client/src/ee/components/EnvInfoHeader/index.tsx new file mode 100644 index 000000000000..6fd41fa2b72a --- /dev/null +++ b/app/client/src/ee/components/EnvInfoHeader/index.tsx @@ -0,0 +1,3 @@ +export function EnvInfoHeader() { + return null; +} diff --git a/app/client/src/ee/components/SwitchEnvironment/index.tsx b/app/client/src/ee/components/SwitchEnvironment/index.tsx index 8ccea0558357..761128f17393 100644 --- a/app/client/src/ee/components/SwitchEnvironment/index.tsx +++ b/app/client/src/ee/components/SwitchEnvironment/index.tsx @@ -1,3 +1,7 @@ -export default function SwitchEnvironment() { +type SwitchEnvironmentProps = { + viewMode: boolean; +}; + +export default function SwitchEnvironment({}: SwitchEnvironmentProps) { return null; } diff --git a/app/client/src/entities/AppsmithConsole/index.ts b/app/client/src/entities/AppsmithConsole/index.ts index 905e4dc7ea2b..920cf4769912 100644 --- a/app/client/src/entities/AppsmithConsole/index.ts +++ b/app/client/src/entities/AppsmithConsole/index.ts @@ -91,6 +91,8 @@ export interface LogActionPayload { logType?: LOG_TYPE; // This is the preview of the log that the user sees. text: string; + // The environment in which the log was generated. + environmentName?: string; // Number of times this log has been repeated occurrenceCount?: number; // Deconstructed data of the log, this includes the whole nested objects/arrays/strings etc. diff --git a/app/client/src/entities/Datasource/index.ts b/app/client/src/entities/Datasource/index.ts index 9abce2a67dde..1ff0c638f4c1 100644 --- a/app/client/src/entities/Datasource/index.ts +++ b/app/client/src/entities/Datasource/index.ts @@ -29,6 +29,18 @@ export enum ActionType { DOCUMENTATION = "documentation", } +/* + Types of messages that can be shown in the toast of the datasource configuration page + EMPTY_TOAST_MESSAGE: No message to be shown + TEST_DATASOURCE_SUCCESS: Test datasource success message + TEST_DATASOURCE_ERROR: Test datasource error message +*/ +export enum ToastMessageType { + EMPTY_TOAST_MESSAGE = "EMPTY_TOAST_MESSAGE", + TEST_DATASOURCE_SUCCESS = "TEST_DATASOURCE_SUCCESS", + TEST_DATASOURCE_ERROR = "TEST_DATASOURCE_ERROR", +} + export interface DatasourceAuthentication { authType?: string; username?: string; @@ -141,6 +153,7 @@ export interface DatasourceStorage { isValid: boolean; structure?: DatasourceStructure; isConfigured?: boolean; + toastMessage?: string; } export interface TokenResponse { diff --git a/app/client/src/navigation/FocusElements.ts b/app/client/src/navigation/FocusElements.ts index 784616d428c2..8a917ea1ff7e 100644 --- a/app/client/src/navigation/FocusElements.ts +++ b/app/client/src/navigation/FocusElements.ts @@ -29,8 +29,8 @@ import { } from "selectors/editorContextSelectors"; import { getAllDatasourceCollapsibleState, + getDsViewModeValues, getSelectedWidgets, - isDatasourceInViewMode, } from "selectors/ui"; import { @@ -173,9 +173,9 @@ export const FocusElementsConfig: Record<FocusEntity, Config[]> = { [FocusEntity.DATASOURCE]: [ { name: FocusElement.DatasourceViewMode, - selector: isDatasourceInViewMode, + selector: getDsViewModeValues, setter: setDatasourceViewMode, - defaultValue: true, + defaultValue: { datasourceId: "", viewMode: true }, }, { name: FocusElement.DatasourceAccordions, diff --git a/app/client/src/pages/AppViewer/index.tsx b/app/client/src/pages/AppViewer/index.tsx index 348dd7c922cd..25d7d66101c3 100644 --- a/app/client/src/pages/AppViewer/index.tsx +++ b/app/client/src/pages/AppViewer/index.tsx @@ -41,17 +41,25 @@ import type { ApplicationPayload } from "@appsmith/constants/ReduxActionConstant import { getCurrentApplication } from "@appsmith/selectors/applicationSelectors"; import { editorInitializer } from "../../utils/editor/EditorUtils"; import { widgetInitialisationSuccess } from "../../actions/widgetActions"; +import BottomBar from "components/BottomBar"; +import { areEnvironmentsFetched } from "@appsmith/selectors/environmentSelectors"; +import { datasourceEnvEnabled } from "@appsmith/selectors/featureFlagsSelectors"; const AppViewerBody = styled.section<{ hasPages: boolean; headerHeight: number; showGuidedTourMessage: boolean; + showBottomBar: boolean; }>` display: flex; flex-direction: row; align-items: stretch; justify-content: flex-start; - height: calc(100vh - ${({ headerHeight }) => headerHeight}px); + height: calc( + 100vh - + ${(props) => (props.showBottomBar ? props.theme.bottomBarHeight : "0px")} - + ${({ headerHeight }) => headerHeight}px + ); --view-mode-header-height: ${({ headerHeight }) => headerHeight}px; `; @@ -93,6 +101,16 @@ function AppViewer(props: Props) { const focusRef = useWidgetFocus(); + const workspaceId = currentApplicationDetails?.workspaceId || ""; + const showBottomBar = useSelector((state: AppState) => { + return ( + areEnvironmentsFetched(state, workspaceId) && datasourceEnvEnabled(state) + ); + }); + + /** + * initializes the widgets factory and registers all widgets + */ useEffect(() => { editorInitializer().then(() => { dispatch(widgetInitialisationSuccess()); @@ -177,13 +195,17 @@ function AppViewer(props: Props) { hasPages={pages.length > 1} headerHeight={headerHeight} ref={focusRef} + showBottomBar={showBottomBar} showGuidedTourMessage={showGuidedTourMessage} > {isInitialized && <AppViewerPageContainer />} </AppViewerBody> + {showBottomBar && <BottomBar viewMode />} {!hideWatermark && ( <a - className="fixed hidden right-8 bottom-4 z-3 hover:no-underline md:flex" + className={`fixed hidden right-8 ${ + showBottomBar ? "bottom-12" : "bottom-4" + } z-3 hover:no-underline md:flex`} href="https://appsmith.com" rel="noreferrer" target="_blank" diff --git a/app/client/src/pages/Editor/APIEditor/RestAPIForm.tsx b/app/client/src/pages/Editor/APIEditor/RestAPIForm.tsx index 72b11ecd2e47..2beffe8c0a63 100644 --- a/app/client/src/pages/Editor/APIEditor/RestAPIForm.tsx +++ b/app/client/src/pages/Editor/APIEditor/RestAPIForm.tsx @@ -23,6 +23,7 @@ import { isEmpty } from "lodash"; import type { CommonFormProps } from "./CommonEditorForm"; import CommonEditorForm from "./CommonEditorForm"; import Pagination from "./Pagination"; +import { getCurrentEnvironment } from "@appsmith/utils/Environments"; const NoBodyMessage = styled.div` margin-top: 20px; @@ -100,12 +101,19 @@ export default connect((state: AppState, props: { pluginId: string }) => { // get messages from action itself const actionId = selector(state, "id"); const action = getAction(state, actionId); + const currentEnvironment = getCurrentEnvironment(); const hintMessages = action?.messages; const datasourceHeaders = - get(datasourceFromAction, "datasourceConfiguration.headers") || []; + get( + datasourceFromAction, + `datasourceStorages.${currentEnvironment}.datasourceConfiguration.headers`, + ) || []; const datasourceParams = - get(datasourceFromAction, "datasourceConfiguration.queryParameters") || []; + get( + datasourceFromAction, + `datasourceStorages.${currentEnvironment}.datasourceConfiguration.queryParameters`, + ) || []; const apiId = selector(state, "id"); const currentActionDatasourceId = selector(state, "datasource.id"); diff --git a/app/client/src/pages/Editor/DataSourceEditor/DBForm.tsx b/app/client/src/pages/Editor/DataSourceEditor/DBForm.tsx index 21bc0fe54d00..63672c39e666 100644 --- a/app/client/src/pages/Editor/DataSourceEditor/DBForm.tsx +++ b/app/client/src/pages/Editor/DataSourceEditor/DBForm.tsx @@ -135,7 +135,6 @@ class DatasourceDBEditor extends JSONtoForm<Props> { {!_.isNil(formConfig) && !_.isNil(datasource) ? ( <DatasourceInformation config={formConfig[0]} - currentEnvironment={this.props.currentEnvironment} datasource={datasource} viewMode={viewMode} /> diff --git a/app/client/src/pages/Editor/DataSourceEditor/DSFormHeader.tsx b/app/client/src/pages/Editor/DataSourceEditor/DSFormHeader.tsx index 83f55b79f7d4..f2cda0163b8e 100644 --- a/app/client/src/pages/Editor/DataSourceEditor/DSFormHeader.tsx +++ b/app/client/src/pages/Editor/DataSourceEditor/DSFormHeader.tsx @@ -38,7 +38,7 @@ export const Header = styled.div` 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); + padding: var(--ads-v2-spaces-5) 0 var(--ads-v2-spaces-5); margin: 0 var(--ads-v2-spaces-7); height: 120px; `; @@ -77,7 +77,10 @@ type DSFormHeaderProps = { pluginImage: string; pluginType: string; pluginName: string; - setDatasourceViewMode: (viewMode: boolean) => void; + setDatasourceViewMode: (payload: { + datasourceId: string; + viewMode: boolean; + }) => void; viewMode: boolean; }; @@ -173,7 +176,10 @@ export const DSFormHeader = (props: DSFormHeaderProps) => { className="t--edit-datasource" kind="secondary" onClick={() => { - setDatasourceViewMode(false); + setDatasourceViewMode({ + datasourceId: datasourceId, + viewMode: false, + }); AnalyticsUtil.logEvent("EDIT_DATASOURCE_CLICK", { datasourceId: datasourceId, pluginName, diff --git a/app/client/src/pages/Editor/DataSourceEditor/DatasourceSection.tsx b/app/client/src/pages/Editor/DataSourceEditor/DatasourceSection.tsx index 428c94cc93e1..6aba69b0ec0f 100644 --- a/app/client/src/pages/Editor/DataSourceEditor/DatasourceSection.tsx +++ b/app/client/src/pages/Editor/DataSourceEditor/DatasourceSection.tsx @@ -1,11 +1,21 @@ -import type { Datasource } from "entities/Datasource"; import React from "react"; +import type { Datasource } from "entities/Datasource"; import { map, get, isArray } from "lodash"; import styled from "styled-components"; import { isHidden, isKVArray } from "components/formControls/utils"; import log from "loglevel"; import { ComparisonOperationsEnum } from "components/formControls/BaseControl"; -import { getCurrentEnvironment } from "@appsmith/utils/Environments"; +import type { AppState } from "@appsmith/reducers"; +import { connect } from "react-redux"; +import { datasourceEnvEnabled } from "@appsmith/selectors/featureFlagsSelectors"; +import { + DB_NOT_SUPPORTED, + getCurrentEnvironment, +} from "@appsmith/utils/Environments"; +import { getPlugin } from "selectors/entitiesSelector"; +import type { PluginType } from "entities/Action"; +import { getDefaultEnvId } from "@appsmith/api/ApiUtils"; +import { EnvConfigSection } from "@appsmith/components/EnvConfigSection.tsx"; const Key = styled.div` color: var(--ads-v2-color-fg-muted); @@ -34,165 +44,225 @@ const FieldWrapper = styled.div` } `; -export default class RenderDatasourceInformation extends React.Component<{ +type RenderDatasourceSectionProps = { config: any; datasource: Datasource; viewMode?: boolean; - currentEnvironment: string; -}> { - renderKVArray = (children: Array<any>) => { - try { - // setup config for each child - const firstConfigProperty = - `datasourceStorages.${this.props.currentEnvironment}.` + - children[0].configProperty || children[0].configProperty; - const configPropertyInfo = firstConfigProperty.split("[*]."); - const values = get(this.props.datasource, configPropertyInfo[0], null); - const renderValues: Array< - Array<{ - key: string; - value: any; - label: string; - }> - > = children.reduce( - ( - acc, - { configProperty, label }: { configProperty: string; label: string }, - ) => { - const configPropertyKey = configProperty.split("[*].")[1]; - values.forEach((value: any, index: number) => { - if (!acc[index]) { - acc[index] = []; - } + showOnlyCurrentEnv?: boolean; + currentEnv: string; + isEnvEnabled: boolean; +}; +const renderKVArray = ( + children: Array<any>, + currentEnvironment: string, + datasource: Datasource, +) => { + try { + // setup config for each child + const firstConfigProperty = + `datasourceStorages.${currentEnvironment}.` + + children[0].configProperty || children[0].configProperty; + const configPropertyInfo = firstConfigProperty.split("[*]."); + const values = get(datasource, configPropertyInfo[0], null); + const renderValues: Array< + Array<{ + key: string; + value: any; + label: string; + }> + > = children.reduce( + ( + acc, + { configProperty, label }: { configProperty: string; label: string }, + ) => { + const configPropertyKey = configProperty.split("[*].")[1]; + values.forEach((value: any, index: number) => { + if (!acc[index]) { + acc[index] = []; + } - acc[index].push({ - key: configPropertyKey, - label, - value: value[configPropertyKey], - }); + acc[index].push({ + key: configPropertyKey, + label, + value: value[configPropertyKey], }); - return acc; - }, - [], - ); - return renderValues.map((renderValue, index: number) => ( - <FieldWrapper key={`${firstConfigProperty}.${index}`}> - {renderValue.map(({ key, label, value }) => ( - <ValueWrapper key={`${firstConfigProperty}.${key}.${index}`}> - <Key>{label}: </Key> - <Value>{value}</Value> - </ValueWrapper> - ))} - </FieldWrapper> - )); - } catch (e) { - return; - } - }; + }); + return acc; + }, + [], + ); + return renderValues.map((renderValue, index: number) => ( + <FieldWrapper key={`${firstConfigProperty}.${index}`}> + {renderValue.map(({ key, label, value }) => ( + <ValueWrapper key={`${firstConfigProperty}.${key}.${index}`}> + <Key>{label}: </Key> + <Value>{value}</Value> + </ValueWrapper> + ))} + </FieldWrapper> + )); + } catch (e) { + return; + } +}; - renderDatasourceSection(section: any) { - const { datasource, viewMode } = this.props; - const currentEnvironment = getCurrentEnvironment(); - return ( - <React.Fragment key={datasource.id}> - {map(section.children, (section) => { - if ( - isHidden( - datasource.datasourceStorages[currentEnvironment], - section.hidden, - undefined, - viewMode, - ) +export function renderDatasourceSection( + section: any, + currentEnvironment: string, + datasource: Datasource, + viewMode: boolean | undefined, +) { + return ( + <React.Fragment key={datasource.id}> + {map(section.children, (section) => { + if ( + isHidden( + datasource.datasourceStorages[currentEnvironment], + section.hidden, + undefined, + viewMode, ) - return null; - if ("children" in section) { - if (isKVArray(section.children)) { - return this.renderKVArray(section.children); - } + ) + return null; + if ("children" in section) { + if (isKVArray(section.children)) { + return renderKVArray( + section.children, + currentEnvironment, + datasource, + ); + } - return this.renderDatasourceSection(section); - } else { - try { - const { configProperty, controlType, label } = section; - const customConfigProperty = - `datasourceStorages.${currentEnvironment}.` + configProperty; - const reactKey = datasource.id + "_" + label; - if (controlType === "FIXED_KEY_INPUT") { - return ( - <FieldWrapper key={reactKey}> - <Key>{configProperty.key}: </Key>{" "} - <Value>{configProperty.value}</Value> - </FieldWrapper> - ); - } + return renderDatasourceSection( + section, + currentEnvironment, + datasource, + viewMode, + ); + } else { + try { + const { configProperty, controlType, label } = section; + const customConfigProperty = + `datasourceStorages.${currentEnvironment}.` + configProperty; + const reactKey = datasource.id + "_" + label; + if (controlType === "FIXED_KEY_INPUT") { + return ( + <FieldWrapper key={reactKey}> + <Key>{configProperty.key}: </Key>{" "} + <Value>{configProperty.value}</Value> + </FieldWrapper> + ); + } - let value = get(datasource, customConfigProperty); + let value = get(datasource, customConfigProperty); - if (controlType === "DROP_DOWN") { - if (Array.isArray(section.options)) { - const option = section.options.find( - (el: any) => el.value === value, - ); - if (option && option.label) { - value = option.label; - } + if (controlType === "DROP_DOWN") { + if (Array.isArray(section.options)) { + const option = section.options.find( + (el: any) => el.value === value, + ); + if (option && option.label) { + value = option.label; } } + } - if ( - !value && - !!viewMode && - !!section.hidden && - "comparison" in section.hidden && - section.hidden.comparison === ComparisonOperationsEnum.VIEW_MODE - ) { - value = section.initialValue; - } - - if (!value || (isArray(value) && value.length < 1)) { - return; - } + if ( + !value && + !!viewMode && + !!section.hidden && + "comparison" in section.hidden && + section.hidden.comparison === ComparisonOperationsEnum.VIEW_MODE + ) { + value = section.initialValue; + } - if (isArray(value)) { - return ( - <FieldWrapper> - <Key>{label}: </Key> - {value.map( - ( - { key, value }: { key: string; value: any }, - index: number, - ) => ( - <div key={`${reactKey}.${index}`}> - <div style={{ display: "inline-block" }}> - <Key>Key: </Key> - <Value>{key}</Value> - </div> - <ValueWrapper> - <Key>Value: </Key> - <Value>{value}</Value> - </ValueWrapper> - </div> - ), - )} - </FieldWrapper> - ); - } + if (!value || (isArray(value) && value.length < 1)) { + return; + } + if (isArray(value)) { return ( - <FieldWrapper key={reactKey}> - <Key>{label}: </Key> <Value>{value}</Value> + <FieldWrapper> + <Key>{label}: </Key> + {value.map( + ( + { key, value }: { key: string; value: any }, + index: number, + ) => ( + <div key={`${reactKey}.${index}`}> + <div style={{ display: "inline-block" }}> + <Key>Key: </Key> + <Value>{key}</Value> + </div> + <ValueWrapper> + <Key>Value: </Key> + <Value>{value}</Value> + </ValueWrapper> + </div> + ), + )} </FieldWrapper> ); - } catch (e) { - log.error(e); } + + return ( + <FieldWrapper key={reactKey}> + <Key>{label}: </Key> <Value>{value}</Value> + </FieldWrapper> + ); + } catch (e) { + log.error(e); } - })} - </React.Fragment> - ); - } + } + })} + </React.Fragment> + ); +} +class RenderDatasourceInformation extends React.Component<RenderDatasourceSectionProps> { render() { - return this.renderDatasourceSection(this.props.config); + const { + config, + currentEnv, + datasource, + isEnvEnabled, + showOnlyCurrentEnv, + viewMode, + } = this.props; + const { datasourceStorages } = datasource; + + if (showOnlyCurrentEnv || !isEnvEnabled) { + // in this case, we will show the env that is present in datasourceStorages + + if (!datasourceStorages) { + return null; + } + return renderDatasourceSection(config, currentEnv, datasource, viewMode); + } + + return ( + <EnvConfigSection + config={config} + currentEnv={currentEnv} + datasource={datasource} + viewMode={viewMode} + /> + ); } } +const mapStateToProps = (state: AppState, ownProps: any) => { + const { datasource } = ownProps; + const pluginId = datasource.pluginId; + const plugin = getPlugin(state, pluginId); + const pluginType = plugin?.type; + const isEnvEnabled = DB_NOT_SUPPORTED.includes(pluginType as PluginType) + ? false + : datasourceEnvEnabled(state); + return { + currentEnv: isEnvEnabled ? getCurrentEnvironment() : getDefaultEnvId(), + isEnvEnabled, + }; +}; + +export default connect(mapStateToProps)(RenderDatasourceInformation); diff --git a/app/client/src/pages/Editor/DataSourceEditor/RestAPIDatasourceForm.tsx b/app/client/src/pages/Editor/DataSourceEditor/RestAPIDatasourceForm.tsx index ebf309e138f3..295a7b3b8ea5 100644 --- a/app/client/src/pages/Editor/DataSourceEditor/RestAPIDatasourceForm.tsx +++ b/app/client/src/pages/Editor/DataSourceEditor/RestAPIDatasourceForm.tsx @@ -42,13 +42,19 @@ import { ENTITY_TYPE } from "entities/AppsmithConsole"; import { TEMP_DATASOURCE_ID } from "constants/Datasource"; import { hasManageDatasourcePermission } from "@appsmith/utils/permissionHelpers"; import { Form } from "./DBForm"; +import { + getCurrentEnvName, + getCurrentEnvironment, +} from "@appsmith/utils/Environments"; interface DatasourceRestApiEditorProps { initializeReplayEntity: (id: string, data: any) => void; updateDatasource: ( formValues: Datasource, + currEditingEnvId: string, onSuccess?: ReduxAction<unknown>, ) => void; + currentEnvironment: string; isSaving: boolean; applicationId: string; datasourceId: string; @@ -208,12 +214,18 @@ class DatasourceRestAPIEditor extends React.Component<Props> { AnalyticsUtil.logEvent("SAVE_DATA_SOURCE_CLICK", { pageId: this.props.pageId, appId: this.props.applicationId, + environmentId: getCurrentEnvironment(), + environmentName: getCurrentEnvName(), pluginName: this.props.pluginName || "", pluginPackageName: this.props.pluginPackageName || "", }); if (this.props.datasource.id !== TEMP_DATASOURCE_ID) { - return this.props.updateDatasource(normalizedValues, onSuccess); + return this.props.updateDatasource( + normalizedValues, + this.props.currentEnvironment, + onSuccess, + ); } this.props.createDatasource( @@ -1036,8 +1048,11 @@ const mapDispatchToProps = (dispatch: any) => { return { initializeReplayEntity: (id: string, data: any) => dispatch(updateReplayEntity(id, data, ENTITY_TYPE.DATASOURCE)), - updateDatasource: (formData: any, onSuccess?: ReduxAction<unknown>) => - dispatch(updateDatasource(formData, onSuccess)), + updateDatasource: ( + formData: any, + currEditingEnvId: string, + onSuccess?: ReduxAction<unknown>, + ) => dispatch(updateDatasource(formData, currEditingEnvId, onSuccess)), createDatasource: (formData: any, onSuccess?: ReduxAction<unknown>) => dispatch(createDatasourceFromForm(formData, onSuccess)), toggleSaveActionFlag: (flag: boolean) => diff --git a/app/client/src/pages/Editor/DataSourceEditor/index.tsx b/app/client/src/pages/Editor/DataSourceEditor/index.tsx index 36050495bdd4..4615055a1bcd 100644 --- a/app/client/src/pages/Editor/DataSourceEditor/index.tsx +++ b/app/client/src/pages/Editor/DataSourceEditor/index.tsx @@ -1,8 +1,14 @@ import React from "react"; import { connect } from "react-redux"; -import { getFormInitialValues, getFormValues, isDirty } from "redux-form"; +import { + getFormInitialValues, + getFormValues, + initialize, + isDirty, + reset, +} from "redux-form"; import type { AppState } from "@appsmith/reducers"; -import { get, isEqual, memoize } from "lodash"; +import { get, isEmpty, isEqual, memoize, merge } from "lodash"; import { getPluginImages, getDatasource, @@ -20,6 +26,7 @@ import { resetDefaultKeyValPairFlag, initializeDatasourceFormDefaults, datasourceDiscardAction, + setDatasourceViewModeFlag, } from "actions/datasourceActions"; import { DATASOURCE_DB_FORM, @@ -27,7 +34,8 @@ import { } from "@appsmith/constants/forms"; import DataSourceEditorForm from "./DBForm"; import RestAPIDatasourceForm from "./RestAPIDatasourceForm"; -import type { Datasource } from "entities/Datasource"; +import type { Datasource, DatasourceStorage } from "entities/Datasource"; +import { ToastMessageType } from "entities/Datasource"; import type { RouteComponentProps } from "react-router"; import EntityNotFoundPane from "pages/Editor/EntityNotFoundPane"; import { DatasourceComponentTypes } from "api/PluginApi"; @@ -44,6 +52,8 @@ import { REST_API_AUTHORIZATION_FAILED, REST_API_AUTHORIZATION_SUCCESSFUL, SAVE_BUTTON_TEXT, + TEST_DATASOURCE_ERROR, + TEST_DATASOURCE_SUCCESS, } from "@appsmith/constants/messages"; import { isDatasourceInViewMode } from "selectors/ui"; import { getQueryParams } from "utils/URLUtils"; @@ -55,7 +65,7 @@ import { hasManageDatasourcePermission, } from "@appsmith/utils/permissionHelpers"; -import { toast } from "design-system"; +import { toast, Callout } from "design-system"; import styled from "styled-components"; import CloseEditor from "components/editorComponents/CloseEditor"; import { isDatasourceAuthorizedForQueryCreation } from "utils/editorContextUtils"; @@ -66,6 +76,8 @@ import Debugger, { import { showDebuggerFlag } from "selectors/debuggerSelectors"; import DatasourceAuth from "pages/common/datasourceAuth"; import { + getConfigInitialValues, + getIsFormDirty, getTrimmedData, normalizeValues, validate, @@ -78,6 +90,8 @@ import type { PluginType } from "entities/Action"; import { PluginPackageName } from "entities/Action"; import DSDataFilter from "@appsmith/components/DSDataFilter"; import { DEFAULT_ENV_ID } from "@appsmith/api/ApiUtils"; +import { onUpdateFilterSuccess } from "@appsmith/utils/Environments"; +import type { CalloutKind } from "design-system"; interface ReduxStateProps { canCreateDatasourceActions: boolean; @@ -130,14 +144,14 @@ type Props = ReduxStateProps & pageId: string; }>; -const DSEditorWrapper = styled.div` +export const DSEditorWrapper = styled.div` height: calc(100vh - ${(props) => props.theme.headerHeight}); overflow: hidden; display: flex; flex-direction: row; `; -type DatasourceFilterState = { +export type DatasourceFilterState = { id: string; name: string; userPermissions: string[]; @@ -158,6 +172,7 @@ type DatasourceFilterState = { type State = { showDialog: boolean; routesBlocked: boolean; + switchFilterBlocked: boolean; readUrlParams: boolean; requiredFields: Record<string, ControlProps>; configDetails: Record<string, string>; @@ -169,13 +184,19 @@ type State = { export interface DatasourcePaneFunctions { switchDatasource: (id: string) => void; - setDatasourceViewMode: (viewMode: boolean) => void; + setDatasourceViewMode: (payload: { + datasourceId: string; + viewMode: boolean; + }) => void; + setDatasourceViewModeFlag: (viewMode: boolean) => void; discardTempDatasource: () => void; deleteTempDSFromDraft: () => void; toggleSaveActionFlag: (flag: boolean) => void; toggleSaveActionFromPopupFlag: (flag: boolean) => void; + reinitializeForm: (formName: string, value: any) => void; createTempDatasource: (data: any) => void; resetDefaultKeyValPairFlag: () => void; + resetForm: (formName: string) => void; initializeFormWithDefaults: (pluginType: string) => void; datasourceDiscardAction: (pluginId: string) => void; } @@ -186,6 +207,7 @@ class DatasourceEditorRouter extends React.Component<Props, State> { this.state = { showDialog: false, routesBlocked: false, + switchFilterBlocked: false, readUrlParams: false, requiredFields: {}, configDetails: {}, @@ -338,7 +360,7 @@ class DatasourceEditorRouter extends React.Component<Props, State> { readUrlParams: true, }, () => { - this.props.setDatasourceViewMode(false); + this.props.setDatasourceViewModeFlag(false); }, ); } @@ -411,11 +433,17 @@ class DatasourceEditorRouter extends React.Component<Props, State> { } onDiscard() { + this.props.resetForm(this.props.formName); this.closeDialogAndUnblockRoutes(); - this.props.discardTempDatasource(); - this.props.deleteTempDSFromDraft(); + if (this.state.switchFilterBlocked) { + //unblock switch filter + this.setState({ switchFilterBlocked: false }); + } else { + this.props.discardTempDatasource(); + this.props.deleteTempDSFromDraft(); + this.props.datasourceDiscardAction(this.props?.pluginId); + } this.state.navigation(); - this.props.datasourceDiscardAction(this.props?.pluginId); } closeDialogAndUnblockRoutes(isNavigateBack?: boolean) { @@ -448,6 +476,100 @@ class DatasourceEditorRouter extends React.Component<Props, State> { userPermissions: string[], showFilterPane: boolean, ) => { + if (id.length > 0 && this.state.filterParams.id !== id) { + if ( + !isEmpty(this.props.formData) && + this.props.isFormDirty && + this.state.filterParams.id.length > 0 + ) { + this.setState({ + showDialog: true, + switchFilterBlocked: true, + navigation: () => { + this.updateFilterSuccess(id, name, userPermissions, showFilterPane); + }, + }); + return false; + } else { + this.props.resetForm(this.props.formName); + } + return this.updateFilterSuccess( + id, + name, + userPermissions, + showFilterPane, + ); + } else if (showFilterPane !== this.state.filterParams.showFilterPane) { + // In case just the viewmode changes but the id remains the same + this.setState({ + filterParams: { + ...this.state.filterParams, + showFilterPane, + }, + }); + } + return true; + }; + + updateFilterSuccess = ( + id: string, + name: string, + userPermissions: string[], + showFilterPane: boolean, + ) => { + onUpdateFilterSuccess(id); + const { datasourceStorages } = this.props.datasource as Datasource; + // check all datasource storages and remove the ones which do not have an id object + const datasourceStoragesWithId = Object.keys(datasourceStorages).reduce( + (acc: Record<string, DatasourceStorage>, envId: string) => { + if ( + datasourceStorages[envId].hasOwnProperty("id") || + datasourceStorages[envId].hasOwnProperty("datasourceId") + ) { + acc[envId] = datasourceStorages[envId]; + } + return acc; + }, + {}, + ); + const initialValues = merge(getConfigInitialValues(this.props.formConfig), { + properties: [], + }); + if (!datasourceStoragesWithId.hasOwnProperty(id)) { + // Create the new datasource storage object + const newDsStorageObject: DatasourceStorage = { + datasourceId: this.props.datasourceId, + environmentId: id, + isValid: false, + datasourceConfiguration: initialValues.datasourceConfiguration, + toastMessage: ToastMessageType.EMPTY_TOAST_MESSAGE, + }; + + // // Add the new datasource storage object to the datasource storages + this.props.reinitializeForm(this.props.formName, { + ...this.props.formData, + datasourceStorages: { + ...datasourceStoragesWithId, + [id]: newDsStorageObject, + }, + }); + } else if ( + !datasourceStoragesWithId[id].hasOwnProperty("datasourceConfiguration") + ) { + // Add the new datasource storage object to the datasource storages + this.props.reinitializeForm(this.props.formName, { + ...this.props.formData, + datasourceStorages: { + ...datasourceStoragesWithId, + [id]: { + ...datasourceStoragesWithId[id], + datasourceConfiguration: initialValues.datasourceConfiguration, + }, + }, + }); + } + + // This is the event that changes the filter and updates the datasource this.setState({ filterParams: { id, @@ -456,6 +578,8 @@ class DatasourceEditorRouter extends React.Component<Props, State> { showFilterPane, }, }); + this.blockRoutes(); + return true; }; renderSaveDisacardModal() { @@ -472,6 +596,59 @@ class DatasourceEditorRouter extends React.Component<Props, State> { ); } + //based on type of toast message, return the message and kind. + decodeToastMessage( + messageType: string, + datasourceName: string, + environmentId: string | null, + ): { message: string; kind: string } { + switch (messageType) { + case ToastMessageType.TEST_DATASOURCE_ERROR: + return { message: createMessage(TEST_DATASOURCE_ERROR), kind: "error" }; + case ToastMessageType.TEST_DATASOURCE_SUCCESS: + return { + message: createMessage( + TEST_DATASOURCE_SUCCESS, + datasourceName, + environmentId, + ), + kind: "success", + }; + default: + return { message: "", kind: "" }; + } + } + + // function to render toast message. + renderToast() { + const { datasource } = this.props; + const environmentId = this.getEnvironmentId() || ""; + const path = `datasourceStorages.${environmentId}.toastMessage`; + const toastMessage = this.decodeToastMessage( + get(datasource, path), + (datasource as Datasource).name, + this.state.filterParams.name, + ); + if (toastMessage.message) + return ( + <div style={{ width: "30vw", marginTop: "24px", marginLeft: "24px" }}> + <Callout + isClosable + kind={toastMessage.kind as CalloutKind} + onClose={() => { + this.props.setDatasourceViewMode({ + datasourceId: this.props.datasourceId, + viewMode: false, + }); + }} + > + {toastMessage.message} + </Callout> + </div> + ); + return null; + } + renderForm() { const { datasource, @@ -492,49 +669,52 @@ class DatasourceEditorRouter extends React.Component<Props, State> { } = this.props; const shouldViewMode = viewMode && !isInsideReconnectModal; + // Check for specific form types first + if ( + pluginDatasourceForm === DatasourceComponentTypes.RestAPIDatasourceForm && + !shouldViewMode + ) { + return ( + <> + <RestAPIDatasourceForm + applicationId={this.props.applicationId} + currentEnvironment={this.state.filterParams.id} + datasource={datasource} + datasourceId={datasourceId} + formData={formData} + formName={formName} + hiddenHeader={isInsideReconnectModal} + isFormDirty={isFormDirty} + isSaving={isSaving} + location={location} + pageId={pageId} + pluginName={pluginName} + pluginPackageName={pluginPackageName} + showFilterComponent={this.state.filterParams.showFilterPane} + /> + {this.renderSaveDisacardModal()} + </> + ); + } + // Default to DB Editor Form return ( <> - { - // Check for specific form types first - pluginDatasourceForm === - DatasourceComponentTypes.RestAPIDatasourceForm && - !shouldViewMode ? ( - <RestAPIDatasourceForm - applicationId={this.props.applicationId} - datasource={datasource} - datasourceId={datasourceId} - formData={formData} - formName={formName} - hiddenHeader={isInsideReconnectModal} - isFormDirty={isFormDirty} - isSaving={isSaving} - location={location} - pageId={pageId} - pluginName={pluginName} - pluginPackageName={pluginPackageName} - showFilterComponent={this.state.filterParams.showFilterPane} - viewMode={shouldViewMode} - /> - ) : ( - // Default to DB Editor Form - <DataSourceEditorForm - applicationId={this.props.applicationId} - currentEnvironment={this.getEnvironmentId()} - datasourceId={datasourceId} - formConfig={formConfig} - formData={formData} - formName={DATASOURCE_DB_FORM} - hiddenHeader={isInsideReconnectModal} - isSaving={isSaving} - pageId={pageId} - pluginType={pluginType} - setupConfig={this.setupConfig} - showFilterComponent={this.state.filterParams.showFilterPane} - viewMode={viewMode && !isInsideReconnectModal} - /> - ) - } + <DataSourceEditorForm + applicationId={this.props.applicationId} + currentEnvironment={this.getEnvironmentId()} + datasourceId={datasourceId} + formConfig={formConfig} + formData={formData} + formName={DATASOURCE_DB_FORM} + hiddenHeader={isInsideReconnectModal} + isSaving={isSaving} + pageId={pageId} + pluginType={pluginType} + setupConfig={this.setupConfig} + showFilterComponent={this.state.filterParams.showFilterPane} + viewMode={viewMode && !isInsideReconnectModal} + /> {this.renderSaveDisacardModal()} </> ); @@ -645,12 +825,16 @@ class DatasourceEditorRouter extends React.Component<Props, State> { <ResizerContentContainer className="db-form-resizer-content"> <DSEditorWrapper> <DSDataFilter + datasourceId={datasourceId} + filterId={this.state.filterParams.id} isInsideReconnectModal={!!isInsideReconnectModal} - pluginType={this.props.pluginType} + pluginName={pluginName} + pluginType={pluginType} updateFilter={this.updateFilter} viewMode={viewMode} /> <div className="db-form-content-container"> + {this.renderToast()} {this.renderForm()} {/* Render datasource form call-to-actions */} {datasource && ( @@ -661,6 +845,7 @@ class DatasourceEditorRouter extends React.Component<Props, State> { datasourceButtonConfiguration } formData={formData} + formName={this.props.formName} getSanitizedFormData={memoize(this.getSanitizedData)} isFormDirty={this.props.isFormDirty} isInsideReconnectModal={isInsideReconnectModal} @@ -701,7 +886,11 @@ class DatasourceEditorRouter extends React.Component<Props, State> { (!createMode && !canManageDatasource) ); } - return validate(this.state.requiredFields, formData); + return validate( + this.state.requiredFields, + formData, + this.state.filterParams.id, + ); } } @@ -722,8 +911,15 @@ const mapStateToProps = (state: AppState, props: any): ReduxStateProps => { const formData = getFormValues(formName)(state) as | Datasource | ApiDatasourceForm; - const isFormDirty = - datasourceId === TEMP_DATASOURCE_ID ? true : isDirty(formName)(state); + const isNewDatasource = datasourcePane.newDatasource === TEMP_DATASOURCE_ID; + const pluginDatasourceForm = + plugin?.datasourceComponent ?? DatasourceComponentTypes.AutoForm; + const isFormDirty = getIsFormDirty( + isDirty(formName)(state), + formData, + isNewDatasource, + pluginDatasourceForm === DatasourceComponentTypes.RestAPIDatasourceForm, + ); const initialValue = getFormInitialValues(formName)(state) as | Datasource | ApiDatasourceForm; @@ -776,13 +972,12 @@ const mapStateToProps = (state: AppState, props: any): ReduxStateProps => { isPluginAuthorized: !!isPluginAuthorized, isTesting: datasources.isTesting, formConfig: formConfigs[pluginId] || [], - isNewDatasource: datasourcePane.newDatasource === TEMP_DATASOURCE_ID, + isNewDatasource, pageId: props.pageId ?? props.match?.params?.pageId, viewMode, pluginType: plugin?.type ?? "", pluginName: plugin?.name ?? "", - pluginDatasourceForm: - plugin?.datasourceComponent ?? DatasourceComponentTypes.AutoForm, + pluginDatasourceForm, pluginPackageName, applicationId: props.applicationId ?? getCurrentApplicationId(state), applicationSlug, @@ -805,15 +1000,22 @@ const mapDispatchToProps = ( // on reconnect data modal, it shouldn't be redirected to datasource edit page dispatch(switchDatasource(id, ownProps.isInsideReconnectModal)); }, - setDatasourceViewMode: (viewMode: boolean) => - dispatch(setDatasourceViewMode(viewMode)), + setDatasourceViewMode: (payload: { + datasourceId: string; + viewMode: boolean; + }) => dispatch(setDatasourceViewMode(payload)), + setDatasourceViewModeFlag: (viewMode: boolean) => + dispatch(setDatasourceViewModeFlag(viewMode)), discardTempDatasource: () => dispatch(removeTempDatasource()), deleteTempDSFromDraft: () => dispatch(deleteTempDSFromDraft()), toggleSaveActionFlag: (flag) => dispatch(toggleSaveActionFlag(flag)), toggleSaveActionFromPopupFlag: (flag) => dispatch(toggleSaveActionFromPopupFlag(flag)), + reinitializeForm: (formName: string, value: any) => + dispatch(initialize(formName, value, false)), createTempDatasource: (data: any) => dispatch(createTempDatasourceFromForm(data)), + resetForm: (formName: string) => dispatch(reset(formName)), resetDefaultKeyValPairFlag: () => dispatch(resetDefaultKeyValPairFlag()), initializeFormWithDefaults: (pluginType: string) => dispatch(initializeDatasourceFormDefaults(pluginType)), diff --git a/app/client/src/pages/Editor/EditorHeader.tsx b/app/client/src/pages/Editor/EditorHeader.tsx index 1482e26fd568..a45e06e5e89b 100644 --- a/app/client/src/pages/Editor/EditorHeader.tsx +++ b/app/client/src/pages/Editor/EditorHeader.tsx @@ -55,7 +55,7 @@ import { snipingModeSelector } from "selectors/editorSelectors"; import { showConnectGitModal } from "actions/gitSyncActions"; import RealtimeAppEditors from "./RealtimeAppEditors"; import { EditorSaveIndicator } from "./EditorSaveIndicator"; - +import { datasourceEnvEnabled } from "@appsmith/selectors/featureFlagsSelectors"; import { retryPromise } from "utils/AppsmithUtils"; import { fetchUsersForWorkspace } from "@appsmith/actions/workspaceActions"; @@ -90,6 +90,8 @@ import EmbedSnippetForm from "@appsmith/pages/Applications/EmbedSnippetTab"; import { getAppsmithConfigs } from "@appsmith/configs"; import { getIsAppSettingsPaneWithNavigationTabOpen } from "selectors/appSettingsPaneSelectors"; import type { NavigationSetting } from "constants/AppConstants"; +import { getUserPreferenceFromStorage } from "@appsmith/utils/Environments"; +import { showEnvironmentDeployInfoModal } from "@appsmith/actions/environmentAction"; import { getIsFirstTimeUserOnboardingEnabled } from "selectors/onboardingSelectors"; const { cloudHosting } = getAppsmithConfigs(); @@ -236,6 +238,7 @@ export function EditorHeader(props: PropsFromRedux) { const [isPopoverOpen, setIsPopoverOpen] = useState<boolean>(false); const [showModal, setShowModal] = useState(false); + const dsEnvEnabled = useSelector(datasourceEnvEnabled); const handlePublish = () => { if (applicationId) { @@ -290,7 +293,11 @@ export function EditorHeader(props: PropsFromRedux) { : "Application name menu (top left)", }); } else { - handlePublish(); + if (!dsEnvEnabled || getUserPreferenceFromStorage() === "true") { + handlePublish(); + } else { + dispatch(showEnvironmentDeployInfoModal()); + } } }, [dispatch, handlePublish], diff --git a/app/client/src/pages/Editor/Explorer/hooks.ts b/app/client/src/pages/Editor/Explorer/hooks.ts index 3502f52e22e0..26a581389d68 100644 --- a/app/client/src/pages/Editor/Explorer/hooks.ts +++ b/app/client/src/pages/Editor/Explorer/hooks.ts @@ -129,7 +129,7 @@ export const useAppWideAndOtherDatasource = () => { }; }; -const MAX_DATASOURCE_SUGGESTIONS = 3; +export const MAX_DATASOURCE_SUGGESTIONS = 3; export const useDatasourceSuggestions = () => { const datasourcesUsedInApplication = useCurrentApplicationDatasource(); diff --git a/app/client/src/pages/Editor/FormControl.tsx b/app/client/src/pages/Editor/FormControl.tsx index 14709142467b..a615b9d6f219 100644 --- a/app/client/src/pages/Editor/FormControl.tsx +++ b/app/client/src/pages/Editor/FormControl.tsx @@ -32,7 +32,7 @@ import { } from "constants/Datasource"; import TemplateMenu from "./QueryEditor/TemplateMenu"; import { SQL_DATASOURCES } from "../../constants/QueryEditorConstants"; -import { getCurrentEnvironment } from "@appsmith/utils/Environments"; +import { getCurrentEditingEnvID } from "@appsmith/utils/Environments"; import type { Datasource } from "entities/Datasource"; import { getSQLPluginsMockTableName } from "utils/editorContextUtils"; @@ -59,7 +59,7 @@ function FormControl(props: FormControlProps) { let formValueForEvaluatingHiddenObj = formValues; if (!!formValues && formValues.hasOwnProperty("datasourceStorages")) { formValueForEvaluatingHiddenObj = (formValues as Datasource) - .datasourceStorages[getCurrentEnvironment()]; + .datasourceStorages[getCurrentEditingEnvID()]; } const hidden = isHidden(formValueForEvaluatingHiddenObj, props.config.hidden); const configErrors: EvaluationError[] = useSelector( diff --git a/app/client/src/pages/Editor/IntegrationEditor/DatasourceCard.tsx b/app/client/src/pages/Editor/IntegrationEditor/DatasourceCard.tsx index 246653c42428..22d0b1a4db75 100644 --- a/app/client/src/pages/Editor/IntegrationEditor/DatasourceCard.tsx +++ b/app/client/src/pages/Editor/IntegrationEditor/DatasourceCard.tsx @@ -46,8 +46,8 @@ import { getAssetUrl } from "@appsmith/utils/airgapHelpers"; import { MenuWrapper, StyledMenu } from "components/utils/formComponents"; import { DatasourceEditEntryPoints } from "constants/Datasource"; import { - getCurrentEnvironment, isEnvironmentConfigured, + getCurrentEnvironment, } from "@appsmith/utils/Environments"; const Wrapper = styled.div` @@ -190,6 +190,8 @@ function DatasourceCard(props: DatasourceCardProps) { datasourceFormConfigs[datasource?.pluginId ?? ""]; const QUERY = queriesWithThisDatasource > 1 ? "queries" : "query"; + const currentEnv = getCurrentEnvironment(); + const editDatasource = useCallback(() => { AnalyticsUtil.logEvent("DATASOURCE_CARD_EDIT_ACTION"); if (plugin && plugin.type === PluginType.SAAS) { @@ -279,12 +281,12 @@ function DatasourceCard(props: DatasourceCardProps) { </Queries> </div> <ButtonsWrapper className="action-wrapper"> - {(!isEnvironmentConfigured(datasource) || + {(!isEnvironmentConfigured(datasource, currentEnv) || supportTemplateGeneration) && isDatasourceAuthorizedForQueryCreation(datasource, plugin) && ( <Button className={ - isEnvironmentConfigured(datasource) + isEnvironmentConfigured(datasource, currentEnv) ? "t--generate-template" : "t--reconnect-btn" } @@ -292,18 +294,18 @@ function DatasourceCard(props: DatasourceCardProps) { onClick={(e) => { e.stopPropagation(); e.preventDefault(); - isEnvironmentConfigured(datasource) + isEnvironmentConfigured(datasource, currentEnv) ? routeToGeneratePage() : editDatasource(); }} size="md" > - {isEnvironmentConfigured(datasource) + {isEnvironmentConfigured(datasource, currentEnv) ? createMessage(GENERATE_NEW_PAGE_BUTTON_TEXT) : createMessage(RECONNECT_BUTTON_TEXT)} </Button> )} - {isEnvironmentConfigured(datasource) && ( + {isEnvironmentConfigured(datasource, currentEnv) && ( <NewActionButton datasource={datasource} disabled={ @@ -385,8 +387,8 @@ function DatasourceCard(props: DatasourceCardProps) { <DatasourceInfo> <RenderDatasourceInformation config={currentFormConfig[0]} - currentEnvironment={getCurrentEnvironment()} datasource={datasource} + showOnlyCurrentEnv /> </DatasourceInfo> </CollapseComponent> diff --git a/app/client/src/pages/Editor/IntegrationEditor/IntegrationsHomeScreen.tsx b/app/client/src/pages/Editor/IntegrationEditor/IntegrationsHomeScreen.tsx index 1818861505a7..7f139811ea10 100644 --- a/app/client/src/pages/Editor/IntegrationEditor/IntegrationsHomeScreen.tsx +++ b/app/client/src/pages/Editor/IntegrationEditor/IntegrationsHomeScreen.tsx @@ -93,41 +93,6 @@ const NewIntegrationsContainer = styled.div` } `; -// This replaces a previous instance of tab. It's a menu, but it's styled to look like a tab from ads. -// This is because this is the only such instance of vertical menu on our platform. When we refactor the view -// on this screen to have a smaller grid size, we should consider removing this entirely. -const VerticalMenu = styled.nav` - display: flex; - flex-direction: column; - align-items: start; - gap: 8px; - - color: var(--ads-v2-color-fg-muted); - // &&&& to override blueprint styles - &&&&&& :hover { - color: var(--ads-v2-color-fg) !important; - text-decoration: none !important; - } -`; - -const VerticalMenuItem = styled.a` - display: flex; - align-items: center; - - height: 30px; - font-size: 14px; - padding-left: 8px; - border-left: solid 2px transparent; - - :hover { - border-left: solid 2px var(--ads-v2-color-border-emphasis); - } - - &[aria-selected="true"] { - border-left: solid 2px var(--ads-v2-color-border-brand); - } -`; - type IntegrationsHomeScreenProps = { pageId: string; selectedTab: string; @@ -162,35 +127,6 @@ const PRIMARY_MENU_IDS = { CREATE_NEW: "CREATE_NEW", }; -const SECONDARY_MENU_IDS = { - API: "API", - DATABASE: "DATABASE", - MOCK_DATABASE: "MOCK_DATABASE", -}; - -const SECONDARY_MENU: TabProp[] = [ - { - key: "API", - title: "API", - panelComponent: <div />, - }, - { - key: "DATABASE", - title: "Database", - panelComponent: <div />, - }, -]; -const getSecondaryMenu = (hasActiveSources: boolean) => { - const mockDbMenu = { - key: "MOCK_DATABASE", - title: "Sample databases", - panelComponent: <div />, - }; - return hasActiveSources - ? [...SECONDARY_MENU, mockDbMenu] - : [mockDbMenu, ...SECONDARY_MENU]; -}; - const getSecondaryMenuIds = (hasActiveSources = false) => { return { API: 0 + (hasActiveSources ? 0 : 1), @@ -227,7 +163,7 @@ function UseMockDatasources({ active, mockDatasources }: MockDataSourcesProps) { }, [active]); return ( <div id="mock-database" ref={useMockRef}> - <Text type={TextType.H2}>Sample databases</Text> + <Text type={TextType.H2}>Get started with our sample datasources</Text> <MockDataSources mockDatasources={mockDatasources} /> </div> ); @@ -264,6 +200,45 @@ function CreateNewAPI({ isCreating={isCreating} location={location} pageId={pageId} + showSaasAPIs={false} + showUnsupportedPluginDialog={showUnsupportedPluginDialog} + /> + </div> + ); +} + +function CreateNewSaasIntegration({ + active, + history, + isCreating, + pageId, + showUnsupportedPluginDialog, +}: any) { + const newSaasAPIRef = useRef<HTMLDivElement>(null); + const isMounted = useRef(false); + + useEffect(() => { + if (active && newSaasAPIRef.current) { + isMounted.current && + scrollIntoView(newSaasAPIRef.current, { + behavior: "smooth", + scrollMode: "always", + block: "start", + boundary: document.getElementById("new-integrations-wrapper"), + }); + } else { + isMounted.current = true; + } + }, [active]); + return ( + <div id="new-saas-api" ref={newSaasAPIRef}> + <Text type={TextType.H2}>Saas Integrations</Text> + <NewApiScreen + history={history} + isCreating={isCreating} + location={location} + pageId={pageId} + showSaasAPIs showUnsupportedPluginDialog={showUnsupportedPluginDialog} /> </div> @@ -509,6 +484,17 @@ class IntegrationsHomeScreen extends React.Component< pageId={pageId} showUnsupportedPluginDialog={this.showUnsupportedPluginDialog} /> + <CreateNewSaasIntegration + active={ + activeSecondaryMenuId === + getSecondaryMenuIds(dataSources.length > 0).API + } + history={history} + isCreating={isCreating} + location={location} + pageId={pageId} + showUnsupportedPluginDialog={this.showUnsupportedPluginDialog} + /> {dataSources.length > 0 && this.props.mockDatasources.length > 0 && mockDataSection} @@ -583,36 +569,6 @@ class IntegrationsHomeScreen extends React.Component< <ResizerMainContainer> <ResizerContentContainer className="integrations-content-container"> {currentScreen} - {activePrimaryMenuId === PRIMARY_MENU_IDS.CREATE_NEW && ( - <VerticalMenu> - {getSecondaryMenu(dataSources.length > 0).map((item) => { - return ( - <VerticalMenuItem - aria-selected={ - this.state.activeSecondaryMenuId === - getSecondaryMenuIds(dataSources.length > 0)[ - item.key as keyof typeof SECONDARY_MENU_IDS - ] - } - key={ - getSecondaryMenuIds(dataSources.length > 0)[ - item.key as keyof typeof SECONDARY_MENU_IDS - ] - } - onClick={() => - this.onSelectSecondaryMenu( - getSecondaryMenuIds(dataSources.length > 0)[ - item.key as keyof typeof SECONDARY_MENU_IDS - ], - ) - } - > - {item.title} - </VerticalMenuItem> - ); - })} - </VerticalMenu> - )} </ResizerContentContainer> {showDebugger && <Debugger />} </ResizerMainContainer> diff --git a/app/client/src/pages/Editor/IntegrationEditor/NewApi.tsx b/app/client/src/pages/Editor/IntegrationEditor/NewApi.tsx index 102ab3c8ca6e..f88c3d60c0f4 100644 --- a/app/client/src/pages/Editor/IntegrationEditor/NewApi.tsx +++ b/app/client/src/pages/Editor/IntegrationEditor/NewApi.tsx @@ -136,6 +136,7 @@ type ApiHomeScreenProps = { isCreating: boolean; showUnsupportedPluginDialog: (callback: any) => void; createTempDatasourceFromForm: (data: any) => void; + showSaasAPIs: boolean; // If this is true, only SaaS APIs will be shown }; type Props = ApiHomeScreenProps; @@ -149,7 +150,14 @@ const API_ACTION = { }; function NewApiScreen(props: Props) { - const { createNewApiAction, history, isCreating, pageId, plugins } = props; + const { + createNewApiAction, + history, + isCreating, + pageId, + plugins, + showSaasAPIs, + } = props; const generateCRUDSupportedPlugin: GenerateCRUDEnabledPluginMap = useSelector( getGenerateCRUDEnabledPluginMap, @@ -250,74 +258,61 @@ function NewApiScreen(props: Props) { }; // Api plugins with Graphql - const API_PLUGINS = plugins.filter( - (p) => p.packageName === PluginPackageName.GRAPHQL, + const API_PLUGINS = plugins.filter((p) => + !showSaasAPIs + ? p.packageName === PluginPackageName.GRAPHQL + : p.type === PluginType.SAAS || p.type === PluginType.REMOTE, ); - plugins.forEach((p) => { - if (p.type === PluginType.SAAS || p.type === PluginType.REMOTE) { - API_PLUGINS.push(p); - } - }); - return ( <StyledContainer> <ApiCardsContainer data-testid="newapi-datasource-card-container"> - <ApiCard - className="t--createBlankApiCard create-new-api" - onClick={() => handleOnClick(API_ACTION.CREATE_NEW_API)} - > - <CardContentWrapper data-testid="newapi-datasource-content-wrapper"> - <img - alt="New" - className="curlImage t--plusImage content-icon" - src={PlusLogo} - /> - <p className="textBtn">REST API</p> - </CardContentWrapper> - {isCreating && <Spinner className="cta" size={25} />} - </ApiCard> - <ApiCard - className="t--createBlankCurlCard" - onClick={() => handleOnClick(API_ACTION.IMPORT_CURL)} - > - <CardContentWrapper> - <img - alt="CURL" - className="curlImage t--curlImage content-icon" - src={CurlLogo} - /> - <p className="textBtn">CURL import</p> - </CardContentWrapper> - </ApiCard> - {authApiPlugin && ( - <ApiCard - className="t--createAuthApiDatasource" - onClick={() => handleOnClick(API_ACTION.AUTH_API)} - > - <CardContentWrapper> - <img - alt="OAuth2" - className="authApiImage t--authApiImage content-icon" - src={getAssetUrl(authApiPlugin.iconLocation)} - /> - <p className="t--plugin-name textBtn">Authenticated API</p> - </CardContentWrapper> - </ApiCard> + {!showSaasAPIs && ( + <> + <ApiCard + className="t--createBlankApiCard create-new-api" + onClick={() => handleOnClick(API_ACTION.CREATE_NEW_API)} + > + <CardContentWrapper data-testid="newapi-datasource-content-wrapper"> + <img + alt="New" + className="curlImage t--plusImage content-icon" + src={PlusLogo} + /> + <p className="textBtn">REST API</p> + </CardContentWrapper> + {isCreating && <Spinner className="cta" size={25} />} + </ApiCard> + <ApiCard + className="t--createBlankApiGraphqlCard" + onClick={() => handleOnClick(API_ACTION.CREATE_NEW_GRAPHQL_API)} + > + <CardContentWrapper> + <img + alt="New" + className="curlImage t--plusImage content-icon" + src={PlusLogo} + /> + <p className="textBtn">GraphQL API</p> + </CardContentWrapper> + </ApiCard> + {authApiPlugin && ( + <ApiCard + className="t--createAuthApiDatasource" + onClick={() => handleOnClick(API_ACTION.AUTH_API)} + > + <CardContentWrapper> + <img + alt="OAuth2" + className="authApiImage t--authApiImage content-icon" + src={getAssetUrl(authApiPlugin.iconLocation)} + /> + <p className="t--plugin-name textBtn">Authenticated API</p> + </CardContentWrapper> + </ApiCard> + )} + </> )} - <ApiCard - className="t--createBlankApiGraphqlCard" - onClick={() => handleOnClick(API_ACTION.CREATE_NEW_GRAPHQL_API)} - > - <CardContentWrapper> - <img - alt="New" - className="curlImage t--plusImage content-icon" - src={PlusLogo} - /> - <p className="textBtn">GraphQL API</p> - </CardContentWrapper> - </ApiCard> {API_PLUGINS.map((p) => ( <ApiCard className={`t--createBlankApi-${p.packageName}`} @@ -344,6 +339,21 @@ function NewApiScreen(props: Props) { </CardContentWrapper> </ApiCard> ))} + {!showSaasAPIs && ( + <ApiCard + className="t--createBlankCurlCard" + onClick={() => handleOnClick(API_ACTION.IMPORT_CURL)} + > + <CardContentWrapper> + <img + alt="CURL" + className="curlImage t--curlImage content-icon" + src={CurlLogo} + /> + <p className="textBtn">CURL import</p> + </CardContentWrapper> + </ApiCard> + )} </ApiCardsContainer> </StyledContainer> ); diff --git a/app/client/src/pages/Editor/MainContainer.tsx b/app/client/src/pages/Editor/MainContainer.tsx index 1bac62950985..7988f414ae01 100644 --- a/app/client/src/pages/Editor/MainContainer.tsx +++ b/app/client/src/pages/Editor/MainContainer.tsx @@ -4,7 +4,6 @@ import React, { useCallback } from "react"; import { Route, Switch, useRouteMatch } from "react-router"; import { updateExplorerWidthAction } from "actions/explorerActions"; -import classNames from "classnames"; import EntityExplorerSidebar from "components/editorComponents/Sidebar"; import { BUILDER_CUSTOM_PATH, @@ -23,13 +22,11 @@ import BottomBar from "components/BottomBar"; const SentryRoute = Sentry.withSentryRouting(Route); -const Container = styled.div<{ - isPreviewMode: boolean; -}>` +const Container = styled.div` display: flex; height: calc( 100vh - ${(props) => props.theme.smallHeaderHeight} - - ${(props) => (props.isPreviewMode ? "0px" : props.theme.bottomBarHeight)} + ${(props) => props.theme.bottomBarHeight} ); background-color: ${(props) => props.theme.appBackground}; `; @@ -61,10 +58,7 @@ function MainContainer() { return ( <> - <Container - className="relative w-full overflow-x-hidden" - isPreviewMode={isPreviewMode} - > + <Container className="relative w-full overflow-x-hidden"> <EntityExplorerSidebar onDragEnd={onLeftSidebarDragEnd} onWidthChange={onLeftSidebarWidthChange} @@ -100,13 +94,7 @@ function MainContainer() { </Switch> </div> </Container> - <BottomBar - className={classNames({ - "translate-y-full bottom-0 overflow-hidden": isPreviewMode, - "translate-y-0 opacity-100": !isPreviewMode, - "transition-all transform duration-400": true, - })} - /> + <BottomBar viewMode={isPreviewMode} /> <Installer left={sidebarWidth} /> </> ); diff --git a/app/client/src/pages/Editor/QueryEditor/index.tsx b/app/client/src/pages/Editor/QueryEditor/index.tsx index 020276eedec7..8776f9ea279b 100644 --- a/app/client/src/pages/Editor/QueryEditor/index.tsx +++ b/app/client/src/pages/Editor/QueryEditor/index.tsx @@ -50,6 +50,10 @@ import { getConfigInitialValues } from "components/formControls/utils"; import { merge } from "lodash"; import { getPathAndValueFromActionDiffObject } from "../../../utils/getPathAndValueFromActionDiffObject"; import { DatasourceCreateEntryPoints } from "constants/Datasource"; +import { + getCurrentEnvName, + getCurrentEnvironment, +} from "@appsmith/utils/Environments"; const EmptyStateContainer = styled.div` display: flex; @@ -163,6 +167,8 @@ class QueryEditor extends React.Component<Props> { AnalyticsUtil.logEvent("RUN_QUERY_CLICK", { actionId: this.props.actionId, dataSourceSize: dataSources.length, + environmentId: getCurrentEnvironment(), + environmentName: getCurrentEnvName(), pluginName: pluginName, datasourceId: datasource?.id, isMock: !!datasource?.isMock, diff --git a/app/client/src/pages/Editor/SaaSEditor/DatasourceCard.tsx b/app/client/src/pages/Editor/SaaSEditor/DatasourceCard.tsx index f310e32058ce..2a7f702354e5 100644 --- a/app/client/src/pages/Editor/SaaSEditor/DatasourceCard.tsx +++ b/app/client/src/pages/Editor/SaaSEditor/DatasourceCard.tsx @@ -19,7 +19,6 @@ import { BaseButton } from "components/designSystems/appsmith/BaseButton"; import { saasEditorDatasourceIdURL } from "RouteBuilder"; import { getAssetUrl } from "@appsmith/utils/airgapHelpers"; import { Button } from "design-system"; -import { getCurrentEnvironment } from "@appsmith/utils/Environments"; const Wrapper = styled.div` border: 2px solid #d6d6d6; @@ -157,8 +156,8 @@ function DatasourceCard(props: DatasourceCardProps) { {!isEmpty(currentFormConfig) ? ( <RenderDatasourceInformation config={currentFormConfig[0]} - currentEnvironment={getCurrentEnvironment()} datasource={datasource} + showOnlyCurrentEnv /> ) : undefined} </Wrapper> diff --git a/app/client/src/pages/Editor/SaaSEditor/DatasourceForm.tsx b/app/client/src/pages/Editor/SaaSEditor/DatasourceForm.tsx index 5b25436e52c5..c492467e605b 100644 --- a/app/client/src/pages/Editor/SaaSEditor/DatasourceForm.tsx +++ b/app/client/src/pages/Editor/SaaSEditor/DatasourceForm.tsx @@ -76,7 +76,11 @@ import Debugger, { } from "../DataSourceEditor/Debugger"; import { showDebuggerFlag } from "selectors/debuggerSelectors"; import { Form, ViewModeWrapper } from "../DataSourceEditor/DBForm"; -import { getCurrentEnvironment } from "@appsmith/utils/Environments"; +import { getCurrentEditingEnvID } from "@appsmith/utils/Environments"; +import DSDataFilter from "@appsmith/components/DSDataFilter"; +import { DSEditorWrapper } from "../DataSourceEditor"; +import type { DatasourceFilterState } from "../DataSourceEditor"; +import { getQueryParams } from "utils/URLUtils"; interface StateProps extends JSONtoFormProps { applicationId: string; @@ -115,7 +119,10 @@ interface DatasourceFormFunctions { toggleSaveActionFlag: (flag: boolean) => void; toggleSaveActionFromPopupFlag: (flag: boolean) => void; createTempDatasource: (data: any) => void; - setDatasourceViewMode: (viewMode: boolean) => void; + setDatasourceViewMode: (payload: { + datasourceId: string; + viewMode: boolean; + }) => void; loadFilePickerAction: () => void; datasourceDiscardAction: (pluginId: string) => void; initializeDatasource: (values: any) => void; @@ -139,6 +146,8 @@ type Props = DatasourceSaaSEditorProps & type State = { showDialog: boolean; routesBlocked: boolean; + readUrlParams: boolean; + filterParams: DatasourceFilterState; unblock(): void; navigation(): void; }; @@ -167,7 +176,7 @@ class SaasEditorWrapper extends React.Component< this.state = { requiredFields: {}, configDetails: {}, - currentEditingEnvironment: getCurrentEnvironment(), + currentEditingEnvironment: getCurrentEditingEnvID(), }; } @@ -213,6 +222,13 @@ class DatasourceSaaSEditor extends JSONtoForm<Props, State> { this.state = { showDialog: false, routesBlocked: false, + readUrlParams: false, + filterParams: { + id: "", + name: "", + userPermissions: [], + showFilterPane: false, + }, unblock: () => { return undefined; }, @@ -221,6 +237,7 @@ class DatasourceSaaSEditor extends JSONtoForm<Props, State> { }, }; this.closeDialog = this.closeDialog.bind(this); + this.updateFilter = this.updateFilter.bind(this); this.onSave = this.onSave.bind(this); this.onDiscard = this.onDiscard.bind(this); this.datasourceDeleteTrigger = this.datasourceDeleteTrigger.bind(this); @@ -250,12 +267,40 @@ class DatasourceSaaSEditor extends JSONtoForm<Props, State> { this.blockRoutes(); } + this.setViewModeFromQueryParams(); + // When save button is clicked in DS form, routes should be unblocked if (this.props.isDatasourceBeingSaved) { this.closeDialogAndUnblockRoutes(); } } + // To move to edit state for new datasources and when we want to move to edit state + // from outside the datasource route + setViewModeFromQueryParams() { + const params = getQueryParams(); + if (this.props.viewMode) { + if ( + (params.viewMode === "false" && !this.state.readUrlParams) || + this.props.isNewDatasource + ) { + // We just want to read the query params once. Cannot remove query params + // here as this triggers history.block + this.setState( + { + readUrlParams: true, + }, + () => { + this.props.setDatasourceViewMode({ + datasourceId: this.props.datasourceId, + viewMode: false, + }); + }, + ); + } + } + } + routesBlockFormChangeCallback() { if (this.props.isFormDirty) { if (!this.state.routesBlocked) { @@ -268,6 +313,28 @@ class DatasourceSaaSEditor extends JSONtoForm<Props, State> { } } + updateFilter( + id: string, + name: string, + userPermissions: string[], + showFilterPane: boolean, + ) { + if ( + this.state.filterParams.id === id && + this.state.filterParams.showFilterPane === showFilterPane + ) + return false; + this.setState({ + filterParams: { + id, + name, + userPermissions, + showFilterPane, + }, + }); + return true; + } + componentDidMount() { const urlObject = new URL(window?.location?.href); const pluginId = urlObject?.searchParams?.get("pluginId"); @@ -432,91 +499,108 @@ class DatasourceSaaSEditor extends JSONtoForm<Props, State> { )} <ResizerMainContainer> <ResizerContentContainer className="db-form-resizer-content"> - <Form - onSubmit={(e) => { - e.preventDefault(); - }} - showFilterComponent={false} - viewMode={viewMode} - > - {(!viewMode || createFlow || isInsideReconnectModal) && ( - <> - {/* This adds information banner when creating google sheets datasource, - this info banner explains why appsmith requires permissions from users google account */} - {datasource && isGoogleSheetPlugin && createFlow ? ( - <AuthMessage - actionType={ActionType.DOCUMENTATION} - calloutType="info" - datasource={datasource} - description={googleSheetsInfoMessage} - pageId={pageId} - /> - ) : null} - {/* This adds error banner for google sheets datasource if the datasource is unauthorised */} - {datasource && - isGoogleSheetPlugin && - !isPluginAuthorized && - datasourceId !== TEMP_DATASOURCE_ID ? ( - <AuthMessage - datasource={datasource} - description={authErrorMessage} - pageId={pageId} - /> - ) : null} - {!isNil(sections) - ? map(sections, this.renderMainSection) - : null} - {""} - </> - )} - {viewMode && !isInsideReconnectModal && ( - <ViewModeWrapper> - {datasource && isGoogleSheetPlugin && !isPluginAuthorized ? ( - <AuthMessage - actionType={ActionType.AUTHORIZE} - datasource={datasource} - description={authErrorMessage} - isInViewMode - pageId={pageId} - /> - ) : null} - {!isNil(formConfig) && - !isNil(datasource) && - !hideDatasourceSection ? ( - <DatasourceInformation - config={formConfig[0]} - currentEnvironment={this.props.currentEnvironment} - datasource={datasource} - viewMode={viewMode} - /> - ) : undefined} - </ViewModeWrapper> - )} - </Form> - {/* Render datasource form call-to-actions */} - {datasource && ( - <DatasourceAuth - currentEnvironment={this.props.currentEnvironment} - datasource={datasource} - datasourceButtonConfiguration={datasourceButtonConfiguration} - formData={formData} - getSanitizedFormData={memoize(this.getSanitizedData)} - isInsideReconnectModal={isInsideReconnectModal} - isInvalid={validate(this.props.requiredFields, formData)} - isSaving={isSaving} - isTesting={isTesting} - pageId={pageId} + <DSEditorWrapper> + <DSDataFilter + datasourceId={datasourceId} + filterId={this.state.filterParams.id} + isInsideReconnectModal={!!isInsideReconnectModal} pluginName={plugin?.name || ""} - pluginPackageName={pluginPackageName} - pluginType={plugin?.type as PluginType} - scopeValue={scopeValue} - setDatasourceViewMode={setDatasourceViewMode} - shouldDisplayAuthMessage={!isGoogleSheetPlugin} - showFilterComponent={false} - triggerSave={this.props.isDatasourceBeingSavedFromPopup} + pluginType={plugin?.type || ""} + updateFilter={this.updateFilter} viewMode={viewMode} /> - )} + <div className="db-form-content-container"> + <Form + onSubmit={(e) => { + e.preventDefault(); + }} + showFilterComponent={this.state.filterParams.showFilterPane} + viewMode={viewMode} + > + {(!viewMode || createFlow || isInsideReconnectModal) && ( + <> + {/* This adds information banner when creating google sheets datasource, + this info banner explains why appsmith requires permissions from users google account */} + {datasource && isGoogleSheetPlugin && createFlow ? ( + <AuthMessage + actionType={ActionType.DOCUMENTATION} + calloutType="info" + datasource={datasource} + description={googleSheetsInfoMessage} + pageId={pageId} + /> + ) : null} + {/* This adds error banner for google sheets datasource if the datasource is unauthorised */} + {datasource && + isGoogleSheetPlugin && + !isPluginAuthorized && + datasourceId !== TEMP_DATASOURCE_ID ? ( + <AuthMessage + datasource={datasource} + description={authErrorMessage} + pageId={pageId} + /> + ) : null} + {!isNil(sections) + ? map(sections, this.renderMainSection) + : null} + {""} + </> + )} + {viewMode && !isInsideReconnectModal && ( + <ViewModeWrapper> + {datasource && + isGoogleSheetPlugin && + !isPluginAuthorized ? ( + <AuthMessage + actionType={ActionType.AUTHORIZE} + datasource={datasource} + description={authErrorMessage} + isInViewMode + pageId={pageId} + /> + ) : null} + {!isNil(formConfig) && + !isNil(datasource) && + !hideDatasourceSection ? ( + <DatasourceInformation + config={formConfig[0]} + datasource={datasource} + viewMode={viewMode} + /> + ) : undefined} + </ViewModeWrapper> + )} + </Form> + {/* Render datasource form call-to-actions */} + {datasource && ( + <DatasourceAuth + currentEnvironment={this.props.currentEnvironment} + datasource={datasource} + datasourceButtonConfiguration={ + datasourceButtonConfiguration + } + formData={formData} + formName={this.props.formName} + getSanitizedFormData={memoize(this.getSanitizedData)} + isInsideReconnectModal={isInsideReconnectModal} + isInvalid={validate(this.props.requiredFields, formData)} + isSaving={isSaving} + isTesting={isTesting} + pageId={pageId} + pluginName={plugin?.name || ""} + pluginPackageName={pluginPackageName} + pluginType={plugin?.type as PluginType} + scopeValue={scopeValue} + setDatasourceViewMode={setDatasourceViewMode} + shouldDisplayAuthMessage={!isGoogleSheetPlugin} + showFilterComponent={this.state.filterParams.showFilterPane} + triggerSave={this.props.isDatasourceBeingSavedFromPopup} + viewMode={viewMode} + /> + )} + </div> + </DSEditorWrapper> </ResizerContentContainer> {showDebugger && <Debugger />} </ResizerMainContainer> @@ -602,7 +686,11 @@ const mapStateToProps = (state: AppState, props: any) => { const isPluginAuthorized = !!plugin && !!formData - ? isDatasourceAuthorizedForQueryCreation(formData, plugin) + ? isDatasourceAuthorizedForQueryCreation( + formData, + plugin, + getCurrentEditingEnvID(), + ) : true; return { @@ -649,15 +737,18 @@ const mapDispatchToProps = (dispatch: any): DatasourceFormFunctions => ({ toggleSaveActionFlag: (flag) => dispatch(toggleSaveActionFlag(flag)), toggleSaveActionFromPopupFlag: (flag) => dispatch(toggleSaveActionFromPopupFlag(flag)), - setDatasourceViewMode: (viewMode: boolean) => { + setDatasourceViewMode: (payload: { + datasourceId: string; + viewMode: boolean; + }) => { // Construct URLSearchParams object instance from current URL querystring. const queryParams = new URLSearchParams(window.location.search); - queryParams.set("viewMode", viewMode.toString()); + queryParams.set("viewMode", payload.viewMode.toString()); // Replace current querystring with the new one. history.replaceState({}, "", "?" + queryParams.toString()); - dispatch(setDatasourceViewMode(viewMode)); + dispatch(setDatasourceViewMode(payload)); }, createTempDatasource: (data: any) => dispatch(createTempDatasourceFromForm(data)), diff --git a/app/client/src/pages/Editor/SaaSEditor/__data__/FinalState.json b/app/client/src/pages/Editor/SaaSEditor/__data__/FinalState.json index d3f7fd48fc20..b6f5a2aac969 100644 --- a/app/client/src/pages/Editor/SaaSEditor/__data__/FinalState.json +++ b/app/client/src/pages/Editor/SaaSEditor/__data__/FinalState.json @@ -157,13 +157,13 @@ "controlType": "SEGMENTED_CONTROL", "initialValue": "READ_WRITE", "options": [ - { - "label": "Read only", - "value": "READ_ONLY" - }, { "label": "Read / Write", "value": "READ_WRITE" + }, + { + "label": "Read only", + "value": "READ_ONLY" } ], "hidden": { @@ -332,13 +332,13 @@ "isRequired": true, "initialValue": "READ_WRITE", "options": [ - { - "label": "Read only", - "value": "READ_ONLY" - }, { "label": "Read / Write", "value": "READ_WRITE" + }, + { + "label": "Read only", + "value": "READ_ONLY" } ] }, diff --git a/app/client/src/pages/Editor/SaaSEditor/__data__/InitialState.json b/app/client/src/pages/Editor/SaaSEditor/__data__/InitialState.json index 047d81e76d95..5e63ef3b3820 100644 --- a/app/client/src/pages/Editor/SaaSEditor/__data__/InitialState.json +++ b/app/client/src/pages/Editor/SaaSEditor/__data__/InitialState.json @@ -156,13 +156,13 @@ "controlType": "SEGMENTED_CONTROL", "initialValue": "READ_WRITE", "options": [ - { - "label": "Read only", - "value": "READ_ONLY" - }, { "label": "Read / Write", "value": "READ_WRITE" + }, + { + "label": "Read only", + "value": "READ_ONLY" } ], "hidden": { @@ -331,13 +331,13 @@ "isRequired": true, "initialValue": "READ_WRITE", "options": [ - { - "label": "Read only", - "value": "READ_ONLY" - }, { "label": "Read / Write", "value": "READ_WRITE" + }, + { + "label": "Read only", + "value": "READ_ONLY" } ] }, diff --git a/app/client/src/pages/Editor/gitSync/GitSyncModal.tsx b/app/client/src/pages/Editor/gitSync/GitSyncModal.tsx index e21a6a8a3e34..fe9c9fe5d4f9 100644 --- a/app/client/src/pages/Editor/gitSync/GitSyncModal.tsx +++ b/app/client/src/pages/Editor/gitSync/GitSyncModal.tsx @@ -24,6 +24,7 @@ import { import AnalyticsUtil from "utils/AnalyticsUtil"; import { useGitConnect } from "./hooks"; import { Modal, ModalContent, ModalHeader } from "design-system"; +import { EnvInfoHeader } from "@appsmith/components/EnvInfoHeader"; const ModalContentContainer = styled(ModalContent)` min-height: 650px; @@ -124,6 +125,7 @@ function GitSyncModal(props: { isImport?: boolean }) { <ModalHeader> {MENU_ITEMS_MAP[activeTabKey]?.modalTitle ?? ""} </ModalHeader> + <EnvInfoHeader /> <Menu activeTabKey={activeTabKey} onSelect={(tabKey: string) => diff --git a/app/client/src/pages/Editor/gitSync/ReconnectDatasourceModal.tsx b/app/client/src/pages/Editor/gitSync/ReconnectDatasourceModal.tsx index 8ebf5709e717..00b456303a76 100644 --- a/app/client/src/pages/Editor/gitSync/ReconnectDatasourceModal.tsx +++ b/app/client/src/pages/Editor/gitSync/ReconnectDatasourceModal.tsx @@ -63,7 +63,11 @@ import { Button, Text, } from "design-system"; -import { isEnvironmentConfigured } from "@appsmith/utils/Environments"; +import { + isEnvironmentConfigured, + getCurrentEnvironment, + getCurrentEnvName, +} from "@appsmith/utils/Environments"; import { keyBy } from "lodash"; import type { Plugin } from "api/PluginApi"; import { @@ -292,12 +296,12 @@ function ReconnectDatasourceModal() { const orgId = queryDS?.workspaceId; const checkIfDatasourceIsConfigured = (ds: Datasource | null) => { - if (!ds) return false; + if (!ds || pluginsArray.length === 0) return false; const plugin = plugins[ds.pluginId]; const output = isGoogleSheetPluginDS(plugin?.packageName) ? isDatasourceAuthorizedForQueryCreation(ds, plugin as Plugin) : ds.datasourceStorages - ? isEnvironmentConfigured(ds) + ? isEnvironmentConfigured(ds, getCurrentEnvironment()) : false; return output; }; @@ -316,6 +320,8 @@ function ReconnectDatasourceModal() { AnalyticsUtil.logEvent("DATASOURCE_AUTH_COMPLETE", { applicationId: queryAppId, datasourceId: queryDatasourceId, + environmentId: getCurrentEnvironment(), + environmentName: getCurrentEnvName(), pageId: queryPageId, oAuthPassOrFailVerdict: status, workspaceId: orgId, diff --git a/app/client/src/pages/Editor/gitSync/components/DatasourceListItem.tsx b/app/client/src/pages/Editor/gitSync/components/DatasourceListItem.tsx index 84bce0823151..cc758b716d61 100644 --- a/app/client/src/pages/Editor/gitSync/components/DatasourceListItem.tsx +++ b/app/client/src/pages/Editor/gitSync/components/DatasourceListItem.tsx @@ -5,7 +5,10 @@ import type { Datasource } from "entities/Datasource"; import styled from "styled-components"; import { getAssetUrl } from "@appsmith/utils/airgapHelpers"; import { PluginImage } from "pages/Editor/DataSourceEditor/DSFormHeader"; -import { isEnvironmentConfigured } from "@appsmith/utils/Environments"; +import { + getCurrentEnvironment, + isEnvironmentConfigured, +} from "@appsmith/utils/Environments"; import type { Plugin } from "api/PluginApi"; import { isDatasourceAuthorizedForQueryCreation, @@ -63,7 +66,7 @@ function ListItemWrapper(props: { const { ds, onClick, plugin, selected } = props; const isPluginAuthorized = isGoogleSheetPluginDS(plugin?.packageName) ? isDatasourceAuthorizedForQueryCreation(ds, plugin ?? {}) - : isEnvironmentConfigured(ds); + : isEnvironmentConfigured(ds, getCurrentEnvironment()); return ( <ListItem className={`t--ds-list ${selected ? "active" : ""}`} diff --git a/app/client/src/pages/common/datasourceAuth/index.tsx b/app/client/src/pages/common/datasourceAuth/index.tsx index 24e8e11dc4be..6d5d8e90ae7a 100644 --- a/app/client/src/pages/common/datasourceAuth/index.tsx +++ b/app/client/src/pages/common/datasourceAuth/index.tsx @@ -35,6 +35,8 @@ import { integrationEditorURL } from "RouteBuilder"; import { getQueryParams } from "utils/URLUtils"; import type { AppsmithLocationState } from "utils/history"; import type { PluginType } from "entities/Action"; +import { reset } from "redux-form"; +import { getCurrentEnvName } from "@appsmith/utils/Environments"; interface Props { datasource: Datasource; @@ -43,6 +45,7 @@ interface Props { currentEnvironment: string; isInvalid: boolean; pageId?: string; + formName: string; viewMode?: boolean; shouldRender?: boolean; isInsideReconnectModal?: boolean; @@ -50,7 +53,10 @@ interface Props { pluginType: PluginType; pluginName: string; pluginPackageName: string; - setDatasourceViewMode: (viewMode: boolean) => void; + setDatasourceViewMode: (payload: { + datasourceId: string; + viewMode: boolean; + }) => void; isSaving: boolean; isTesting: boolean; shouldDisplayAuthMessage?: boolean; @@ -128,6 +134,7 @@ function DatasourceAuth({ DatasourceButtonTypeEnum.SAVE, ], formData, + formName, getSanitizedFormData, isInvalid, pageId: pageIdProp, @@ -240,6 +247,8 @@ function DatasourceAuth({ pageId: pageId, appId: applicationId, datasourceId: datasourceId, + environmentId: currentEnvironment, + environmentName: getCurrentEnvName(), pluginName: pluginName, }); dispatch(testDatasource(getSanitizedFormData())); @@ -251,6 +260,8 @@ function DatasourceAuth({ AnalyticsUtil.logEvent("SAVE_DATA_SOURCE_CLICK", { pageId: pageId, appId: applicationId, + environmentId: currentEnvironment, + environmentName: getCurrentEnvName(), pluginName: pluginName || "", pluginPackageName: pluginPackageName || "", }); @@ -262,6 +273,7 @@ function DatasourceAuth({ dispatch( updateDatasource( getSanitizedFormData(), + currentEnvironment, undefined, undefined, isInsideReconnectModal, @@ -286,6 +298,7 @@ function DatasourceAuth({ dispatch( updateDatasource( getSanitizedFormData(), + currentEnvironment, pluginType ? redirectAuthorizationCode(pageId, datasourceId, pluginType) : undefined, @@ -301,7 +314,10 @@ function DatasourceAuth({ }; const createMode = datasourceId === TEMP_DATASOURCE_ID; - const datasourceButtonsComponentMap = (buttonType: string): JSX.Element => { + const datasourceButtonsComponentMap = ( + buttonType: string, + datasourceId: string, + ): JSX.Element => { return { [DatasourceButtonType.TEST]: ( <ActionButton @@ -330,7 +346,10 @@ function DatasourceAuth({ params: getQueryParams(), }); history.push(URL); - } else setDatasourceViewMode(true); + } else { + setDatasourceViewMode({ datasourceId, viewMode: true }); + dispatch(reset(formName)); + } }} size="md" > @@ -341,7 +360,9 @@ function DatasourceAuth({ <Button className="t--save-datasource" isDisabled={ - isInvalid || !isFormDirty || (!createMode && !canManageDatasource) + isInvalid || + (!createMode && !isFormDirty) || + (!createMode && !canManageDatasource) } isLoading={isSaving} key={buttonType} @@ -376,7 +397,7 @@ function DatasourceAuth({ {shouldRender && ( <SaveButtonContainer isInsideReconnectModal={isInsideReconnectModal}> {datasourceButtonConfiguration?.map((btnConfig) => - datasourceButtonsComponentMap(btnConfig), + datasourceButtonsComponentMap(btnConfig, datasource.id), )} </SaveButtonContainer> )} diff --git a/app/client/src/reducers/entityReducers/datasourceReducer.ts b/app/client/src/reducers/entityReducers/datasourceReducer.ts index 16aa383b7de1..c184282be2f3 100644 --- a/app/client/src/reducers/entityReducers/datasourceReducer.ts +++ b/app/client/src/reducers/entityReducers/datasourceReducer.ts @@ -10,6 +10,7 @@ import type { DatasourceStructure, MockDatasource, } from "entities/Datasource"; +import { ToastMessageType } from "entities/Datasource"; import { TEMP_DATASOURCE_ID } from "constants/Datasource"; import type { DropdownOption } from "design-system-old"; import produce from "immer"; @@ -232,6 +233,7 @@ const datasourceReducer = createReducer(initialState, { action: ReduxAction<{ show: boolean; id?: string; + environmentId: string; messages?: Array<string>; error?: any; }>, @@ -239,13 +241,33 @@ const datasourceReducer = createReducer(initialState, { if (action.payload.id) { const list = state.list.map((datasource) => { if (datasource.id === action.payload.id) { - return { ...datasource, messages: action.payload.messages }; + return { + ...datasource, + messages: action.payload.messages, + datasourceStorages: { + ...datasource.datasourceStorages, + [action.payload.environmentId]: { + ...datasource.datasourceStorages[action.payload.environmentId], + toastMessage: ToastMessageType.TEST_DATASOURCE_SUCCESS, + }, + }, + }; } return datasource; }); const unconfiguredList = state.unconfiguredList.map((datasource) => { if (datasource.id === action.payload.id) { - return { ...datasource, messages: action.payload.messages }; + return { + ...datasource, + messages: action.payload.messages, + datasourceStorages: { + ...datasource.datasourceStorages, + [action.payload.environmentId]: { + ...datasource.datasourceStorages[action.payload.environmentId], + toastMessage: ToastMessageType.TEST_DATASOURCE_SUCCESS, + }, + }, + }; } return datasource; }); @@ -447,6 +469,7 @@ const datasourceReducer = createReducer(initialState, { action: ReduxAction<{ show: boolean; id?: string; + environmentId: string; messages?: Array<string>; error?: any; }>, @@ -454,13 +477,33 @@ const datasourceReducer = createReducer(initialState, { if (action.payload.id) { const list = state.list.map((datasource) => { if (datasource.id === action.payload.id) { - return { ...datasource, messages: action.payload.messages }; + return { + ...datasource, + messages: action.payload.messages, + datasourceStorages: { + ...datasource.datasourceStorages, + [action.payload.environmentId]: { + ...datasource.datasourceStorages[action.payload.environmentId], + toastMessage: ToastMessageType.TEST_DATASOURCE_ERROR, + }, + }, + }; } return datasource; }); const unconfiguredList = state.unconfiguredList.map((datasource) => { if (datasource.id === action.payload.id) { - return { ...datasource, messages: action.payload.messages }; + return { + ...datasource, + messages: action.payload.messages, + datasourceStorages: { + ...datasource.datasourceStorages, + [action.payload.environmentId]: { + ...datasource.datasourceStorages[action.payload.environmentId], + toastMessage: ToastMessageType.TEST_DATASOURCE_ERROR, + }, + }, + }; } return datasource; }); @@ -653,6 +696,43 @@ const datasourceReducer = createReducer(initialState, { draftState.gsheetStructure.isFetchingColumns = false; }); }, + [ReduxActionTypes.RESET_DATASOURCE_BANNER_MESSAGE]: ( + state: DatasourceDataState, + action: ReduxAction<string>, + ) => { + if (action.payload) { + const list = state.list.map((datasource) => { + if (datasource.id === action.payload) { + Object.keys(datasource.datasourceStorages).map( + (datasourceStorage) => { + datasource.datasourceStorages[datasourceStorage].toastMessage = + ToastMessageType.EMPTY_TOAST_MESSAGE; + }, + ); + } + return datasource; + }); + const unconfiguredList = state.unconfiguredList.map((datasource) => { + if (datasource.id === action.payload) { + Object.keys(datasource.datasourceStorages).forEach( + (datasourceStorage) => { + datasource.datasourceStorages[datasourceStorage].toastMessage = + ToastMessageType.EMPTY_TOAST_MESSAGE; + }, + ); + } + return datasource; + }); + return { + ...state, + list: list, + unconfiguredList: unconfiguredList, + }; + } + return { + ...state, + }; + }, }); export default datasourceReducer; diff --git a/app/client/src/reducers/uiReducers/datasourcePaneReducer.ts b/app/client/src/reducers/uiReducers/datasourcePaneReducer.ts index 06a31ff04063..21a9e6bbc09a 100644 --- a/app/client/src/reducers/uiReducers/datasourcePaneReducer.ts +++ b/app/client/src/reducers/uiReducers/datasourcePaneReducer.ts @@ -101,7 +101,7 @@ const datasourcePaneReducer = createReducer(initialState, { expandDatasourceId: action.payload.id, }; }, - [ReduxActionTypes.SET_DATASOURCE_EDITOR_MODE]: ( + [ReduxActionTypes.SET_DATASOURCE_EDITOR_MODE_FLAG]: ( state: DatasourcePaneReduxState, action: ReduxAction<boolean>, ) => { diff --git a/app/client/src/sagas/ActionExecution/PluginActionSaga.ts b/app/client/src/sagas/ActionExecution/PluginActionSaga.ts index 04b9ab24bfd9..f2ccfd67ae7e 100644 --- a/app/client/src/sagas/ActionExecution/PluginActionSaga.ts +++ b/app/client/src/sagas/ActionExecution/PluginActionSaga.ts @@ -78,6 +78,7 @@ import { ERROR_PLUGIN_ACTION_EXECUTE, ACTION_EXECUTION_CANCELLED, ACTION_EXECUTION_FAILED, + SWITCH_ENVIRONMENT_SUCCESS, } from "@appsmith/constants/messages"; import type { LayoutOnLoadActionErrors, @@ -112,6 +113,7 @@ import { QUERIES_EDITOR_BASE_PATH, QUERIES_EDITOR_ID_PATH, CURL_IMPORT_PAGE_PATH, + matchQueryBuilderPath, } from "constants/routes"; import { SAAS_EDITOR_API_ID_PATH } from "pages/Editor/SaaSEditor/constants"; import { APP_MODE } from "entities/App"; @@ -150,6 +152,12 @@ import type { ActionData } from "reducers/entityReducers/actionsReducer"; import { handleStoreOperations } from "./StoreActionSaga"; import { fetchPage } from "actions/pageActions"; import type { Datasource } from "entities/Datasource"; +import { softRefreshDatasourceStructure } from "actions/datasourceActions"; +import { + getCurrentEnvName, + getCurrentEnvironment, +} from "@appsmith/utils/Environments"; +import { changeQuery } from "actions/queryPaneActions"; enum ActionResponseDataTypes { BINARY = "BINARY", @@ -519,6 +527,8 @@ export default function* executePluginActionTriggerSaga( appId: currentApp.id, appMode: appMode, appName: currentApp.name, + environmentId: getCurrentEnvironment(), + environmentName: getCurrentEnvName(), isExampleApp: currentApp.appIsExample, pluginName: plugin?.name, datasourceId: datasourceId, @@ -556,6 +566,7 @@ export default function* executePluginActionTriggerSaga( iconId: action.pluginId, logType: LOG_TYPE.ACTION_EXECUTION_ERROR, text: `Execution failed with status ${payload.statusCode}`, + environmentName: getCurrentEnvName() || "", source: { type: ENTITY_TYPE.ACTION, name: action.name, @@ -589,6 +600,8 @@ export default function* executePluginActionTriggerSaga( appId: currentApp.id, appMode: appMode, appName: currentApp.name, + environmentId: getCurrentEnvironment(), + environmentName: getCurrentEnvName(), isExampleApp: currentApp.appIsExample, pluginName: plugin?.name, datasourceId: datasourceId, @@ -615,6 +628,8 @@ export default function* executePluginActionTriggerSaga( appId: currentApp.id, appMode: appMode, appName: currentApp.name, + environmentId: getCurrentEnvironment(), + environmentName: getCurrentEnvName(), isExampleApp: currentApp.appIsExample, pluginName: plugin?.name, datasourceId: datasourceId, @@ -879,6 +894,7 @@ function* runActionSaga( id: actionId, iconId: actionObject.pluginId, logType: LOG_TYPE.ACTION_EXECUTION_ERROR, + environmentName: getCurrentEnvName() || "", text: `Execution failed${ payload.statusCode ? ` with status ${payload.statusCode}` : "" }`, @@ -914,6 +930,8 @@ function* runActionSaga( AnalyticsUtil.logEvent(failureEventName, { actionId, actionName: actionObject.name, + environmentId: getCurrentEnvironment(), + environmentName: getCurrentEnvName(), pageName: pageName, apiType: "INTERNAL", datasourceId: datasource?.id, @@ -935,6 +953,8 @@ function* runActionSaga( AnalyticsUtil.logEvent(eventName, { actionId, actionName: actionObject.name, + environmentId: getCurrentEnvironment(), + environmentName: getCurrentEnvName(), pageName: pageName, responseTime: payload.duration, apiType: "INTERNAL", @@ -1062,6 +1082,8 @@ function* executePageLoadAction(pageAction: PageAction) { appId: currentApp.id, onPageLoad: true, appName: currentApp.name, + environmentId: getCurrentEnvironment(), + environmentName: getCurrentEnvName(), isExampleApp: currentApp.appIsExample, pluginName: plugin?.name, datasourceId: datasourceId, @@ -1103,6 +1125,7 @@ function* executePageLoadAction(pageAction: PageAction) { id: pageAction.id, iconId: action.pluginId, logType: LOG_TYPE.ACTION_EXECUTION_ERROR, + environmentName: getCurrentEnvName() || "", text: `Execution failed with status ${payload.statusCode}`, source: { type: ENTITY_TYPE.ACTION, @@ -1147,6 +1170,8 @@ function* executePageLoadAction(pageAction: PageAction) { appId: currentApp.id, onPageLoad: true, appName: currentApp.name, + environmentId: getCurrentEnvironment(), + environmentName: getCurrentEnvName(), isExampleApp: currentApp.appIsExample, pluginName: plugin?.name, datasourceId: datasourceId, @@ -1163,6 +1188,8 @@ function* executePageLoadAction(pageAction: PageAction) { appId: currentApp.id, onPageLoad: true, appName: currentApp.name, + environmentId: getCurrentEnvironment(), + environmentName: getCurrentEnvName(), isExampleApp: currentApp.appIsExample, pluginName: plugin?.name, datasourceId: datasourceId, @@ -1483,6 +1510,19 @@ function* softRefreshActionsSaga() { yield call(clearTriggerActionResponse); //Rerun all the page load actions on the page yield call(executePageLoadActionsSaga); + try { + // we fork to prevent the call from blocking + yield put(softRefreshDatasourceStructure()); + } catch (error) {} + //This will refresh the query editor with the latest datasource structure. + const isQueryPane = matchQueryBuilderPath(window.location.pathname); + //This is reuired only when the query editor is open. + if (isQueryPane) { + yield put(changeQuery(isQueryPane.params.queryId)); + } + toast.show(createMessage(SWITCH_ENVIRONMENT_SUCCESS, getCurrentEnvName()), { + kind: "success", + }); } export function* watchPluginActionExecutionSagas() { diff --git a/app/client/src/sagas/DatasourcesSagas.ts b/app/client/src/sagas/DatasourcesSagas.ts index f99460a63ff2..839dae863381 100644 --- a/app/client/src/sagas/DatasourcesSagas.ts +++ b/app/client/src/sagas/DatasourcesSagas.ts @@ -44,9 +44,12 @@ import { getEditorConfig, getPluginByPackageName, getDatasourcesUsedInApplicationByActions, - getDatasourceStructureById, + getEntityExplorerDatasources, } from "selectors/entitiesSelector"; -import { addMockDatasourceToWorkspace } from "actions/datasourceActions"; +import { + addMockDatasourceToWorkspace, + setDatasourceViewModeFlag, +} from "actions/datasourceActions"; import type { UpdateDatasourceSuccessAction, executeDatasourceQueryReduxAction, @@ -67,11 +70,11 @@ import type { CreateDatasourceConfig } from "api/DatasourcesApi"; import DatasourcesApi from "api/DatasourcesApi"; import type { Datasource, - DatasourceStructure, + DatasourceStorage, MockDatasource, TokenResponse, } from "entities/Datasource"; -import { AuthenticationStatus } from "entities/Datasource"; +import { AuthenticationStatus, ToastMessageType } from "entities/Datasource"; import { FilePickerActionStatus } from "entities/Datasource"; import { INTEGRATION_EDITOR_MODES, @@ -113,7 +116,7 @@ import localStorage from "utils/localStorage"; import log from "loglevel"; import { APPSMITH_TOKEN_STORAGE_KEY } from "pages/Editor/SaaSEditor/constants"; import { checkAndGetPluginFormConfigsSaga } from "sagas/PluginSagas"; -import { PluginPackageName, PluginType } from "entities/Action"; +import { PluginType, PluginPackageName } from "entities/Action"; import LOG_TYPE from "entities/AppsmithConsole/logtype"; import { isDynamicValue } from "utils/DynamicBindingUtils"; import { getQueryParams } from "utils/URLUtils"; @@ -143,7 +146,11 @@ import { toast } from "design-system"; import { fetchPluginFormConfig } from "actions/pluginActions"; import { addClassToDocumentRoot } from "pages/utils"; import { AuthorizationStatus } from "pages/common/datasourceAuth"; -import { getCurrentEnvironment } from "@appsmith/utils/Environments"; +import { + getCurrentEditingEnvID, + getCurrentEnvName, + getCurrentEnvironment, +} from "@appsmith/utils/Environments"; import { getFormDiffPaths, getFormName, @@ -151,6 +158,7 @@ import { } from "utils/editorContextUtils"; import { getDefaultEnvId } from "@appsmith/api/ApiUtils"; import type { DatasourceStructureContext } from "pages/Editor/Explorer/Datasources/DatasourceStructureContainer"; +import { MAX_DATASOURCE_SUGGESTIONS } from "pages/Editor/Explorer/hooks"; function* fetchDatasourcesSaga( action: ReduxAction<{ workspaceId?: string } | undefined>, @@ -186,17 +194,23 @@ function* handleFetchDatasourceStructureOnLoad() { function* fetchDatasourceStructureOnLoad() { try { // get datasources of all actions used in the the application - const datasourcesUsedInApplication: Datasource[] = yield select( + let datasourcesUsedInApplication: Datasource[] = yield select( getDatasourcesUsedInApplicationByActions, ); + // get datasources present in entity explorer and not part of any action. + if (datasourcesUsedInApplication.length < MAX_DATASOURCE_SUGGESTIONS) { + const datasourceInEntityExplorer: Datasource[] = yield select( + getEntityExplorerDatasources, + ); + datasourcesUsedInApplication = [ + ...datasourcesUsedInApplication, + ...datasourceInEntityExplorer, + ]; + } + + //fetch datasource structure for each datasource for (const datasource of datasourcesUsedInApplication) { - // it is very unlikely for this to happen, but it does not hurt to check. - const doesDatasourceStructureAlreadyExist: DatasourceStructure = - yield select(getDatasourceStructureById, datasource.id); - if (doesDatasourceStructureAlreadyExist) { - continue; - } yield put(fetchDatasourceStructure(datasource.id, true)); } } catch (error) {} @@ -413,48 +427,76 @@ export function* deleteDatasourceSaga( function* updateDatasourceSaga( actionPayload: ReduxActionWithCallbacks< - Datasource & { isInsideReconnectModal: boolean }, + Datasource & { isInsideReconnectModal: boolean; currEditingEnvId?: string }, unknown, unknown >, ) { try { const queryParams = getQueryParams(); - const currentEnvironment = getCurrentEnvironment(); + const currentEnvironment = + actionPayload.payload?.currEditingEnvId || getCurrentEnvironment(); const datasourcePayload = omit(actionPayload.payload, "name"); + const datasourceStoragePayload = + datasourcePayload.datasourceStorages[currentEnvironment]; const pluginPackageName: PluginPackageName = yield select( getPluginPackageFromDatasourceId, datasourcePayload?.id, ); // when clicking save button, it should be changed as configured - set( - datasourcePayload, - `datasourceStorages.${currentEnvironment}.isConfigured`, - true, - ); + set(datasourceStoragePayload, `isConfigured`, true); + if (!datasourceStoragePayload.hasOwnProperty("datasourceId")) { + if (datasourcePayload.id !== TEMP_DATASOURCE_ID) + set(datasourceStoragePayload, `datasourceId`, datasourcePayload.id); + } else if (datasourceStoragePayload.datasourceId === TEMP_DATASOURCE_ID) { + datasourceStoragePayload.datasourceId = ""; + } + + if (!datasourceStoragePayload.hasOwnProperty("environmentId")) { + set(datasourceStoragePayload, `environmentId`, currentEnvironment); + } // When importing app with google sheets with specific sheets scope // We do not want to set isConfigured to true immediately on save // instead we want to wait for authorisation as well as file selection to be complete if (isGoogleSheetPluginDS(pluginPackageName)) { - const value = get( - datasourcePayload, - `datasourceStorages.${currentEnvironment}.datasourceConfiguration.authentication.scopeString`, - ); + const value = get(datasourceStoragePayload, `authentication.scopeString`); const scopeString: string = value ? value : ""; if (scopeString.includes(GOOGLE_SHEET_SPECIFIC_SHEETS_SCOPE)) { - datasourcePayload.datasourceStorages[currentEnvironment].isConfigured = - false; + datasourceStoragePayload.isConfigured = false; } } - const response: ApiResponse<Datasource> = - yield DatasourcesApi.updateDatasourceStorage( - datasourcePayload.datasourceStorages[currentEnvironment], + const isNewStorage = !datasourceStoragePayload.hasOwnProperty("id"); + let response: ApiResponse<Datasource>; + + // if storage is new, we have to use create datasource call + if (isNewStorage) { + response = yield DatasourcesApi.createDatasource(datasourcePayload); + } else { + // if storage is already created, we can use update datasource call + response = yield DatasourcesApi.updateDatasourceStorage( + datasourceStoragePayload, ); + } + const isValidResponse: boolean = yield validateResponse(response); if (isValidResponse) { - const plugin: Plugin = yield select(getPlugin, response?.data?.pluginId); + //Update call only returns the updated storage of current environment. + //So we need to update the other storages with the old values. + // TODO server should send ony the updated storage or whole datasource. + if (!isNewStorage) { + Object.keys(datasourcePayload.datasourceStorages).forEach( + (storageId: string) => { + if (storageId !== currentEnvironment) { + response.data.datasourceStorages[storageId] = + datasourcePayload.datasourceStorages[storageId]; + } + }, + ); + } + const responseData: Datasource = response.data; + const plugin: Plugin = yield select(getPlugin, responseData?.pluginId); const formName: string = getFormName(plugin); const state: AppState = yield select(); const isFormValid = isValid(formName)(state); @@ -464,14 +506,16 @@ function* updateDatasourceSaga( formData.values, ); AnalyticsUtil.logEvent("SAVE_DATA_SOURCE", { - datasourceId: response?.data?.id, - datasourceName: response.data.name, + datasourceId: responseData?.id, + datasourceName: responseData.name, + environmentId: currentEnvironment, + environmentName: getCurrentEnvName(), pluginName: plugin?.name || "", pluginPackageName: plugin?.packageName || "", isFormValid: isFormValid, editedFields: formDiffPaths, }); - toast.show(createMessage(DATASOURCE_UPDATE, response.data.name), { + toast.show(createMessage(DATASOURCE_UPDATE, responseData.name), { kind: "success", }); @@ -480,7 +524,7 @@ function* updateDatasourceSaga( // Dont redirect if action payload has an onSuccess yield put( updateDatasourceSuccess( - response.data, + responseData, !actionPayload.onSuccess, queryParams, ), @@ -488,26 +532,26 @@ function* updateDatasourceSaga( yield put({ type: ReduxActionTypes.DELETE_DATASOURCE_DRAFT, payload: { - id: response.data.id, + id: responseData.id, }, }); if (actionPayload.onSuccess) { yield put(actionPayload.onSuccess); } - if (expandDatasourceId === response.data.id) { - yield put(fetchDatasourceStructure(response.data.id, true)); + if (expandDatasourceId === responseData.id) { + yield put(fetchDatasourceStructure(responseData.id, true)); } AppsmithConsole.info({ text: "Datasource configuration saved", source: { - id: response.data.id, - name: response.data.name, + id: responseData.id, + name: responseData.name, type: ENTITY_TYPE.DATASOURCE, }, state: { datasourceConfiguration: - response.data.datasourceStorages[currentEnvironment] + responseData.datasourceStorages[currentEnvironment] .datasourceConfiguration, }, }); @@ -517,11 +561,16 @@ function* updateDatasourceSaga( if (!datasourcePayload.isInsideReconnectModal) { // Don't redirect to view mode if the plugin is google sheets if (pluginPackageName !== PluginPackageName.GOOGLE_SHEETS) { - yield put(setDatasourceViewMode(true)); + yield put( + setDatasourceViewMode({ + datasourceId: response.data.id, + viewMode: true, + }), + ); } // updating form initial values to latest data, so that next time when form is opened // isDirty will use updated initial values data to compare actual values with - yield put(initialize(DATASOURCE_DB_FORM, response.data)); + yield put(initialize(DATASOURCE_DB_FORM, responseData)); } } } catch (error) { @@ -619,6 +668,8 @@ function* getOAuthAccessTokenSaga( AnalyticsUtil.logEvent("DATASOURCE_AUTH_COMPLETE", { applicationId: applicationId, datasourceId: datasourceId, + environmentId: getCurrentEnvironment(), + environmentName: getCurrentEnvName(), pageId: pageId, oAuthPassOrFailVerdict: "success", workspaceId: response.data.datasource?.workspaceId, @@ -686,31 +737,39 @@ function* testDatasourceSaga(actionPayload: ReduxAction<Datasource>) { if (!workspaceId) { workspaceId = yield select(getWorkspaceIdForImport); } - const { initialValues, values } = yield select( - getFormData, - DATASOURCE_DB_FORM, - ); + const { initialValues } = yield select(getFormData, DATASOURCE_DB_FORM); const datasource = shouldBeDefined<Datasource>( yield select(getDatasource, actionPayload.payload.id), `Datasource not found for id - ${actionPayload.payload.id}`, ); - const currentEnvironment = getCurrentEnvironment(); + const currentEnvironment = getCurrentEditingEnvID(); const payload = { ...actionPayload.payload, id: actionPayload.payload.id as any, }; const plugin: Plugin = yield select(getPlugin, datasource?.pluginId); + let payloadWithoutDatasourceId: DatasourceStorage = + payload.datasourceStorages[currentEnvironment]; + + const initialDSStorage = initialValues.datasourceStorages[currentEnvironment]; // when datasource is not yet saved by user, datasource id is temporary // for temporary datasource, we do not need to pass datasource id in test api call - if (!equal(initialValues, values) || datasource?.id === TEMP_DATASOURCE_ID) { - delete payload.id; + if ( + !equal(initialDSStorage, payloadWithoutDatasourceId) || + payloadWithoutDatasourceId?.datasourceId === TEMP_DATASOURCE_ID + ) { + // we have to do this so that the original object is not mutated + payloadWithoutDatasourceId = { + ...payloadWithoutDatasourceId, + datasourceId: "", + }; } try { const response: ApiResponse<Datasource> = yield DatasourcesApi.testDatasource( - payload.datasourceStorages[currentEnvironment], + payloadWithoutDatasourceId, plugin.id, workspaceId, ); @@ -724,6 +783,8 @@ function* testDatasourceSaga(actionPayload: ReduxAction<Datasource>) { ) { AnalyticsUtil.logEvent("TEST_DATA_SOURCE_FAILED", { datasoureId: datasource?.id, + environmentId: currentEnvironment, + environmentName: getCurrentEnvName(), pluginName: plugin?.name, errorMessages: responseData.invalids, messages: responseData.messages, @@ -745,7 +806,12 @@ function* testDatasourceSaga(actionPayload: ReduxAction<Datasource>) { } yield put({ type: ReduxActionErrorTypes.TEST_DATASOURCE_ERROR, - payload: { show: false, id: datasource.id, messages: messages }, + payload: { + show: false, + id: datasource.id, + environmentId: currentEnvironment, + messages: messages, + }, }); AppsmithConsole.error({ text: "Test Connection failed", @@ -765,6 +831,8 @@ function* testDatasourceSaga(actionPayload: ReduxAction<Datasource>) { AnalyticsUtil.logEvent("TEST_DATA_SOURCE_SUCCESS", { datasourceName: payload.name, datasoureId: datasource?.id, + environmentId: currentEnvironment, + environmentName: getCurrentEnvName(), pluginName: plugin?.name, }); toast.show(createMessage(DATASOURCE_VALID, payload.name), { @@ -772,7 +840,12 @@ function* testDatasourceSaga(actionPayload: ReduxAction<Datasource>) { }); yield put({ type: ReduxActionTypes.TEST_DATASOURCE_SUCCESS, - payload: { show: false, id: datasource.id, messages: [] }, + payload: { + show: false, + id: datasource.id, + environmentId: currentEnvironment, + messages: [], + }, }); AppsmithConsole.info({ text: "Test Connection successful", @@ -787,10 +860,12 @@ function* testDatasourceSaga(actionPayload: ReduxAction<Datasource>) { } catch (error) { yield put({ type: ReduxActionErrorTypes.TEST_DATASOURCE_ERROR, - payload: { error, show: false }, + payload: { error, show: false, environmentId: currentEnvironment }, }); AnalyticsUtil.logEvent("TEST_DATA_SOURCE_FAILED", { datasoureId: datasource?.id, + environmentId: currentEnvironment, + environmentName: getCurrentEnvName(), pluginName: plugin?.name, errorMessages: (error as any)?.message, }); @@ -841,11 +916,13 @@ function* createTempDatasourceFromFormSaga( new: false, datasourceStorages: { [defaultEnvId]: { - datasourceId: "", + datasourceId: TEMP_DATASOURCE_ID, environmentId: defaultEnvId, + isValid: false, datasourceConfiguration: { properties: [], }, + toastMessage: ToastMessageType.EMPTY_TOAST_MESSAGE, }, }, }; @@ -862,7 +939,12 @@ function* createTempDatasourceFromFormSaga( payload, }); - yield put(setDatasourceViewMode(false)); + yield put( + setDatasourceViewMode({ + datasourceId: payload.id, + viewMode: false, + }), + ); } function* createDatasourceFromFormSaga( @@ -884,21 +966,37 @@ function* createDatasourceFromFormSaga( getPluginForm, actionPayload.payload.pluginId, ); - const currentEnvironment = getCurrentEnvironment(); + const currentEnvironment = getCurrentEditingEnvID(); const initialValues: unknown = yield call( getConfigInitialValues, formConfig, ); - actionPayload.payload.datasourceStorages[currentEnvironment] = merge( - initialValues, - actionPayload.payload.datasourceStorages[currentEnvironment], - ); + let datasourceStoragePayload = + actionPayload.payload.datasourceStorages[currentEnvironment]; + + datasourceStoragePayload = merge(initialValues, datasourceStoragePayload); + + // in the datasourcestorages, we only need one key, the currentEnvironment + // we need to remove any other keys present + const datasourceStorages = { + [currentEnvironment]: datasourceStoragePayload, + }; - const payload = omit(actionPayload.payload, ["id", "new", "type"]); + const payload = omit( + { + ...actionPayload.payload, + datasourceStorages, + }, + ["id", "new", "type", "datasourceConfiguration"], + ); if (payload.datasourceStorages) - payload.datasourceStorages[currentEnvironment].isConfigured = true; + datasourceStoragePayload.isConfigured = true; + + // remove datasourceId from payload if it is equal to TEMP_DATASOURCE_ID + if (datasourceStoragePayload.datasourceId === TEMP_DATASOURCE_ID) + datasourceStoragePayload.datasourceId = ""; const response: ApiResponse<Datasource> = yield DatasourcesApi.createDatasource({ @@ -919,6 +1017,8 @@ function* createDatasourceFromFormSaga( AnalyticsUtil.logEvent("SAVE_DATA_SOURCE", { datasourceId: response?.data?.id, datasourceName: response?.data?.name, + environmentId: currentEnvironment, + environmentName: getCurrentEnvName(), pluginName: plugin?.name || "", pluginPackageName: plugin?.packageName || "", isFormValid: isFormValid, @@ -1113,7 +1213,12 @@ function* storeAsDatasourceSaga() { ); createdDatasource = omit(createdDatasource, ["datasourceConfiguration"]); // Set datasource page to edit mode - yield put(setDatasourceViewMode(false)); + yield put( + setDatasourceViewMode({ + datasourceId: datasource.id, + viewMode: false, + }), + ); yield put({ type: ReduxActionTypes.STORE_AS_DATASOURCE_UPDATE, @@ -1250,6 +1355,8 @@ function* fetchDatasourceStructureSaga( AnalyticsUtil.logEvent("DATASOURCE_SCHEMA_FETCH", { datasourceId: datasource?.id, pluginName: plugin?.name, + environmentId: getCurrentEnvironment(), + environmentName: getCurrentEnvName(), errorMessage: errorMessage, isSuccess: isSuccess, source: action.payload.schemaFetchContext, @@ -1363,6 +1470,8 @@ function* refreshDatasourceStructure( AnalyticsUtil.logEvent("DATASOURCE_SCHEMA_FETCH", { datasourceId: datasource?.id, pluginName: plugin?.name, + environmentId: getCurrentEnvironment(), + environmentName: getCurrentEnvName(), errorMessage: errorMessage, isSuccess: isSuccess, source: action.payload.schemaRefreshContext, @@ -1484,6 +1593,8 @@ function* filePickerActionCallbackSaga( applicationId: applicationId, pageId: pageId, datasourceId: datasource?.id, + environmentId: currentEnvironment, + environmentName: getCurrentEnvName(), oAuthPassOrFailVerdict: authStatus === AuthenticationStatus.FAILURE_FILE_NOT_SELECTED ? createMessage(FILES_NOT_SELECTED_EVENT) @@ -1736,7 +1847,7 @@ function* updateDatasourceAuthStateSaga( ) { try { const { authStatus, datasource } = actionPayload.payload; - const currentEnvironment = getCurrentEnvironment(); + const currentEnvironment = getCurrentEditingEnvID(); set( datasource, `datasourceStorages.${currentEnvironment}.datasourceConfiguration.authentication.authenticationStatus`, @@ -1792,6 +1903,18 @@ function* datasourceDiscardActionSaga( }); } +function* setDatasourceViewModeSaga( + action: ReduxAction<{ datasourceId: string; viewMode: boolean }>, +) { + //Set the view mode flag in store + yield put(setDatasourceViewModeFlag(action.payload.viewMode)); + //Reset the banner message for the datasource + yield put({ + type: ReduxActionTypes.RESET_DATASOURCE_BANNER_MESSAGE, + payload: action.payload.datasourceId, + }); +} + export function* watchDatasourcesSagas() { yield all([ takeEvery(ReduxActionTypes.FETCH_DATASOURCES_INIT, fetchDatasourcesSaga), @@ -1881,5 +2004,13 @@ export function* watchDatasourcesSagas() { ReduxActionTypes.FETCH_DATASOURCES_SUCCESS, handleFetchDatasourceStructureOnLoad, ), + takeEvery( + ReduxActionTypes.SOFT_REFRESH_DATASOURCE_STRUCTURE, + handleFetchDatasourceStructureOnLoad, + ), + takeEvery( + ReduxActionTypes.SET_DATASOURCE_EDITOR_MODE, + setDatasourceViewModeSaga, + ), ]); } diff --git a/app/client/src/sagas/DebuggerSagas.ts b/app/client/src/sagas/DebuggerSagas.ts index 81c7bf96d460..7189100d608c 100644 --- a/app/client/src/sagas/DebuggerSagas.ts +++ b/app/client/src/sagas/DebuggerSagas.ts @@ -62,6 +62,10 @@ import { isAction, isWidget, } from "@appsmith/workers/Evaluation/evaluationUtils"; +import { + getCurrentEnvName, + getCurrentEnvironment, +} from "@appsmith/utils/Environments"; // Saga to format action request values to be shown in the debugger function* formatActionRequestSaga( @@ -487,6 +491,8 @@ function* addDebuggerErrorLogsSaga(action: ReduxAction<Log[]>) { type: ReduxActionTypes.DEBUGGER_ERROR_ANALYTICS, payload: { ...analyticsPayload, + environmentId: getCurrentEnvironment(), + environmentName: getCurrentEnvName(), eventName: "DEBUGGER_NEW_ERROR_MESSAGE", errorId: errorLog.id + "_" + errorLog.timestamp, errorMessage: errorMessage.message, @@ -516,6 +522,8 @@ function* addDebuggerErrorLogsSaga(action: ReduxAction<Log[]>) { type: ReduxActionTypes.DEBUGGER_ERROR_ANALYTICS, payload: { ...analyticsPayload, + environmentId: getCurrentEnvironment(), + environmentName: getCurrentEnvName(), eventName: "DEBUGGER_NEW_ERROR_MESSAGE", errorId: errorLog.id + "_" + errorLog.timestamp, errorMessage: updatedErrorMessage.message, @@ -542,6 +550,8 @@ function* addDebuggerErrorLogsSaga(action: ReduxAction<Log[]>) { type: ReduxActionTypes.DEBUGGER_ERROR_ANALYTICS, payload: { ...analyticsPayload, + environmentId: getCurrentEnvironment(), + environmentName: getCurrentEnvName(), eventName: "DEBUGGER_RESOLVED_ERROR_MESSAGE", errorId: currentDebuggerErrors[id].id + @@ -607,6 +617,8 @@ function* deleteDebuggerErrorLogsSaga( type: ReduxActionTypes.DEBUGGER_ERROR_ANALYTICS, payload: { ...analyticsPayload, + environmentId: getCurrentEnvironment(), + environmentName: getCurrentEnvName(), eventName: "DEBUGGER_RESOLVED_ERROR_MESSAGE", errorId: error.id + "_" + error.timestamp, errorMessage: errorMessage.message, diff --git a/app/client/src/sagas/QueryPaneSagas.ts b/app/client/src/sagas/QueryPaneSagas.ts index 5e4cc790e000..45c469d546fd 100644 --- a/app/client/src/sagas/QueryPaneSagas.ts +++ b/app/client/src/sagas/QueryPaneSagas.ts @@ -81,7 +81,10 @@ import { getIsGeneratePageInitiator } from "utils/GenerateCrudUtil"; import { toast } from "design-system"; import type { CreateDatasourceSuccessAction } from "actions/datasourceActions"; import { createDefaultActionPayload } from "./ActionSagas"; -import { getCurrentEnvironment } from "@appsmith/utils/Environments"; +import { + DB_NOT_SUPPORTED, + getCurrentEnvironment, +} from "@appsmith/utils/Environments"; // Called whenever the query being edited is changed via the URL or query pane function* changeQuerySaga(actionPayload: ReduxAction<{ id: string }>) { @@ -190,6 +193,7 @@ function* formValueChangeSaga( const plugins: Plugin[] = yield select(getPlugins); const uiComponent = getUIComponent(values.pluginId, plugins); + const plugin = plugins.find((p) => p.id === values.pluginId); if (field === "datasource.id") { const datasource: Datasource | undefined = yield select( @@ -258,10 +262,21 @@ function* formValueChangeSaga( getDatasource, values.datasource.id, ); + const datasourceStorages = datasource?.datasourceStorages || {}; // Editing form fields triggers evaluations. // We pass the action to run form evaluations when the dataTree evaluation is complete - const currentEnvironment = getCurrentEnvironment(); + let currentEnvironment = getCurrentEnvironment(); + const pluginType = plugin?.type; + if ( + (!!pluginType && DB_NOT_SUPPORTED.includes(pluginType)) || + !datasourceStorages.hasOwnProperty(currentEnvironment) || + !datasourceStorages[currentEnvironment].hasOwnProperty( + "datasourceConfiguration", + ) + ) { + currentEnvironment = Object.keys(datasourceStorages)[0]; + } const postEvalActions = uiComponent === UIComponentTypes.UQIDbEditorForm ? [ @@ -272,8 +287,7 @@ function* formValueChangeSaga( values.pluginId, field, hasRouteChanged, - datasource?.datasourceStorages[currentEnvironment] - .datasourceConfiguration, + datasourceStorages[currentEnvironment].datasourceConfiguration, ), ] : []; diff --git a/app/client/src/selectors/debuggerSelectors.tsx b/app/client/src/selectors/debuggerSelectors.tsx index b6fbef2281fb..5d62de17e1fb 100644 --- a/app/client/src/selectors/debuggerSelectors.tsx +++ b/app/client/src/selectors/debuggerSelectors.tsx @@ -1,4 +1,3 @@ -import { matchDatasourcePath } from "constants/routes"; import type { Log } from "entities/AppsmithConsole"; import type { DataTree, WidgetEntity } from "entities/DataTree/dataTreeFactory"; import { isEmpty } from "lodash"; @@ -126,9 +125,6 @@ export const getMessageCount = createSelector(getFilteredErrors, (errors) => { return { errors: errorsCount, warnings: warningsCount }; }); -export const hideDebuggerIconSelector = () => - matchDatasourcePath(window.location.pathname); - // get selected tab in debugger. export const getDebuggerSelectedTab = (state: AppState) => state.ui.debugger.context.selectedDebuggerTab; diff --git a/app/client/src/selectors/entitiesSelector.ts b/app/client/src/selectors/entitiesSelector.ts index c05dfe54e0d8..16af507bb72f 100644 --- a/app/client/src/selectors/entitiesSelector.ts +++ b/app/client/src/selectors/entitiesSelector.ts @@ -43,6 +43,7 @@ import type { TJSLibrary } from "workers/common/JSLibrary"; import { getEntityNameAndPropertyPath } from "@appsmith/workers/Evaluation/evaluationUtils"; import { getFormValues } from "redux-form"; import { TEMP_DATASOURCE_ID } from "constants/Datasource"; +import { MAX_DATASOURCE_SUGGESTIONS } from "pages/Editor/Explorer/hooks"; export const getEntities = (state: AppState): AppState["entities"] => state.entities; @@ -1164,3 +1165,37 @@ export const getDatasourcesUsedInApplicationByActions = ( ds.id !== TEMP_DATASOURCE_ID, ); }; + +const getOtherDatasourcesInWorkspace = (state: AppState): Datasource[] => { + const actions = getActions(state); + const allDatasources = getDatasources(state); + const datasourceIdsUsedInCurrentApplication = actions.reduce( + (acc, action: ActionData) => { + if ( + isStoredDatasource(action.config.datasource) && + action.config.datasource.id + ) { + acc.add(action.config.datasource.id); + } + return acc; + }, + new Set(), + ); + return allDatasources.filter( + (ds) => + !datasourceIdsUsedInCurrentApplication.has(ds.id) && + ds.id !== TEMP_DATASOURCE_ID, + ); +}; + +//This function returns the datasources which are not used by actions but visible in the workspace +export const getEntityExplorerDatasources = (state: AppState): Datasource[] => { + const datasourcesUsedInApplication = + getDatasourcesUsedInApplicationByActions(state); + const otherDatasourceInWorkspace = getOtherDatasourcesInWorkspace(state); + otherDatasourceInWorkspace.reverse(); + return otherDatasourceInWorkspace.slice( + 0, + MAX_DATASOURCE_SUGGESTIONS - datasourcesUsedInApplication.length, + ); +}; diff --git a/app/client/src/selectors/ui.tsx b/app/client/src/selectors/ui.tsx index d8120387cd7b..f806158ae4e3 100644 --- a/app/client/src/selectors/ui.tsx +++ b/app/client/src/selectors/ui.tsx @@ -37,6 +37,11 @@ export const getFocusedWidget = (state: AppState) => export const isDatasourceInViewMode = (state: AppState) => state.ui.datasourcePane.viewMode; +export const getDsViewModeValues = (state: AppState) => ({ + datasourceId: state.ui.datasourcePane.expandDatasourceId, + viewMode: state.ui.datasourcePane.viewMode, +}); + export const getAllDatasourceCollapsibleState = (state: AppState) => state.ui.datasourcePane.collapsibleState; diff --git a/app/client/src/transformers/RestAPIDatasourceFormTransformer.ts b/app/client/src/transformers/RestAPIDatasourceFormTransformer.ts index 018c6d015c7a..08a5853bc4cf 100644 --- a/app/client/src/transformers/RestAPIDatasourceFormTransformer.ts +++ b/app/client/src/transformers/RestAPIDatasourceFormTransformer.ts @@ -1,9 +1,9 @@ import { - getCurrentEnvironment, + getCurrentEditingEnvID, isEnvironmentValid, } from "@appsmith/utils/Environments"; import type { Property } from "entities/Action"; -import type { Datasource } from "entities/Datasource"; +import type { Datasource, DatasourceStorage } from "entities/Datasource"; import type { ApiDatasourceForm, Authentication, @@ -21,7 +21,7 @@ import { get, set } from "lodash"; export const datasourceToFormValues = ( datasource: Datasource, ): ApiDatasourceForm => { - const currentEnvironment = getCurrentEnvironment(); + const currentEnvironment = getCurrentEditingEnvID(); const authType = get( datasource, `datasourceStorages.${currentEnvironment}.datasourceConfiguration.authentication.authenticationType`, @@ -87,11 +87,29 @@ export const formValuesToDatasource = ( datasource: Datasource, form: ApiDatasourceForm, ): Datasource => { - const currentEnvironment = getCurrentEnvironment(); + const currentEnvironment = getCurrentEditingEnvID(); const authentication = formToDatasourceAuthentication( form.authType, form.authentication, ); + const dsStorages = datasource.datasourceStorages; + let dsStorage: DatasourceStorage; + if (dsStorages.hasOwnProperty(currentEnvironment)) { + dsStorage = dsStorages[currentEnvironment]; + } else { + dsStorage = { + environmentId: currentEnvironment, + datasourceConfiguration: { + url: "", + }, + isValid: false, + datasourceId: datasource.id, + }; + } + + if (!dsStorage.hasOwnProperty("environmentId")) { + dsStorage.environmentId = currentEnvironment; + } const connection = form.connection; if (connection) { @@ -116,11 +134,8 @@ export const formValuesToDatasource = ( authentication: authentication, connection: form.connection, }; - set( - datasource, - `datasourceStorages.${currentEnvironment}.datasourceConfiguration`, - conf, - ); + set(dsStorage, "datasourceConfiguration", conf); + set(dsStorages, currentEnvironment, dsStorage); return datasource; }; @@ -209,7 +224,7 @@ const datasourceToFormAuthentication = ( authType: AuthType, datasource: Datasource, ): Authentication | undefined => { - const currentEnvironment = getCurrentEnvironment(); + const currentEnvironment = getCurrentEditingEnvID(); if ( !datasource || !datasource.datasourceStorages[currentEnvironment] diff --git a/app/client/src/utils/AnalyticsUtil.tsx b/app/client/src/utils/AnalyticsUtil.tsx index 33def0c07267..ca9308119b38 100644 --- a/app/client/src/utils/AnalyticsUtil.tsx +++ b/app/client/src/utils/AnalyticsUtil.tsx @@ -311,6 +311,7 @@ export type EventName = | "DISCARD_DATASOURCE_CHANGES" | "TEST_DATA_SOURCE_FAILED" | "DATASOURCE_SCHEMA_FETCH" + | "SWITCH_ENVIRONMENT" | "EDIT_ACTION_CLICK" | "QUERY_TEMPLATE_SELECTED" | "RUN_API_FAILURE" diff --git a/app/client/src/utils/editorContextUtils.ts b/app/client/src/utils/editorContextUtils.ts index 71e0fdd779ba..f3efe3788024 100644 --- a/app/client/src/utils/editorContextUtils.ts +++ b/app/client/src/utils/editorContextUtils.ts @@ -86,12 +86,24 @@ export function getPropertyControlFocusElement( export function isDatasourceAuthorizedForQueryCreation( datasource: Datasource, plugin: Plugin, + currentEnvironment = getCurrentEnvironment(), ): boolean { - const currentEnvironment = getCurrentEnvironment(); - if (!datasource) return false; + if ( + !datasource || + !datasource.hasOwnProperty("datasourceStorages") || + !datasource.datasourceStorages.hasOwnProperty(currentEnvironment) + ) + return false; + const datasourceStorage = datasource.datasourceStorages[currentEnvironment]; + if ( + !datasourceStorage || + !datasourceStorage.hasOwnProperty("id") || + !datasourceStorage.hasOwnProperty("datasourceConfiguration") + ) + return false; const authType = get( - datasource, - `datasourceStorages.${currentEnvironment}.datasourceConfiguration.authentication.authenticationType`, + datasourceStorage, + "datasourceConfiguration.authentication.authenticationType", ); const isGoogleSheetPlugin = isGoogleSheetPluginDS(plugin?.packageName); @@ -99,8 +111,8 @@ export function isDatasourceAuthorizedForQueryCreation( const isAuthorized = authType === AuthType.OAUTH2 && get( - datasource, - `datasourceStorages.${currentEnvironment}.datasourceConfiguration.authentication.authenticationStatus`, + datasourceStorage, + "datasourceConfiguration.authentication.authenticationStatus", ) === AuthenticationStatus.SUCCESS; return isAuthorized; } diff --git a/app/server/appsmith-plugins/mongoPlugin/src/main/resources/form.json b/app/server/appsmith-plugins/mongoPlugin/src/main/resources/form.json index 965b929b84c6..1cb0408f711b 100644 --- a/app/server/appsmith-plugins/mongoPlugin/src/main/resources/form.json +++ b/app/server/appsmith-plugins/mongoPlugin/src/main/resources/form.json @@ -50,13 +50,13 @@ "controlType": "SEGMENTED_CONTROL", "initialValue": "READ_WRITE", "options": [ - { - "label": "Read only", - "value": "READ_ONLY" - }, { "label": "Read / Write", "value": "READ_WRITE" + }, + { + "label": "Read only", + "value": "READ_ONLY" } ], "hidden": { diff --git a/app/server/appsmith-plugins/mssqlPlugin/src/main/resources/form.json b/app/server/appsmith-plugins/mssqlPlugin/src/main/resources/form.json index 7909b07a147d..a0eb7d851df3 100644 --- a/app/server/appsmith-plugins/mssqlPlugin/src/main/resources/form.json +++ b/app/server/appsmith-plugins/mssqlPlugin/src/main/resources/form.json @@ -8,16 +8,16 @@ "label": "Connection mode", "configProperty": "datasourceConfiguration.connection.mode", "controlType": "SEGMENTED_CONTROL", - "isRequired": true, "initialValue": "READ_WRITE", "options": [ - { - "label": "Read only", - "value": "READ_ONLY" - }, + { "label": "Read / Write", "value": "READ_WRITE" + }, + { + "label": "Read only", + "value": "READ_ONLY" } ] }, diff --git a/app/server/appsmith-plugins/mysqlPlugin/src/main/resources/form.json b/app/server/appsmith-plugins/mysqlPlugin/src/main/resources/form.json index 2e114eb44c8b..dd65a2840594 100644 --- a/app/server/appsmith-plugins/mysqlPlugin/src/main/resources/form.json +++ b/app/server/appsmith-plugins/mysqlPlugin/src/main/resources/form.json @@ -8,16 +8,15 @@ "label": "Connection mode", "configProperty": "datasourceConfiguration.connection.mode", "controlType": "SEGMENTED_CONTROL", - "isRequired": true, "initialValue": "READ_WRITE", "options": [ - { - "label": "Read only", - "value": "READ_ONLY" - }, { "label": "Read / Write", "value": "READ_WRITE" + }, + { + "label": "Read only", + "value": "READ_ONLY" } ] }, diff --git a/app/server/appsmith-plugins/postgresPlugin/src/main/resources/form.json b/app/server/appsmith-plugins/postgresPlugin/src/main/resources/form.json index b02d8eab6537..3a8fecaa11bf 100644 --- a/app/server/appsmith-plugins/postgresPlugin/src/main/resources/form.json +++ b/app/server/appsmith-plugins/postgresPlugin/src/main/resources/form.json @@ -8,16 +8,15 @@ "label": "Connection mode", "configProperty": "datasourceConfiguration.connection.mode", "controlType": "SEGMENTED_CONTROL", - "isRequired": true, "initialValue": "READ_WRITE", "options": [ - { - "label": "Read only", - "value": "READ_ONLY" - }, { "label": "Read / Write", "value": "READ_WRITE" + }, + { + "label": "Read only", + "value": "READ_ONLY" } ] }, diff --git a/app/server/appsmith-plugins/redshiftPlugin/src/main/resources/form.json b/app/server/appsmith-plugins/redshiftPlugin/src/main/resources/form.json index a726ada9dcfe..e4fafa48da1c 100644 --- a/app/server/appsmith-plugins/redshiftPlugin/src/main/resources/form.json +++ b/app/server/appsmith-plugins/redshiftPlugin/src/main/resources/form.json @@ -8,16 +8,16 @@ "label": "Connection mode", "configProperty": "datasourceConfiguration.connection.mode", "controlType": "SEGMENTED_CONTROL", - "isRequired": true, "initialValue": "READ_WRITE", "options": [ - { - "label": "Read only", - "value": "READ_ONLY" - }, + { "label": "Read / Write", "value": "READ_WRITE" + }, + { + "label": "Read only", + "value": "READ_ONLY" } ] },
67567e1ee77b1d36eb087e7a37f0e6e1cb5c8ab4
2023-06-30 16:51:00
akash-codemonk
fix: disabled steps should not be clickable in signposting (#24963)
false
disabled steps should not be clickable in signposting (#24963)
fix
diff --git a/app/client/src/pages/Editor/FirstTimeUserOnboarding/Checklist.test.tsx b/app/client/src/pages/Editor/FirstTimeUserOnboarding/Checklist.test.tsx index ccf51cb760f6..79907189a387 100644 --- a/app/client/src/pages/Editor/FirstTimeUserOnboarding/Checklist.test.tsx +++ b/app/client/src/pages/Editor/FirstTimeUserOnboarding/Checklist.test.tsx @@ -102,6 +102,22 @@ describe("Checklist", () => { ); }); + it("disabled items should not be clickable", () => { + renderComponent(getStore(0)); + const wrapper = screen.getAllByTestId("checklist-wrapper"); + expect(wrapper.length).toBe(1); + + const actionButton = screen.queryAllByTestId("checklist-action"); + dispatch.mockClear(); + fireEvent.click(actionButton[0]); + expect(dispatch).toHaveBeenCalledTimes(0); + + const connectionButton = screen.queryAllByTestId("checklist-connection"); + dispatch.mockClear(); + fireEvent.click(connectionButton[0]); + expect(dispatch).toHaveBeenCalledTimes(0); + }); + it("with `add a datasource` task checked off", () => { renderComponent(getStore(1)); const datasourceButton = screen.queryAllByTestId("checklist-datasource"); diff --git a/app/client/src/pages/Editor/FirstTimeUserOnboarding/Checklist.tsx b/app/client/src/pages/Editor/FirstTimeUserOnboarding/Checklist.tsx index 59938109cafe..9a9ffb68ed41 100644 --- a/app/client/src/pages/Editor/FirstTimeUserOnboarding/Checklist.tsx +++ b/app/client/src/pages/Editor/FirstTimeUserOnboarding/Checklist.tsx @@ -257,7 +257,7 @@ function CheckListItem(props: { data-testid={props.testid} disabled={props.disabled} onClick={ - props.completed + props.completed || props.disabled ? () => null : () => { props.onClick(); @@ -320,6 +320,7 @@ function CheckListItem(props: { targetOffset: [13, 0], }} content={createMessage(SIGNPOSTING_TOOLTIP.DOCUMENTATION.content)} + isDisabled={props.disabled} placement={"bottomLeft"} > <div className="absolute right-3"> diff --git a/app/client/src/sagas/OnboardingSagas.ts b/app/client/src/sagas/OnboardingSagas.ts index 516bbdc0aa25..6b8acefa21d2 100644 --- a/app/client/src/sagas/OnboardingSagas.ts +++ b/app/client/src/sagas/OnboardingSagas.ts @@ -461,6 +461,7 @@ function* firstTimeUserOnboardingInitSaga( type: ReduxActionTypes.SET_SHOW_FIRST_TIME_USER_ONBOARDING_MODAL, payload: true, }); + AnalyticsUtil.logEvent("SIGNPOSTING_MODAL_FIRST_TIME_OPEN"); } function* setFirstTimeUserOnboardingCompleteSaga(action: ReduxAction<boolean>) { diff --git a/app/client/src/utils/AnalyticsUtil.tsx b/app/client/src/utils/AnalyticsUtil.tsx index 75925ac27a94..e3985e1108d8 100644 --- a/app/client/src/utils/AnalyticsUtil.tsx +++ b/app/client/src/utils/AnalyticsUtil.tsx @@ -195,6 +195,7 @@ export type EventName = | "SIGNPOSTING_WELCOME_TOUR_CLICK" | "SIGNPOSTING_MODAL_CLOSE_CLICK" | "SIGNPOSTING_INFO_CLICK" + | "SIGNPOSTING_MODAL_FIRST_TIME_OPEN" | "GS_BRANCH_MORE_MENU_OPEN" | "GIT_DISCARD_WARNING" | "GIT_DISCARD_CANCEL"
9f8e1e96d06eb2107db7d99378b27f3861ee7280
2024-06-27 14:41:58
Rahul Barwal
fix: Disable custom widgets for airgapped environments (#34540)
false
Disable custom widgets for airgapped environments (#34540)
fix
diff --git a/app/client/cypress/e2e/Regression/ClientSide/Widgets/Custom/CustomWidgetDefaultComponent_spec.ts b/app/client/cypress/e2e/Regression/ClientSide/Widgets/Custom/CustomWidgetDefaultComponent_spec.ts index 4affed344fa2..94b740264599 100644 --- a/app/client/cypress/e2e/Regression/ClientSide/Widgets/Custom/CustomWidgetDefaultComponent_spec.ts +++ b/app/client/cypress/e2e/Regression/ClientSide/Widgets/Custom/CustomWidgetDefaultComponent_spec.ts @@ -6,14 +6,13 @@ import { propPane, } from "../../../../../support/Objects/ObjectsCore"; -import { featureFlagIntercept } from "../../../../../support/Objects/FeatureFlags"; import EditorNavigation, { EntityType, } from "../../../../../support/Pages/EditorNavigation"; describe( "Custom widget Tests", - { tags: ["@tag.Widget", "@tag.Custom"] }, + { tags: ["@tag.Widget", "@tag.excludeForAirgap"] }, function () { before(() => { entityExplorer.DragDropWidgetNVerify("customwidget", 550, 100); diff --git a/app/client/cypress/e2e/Regression/ClientSide/Widgets/Custom/CustomWidgetEditorPropertyPane_spec.ts b/app/client/cypress/e2e/Regression/ClientSide/Widgets/Custom/CustomWidgetEditorPropertyPane_spec.ts index fb8c2636ce0a..6805ad328817 100644 --- a/app/client/cypress/e2e/Regression/ClientSide/Widgets/Custom/CustomWidgetEditorPropertyPane_spec.ts +++ b/app/client/cypress/e2e/Regression/ClientSide/Widgets/Custom/CustomWidgetEditorPropertyPane_spec.ts @@ -7,7 +7,7 @@ import { describe( "Custom widget Tests", - { tags: ["@tag.Widget", "@tag.Custom"] }, + { tags: ["@tag.Widget", "@tag.excludeForAirgap"] }, function () { before(() => { agHelper.AddDsl("customWidget"); diff --git a/app/client/src/widgets/CustomWidget/widget/index.tsx b/app/client/src/widgets/CustomWidget/widget/index.tsx index 58f7a3320a93..86657aae51c5 100644 --- a/app/client/src/widgets/CustomWidget/widget/index.tsx +++ b/app/client/src/widgets/CustomWidget/widget/index.tsx @@ -34,6 +34,7 @@ import { ReduxActionTypes } from "@appsmith/constants/ReduxActionConstants"; import { Colors } from "constants/Colors"; import AnalyticsUtil from "@appsmith/utils/AnalyticsUtil"; import { DynamicHeight, type WidgetFeatures } from "utils/WidgetFeatures"; +import { isAirgapped } from "@appsmith/utils/airgapHelpers"; const StyledLink = styled(Link)` display: inline-block; @@ -55,6 +56,7 @@ class CustomWidget extends BaseWidget<CustomWidgetProps, WidgetState> { tags: [WIDGET_TAGS.DISPLAY], searchTags: ["external"], isSearchWildcard: true, + hideCard: isAirgapped(), }; }
e2408f6e3980c3ac153a3a016ee14df247dbfd00
2023-06-27 11:55:40
Rudraprasad Das
fix: replacing onInteractOutside with onPointerDownOutside (#24830)
false
replacing onInteractOutside with onPointerDownOutside (#24830)
fix
diff --git a/app/client/src/pages/Editor/gitSync/components/BranchMoreMenu.tsx b/app/client/src/pages/Editor/gitSync/components/BranchMoreMenu.tsx index 5a1c6a83e8ff..10abb2abfca0 100644 --- a/app/client/src/pages/Editor/gitSync/components/BranchMoreMenu.tsx +++ b/app/client/src/pages/Editor/gitSync/components/BranchMoreMenu.tsx @@ -99,7 +99,7 @@ export default function BranchMoreMenu({ branchName, open, setOpen }: Props) { <MenuContent align="end" onEscapeKeyDown={handleMenuClose} - onInteractOutside={handleMenuClose} + onPointerDownOutside={handleMenuClose} > {buttons} </MenuContent>
adedf0c1598e8571ff786c070f579b6286d071b7
2023-08-28 18:06:07
Sumesh Pradhan
ci: cypress on documentDB init db from backup archive (#26710)
false
cypress on documentDB init db from backup archive (#26710)
ci
diff --git a/.github/workflows/ci-test-with-documentdb.yml b/.github/workflows/ci-test-with-documentdb.yml index 55c75bdea0fe..5bf5b667cb85 100644 --- a/.github/workflows/ci-test-with-documentdb.yml +++ b/.github/workflows/ci-test-with-documentdb.yml @@ -125,6 +125,19 @@ jobs: - name: cat run_result run: echo ${{ steps.run_result.outputs.run_result }} + + - name: Install mongosh + run: | + sudo apt-get update + sudo apt-get install -y wget gnupg + wget -qO - https://www.mongodb.org/static/pgp/server-5.0.asc | sudo apt-key add - + echo "deb [ arch=amd64,arm64 ] https://repo.mongodb.org/apt/ubuntu jammy/mongodb-org/5.0 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-6.0.list + sudo apt-get update + sudo apt-get install -y mongodb-mongosh + + - name: Download mongodb archive + run: | + curl -o data.gz https://appsmithctl-backup-restore-test.s3.ap-south-1.amazonaws.com/docdb-data.gz - name: Download Docker image artifact uses: actions/download-artifact@v3 @@ -154,6 +167,7 @@ jobs: chmod 400 ssh_key.pem ssh -4 -o StrictHostKeyChecking=no -o ServerAliveInterval=180 -o ServerAliveCountMax=5 -i "ssh_key.pem" -L 0.0.0.0:27010:docdb-ansible-test-cluster.cluster-cz8diybf9wdj.ap-south-1.docdb.amazonaws.com:27017 [email protected] -N -f + - name: Run Appsmith, CS & TED docker image if: steps.run_result.outputs.run_result != 'success' working-directory: "." @@ -165,6 +179,7 @@ jobs: hash=$(echo -n "$timestamp" | sha1sum | awk '{print $1}') current_date=$(date -d "@$timestamp" +"%d-%m") DB_NAME="ci${hash:1:3}-${current_date}" + mongorestore --uri="${APPSMITH_MONGODB_URI}${DB_NAME}?retryWrites=false&replicaSet=rs0&directConnection=true" --archive=data.gz --gzip --drop --nsInclude=* sudo /etc/init.d/ssh stop ; mkdir -p ~/git-server/keys mkdir -p ~/git-server/repos
e662e7edc7ffdcd90f7af4c333bdcd4b4204ecd4
2024-06-28 17:38:35
Ayush Pahwa
fix: workflow js func rename code split (#34512)
false
workflow js func rename code split (#34512)
fix
diff --git a/app/client/src/ce/api/JSActionAPI.tsx b/app/client/src/ce/api/JSActionAPI.tsx index 8f2b4b8232cb..6e18d265f7db 100644 --- a/app/client/src/ce/api/JSActionAPI.tsx +++ b/app/client/src/ce/api/JSActionAPI.tsx @@ -52,6 +52,7 @@ export interface RefactorAction { oldName: string; collectionName: string; moduleId?: string; + workflowId?: string; contextType?: ActionParentEntityTypeInterface; } export interface RefactorActionRequest extends RefactorAction { diff --git a/app/client/src/sagas/JSPaneSagas.ts b/app/client/src/sagas/JSPaneSagas.ts index a6f20923cf2f..9990f3dd4d8e 100644 --- a/app/client/src/sagas/JSPaneSagas.ts +++ b/app/client/src/sagas/JSPaneSagas.ts @@ -217,6 +217,7 @@ function* handleEachUpdateJSCollection(update: JSUpdate) { collectionName: jsAction.name, pageId: data.nameChangedActions[i].pageId || "", moduleId: data.nameChangedActions[i].moduleId, + workflowId: data.nameChangedActions[i].workflowId, oldName: data.nameChangedActions[i].oldName, newName: data.nameChangedActions[i].newName, }, diff --git a/app/client/src/utils/JSPaneUtils.test.ts b/app/client/src/utils/JSPaneUtils.test.ts index a9720031f432..1d18810cb4b4 100644 --- a/app/client/src/utils/JSPaneUtils.test.ts +++ b/app/client/src/utils/JSPaneUtils.test.ts @@ -299,6 +299,7 @@ const resultRenamedActions = { id: "fun1", collectionId: "1234", moduleId: undefined, + workflowId: undefined, oldName: "myFun1", newName: "myFun11", pageId: "page123", diff --git a/app/client/src/utils/JSPaneUtils.tsx b/app/client/src/utils/JSPaneUtils.tsx index bb1e1834f507..5c37a3d346aa 100644 --- a/app/client/src/utils/JSPaneUtils.tsx +++ b/app/client/src/utils/JSPaneUtils.tsx @@ -31,6 +31,7 @@ export interface JSCollectionDifference { newName: string; pageId: string; moduleId?: string; + workflowId?: string; }>; changedVariables: Variable[]; } @@ -104,6 +105,7 @@ export const getDifferenceInJSCollection = ( newName: newActions[i].name, pageId: updateExisting.pageId, moduleId: updateExisting.moduleId, + workflowId: updateExisting.workflowId, }); newActions.splice(i, 1); toBearchivedActions.splice(indexOfArchived, 1);
70cbe74c35ee625faa90f1312102f3ad45685949
2023-09-19 15:27:44
Dhruvik Neharia
chore: remove widget discovery feature flag from code (#27401)
false
remove widget discovery feature flag from code (#27401)
chore
diff --git a/app/client/cypress/e2e/Regression/ClientSide/ExplorerTests/Widgets_Sidebar.ts b/app/client/cypress/e2e/Regression/ClientSide/ExplorerTests/Widgets_Sidebar.ts index 11253154c270..654b84b89424 100644 --- a/app/client/cypress/e2e/Regression/ClientSide/ExplorerTests/Widgets_Sidebar.ts +++ b/app/client/cypress/e2e/Regression/ClientSide/ExplorerTests/Widgets_Sidebar.ts @@ -64,16 +64,6 @@ describe("Entity explorer tests related to widgets and validation", function () WIDGETS_CATALOG.Content = ["Progress", "Rating", "Text"]; } - before(() => { - featureFlagIntercept( - { - release_widgetdiscovery_enabled: true, - }, - false, - ); - agHelper.RefreshPage(); - }); - const getTotalNumberOfWidgets = () => { return Object.values(WIDGETS_CATALOG).reduce( (totalLength, widgets) => totalLength + widgets.length, diff --git a/app/client/src/ce/entities/FeatureFlag.ts b/app/client/src/ce/entities/FeatureFlag.ts index 07e99b7448d8..6c357f8b1cfb 100644 --- a/app/client/src/ce/entities/FeatureFlag.ts +++ b/app/client/src/ce/entities/FeatureFlag.ts @@ -12,7 +12,6 @@ export const FEATURE_FLAG = { "release_embed_hide_share_settings_enabled", ab_gsheet_schema_enabled: "ab_gsheet_schema_enabled", ab_wds_enabled: "ab_wds_enabled", - release_widgetdiscovery_enabled: "release_widgetdiscovery_enabled", release_table_serverside_filtering_enabled: "release_table_serverside_filtering_enabled", release_custom_echarts_enabled: "release_custom_echarts_enabled", @@ -42,7 +41,6 @@ export const DEFAULT_FEATURE_FLAG_VALUE: FeatureFlags = { release_embed_hide_share_settings_enabled: false, ab_gsheet_schema_enabled: false, ab_wds_enabled: false, - release_widgetdiscovery_enabled: false, release_table_serverside_filtering_enabled: false, release_custom_echarts_enabled: false, license_branding_enabled: false, diff --git a/app/client/src/pages/Editor/Explorer/Pages/index.tsx b/app/client/src/pages/Editor/Explorer/Pages/index.tsx index 1a6d377fe683..c597c934fff4 100644 --- a/app/client/src/pages/Editor/Explorer/Pages/index.tsx +++ b/app/client/src/pages/Editor/Explorer/Pages/index.tsx @@ -43,8 +43,6 @@ import { import type { AppState } from "@appsmith/reducers"; import { getCurrentWorkspaceId } from "@appsmith/selectors/workspaceSelectors"; import { getInstanceId } from "@appsmith//selectors/tenantSelectors"; -import classNames from "classnames"; -import { selectFeatureFlags } from "@appsmith/selectors/featureFlagsSelectors"; const ENTITY_HEIGHT = 36; const MIN_PAGES_HEIGHT = 60; @@ -96,7 +94,6 @@ function Pages() { const storedHeightKey = "pagesContainerHeight_" + applicationId; const storedHeight = localStorage.getItem(storedHeightKey); const location = useLocation(); - const featureFlags = useSelector(selectFeatureFlags); const resizeAfterCallback = (data: CallbackResponseType) => { localStorage.setItem(storedHeightKey, data.height.toString()); @@ -226,10 +223,7 @@ function Pages() { <StyledEntity addButtonHelptext={createMessage(ADD_PAGE_TOOLTIP)} alwaysShowRightIcon - className={classNames({ - "group pages": true, - "p-3 pb-0": featureFlags.release_widgetdiscovery_enabled, - })} + className="group pages p-3 pb-0" collapseRef={pageResizeRef} customAddButton={ <AddPageContextMenu diff --git a/app/client/src/pages/Editor/Explorer/index.tsx b/app/client/src/pages/Editor/Explorer/index.tsx index 62530fa1cd5e..8e11e960a71a 100644 --- a/app/client/src/pages/Editor/Explorer/index.tsx +++ b/app/client/src/pages/Editor/Explorer/index.tsx @@ -12,14 +12,10 @@ import { getIsFirstTimeUserOnboardingEnabled } from "selectors/onboardingSelecto import AnalyticsUtil from "utils/AnalyticsUtil"; import { trimQueryString } from "utils/helpers"; import history from "utils/history"; -import WidgetSidebar from "../WidgetSidebar"; import EntityExplorer from "./EntityExplorer"; import { getExplorerSwitchIndex } from "selectors/editorContextSelectors"; import { setExplorerSwitchIndex } from "actions/editorContextActions"; -import { - adaptiveSignpostingEnabled, - selectFeatureFlags, -} from "@appsmith/selectors/featureFlagsSelectors"; +import { adaptiveSignpostingEnabled } from "@appsmith/selectors/featureFlagsSelectors"; import WidgetSidebarWithTags from "../WidgetSidebarWithTags"; import WalkthroughContext from "components/featureWalkthrough/walkthroughContext"; import { getFeatureWalkthroughShown } from "utils/storage"; @@ -52,7 +48,6 @@ function ExplorerContent() { const pageId = useSelector(getCurrentPageId); const location = useLocation(); const activeSwitchIndex = useSelector(getExplorerSwitchIndex); - const featureFlags = useSelector(selectFeatureFlags); const setActiveSwitchIndex = (index: number) => { dispatch(setExplorerSwitchIndex(index)); @@ -148,11 +143,7 @@ function ExplorerContent() { /> </div> - {featureFlags.release_widgetdiscovery_enabled ? ( - <WidgetSidebarWithTags isActive={activeOption === "widgets"} /> - ) : ( - <WidgetSidebar isActive={activeOption === "widgets"} /> - )} + <WidgetSidebarWithTags isActive={activeOption === "widgets"} /> <EntityExplorer isActive={activeOption === "explorer"} /> </div> diff --git a/app/client/src/pages/Editor/WidgetSidebar.tsx b/app/client/src/pages/Editor/WidgetSidebar.tsx deleted file mode 100644 index 5024147e57d9..000000000000 --- a/app/client/src/pages/Editor/WidgetSidebar.tsx +++ /dev/null @@ -1,148 +0,0 @@ -import React, { useContext, useEffect, useMemo, useRef, useState } from "react"; -import { useSelector } from "react-redux"; -import WidgetCard from "./WidgetCard"; -import { getWidgetCards } from "selectors/editorSelectors"; -import { SearchInput } from "design-system"; -import { ENTITY_EXPLORER_SEARCH_ID } from "constants/Explorer"; -import { debounce } from "lodash"; -import { - createMessage, - WIDGET_SIDEBAR_CAPTION, -} from "@appsmith/constants/messages"; -import Fuse from "fuse.js"; -import type { WidgetCardProps } from "widgets/BaseWidget"; -import AnalyticsUtil from "utils/AnalyticsUtil"; -import { getFeatureWalkthroughShown } from "utils/storage"; -import { FEATURE_WALKTHROUGH_KEYS } from "constants/WalkthroughConstants"; -import { getIsFirstTimeUserOnboardingEnabled } from "selectors/onboardingSelectors"; -import { adaptiveSignpostingEnabled } from "@appsmith/selectors/featureFlagsSelectors"; -import { - actionsExistInCurrentPage, - widgetsExistCurrentPage, -} from "@appsmith/selectors/entitiesSelector"; -import WalkthroughContext from "components/featureWalkthrough/walkthroughContext"; -import { SignpostingWalkthroughConfig } from "./FirstTimeUserOnboarding/Utils"; - -function WidgetSidebar({ isActive }: { isActive: boolean }) { - const cards = useSelector(getWidgetCards); - const [filteredCards, setFilteredCards] = useState(cards); - const searchInputRef = useRef<HTMLInputElement | null>(null); - - const fuse = useMemo(() => { - const options = { - keys: [ - { - name: "displayName", - weight: 0.9, - }, - { - name: "searchTags", - weight: 0.1, - }, - ], - threshold: 0.2, - distance: 100, - }; - - return new Fuse(cards, options); - }, [cards]); - - const sendWidgetSearchAnalytics = debounce((value: string) => { - if (value !== "") { - AnalyticsUtil.logEvent("WIDGET_SEARCH", { value }); - } - }, 1000); - - const filterCards = (keyword: string) => { - sendWidgetSearchAnalytics(keyword); - if (keyword.trim().length > 0) { - const searchResult = fuse.search(keyword); - setFilteredCards(searchResult as WidgetCardProps[]); - } else { - setFilteredCards(cards); - } - }; - - useEffect(() => { - if (isActive) searchInputRef.current?.focus(); - }, [isActive]); - - const search = debounce((value: string) => { - filterCards(value.toLowerCase()); - }, 300); - - const { pushFeature } = useContext(WalkthroughContext) || {}; - const signpostingEnabled = useSelector(getIsFirstTimeUserOnboardingEnabled); - const adaptiveSignposting = useSelector(adaptiveSignpostingEnabled); - const hasWidgets = useSelector(widgetsExistCurrentPage); - const actionsExist = useSelector(actionsExistInCurrentPage); - useEffect(() => { - async function scrollToTableWidgetCard() { - const isFeatureWalkthroughShown = await getFeatureWalkthroughShown( - FEATURE_WALKTHROUGH_KEYS.add_table_widget, - ); - const widgetCard = document.getElementById( - "widget-card-draggable-tablewidgetv2", - ); - - if (!isFeatureWalkthroughShown) { - widgetCard?.scrollIntoView(); - checkAndShowTableWidgetWalkthrough(); - } - } - if ( - signpostingEnabled && - !hasWidgets && - adaptiveSignposting && - isActive && - actionsExist - ) { - scrollToTableWidgetCard(); - } - }, [ - isActive, - hasWidgets, - signpostingEnabled, - adaptiveSignposting, - actionsExist, - ]); - const checkAndShowTableWidgetWalkthrough = async () => { - pushFeature && - pushFeature(SignpostingWalkthroughConfig.ADD_TABLE_WIDGET, true); - }; - - return ( - <div - className={`flex flex-col overflow-hidden ${isActive ? "" : "hidden"}`} - > - <div className="sticky top-0 px-3 mt-0.5"> - <SearchInput - autoComplete="off" - autoFocus - id={ENTITY_EXPLORER_SEARCH_ID} - onChange={search} - placeholder="Search widgets" - ref={searchInputRef} - type="text" - /> - </div> - <div - className="flex-grow px-3 mt-3 overflow-y-scroll" - data-testid="widget-sidebar-scrollable-wrapper" - > - <p className="px-3 py-3 text-sm leading-relaxed t--widget-sidebar"> - {createMessage(WIDGET_SIDEBAR_CAPTION)} - </p> - <div className="grid items-stretch grid-cols-3 gap-3 justify-items-stretch"> - {filteredCards.map((card) => ( - <WidgetCard details={card} key={card.key} /> - ))} - </div> - </div> - </div> - ); -} - -WidgetSidebar.displayName = "WidgetSidebar"; - -export default WidgetSidebar;
b831a3943b474961e7417e697e6f3d9dfe409d64
2024-05-22 11:36:20
Shrikant Sharat Kandula
chore: Add ApplicationCreationDTO for Application creation API body (#33200)
false
Add ApplicationCreationDTO for Application creation API body (#33200)
chore
diff --git a/app/client/cypress/support/commands.js b/app/client/cypress/support/commands.js index a888f44863a0..c666246cb64f 100644 --- a/app/client/cypress/support/commands.js +++ b/app/client/cypress/support/commands.js @@ -954,9 +954,7 @@ Cypress.Commands.add("startServerAndRoutes", () => { cy.intercept("GET", "/api/v1/plugins/*/form").as("getPluginForm"); cy.intercept("DELETE", "/api/v1/applications/*").as("deleteApplication"); - cy.intercept("POST", "/api/v1/applications?workspaceId=*").as( - "createNewApplication", - ); + cy.intercept("POST", "/api/v1/applications").as("createNewApplication"); cy.intercept("PUT", "/api/v1/applications/*").as("updateApplication"); cy.intercept("PUT", "/api/v1/actions/*").as("saveAction"); cy.intercept("PUT", "/api/v1/actions/move").as("moveAction"); diff --git a/app/client/src/ce/api/ApplicationApi.tsx b/app/client/src/ce/api/ApplicationApi.tsx index a019cf62204b..2ffa8cc883fb 100644 --- a/app/client/src/ce/api/ApplicationApi.tsx +++ b/app/client/src/ce/api/ApplicationApi.tsx @@ -283,8 +283,6 @@ export class ApplicationApi extends Api { static baseURL = "v1/applications"; static publishURLPath = (applicationId: string) => `/publish/${applicationId}`; - static createApplicationPath = (workspaceId: string) => - `?workspaceId=${workspaceId}`; static changeAppViewAccessPath = (applicationId: string) => `/${applicationId}/changeAccess`; static setDefaultPagePath = (request: SetDefaultPageRequest) => @@ -341,28 +339,14 @@ export class ApplicationApi extends Api { static async createApplication( request: CreateApplicationRequest, ): Promise<AxiosPromise<PublishApplicationResponse>> { - const applicationDetail = { - appPositioning: { - type: request.layoutSystemType, - }, - } as any; - - if (request.showNavbar !== undefined) { - applicationDetail.navigationSetting = { - showNavbar: request.showNavbar, - }; - } - - return Api.post( - ApplicationApi.baseURL + - ApplicationApi.createApplicationPath(request.workspaceId), - { - name: request.name, - color: request.color, - icon: request.icon, - applicationDetail, - }, - ); + return Api.post(ApplicationApi.baseURL, { + workspaceId: request.workspaceId, + name: request.name, + color: request.color, + icon: request.icon, + positioningType: request.layoutSystemType, + showNavbar: request.showNavbar ?? null, + }); } static async setDefaultApplicationPage( 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 5fdb997c6f6e..872c9ab606fd 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 @@ -9,6 +9,7 @@ import com.appsmith.server.domains.GitAuth; import com.appsmith.server.domains.Theme; import com.appsmith.server.dtos.ApplicationAccessDTO; +import com.appsmith.server.dtos.ApplicationCreationDTO; import com.appsmith.server.dtos.ApplicationImportDTO; import com.appsmith.server.dtos.ApplicationJson; import com.appsmith.server.dtos.ApplicationPagesDTO; @@ -19,8 +20,6 @@ import com.appsmith.server.dtos.PartialExportFileDTO; import com.appsmith.server.dtos.ReleaseItemsDTO; import com.appsmith.server.dtos.ResponseDTO; -import com.appsmith.server.exceptions.AppsmithError; -import com.appsmith.server.exceptions.AppsmithException; import com.appsmith.server.exports.internal.ExportService; import com.appsmith.server.exports.internal.partial.PartialExportService; import com.appsmith.server.fork.internal.ApplicationForkingService; @@ -77,14 +76,10 @@ public class ApplicationControllerCE { @JsonView(Views.Public.class) @PostMapping @ResponseStatus(HttpStatus.CREATED) - public Mono<ResponseDTO<Application>> create( - @Valid @RequestBody Application resource, @RequestParam String workspaceId) { - if (workspaceId == null) { - return Mono.error(new AppsmithException(AppsmithError.INVALID_PARAMETER, "workspace id")); - } - log.debug("Going to create application in workspace {}", workspaceId); + public Mono<ResponseDTO<Application>> create(@Valid @RequestBody ApplicationCreationDTO resource) { + log.debug("Going to create application in workspace {}", resource.workspaceId()); return applicationPageService - .createApplication(resource, workspaceId) + .createApplication(resource.toApplication()) .map(created -> new ResponseDTO<>(HttpStatus.CREATED.value(), created, null)); } 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 b8edc1f34be3..3b88521ed641 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 @@ -428,12 +428,13 @@ public static class NavigationSetting { */ @Data @NoArgsConstructor + @AllArgsConstructor public static class AppPositioning { @JsonView({Views.Public.class, Git.class}) Type type; - public AppPositioning(Type type) { - this.type = type; + public AppPositioning(String type) { + setType(Type.valueOf(type)); } public enum Type { diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/dtos/ApplicationCreationDTO.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/dtos/ApplicationCreationDTO.java new file mode 100644 index 000000000000..2ee5349daf4f --- /dev/null +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/dtos/ApplicationCreationDTO.java @@ -0,0 +1,37 @@ +package com.appsmith.server.dtos; + +import com.appsmith.server.domains.Application; +import com.appsmith.server.domains.ApplicationDetail; +import com.appsmith.server.meta.validations.IconName; +import jakarta.validation.constraints.NotBlank; +import jakarta.validation.constraints.Pattern; +import jakarta.validation.constraints.Size; +import org.apache.commons.lang3.StringUtils; + +public record ApplicationCreationDTO( + @NotBlank @Size(max = 99) String workspaceId, + @NotBlank @Size(max = 99) String name, + @IconName String icon, + @Pattern(regexp = "#[A-F0-9]{6}") String color, + Application.AppPositioning positioningType, + Boolean showNavBar) { + + public Application toApplication() { + final Application application = new Application(); + application.setWorkspaceId(workspaceId); + application.setName(name.trim()); + application.setIcon(StringUtils.isBlank(icon) ? null : icon.trim()); + application.setColor(color); + + final ApplicationDetail applicationDetail = new ApplicationDetail(); + application.setApplicationDetail(applicationDetail); + + applicationDetail.setAppPositioning(positioningType); + + final Application.NavigationSetting navigationSetting = new Application.NavigationSetting(); + navigationSetting.setShowNavbar(showNavBar); + applicationDetail.setNavigationSetting(navigationSetting); + + return application; + } +} diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/dtos/PageCreationDTO.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/dtos/PageCreationDTO.java index 455bb912730d..cf567a80a25d 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/dtos/PageCreationDTO.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/dtos/PageCreationDTO.java @@ -8,13 +8,13 @@ import java.util.List; public record PageCreationDTO( - @FileName(message = "Page names must be valid file names") @Size(max = 30) String name, + @FileName(message = "Page names must be valid file names", isNullValid = false) @Size(max = 30) String name, @NotEmpty @Size(min = 24, max = 50) String applicationId, @NotEmpty List<Layout> layouts) { public PageDTO toPageDTO() { final PageDTO page = new PageDTO(); - page.setName(name); + page.setName(name.trim()); page.setApplicationId(applicationId); page.setLayouts(layouts); return page; diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/dtos/PageUpdateDTO.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/dtos/PageUpdateDTO.java index 45f089e1cfd8..b0490f7c411a 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/dtos/PageUpdateDTO.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/dtos/PageUpdateDTO.java @@ -1,19 +1,21 @@ package com.appsmith.server.dtos; import com.appsmith.server.meta.validations.FileName; +import com.appsmith.server.meta.validations.IconName; import jakarta.validation.constraints.Pattern; import jakarta.validation.constraints.Size; +import org.apache.commons.lang3.StringUtils; public record PageUpdateDTO( @FileName(message = "Page names must be valid file names") @Size(max = 30) String name, - @Pattern(regexp = "[-a-z]+") @Size(max = 20) String icon, + @IconName String icon, @Pattern(regexp = "[-\\w]*") String customSlug, Boolean isHidden) { public PageDTO toPageDTO() { final PageDTO page = new PageDTO(); - page.setName(name); - page.setIcon(icon); + page.setName(name == null ? null : name.trim()); + page.setIcon(StringUtils.isBlank(icon) ? null : icon.trim()); page.setCustomSlug(customSlug); page.setIsHidden(isHidden); return page; diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/meta/validations/IconName.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/meta/validations/IconName.java new file mode 100644 index 000000000000..7a12f1447bf4 --- /dev/null +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/meta/validations/IconName.java @@ -0,0 +1,22 @@ +package com.appsmith.server.meta.validations; + +import jakarta.validation.Constraint; +import jakarta.validation.Payload; + +import java.lang.annotation.Documented; +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +@Documented +@Constraint(validatedBy = {IconNameValidator.class}) +@Target({ElementType.FIELD, ElementType.METHOD}) +@Retention(RetentionPolicy.RUNTIME) +public @interface IconName { + String message() default "Invalid icon name"; + + Class<?>[] groups() default {}; + + Class<? extends Payload>[] payload() default {}; +} diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/meta/validations/IconNameValidator.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/meta/validations/IconNameValidator.java new file mode 100644 index 000000000000..77a95aad219e --- /dev/null +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/meta/validations/IconNameValidator.java @@ -0,0 +1,16 @@ +package com.appsmith.server.meta.validations; + +import jakarta.validation.ConstraintValidator; +import jakarta.validation.ConstraintValidatorContext; + +import java.util.regex.Pattern; + +public class IconNameValidator implements ConstraintValidator<IconName, String> { + + private static final Pattern PATTERN = Pattern.compile("[-a-z]{1,20}"); + + @Override + public boolean isValid(String value, ConstraintValidatorContext context) { + return value == null || PATTERN.matcher(value).matches(); + } +} diff --git a/app/server/appsmith-server/src/test/java/com/appsmith/server/domains/EqualityTest.java b/app/server/appsmith-server/src/test/java/com/appsmith/server/domains/EqualityTest.java index 4b1062dc01f3..e15667024b9c 100644 --- a/app/server/appsmith-server/src/test/java/com/appsmith/server/domains/EqualityTest.java +++ b/app/server/appsmith-server/src/test/java/com/appsmith/server/domains/EqualityTest.java @@ -58,12 +58,9 @@ void testTenantConfiguration() { @Test void testApplicationDetail() { - Application.AppPositioning p1 = new Application.AppPositioning(); - p1.setType(Application.AppPositioning.Type.AUTO); - Application.AppPositioning p2 = new Application.AppPositioning(); - p2.setType(Application.AppPositioning.Type.AUTO); - Application.AppPositioning p3 = new Application.AppPositioning(); - p3.setType(Application.AppPositioning.Type.FIXED); + Application.AppPositioning p1 = new Application.AppPositioning(Application.AppPositioning.Type.AUTO); + Application.AppPositioning p2 = new Application.AppPositioning(Application.AppPositioning.Type.AUTO); + Application.AppPositioning p3 = new Application.AppPositioning(Application.AppPositioning.Type.FIXED); assertThat(p1).isEqualTo(p2).isNotEqualTo(p3); ApplicationDetail d1 = new ApplicationDetail();
324b077ffa19855e3058121744dda08196f4d671
2022-02-04 16:27:14
yatinappsmith
test: Fix reusing the result of Github actions in case the previous run fails (#10888)
false
Fix reusing the result of Github actions in case the previous run fails (#10888)
test
diff --git a/.github/workflows/integration-tests-command.yml b/.github/workflows/integration-tests-command.yml index cdfa6835a6cd..157464dbdf3d 100644 --- a/.github/workflows/integration-tests-command.yml +++ b/.github/workflows/integration-tests-command.yml @@ -125,6 +125,9 @@ jobs: name: build path: app/server/dist/ + # Set status = success + - run: echo "::set-output name=run_result::success" > ~/run_result + build: runs-on: ubuntu-latest if: github.event_name == 'repository_dispatch' && @@ -341,7 +344,7 @@ jobs: fail-fast: false matrix: job: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23] - + # Service containers to run with this job. Required for running tests services: # Label used to access the service container @@ -660,6 +663,9 @@ jobs: name: server-logs-${{ matrix.job }} path: app/server/server-logs.log + # Set status = success + - run: echo "::set-output name=run_result::success" > ~/run_result + ui-test-result: needs: ui-test # Only run if the ui-test with matrices step is successful
3ea05687715164a1dd98ffeaafc28c5d686527ea
2023-07-24 15:59:05
Ayangade Adeoluwa
fix: Fix cancel issue and form value state persistence (#25412)
false
Fix cancel issue and form value state persistence (#25412)
fix
diff --git a/app/client/cypress/e2e/Regression/ClientSide/BugTests/DSDiscardBugs_spec.ts b/app/client/cypress/e2e/Regression/ClientSide/BugTests/DSDiscardBugs_spec.ts index d8f5b6bf622d..5c32366b2528 100644 --- a/app/client/cypress/e2e/Regression/ClientSide/BugTests/DSDiscardBugs_spec.ts +++ b/app/client/cypress/e2e/Regression/ClientSide/BugTests/DSDiscardBugs_spec.ts @@ -91,7 +91,88 @@ describe("datasource unsaved changes popup shows even without changes", function }); }); - it("4. Bug 19801: Create new Auth DS, refresh the page without saving, we should not see discard popup", () => { + it("4. Validate that the DS modal shows up when cancel button is pressed after change", () => { + _.dataSources.NavigateToDSCreateNew(); + _.agHelper.GenerateUUID(); + cy.get("@guid").then((uid) => { + // using CreatePlugIn function instead of CreateDatasource, + // because I do not need to fill the datasource form and use the same default data + _.dataSources.CreatePlugIn("MongoDB"); + dsName = "Mongo" + uid; + _.agHelper.RenameWithInPane(dsName, false); + _.dataSources.FillMongoDSForm(); + _.dataSources.SaveDatasource(); + _.agHelper.Sleep(); + + // Edit datasource, change connection string uri param and click on back button + _.dataSources.EditDatasource(); + _.dataSources.FillMongoDatasourceFormWithURI(); + + // Assert that popup is visible + _.dataSources.cancelDSEditAndAssertModalPopUp(true, false); + + _.dataSources.DeleteDatasouceFromActiveTab(dsName); + }); + }); + + it("5. Validate that the DS modal does not show up when cancel button is pressed without any changes being made", () => { + _.dataSources.NavigateToDSCreateNew(); + _.agHelper.GenerateUUID(); + cy.get("@guid").then((uid) => { + // using CreatePlugIn function instead of CreateDatasource, + // because I do not need to fill the datasource form and use the same default data + _.dataSources.CreatePlugIn("MongoDB"); + dsName = "Mongo" + uid; + _.agHelper.RenameWithInPane(dsName, false); + _.dataSources.FillMongoDSForm(); + _.dataSources.SaveDatasource(); + _.agHelper.Sleep(); + + // Edit datasource, change connection string uri param and click on back button + _.dataSources.EditDatasource(); + + // Assert that popup is visible + _.dataSources.cancelDSEditAndAssertModalPopUp(false, false); + + _.dataSources.DeleteDatasouceFromActiveTab(dsName); + }); + }); + + it("6. Validate that changes made to the form are not persisted after cancellation", () => { + _.dataSources.NavigateToDSCreateNew(); + _.agHelper.GenerateUUID(); + cy.get("@guid").then((uid) => { + // using CreatePlugIn function instead of CreateDatasource, + // because I do not need to fill the datasource form and use the same default data + _.dataSources.CreatePlugIn("MongoDB"); + dsName = "Mongo" + uid; + _.agHelper.RenameWithInPane(dsName, false); + _.dataSources.FillMongoDSForm(); + _.dataSources.SaveDatasource(); + _.agHelper.Sleep(); + + // Edit datasource, change connection string uri param and click on back button + _.dataSources.EditDatasource(); + + _.agHelper.UpdateInputValue(_.dataSources._host, "jargons"); + + // Assert that popup is visible + _.dataSources.cancelDSEditAndAssertModalPopUp(true, false); + + // try to edit again + _.dataSources.EditDatasource(); + + // validate the input field value still remains as the saved value + _.agHelper.ValidateFieldInputValue( + _.dataSources._host, + _.tedTestConfig.dsValues.staging.mongo_host, + ); + + _.dataSources.DeleteDatasouceFromActiveTab(dsName); + }); + }); + + it("7. Bug 19801: Create new Auth DS, refresh the page without saving, we should not see discard popup", () => { _.dataSources.NavigateToDSCreateNew(); _.agHelper.GenerateUUID(); // using CreatePlugIn function instead of CreateDatasource, diff --git a/app/client/cypress/support/Pages/AggregateHelper.ts b/app/client/cypress/support/Pages/AggregateHelper.ts index 58fe673145ec..85e9694df502 100644 --- a/app/client/cypress/support/Pages/AggregateHelper.ts +++ b/app/client/cypress/support/Pages/AggregateHelper.ts @@ -1085,6 +1085,17 @@ export class AggregateHelper extends ReusableHelper { this.Sleep(); //for value set to settle } + public ValidateFieldInputValue(selector: string, value: string) { + this.GetElement(selector) + .closest("input") + .scrollIntoView({ easing: "linear" }) + .invoke("val") + .then((inputValue) => { + expect(inputValue).to.equal(value); + }); + this.Sleep(); //for value set to settle + } + public UpdateTextArea(selector: string, value: string) { this.GetElement(selector) .find("textarea") diff --git a/app/client/cypress/support/Pages/DataSources.ts b/app/client/cypress/support/Pages/DataSources.ts index bb123644c6d3..85d992627d8c 100644 --- a/app/client/cypress/support/Pages/DataSources.ts +++ b/app/client/cypress/support/Pages/DataSources.ts @@ -761,6 +761,21 @@ export class DataSources { this.DeleteDSDirectly(expectedRes); } + // this initiates saving via the cancel button. + public cancelDSEditAndAssertModalPopUp( + shouldPopUpBeShown = false, + shouldSave = false, + ) { + // click cancel button. + this.agHelper.GetNClick(this._cancelEditDatasourceButton, 0, false, 200); + + if (shouldPopUpBeShown) { + this.AssertDatasourceSaveModalVisibilityAndSave(shouldSave); + } else { + this.AssertDSDialogVisibility(false); + } + } + public DeleteDSDirectly( expectedRes: number | number[] = 200 || 409 || [200 | 409], ) { @@ -1290,10 +1305,18 @@ export class DataSources { } } - public SaveDSFromDialog(save = true) { - this.agHelper.GoBack(); - this.agHelper.AssertElementVisible(this._datasourceModalDoNotSave); - this.agHelper.AssertElementVisible(this._datasourceModalSave); + public AssertDSDialogVisibility(isVisible = true) { + if (isVisible) { + this.agHelper.AssertElementVisible(this._datasourceModalDoNotSave); + this.agHelper.AssertElementVisible(this._datasourceModalSave); + } else { + this.agHelper.AssertElementAbsence(this._datasourceModalDoNotSave); + this.agHelper.AssertElementAbsence(this._datasourceModalSave); + } + } + + public AssertDatasourceSaveModalVisibilityAndSave(save = true) { + this.AssertDSDialogVisibility(); if (save) { this.agHelper.GetNClick( this.locator._visibleTextSpan("Save"), @@ -1312,6 +1335,12 @@ export class DataSources { ); } + // this initiates saving via the back button. + public SaveDSFromDialog(save = true) { + this.agHelper.GoBack(); + this.AssertDatasourceSaveModalVisibilityAndSave(save); + } + public getDSEntity(dSName: string) { return `[data-guided-tour-id="explorer-entity-${dSName}"]`; } diff --git a/app/client/src/pages/Editor/DataSourceEditor/index.tsx b/app/client/src/pages/Editor/DataSourceEditor/index.tsx index 4615055a1bcd..057ae0d81719 100644 --- a/app/client/src/pages/Editor/DataSourceEditor/index.tsx +++ b/app/client/src/pages/Editor/DataSourceEditor/index.tsx @@ -424,6 +424,18 @@ class DatasourceEditorRouter extends React.Component<Props, State> { }); } + onCancel() { + // if form has changed, show modal popup, or else simply set to view mode. + if (this.props.isFormDirty) { + this.setState({ showDialog: true }); + } else { + this.props.setDatasourceViewMode({ + datasourceId: this.props.datasourceId, + viewMode: true, + }); + } + } + closeDialog() { this.setState({ showDialog: false }); } @@ -444,6 +456,18 @@ class DatasourceEditorRouter extends React.Component<Props, State> { this.props.datasourceDiscardAction(this.props?.pluginId); } this.state.navigation(); + this.props.datasourceDiscardAction(this.props?.pluginId); + + if (!this.props.viewMode) { + this.props.setDatasourceViewMode({ + datasourceId: this.props.datasourceId, + viewMode: true, + }); + } + + if (this.props.isFormDirty) { + this.props.resetForm(this.props.formName); + } } closeDialogAndUnblockRoutes(isNavigateBack?: boolean) { @@ -852,6 +876,7 @@ class DatasourceEditorRouter extends React.Component<Props, State> { isInvalid={this.validateForm()} isSaving={isSaving} isTesting={isTesting} + onCancel={() => this.onCancel()} pluginName={pluginName} pluginPackageName={pluginPackageName} pluginType={pluginType as PluginType} diff --git a/app/client/src/pages/Editor/SaaSEditor/DatasourceForm.tsx b/app/client/src/pages/Editor/SaaSEditor/DatasourceForm.tsx index c492467e605b..0c7caa6cd98a 100644 --- a/app/client/src/pages/Editor/SaaSEditor/DatasourceForm.tsx +++ b/app/client/src/pages/Editor/SaaSEditor/DatasourceForm.tsx @@ -10,6 +10,7 @@ import { reduxForm, initialize, getFormInitialValues, + reset, } from "redux-form"; import type { RouteComponentProps } from "react-router"; import { connect } from "react-redux"; @@ -126,6 +127,7 @@ interface DatasourceFormFunctions { loadFilePickerAction: () => void; datasourceDiscardAction: (pluginId: string) => void; initializeDatasource: (values: any) => void; + resetForm: (formName: string) => void; } type DatasourceSaaSEditorProps = StateProps & @@ -397,6 +399,17 @@ class DatasourceSaaSEditor extends JSONtoForm<Props, State> { this.closeDialogAndUnblockRoutes(); this.state.navigation(); this.props.datasourceDiscardAction(this.props?.pluginId); + + if (!this.props.viewMode) { + this.props.setDatasourceViewMode({ + datasourceId: this.props.datasourceId, + viewMode: true, + }); + } + + if (this.props.isFormDirty) { + this.props.resetForm(this.props.formName); + } } closeDialogAndUnblockRoutes(isNavigateBack?: boolean) { @@ -430,6 +443,18 @@ class DatasourceSaaSEditor extends JSONtoForm<Props, State> { }; }; + onCancel() { + // if form has changed, show modal popup, or else simply set to view mode. + if (this.props.isFormDirty) { + this.setState({ showDialog: true }); + } else { + this.props.setDatasourceViewMode({ + datasourceId: this.props.datasourceId, + viewMode: true, + }); + } + } + renderDataSourceConfigForm = (sections: any) => { const { canCreateDatasourceActions, @@ -587,6 +612,7 @@ class DatasourceSaaSEditor extends JSONtoForm<Props, State> { isInvalid={validate(this.props.requiredFields, formData)} isSaving={isSaving} isTesting={isTesting} + onCancel={() => this.onCancel()} pageId={pageId} pluginName={plugin?.name || ""} pluginPackageName={pluginPackageName} @@ -757,6 +783,7 @@ const mapDispatchToProps = (dispatch: any): DatasourceFormFunctions => ({ dispatch(datasourceDiscardAction(pluginId)), initializeDatasource: (values: any) => dispatch(initialize(DATASOURCE_SAAS_FORM, values)), + resetForm: (formName: string) => dispatch(reset(formName)), }); const SaaSEditor = connect( diff --git a/app/client/src/pages/common/datasourceAuth/index.tsx b/app/client/src/pages/common/datasourceAuth/index.tsx index 6d5d8e90ae7a..3f3d3edea34a 100644 --- a/app/client/src/pages/common/datasourceAuth/index.tsx +++ b/app/client/src/pages/common/datasourceAuth/index.tsx @@ -35,7 +35,6 @@ import { integrationEditorURL } from "RouteBuilder"; import { getQueryParams } from "utils/URLUtils"; import type { AppsmithLocationState } from "utils/history"; import type { PluginType } from "entities/Action"; -import { reset } from "redux-form"; import { getCurrentEnvName } from "@appsmith/utils/Environments"; interface Props { @@ -64,6 +63,7 @@ interface Props { isFormDirty?: boolean; scopeValue?: string; showFilterComponent: boolean; + onCancel: () => void; } export type DatasourceFormButtonTypes = Record<string, string[]>; @@ -134,7 +134,6 @@ function DatasourceAuth({ DatasourceButtonTypeEnum.SAVE, ], formData, - formName, getSanitizedFormData, isInvalid, pageId: pageIdProp, @@ -145,12 +144,12 @@ function DatasourceAuth({ isTesting, viewMode, shouldDisplayAuthMessage = true, - setDatasourceViewMode, triggerSave, isFormDirty, scopeValue, isInsideReconnectModal, showFilterComponent, + onCancel, }: Props) { const shouldRender = !viewMode || isInsideReconnectModal; const authType = @@ -314,10 +313,7 @@ function DatasourceAuth({ }; const createMode = datasourceId === TEMP_DATASOURCE_ID; - const datasourceButtonsComponentMap = ( - buttonType: string, - datasourceId: string, - ): JSX.Element => { + const datasourceButtonsComponentMap = (buttonType: string): JSX.Element => { return { [DatasourceButtonType.TEST]: ( <ActionButton @@ -347,8 +343,7 @@ function DatasourceAuth({ }); history.push(URL); } else { - setDatasourceViewMode({ datasourceId, viewMode: true }); - dispatch(reset(formName)); + !!onCancel && onCancel(); } }} size="md" @@ -397,7 +392,7 @@ function DatasourceAuth({ {shouldRender && ( <SaveButtonContainer isInsideReconnectModal={isInsideReconnectModal}> {datasourceButtonConfiguration?.map((btnConfig) => - datasourceButtonsComponentMap(btnConfig, datasource.id), + datasourceButtonsComponentMap(btnConfig), )} </SaveButtonContainer> )}
e1d09b47d31c4b54df035da8bf7c570dcdaaca18
2025-03-14 17:40:02
Ankita Kinger
chore: Removing the feature flag for using Entity Item component from ADS templates (#39093)
false
Removing the feature flag for using Entity Item component from ADS templates (#39093)
chore
diff --git a/app/client/cypress/e2e/Regression/Apps/EchoApiCMS_spec.js b/app/client/cypress/e2e/Regression/Apps/EchoApiCMS_spec.js index c535eedbe285..15c00e8427fd 100644 --- a/app/client/cypress/e2e/Regression/Apps/EchoApiCMS_spec.js +++ b/app/client/cypress/e2e/Regression/Apps/EchoApiCMS_spec.js @@ -92,7 +92,7 @@ describe( cy.get(appPage.closeButton).closest("div").click({ force: true }); PageLeftPane.switchSegment(PagePaneSegment.UI); PageLeftPane.switchSegment(PagePaneSegment.Queries); - cy.xpath(appPage.postApi).click({ force: true }); + cy.get(appPage.postApi).click({ force: true }); cy.ResponseCheck("Test"); // cy.ResponseCheck("Task completed"); cy.ResponseCheck("[email protected]"); diff --git a/app/client/cypress/e2e/Regression/ClientSide/Autocomplete/Bugs_AC_Spec.ts b/app/client/cypress/e2e/Regression/ClientSide/Autocomplete/Bugs_AC_Spec.ts index 6f149a7b49ee..495d8e4987b4 100644 --- a/app/client/cypress/e2e/Regression/ClientSide/Autocomplete/Bugs_AC_Spec.ts +++ b/app/client/cypress/e2e/Regression/ClientSide/Autocomplete/Bugs_AC_Spec.ts @@ -112,6 +112,8 @@ describe( "8. No autocomplete for Removed libraries", { tags: ["@tag.excludeForAirgap"] }, function () { + AppSidebar.navigate(AppSidebarButton.Editor); + EditorNavigation.SelectEntityByName("Text1Copy", EntityType.Widget); entityExplorer.RenameEntityFromExplorer("Text1Copy", "UUIDTEXT"); AppSidebar.navigate(AppSidebarButton.Libraries); installer.uninstallLibrary("uuidjs"); diff --git a/app/client/cypress/e2e/Regression/ClientSide/BugTests/Bug20275_Spec.js b/app/client/cypress/e2e/Regression/ClientSide/BugTests/Bug20275_Spec.js index 45d072a8b392..442c680e1391 100644 --- a/app/client/cypress/e2e/Regression/ClientSide/BugTests/Bug20275_Spec.js +++ b/app/client/cypress/e2e/Regression/ClientSide/BugTests/Bug20275_Spec.js @@ -30,7 +30,7 @@ describe( prettify: false, }); - jsEditor.EnableDisableAsyncFuncSettings("myFun1", true, false); + jsEditor.EnableDisableAsyncFuncSettings("myFun1", true); ee.DragDropWidgetNVerify(WIDGET.TEXT, 200, 600); EditorNavigation.SelectEntityByName("Text1", EntityType.Widget); diff --git a/app/client/cypress/e2e/Regression/ClientSide/ExplorerTests/API_Pane_spec.js b/app/client/cypress/e2e/Regression/ClientSide/ExplorerTests/API_Pane_spec.js index 11e9fd975b15..c830261e661a 100644 --- a/app/client/cypress/e2e/Regression/ClientSide/ExplorerTests/API_Pane_spec.js +++ b/app/client/cypress/e2e/Regression/ClientSide/ExplorerTests/API_Pane_spec.js @@ -108,11 +108,6 @@ describe( action: "Rename", }); cy.EditApiNameFromExplorer("SecondAPI"); - cy.xpath(apiwidget.popover) - .last() - .should("be.hidden") - .invoke("show") - .click({ force: true }); ee.ActionContextMenuByEntityName({ entityNameinLeftSidebar: "SecondAPI", action: "Move to page", diff --git a/app/client/cypress/e2e/Regression/ClientSide/ExplorerTests/JSEditorContextMenu_Spec.ts b/app/client/cypress/e2e/Regression/ClientSide/ExplorerTests/JSEditorContextMenu_Spec.ts index c132f969099e..cd67484a5563 100644 --- a/app/client/cypress/e2e/Regression/ClientSide/ExplorerTests/JSEditorContextMenu_Spec.ts +++ b/app/client/cypress/e2e/Regression/ClientSide/ExplorerTests/JSEditorContextMenu_Spec.ts @@ -59,7 +59,7 @@ describe( toastToValidate: "moved to page", entityType: EntityItems.Page, }); - EditorNavigation.SelectEntityByName(newPageId, EntityType.Page); + PageList.VerifyIsCurrentPage(newPageId); PageLeftPane.switchSegment(PagePaneSegment.JS); PageLeftPane.assertPresence("RenamedJSObjectCopy"); jsEditor.ValidateDefaultJSObjProperties("RenamedJSObjectCopy"); diff --git a/app/client/cypress/e2e/Regression/ClientSide/ExplorerTests/Renaming_spec.js b/app/client/cypress/e2e/Regression/ClientSide/ExplorerTests/Renaming_spec.js index 8df62d3156c0..39ac3ba7c28a 100644 --- a/app/client/cypress/e2e/Regression/ClientSide/ExplorerTests/Renaming_spec.js +++ b/app/client/cypress/e2e/Regression/ClientSide/ExplorerTests/Renaming_spec.js @@ -32,7 +32,10 @@ describe( cy.get(".t--context-menu").click({ force: true }); }); cy.selectAction("Rename"); - cy.get(explorer.editEntity).last().type(firstApiName, { force: true }); + cy.get(explorer.editEntity) + .last() + .clear() + .type(firstApiName, { force: true }); cy.validateMessage(firstApiName); agHelper.PressEnter(); entityExplorer.ActionContextMenuByEntityName({ @@ -98,7 +101,10 @@ describe("Entity Naming conflict test", { tags: ["@tag.IDE"] }, function () { }); cy.selectAction("Rename"); - cy.get(explorer.editEntity).last().type(firstApiName, { force: true }); + cy.get(explorer.editEntity) + .last() + .clear() + .type(firstApiName, { force: true }); entityExplorer.ValidateDuplicateMessageToolTip(firstApiName); cy.get("body").click(0, 0); cy.wait(2000); diff --git a/app/client/cypress/e2e/Regression/ClientSide/ExplorerTests/Tab_rename_Delete_spec.ts b/app/client/cypress/e2e/Regression/ClientSide/ExplorerTests/Tab_rename_Delete_spec.ts index df52ca57622b..02466b00c31f 100644 --- a/app/client/cypress/e2e/Regression/ClientSide/ExplorerTests/Tab_rename_Delete_spec.ts +++ b/app/client/cypress/e2e/Regression/ClientSide/ExplorerTests/Tab_rename_Delete_spec.ts @@ -31,7 +31,7 @@ describe( entityNameinLeftSidebar: "Tab2", action: "Rename", }); - agHelper.TypeText(locators._entityNameEditing("Tab2"), tabname); + agHelper.TypeText(locators._entityNameEditing, tabname, { clear: true }); agHelper.Sleep(2000); entityExplorer.ValidateDuplicateMessageToolTip(tabname); cy.get(explorer.editEntity) diff --git a/app/client/cypress/e2e/Regression/ClientSide/Git/GitSync/GitSyncGitBugs_spec.js b/app/client/cypress/e2e/Regression/ClientSide/Git/GitSync/GitSyncGitBugs_spec.js index 2b50b44e9d98..5eebeaba3f48 100644 --- a/app/client/cypress/e2e/Regression/ClientSide/Git/GitSync/GitSyncGitBugs_spec.js +++ b/app/client/cypress/e2e/Regression/ClientSide/Git/GitSync/GitSyncGitBugs_spec.js @@ -158,7 +158,7 @@ describe( gitSync.CreateGitBranch(tempBranch, true); cy.wait(2000); - EditorNavigation.SelectEntityByName("Page1", EntityType.Page); + PageList.VerifyIsCurrentPage("Page1"); PageLeftPane.switchSegment(PagePaneSegment.JS); // verify jsObject is not duplicated PageLeftPane.assertPresence(jsObject); @@ -232,8 +232,8 @@ describe( cy.xpath("//input[@class='bp3-input' and @value='Success']").should( "be.visible", ); - // switch to Page1 copy and verify jsObject data binding - EditorNavigation.SelectEntityByName("Page1", EntityType.Page); + // switch to Page1 and verify jsObject data binding + PageList.VerifyIsCurrentPage("Page1"); PageLeftPane.switchSegment(PagePaneSegment.JS); // verify jsObject is not duplicated PageLeftPane.assertPresence(jsObject); diff --git a/app/client/cypress/e2e/Regression/ClientSide/Git/GitSync/GitSyncedApps_spec.js b/app/client/cypress/e2e/Regression/ClientSide/Git/GitSync/GitSyncedApps_spec.js index 8b08261e05b4..b407f88e9524 100644 --- a/app/client/cypress/e2e/Regression/ClientSide/Git/GitSync/GitSyncedApps_spec.js +++ b/app/client/cypress/e2e/Regression/ClientSide/Git/GitSync/GitSyncedApps_spec.js @@ -119,7 +119,7 @@ describe( entityExplorer.RenameEntityFromExplorer( "Page1", pageName, - false, + true, EntityItems.Page, ); PageList.ClonePage(pageName); diff --git a/app/client/cypress/e2e/Regression/ClientSide/Git/GitSync/SwitchBranches_spec.js b/app/client/cypress/e2e/Regression/ClientSide/Git/GitSync/SwitchBranches_spec.js index e935bf114258..bf8caae3980f 100644 --- a/app/client/cypress/e2e/Regression/ClientSide/Git/GitSync/SwitchBranches_spec.js +++ b/app/client/cypress/e2e/Regression/ClientSide/Git/GitSync/SwitchBranches_spec.js @@ -83,7 +83,7 @@ describe( entityExplorer.RenameEntityFromExplorer( "Page2", "ParentPage1", - false, + true, EntityItems.Page, ); dataSources.NavigateToDSCreateNew(); @@ -101,7 +101,7 @@ describe( entityExplorer.RenameEntityFromExplorer( "Page2", "ChildPage1", - false, + true, EntityItems.Page, ); dataSources.NavigateToDSCreateNew(); @@ -132,7 +132,7 @@ describe( entityExplorer.RenameEntityFromExplorer( "ParentPage1", "ParentPageRenamed", - false, + true, EntityItems.Page, ); agHelper.RemoveUIElement( diff --git a/app/client/cypress/e2e/Regression/ClientSide/IDE/Canvas_Context_Bug_Fixes.js b/app/client/cypress/e2e/Regression/ClientSide/IDE/Canvas_Context_Bug_Fixes.js index 341a83185c6f..0ccca4a5700c 100644 --- a/app/client/cypress/e2e/Regression/ClientSide/IDE/Canvas_Context_Bug_Fixes.js +++ b/app/client/cypress/e2e/Regression/ClientSide/IDE/Canvas_Context_Bug_Fixes.js @@ -25,6 +25,6 @@ describe("Canvas context Property Pane", { tags: ["@tag.IDE"] }, function () { cy.get(".t--widget-imagewidget").eq(0).click(); //check if the entities are expanded - cy.get(`[data-guided-tour-id="explorer-entity-Image1"]`).should("exist"); + cy.get(`[data-testid="t--entity-item-Image1"]`).should("exist"); }); }); diff --git a/app/client/cypress/e2e/Regression/ClientSide/IDE/Command_Click_Navigation_spec.js b/app/client/cypress/e2e/Regression/ClientSide/IDE/Command_Click_Navigation_spec.js index f2300cc4b0c0..6907a545452b 100644 --- a/app/client/cypress/e2e/Regression/ClientSide/IDE/Command_Click_Navigation_spec.js +++ b/app/client/cypress/e2e/Regression/ClientSide/IDE/Command_Click_Navigation_spec.js @@ -155,9 +155,14 @@ describe( agHelper.Sleep(); // Assert context switching works when going back to canvas - EditorNavigation.SelectEntityByName("Page1", EntityType.Page); + cy.get(`div.t--entity-item[data-selected='true']`).should( + "have.length", + 1, + ); - cy.get(`div[data-testid='t--selected']`).should("have.length", 1); + EditorNavigation.SelectEntityByName("Text1", EntityType.Widget, {}, [ + "Container1", + ]); cy.get(".t--property-pane-title").should("contain", "Text1"); // Go back to JS editor diff --git a/app/client/cypress/e2e/Regression/ClientSide/JSLibrary/Library_spec.ts b/app/client/cypress/e2e/Regression/ClientSide/JSLibrary/Library_spec.ts index 16d7edefd6a3..8a4aea90d91f 100644 --- a/app/client/cypress/e2e/Regression/ClientSide/JSLibrary/Library_spec.ts +++ b/app/client/cypress/e2e/Regression/ClientSide/JSLibrary/Library_spec.ts @@ -9,9 +9,10 @@ import { installer, draggableWidgets, } from "../../../../support/Objects/ObjectsCore"; -import { +import EditorNavigation, { AppSidebar, AppSidebarButton, + EntityType, PageLeftPane, PagePaneSegment, } from "../../../../support/Pages/EditorNavigation"; @@ -32,6 +33,7 @@ describe( AppSidebar.navigate(AppSidebarButton.Editor); entityExplorer.DragDropWidgetNVerify(draggableWidgets.TABLE, 200, 200); PageLeftPane.switchSegment(PagePaneSegment.UI); + EditorNavigation.SelectEntityByName("Table1", EntityType.Widget); entityExplorer.RenameEntityFromExplorer("Table1", "jsonwebtoken"); AppSidebar.navigate(AppSidebarButton.Libraries); installer.OpenInstaller(); diff --git a/app/client/cypress/e2e/Regression/ClientSide/JSObject/JSObject_ForkApp_spec.ts b/app/client/cypress/e2e/Regression/ClientSide/JSObject/JSObject_ForkApp_spec.ts index ea2d5aa1d042..c806663383e2 100644 --- a/app/client/cypress/e2e/Regression/ClientSide/JSObject/JSObject_ForkApp_spec.ts +++ b/app/client/cypress/e2e/Regression/ClientSide/JSObject/JSObject_ForkApp_spec.ts @@ -35,12 +35,20 @@ describe("Fork application with Jsobjects", {}, function () { for (let i = 1; i <= 11; i++) { agHelper.GetNClick(locators._entityTestId(`JS${i}`)); agHelper.FailIfErrorToast(""); - agHelper.AssertClassExists(locators._entityTestId(`JS${i}`), "active"); + agHelper.AssertAttribute( + locators._entityTestId(`JS${i}`), + "data-selected", + "true", + ); } for (let i = 12; i <= 17; i++) { agHelper.GetNClick(locators._entityTestId(`J${i}`)); agHelper.FailIfErrorToast(""); - agHelper.AssertClassExists(locators._entityTestId(`J${i}`), "active"); + agHelper.AssertAttribute( + locators._entityTestId(`J${i}`), + "data-selected", + "true", + ); } jsEditor.CreateJSObject('"MiddleName": "Test",\n', { @@ -51,9 +59,17 @@ describe("Fork application with Jsobjects", {}, function () { lineNumber: 5, }); agHelper.GetNClick(locators._entityTestId("J16")); - agHelper.AssertClassExists(locators._entityTestId("J16"), "active"); + agHelper.AssertAttribute( + locators._entityTestId("J16"), + "data-selected", + "true", + ); agHelper.GetNClick(locators._entityTestId("J17")); - agHelper.AssertClassExists(locators._entityTestId("J17"), "active"); + agHelper.AssertAttribute( + locators._entityTestId("J17"), + "data-selected", + "true", + ); agHelper.GetNAssertContains(".CodeMirror-line ", '"MiddleName": "Test"'); }); }); diff --git a/app/client/cypress/e2e/Regression/ClientSide/OtherUIFeatures/ApplicationURL_spec.js b/app/client/cypress/e2e/Regression/ClientSide/OtherUIFeatures/ApplicationURL_spec.js index d93525a20f76..27ffbfadafa9 100644 --- a/app/client/cypress/e2e/Regression/ClientSide/OtherUIFeatures/ApplicationURL_spec.js +++ b/app/client/cypress/e2e/Regression/ClientSide/OtherUIFeatures/ApplicationURL_spec.js @@ -45,7 +45,7 @@ describe("Slug URLs", { tags: ["@tag.AppUrl"] }, () => { entityExplorer.RenameEntityFromExplorer( "Page1", "Renamed", - false, + true, EntityItems.Page, ); assertHelper.AssertNetworkStatus("updatePage"); diff --git a/app/client/cypress/e2e/Regression/ClientSide/PartialImportExport/PageActions_spec.ts b/app/client/cypress/e2e/Regression/ClientSide/PartialImportExport/PageActions_spec.ts index 1943783c3eb7..c7b0217dd76b 100644 --- a/app/client/cypress/e2e/Regression/ClientSide/PartialImportExport/PageActions_spec.ts +++ b/app/client/cypress/e2e/Regression/ClientSide/PartialImportExport/PageActions_spec.ts @@ -13,26 +13,27 @@ import { propPane, } from "../../../../support/Objects/ObjectsCore"; import PageList from "../../../../support/Pages/PageList"; +import { EntityItems } from "../../../../support/Pages/AssertHelper"; describe("Check Page Actions Menu", {}, function () { it("1. Verify Page Actions when a page is selected", function () { homePage.RenameApplication("PageActions"); PageList.AddNewPage("New blank page"); entityExplorer.DragDropWidgetNVerify(draggableWidgets.TEXT, 500, 100); - PageList.ShowList(); - agHelper.GetNClick(entityExplorer._contextMenu("Page2"), 0, true); - agHelper.GetNClick(locators._contextMenuItem("Rename")); - agHelper.TypeText(propPane._placeholderName, `NewPage{enter}`, { - parseSpecialCharSeq: true, - }); + entityExplorer.RenameEntityFromExplorer( + "Page2", + "NewPage", + true, + EntityItems.Page, + ); PageList.ClonePage("NewPage"); PageList.HidePage("NewPage Copy"); PageList.ShowList(); agHelper.AssertAttribute( locators._entityTestId("NewPage Copy"), - "disabled", - "disabled", + "data-disabled", + "true", ); PageList.DeletePage("NewPage Copy"); PageList.assertAbsence("NewPage Copy"); @@ -79,12 +80,12 @@ describe("Check Page Actions Menu", {}, function () { it("2. Verify Page Actions when a page is not selected", function () { EditorNavigation.NavigateToPage("Page1", true); - PageList.ShowList(); - agHelper.GetNClick(entityExplorer._contextMenu("NewPage"), 0, true); - agHelper.GetNClick(locators._contextMenuItem("Rename")); - agHelper.TypeText(propPane._placeholderName, `Page2{enter}`, { - parseSpecialCharSeq: true, - }); + entityExplorer.RenameEntityFromExplorer( + "NewPage", + "Page2", + true, + EntityItems.Page, + ); PageList.ClonePage("Page2"); EditorNavigation.NavigateToPage("Page1", true); @@ -92,8 +93,8 @@ describe("Check Page Actions Menu", {}, function () { PageList.ShowList(); agHelper.AssertAttribute( locators._entityTestId("Page2 Copy"), - "disabled", - "disabled", + "data-disabled", + "true", ); PageList.DeletePage("Page2 Copy"); PageList.assertAbsence("Page2 Copy"); @@ -102,19 +103,20 @@ describe("Check Page Actions Menu", {}, function () { it("3. Verify Page Actions when a home page is selected", function () { entityExplorer.DragDropWidgetNVerify(draggableWidgets.TEXT, 500, 100); PageList.ShowList(); - agHelper.GetNClick(entityExplorer._contextMenu("Page1"), 0, true); - agHelper.GetNClick(locators._contextMenuItem("Rename")); - agHelper.TypeText(propPane._placeholderName, `HomePage{enter}`, { - parseSpecialCharSeq: true, - }); + entityExplorer.RenameEntityFromExplorer( + "Page1", + "HomePage", + true, + EntityItems.Page, + ); PageList.ClonePage("HomePage"); PageList.HidePage("HomePage Copy"); PageList.ShowList(); agHelper.AssertAttribute( locators._entityTestId("HomePage Copy"), - "disabled", - "disabled", + "data-disabled", + "true", ); PageList.DeletePage("HomePage Copy"); PageList.assertAbsence("HomePage Copy"); diff --git a/app/client/cypress/e2e/Regression/ClientSide/PartialImportExport/PartialImportRegularApp.ts b/app/client/cypress/e2e/Regression/ClientSide/PartialImportExport/PartialImportRegularApp.ts index 71edae318bd7..037ea3fdea8c 100644 --- a/app/client/cypress/e2e/Regression/ClientSide/PartialImportExport/PartialImportRegularApp.ts +++ b/app/client/cypress/e2e/Regression/ClientSide/PartialImportExport/PartialImportRegularApp.ts @@ -25,7 +25,7 @@ describe( entityExplorer.RenameEntityFromExplorer( "Page1", "Home", - false, + true, entityItems.Page, ); }); diff --git a/app/client/cypress/e2e/Regression/ClientSide/Refactoring/Refactoring_spec.ts b/app/client/cypress/e2e/Regression/ClientSide/Refactoring/Refactoring_spec.ts index 993d7649a4f1..2561188885ba 100644 --- a/app/client/cypress/e2e/Regression/ClientSide/Refactoring/Refactoring_spec.ts +++ b/app/client/cypress/e2e/Regression/ClientSide/Refactoring/Refactoring_spec.ts @@ -82,15 +82,30 @@ describe( refactorInput.inputWidget.newName, ); PageLeftPane.switchSegment(PagePaneSegment.Queries); + + EditorNavigation.SelectEntityByName( + refactorInput.query.oldName, + EntityType.Query, + ); entityExplorer.RenameEntityFromExplorer( refactorInput.query.oldName, refactorInput.query.newName, ); + + EditorNavigation.SelectEntityByName( + refactorInput.api.oldName, + EntityType.Api, + ); entityExplorer.RenameEntityFromExplorer( refactorInput.api.oldName, refactorInput.api.newName, ); + PageLeftPane.switchSegment(PagePaneSegment.JS); + EditorNavigation.SelectEntityByName( + refactorInput.jsObject.oldName, + EntityType.JSObject, + ); entityExplorer.RenameEntityFromExplorer( refactorInput.jsObject.oldName, refactorInput.jsObject.newName, diff --git a/app/client/cypress/e2e/Regression/ClientSide/SetProperty/SetOptions_Spec.ts b/app/client/cypress/e2e/Regression/ClientSide/SetProperty/SetOptions_Spec.ts index e2760744b5e1..c4e6051f9523 100644 --- a/app/client/cypress/e2e/Regression/ClientSide/SetProperty/SetOptions_Spec.ts +++ b/app/client/cypress/e2e/Regression/ClientSide/SetProperty/SetOptions_Spec.ts @@ -209,7 +209,7 @@ describe( it("3. Update 'setOptions' property - during onPage load", () => { EditorNavigation.SelectEntityByName("JSObject1", EntityType.JSObject); - jsEditor.EnableDisableAsyncFuncSettings("myFun1", true, false); //for on page load execution + jsEditor.EnableDisableAsyncFuncSettings("myFun1", true); //for on page load execution deployMode.DeployApp(); agHelper .GetText( @@ -268,7 +268,7 @@ describe( ])}, () => {showAlert('unable to run API')}); } }`); - jsEditor.EnableDisableAsyncFuncSettings("myFunc1", true, false); //for on page load execution, since sync function is updated to async + jsEditor.EnableDisableAsyncFuncSettings("myFunc1", true); //for on page load execution, since sync function is updated to async deployMode.DeployApp(); agHelper.WaitForCondition( agHelper @@ -313,7 +313,7 @@ describe( Select3.setOptions(Select1.options.concat(Select2.options)); } }`); - jsEditor.EnableDisableAsyncFuncSettings("myFunc1", true, false); //for on page load execution, since sync function is updated to async + jsEditor.EnableDisableAsyncFuncSettings("myFunc1", true); //for on page load execution, since sync function is updated to async EditorNavigation.SelectEntityByName("Input1", EntityType.Widget); propPane.UpdatePropertyFieldValue("Default value", "{{Select3.options}}"); deployMode.DeployApp(); @@ -355,7 +355,7 @@ describe( setTimeout(() => {Select1.setOptions(localValue)}, 1000); } }`); - jsEditor.EnableDisableAsyncFuncSettings("myFun1", false, false); //for on page load execution + jsEditor.EnableDisableAsyncFuncSettings("myFun1", false); //for on page load execution deployMode.DeployApp(); agHelper .GetText( diff --git a/app/client/cypress/e2e/Regression/ClientSide/SetProperty/WidgetPropertySetters2_spec.ts b/app/client/cypress/e2e/Regression/ClientSide/SetProperty/WidgetPropertySetters2_spec.ts index a89504d1794d..46697dee2b28 100644 --- a/app/client/cypress/e2e/Regression/ClientSide/SetProperty/WidgetPropertySetters2_spec.ts +++ b/app/client/cypress/e2e/Regression/ClientSide/SetProperty/WidgetPropertySetters2_spec.ts @@ -14,6 +14,7 @@ import EditorNavigation, { PageLeftPane, PagePaneSegment, } from "../../../../support/Pages/EditorNavigation"; +import PageList from "../../../../support/Pages/PageList"; describe( "Widget Property Setters - Part II - Tc #2409", @@ -135,7 +136,7 @@ describe( false, ); jsEditor.RunJSObj(); - EditorNavigation.SelectEntityByName("Page1", EntityType.Page); + PageList.VerifyIsCurrentPage("Page1"); PageLeftPane.switchSegment(PagePaneSegment.UI); agHelper .GetText( @@ -176,7 +177,7 @@ describe( }`, false, ); - jsEditor.EnableDisableAsyncFuncSettings("myFun1", true, false); + jsEditor.EnableDisableAsyncFuncSettings("myFun1", true); deployMode.DeployApp(locators._widgetInDeployed(draggableWidgets.BUTTON)); //Asserting before setTimeout JS function execution, button is visible agHelper.Sleep(2000); //waiting for settimeout to execute agHelper.AssertElementAbsence( @@ -235,7 +236,7 @@ describe( }`, false, ); - jsEditor.EnableDisableAsyncFuncSettings("myFun1", false, false); + jsEditor.EnableDisableAsyncFuncSettings("myFun1", false); deployMode.DeployApp(); agHelper.AssertElementVisibility( locators._widgetInDeployed(draggableWidgets.INPUT_V2), //Asserting before setTimeout JS function execution, Input is visible diff --git a/app/client/cypress/e2e/Regression/ClientSide/Widgets/Dropdown/Dropdown_onOptionChange_spec.js b/app/client/cypress/e2e/Regression/ClientSide/Widgets/Dropdown/Dropdown_onOptionChange_spec.js index f6c2128c334a..453c616a6998 100644 --- a/app/client/cypress/e2e/Regression/ClientSide/Widgets/Dropdown/Dropdown_onOptionChange_spec.js +++ b/app/client/cypress/e2e/Regression/ClientSide/Widgets/Dropdown/Dropdown_onOptionChange_spec.js @@ -94,7 +94,6 @@ describe( 'SELECT * FROM public."country" LIMIT 10;', ); // Going to HomePage where the button widget is located and opeing it's property pane. - EditorNavigation.SelectEntityByName("Page1", EntityType.Page); PageLeftPane.switchSegment(PagePaneSegment.UI); cy.openPropertyPane("selectwidget"); cy.reload(); diff --git a/app/client/cypress/e2e/Regression/ServerSide/JsFunctionExecution/SetTimeout_spec.ts b/app/client/cypress/e2e/Regression/ServerSide/JsFunctionExecution/SetTimeout_spec.ts index 59fb56693b34..08c72ab99a3d 100644 --- a/app/client/cypress/e2e/Regression/ServerSide/JsFunctionExecution/SetTimeout_spec.ts +++ b/app/client/cypress/e2e/Regression/ServerSide/JsFunctionExecution/SetTimeout_spec.ts @@ -227,7 +227,7 @@ describe( prettify: true, }, ); - jsEditor.EnableDisableAsyncFuncSettings("myFun1", true, false); + jsEditor.EnableDisableAsyncFuncSettings("myFun1", true); deployMode.DeployApp(); agHelper.Sleep(1000); //DeployApp already waiting 2000ms hence reducing it here to equate to 3000 timeout agHelper.AssertContains("Success!"); diff --git a/app/client/cypress/fixtures/chartUpdatedDsl.json b/app/client/cypress/fixtures/chartUpdatedDsl.json index 1fb7e865c43f..d78064c37f3e 100644 --- a/app/client/cypress/fixtures/chartUpdatedDsl.json +++ b/app/client/cypress/fixtures/chartUpdatedDsl.json @@ -37,6 +37,7 @@ "parentColumnSpace": 75.25, "dynamicBindingPathList": [], "leftColumn": 0, + "parentId": "0", "children": [ { "backgroundColor": "transparent", @@ -57,6 +58,7 @@ "isLoading": false, "parentColumnSpace": 1, "leftColumn": 0, + "parentId": "mxbaasg65u", "dynamicBindingPathList": [], "children": [] } @@ -80,6 +82,7 @@ "parentColumnSpace": 75.25, "dynamicBindingPathList": [], "leftColumn": 0, + "parentId": "0", "children": [ { "backgroundColor": "transparent", @@ -101,6 +104,7 @@ "parentColumnSpace": 1, "leftColumn": 0, "dynamicBindingPathList": [], + "parentId": "i331vll2mg", "children": [ { "widgetName": "Test", @@ -152,6 +156,7 @@ "parentColumnSpace": 75.25, "dynamicBindingPathList": [], "leftColumn": 32, + "parentId": "0", "children": [ { "backgroundColor": "transparent", @@ -173,7 +178,8 @@ "parentColumnSpace": 1, "leftColumn": 0, "dynamicBindingPathList": [], - "children": [] + "children": [], + "parentId": "qznzsquf70" } ] } diff --git a/app/client/cypress/fixtures/newFormDsl.json b/app/client/cypress/fixtures/newFormDsl.json index a12ae1171e45..f3a1cf7043cc 100644 --- a/app/client/cypress/fixtures/newFormDsl.json +++ b/app/client/cypress/fixtures/newFormDsl.json @@ -35,6 +35,7 @@ "bottomRow": 20, "snapColumns": 16, "orientation": "VERTICAL", + "parentId": "0", "children": [ { "backgroundColor": "transparent", @@ -51,6 +52,7 @@ "bottomRow": 532, "snapColumns": 16, "orientation": "VERTICAL", + "parentId": "jaftzrmtin", "children": [ { "widgetName": "Text1", diff --git a/app/client/cypress/locators/CMSApplocators.js b/app/client/cypress/locators/CMSApplocators.js index f84c813e63ea..1ad3b7439ff9 100644 --- a/app/client/cypress/locators/CMSApplocators.js +++ b/app/client/cypress/locators/CMSApplocators.js @@ -12,7 +12,7 @@ export default { confirmButton: "span:contains('Confirm')", closeButton: "span:contains('Close')", datasourcesbutton: "//div[text()='Datasources']", - postApi: "//div[text()='send_mail']", + postApi: "[data-testid='t--ide-tab-send_mail']", deleteButton: "//span[text()='Delete Proposal']", deleteTaskText: "//span[text()='Delete this task']", }; diff --git a/app/client/cypress/locators/apiWidgetslocator.json b/app/client/cypress/locators/apiWidgetslocator.json index e410f4a25293..2004e7f89a48 100644 --- a/app/client/cypress/locators/apiWidgetslocator.json +++ b/app/client/cypress/locators/apiWidgetslocator.json @@ -4,7 +4,7 @@ "searchApi": ".t--sidebar input[type=text]", "createapi": ".t--createBlankApiCard", "createAuthApiDatasource": ".t--createAuthApiDatasource", - "popover": "//button[contains(@class, 'entity-context-menu')]", + "popover": "button[data-testid='t--entity-context-menu-trigger']", "moveTo": ".single-select >div:contains('Move to')", "copyTo": ".single-select >div:contains('Copy to page')", "home": ".single-select >div:contains('Page1')", diff --git a/app/client/cypress/locators/commonlocators.json b/app/client/cypress/locators/commonlocators.json index e6750c2d4e93..fbe4305f8aca 100644 --- a/app/client/cypress/locators/commonlocators.json +++ b/app/client/cypress/locators/commonlocators.json @@ -183,7 +183,6 @@ "filepickerv2": ".t--draggable-filepickerwidgetv2", "dashboardItemName": ".uppy-Dashboard-Item-name", "mapChartShowLabels": ".t--property-control-showlabels input", - "widgetSection": ".t--entity.widgets > .t--entity-item > span.t--entity-collapse-toggle", "changeThemeBtn": ".t--change-theme-btn", "editThemeBtn": ".t--edit-theme-btn", "themeCard": ".t--theme-card", @@ -248,4 +247,4 @@ "downloadFileType": "button[class*='t--open-dropdown-Select-file-type'] > span:first-of-type", "listToggle": "[data-testid='t--list-toggle']", "showBindingsMenu": "//*[@id='entity-properties-container']" -} \ No newline at end of file +} diff --git a/app/client/cypress/support/ApiCommands.js b/app/client/cypress/support/ApiCommands.js index 6136d917e789..94469328d70d 100644 --- a/app/client/cypress/support/ApiCommands.js +++ b/app/client/cypress/support/ApiCommands.js @@ -145,12 +145,14 @@ Cypress.Commands.add("CreateApiAndValidateUniqueEntityName", (apiname) => { Cypress.Commands.add("validateMessage", (value) => { cy.get(".rc-tooltip-inner").should(($x) => { - expect($x).contain(value.concat(" is already being used.")); + expect($x).contain( + value.concat(" is already being used or is a restricted keyword."), + ); }); }); Cypress.Commands.add("DeleteWidgetFromSideBar", () => { - cy.xpath(apiwidget.popover).last().click({ force: true }); + cy.get(apiwidget.popover).last().click({ force: true }); cy.get(apiwidget.delete).click({ force: true }); cy.wait("@updateLayout").should( "have.nested.property", diff --git a/app/client/cypress/support/Objects/CommonLocators.ts b/app/client/cypress/support/Objects/CommonLocators.ts index f10c896d3b45..ac2eadef9447 100644 --- a/app/client/cypress/support/Objects/CommonLocators.ts +++ b/app/client/cypress/support/Objects/CommonLocators.ts @@ -98,10 +98,7 @@ export class CommonLocators { "//div[text()='" + entityNameinLeftSidebar + "']/ancestor::div[contains(@class, 't--entity-item')]/following-sibling::div//div[contains(@class, 't--entity-property')]//code"; - _entityNameEditing = (entityNameinLeftSidebar: string) => - "//span[text()='" + - entityNameinLeftSidebar + - "']/parent::div[contains(@class, 't--entity-name editing')]/input"; + _entityNameEditing = ".t--entity-name.editing input"; _jsToggle = (controlToToggle: string) => `.t--property-control-${controlToToggle} .t--js-toggle, [data-guided-tour-iid='${controlToToggle}']`; _buttonByText = (btnVisibleText: string) => @@ -334,9 +331,14 @@ export class CommonLocators { _exitFullScreen = ".application-demo-new-dashboard-control-exit-fullscreen"; _menuItem = ".bp3-menu-item"; _slashCommandHintText = ".slash-command-hint-text"; - _selectionItem = ".rc-select-selection-item"; errorPageTitle = ".t--error-page-title"; errorPageDescription = ".t--error-page-description"; + _moduleInstanceEntity = (module: string) => + `[data-testid=t--entity-item-${module}1]`; + _codeEditor = "[data-testid=code-editor-target]"; + _selectionItem = ".rc-select-selection-item"; + _moduleInputEntity = (inputName: string) => + `[data-testid=t--module-instance-input-field-wrapper-${inputName}]`; _selectClearButton_testId = "selectbutton.btn.cancel"; _selectClearButton_dataTestId = `[data-testid="${this._selectClearButton_testId}"]`; _saveDatasource = `[data-testid='t--store-as-datasource']`; @@ -347,6 +349,7 @@ export class CommonLocators { _showBoundary = ".show-boundary"; _entityItem = "[data-testid='t--entity-item-Api1']"; _rowData = "[data-colindex='0'][data-rowindex='0']"; + _visualNonIdeaState = ".bp3-non-ideal-state"; _editorTab = ".editor-tab"; _entityTestId = (entity: string) => `[data-testid="t--entity-item-${entity}"]`; diff --git a/app/client/cypress/support/Objects/FeatureFlags.ts b/app/client/cypress/support/Objects/FeatureFlags.ts index 31d8ebedac2e..8301ff7da0e1 100644 --- a/app/client/cypress/support/Objects/FeatureFlags.ts +++ b/app/client/cypress/support/Objects/FeatureFlags.ts @@ -4,6 +4,7 @@ import { ObjectsRegistry } from "./Registry"; const defaultFlags = { rollout_remove_feature_walkthrough_enabled: false, // remove this flag from here when it's removed from code release_git_modularisation_enabled: true, + release_ads_entity_item_enabled: true, }; export const featureFlagIntercept = ( diff --git a/app/client/cypress/support/Pages/AggregateHelper.ts b/app/client/cypress/support/Pages/AggregateHelper.ts index fa74ea5a239f..6ad77693d172 100644 --- a/app/client/cypress/support/Pages/AggregateHelper.ts +++ b/app/client/cypress/support/Pages/AggregateHelper.ts @@ -986,12 +986,14 @@ export class AggregateHelper { parseSpecialCharSeq: boolean; shouldFocus: boolean; delay: number; + clear: boolean; }> = 0, ) { let index: number; let shouldFocus = true; let parseSpecialCharSeq = false; let delay = 10; + let clear = false; if (typeof indexOrOptions === "number") { index = indexOrOptions; @@ -1003,6 +1005,7 @@ export class AggregateHelper { indexOrOptions.shouldFocus !== undefined ? indexOrOptions.shouldFocus : true; + clear = indexOrOptions.clear || false; } const element = this.GetElement(selector).eq(index); @@ -1013,6 +1016,14 @@ export class AggregateHelper { if (value === "") return element; + if (clear) { + return element.wait(100).clear().type(value, { + parseSpecialCharSequences: parseSpecialCharSeq, + delay: delay, + force: true, + }); + } + return element.wait(100).type(value, { parseSpecialCharSequences: parseSpecialCharSeq, delay: delay, diff --git a/app/client/cypress/support/Pages/EditorNavigation.ts b/app/client/cypress/support/Pages/EditorNavigation.ts index 38fc48ad3ffe..2ffbd327515c 100644 --- a/app/client/cypress/support/Pages/EditorNavigation.ts +++ b/app/client/cypress/support/Pages/EditorNavigation.ts @@ -29,12 +29,12 @@ export enum EditorViewMode { } const pagePaneListItemSelector = (name: string) => - "//div[contains(@class, 't--entity-name')][text()='" + name + "']"; + `//span[contains(@class, 't--entity-name')][text()='${name}']`; export const PageLeftPane = new LeftPane( pagePaneListItemSelector, ".ide-editor-left-pane", - ".ide-editor-left-pane__content .active.t--entity-item", + ".ide-editor-left-pane__content .t--entity-item[data-selected='true']", Object.values(PagePaneSegment), ); diff --git a/app/client/cypress/support/Pages/EntityExplorer.ts b/app/client/cypress/support/Pages/EntityExplorer.ts index 5166d520622e..11fa60aacea1 100644 --- a/app/client/cypress/support/Pages/EntityExplorer.ts +++ b/app/client/cypress/support/Pages/EntityExplorer.ts @@ -52,13 +52,9 @@ export class EntityExplorer { private assertHelper = ObjectsRegistry.AssertHelper; public _contextMenu = (entityNameinLeftSidebar: string) => - "//div[text()='" + + "//span[text()='" + entityNameinLeftSidebar + - "']/ancestor::div[1]/following-sibling::div//button[contains(@class, 'entity-context-menu')]"; - _entityNameInExplorer = (entityNameinLeftSidebar: string) => - "//div[contains(@class, 't--entity-explorer')]//div[contains(@class, 't--entity-name')][text()='" + - entityNameinLeftSidebar + - "']"; + "']/parent::div/following-sibling::div//button"; private _visibleTextSpan = (spanText: string) => "//span[text()='" + spanText + "']"; @@ -72,6 +68,7 @@ export class EntityExplorer { _widgetTagSuggestedWidgets = ".widget-tag-collapsible-suggested"; _widgetTagBuildingBlocks = ".widget-tag-collapsible-building-blocks"; _widgetSeeMoreButton = "[data-testid='t--explorer-ui-entity-tag-see-more']"; + _entityAddButton = ".t--entity-add-btn"; _entityName = ".t--entity-name"; public ActionContextMenuByEntityName({ @@ -103,7 +100,7 @@ export class EntityExplorer { toastToValidate: toastToValidate, }); } - if (entityType === EntityItems.Page) { + if (entityType === EntityItems.Page && action !== "Rename") { PageList.HideList(); } } @@ -121,28 +118,43 @@ export class EntityExplorer { } public ValidateDuplicateMessageToolTip(tooltipText: string) { - this.agHelper.AssertTooltip(tooltipText.concat(" is already being used.")); + this.agHelper.AssertTooltip( + tooltipText.concat(" is already being used or is a restricted keyword."), + ); + } + + private deleteQueryUnderDatasource(dsName: string) { + return cy.get("body").then(($body) => { + if ($body.find(`span:contains('${dsName}')`).length === 0) return; + + return this.agHelper + .GetElement(this._visibleTextSpan(dsName)) + .siblings() + .children() + .then(($items) => { + if ($items.length > 0) { + cy.wrap($items[0]) + .find("button[data-testid='t--entity-context-menu-trigger']") + .click({ + force: true, + }); + cy.xpath(this.locator._contextMenuItem("Delete")).click({ + force: true, + }); + this.agHelper.GetNClick( + this.locator._contextMenuItem("Are you sure?"), + ); + cy.wait(500); + this.deleteQueryUnderDatasource(dsName); + } + }); + }); } public DeleteAllQueriesForDB(dsName: string) { AppSidebar.navigate(AppSidebarButton.Editor); PageLeftPane.switchSegment(PagePaneSegment.Queries); - this.agHelper - .GetElement(this._visibleTextSpan(dsName)) - .parent() - .siblings() - .each(($el: any) => { - cy.wrap($el) - .find(".t--entity-name") - .invoke("text") - .then(($query) => { - this.ActionContextMenuByEntityName({ - entityNameinLeftSidebar: $query as string, - action: "Delete", - entityType: EntityItems.Query, - }); - }); - }); + this.deleteQueryUnderDatasource(dsName); } public SearchWidgetPane(widgetType: string) { @@ -266,17 +278,24 @@ export class EntityExplorer { entityType?: EntityItemsType, ) { AppSidebar.navigate(AppSidebarButton.Editor); - if (entityType === EntityItems.Page && !viaMenu) { - PageList.ShowList(); - } if (viaMenu) this.ActionContextMenuByEntityName({ entityNameinLeftSidebar: entityName, action: "Rename", entityType, }); - else cy.xpath(PageLeftPane.listItemSelector(entityName)).dblclick(); - cy.xpath(this.locator._entityNameEditing(entityName)) + else { + if (entityType === EntityItems.Page) { + PageList.ShowList(); + cy.get(this.locator._entityTestId(entityName)).click(); + PageList.ShowList(); + cy.get(this.locator._entityTestId(entityName)).dblclick(); + } else { + cy.get(this.locator._entityTestId(entityName)).dblclick(); + } + } + cy.get(this.locator._entityNameEditing) + .clear() .type(renameVal) .wait(500) .type("{enter}") diff --git a/app/client/cypress/support/Pages/IDE/LeftPane.ts b/app/client/cypress/support/Pages/IDE/LeftPane.ts index c2f5aec05ee4..1a0050ee923e 100644 --- a/app/client/cypress/support/Pages/IDE/LeftPane.ts +++ b/app/client/cypress/support/Pages/IDE/LeftPane.ts @@ -1,7 +1,5 @@ import { ObjectsRegistry } from "../../Objects/Registry"; -import { PagePaneSegment } from "../EditorNavigation"; import AddView from "./AddView"; -import FileTabs from "./FileTabs"; import ListView from "./ListView"; export class LeftPane { @@ -11,11 +9,10 @@ export class LeftPane { locators = { segment: (name: string) => "//span[text()='" + name + "']/ancestor::div", expandCollapseArrow: (name: string) => - "//div[text()='" + - name + - "']/ancestor::div/span[contains(@class, 't--entity-collapse-toggle')]", + `//span[contains(@class, 't--entity-name')][text()="${name}"]/ancestor::div//*[@data-testid="t--entity-collapse-toggle"]`, activeItemSelector: "", selector: "", + entityItem: (name: string) => `div[data-testid='t--entity-item-${name}']`, }; public listView: ListView; @@ -41,7 +38,7 @@ export class LeftPane { public assertPresence(name: string) { ObjectsRegistry.AggregateHelper.AssertElementLength( - this.listItemSelector(name), + this.locators.entityItem(name), 1, ); } @@ -79,10 +76,11 @@ export class LeftPane { this.locators.expandCollapseArrow(itemName), ); cy.xpath(this.locators.expandCollapseArrow(itemName)) - .invoke("attr", "id") + .invoke("attr", "data-icon") .then((state) => { const closed = state === "arrow-right-s-line"; const opened = state === "arrow-down-s-line"; + if ((expand && closed) || (!expand && opened)) { ObjectsRegistry.AggregateHelper.GetNClick( this.locators.expandCollapseArrow(itemName), @@ -90,6 +88,7 @@ export class LeftPane { } }); } + public selectedItem( exists?: "exist" | "not.exist" | "noVerify", ): Cypress.Chainable { diff --git a/app/client/cypress/support/Pages/IDE/ListView.ts b/app/client/cypress/support/Pages/IDE/ListView.ts index f9f4352af532..2a0bd1e989a2 100644 --- a/app/client/cypress/support/Pages/IDE/ListView.ts +++ b/app/client/cypress/support/Pages/IDE/ListView.ts @@ -3,7 +3,7 @@ import { ObjectsRegistry } from "../../Objects/Registry"; class ListView { public locators = { list: "[data-testid='t--ide-list']", - listItem: "[data-testid='t--ide-list-item']", + listItem: ".t--ide-list-item", addItem: "[data-testid='t--add-item']", }; diff --git a/app/client/cypress/support/Pages/JSEditor.ts b/app/client/cypress/support/Pages/JSEditor.ts index 88d268b23360..85bc32fcd3b7 100644 --- a/app/client/cypress/support/Pages/JSEditor.ts +++ b/app/client/cypress/support/Pages/JSEditor.ts @@ -254,9 +254,9 @@ export class JSEditor { entityNameinLeftSidebar: entityName, action: "Rename", }); - cy.xpath(this.locator._entityNameEditing(entityName)).type( - renameVal + "{enter}", - ); + cy.get(this.locator._entityNameEditing) + .clear() + .type(renameVal + "{enter}"); PageLeftPane.assertPresence(renameVal); } diff --git a/app/client/cypress/support/Pages/PageList.ts b/app/client/cypress/support/Pages/PageList.ts index 5d48942cf12f..39c953de3961 100644 --- a/app/client/cypress/support/Pages/PageList.ts +++ b/app/client/cypress/support/Pages/PageList.ts @@ -9,7 +9,7 @@ import { PAGE_ENTITY_NAME } from "../../../src/ce/constants/messages"; class PageList { private locators = { pageListItem: (pageName: string) => - `.t--entity.page:contains('${pageName}')`, + `.t--entity-item.page:contains('${pageName}')`, newButton: ".pages .t--entity-add-btn", newPageOption: ".ads-v2-menu__menu-item-children", switcher: `.t--pages-switcher`, @@ -49,7 +49,7 @@ class PageList { public SelectedPageItem(): Cypress.Chainable { this.ShowList(); - return cy.get(".t--entity.page > .active"); + return cy.get(".t--entity-item.page > .active"); this.HideList(); } diff --git a/app/client/cypress/support/queryCommands.js b/app/client/cypress/support/queryCommands.js index 2faddda47a91..5419b61d50c9 100644 --- a/app/client/cypress/support/queryCommands.js +++ b/app/client/cypress/support/queryCommands.js @@ -57,14 +57,6 @@ Cypress.Commands.add("onlyQueryRun", () => { cy.get(".ads-v2-spinner").should("not.exist"); }); -Cypress.Commands.add("hoverAndClick", (entity) => { - cy.xpath( - "//div[text()='" + - entity + - "']/ancestor::div[1]/following-sibling::div//button[contains(@class, 'entity-context-menu')]", - ).click({ force: true }); -}); - Cypress.Commands.add("deleteQueryUsingContext", () => { cy.get(queryEditor.queryMoreAction).first().click(); cy.get(queryEditor.deleteUsingContext).click(); diff --git a/app/client/cypress/support/widgetCommands.js b/app/client/cypress/support/widgetCommands.js index 9e42a7b359af..c15c53767874 100644 --- a/app/client/cypress/support/widgetCommands.js +++ b/app/client/cypress/support/widgetCommands.js @@ -969,7 +969,7 @@ Cypress.Commands.add("Createpage", (pageName, navigateToCanvasPage = true) => { ee.RenameEntityFromExplorer( oldPageName, pageName, - false, + true, EntityItems.Page, ); } diff --git a/app/client/src/pages/AppIDE/components/AppPluginActionEditor/loader.tsx b/app/client/src/pages/AppIDE/components/AppPluginActionEditor/loader.tsx index 43e67b4980b0..0b615d3d6935 100644 --- a/app/client/src/pages/AppIDE/components/AppPluginActionEditor/loader.tsx +++ b/app/client/src/pages/AppIDE/components/AppPluginActionEditor/loader.tsx @@ -11,7 +11,7 @@ const LazyPluginActionEditor = lazy(async () => const AppPluginActionEditor = () => { return ( - <Suspense fallback={Skeleton}> + <Suspense fallback={<Skeleton />}> <LazyPluginActionEditor /> </Suspense> ); diff --git a/app/client/src/pages/AppIDE/components/JSAdd/loader.tsx b/app/client/src/pages/AppIDE/components/JSAdd/loader.tsx index 8c6769fe7271..e4449dba52a3 100644 --- a/app/client/src/pages/AppIDE/components/JSAdd/loader.tsx +++ b/app/client/src/pages/AppIDE/components/JSAdd/loader.tsx @@ -10,7 +10,7 @@ const LazyAddJS = lazy(async () => const AddJS = () => { return ( - <Suspense fallback={Skeleton}> + <Suspense fallback={<Skeleton />}> <LazyAddJS /> </Suspense> ); diff --git a/app/client/src/pages/AppIDE/components/JSEntityItem/JSEntityItem.tsx b/app/client/src/pages/AppIDE/components/JSEntityItem/JSEntityItem.tsx index a515c9779682..24a6599f25fd 100644 --- a/app/client/src/pages/AppIDE/components/JSEntityItem/JSEntityItem.tsx +++ b/app/client/src/pages/AppIDE/components/JSEntityItem/JSEntityItem.tsx @@ -44,7 +44,7 @@ export const JSEntityItem = ({ item }: { item: EntityItemProps }) => { } return ( - <EntityContextMenu> + <EntityContextMenu dataTestId="t--entity-context-menu-trigger"> <AppJSContextMenuItems jsAction={jsAction} /> </EntityContextMenu> ); diff --git a/app/client/src/pages/AppIDE/components/QueryAdd/loader.tsx b/app/client/src/pages/AppIDE/components/QueryAdd/loader.tsx index 2180702b13ac..abef6e53151c 100644 --- a/app/client/src/pages/AppIDE/components/QueryAdd/loader.tsx +++ b/app/client/src/pages/AppIDE/components/QueryAdd/loader.tsx @@ -10,7 +10,7 @@ const LazyAddQuery = lazy(async () => const QueryAdd = () => { return ( - <Suspense fallback={Skeleton}> + <Suspense fallback={<Skeleton />}> <LazyAddQuery /> </Suspense> ); diff --git a/app/client/src/pages/AppIDE/components/QueryEntityItem/QueryEntityItem.tsx b/app/client/src/pages/AppIDE/components/QueryEntityItem/QueryEntityItem.tsx index 2757aba2763e..3574a814f255 100644 --- a/app/client/src/pages/AppIDE/components/QueryEntityItem/QueryEntityItem.tsx +++ b/app/client/src/pages/AppIDE/components/QueryEntityItem/QueryEntityItem.tsx @@ -50,7 +50,10 @@ export const QueryEntityItem = ({ item }: { item: EntityItemProps }) => { const dispatch = useDispatch(); const contextMenu = useMemo( () => ( - <EntityContextMenu dataTestId="t--entity-context-menu-trigger"> + <EntityContextMenu + dataTestId="t--entity-context-menu-trigger" + key={action.id} + > <AppQueryContextMenuItems action={action} /> </EntityContextMenu> ), diff --git a/app/client/src/pages/AppIDE/components/QueryExplorer/QuerySegmentList.tsx b/app/client/src/pages/AppIDE/components/QueryExplorer/QuerySegmentList.tsx index bd8bc121ab12..cbb09871231a 100644 --- a/app/client/src/pages/AppIDE/components/QueryExplorer/QuerySegmentList.tsx +++ b/app/client/src/pages/AppIDE/components/QueryExplorer/QuerySegmentList.tsx @@ -89,7 +89,7 @@ export const ListQuery = () => { items: items, className: "", renderList: (item: EntityItem) => { - return <ActionEntityItem item={item} />; + return <ActionEntityItem item={item} key={item.key} />; }, }; })} diff --git a/app/client/src/pages/AppIDE/components/UIEntityListTree/WidgetContextMenu.tsx b/app/client/src/pages/AppIDE/components/UIEntityListTree/WidgetContextMenu.tsx index bde8eb4018f7..b1653eae0990 100644 --- a/app/client/src/pages/AppIDE/components/UIEntityListTree/WidgetContextMenu.tsx +++ b/app/client/src/pages/AppIDE/components/UIEntityListTree/WidgetContextMenu.tsx @@ -102,7 +102,7 @@ export const WidgetContextMenu = (props: { <Menu onOpenChange={toggleMenuOpen} open={isMenuOpen}> <MenuTrigger> <Button - data-testid="t--more-action-trigger" + data-testid="t--entity-context-menu-trigger" isIconButton kind="tertiary" startIcon="more-2-fill" diff --git a/app/client/src/pages/AppIDE/components/UIList/UIList.test.tsx b/app/client/src/pages/AppIDE/components/UIList/UIList.test.tsx index f08fa800d7e9..b3095bc6b26d 100644 --- a/app/client/src/pages/AppIDE/components/UIList/UIList.test.tsx +++ b/app/client/src/pages/AppIDE/components/UIList/UIList.test.tsx @@ -14,6 +14,7 @@ import * as widgetSelectionsActions from "actions/widgetSelectionActions"; import { SelectionRequestType } from "sagas/WidgetSelectUtils"; import { NavigationMethod } from "utils/history"; import ListWidgets from "./UIList"; +import { DEFAULT_FEATURE_FLAG_VALUE } from "ee/entities/FeatureFlag"; jest.useFakeTimers(); const pushState = jest.spyOn(window.history, "pushState"); @@ -51,6 +52,15 @@ jest .spyOn(explorerSelector, "getExplorerWidth") .mockImplementation(() => DEFAULT_ENTITY_EXPLORER_WIDTH); +jest.mock("ee/selectors/featureFlagsSelectors", () => ({ + __esModule: true, + ...jest.requireActual("ee/selectors/featureFlagsSelectors"), + selectFeatureFlags: () => ({ + ...DEFAULT_FEATURE_FLAG_VALUE, + release_ads_entity_item_enabled: true, + }), +})); + const setFocusSearchInput = jest.fn(); describe("Widget List in Explorer tests", () => { @@ -93,7 +103,7 @@ describe("Widget List in Explorer tests", () => { const widgetsTree: Element = await component.findByText( children[0].widgetName, { - selector: "div.t--entity-name", + selector: "span.t--entity-name", }, { timeout: 3000 }, ); @@ -128,6 +138,7 @@ describe("Widget List in Explorer tests", () => { const dsl: any = widgetCanvasFactory.build({ children, }); + const component = render( <MockPageDSL dsl={dsl}> <ListWidgets setFocusSearchInput={setFocusSearchInput} /> @@ -346,8 +357,8 @@ describe("Widget List in Explorer tests", () => { // TODO: Fix this the next time the file is edited // eslint-disable-next-line @typescript-eslint/no-explicit-any - const collapsible: any = component.container.querySelector( - `.t--entity-collapse-toggle[id="arrow-right-s-line"]`, + const collapsible: any = component.getByTestId( + `t--entity-collapse-toggle`, ); fireEvent.click(collapsible); diff --git a/app/client/src/pages/AppIDE/layouts/routers/JSEditor/JSRender.test.tsx b/app/client/src/pages/AppIDE/layouts/routers/JSEditor/JSRender.test.tsx index d83fdd7a162c..eacaa5e349b4 100644 --- a/app/client/src/pages/AppIDE/layouts/routers/JSEditor/JSRender.test.tsx +++ b/app/client/src/pages/AppIDE/layouts/routers/JSEditor/JSRender.test.tsx @@ -137,6 +137,9 @@ describe("IDE Render: JS", () => { { url: `/app/applicationSlug/pageSlug-${page.basePageId}/edit/jsObjects/${js1.baseId}`, initialState: state, + featureFlags: { + release_ads_entity_item_enabled: true, + }, }, ); @@ -153,8 +156,8 @@ describe("IDE Render: JS", () => { expect(getAllByText("JSObject1").length).toEqual(2); // Left pane active state expect( - getByTestId("t--entity-item-JSObject1").classList.contains("active"), - ).toBe(true); + getByTestId("t--entity-item-JSObject1").getAttribute("data-selected"), + ).toBe("true"); // Tabs active state expect( getByTestId("t--ide-tab-jsobject1").classList.contains("active"), diff --git a/app/client/src/pages/AppIDE/layouts/routers/QueryEditor/QueryRender.test.tsx b/app/client/src/pages/AppIDE/layouts/routers/QueryEditor/QueryRender.test.tsx index 9dd04b0a333c..cfc233e97035 100644 --- a/app/client/src/pages/AppIDE/layouts/routers/QueryEditor/QueryRender.test.tsx +++ b/app/client/src/pages/AppIDE/layouts/routers/QueryEditor/QueryRender.test.tsx @@ -158,6 +158,9 @@ describe("IDE URL rendering of Queries", () => { { url: `/app/applicationSlug/pageSlug-${page.basePageId}/edit/api/${anApi.baseId}`, initialState: state, + featureFlags: { + release_ads_entity_item_enabled: true, + }, }, ); @@ -174,8 +177,8 @@ describe("IDE URL rendering of Queries", () => { expect(getAllByText("Api1").length).toEqual(2); // Left pane active state expect( - getByTestId("t--entity-item-Api1").classList.contains("active"), - ).toBe(true); + getByTestId("t--entity-item-Api1").getAttribute("data-selected"), + ).toBe("true"); // Tabs active state expect(getByTestId("t--ide-tab-api1").classList.contains("active")).toBe( true, @@ -370,6 +373,9 @@ describe("IDE URL rendering of Queries", () => { url: `/app/applicationSlug/pageSlug-${page.basePageId}/edit/queries/${anQuery.baseId}`, sagasToRun: sagasToRunForTests, initialState: state, + featureFlags: { + release_ads_entity_item_enabled: true, + }, }, ); @@ -385,8 +391,8 @@ describe("IDE URL rendering of Queries", () => { expect(getAllByText("Query1").length).toBe(2); // Left pane active state expect( - getByTestId("t--entity-item-Query1").classList.contains("active"), - ).toBe(true); + getByTestId("t--entity-item-Query1").getAttribute("data-selected"), + ).toBe("true"); // Tabs active state expect( getByTestId("t--ide-tab-query1").classList.contains("active"), @@ -582,6 +588,9 @@ describe("IDE URL rendering of Queries", () => { url: `/app/applicationSlug/pageSlug-${page.basePageId}/edit/saas/google-sheets-plugin/api/${anQuery.baseId}`, sagasToRun: sagasToRunForTests, initialState: state, + featureFlags: { + release_ads_entity_item_enabled: true, + }, }, ); @@ -589,8 +598,8 @@ describe("IDE URL rendering of Queries", () => { expect(getAllByText("Sheets1").length).toBe(2); // Left pane active state expect( - getByTestId("t--entity-item-Sheets1").classList.contains("active"), - ).toBe(true); + getByTestId("t--entity-item-Sheets1").getAttribute("data-selected"), + ).toBe("true"); // Tabs active state expect( getByTestId("t--ide-tab-sheets1").classList.contains("active"), diff --git a/app/client/src/pages/Editor/Explorer/Entity/Name.tsx b/app/client/src/pages/Editor/Explorer/Entity/Name.tsx index c30f51dbbeab..dfe3f230d282 100644 --- a/app/client/src/pages/Editor/Explorer/Entity/Name.tsx +++ b/app/client/src/pages/Editor/Explorer/Entity/Name.tsx @@ -26,7 +26,7 @@ const Container = styled.div` overflow: hidden; `; -const Wrapper = styled.div` +const Wrapper = styled.span` overflow: hidden; text-overflow: ellipsis; white-space: nowrap; diff --git a/app/client/src/pages/Editor/JSEditor/loader.tsx b/app/client/src/pages/Editor/JSEditor/loader.tsx index 328d4034ebe9..8831c1408266 100644 --- a/app/client/src/pages/Editor/JSEditor/loader.tsx +++ b/app/client/src/pages/Editor/JSEditor/loader.tsx @@ -10,7 +10,7 @@ const LazyJSEditor = lazy(async () => const JSEditor = () => { return ( - <Suspense fallback={Skeleton}> + <Suspense fallback={<Skeleton />}> <LazyJSEditor /> </Suspense> ); diff --git a/app/client/test/testUtils.tsx b/app/client/test/testUtils.tsx index 0d57bddfc09a..1aaee0579cfc 100644 --- a/app/client/test/testUtils.tsx +++ b/app/client/test/testUtils.tsx @@ -59,6 +59,7 @@ const setupState = (state?: State) => { reduxStore.dispatch( fetchFeatureFlagsSuccess({ ...DEFAULT_FEATURE_FLAG_VALUE, + release_ads_entity_item_enabled: true, ...state.featureFlags, }), );
ceb117d1713b836d2b33e002a164b256abed0f53
2023-08-16 11:29:22
sharanya-appsmith
test: cypress - switch group cases - 1 (#26208)
false
cypress - switch group cases - 1 (#26208)
test
diff --git a/app/client/cypress/e2e/Regression/ClientSide/Widgets/Switch/SwitchGroup1_spec.ts b/app/client/cypress/e2e/Regression/ClientSide/Widgets/Switch/SwitchGroup1_spec.ts new file mode 100644 index 000000000000..d039fd7846ac --- /dev/null +++ b/app/client/cypress/e2e/Regression/ClientSide/Widgets/Switch/SwitchGroup1_spec.ts @@ -0,0 +1,265 @@ +import { + agHelper, + draggableWidgets, + entityExplorer, + deployMode, + propPane, + locators, +} from "../../../../../support/Objects/ObjectsCore"; + +import { + switchlocators, + checkboxlocators, +} from "../../../../../locators/WidgetLocators"; + +import widgetsLoc from "../../../../../locators/Widgets.json"; +import widgets from "../../../../../locators/publishWidgetspage.json"; +import commonlocators from "../../../../../locators/commonlocators.json"; + +describe("Switchgroup Widget Functionality", function () { + /** + * Adding switch group, checkbox group and text widgets + */ + before(() => { + entityExplorer.DragNDropWidget(draggableWidgets.SWITCHGROUP, 300, 300); + entityExplorer.DragNDropWidget(draggableWidgets.CHECKBOXGROUP, 300, 500); + entityExplorer.DragNDropWidget(draggableWidgets.TEXT, 300, 700); + propPane.UpdatePropertyFieldValue( + "Text", + "{{SwitchGroup1.selectedValues[0]}}", + ); + }); + + it("1. Check for empty, duplicate values and other error texts in options", () => { + entityExplorer.SelectEntityByName("SwitchGroup1"); + propPane.UpdatePropertyFieldValue( + "Options", + `[ + { + "label": "Blue", + "value": "" + }, + { + "label": "Green", + "value": "GREEN" + }, + { + "label": "Red", + "value": "RED" + } + ]`, + ); + agHelper.AssertElementAbsence(locators._evaluatedErrorMessage); + propPane.UpdatePropertyFieldValue( + "Options", + `[ + { + "label": "Blue", + "value": "" + }, + { + "label": "Green", + "value": "" + }, + { + "label": "Red", + "value": "RED" + } + ]`, + ); + agHelper.VerifyEvaluatedErrorMessage( + "Duplicate values found for the following properties," + + " in the array entries, that must be unique -- label,value.", + ); + propPane.UpdatePropertyFieldValue( + "Options", + `[ + { + "value": "Blue" + }, + { + "label": "Green", + "value": "GREEN" + }, + { + "label": "Red", + "value": "RED" + } + ]`, + ); + agHelper.VerifyEvaluatedErrorMessage( + "Invalid entry at index: 0. Missing required key: label", + ); + propPane.UpdatePropertyFieldValue("Options", "hello"); + agHelper.VerifyEvaluatedErrorMessage( + 'This value does not evaluate to type Array<{ "label": "string", "value": "string" }>', + ); + + // asserts if new option added is not checked + const newOption = `[ + { + "label": "Blue", + "value": "BLUE" + }, + { + "label": "Green", + "value": "GREEN" + }, + { + "label": "Red", + "value": "RED" + }, + { + "label": "Yellow", + "value": "YELLOW" + } + ]`; + propPane.UpdatePropertyFieldValue("Options", newOption); + agHelper + .GetElement(switchlocators.switchGroupToggleChecked("Yellow")) + .should("not.be.checked"); + }); + + it("2. test default selected value func and error texts", () => { + entityExplorer.SelectEntityByName("SwitchGroup1"); + propPane.UpdatePropertyFieldValue( + "Options", + `[ + { + "label": "Blue", + "value": "BLUE" + }, + { + "label": "Green", + "value": "GREEN" + }, + { + "label": "Red", + "value": "RED" + } + ]`, + ); + + propPane.UpdatePropertyFieldValue("Default selected values", "1"); + agHelper.VerifyEvaluatedErrorMessage( + "This value does not evaluate to type Array<string>", + ); + propPane.UpdatePropertyFieldValue("Default selected values", "[]"); + agHelper.AssertElementAbsence(locators._evaluatedErrorMessage); + propPane.UpdatePropertyFieldValue( + "Default selected values", + '["RED", "GREEN"]', + ); + agHelper + .GetElement(switchlocators.switchGroupToggleChecked("Red")) + .should("be.checked"); + agHelper + .GetElement(switchlocators.switchGroupToggleChecked("Green")) + .should("be.checked"); + + propPane.UpdatePropertyFieldValue( + "Default selected values", + "{{CheckboxGroup1.selectedValues}}", + ); + + entityExplorer.SelectEntityByName("CheckboxGroup1"); + agHelper.GetNClick(checkboxlocators.checkBoxLabel("Blue")); + agHelper.GetNClick(checkboxlocators.checkBoxLabel("Red")); + agHelper.GetNClick(checkboxlocators.checkBoxLabel("Green")); + agHelper + .GetElement(switchlocators.switchGroupToggleChecked("Blue")) + .should("not.be.checked"); + agHelper + .GetElement(switchlocators.switchGroupToggleChecked("Red")) + .should("be.checked"); + agHelper + .GetElement(switchlocators.switchGroupToggleChecked("Green")) + .should("be.checked"); + }); + + //Note: Old case, rewrittwen to using ts methods + it("3. Setting selectedValues to undefined does not crash the app", () => { + // Reset options for switch group + entityExplorer.SelectEntityByName("SwitchGroup1"); + propPane.UpdatePropertyFieldValue( + "Options", + `[ + { + "label": "Blue", + "value": "BLUE" + }, + { + "label": "Green1", + "value": "GREEN" + }, + { + "label": "Red", + "value": "RED" + } + ]`, + ); + // throw a cyclic dependency error from checkbox group + entityExplorer.SelectEntityByName("CheckboxGroup1"); + agHelper.TypeText(widgetsLoc.RadioInput, "{{BLUE}}", 1); + propPane.ToggleJSMode("Options", true); + agHelper.AssertElementAbsence(locators._toastMsg); + agHelper.GetNAssertElementText(widgets.textWidget, "RED"); + }); + + it("4. Set Label, Tooltip, Inline and check switch group", () => { + entityExplorer.SelectEntityByName("SwitchGroup1"); + propPane.UpdatePropertyFieldValue("Text", "SG Widget"); + propPane.UpdatePropertyFieldValue("Tooltip", "Select any color"); + // assert label and tooltip + deployMode.DeployApp(); + agHelper.AssertText(switchlocators.switchGroupLabel, "text", "SG Widget"); + agHelper.GetNClick(switchlocators.switchTooltip, 1); + agHelper.AssertPopoverTooltip("Select any color"); + deployMode.NavigateBacktoEditor(); + // assert height of the container based on inline property value + entityExplorer.SelectEntityByName("SwitchGroup1"); + agHelper.AssertElementExist(switchlocators.switchWidgetHeight("60")); + propPane.TogglePropertyState("Inline", "Off"); + agHelper.AssertElementExist(switchlocators.switchWidgetHeight("110")); + }); + + it("5. Check visible, disabled, Height", () => { + entityExplorer.SelectEntityByName("SwitchGroup1"); + propPane.SelectPropertiesDropDown("Height", "Auto Height with limits"); + agHelper.HoverElement(propPane._autoHeightLimitMin); + agHelper.AssertElementExist(propPane._autoHeightLimitMin); + agHelper.AssertElementExist(propPane._autoHeightLimitMax); + + propPane.TogglePropertyState("Visible", "Off"); + deployMode.DeployApp(); + agHelper.AssertElementAbsence(switchlocators.switchGroupLabel); + deployMode.NavigateBacktoEditor(); + entityExplorer.SelectEntityByName("SwitchGroup1"); + propPane.TogglePropertyState("Visible", "On"); + + propPane.TogglePropertyState("Disabled", "On"); + deployMode.DeployApp(); + agHelper.AssertElementExist(commonlocators.disabledField); + deployMode.NavigateBacktoEditor(); + }); + + it("6. Check events - on selection change", () => { + entityExplorer.SelectEntityByName("SwitchGroup1"); + propPane.SelectPropertiesDropDown("Height", "Auto Height"); + propPane.TogglePropertyState("Inline", "On"); + propPane.TogglePropertyState("Disabled", "Off"); + propPane.ToggleJSMode("onSelectionChange", true); + // reset text widget on selecting default color in switch group + propPane.UpdatePropertyFieldValue( + "onSelectionChange", + "{{resetWidget('Text1', true);}}", + ); + agHelper.GetNClick( + switchlocators.switchGroupToggleChecked("Blue"), + 0, + true, + ); + agHelper.GetNClick(switchlocators.switchGroupToggleChecked("Red"), 0, true); + agHelper.AssertElementVisibility(locators._visibleTextSpan("RED")); + }); +}); diff --git a/app/client/cypress/e2e/Regression/ClientSide/Widgets/Switch/SwitchGroup2_spec.js b/app/client/cypress/e2e/Regression/ClientSide/Widgets/Switch/SwitchGroup2_spec.js index 19ceec7e6c3d..17d85989f345 100644 --- a/app/client/cypress/e2e/Regression/ClientSide/Widgets/Switch/SwitchGroup2_spec.js +++ b/app/client/cypress/e2e/Regression/ClientSide/Widgets/Switch/SwitchGroup2_spec.js @@ -5,100 +5,10 @@ import * as _ from "../../../../../support/Objects/ObjectsCore"; describe("Switch Group Widget Functionality", function () { before(() => { _.agHelper.AddDsl("SwitchGroupWidgetDsl"); - }); - /* - afterEach(() => { - _.deployMode.NavigateBacktoEditor(); - }); -*/ - it("1. Widget name changes", function () { - /** - * @param{Text} Random Text - * @param{RadioWidget}Mouseover - * @param{RadioPre Css} Assertion - */ _.propPane.RenameWidget("SwitchGroup1", "SwitchGroupTest"); }); - it("2. Property: options", function () { - // Add a new option - _.entityExplorer.SelectEntityByName("SwitchGroupTest"); - - const optionToAdd = `[ - { - "label": "Blue", - "value": "BLUE" - }, - { - "label": "Green", - "value": "GREEN" - }, - { - "label": "Red", - "value": "RED" - }, - { - "label": "Yellow", - "value": "YELLOW" - } - ]`; - _.propPane.UpdatePropertyFieldValue("Options", optionToAdd); - // Assert - cy.get(formWidgetsPage.labelSwitchGroup) - .should("have.length", 4) - .eq(3) - .contains("Yellow"); - }); - - it("3. Property: defaultSelectedValues", function () { - // Add a new option - const valueToAdd = `[ - "BLUE", "GREEN" - ]`; - _.propPane.UpdatePropertyFieldValue("Default selected values", valueToAdd); - // Assert - cy.get(`${formWidgetsPage.labelSwitchGroup} input:checked`) - .should("have.length", 2) - .eq(1) - .parent() - .contains("Green"); - }); - - it("4. Property: isVisible === FALSE", function () { - cy.togglebarDisable(commonlocators.visibleCheckbox); - /* - _.deployMode.DeployApp(); - cy.get(publish.switchGroupWidget + " " + "input").should("not.exist"); - */ - }); - - it("5. Property: isVisible === TRUE", function () { - cy.togglebar(commonlocators.visibleCheckbox); - /* - _.deployMode.DeployApp(); - cy.get(publish.switchGroupWidget + " " + "input") - .eq(0) - .should("exist"); - */ - }); - - it("6. Property: onSelectionChange", function () { - // create an alert modal and verify its name - cy.createModal(this.dataSet.ModalName, "onSelectionChange"); - /* - _.deployMode.DeployApp(); - cy.get(publish.switchGroupWidget + " " + "label.bp3-switch") - .children() - .first() - .click({ force: true }); - cy.get(modalWidgetPage.modelTextField).should( - "have.text", - this.dataSet.ModalName, - ); - */ - }); - - it("7. Check isDirty meta property", function () { + it("1. Check isDirty meta property", function () { cy.openPropertyPane("textwidget"); cy.updateCodeInput( ".t--property-control-text", diff --git a/app/client/cypress/e2e/Regression/ClientSide/Widgets/Switch/Switchgroup1_spec.js b/app/client/cypress/e2e/Regression/ClientSide/Widgets/Switch/Switchgroup1_spec.js deleted file mode 100644 index 03229982f77f..000000000000 --- a/app/client/cypress/e2e/Regression/ClientSide/Widgets/Switch/Switchgroup1_spec.js +++ /dev/null @@ -1,112 +0,0 @@ -import * as _ from "../../../../../support/Objects/ObjectsCore"; -const explorer = require("../../../../../locators/explorerlocators.json"); - -describe("Switchgroup Widget Functionality", function () { - before(() => { - _.agHelper.AddDsl("emptyDSL"); - }); - - it("1. Add a new switch group widget with others", () => { - cy.get(explorer.addWidget).click(); - cy.dragAndDropToCanvas("switchgroupwidget", { x: 300, y: 300 }); - cy.get(".t--widget-switchgroupwidget").should("exist"); - cy.dragAndDropToCanvas("checkboxgroupwidget", { x: 300, y: 500 }); - cy.get(".t--widget-checkboxgroupwidget").should("exist"); - cy.dragAndDropToCanvas("textwidget", { x: 300, y: 700 }); - cy.get(".t--widget-textwidget").should("exist"); - cy.updateCodeInput( - ".t--property-control-text", - `{{SwitchGroup1.selectedValues[0]}}`, - ); - }); - - it("2. Should check that empty value is allowed in options", () => { - cy.openPropertyPane("switchgroupwidget"); - cy.updateCodeInput( - ".t--property-control-options", - `[ - { - "label": "Blue", - "value": "" - }, - { - "label": "Green", - "value": "GREEN" - }, - { - "label": "Red", - "value": "RED" - } - ]`, - ); - cy.get(".t--property-control-options .t--codemirror-has-error").should( - "not.exist", - ); - }); - - it("3. Should check that more thatn empty value is not allowed in options", () => { - cy.openPropertyPane("switchgroupwidget"); - cy.updateCodeInput( - ".t--property-control-options", - `[ - { - "label": "Blue", - "value": "" - }, - { - "label": "Green", - "value": "" - }, - { - "label": "Red", - "value": "RED" - } - ]`, - ); - cy.get(".t--property-control-options .t--codemirror-has-error").should( - "exist", - ); - }); - - it("4. Setting selectedValues to undefined does not crash the app", () => { - // Reset options for switch group - cy.openPropertyPane("switchgroupwidget"); - cy.updateCodeInput( - ".t--property-control-options", - `[ - { - "label": "Blue", - "value": "BLUE" - }, - { - "label": "Green", - "value": "GREEN" - }, - { - "label": "Red", - "value": "RED" - } - ]`, - ); - // throw a cyclic dependency error from checkbox group - cy.openPropertyPane("checkboxgroupwidget"); - cy.get(".t--property-control-options input") - .eq(1) - .click({ force: true }) - .type("{{BLUE}}", { parseSpecialCharSequences: false }); - cy.wait(2000); - cy.get(".t--property-control-options") - .find(".t--js-toggle") - .trigger("click") - .wait(3000); - // verify absence of cyclic dependency error - cy.VerifyErrorMsgAbsence("Cyclic dependency found while evaluating"); - // check if a crash messsge is appeared - cy.get(".t--widget-switchgroupwidget") - .contains("Oops, Something went wrong.") - .should("not.exist"); - cy.wait(1000); - // Assert that evaluation is not disabled - cy.get(".t--widget-textwidget").should("contain", `BLUE`); - }); -}); diff --git a/app/client/cypress/locators/WidgetLocators.ts b/app/client/cypress/locators/WidgetLocators.ts index 049bb362ac72..f0c6bd849be8 100644 --- a/app/client/cypress/locators/WidgetLocators.ts +++ b/app/client/cypress/locators/WidgetLocators.ts @@ -71,4 +71,19 @@ export const modalWidgetSelector = ".t--modal-widget"; // export data-testid with user input export const progressWidgetProgress = (input: any) => `[data-testid='${input}']` +//switch widget locators +export const switchlocators = { + switchGroupLabel: ".switchgroup-label", + switchTooltip: "//*[@data-testid='switchgroup-container']//*[@class='bp3-popover-target']", + switchWidget:"//*[@data-testid='switchgroup-container']", + switchWidgetHeight: (height: string) => `//*[@data-testid='switchgroup-container']//div[@height="${height}"]`, + switchGroupToggleChecked : (value: string) => + `//*[text()='${value}']//input[@type="checkbox"]`, +} + +export const checkboxlocators = { + // read Blue here + checkBoxLabel: (value: string) => `//*[contains(@class,'t--checkbox-widget-label') and text()='${value}']`, +} +
16cd15a103b63ae2e32448245e026fe7ef786f1d
2024-05-18 00:14:20
Shrikant Sharat Kandula
ci: Include edition in failure messages to Slack (#33553)
false
Include edition in failure messages to Slack (#33553)
ci
diff --git a/.github/workflows/test-build-docker-image.yml b/.github/workflows/test-build-docker-image.yml index a64ff386f380..6535a574394a 100644 --- a/.github/workflows/test-build-docker-image.yml +++ b/.github/workflows/test-build-docker-image.yml @@ -439,15 +439,7 @@ jobs: set -o xtrace run_url='${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}/attempts/${{ github.run_attempt }}' - common_parent_sha='${{ steps.merge.outputs.common_parent_sha }}' - common_parent_sha_short="$(echo "$common_parent_sha" | grep -o '^.\{8\}' || true)" - merged_upto_sha='${{ steps.merge.outputs.merged_upto_sha }}' - merged_upto_sha_short="$(echo "$merged_upto_sha" | grep -o '^.\{8\}' || true)" - - details="🚨 TBP workflow failed in <$run_url|${{ github.run_id }}/attempts/${{ github.run_attempt }}>." - - # This unwieldy horror of a sed command, converts standard Markdown links to Slack's unwieldy link syntax. - slack_message=$(echo "$details" | sed -E 's/\[([^]]+)\]\(([^)]+)\)/<\2|\1>/g') + slack_message="🚨 TBP workflow failed in <$run_url|${{ vars.EDITION }} attempt ${{ github.run_attempt }} (run ${{ github.run_id }})>." # This is the ChannelId of the tech channel. body="$(jq -nc \
d70f2980706ff50c0484af808201ab2e60407c9b
2022-12-23 15:37:29
Aswath K
chore: Makes use of DS components in ThemeControls (#19000)
false
Makes use of DS components in ThemeControls (#19000)
chore
diff --git a/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/ThemingTests/Basic_spec.js b/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/ThemingTests/Basic_spec.js index 0bb41e2769a0..58b18d623005 100644 --- a/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/ThemingTests/Basic_spec.js +++ b/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/ThemingTests/Basic_spec.js @@ -8,6 +8,8 @@ import { ObjectsRegistry } from "../../../../support/Objects/Registry"; const ee = ObjectsRegistry.EntityExplorer, appSettings = ObjectsRegistry.AppSettings; +const containerShadowElement = `${widgetsPage.containerWidget} [data-testid^="container-wrapper-"]`; + describe("App Theming funtionality", function() { before(() => { cy.addDsl(dsl); @@ -62,9 +64,10 @@ describe("App Theming funtionality", function() { cy.get(commonlocators.selectThemeBackBtn).click({ force: true }); appSettings.ClosePane(); - // drop a button widget and click on body + // drop a button & container widget and click on body cy.get(explorer.widgetSwitchId).click(); - cy.dragAndDropToCanvas("buttonwidget", { x: 200, y: 200 }); //iconbuttonwidget + cy.dragAndDropToCanvas("buttonwidget", { x: 200, y: 200 }); + cy.dragAndDropToCanvas("containerwidget", { x: 200, y: 50 }); cy.assertPageSave(); cy.get("canvas") .first(0) @@ -87,7 +90,7 @@ describe("App Theming funtionality", function() { .click({ force: true }); // check if border radius is changed on button - cy.get(`${commonlocators.themeAppBorderRadiusBtn} > div`) + cy.get(commonlocators.themeAppBorderRadiusBtn) .eq(1) .invoke("css", "border-top-left-radius") .then((borderRadius) => { @@ -143,18 +146,18 @@ describe("App Theming funtionality", function() { ); }); - //Change the shadow //Commenting below since expanded by default - //cy.contains("Shadow").click({ force: true }); - cy.contains("App Box Shadow") - .siblings("div") - .children("span") - .last() - .then(($elem) => { - cy.get($elem).click({ force: true }); - cy.get(widgetsPage.widgetBtn).should( + // Change the shadow + cy.get(commonlocators.themeAppBoxShadowBtn) + .eq(3) + .click({ force: true }); + cy.get(commonlocators.themeAppBoxShadowBtn) + .eq(3) + .invoke("css", "box-shadow") + .then((boxShadow) => { + cy.get(containerShadowElement).should( "have.css", "box-shadow", - $elem.css("box-shadow"), + boxShadow, ); }); @@ -306,7 +309,7 @@ describe("App Theming funtionality", function() { cy.get(commonlocators.themeAppBorderRadiusBtn) .eq(2) .click({ force: true }); - cy.get(`${commonlocators.themeAppBorderRadiusBtn} > div`) + cy.get(`${commonlocators.themeAppBorderRadiusBtn}`) .eq(2) .invoke("css", "border-top-left-radius") .then((borderRadius) => { @@ -325,22 +328,17 @@ describe("App Theming funtionality", function() { //#endregion //#region Change the shadow & verify widgets - //cy.contains("Shadow").click({ force: true }); - cy.contains("App Box Shadow") - .siblings("div") - .children("span") - .first() - .then(($elem) => { - cy.get($elem).click({ force: true }); - cy.get(widgetsPage.iconWidgetBtn).should( - "have.css", - "box-shadow", - $elem.css("box-shadow"), - ); - cy.get(widgetsPage.widgetBtn).should( + cy.get(commonlocators.themeAppBoxShadowBtn) + .eq(3) + .click({ force: true }); + cy.get(commonlocators.themeAppBoxShadowBtn) + .eq(3) + .invoke("css", "box-shadow") + .then((boxShadow) => { + cy.get(containerShadowElement).should( "have.css", "box-shadow", - $elem.css("box-shadow"), + boxShadow, ); }); diff --git a/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/ThemingTests/Theme_FormWidget_spec.js b/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/ThemingTests/Theme_FormWidget_spec.js index e41b1f177225..ec5650490476 100644 --- a/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/ThemingTests/Theme_FormWidget_spec.js +++ b/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/ThemingTests/Theme_FormWidget_spec.js @@ -55,7 +55,7 @@ describe("Theme validation usecases", function() { cy.shadowMouseover(1, "S"); cy.shadowMouseover(2, "M"); cy.shadowMouseover(3, "L"); - cy.xpath(themelocator.shadow) + cy.get(themelocator.shadow) .eq(3) .click({ force: true }); cy.wait("@updateTheme").should( diff --git a/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/ThemingTests/Theme_MultiSelectWidget_spec.js b/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/ThemingTests/Theme_MultiSelectWidget_spec.js index 6552a77c278c..4e56d4bea879 100644 --- a/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/ThemingTests/Theme_MultiSelectWidget_spec.js +++ b/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/ThemingTests/Theme_MultiSelectWidget_spec.js @@ -43,7 +43,7 @@ describe("Theme validation usecase for multi-select widget", function() { cy.shadowMouseover(1, "S"); cy.shadowMouseover(2, "M"); cy.shadowMouseover(3, "L"); - cy.xpath(themelocator.shadow) + cy.get(themelocator.shadow) .eq(3) .click({ force: true }); cy.wait("@updateTheme").should( diff --git a/app/client/cypress/locators/ThemeLocators.json b/app/client/cypress/locators/ThemeLocators.json index 1095be936470..abc4d89135f8 100644 --- a/app/client/cypress/locators/ThemeLocators.json +++ b/app/client/cypress/locators/ThemeLocators.json @@ -2,7 +2,7 @@ "canvas": "#canvas-selection-0", "border": ".t--theme-appBorderRadius", "popover": ".bp3-popover-content", - "shadow": "//h3[contains(text(),'Shadow')]/following-sibling::div//button", + "shadow": ".t--theme-appBoxShadow", "color": ".t--property-pane-sidebar .bp3-popover-target .cursor-pointer", "inputColor": ".t--colorpicker-v2-popover input", "colorPicker": "[data-testid='color-picker']", diff --git a/app/client/cypress/locators/commonlocators.json b/app/client/cypress/locators/commonlocators.json index 3a7c2d7fd5bc..0d6ca2a1dbeb 100644 --- a/app/client/cypress/locators/commonlocators.json +++ b/app/client/cypress/locators/commonlocators.json @@ -183,6 +183,7 @@ "saveThemeBtn": ".t--save-theme-btn", "selectThemeBackBtn": ".t--theme-select-back-btn", "themeAppBorderRadiusBtn": ".t--theme-appBorderRadius", + "themeAppBoxShadowBtn": ".t--theme-appBoxShadow", "codeEditorWrapper": ".unfocused-code-editor", "textWidgetContainer": ".t--text-widget-container", "propertyStyle": "li:contains('STYLE')", diff --git a/app/client/cypress/support/themeCommands.js b/app/client/cypress/support/themeCommands.js index eca86ba3b5cc..278119b64023 100644 --- a/app/client/cypress/support/themeCommands.js +++ b/app/client/cypress/support/themeCommands.js @@ -15,7 +15,7 @@ Cypress.Commands.add("borderMouseover", (index, text) => { }); Cypress.Commands.add("shadowMouseover", (index, text) => { - cy.xpath(themelocator.shadow) + cy.get(themelocator.shadow) .eq(index) .trigger("mouseover"); cy.wait(1000); diff --git a/app/client/src/components/propertyControls/BorderRadiusOptionsControl.tsx b/app/client/src/components/propertyControls/BorderRadiusOptionsControl.tsx index d6adaf15897f..a4216c1ef721 100644 --- a/app/client/src/components/propertyControls/BorderRadiusOptionsControl.tsx +++ b/app/client/src/components/propertyControls/BorderRadiusOptionsControl.tsx @@ -23,20 +23,14 @@ export interface BorderRadiusOptionsControlProps extends ControlProps { const options = Object.keys(borderRadiusOptions).map((optionKey) => ({ icon: ( <TooltipComponent - content={ - <div> - <div>{optionKey}</div> - </div> - } + content={optionKey} key={optionKey} openOnTargetFocus={false} > - <button tabIndex={-1}> - <div - className="w-5 h-5 border-t-2 border-l-2 border-gray-500" - style={{ borderTopLeftRadius: borderRadiusOptions[optionKey] }} - /> - </button> + <div + className="w-5 h-5 border-t-2 border-l-2 border-gray-500" + style={{ borderTopLeftRadius: borderRadiusOptions[optionKey] }} + /> </TooltipComponent> ), value: borderRadiusOptions[optionKey], diff --git a/app/client/src/components/propertyControls/BoxShadowOptionsControl.tsx b/app/client/src/components/propertyControls/BoxShadowOptionsControl.tsx index 2935eab0c796..da2e8bb236c9 100644 --- a/app/client/src/components/propertyControls/BoxShadowOptionsControl.tsx +++ b/app/client/src/components/propertyControls/BoxShadowOptionsControl.tsx @@ -18,24 +18,18 @@ export interface BoxShadowOptionsControlProps extends ControlProps { const options = Object.keys(boxShadowOptions).map((optionKey) => ({ icon: ( <TooltipComponent - content={ - <div> - <div>{optionKey}</div> - </div> - } + content={optionKey} key={optionKey} openOnTargetFocus={false} > - <button tabIndex={-1}> - <div - className="flex items-center justify-center w-5 h-5 bg-white" - style={{ boxShadow: boxShadowOptions[optionKey] }} - > - {boxShadowOptions[optionKey] === "none" && ( - <CloseLineIcon className="text-gray-700" /> - )} - </div> - </button> + <div + className="flex items-center justify-center w-5 h-5 bg-white" + style={{ boxShadow: boxShadowOptions[optionKey] }} + > + {boxShadowOptions[optionKey] === "none" && ( + <CloseLineIcon className="text-gray-700" /> + )} + </div> </TooltipComponent> ), value: boxShadowOptions[optionKey], diff --git a/app/client/src/constants/ThemeConstants.tsx b/app/client/src/constants/ThemeConstants.tsx index 3980e6578afe..af6cefec52d4 100644 --- a/app/client/src/constants/ThemeConstants.tsx +++ b/app/client/src/constants/ThemeConstants.tsx @@ -1,3 +1,5 @@ +import { invert } from "lodash"; + /** * mapping of tailwind colors * @@ -126,6 +128,10 @@ export const borderRadiusOptions: Record<string, string> = { L: "1.5rem", }; +export const invertedBorderRadiusOptions: Record<string, string> = invert( + borderRadiusOptions, +); + export const boxShadowPropertyName = "boxShadow"; /** @@ -138,6 +144,10 @@ export const boxShadowOptions: Record<string, string> = { L: "0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -2px rgba(0, 0, 0, 0.05)", }; +export const invertedBoxShadowOptions: Record<string, string> = invert( + boxShadowOptions, +); + export const colorsPropertyName = "colors"; // Text sizes in theming diff --git a/app/client/src/pages/Editor/ThemePropertyPane/controls/ThemeBorderRadiusControl.tsx b/app/client/src/pages/Editor/ThemePropertyPane/controls/ThemeBorderRadiusControl.tsx index 077b8f58d075..bd7efbba71ba 100644 --- a/app/client/src/pages/Editor/ThemePropertyPane/controls/ThemeBorderRadiusControl.tsx +++ b/app/client/src/pages/Editor/ThemePropertyPane/controls/ThemeBorderRadiusControl.tsx @@ -1,8 +1,8 @@ -import classNames from "classnames"; import React, { useCallback } from "react"; import { AppTheme } from "entities/AppTheming"; -import { TooltipComponent } from "design-system"; +import { ButtonTab, TooltipComponent } from "design-system"; +import { invertedBorderRadiusOptions } from "constants/ThemeConstants"; interface ThemeBorderRadiusControlProps { options: { @@ -35,33 +35,32 @@ function ThemeBorderRadiusControl(props: ThemeBorderRadiusControlProps) { [updateTheme, theme], ); + const selectedOptionKey = selectedOption + ? [invertedBorderRadiusOptions[selectedOption]] + : []; + + const buttonTabOptions = Object.keys(options).map((optionKey) => ({ + icon: ( + <TooltipComponent + content={optionKey} + key={optionKey} + openOnTargetFocus={false} + > + <div + className="w-5 h-5 border-t-2 border-l-2 border-gray-500 t--theme-appBorderRadius" + style={{ borderTopLeftRadius: options[optionKey] }} + /> + </TooltipComponent> + ), + value: optionKey, + })); + return ( - <div className="grid grid-cols-6 gap-2 auto-cols-max"> - {Object.keys(options).map((optionKey) => ( - <TooltipComponent content={optionKey} key={optionKey}> - <button - className={classNames({ - "flex items-center justify-center w-8 h-8 bg-white ring-1 cursor-pointer hover:bg-trueGray-50": true, - "ring-gray-800": selectedOption === options[optionKey], - "ring-gray-300": selectedOption !== options[optionKey], - [`t--theme-${sectionName}`]: true, - })} - onClick={() => onChangeBorder(optionKey)} - > - <div - className={classNames({ - "w-5 h-5 border-t-2 border-l-2": true, - "border-gray-800": selectedOption === options[optionKey], - "border-gray-500": selectedOption !== options[optionKey], - })} - style={{ - borderTopLeftRadius: options[optionKey], - }} - /> - </button> - </TooltipComponent> - ))} - </div> + <ButtonTab + options={buttonTabOptions} + selectButton={onChangeBorder} + values={selectedOptionKey} + /> ); } diff --git a/app/client/src/pages/Editor/ThemePropertyPane/controls/ThemeShadowControl.tsx b/app/client/src/pages/Editor/ThemePropertyPane/controls/ThemeShadowControl.tsx index 7301f323d299..8388b8cab7b9 100644 --- a/app/client/src/pages/Editor/ThemePropertyPane/controls/ThemeShadowControl.tsx +++ b/app/client/src/pages/Editor/ThemePropertyPane/controls/ThemeShadowControl.tsx @@ -1,9 +1,10 @@ -import classNames from "classnames"; import React, { useCallback } from "react"; +import { ButtonTab } from "design-system"; import { AppTheme } from "entities/AppTheming"; import { TooltipComponent } from "design-system"; import CloseLineIcon from "remixicon-react/CloseLineIcon"; +import { invertedBoxShadowOptions } from "constants/ThemeConstants"; interface ThemeBoxShadowControlProps { options: { @@ -37,31 +38,36 @@ function ThemeBoxShadowControl(props: ThemeBoxShadowControlProps) { [updateTheme, theme], ); + const selectedOptionKey = selectedOption + ? [invertedBoxShadowOptions[selectedOption]] + : []; + + const buttonTabOptions = Object.keys(options).map((optionKey) => ({ + icon: ( + <TooltipComponent + content={optionKey} + key={optionKey} + openOnTargetFocus={false} + > + <div + className="flex items-center justify-center w-5 h-5 bg-white t--theme-appBoxShadow" + style={{ boxShadow: options[optionKey] }} + > + {options[optionKey] === "none" && ( + <CloseLineIcon className="text-gray-700" /> + )} + </div> + </TooltipComponent> + ), + value: optionKey, + })); + return ( - <div className="grid grid-flow-col gap-2 auto-cols-max"> - {Object.keys(options).map((optionKey) => ( - <TooltipComponent content={optionKey} key={optionKey}> - <button - className={classNames({ - "flex items-center justify-center w-8 h-8 bg-white border ring-gray-700": true, - "ring-1": selectedOption === options[optionKey], - })} - onClick={() => onChangeShadow(optionKey)} - > - <div - className="flex items-center justify-center w-5 h-5 bg-white" - style={{ - boxShadow: options[optionKey], - }} - > - {options[optionKey] === "none" && ( - <CloseLineIcon className="text-gray-700" /> - )} - </div> - </button> - </TooltipComponent> - ))} - </div> + <ButtonTab + options={buttonTabOptions} + selectButton={onChangeShadow} + values={selectedOptionKey} + /> ); }
00ef2b9e093757abdaba7ee807ac608e69b1f29b
2023-07-28 21:20:43
Ankita Kinger
chore: Adding integration tests for provisioning upgrade page (#25818)
false
Adding integration tests for provisioning upgrade page (#25818)
chore
diff --git a/app/client/cypress/e2e/Regression/Enterprise/AdminSettings/Admin_settings_spec.js b/app/client/cypress/e2e/Regression/Enterprise/AdminSettings/Admin_settings_spec.js index 4c85d7febf18..5f1eb0dce74c 100644 --- a/app/client/cypress/e2e/Regression/Enterprise/AdminSettings/Admin_settings_spec.js +++ b/app/client/cypress/e2e/Regression/Enterprise/AdminSettings/Admin_settings_spec.js @@ -59,9 +59,15 @@ describe("Admin settings page", function () { cy.go(-1); } }); + it("3. should test that Business features shows upgrade button and direct to pricing page", () => { cy.visit("/settings/general", { timeout: 60000 }); if (CURRENT_REPO === REPO.CE) { + cy.get(adminsSettings.accessControl).within(() => { + cy.get(adminsSettings.businessTag) + .should("exist") + .should("contain", "Business"); + }); cy.get(adminsSettings.accessControl).click(); cy.url().should("contain", "/settings/access-control"); stubPricingPage(); @@ -69,6 +75,11 @@ describe("Admin settings page", function () { cy.get("@pricingPage").should("be.called"); cy.wait(2000); cy.go(-1); + cy.get(adminsSettings.auditLogs).within(() => { + cy.get(adminsSettings.businessTag) + .should("exist") + .should("contain", "Business"); + }); cy.get(adminsSettings.auditLogs).click(); cy.url().should("contain", "/settings/audit-logs"); stubPricingPage(); @@ -76,6 +87,18 @@ describe("Admin settings page", function () { cy.get("@pricingPage").should("be.called"); cy.wait(2000); cy.go(-1); + cy.get(adminsSettings.provisioning).within(() => { + cy.get(adminsSettings.businessTag) + .should("exist") + .should("contain", "Enterprise"); + }); + cy.get(adminsSettings.provisioning).click(); + cy.url().should("contain", "/settings/provisioning"); + stubPricingPage(); + cy.xpath(adminsSettings.upgrade).click(); + cy.get("@pricingPage").should("be.called"); + cy.wait(2000); + cy.go(-1); } }); }); diff --git a/app/client/cypress/locators/AdminsSettings.js b/app/client/cypress/locators/AdminsSettings.js index 22516a2cfaea..a4ded7908557 100644 --- a/app/client/cypress/locators/AdminsSettings.js +++ b/app/client/cypress/locators/AdminsSettings.js @@ -29,5 +29,7 @@ export default { upgrade: "//button//span[text()='Upgrade']", accessControl: ".t--settings-category-access-control", auditLogs: ".t--settings-category-audit-logs", + provisioning: ".t--settings-category-provisioning", upgrageLeftPane: "[data-testid='t--enterprise-settings-category-item-be']", + businessTag: "[data-testid='t--business-tag']", }; diff --git a/app/client/src/ce/constants/messages.ts b/app/client/src/ce/constants/messages.ts index 80017d7e437b..fba2fee0c9ec 100644 --- a/app/client/src/ce/constants/messages.ts +++ b/app/client/src/ce/constants/messages.ts @@ -169,7 +169,6 @@ export const INVITE_USER_RAMP_TEXT = () => "Users will have access to all applications in the workspace. For application-level access, try out our "; export const CUSTOM_ROLES_RAMP_TEXT = () => "To build and assign custom roles, try out our "; -export const BUSINESS_TEXT = () => "Business"; export const CUSTOM_ROLE_TEXT = () => "Custom role"; export const CUSTOM_ROLE_DISABLED_OPTION_TEXT = () => "Can access specific applications or only certain pages and queries within an application"; diff --git a/app/client/src/ce/pages/AdminSettings/LeftPane.tsx b/app/client/src/ce/pages/AdminSettings/LeftPane.tsx index e21e6129b40f..57916852eb6f 100644 --- a/app/client/src/ce/pages/AdminSettings/LeftPane.tsx +++ b/app/client/src/ce/pages/AdminSettings/LeftPane.tsx @@ -160,7 +160,7 @@ export function Categories({ )} <SettingName active={active}>{config.title}</SettingName> {config?.needsUpgrade && ( - <Tag isClosable={false}> + <Tag data-testid="t--business-tag" isClosable={false}> {createMessage( config?.isEnterprise ? ENTERPRISE_TAG : BUSINESS_TAG, )} diff --git a/app/client/src/ce/pages/workspace/WorkspaceInviteUsersForm.tsx b/app/client/src/ce/pages/workspace/WorkspaceInviteUsersForm.tsx index 5b19547cc9a5..a6ba1cf8e473 100644 --- a/app/client/src/ce/pages/workspace/WorkspaceInviteUsersForm.tsx +++ b/app/client/src/ce/pages/workspace/WorkspaceInviteUsersForm.tsx @@ -24,9 +24,9 @@ import { BUSINESS_EDITION_TEXT, INVITE_USER_RAMP_TEXT, CUSTOM_ROLES_RAMP_TEXT, - BUSINESS_TEXT, CUSTOM_ROLE_DISABLED_OPTION_TEXT, CUSTOM_ROLE_TEXT, + BUSINESS_TAG, } from "@appsmith/constants/messages"; import { isEmail } from "utils/formhelpers"; import { @@ -309,7 +309,7 @@ export function CustomRolesRamp() { {createMessage(CUSTOM_ROLE_TEXT)} </Text> <Tag isClosable={false} size="md"> - {createMessage(BUSINESS_TEXT)} + {createMessage(BUSINESS_TAG)} </Tag> </div> <Text kind="body-s"> diff --git a/app/client/src/pages/Applications/EmbedSnippet/PrivateEmbeddingContent.tsx b/app/client/src/pages/Applications/EmbedSnippet/PrivateEmbeddingContent.tsx index a703e8725145..d1e7b7adb489 100644 --- a/app/client/src/pages/Applications/EmbedSnippet/PrivateEmbeddingContent.tsx +++ b/app/client/src/pages/Applications/EmbedSnippet/PrivateEmbeddingContent.tsx @@ -1,7 +1,7 @@ import React from "react"; import { Text, Link, Button, Icon, Tag } from "design-system"; import { - BUSINESS_TEXT, + BUSINESS_TAG, createMessage, IN_APP_EMBED_SETTING, } from "@appsmith/constants/messages"; @@ -60,7 +60,7 @@ export function PrivateEmbedRampModal() { {createMessage(IN_APP_EMBED_SETTING.privateAppsText)} </Text> <Tag className="ml-1 mt-0.5" isClosable={false}> - {createMessage(BUSINESS_TEXT)} + {createMessage(BUSINESS_TAG)} </Tag> </div> <Text
6765888eb033b28753c64d34056a09fee5df433c
2024-01-31 11:02:38
Ashok Kumar M
chore: Anvil cypress tests (#30580)
false
Anvil cypress tests (#30580)
chore
diff --git a/app/client/cypress/e2e/Regression/ClientSide/Anvil/AnvilAppNavigation_spec.ts b/app/client/cypress/e2e/Regression/ClientSide/Anvil/AnvilAppNavigation_spec.ts new file mode 100644 index 000000000000..e4edb08b8d51 --- /dev/null +++ b/app/client/cypress/e2e/Regression/ClientSide/Anvil/AnvilAppNavigation_spec.ts @@ -0,0 +1,77 @@ +import { WIDGET } from "../../../../locators/WidgetLocators"; +import { ANVIL_EDITOR_TEST } from "../../../../support/Constants"; +import { + agHelper, + locators, + propPane, + appSettings, + anvilLayout, +} from "../../../../support/Objects/ObjectsCore"; +import { MAIN_CONTAINER_WIDGET_ID } from "../../../../../src/constants/WidgetConstants"; +import { getAnvilCanvasId } from "../../../../../src/layoutSystems/anvil/canvas/utils"; +import { featureFlagIntercept } from "../../../../support/Objects/FeatureFlags"; + +describe( + `${ANVIL_EDITOR_TEST}: Validating multiple widgets in anvil layout mode with App navigation settings`, + { tags: ["@tag.Anvil"] }, + function () { + beforeEach(() => { + // intercept features call for Anvil + WDS tests + featureFlagIntercept({ + release_anvil_enabled: true, + ab_wds_enabled: true, + }); + // Cleanup the canvas before each test + agHelper.SelectAllWidgets(); + agHelper.PressDelete(); + }); + it("1. Change App navigation settings and valdiate the layout settings", () => { + const mainCanvasId = `#${getAnvilCanvasId(MAIN_CONTAINER_WIDGET_ID)}`; + const paddingBetweenZoneAndMainCanvas = 35; + agHelper.AssertElementExist(mainCanvasId).then((mainCanvas) => { + const x = mainCanvas.position().left; + const y = mainCanvas.position().top; + anvilLayout.DragDropAnvilWidgetNVerify( + WIDGET.WDSINPUT, + x + 10, + y + paddingBetweenZoneAndMainCanvas, + { + skipWidgetSearch: true, + }, + ); + anvilLayout.DragDropAnvilWidgetNVerify( + WIDGET.WDSINPUT, + x + 10, + y + paddingBetweenZoneAndMainCanvas, + { + skipWidgetSearch: true, + dropTargetDetails: { + name: "Section1", + }, + }, + ); + anvilLayout.DragDropAnvilWidgetNVerify( + WIDGET.WDSBUTTON, + x + 10, + y + paddingBetweenZoneAndMainCanvas, + { + skipWidgetSearch: true, + dropTargetDetails: { + name: "Section1", + }, + }, + ); + }); + propPane.NavigateToPage("Page1", "onClick"); + appSettings.OpenAppSettings(); + agHelper.GetNClick(appSettings.locators._navigationSettingsTab); + agHelper.GetNClick( + appSettings.locators._navigationSettings._orientationOptions._side, + ); + agHelper.AssertElementExist(appSettings.locators._sideNavbar); + agHelper.GetNClick(locators._canvas); + agHelper.AssertElementExist(locators._widgetInCanvas(WIDGET.WDSINPUT)); + agHelper.AssertElementExist(locators._widgetInCanvas(WIDGET.WDSINPUT), 1); + }); + }, +); diff --git a/app/client/cypress/e2e/Regression/ClientSide/Anvil/AnvilDnD_spec.ts b/app/client/cypress/e2e/Regression/ClientSide/Anvil/AnvilDnD_spec.ts new file mode 100644 index 000000000000..0d7d1a1aaa69 --- /dev/null +++ b/app/client/cypress/e2e/Regression/ClientSide/Anvil/AnvilDnD_spec.ts @@ -0,0 +1,73 @@ +import { MAIN_CONTAINER_WIDGET_ID } from "../../../../../src/constants/WidgetConstants"; +import { WIDGET } from "../../../../locators/WidgetLocators"; +import { + agHelper, + anvilLayout, + locators, +} from "../../../../support/Objects/ObjectsCore"; +import { getAnvilCanvasId } from "../../../../../src/layoutSystems/anvil/canvas/utils"; +import { ANVIL_EDITOR_TEST } from "../../../../support/Constants"; +import { featureFlagIntercept } from "../../../../support/Objects/FeatureFlags"; + +describe( + `${ANVIL_EDITOR_TEST}: Anvil tests for DnD Module`, + { tags: ["@tag.Anvil"] }, + () => { + beforeEach(() => { + // intercept features call for Anvil + WDS tests + featureFlagIntercept({ + release_anvil_enabled: true, + ab_wds_enabled: true, + }); + // Cleanup the canvas before each test + agHelper.SelectAllWidgets(); + agHelper.PressDelete(); + }); + it("1. Drag and Drop widget onto Empty Canvas", () => { + const mainCanvasId = `#${getAnvilCanvasId(MAIN_CONTAINER_WIDGET_ID)}`; + agHelper.AssertElementExist(mainCanvasId).then((mainCanvas) => { + const x = mainCanvas.position().left; + const y = mainCanvas.position().top; + const width = mainCanvas.width() || 0; + const paddingBetweenZoneAndMainCanvas = 35; + // start align + anvilLayout.DragDropAnvilWidgetNVerify( + WIDGET.WDSBUTTON, + x + 10, + y + paddingBetweenZoneAndMainCanvas * 0.5, + { + skipWidgetSearch: true, + }, + ); + // center align + anvilLayout.DragDropAnvilWidgetNVerify( + WIDGET.WDSBUTTON, + x + (width - 2 * paddingBetweenZoneAndMainCanvas) / 2, + y + paddingBetweenZoneAndMainCanvas * 0.5, + { + skipWidgetSearch: true, + dropTargetDetails: { + name: "Zone1", + }, + }, + ); + // end align + anvilLayout.DragDropAnvilWidgetNVerify( + WIDGET.WDSBUTTON, + x + (width - 2 * paddingBetweenZoneAndMainCanvas), + y + paddingBetweenZoneAndMainCanvas * 0.5, + { + skipWidgetSearch: true, + dropTargetDetails: { + name: "Zone1", + }, + }, + ); + agHelper.AssertElementLength( + locators._widgetInCanvas(WIDGET.WDSBUTTON), + 3, + ); + }); + }); + }, +); diff --git a/app/client/cypress/e2e/Regression/ClientSide/Anvil/AnvilSuggestedWidgets_spec.ts b/app/client/cypress/e2e/Regression/ClientSide/Anvil/AnvilSuggestedWidgets_spec.ts new file mode 100644 index 000000000000..76a1beb115e6 --- /dev/null +++ b/app/client/cypress/e2e/Regression/ClientSide/Anvil/AnvilSuggestedWidgets_spec.ts @@ -0,0 +1,27 @@ +import { ANVIL_EDITOR_TEST } from "../../../../support/Constants"; +import { featureFlagIntercept } from "../../../../support/Objects/FeatureFlags"; +import { dataSources } from "../../../../support/Objects/ObjectsCore"; +import { Widgets } from "../../../../support/Pages/DataSources"; + +describe( + `${ANVIL_EDITOR_TEST}:Check Suggested Widgets Feature`, + { tags: ["@tag.Anvil"] }, + function () { + beforeEach(() => { + // intercept features call for Anvil + WDS tests + featureFlagIntercept({ + release_anvil_enabled: true, + ab_wds_enabled: true, + }); + }); + it("1. Suggested wds widgets for anvil layout", () => { + dataSources.CreateDataSource("Postgres"); + dataSources.CreateQueryAfterDSSaved("SELECT * FROM configs LIMIT 10;"); + cy.intercept("/api/v1/actions/execute", { + fixture: "addWidgetTable-mock", + }); + dataSources.RunQuery({ toValidateResponse: false }); + dataSources.AddSuggestedWidget(Widgets.WDSTable); + }); + }, +); diff --git a/app/client/cypress/locators/WidgetLocators.ts b/app/client/cypress/locators/WidgetLocators.ts index c02bb0f7ea08..8c559a4eecda 100644 --- a/app/client/cypress/locators/WidgetLocators.ts +++ b/app/client/cypress/locators/WidgetLocators.ts @@ -5,6 +5,9 @@ export const WIDGET = { PHONE_INPUT: "phoneinputwidget", CURRENCY_INPUT: "currencyinputwidget", BUTTON: "buttonwidget", + WDSBUTTON: "wdsbuttonwidget", + WDSTABLE: "wdstablewidget", + WDSINPUT: "wdsinputwidget", BUTTONNAME: (index: string) => `Button${index}`, CODESCANNER: "codescannerwidget", CONTAINER: "containerwidget", diff --git a/app/client/cypress/support/Constants.js b/app/client/cypress/support/Constants.js index fc499119dfda..0fe95fd43976 100644 --- a/app/client/cypress/support/Constants.js +++ b/app/client/cypress/support/Constants.js @@ -118,6 +118,7 @@ export const TABLE_DATA_STATIC = ` `; export const WALKTHROUGH_TEST_PAGE = "WALKTHROUGH_TEST_PAGE"; +export const ANVIL_EDITOR_TEST = "ANVIL_EDITOR_TEST"; export const DEFAULT_COLUMN_NAME = "Table Column"; export const FEATURE_WALKTHROUGH_INDEX_KEY = "FEATURE_WALKTHROUGH"; export const USER_SIGN_UP_INDEX_KEY = "USER_SIGN_UP"; diff --git a/app/client/cypress/support/Objects/CommonLocators.ts b/app/client/cypress/support/Objects/CommonLocators.ts index c8600b62c884..661cd054bd1c 100644 --- a/app/client/cypress/support/Objects/CommonLocators.ts +++ b/app/client/cypress/support/Objects/CommonLocators.ts @@ -83,6 +83,7 @@ export class CommonLocators { _visibleTextSpan = (spanText: string, isCss = false) => isCss ? `span:contains("${spanText}")` : `//span[text()="${spanText}"]`; _dropHere = ".t--drop-target"; + _canvasSlider = "[data-type=canvas-slider]"; _editPage = "[data-testid=onboarding-tasks-datasource-text], .t--drop-target"; _crossBtn = "span.cancel-icon"; _createNew = ".t--add-item"; diff --git a/app/client/cypress/support/Objects/ObjectsCore.ts b/app/client/cypress/support/Objects/ObjectsCore.ts index 19bcd9ae54fa..29dd82bfcd12 100644 --- a/app/client/cypress/support/Objects/ObjectsCore.ts +++ b/app/client/cypress/support/Objects/ObjectsCore.ts @@ -35,4 +35,5 @@ export const tabs = ObjectsRegistry.Tabs; export const gsheetHelper = ObjectsRegistry.GSheetHelper; export const widgetLocators = WIDGETSKIT; export const communityTemplates = ObjectsRegistry.CommunityTemplates; +export const anvilLayout = ObjectsRegistry.AnvilLayout; export const partialImportExport = ObjectsRegistry.PartialImportExport; diff --git a/app/client/cypress/support/Objects/Registry.ts b/app/client/cypress/support/Objects/Registry.ts index c0ab9cbd0014..5c701fea1ebe 100644 --- a/app/client/cypress/support/Objects/Registry.ts +++ b/app/client/cypress/support/Objects/Registry.ts @@ -28,6 +28,7 @@ import { AssertHelper } from "../Pages/AssertHelper"; import { Tabs } from "../Pages/Tabs"; import { GsheetHelper } from "../Pages/GSheetHelper"; import { CommunityTemplates } from "../Pages/CommunityTemplates"; +import { AnvilLayout } from "../Pages/AnvilLayout"; import PartialImportExport from "../Pages/PartialImportExport"; export class ObjectsRegistry { @@ -247,6 +248,14 @@ export class ObjectsRegistry { return ObjectsRegistry.autoLayout__; } + private static anvilLayout__: AnvilLayout; + static get AnvilLayout(): AnvilLayout { + if (ObjectsRegistry.anvilLayout__ === undefined) { + ObjectsRegistry.anvilLayout__ = new AnvilLayout(); + } + return ObjectsRegistry.anvilLayout__; + } + private static dataManager__: DataManager; static get DataManager(): DataManager { if (ObjectsRegistry.dataManager__ === undefined) { diff --git a/app/client/cypress/support/Pages/AnvilLayout.ts b/app/client/cypress/support/Pages/AnvilLayout.ts new file mode 100644 index 000000000000..120dc705c149 --- /dev/null +++ b/app/client/cypress/support/Pages/AnvilLayout.ts @@ -0,0 +1,121 @@ +import { drop } from "lodash"; +import { getWidgetSelector } from "../../locators/WidgetLocators"; +import { ObjectsRegistry } from "../Objects/Registry"; +import { + AppSidebar, + AppSidebarButton, + PageLeftPane, + PagePaneSegment, +} from "./EditorNavigation"; + +interface DropTargetDetails { + id?: string; + name?: string; +} + +interface DragDropWidgetOptions { + skipWidgetSearch?: boolean; + dropTargetDetails?: DropTargetDetails; +} + +export class AnvilLayout { + private entityExplorer = ObjectsRegistry.EntityExplorer; + private locator = ObjectsRegistry.CommonLocators; + private agHelper = ObjectsRegistry.AggregateHelper; + + private getAnvilDropTargetSelectorFromOptions = ( + dropTarget?: DropTargetDetails, + ) => { + if (dropTarget) { + if (dropTarget.id) { + return `#${dropTarget.id}`; + } + if (dropTarget.name) { + return `${getWidgetSelector(dropTarget.name.toLowerCase() as any)} ${ + this.locator._canvasSlider + }`; + } + } + return this.locator._canvasSlider; + }; + + private performDnDInAnvil( + xPos: number, + yPos: number, + options = {} as DragDropWidgetOptions, + ) { + const dropAreaSelector = this.getAnvilDropTargetSelectorFromOptions( + options.dropTargetDetails, + ); + cy.get(dropAreaSelector) + .first() + .then((dropAreaDom) => { + const { left, top } = dropAreaDom[0].getBoundingClientRect(); + cy.document() + // to activate ANVIL canvas + .trigger("mousemove", left + xPos, top + yPos, { + eventConstructor: "MouseEvent", + clientX: left + xPos, + clientY: top + yPos, + force: true, + }); + this.agHelper.Sleep(200); + cy.get(dropAreaSelector).first().trigger("mousemove", xPos, yPos, { + eventConstructor: "MouseEvent", + force: true, + }); + this.agHelper.Sleep(200); + cy.get(dropAreaSelector).first().trigger("mousemove", xPos, yPos, { + eventConstructor: "MouseEvent", + force: true, + }); + cy.get(this.locator._canvasSlider) + .first() + .trigger("mouseup", xPos, yPos, { + eventConstructor: "MouseEvent", + force: true, + }); + }); + } + + private startDraggingWidgetFromPane(widgetType: string) { + cy.get(this.locator._widgetPageIcon(widgetType)) + .first() + .trigger("dragstart", { force: true }); + } + + private setupWidgetPane(skipWidgetSearch: boolean, widgetType: string) { + if (!skipWidgetSearch) { + this.entityExplorer.SearchWidgetPane(widgetType); + } else { + AppSidebar.navigate(AppSidebarButton.Editor); + PageLeftPane.switchSegment(PagePaneSegment.UI); + PageLeftPane.switchToAddNew(); + cy.focused().blur(); + } + } + + private DragNDropAnvilWidget( + widgetType: string, + x = 300, + y = 100, + options = {} as DragDropWidgetOptions, + ) { + const { skipWidgetSearch = false } = options; + this.setupWidgetPane(skipWidgetSearch, widgetType); + this.startDraggingWidgetFromPane(widgetType); + this.performDnDInAnvil(x, y, options); + } + + public DragDropAnvilWidgetNVerify( + widgetType: string, + x = 300, + y = 100, + options = {} as DragDropWidgetOptions, + ) { + this.DragNDropAnvilWidget(widgetType, x, y, options); + this.agHelper.AssertAutoSave(); //settling time for widget on canvas! + this.agHelper.AssertElementExist(this.locator._widgetInCanvas(widgetType)); + this.agHelper.Sleep(200); //waiting a bit for widget properties to open + } +} diff --git a/app/client/cypress/support/Pages/DataSources.ts b/app/client/cypress/support/Pages/DataSources.ts index 81b94a433b27..cda755ea6f98 100644 --- a/app/client/cypress/support/Pages/DataSources.ts +++ b/app/client/cypress/support/Pages/DataSources.ts @@ -34,6 +34,7 @@ export enum Widgets { Table, Chart, Text, + WDSTable, } type AppModes = "Edit" | "View"; @@ -1672,6 +1673,16 @@ export class DataSources { this.locator._widgetInCanvas(WIDGET.TABLE), ); break; + case Widgets.WDSTable: + this.agHelper.GetNClick( + this._suggestedWidget("TABLE_WIDGET_V2", parentClass), + index, + force, + ); + this.agHelper.AssertElementVisibility( + this.locator._widgetInCanvas(WIDGET.WDSTABLE), + ); + break; case Widgets.Chart: this.agHelper.GetNClick( this._suggestedWidget("CHART_WIDGET", parentClass), diff --git a/app/client/cypress/support/commands.js b/app/client/cypress/support/commands.js index 64d836675694..2c25ba90eb89 100644 --- a/app/client/cypress/support/commands.js +++ b/app/client/cypress/support/commands.js @@ -1,6 +1,7 @@ /* eslint-disable cypress/no-unnecessary-waiting */ /* eslint-disable cypress/no-assigning-return-values */ /* This file is used to maintain comman methods across tests , refer other *.js files for adding common methods */ +import { ANVIL_EDITOR_TEST } from "./Constants.js"; import EditorNavigation, { EntityType, @@ -1074,7 +1075,15 @@ Cypress.Commands.add("startServerAndRoutes", () => { }).as("postTenant"); cy.intercept("PUT", "/api/v1/git/discard/app/*").as("discardChanges"); cy.intercept("GET", "/api/v1/libraries/*").as("getLibraries"); - featureFlagIntercept({}, false); + if (Cypress.currentTest.titlePath[0].includes(ANVIL_EDITOR_TEST)) { + // intercept features call for creating pages that support Anvil + WDS tests + featureFlagIntercept( + { release_anvil_enabled: true, ab_wds_enabled: true }, + false, + ); + } else { + featureFlagIntercept({}, false); + } cy.intercept( { method: "GET", diff --git a/app/client/cypress/tags.js b/app/client/cypress/tags.js index 34560c59c4aa..a2765666f712 100644 --- a/app/client/cypress/tags.js +++ b/app/client/cypress/tags.js @@ -1,5 +1,6 @@ module.exports = { Tag: [ + "@tag.Anvil", "@tag.excludeForAirgap", "@tag.airgap", "@tag.Git", diff --git a/app/client/src/layoutSystems/anvil/canvas/AnvilCanvas.tsx b/app/client/src/layoutSystems/anvil/canvas/AnvilCanvas.tsx index c4a982d8e1f0..9ba2df187a4b 100644 --- a/app/client/src/layoutSystems/anvil/canvas/AnvilCanvas.tsx +++ b/app/client/src/layoutSystems/anvil/canvas/AnvilCanvas.tsx @@ -32,6 +32,7 @@ export const AnvilCanvas = (props: BaseWidgetProps) => { className={className} id={getAnvilCanvasId(props.widgetId)} onClick={handleOnClickCapture} + tabIndex={0} //adding for accessibility in test cases. > <LayoutProvider {...props} /> </div> diff --git a/app/client/src/layoutSystems/anvil/canvasArenas/hooks/mainCanvas/useCanvasActivation.ts b/app/client/src/layoutSystems/anvil/canvasArenas/hooks/mainCanvas/useCanvasActivation.ts index 49f815aa9b5c..30b135a6c2ba 100644 --- a/app/client/src/layoutSystems/anvil/canvasArenas/hooks/mainCanvas/useCanvasActivation.ts +++ b/app/client/src/layoutSystems/anvil/canvasArenas/hooks/mainCanvas/useCanvasActivation.ts @@ -65,7 +65,6 @@ export const useCanvasActivation = () => { const draggedWidgetPositions = selectedWidgets.map((each) => { return layoutElementPositions[each]; }); - /** * boolean ref that indicates if the mouse position is outside of main canvas while dragging * this is being tracked in order to activate/deactivate canvas. diff --git a/app/client/src/layoutSystems/common/canvasArenas/StickyCanvasArena.tsx b/app/client/src/layoutSystems/common/canvasArenas/StickyCanvasArena.tsx index 57507117c979..dd51e96eabc4 100644 --- a/app/client/src/layoutSystems/common/canvasArenas/StickyCanvasArena.tsx +++ b/app/client/src/layoutSystems/common/canvasArenas/StickyCanvasArena.tsx @@ -210,6 +210,7 @@ export const StickyCanvasArena = forwardRef( /> <StyledCanvasSlider data-testid={sliderId} + data-type={"canvas-slider"} id={sliderId} paddingBottom={canvasPadding} ref={slidingArenaRef}
065ced345b6ec4732d27059908eab18b817008df
2024-04-18 10:05:34
Hetu Nandu
chore: Make Editor Pane Segments GA (#32712)
false
Make Editor Pane Segments GA (#32712)
chore
diff --git a/app/client/cypress/support/Objects/FeatureFlags.ts b/app/client/cypress/support/Objects/FeatureFlags.ts index f7b4f18740e8..bd6c9b080a76 100644 --- a/app/client/cypress/support/Objects/FeatureFlags.ts +++ b/app/client/cypress/support/Objects/FeatureFlags.ts @@ -3,7 +3,6 @@ import { ObjectsRegistry } from "./Registry"; import produce from "immer"; const defaultFlags = { - release_show_new_sidebar_pages_pane_enabled: true, release_side_by_side_ide_enabled: true, }; diff --git a/app/client/src/ce/entities/FeatureFlag.ts b/app/client/src/ce/entities/FeatureFlag.ts index 8e12d0206a96..41eee1c336f4 100644 --- a/app/client/src/ce/entities/FeatureFlag.ts +++ b/app/client/src/ce/entities/FeatureFlag.ts @@ -33,15 +33,12 @@ export const FEATURE_FLAG = { license_widget_rtl_support_enabled: "license_widget_rtl_support_enabled", release_show_partial_import_export_enabled: "release_show_partial_import_export_enabled", - release_show_new_sidebar_pages_pane_enabled: - "release_show_new_sidebar_pages_pane_enabled", ab_one_click_learning_popover_enabled: "ab_one_click_learning_popover_enabled", release_side_by_side_ide_enabled: "release_side_by_side_ide_enabled", release_global_add_pane_enabled: "release_global_add_pane_enabled", ab_appsmith_ai_query: "ab_appsmith_ai_query", release_actions_redesign_enabled: "release_actions_redesign_enabled", - rollout_editor_pane_segments_enabled: "rollout_editor_pane_segments_enabled", rollout_remove_feature_walkthrough_enabled: "rollout_remove_feature_walkthrough_enabled", release_drag_drop_building_blocks_enabled: @@ -84,13 +81,11 @@ export const DEFAULT_FEATURE_FLAG_VALUE: FeatureFlags = { release_git_continuous_delivery_enabled: false, license_widget_rtl_support_enabled: false, release_show_partial_import_export_enabled: false, - release_show_new_sidebar_pages_pane_enabled: false, ab_one_click_learning_popover_enabled: false, release_side_by_side_ide_enabled: false, release_global_add_pane_enabled: false, ab_appsmith_ai_query: false, release_actions_redesign_enabled: false, - rollout_editor_pane_segments_enabled: false, rollout_remove_feature_walkthrough_enabled: false, rollout_js_enabled_one_click_binding_enabled: false, rollout_side_by_side_enabled: false, diff --git a/app/client/src/ce/sagas/JSActionSagas.ts b/app/client/src/ce/sagas/JSActionSagas.ts index d117c20337aa..280e7e4de9a2 100644 --- a/app/client/src/ce/sagas/JSActionSagas.ts +++ b/app/client/src/ce/sagas/JSActionSagas.ts @@ -69,7 +69,6 @@ import type { CanvasWidgetsReduxState } from "reducers/entityReducers/canvasWidg import { getIsServerDSLMigrationsEnabled } from "selectors/pageSelectors"; import { getWidgets } from "sagas/selectors"; import FocusRetention from "sagas/FocusRetentionSaga"; -import { getIsEditorPaneSegmentsEnabled } from "@appsmith/selectors/featureFlagsSelectors"; import { handleJSEntityRedirect } from "sagas/IDESaga"; import { getIDETypeByUrl } from "@appsmith/entities/IDE/utils"; import { IDE_TYPE } from "@appsmith/entities/IDE/constants"; @@ -303,11 +302,8 @@ export function* deleteJSCollectionSaga( toast.show(createMessage(JS_ACTION_DELETE_SUCCESS, response.data.name), { kind: "success", }); - const isEditorPaneSegmentsEnabled: boolean = yield select( - getIsEditorPaneSegmentsEnabled, - ); yield call(FocusRetention.handleRemoveFocusHistory, currentUrl); - if (isEditorPaneSegmentsEnabled && ideType === IDE_TYPE.App) { + if (ideType === IDE_TYPE.App) { yield call(handleJSEntityRedirect, id); } else { history.push(builderURL({ pageId })); diff --git a/app/client/src/ce/selectors/featureFlagsSelectors.ts b/app/client/src/ce/selectors/featureFlagsSelectors.ts index 9bcc0efef535..80ef0ca73dc9 100644 --- a/app/client/src/ce/selectors/featureFlagsSelectors.ts +++ b/app/client/src/ce/selectors/featureFlagsSelectors.ts @@ -1,7 +1,5 @@ import type { AppState } from "@appsmith/reducers"; import type { FeatureFlag, FeatureFlags } from "@appsmith/entities/FeatureFlag"; -import { createSelector } from "reselect"; -import { FEATURE_FLAG } from "@appsmith/entities/FeatureFlag"; import memoize from "micro-memoize"; import type { OverriddenFeatureFlags } from "utils/hooks/useFeatureFlagOverride"; @@ -29,16 +27,3 @@ export const selectFeatureFlagCheck = ( } return false; }; - -export const getIsEditorPaneSegmentsEnabled = createSelector( - selectFeatureFlags, - (flags) => { - const isEditorSegmentsReleaseEnabled = - flags[FEATURE_FLAG.release_show_new_sidebar_pages_pane_enabled]; - - const isEditorSegmentsRolloutEnabled = - flags[FEATURE_FLAG.rollout_editor_pane_segments_enabled]; - - return isEditorSegmentsReleaseEnabled || isEditorSegmentsRolloutEnabled; - }, -); diff --git a/app/client/src/components/editorComponents/PartialImportExport/PartialExportModal/unitTestUtils.ts b/app/client/src/components/editorComponents/PartialImportExport/PartialExportModal/unitTestUtils.ts index 140464e00f1e..52fd24c045c6 100644 --- a/app/client/src/components/editorComponents/PartialImportExport/PartialExportModal/unitTestUtils.ts +++ b/app/client/src/components/editorComponents/PartialImportExport/PartialExportModal/unitTestUtils.ts @@ -12771,7 +12771,6 @@ export const defaultAppState = { release_show_new_sidebar_announcement_enabled: false, rollout_app_sidebar_enabled: false, release_show_partial_import_export_enabled: true, - release_show_new_sidebar_pages_pane_enabled: false, ab_one_click_learning_popover_enabled: false, release_side_by_side_ide_enabled: false, release_global_add_pane_enabled: false, diff --git a/app/client/src/pages/Editor/APIEditor/CurlImportEditor.tsx b/app/client/src/pages/Editor/APIEditor/CurlImportEditor.tsx index aba46cc8e536..99eb4362531a 100644 --- a/app/client/src/pages/Editor/APIEditor/CurlImportEditor.tsx +++ b/app/client/src/pages/Editor/APIEditor/CurlImportEditor.tsx @@ -1,4 +1,4 @@ -import React, { useMemo } from "react"; +import React from "react"; import CurlImportForm from "./CurlImportForm"; import { curlImportSubmitHandler } from "./helpers"; @@ -8,10 +8,8 @@ import { showDebuggerFlag } from "selectors/debuggerSelectors"; import { useSelector } from "react-redux"; import type { RouteComponentProps } from "react-router"; import type { BuilderRouteParams } from "constants/routes"; -import CloseEditor from "components/editorComponents/CloseEditor"; import { CreateNewActionKey } from "@appsmith/entities/Engine/actionHelpers"; import { DEFAULT_PREFIX } from "sagas/ActionSagas"; -import { useIsEditorPaneSegmentsEnabled } from "../IDE/hooks"; import { ActionParentEntityType } from "@appsmith/entities/Engine/actionHelpers"; type CurlImportEditorProps = RouteComponentProps<BuilderRouteParams>; @@ -34,13 +32,9 @@ function CurlImportEditor(props: CurlImportEditorProps) { contextType: ActionParentEntityType.PAGE, name: actionName, }; - const isEditorPaneEnabled = useIsEditorPaneSegmentsEnabled(); - - const closeEditorLink = useMemo(() => <CloseEditor />, []); return ( <CurlImportForm - closeEditorLink={isEditorPaneEnabled ? null : closeEditorLink} curlImportSubmitHandler={curlImportSubmitHandler} initialValues={initialFormValues} isImportingCurl={isImportingCurl} diff --git a/app/client/src/pages/Editor/APIEditor/index.tsx b/app/client/src/pages/Editor/APIEditor/index.tsx index 7f1f5b7da25f..430b2c28c13a 100644 --- a/app/client/src/pages/Editor/APIEditor/index.tsx +++ b/app/client/src/pages/Editor/APIEditor/index.tsx @@ -32,12 +32,10 @@ import { get, keyBy } from "lodash"; import PerformanceTracker, { PerformanceTransactionName, } from "utils/PerformanceTracker"; -import CloseEditor from "components/editorComponents/CloseEditor"; import ConvertToModuleInstanceCTA from "@appsmith/pages/Editor/EntityEditor/ConvertToModuleInstanceCTA"; import { MODULE_TYPE } from "@appsmith/constants/ModuleConstants"; import Disabler from "pages/common/Disabler"; import ConvertEntityNotification from "@appsmith/pages/common/ConvertEntityNotification"; -import { useIsEditorPaneSegmentsEnabled } from "../IDE/hooks"; import { Icon } from "design-system"; import { resolveIcon } from "../utils"; import { ENTITY_ICON_SIZE, EntityIcon } from "../Explorer/ExplorerIcons"; @@ -159,10 +157,6 @@ function ApiEditorWrapper(props: ApiEditorWrapperProps) { dispatch(deleteAction({ id: apiId, name: apiName })); }, [getPageName, pages, pageId, apiName]); - const isEditorPaneEnabled = useIsEditorPaneSegmentsEnabled(); - - const closeEditorLink = useMemo(() => <CloseEditor />, []); - const notification = useMemo(() => { if (!isConverting) return null; @@ -172,7 +166,6 @@ function ApiEditorWrapper(props: ApiEditorWrapperProps) { return ( <ApiEditorContextProvider actionRightPaneBackLink={actionRightPaneBackLink} - closeEditorLink={isEditorPaneEnabled ? null : closeEditorLink} handleDeleteClick={handleDeleteClick} handleRunClick={handleRunClick} moreActionsMenu={moreActionsMenu} diff --git a/app/client/src/pages/Editor/IDE/AppsmithIDE.test.tsx b/app/client/src/pages/Editor/IDE/AppsmithIDE.test.tsx index 20e58a7ac792..864f81f35130 100644 --- a/app/client/src/pages/Editor/IDE/AppsmithIDE.test.tsx +++ b/app/client/src/pages/Editor/IDE/AppsmithIDE.test.tsx @@ -597,12 +597,7 @@ describe("Drag and Drop widgets into Main container", () => { const canvasWidgets = component.queryAllByTestId("test-widget"); // empty canvas expect(canvasWidgets.length).toBe(0); - const allAddEntityButtons: any = - component.container.querySelectorAll(".t--entity-add-btn"); - const widgetAddButton = allAddEntityButtons[1]; - act(() => { - fireEvent.click(widgetAddButton); - }); + const containerButton: any = component.queryAllByText("Container"); act(() => { diff --git a/app/client/src/pages/Editor/IDE/EditorPane/JS/JSRender.test.tsx b/app/client/src/pages/Editor/IDE/EditorPane/JS/JSRender.test.tsx index 668cf9fa9bfa..cb1418467f4a 100644 --- a/app/client/src/pages/Editor/IDE/EditorPane/JS/JSRender.test.tsx +++ b/app/client/src/pages/Editor/IDE/EditorPane/JS/JSRender.test.tsx @@ -15,7 +15,6 @@ import { JSObjectFactory } from "test/factories/Actions/JSObject"; const FeatureFlags = { rollout_side_by_side_enabled: true, - rollout_editor_pane_segments_enabled: true, }; describe("IDE Render: JS", () => { localStorage.setItem("SPLITPANE_ANNOUNCEMENT", "false"); diff --git a/app/client/src/pages/Editor/IDE/EditorPane/Query/QueryRender.test.tsx b/app/client/src/pages/Editor/IDE/EditorPane/Query/QueryRender.test.tsx index 3b63d17df166..7828b739a6b1 100644 --- a/app/client/src/pages/Editor/IDE/EditorPane/Query/QueryRender.test.tsx +++ b/app/client/src/pages/Editor/IDE/EditorPane/Query/QueryRender.test.tsx @@ -20,7 +20,6 @@ import { GoogleSheetFactory } from "test/factories/Actions/GoogleSheetFactory"; const FeatureFlags = { rollout_side_by_side_enabled: true, - rollout_editor_pane_segments_enabled: true, }; describe("IDE URL rendering of Queries", () => { diff --git a/app/client/src/pages/Editor/IDE/EditorPane/UI/UIRender.test.tsx b/app/client/src/pages/Editor/IDE/EditorPane/UI/UIRender.test.tsx index 39f58a97af05..37f1e0c9b061 100644 --- a/app/client/src/pages/Editor/IDE/EditorPane/UI/UIRender.test.tsx +++ b/app/client/src/pages/Editor/IDE/EditorPane/UI/UIRender.test.tsx @@ -15,7 +15,6 @@ import { EditorViewMode } from "@appsmith/entities/IDE/constants"; const FeatureFlags = { rollout_side_by_side_enabled: true, - rollout_editor_pane_segments_enabled: true, }; describe("IDE URL rendering: UI", () => { diff --git a/app/client/src/pages/Editor/IDE/LeftPane/index.tsx b/app/client/src/pages/Editor/IDE/LeftPane/index.tsx index e43c36eed161..f883a59796b4 100644 --- a/app/client/src/pages/Editor/IDE/LeftPane/index.tsx +++ b/app/client/src/pages/Editor/IDE/LeftPane/index.tsx @@ -1,5 +1,4 @@ import React from "react"; -import WidgetsEditorEntityExplorer from "../../WidgetsEditorEntityExplorer"; import styled from "styled-components"; import { Switch, useRouteMatch } from "react-router"; import { SentryRoute } from "@appsmith/AppRouter"; @@ -15,7 +14,6 @@ import AppSettingsPane from "./AppSettings"; import DataSidePane from "./DataSidePane"; import LibrarySidePane from "./LibrarySidePane"; import EditorPane from "../EditorPane"; -import { useIsEditorPaneSegmentsEnabled } from "../hooks"; export const LeftPaneContainer = styled.div` height: 100%; @@ -24,7 +22,6 @@ export const LeftPaneContainer = styled.div` `; const LeftPane = () => { - const isEditorPaneEnabled = useIsEditorPaneSegmentsEnabled(); const { path } = useRouteMatch(); return ( <LeftPaneContainer> @@ -49,11 +46,7 @@ const LeftPane = () => { exact path={`${path}${APP_SETTINGS_EDITOR_PATH}`} /> - {isEditorPaneEnabled ? ( - <SentryRoute component={EditorPane} /> - ) : ( - <SentryRoute component={WidgetsEditorEntityExplorer} /> - )} + <SentryRoute component={EditorPane} /> </Switch> </LeftPaneContainer> ); diff --git a/app/client/src/pages/Editor/IDE/hooks.ts b/app/client/src/pages/Editor/IDE/hooks.ts index fb767a948ecd..d45470f07fd2 100644 --- a/app/client/src/pages/Editor/IDE/hooks.ts +++ b/app/client/src/pages/Editor/IDE/hooks.ts @@ -27,8 +27,6 @@ import { DEFAULT_EDITOR_PANE_WIDTH, DEFAULT_SPLIT_SCREEN_WIDTH, } from "constants/AppConstants"; -import { useFeatureFlag } from "utils/hooks/useFeatureFlag"; -import { FEATURE_FLAG } from "@appsmith/entities/FeatureFlag"; import { getIsAltFocusWidget, getWidgetSelectionBlock } from "selectors/ui"; import { altFocusWidget, setWidgetSelectionBlock } from "actions/widgetActions"; import { useJSAdd } from "@appsmith/pages/Editor/IDE/EditorPane/JS/hooks"; @@ -212,18 +210,6 @@ export const useGetPageFocusUrl = (pageId: string): string => { return focusPageUrl; }; -export const useIsEditorPaneSegmentsEnabled = () => { - const isEditorSegmentsReleaseEnabled = useFeatureFlag( - FEATURE_FLAG.release_show_new_sidebar_pages_pane_enabled, - ); - - const isEditorSegmentsRolloutEnabled = useFeatureFlag( - FEATURE_FLAG.rollout_editor_pane_segments_enabled, - ); - - return isEditorSegmentsReleaseEnabled || isEditorSegmentsRolloutEnabled; -}; - export function useWidgetSelectionBlockListener() { const { pathname } = useLocation(); const dispatch = useDispatch(); diff --git a/app/client/src/pages/Editor/JSEditor/index.tsx b/app/client/src/pages/Editor/JSEditor/index.tsx index 343001591235..0226184e1433 100644 --- a/app/client/src/pages/Editor/JSEditor/index.tsx +++ b/app/client/src/pages/Editor/JSEditor/index.tsx @@ -12,8 +12,6 @@ import AppJSEditorContextMenu from "./AppJSEditorContextMenu"; import { updateFunctionProperty } from "actions/jsPaneActions"; import type { OnUpdateSettingsProps } from "./JSFunctionSettings"; import { saveJSObjectName } from "actions/jsActionActions"; -import CloseEditor from "components/editorComponents/CloseEditor"; -import { useIsEditorPaneSegmentsEnabled } from "../IDE/hooks"; const LoadingContainer = styled(CenteredWrapper)` height: 50%; @@ -32,7 +30,6 @@ function JSEditor(props: Props) { getJSCollectionDataById(state, collectionId), ); const { isCreating } = useSelector((state) => state.ui.jsPane); - const isEditorPaneEnabled = useIsEditorPaneSegmentsEnabled(); const jsCollection = jsCollectionData?.config; const contextMenu = useMemo(() => { @@ -57,12 +54,9 @@ function JSEditor(props: Props) { dispatch(updateFunctionProperty(props)); }; - const backLink = <CloseEditor />; - if (!!jsCollection) { return ( <JsEditorForm - backLink={isEditorPaneEnabled ? null : backLink} contextMenu={contextMenu} hideContextMenuOnEditor={Boolean( jsCollectionData?.config.isMainJSCollection, diff --git a/app/client/src/pages/Editor/QueryEditor/index.tsx b/app/client/src/pages/Editor/QueryEditor/index.tsx index 5ca74efe6d99..54f39afd37b0 100644 --- a/app/client/src/pages/Editor/QueryEditor/index.tsx +++ b/app/client/src/pages/Editor/QueryEditor/index.tsx @@ -32,13 +32,11 @@ import { } from "@appsmith/utils/BusinessFeatures/permissionPageHelpers"; import { FEATURE_FLAG } from "@appsmith/entities/FeatureFlag"; import { useFeatureFlag } from "utils/hooks/useFeatureFlag"; -import CloseEditor from "components/editorComponents/CloseEditor"; import Disabler from "pages/common/Disabler"; import ConvertToModuleInstanceCTA from "@appsmith/pages/Editor/EntityEditor/ConvertToModuleInstanceCTA"; import { MODULE_TYPE } from "@appsmith/constants/ModuleConstants"; import ConvertEntityNotification from "@appsmith/pages/common/ConvertEntityNotification"; import { PluginType } from "entities/Action"; -import { useIsEditorPaneSegmentsEnabled } from "../IDE/hooks"; import { Icon } from "design-system"; import { resolveIcon } from "../utils"; import { ENTITY_ICON_SIZE, EntityIcon } from "../Explorer/ExplorerIcons"; @@ -166,10 +164,6 @@ function QueryEditor(props: QueryEditorProps) { [pageId, history, integrationEditorURL], ); - const isEditorPaneEnabled = useIsEditorPaneSegmentsEnabled(); - - const closeEditorLink = useMemo(() => <CloseEditor />, []); - const notification = useMemo(() => { if (!isConverting) return null; @@ -186,7 +180,6 @@ function QueryEditor(props: QueryEditorProps) { <QueryEditorContextProvider actionRightPaneBackLink={actionRightPaneBackLink} changeQueryPage={changeQueryPage} - closeEditorLink={isEditorPaneEnabled ? null : closeEditorLink} moreActionsMenu={moreActionsMenu} notification={notification} onCreateDatasourceClick={onCreateDatasourceClick} diff --git a/app/client/src/pages/Editor/widgetSidebar/WidgetCard.tsx b/app/client/src/pages/Editor/widgetSidebar/WidgetCard.tsx index 3adef1d8b57a..ebcf2c804ed8 100644 --- a/app/client/src/pages/Editor/widgetSidebar/WidgetCard.tsx +++ b/app/client/src/pages/Editor/widgetSidebar/WidgetCard.tsx @@ -4,9 +4,7 @@ import styled from "styled-components"; import { useWidgetDragResize } from "utils/hooks/dragResizeHooks"; import AnalyticsUtil from "utils/AnalyticsUtil"; import { generateReactKey } from "utils/generators"; -import { useWidgetSelection } from "utils/hooks/useWidgetSelection"; import { Text } from "design-system"; -import { useIsEditorPaneSegmentsEnabled } from "../IDE/hooks"; interface CardProps { details: WidgetCardProps; @@ -75,8 +73,6 @@ const THUMBNAIL_WIDTH = 72; function WidgetCard(props: CardProps) { const { setDraggingNewWidget } = useWidgetDragResize(); - const { deselectAll } = useWidgetSelection(); - const isEditorPaneEnabled = useIsEditorPaneSegmentsEnabled(); const onDragStart = (e: any) => { e.preventDefault(); @@ -90,9 +86,6 @@ function WidgetCard(props: CardProps) { ...props.details, widgetId: generateReactKey(), }); - if (!isEditorPaneEnabled) { - deselectAll(); - } }; const type = `${props.details.type.split("_").join("").toLowerCase()}`; diff --git a/app/client/src/sagas/ActionSagas.ts b/app/client/src/sagas/ActionSagas.ts index fccdf2272cb2..c608eb6391f2 100644 --- a/app/client/src/sagas/ActionSagas.ts +++ b/app/client/src/sagas/ActionSagas.ts @@ -136,7 +136,6 @@ import { EditorModes } from "components/editorComponents/CodeEditor/EditorConfig import { updateActionAPICall } from "@appsmith/sagas/ApiCallerSagas"; import { getIsServerDSLMigrationsEnabled } from "selectors/pageSelectors"; import FocusRetention from "./FocusRetentionSaga"; -import { getIsEditorPaneSegmentsEnabled } from "@appsmith/selectors/featureFlagsSelectors"; import { resolveParentEntityMetadata } from "@appsmith/sagas/helpers"; import { handleQueryEntityRedirect } from "./IDESaga"; import { EditorViewMode, IDE_TYPE } from "@appsmith/entities/IDE/constants"; @@ -625,11 +624,8 @@ export function* deleteActionSaga( }); } yield call(FocusRetention.handleRemoveFocusHistory, currentUrl); - const isEditorPaneSegmentsEnabled: boolean = yield select( - getIsEditorPaneSegmentsEnabled, - ); - if (isEditorPaneSegmentsEnabled && ideType === IDE_TYPE.App) { + if (ideType === IDE_TYPE.App) { yield call(handleQueryEntityRedirect, action.id); } else { if (!!actionPayload.payload.onSuccess) { diff --git a/app/client/src/sagas/DatasourcesSagas.ts b/app/client/src/sagas/DatasourcesSagas.ts index 3a5b346fd092..96ba39d36994 100644 --- a/app/client/src/sagas/DatasourcesSagas.ts +++ b/app/client/src/sagas/DatasourcesSagas.ts @@ -83,7 +83,6 @@ import { ToastMessageType, } from "entities/Datasource"; import { - INTEGRATION_EDITOR_MODES, INTEGRATION_TABS, RESPONSE_STATUS, SHOW_FILE_PICKER_KEY, @@ -170,7 +169,6 @@ import { import { waitForFetchEnvironments } from "@appsmith/sagas/EnvironmentSagas"; import { getCurrentGitBranch } from "selectors/gitSyncSelectors"; import FocusRetention from "./FocusRetentionSaga"; -import { getIsEditorPaneSegmentsEnabled } from "@appsmith/selectors/featureFlagsSelectors"; import { identifyEntityFromPath } from "../navigation/FocusEntity"; import { MAX_DATASOURCE_SUGGESTIONS } from "constants/DatasourceEditorConstants"; import { getFromServerWhenNoPrefetchedResult } from "./helper"; @@ -425,53 +423,13 @@ export function* deleteDatasourceSaga( const id = actionPayload.payload.id; const response: ApiResponse<Datasource> = yield DatasourcesApi.deleteDatasource(id); - const pageId: string = yield select(getCurrentPageId); const isValidResponse: boolean = yield validateResponse(response); if (isValidResponse) { - const pluginPackageName = shouldBeDefined<string>( - yield select((state: AppState) => - getPluginPackageFromDatasourceId(state, id), - ), - `Plugin package not found for the given id - ${id}`, - ); - const datasourcePathWithoutQuery = trimQueryString( - datasourcesEditorIdURL({ - pageId, - datasourceId: id, - }), - ); - - const saasPathWithoutQuery = trimQueryString( - saasEditorDatasourceIdURL({ - pageId, - pluginPackageName, - datasourceId: id, - }), - ); const currentUrl = `${window.location.pathname}`; yield call(FocusRetention.handleRemoveFocusHistory, currentUrl); - const isEditorPaneSegmentsEnabled: boolean = yield select( - getIsEditorPaneSegmentsEnabled, - ); - if (isEditorPaneSegmentsEnabled) { - yield call(handleDatasourceDeleteRedirect, id); - } else if ( - currentUrl === datasourcePathWithoutQuery || - currentUrl === saasPathWithoutQuery - ) { - history.push( - integrationEditorURL({ - pageId, - selectedTab: INTEGRATION_TABS.NEW, - params: { - ...getQueryParams(), - mode: INTEGRATION_EDITOR_MODES.AUTO, - }, - }), - ); - } + yield call(handleDatasourceDeleteRedirect, id); toast.show(createMessage(DATASOURCE_DELETE, response.data.name), { kind: "success",
47a0a48943b1d613611cb395be70b5f4a98f5988
2022-10-13 16:12:36
Aishwarya-U-R
test: Script updates for flaky tests to unblock CI (#17469)
false
Script updates for flaky tests to unblock CI (#17469)
test
diff --git a/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/BugTests/Bug16702_Spec.ts b/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/BugTests/Bug16702_Spec.ts new file mode 100644 index 000000000000..9e3d87615c07 --- /dev/null +++ b/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/BugTests/Bug16702_Spec.ts @@ -0,0 +1,72 @@ +import datasourceFormData from "../../../../fixtures/datasources.json"; +import { ObjectsRegistry } from "../../../../support/Objects/Registry"; + +const locator = ObjectsRegistry.CommonLocators, + apiPage = ObjectsRegistry.ApiPage, + agHelper = ObjectsRegistry.AggregateHelper, + dataSources = ObjectsRegistry.DataSources, + jsEditor = ObjectsRegistry.JSEditor; + +const GRAPHQL_LIMIT_QUERY = ` + query { + launchesPast(limit: "__limit__", offset: "__offset__") { + mission_name + rocket { + rocket_name +`; + +const GRAPHQL_RESPONSE = { + mission_name: "Sentinel-6 Michael Freilich", +}; + +describe("Binding Expressions should not be truncated in Url and path extraction", function() { + it("Bug 16702, Moustache+Quotes formatting goes wrong in graphql body resulting in autocomplete failure", function() { + const jsObjectBody = `export default { + limitValue: 1, + offsetValue: 1, + }`; + + jsEditor.CreateJSObject(jsObjectBody, { + paste: true, + completeReplace: true, + toRun: false, + shouldCreateNewJSObj: true, + }); + + apiPage.CreateAndFillGraphqlApi(datasourceFormData.graphqlApiUrl); + dataSources.UpdateGraphqlQueryAndVariable({ + query: GRAPHQL_LIMIT_QUERY, + }); + + cy.get(".t--graphql-query-editor pre.CodeMirror-line span") + .contains("__offset__") + // .should($el => { + // expect(Cypress.dom.isDetached($el)).to.false; + // }) + //.trigger("mouseover") + .click() + .type("{{JSObject1."); + agHelper.GetNClickByContains(locator._hints, "offsetValue"); + agHelper.Sleep(200); + + /* Start: Block of code to remove error of detached node of codemirror for cypress reference */ + + apiPage.SelectPaneTab("Params"); + apiPage.SelectPaneTab("Body"); + /* End: Block of code to remove error of detached node of codemirror for cypress reference */ + + cy.get(".t--graphql-query-editor pre.CodeMirror-line span") + .contains("__limit__") + //.trigger("mouseover") + .click() + .type("{{JSObject1."); + agHelper.GetNClickByContains(locator._hints, "limitValue"); + agHelper.Sleep(); + //Commenting this since - many runs means - API response is 'You are doing too many launches' + // apiPage.RunAPI(false, 20, { + // expectedPath: "response.body.data.body.data.launchesPast[0].mission_name", + // expectedRes: GRAPHQL_RESPONSE.mission_name, + // }); + apiPage.RunAPI(); + }); +}); diff --git a/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/BugTests/InvalidURL_Spec.ts b/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/BugTests/InvalidURL_Spec.ts index 58f8e2c385df..fa391c453867 100644 --- a/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/BugTests/InvalidURL_Spec.ts +++ b/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/BugTests/InvalidURL_Spec.ts @@ -1,7 +1,10 @@ import { ObjectsRegistry } from "../../../../support/Objects/Registry"; +import { WIDGET } from "../../../../locators/WidgetLocators"; const jsEditor = ObjectsRegistry.JSEditor, - agHelper = ObjectsRegistry.AggregateHelper; + agHelper = ObjectsRegistry.AggregateHelper, + ee = ObjectsRegistry.EntityExplorer, + deployMode = ObjectsRegistry.DeployMode; describe("Invalid page routing", () => { it("1. Bug #16047 - Shows Invalid URL UI for invalid JS Object page url", () => { @@ -33,4 +36,10 @@ describe("Invalid page routing", () => { ); }); }); + + // it("2. Multi select - test ", () => { + // ee.DragDropWidgetNVerify(WIDGET.MULTITREESELECT); + // deployMode.DeployApp(); + // agHelper.SelectFromMutliTree("Red"); + // }); }); diff --git a/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/ThemingTests/Theme_FormWidget_spec.js b/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/ThemingTests/Theme_FormWidget_spec.js index 8bad204eccea..3210faea4fe4 100644 --- a/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/ThemingTests/Theme_FormWidget_spec.js +++ b/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/ThemingTests/Theme_FormWidget_spec.js @@ -8,7 +8,7 @@ let themeBackgroudColor; let themeFont; describe("Theme validation usecases", function() { - it("Drag and drop form widget and validate Default font and list of font validation", function() { + it("1. Drag and drop form widget and validate Default font and list of font validation", function() { cy.log("Login Successful"); cy.reload(); // To remove the rename tooltip cy.get(explorer.addWidget).click(); @@ -133,7 +133,7 @@ describe("Theme validation usecases", function() { cy.contains("Color").click({ force: true }); }); - it("Publish the App and validate Font across the app", function() { + it("2. Publish the App and validate Font across the app", function() { cy.PublishtheApp(); cy.get(".bp3-button:contains('Sub')").should( "have.css", @@ -157,7 +157,7 @@ describe("Theme validation usecases", function() { ); }); - it("Validate Default Theme change across application", function() { + it("3. Validate Default Theme change across application", function() { cy.goToEditFromPublish(); cy.get(formWidgetsPage.formD).click(); cy.widgetText( @@ -194,7 +194,7 @@ describe("Theme validation usecases", function() { }); }); - it("Publish the App and validate Default Theme across the app", function() { + it("4. Publish the App and validate Default Theme across the app", function() { cy.PublishtheApp(); /* Bug Form backgroud colour reset in Publish mode cy.get(formWidgetsPage.formD) @@ -214,7 +214,7 @@ describe("Theme validation usecases", function() { }); }); - it("Validate Theme change across application", function() { + it("5. Validate Theme change across application", function() { cy.goToEditFromPublish(); cy.get(formWidgetsPage.formD).click(); cy.widgetText( @@ -304,7 +304,7 @@ describe("Theme validation usecases", function() { .and("eq", "rgb(255, 193, 61)"); }); - it("Publish the App and validate Theme across the app", function() { + it("6. Publish the App and validate Theme across the app", function() { cy.PublishtheApp(); //Bug Form backgroud colour reset in Publish mode /* diff --git a/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/Widgets/List/List1_spec.js b/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/Widgets/List/List1_spec.js index 2918e0abb673..2565d0d4afcb 100644 --- a/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/Widgets/List/List1_spec.js +++ b/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/Widgets/List/List1_spec.js @@ -1,107 +1,10 @@ const dsl = require("../../../../../fixtures/listRegressionDsl.json"); -const publish = require("../../../../../locators/publishWidgetspage.json"); -const commonlocators = require("../../../../../locators/commonlocators.json"); -import { ObjectsRegistry } from "../../../../../support/Objects/Registry"; - -let propPane = ObjectsRegistry.PropertyPane; describe("Binding the list widget with text widget", function() { //const modifierKey = Cypress.platform === "darwin" ? "meta" : "ctrl"; - - before(() => { + it("1. Validate delete widget action from side bar", function() { cy.addDsl(dsl); - }); - - it("1. Validate text widget data based on changes in list widget Data1", function() { - cy.PublishtheApp(); - cy.wait(2000); - 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("2. Validate text widget data based on changes in list widget Data2", function() { - cy.SearchEntityandOpen("List1"); - propPane.UpdatePropertyFieldValue( - "Items", - '[[{ "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(1000); - propPane.UpdatePropertyFieldValue( - "Text", - '{{currentItem.map(item => item.name).join(", ")}}', - ); - cy.wait("@updateLayout").should( - "have.nested.property", - "response.body.responseMeta.status", - 200, - ); - cy.PublishtheApp(); - cy.wait(2000); - 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("3. Validate text widget data based on changes in list widget Data3", function() { - cy.SearchEntityandOpen("List1"); - propPane.UpdatePropertyFieldValue( - "Items", - '[{ "name": "pawan"}, { "name": "Vivek" }]', - ); - cy.wait("@updateLayout").should( - "have.nested.property", - "response.body.responseMeta.status", - 200, - ); - cy.SearchEntityandOpen("Text3"); - cy.wait(1000); - propPane.UpdatePropertyFieldValue("Text", "{{currentItem.name}}"); - cy.wait("@updateLayout").should( - "have.nested.property", - "response.body.responseMeta.status", - 200, - ); - cy.PublishtheApp(); - cy.wait(2000); - 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("4. Validate delete widget action from side bar", function() { + cy.wait(3000); //for dsl to settle cy.openPropertyPane("listwidget"); cy.verifyUpdatedWidgetName("Test"); cy.verifyUpdatedWidgetName("#$%1234", "___1234"); @@ -110,12 +13,13 @@ describe("Binding the list widget with text widget", function() { cy.get(".t--toast-action span") .eq(0) .contains("56789 is removed"); - // cy.wait("@updateLayout").should( - // "have.nested.property", - // "response.body.responseMeta.status", - // 200, - // ); + cy.wait("@updateLayout").should( + "have.nested.property", + "response.body.responseMeta.status", + 200, + ); cy.reload(); - cy.wait(2000); + //cy.get(commonlocators.homeIcon).click({ force: true }); + // eslint-disable-next-line cypress/no-unnecessary-waiting }); }); diff --git a/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/Widgets/List/List6_spec.js b/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/Widgets/List/List6_spec.js new file mode 100644 index 000000000000..b2530fd4cefd --- /dev/null +++ b/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/Widgets/List/List6_spec.js @@ -0,0 +1,110 @@ +const dsl = require("../../../../../fixtures/listRegressionDsl.json"); +const publish = require("../../../../../locators/publishWidgetspage.json"); +import { ObjectsRegistry } from "../../../../../support/Objects/Registry"; + +let propPane = ObjectsRegistry.PropertyPane, + agHelper = ObjectsRegistry.AggregateHelper; + +describe("Binding the list widget with text widget", function() { + //const modifierKey = Cypress.platform === "darwin" ? "meta" : "ctrl"; + + before(() => { + cy.addDsl(dsl); + cy.wait(3000); //for dsl to settle + }); + + it("1. Validate text widget data based on changes in list widget Data1", function() { + cy.PublishtheApp(); + cy.wait(2000); + 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("2. Validate text widget data based on changes in list widget Data2", function() { + cy.SearchEntityandOpen("List1"); + propPane.UpdatePropertyFieldValue( + "Items", + '[[{ "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(1000); + propPane.UpdatePropertyFieldValue( + "Text", + '{{currentItem.map(item => item.name).join(", ")}}', + ); + cy.wait("@updateLayout").should( + "have.nested.property", + "response.body.responseMeta.status", + 200, + ); + cy.PublishtheApp(); + cy.wait(2000); + 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("3. Validate text widget data based on changes in list widget Data3", function() { + cy.SearchEntityandOpen("List1"); + propPane.UpdatePropertyFieldValue( + "Items", + '[{ "name": "pawan"}, { "name": "Vivek" }]', + ); + cy.wait("@updateLayout").should( + "have.nested.property", + "response.body.responseMeta.status", + 200, + ); + cy.SearchEntityandOpen("Text3"); + cy.wait(1000); + propPane.UpdatePropertyFieldValue("Text", "{{currentItem.name}}"); + cy.wait("@updateLayout").should( + "have.nested.property", + "response.body.responseMeta.status", + 200, + ); + cy.PublishtheApp(); + cy.wait(2000); + 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 }); + }); + + after(function() { + //-- Deleting the application by Api---// + cy.DeleteAppByApi(); + //-- LogOut Application---// + }); +}); diff --git a/app/client/cypress/integration/Smoke_TestSuite/ServerSideTests/OnLoadTests/JSOnLoad1_Spec.ts b/app/client/cypress/integration/Smoke_TestSuite/ServerSideTests/OnLoadTests/JSOnLoad1_Spec.ts index b3f6228b8190..992895d89e53 100644 --- a/app/client/cypress/integration/Smoke_TestSuite/ServerSideTests/OnLoadTests/JSOnLoad1_Spec.ts +++ b/app/client/cypress/integration/Smoke_TestSuite/ServerSideTests/OnLoadTests/JSOnLoad1_Spec.ts @@ -116,7 +116,7 @@ describe("JSObjects OnLoad Actions tests", function() { ee.ExpandCollapseEntity("Queries/JS"); ee.SelectEntityByName(jsName as string); jsEditor.EnableDisableAsyncFuncSettings("getEmployee", true, true); - deployMode.DeployApp(); + deployMode.DeployApp(locator._widgetInDeployed("tablewidget"), false); agHelper.AssertElementVisible(jsEditor._dialog("Confirmation Dialog")); agHelper.AssertElementVisible( jsEditor._dialogBody((jsName as string) + ".getEmployee"), @@ -302,39 +302,56 @@ describe("JSObjects OnLoad Actions tests", function() { deployMode.DeployApp(); + //Commenting & changnig flow since either of confirmation modals can appear first! + + // //Confirmation - first JSObj then API + // agHelper.AssertElementVisible( + // jsEditor._dialogBody((jsName as string) + ".callTrump"), + // ); + // agHelper.ClickButton("No"); + // agHelper.WaitUntilToastDisappear( + // `${jsName + ".callTrump"} was cancelled`, + // ); //When Confirmation is NO validate error toast! + + agHelper.ClickButton("No"); + agHelper.AssertContains("was cancelled"); + //One Quotes confirmation - for API true - agHelper.AssertElementVisible(jsEditor._dialogBody("Quotes")); + // agHelper.AssertElementVisible(jsEditor._dialogBody("Quotes")); + // agHelper.ClickButton("No"); + // agHelper.WaitUntilToastDisappear("Quotes was cancelled"); + agHelper.ClickButton("No"); - agHelper.WaitUntilToastDisappear("Quotes was cancelled"); + agHelper.AssertContains("was cancelled"); + + // //Another for API called via JS callQuotes() + // agHelper.AssertElementVisible(jsEditor._dialogBody("Quotes")); + // agHelper.ClickButton("No"); - //Another for API called via JS callQuotes() - agHelper.AssertElementVisible(jsEditor._dialogBody("Quotes")); agHelper.ClickButton("No"); //agHelper.WaitUntilToastDisappear('The action "Quotes" has failed');No toast appears! - //Confirmation - first JSObj then API - agHelper.AssertElementVisible( - jsEditor._dialogBody((jsName as string) + ".callTrump"), - ); - agHelper.ClickButton("No"); - agHelper.WaitUntilToastDisappear( - `${jsName + ".callTrump"} was cancelled`, - ); //When Confirmation is NO validate error toast! agHelper.AssertElementAbsence(jsEditor._dialogBody("WhatTrumpThinks")); //Since JS call is NO, dependent API confirmation should not appear agHelper.RefreshPage(); - agHelper.AssertElementVisible(jsEditor._dialogBody("Quotes")); + // agHelper.AssertElementVisible( + // jsEditor._dialogBody((jsName as string) + ".callTrump"), + // ); + agHelper.AssertElementExist(jsEditor._dialogInDeployView); agHelper.ClickButton("Yes"); - agHelper.AssertElementVisible(jsEditor._dialogBody("Quotes")); + agHelper.Sleep(); + //agHelper.AssertElementVisible(jsEditor._dialogBody("WhatTrumpThinks")); //Since JS call is Yes, dependent confirmation should appear aswell! + agHelper.AssertElementExist(jsEditor._dialogInDeployView); agHelper.ClickButton("Yes"); - agHelper.AssertElementVisible( - jsEditor._dialogBody((jsName as string) + ".callTrump"), - ); + //agHelper.AssertElementVisible(jsEditor._dialogBody("Quotes")); + agHelper.AssertElementExist(jsEditor._dialogInDeployView); agHelper.ClickButton("Yes"); - agHelper.AssertElementVisible(jsEditor._dialogBody("WhatTrumpThinks")); //Since JS call is Yes, dependent confirmation should appear aswell! + agHelper.Sleep(500); + //agHelper.AssertElementVisible(jsEditor._dialogBody("Quotes")); + agHelper.AssertElementExist(jsEditor._dialogInDeployView); agHelper.ClickButton("Yes"); agHelper.Sleep(4000); //to let the api's call be finished & populate the text fields before validation! @@ -355,20 +372,18 @@ describe("JSObjects OnLoad Actions tests", function() { it("10. Tc #1912 - API with OnPageLoad & Confirmation both enabled & called directly & setting previous Api's confirmation to false", () => { deployMode.NavigateBacktoEditor(); - agHelper.AssertElementVisible(jsEditor._dialogBody("Quotes")); + agHelper.AssertElementExist(jsEditor._dialogInDeployView); agHelper.ClickButton("No"); - agHelper.AssertContains("Quotes was cancelled"); + agHelper.AssertContains("was cancelled"); //agHelper.AssertContains("Quotes was cancelled"); agHelper.WaitUntilAllToastsDisappear(); - agHelper.AssertElementVisible(jsEditor._dialogBody("Quotes")); + agHelper.AssertElementExist(jsEditor._dialogInDeployView); agHelper.ClickButton("No"); //Ask Favour abt below //agHelper.ValidateToastMessage("callQuotes ran successfully"); //Verify this toast comes in EDIT page only - agHelper.AssertElementVisible( - jsEditor._dialogBody((jsName as string) + ".callTrump"), - ); + agHelper.AssertElementExist(jsEditor._dialogInDeployView); agHelper.ClickButton("No"); - agHelper.AssertContains(`${jsName + ".callTrump"} was cancelled`); + agHelper.AssertContains("was cancelled"); ee.ExpandCollapseEntity("Queries/JS"); apiPage.CreateAndFillApi("https://catfact.ninja/fact", "CatFacts", 30000); apiPage.ToggleOnPageLoadRun(true); diff --git a/app/client/cypress/integration/Smoke_TestSuite/ServerSideTests/OnLoadTests/OnLoadActions_Spec.ts b/app/client/cypress/integration/Smoke_TestSuite/ServerSideTests/OnLoadTests/OnLoadActions_Spec.ts index 86addcb24d6f..371472ea200b 100644 --- a/app/client/cypress/integration/Smoke_TestSuite/ServerSideTests/OnLoadTests/OnLoadActions_Spec.ts +++ b/app/client/cypress/integration/Smoke_TestSuite/ServerSideTests/OnLoadTests/OnLoadActions_Spec.ts @@ -1,6 +1,4 @@ import { ObjectsRegistry } from "../../../../support/Objects/Registry"; - -let dsl: any; const agHelper = ObjectsRegistry.AggregateHelper, ee = ObjectsRegistry.EntityExplorer, apiPage = ObjectsRegistry.ApiPage, @@ -9,14 +7,18 @@ const agHelper = ObjectsRegistry.AggregateHelper, deployMode = ObjectsRegistry.DeployMode; describe("Layout OnLoad Actions tests", function() { - before(() => { + beforeEach(() => { + agHelper.RestoreLocalStorageCache(); + }); + + afterEach(() => { + agHelper.SaveLocalStorageCache(); + }); + + it.only("1. Bug 8595: OnPageLoad execution - when No api to run on Pageload", function() { cy.fixture("onPageLoadActionsDsl").then((val: any) => { agHelper.AddDsl(val); - dsl = val; }); - }); - - it("1. Bug 8595: OnPageLoad execution - when No api to run on Pageload", function() { ee.SelectEntityByName("Widgets"); ee.SelectEntityByName("Page1"); cy.url().then((url) => { @@ -35,7 +37,9 @@ describe("Layout OnLoad Actions tests", function() { }); it("2. Bug 8595: OnPageLoad execution - when Query Parmas added via Params tab", function() { - agHelper.AddDsl(dsl, locator._imageWidget); + cy.fixture("onPageLoadActionsDsl").then((val: any) => { + agHelper.AddDsl(val, locator._imageWidget); + }); apiPage.CreateAndFillApi( "https://source.unsplash.com/collection/1599413", "RandomFlora", @@ -174,7 +178,8 @@ describe("Layout OnLoad Actions tests", function() { apiPage.CreateAndFillApi( "https://api.genderize.io?name={{RandomUser.data.results[0].name.first}}", - "Genderize", 30000 + "Genderize", + 30000, ); apiPage.ValidateQueryParams({ key: "name", diff --git a/app/client/cypress/support/Objects/CommonLocators.ts b/app/client/cypress/support/Objects/CommonLocators.ts index 0627e79a9c1b..882e1839687d 100644 --- a/app/client/cypress/support/Objects/CommonLocators.ts +++ b/app/client/cypress/support/Objects/CommonLocators.ts @@ -154,4 +154,7 @@ export class CommonLocators { _deployedPage = `.t--page-switch-tab`; _hints = "ul.CodeMirror-hints li"; _cancelActionExecution = ".t--cancel-action-button"; + _dropDownMultiTreeValue = (dropdownOption: string) => + "//span[@class='rc-tree-select-tree-title']/parent::span[@title='" + dropdownOption + "']"; + _dropDownMultiTreeSelect = ".rc-tree-select-multiple" } diff --git a/app/client/cypress/support/Pages/AggregateHelper.ts b/app/client/cypress/support/Pages/AggregateHelper.ts index 9d5ec0876845..1a5fdf049660 100644 --- a/app/client/cypress/support/Pages/AggregateHelper.ts +++ b/app/client/cypress/support/Pages/AggregateHelper.ts @@ -60,8 +60,8 @@ export class AggregateHelper { dsl: string, elementToCheckPresenceaftDslLoad: string | "" = "", ) { - let pageid: string; - let layoutId; + let pageid: string, layoutId, appId: string | null; + appId = localStorage.getItem("applicationId"); cy.url().then((url) => { pageid = url .split("/")[5] @@ -75,7 +75,12 @@ export class AggregateHelper { // Dumping the DSL to the created page cy.request( "PUT", - "api/v1/layouts/" + layoutId + "/pages/" + pageid, + "api/v1/layouts/" + + layoutId + + "/pages/" + + pageid + + "?applicationId=" + + appId, dsl, ).then((dslDumpResp) => { //cy.log("Pages resposne is : " + dslDumpResp.body); @@ -136,9 +141,10 @@ export class AggregateHelper { public GetElement(selector: ElementType, timeout = 20000) { let locator; if (typeof selector == "string") { - locator = selector.startsWith("//") || selector.startsWith("(//") - ? cy.xpath(selector, { timeout: timeout }) - : cy.get(selector, { timeout: timeout }); + locator = + selector.startsWith("//") || selector.startsWith("(//") + ? cy.xpath(selector, { timeout: timeout }) + : cy.get(selector, { timeout: timeout }); } else locator = cy.wrap(selector); return locator; } @@ -309,6 +315,11 @@ export class AggregateHelper { this.Sleep(); //for selected value to reflect! } + public SelectFromMutliTree(dropdownOption: string) { + this.GetNClick(this.locator._dropDownMultiTreeSelect); + this.GetNClick(this.locator._dropDownMultiTreeValue(dropdownOption)); + } + public SelectFromDropDown( dropdownOption: string, insideParent = "", diff --git a/app/client/cypress/support/Pages/EntityExplorer.ts b/app/client/cypress/support/Pages/EntityExplorer.ts index 24639195adb0..06abc9646f9d 100644 --- a/app/client/cypress/support/Pages/EntityExplorer.ts +++ b/app/client/cypress/support/Pages/EntityExplorer.ts @@ -162,7 +162,7 @@ export class EntityExplorer { this.agHelper.Sleep(500); } - public DragDropWidgetNVerify(widgetType: string, x: number, y: number) { + public DragDropWidgetNVerify(widgetType: string, x: number = 200, y: number =200) { this.NavigateToSwitcher("widgets"); this.agHelper.Sleep(); cy.get(this.locator._widgetPageIcon(widgetType)) diff --git a/app/client/cypress/support/Pages/JSEditor.ts b/app/client/cypress/support/Pages/JSEditor.ts index bf465bf94962..5165c44790c4 100644 --- a/app/client/cypress/support/Pages/JSEditor.ts +++ b/app/client/cypress/support/Pages/JSEditor.ts @@ -83,6 +83,10 @@ export class JSEditor { "')]//*[contains(text(),'" + jsFuncName + "')]"; + _dialogInDeployView = + "//div[@class='bp3-dialog-body']//*[contains(text(), '" + + Cypress.env("MESSAGES").QUERY_CONFIRMATION_MODAL_MESSAGE() + + "')]"; _funcDropdown = ".t--formActionButtons div[role='listbox']"; _funcDropdownOptions = ".ads-dropdown-options-wrapper div > span div"; _getJSFunctionSettingsId = (JSFunctionName: string) =>
186d9934e8b584bd1e002aaa041316b7011153a0
2024-01-17 21:09:44
Anagh Hegde
fix: Queries do not get exported in a git connected app, by using partial export. (#30368)
false
Queries do not get exported in a git connected app, by using partial export. (#30368)
fix
diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/exports/internal/PartialExportServiceCEImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/exports/internal/PartialExportServiceCEImpl.java index ea103a46be46..80f99d269b9f 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/exports/internal/PartialExportServiceCEImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/exports/internal/PartialExportServiceCEImpl.java @@ -136,7 +136,8 @@ public Mono<ApplicationJson> getPartialExportResources( branchedPageId, partialExportFileDTO.getActionCollectionList(), applicationJson, - mappedResourcesDTO) + mappedResourcesDTO, + branchName) .then(Mono.just(branchedPageId)); } return Mono.just(branchedPageId); @@ -148,7 +149,8 @@ public Mono<ApplicationJson> getPartialExportResources( branchedPageId, partialExportFileDTO.getActionList(), applicationJson, - mappedResourcesDTO) + mappedResourcesDTO, + branchName) .then(Mono.just(branchedPageId)); } return Mono.just(branchedPageId); @@ -212,11 +214,17 @@ private Mono<ApplicationJson> exportActions( String pageId, List<String> validActions, ApplicationJson applicationJson, - MappedExportableResourcesDTO mappedResourcesDTO) { + MappedExportableResourcesDTO mappedResourcesDTO, + String branchName) { return newActionService.findByPageId(pageId).collectList().flatMap(actions -> { + // For git connected app, the filtering has to be done on the default action id + // since the client is not aware of the branched resource id List<NewAction> updatedActionList = actions.stream() - .filter(action -> validActions.contains(action.getId())) + .filter(action -> branchName != null + ? validActions.contains(action.getDefaultResources().getActionId()) + : validActions.contains(action.getId())) .toList(); + // Map name to id for exportable entities newActionExportableService.mapNameToIdForExportableEntities(mappedResourcesDTO, updatedActionList); // Make it exportable by removing the ids @@ -232,10 +240,16 @@ private Mono<ApplicationJson> exportActionCollections( String pageId, List<String> validActions, ApplicationJson applicationJson, - MappedExportableResourcesDTO mappedResourcesDTO) { + MappedExportableResourcesDTO mappedResourcesDTO, + String branchName) { return actionCollectionService.findByPageId(pageId).collectList().flatMap(actionCollections -> { + // For git connected app, the filtering has to be done on the default actionCollection id + // since the client is not aware of the branched resource id List<ActionCollection> updatedActionCollectionList = actionCollections.stream() - .filter(actionCollection -> validActions.contains(actionCollection.getId())) + .filter(actionCollection -> branchName != null + ? validActions.contains( + actionCollection.getDefaultResources().getCollectionId()) + : validActions.contains(actionCollection.getId())) .toList(); // Map name to id for exportable entities actionCollectionExportableService.mapNameToIdForExportableEntities( diff --git a/app/server/appsmith-server/src/test/java/com/appsmith/server/services/PartialExportServiceTest.java b/app/server/appsmith-server/src/test/java/com/appsmith/server/services/PartialExportServiceTest.java index 8bebe5e3c2bf..ed40c09bc0d3 100644 --- a/app/server/appsmith-server/src/test/java/com/appsmith/server/services/PartialExportServiceTest.java +++ b/app/server/appsmith-server/src/test/java/com/appsmith/server/services/PartialExportServiceTest.java @@ -340,4 +340,75 @@ public void testGetPartialExport_gitConnectedApp_branchResourceExported() { }) .verifyComplete(); } + + @Test + @WithUserDetails(value = "api_user") + public void testGetPartialExport_gitConnectedApp_featureBranchResourceExported() { + Mockito.when(pluginService.findAllByIdsWithoutPermission(Mockito.any(), Mockito.anyList())) + .thenReturn(Flux.fromIterable(List.of(installedPlugin, installedJsPlugin))); + + Application application = + createGitConnectedApp("testGetPartialExport_gitConnectedApp_featureBranchResourceExported"); + + // update git branch name for page + PageDTO savedPage = new PageDTO(); + savedPage.setName("Page 2"); + savedPage.setApplicationId(application.getId()); + DefaultResources defaultResources = new DefaultResources(); + defaultResources.setApplicationId(application.getId()); + defaultResources.setBranchName("master"); + savedPage.setDefaultResources(defaultResources); + savedPage = applicationPageService + .createPageWithBranchName(savedPage, "master") + .block(); + + // Create Action + ActionDTO action = new ActionDTO(); + action.setName("validAction"); + action.setPageId(savedPage.getId()); + action.setExecuteOnLoad(true); + ActionConfiguration actionConfiguration = new ActionConfiguration(); + actionConfiguration.setHttpMethod(HttpMethod.GET); + actionConfiguration.setTimeoutInMillisecond("6000"); + action.setActionConfiguration(actionConfiguration); + action.setDatasource(datasourceMap.get("DS1")); + DefaultResources defaultResource = new DefaultResources(); + defaultResource.setApplicationId(application.getId()); + defaultResource.setBranchName("master"); + defaultResource.setActionId("testActionId"); + action.setDefaultResources(defaultResource); + + ActionDTO savedAction = + layoutActionService.createSingleAction(action, Boolean.FALSE).block(); + + PartialExportFileDTO partialExportFileDTO = new PartialExportFileDTO(); + partialExportFileDTO.setDatasourceList(List.of( + datasourceMap.get("DS1").getId(), datasourceMap.get("DS2").getId())); + // For a feature branch the resources in the client always get the default resource id + partialExportFileDTO.setActionList(List.of("testActionId")); + + // Get the partial export resources + Mono<ApplicationJson> partialExportFileDTOMono = partialExportService.getPartialExportResources( + application.getId(), savedPage.getId(), "master", partialExportFileDTO); + + StepVerifier.create(partialExportFileDTOMono) + .assertNext(applicationJson -> { + assertThat(applicationJson.getDatasourceList().size()).isEqualTo(2); + List<String> dsNames = applicationJson.getDatasourceList().stream() + .map(DatasourceStorage::getName) + .toList(); + assertThat(dsNames).containsAll(List.of("DS1", "DS2")); + assertThat(applicationJson.getDatasourceList().get(0).getPluginId()) + .isEqualTo("installed-plugin"); + assertThat(applicationJson.getDatasourceList().get(1).getPluginId()) + .isEqualTo("installed-plugin"); + assertThat(applicationJson.getActionList().size()).isEqualTo(1); + + NewAction newAction = applicationJson.getActionList().get(0); + assertThat(newAction.getUnpublishedAction().getName()).isEqualTo("validAction"); + assertThat(newAction.getUnpublishedAction().getPageId()).isEqualTo("Page 2"); + assertThat(newAction.getId()).isEqualTo("Page 2_validAction"); + }) + .verifyComplete(); + } }
a411e27b46a392ff060f263bf286e6db5149814c
2023-12-18 13:07:03
sharanya-appsmith
test: Cypress - added tag- @tag.Binding (#29679)
false
Cypress - added tag- @tag.Binding (#29679)
test
diff --git a/app/client/cypress/e2e/Regression/ClientSide/OneClickBinding/JSONFormWidget/ConnectToWidget_spec.ts b/app/client/cypress/e2e/Regression/ClientSide/OneClickBinding/JSONFormWidget/ConnectToWidget_spec.ts index 2f4a4d9e6352..655f816a81ae 100644 --- a/app/client/cypress/e2e/Regression/ClientSide/OneClickBinding/JSONFormWidget/ConnectToWidget_spec.ts +++ b/app/client/cypress/e2e/Regression/ClientSide/OneClickBinding/JSONFormWidget/ConnectToWidget_spec.ts @@ -17,90 +17,100 @@ import PageList from "../../../../../support/Pages/PageList"; const oneClickBinding = new OneClickBinding(); -describe("JSONForm widget one click binding feature", () => { - let datasourceName: string; +describe( + "JSONForm widget one click binding feature", + { tags: ["@tag.Binding"] }, + () => { + let datasourceName: string; + + it("1.Connect to a table widget", () => { + entityExplorer.DragDropWidgetNVerify(draggableWidgets.TABLE, 200, 200); + entityExplorer.DragDropWidgetNVerify(draggableWidgets.JSONFORM, 600, 400); + + dataSources.CreateDataSource("Postgres"); + + cy.get("@dsName").then((dsName) => { + datasourceName = dsName as unknown as string; + + EditorNavigation.SelectEntityByName("Table1", EntityType.Widget); + + oneClickBinding.ChooseAndAssertForm( + `${datasourceName}`, + datasourceName, + "public.employees", + { + searchableColumn: "first_name", + }, + ); + }); - it("1.Connect to a table widget", () => { - entityExplorer.DragDropWidgetNVerify(draggableWidgets.TABLE, 200, 200); - entityExplorer.DragDropWidgetNVerify(draggableWidgets.JSONFORM, 600, 400); + agHelper.GetNClick(oneClickBindingLocator.connectData); - dataSources.CreateDataSource("Postgres"); + assertHelper.AssertNetworkStatus("@postExecute"); - cy.get("@dsName").then((dsName) => { - datasourceName = dsName as unknown as string; + agHelper.Sleep(2000); - EditorNavigation.SelectEntityByName("Table1", EntityType.Widget); + EditorNavigation.SelectEntityByName("JSONForm1", EntityType.Widget); - oneClickBinding.ChooseAndAssertForm( - `${datasourceName}`, - datasourceName, - "public.employees", - { - searchableColumn: "first_name", - }, + agHelper.GetNClick(oneClickBindingLocator.datasourceDropdownSelector); + agHelper.GetNClick( + oneClickBindingLocator.datasourceQuerySelector("Table1"), ); - }); - - agHelper.GetNClick(oneClickBindingLocator.connectData); - - assertHelper.AssertNetworkStatus("@postExecute"); - agHelper.Sleep(2000); + agHelper.Sleep(2000); - EditorNavigation.SelectEntityByName("JSONForm1", EntityType.Widget); + table.SelectTableRow(0, 1, true, "v2"); - agHelper.GetNClick(oneClickBindingLocator.datasourceDropdownSelector); - agHelper.GetNClick( - oneClickBindingLocator.datasourceQuerySelector("Table1"), - ); - - agHelper.Sleep(2000); + table.ReadTableRowColumnData(0, 1, "v2").then((cellData) => { + agHelper + .GetText(locators._jsonFormInputField("last_name"), "val") + .should("be.equal", cellData); + }); - table.SelectTableRow(0, 1, true, "v2"); + agHelper.GetNClick(locators._jsonFormSubmitBtn, 0, true); - table.ReadTableRowColumnData(0, 1, "v2").then((cellData) => { - agHelper - .GetText(locators._jsonFormInputField("last_name"), "val") - .should("be.equal", cellData); + agHelper.AssertElementVisibility(locators._toastMsg); + agHelper.AssertElementVisibility( + locators._specificToast( + "onSubmit event is not configured for JSONForm1", + ), + ); }); - agHelper.GetNClick(locators._jsonFormSubmitBtn, 0, true); + it("Connect to a list widget", () => { + PageList.AddNewPage("New blank page"); - agHelper.AssertElementVisibility(locators._toastMsg); - agHelper.AssertElementVisibility( - locators._specificToast("onSubmit event is not configured for JSONForm1"), - ); - }); + entityExplorer.DragDropWidgetNVerify(draggableWidgets.LIST_V2, 200, 200); + entityExplorer.DragDropWidgetNVerify(draggableWidgets.JSONFORM, 600, 400); - it("Connect to a list widget", () => { - PageList.AddNewPage("New blank page"); - - entityExplorer.DragDropWidgetNVerify(draggableWidgets.LIST_V2, 200, 200); - entityExplorer.DragDropWidgetNVerify(draggableWidgets.JSONFORM, 600, 400); - - agHelper.GetNClick(oneClickBindingLocator.datasourceDropdownSelector); - agHelper.GetNClick(oneClickBindingLocator.datasourceQuerySelector("List1")); + agHelper.GetNClick(oneClickBindingLocator.datasourceDropdownSelector); + agHelper.GetNClick( + oneClickBindingLocator.datasourceQuerySelector("List1"), + ); - agHelper.Sleep(2000); + agHelper.Sleep(2000); - EditorNavigation.SelectEntityByName("List1", EntityType.Widget); + EditorNavigation.SelectEntityByName("List1", EntityType.Widget); - propPane.UpdatePropertyFieldValue("Default selected item", "001"); + propPane.UpdatePropertyFieldValue("Default selected item", "001"); - agHelper - .GetText(locators._jsonFormInputField("name"), "val") - .then((text) => { - agHelper.Sleep(500); - agHelper.GetText(".t--widget-textwidget span", "text").then((val) => { - expect(val).to.eq(text); + agHelper + .GetText(locators._jsonFormInputField("name"), "val") + .then((text) => { + agHelper.Sleep(500); + agHelper.GetText(".t--widget-textwidget span", "text").then((val) => { + expect(val).to.eq(text); + }); }); - }); - agHelper.GetNClick(locators._jsonFormSubmitBtn, 0, true); + agHelper.GetNClick(locators._jsonFormSubmitBtn, 0, true); - agHelper.AssertElementVisibility(locators._toastMsg); - agHelper.AssertElementVisibility( - locators._specificToast("onSubmit event is not configured for JSONForm1"), - ); - }); -}); + agHelper.AssertElementVisibility(locators._toastMsg); + agHelper.AssertElementVisibility( + locators._specificToast( + "onSubmit event is not configured for JSONForm1", + ), + ); + }); + }, +); diff --git a/app/client/cypress/e2e/Regression/ClientSide/OneClickBinding/JSONFormWidget/FieldConfigModal_spec.ts b/app/client/cypress/e2e/Regression/ClientSide/OneClickBinding/JSONFormWidget/FieldConfigModal_spec.ts index c5645c41593c..5f671a2a19af 100644 --- a/app/client/cypress/e2e/Regression/ClientSide/OneClickBinding/JSONFormWidget/FieldConfigModal_spec.ts +++ b/app/client/cypress/e2e/Regression/ClientSide/OneClickBinding/JSONFormWidget/FieldConfigModal_spec.ts @@ -13,60 +13,64 @@ import EditorNavigation, { const oneClickBinding = new OneClickBinding(); -describe("JSONForm widget one click binding feature", () => { - it("1.tests select/unselect fields for json form widget", () => { - entityExplorer.DragDropWidgetNVerify(draggableWidgets.JSONFORM, 450, 200); +describe( + "JSONForm widget one click binding feature", + { tags: ["@tag.Binding"] }, + () => { + it("1.tests select/unselect fields for json form widget", () => { + entityExplorer.DragDropWidgetNVerify(draggableWidgets.JSONFORM, 450, 200); - dataSources.CreateDataSource("Postgres"); + dataSources.CreateDataSource("Postgres"); - cy.get("@dsName").then((dsName) => { - EditorNavigation.SelectEntityByName("JSONForm1", EntityType.Widget); + cy.get("@dsName").then((dsName) => { + EditorNavigation.SelectEntityByName("JSONForm1", EntityType.Widget); - oneClickBinding.ChooseAndAssertForm( - `${dsName}`, - dsName, - "public.employees", - ); - }); + oneClickBinding.ChooseAndAssertForm( + `${dsName}`, + dsName, + "public.employees", + ); + }); - // Open the column selector modal - agHelper.GetNClick(oneClickBindingLocator.columnSelectorModalTrigger); + // Open the column selector modal + agHelper.GetNClick(oneClickBindingLocator.columnSelectorModalTrigger); - // Assert that the primary column is unchecked - agHelper.AssertAttribute( - oneClickBindingLocator.checkBox, - "data-checked", - "false", - ); + // Assert that the primary column is unchecked + agHelper.AssertAttribute( + oneClickBindingLocator.checkBox, + "data-checked", + "false", + ); - // Deselect some columns - const deselectColumns = ["title_of_courtesy", "birth_date", "hire_date"]; + // Deselect some columns + const deselectColumns = ["title_of_courtesy", "birth_date", "hire_date"]; - deselectColumns.forEach((column) => { - agHelper.GetNClick( - oneClickBindingLocator.columnSelectorField(column), - 0, - true, - ); - }); + deselectColumns.forEach((column) => { + agHelper.GetNClick( + oneClickBindingLocator.columnSelectorField(column), + 0, + true, + ); + }); - // Save the column selection - agHelper.GetNClick(oneClickBindingLocator.columnselectorModalSaveBtn); + // Save the column selection + agHelper.GetNClick(oneClickBindingLocator.columnselectorModalSaveBtn); - agHelper.GetNClick(oneClickBindingLocator.connectData); + agHelper.GetNClick(oneClickBindingLocator.connectData); - agHelper.Sleep(2000); + agHelper.Sleep(2000); - const selectedColumns = ["last_name", "first_name", "title"]; + const selectedColumns = ["last_name", "first_name", "title"]; - // Assert that the selected columns are present in the form - selectedColumns.forEach((column) => { - agHelper.AssertElementExist(locators._draggableFieldConfig(column)); - }); + // Assert that the selected columns are present in the form + selectedColumns.forEach((column) => { + agHelper.AssertElementExist(locators._draggableFieldConfig(column)); + }); - // Assert that the deselected columns are not present in the form - deselectColumns.forEach((column) => { - agHelper.AssertElementAbsence(locators._draggableFieldConfig(column)); + // Assert that the deselected columns are not present in the form + deselectColumns.forEach((column) => { + agHelper.AssertElementAbsence(locators._draggableFieldConfig(column)); + }); }); - }); -}); + }, +); diff --git a/app/client/cypress/e2e/Regression/ClientSide/OneClickBinding/JSONFormWidget/mongoDb_spec.ts b/app/client/cypress/e2e/Regression/ClientSide/OneClickBinding/JSONFormWidget/mongoDb_spec.ts index b0d50a7d7fcf..1c9184f7f8bc 100644 --- a/app/client/cypress/e2e/Regression/ClientSide/OneClickBinding/JSONFormWidget/mongoDb_spec.ts +++ b/app/client/cypress/e2e/Regression/ClientSide/OneClickBinding/JSONFormWidget/mongoDb_spec.ts @@ -16,120 +16,124 @@ import PageList from "../../../../../support/Pages/PageList"; const oneClickBinding = new OneClickBinding(); -describe("JSONForm widget one click binding feature", () => { - let datasourceName: string; - it("1.Create flow: should check that queries are created and bound to jsonform widget properly", () => { - entityExplorer.DragDropWidgetNVerify(draggableWidgets.JSONFORM, 450, 200); +describe( + "JSONForm widget one click binding feature", + { tags: ["@tag.Binding"] }, + () => { + let datasourceName: string; + it("1.Create flow: should check that queries are created and bound to jsonform widget properly", () => { + entityExplorer.DragDropWidgetNVerify(draggableWidgets.JSONFORM, 450, 200); + + dataSources.CreateDataSource("Mongo"); + + cy.get("@dsName").then((dsName) => { + datasourceName = dsName as unknown as string; + + EditorNavigation.SelectEntityByName("JSONForm1", EntityType.Widget); + + oneClickBinding.ChooseAndAssertForm( + `${datasourceName}`, + datasourceName, + "netflix", + { + formType: "Create records", + }, + ); + }); + + agHelper.GetNClick(oneClickBindingLocator.connectData); + + agHelper.Sleep(2000); + + const columns = [ + "contentRating", + "contentType", + "creator", + "description", + "director", + "genre", + "name", + "numberOfSeasons", + "releasedDate", + "seasonStartDate", + "url", + ]; + + columns.forEach((column) => { + agHelper.AssertElementExist(locators._draggableFieldConfig(column)); + }); + }); - dataSources.CreateDataSource("Mongo"); + it("2.Update flow: should check that queries are created and bound to table jsonform widget properly ", () => { + PageList.AddNewPage("New blank page"); - cy.get("@dsName").then((dsName) => { - datasourceName = dsName as unknown as string; + entityExplorer.DragDropWidgetNVerify(draggableWidgets.TABLE, 200, 200); + entityExplorer.DragDropWidgetNVerify(draggableWidgets.JSONFORM, 600, 400); - EditorNavigation.SelectEntityByName("JSONForm1", EntityType.Widget); + EditorNavigation.SelectEntityByName("Table1", EntityType.Widget); oneClickBinding.ChooseAndAssertForm( `${datasourceName}`, datasourceName, "netflix", { - formType: "Create records", + searchableColumn: "creator", }, ); - }); - - agHelper.GetNClick(oneClickBindingLocator.connectData); - - agHelper.Sleep(2000); - - const columns = [ - "contentRating", - "contentType", - "creator", - "description", - "director", - "genre", - "name", - "numberOfSeasons", - "releasedDate", - "seasonStartDate", - "url", - ]; - - columns.forEach((column) => { - agHelper.AssertElementExist(locators._draggableFieldConfig(column)); - }); - }); - it("2.Update flow: should check that queries are created and bound to table jsonform widget properly ", () => { - PageList.AddNewPage("New blank page"); + agHelper.GetNClick(oneClickBindingLocator.connectData); - entityExplorer.DragDropWidgetNVerify(draggableWidgets.TABLE, 200, 200); - entityExplorer.DragDropWidgetNVerify(draggableWidgets.JSONFORM, 600, 400); + assertHelper.AssertNetworkStatus("@postExecute"); - EditorNavigation.SelectEntityByName("Table1", EntityType.Widget); + agHelper.Sleep(2000); - oneClickBinding.ChooseAndAssertForm( - `${datasourceName}`, - datasourceName, - "netflix", - { - searchableColumn: "creator", - }, - ); - - agHelper.GetNClick(oneClickBindingLocator.connectData); - - assertHelper.AssertNetworkStatus("@postExecute"); - - agHelper.Sleep(2000); + EditorNavigation.SelectEntityByName("JSONForm1", EntityType.Widget); - EditorNavigation.SelectEntityByName("JSONForm1", EntityType.Widget); + oneClickBinding.ChooseAndAssertForm( + `${datasourceName}`, + datasourceName, + "netflix", + { + formType: "Edit records", + defaultValues: "Table1", + dataIdentifier: "id", + }, + ); - oneClickBinding.ChooseAndAssertForm( - `${datasourceName}`, - datasourceName, - "netflix", - { - formType: "Edit records", - defaultValues: "Table1", - dataIdentifier: "id", - }, - ); + agHelper.GetNClick(oneClickBindingLocator.connectData); - agHelper.GetNClick(oneClickBindingLocator.connectData); + assertHelper.AssertNetworkStatus("@postExecute"); - assertHelper.AssertNetworkStatus("@postExecute"); + agHelper.Sleep(2000); - agHelper.Sleep(2000); + table.SelectTableRow(0, 3, true, "v2"); - table.SelectTableRow(0, 3, true, "v2"); + table.ReadTableRowColumnData(0, 3, "v2").then((cellData) => { + agHelper + .GetText(locators._jsonFormInputField("creator"), "val") + .should("be.equal", cellData); + }); - table.ReadTableRowColumnData(0, 3, "v2").then((cellData) => { + agHelper + .GetElement(locators._jsonFormInputField("creator")) + .clear() + .type("Doe"); agHelper .GetText(locators._jsonFormInputField("creator"), "val") - .should("be.equal", cellData); - }); - - agHelper - .GetElement(locators._jsonFormInputField("creator")) - .clear() - .type("Doe"); - agHelper - .GetText(locators._jsonFormInputField("creator"), "val") - .should("be.equal", "Doe"); + .should("be.equal", "Doe"); - agHelper.GetNClick(locators._jsonFormSubmitBtn, 0, true); + agHelper.GetNClick(locators._jsonFormSubmitBtn, 0, true); - agHelper.Sleep(2000); + agHelper.Sleep(2000); - // reloading because we don't create select query with json form, so we need to reload the page to get the updated data - cy.reload(); + // reloading because we don't create select query with json form, so we need to reload the page to get the updated data + cy.reload(); - EditorNavigation.SelectEntityByName("Table1", EntityType.Widget); + EditorNavigation.SelectEntityByName("Table1", EntityType.Widget); - table.ReadTableRowColumnData(0, 3, "v2").then((cellData) => { - expect(cellData).to.eq("Doe"); + table.ReadTableRowColumnData(0, 3, "v2").then((cellData) => { + expect(cellData).to.eq("Doe"); + }); }); - }); -}); + }, +); diff --git a/app/client/cypress/e2e/Regression/ClientSide/OneClickBinding/JSONFormWidget/postgres_spec.ts b/app/client/cypress/e2e/Regression/ClientSide/OneClickBinding/JSONFormWidget/postgres_spec.ts index 6d81681da555..4cbaa5c18db6 100644 --- a/app/client/cypress/e2e/Regression/ClientSide/OneClickBinding/JSONFormWidget/postgres_spec.ts +++ b/app/client/cypress/e2e/Regression/ClientSide/OneClickBinding/JSONFormWidget/postgres_spec.ts @@ -16,115 +16,119 @@ import PageList from "../../../../../support/Pages/PageList"; const oneClickBinding = new OneClickBinding(); -describe("JSONForm widget one click binding feature", () => { - let datasourceName: string; - it("1.Create flow: should check that queries are created and bound to table jsonform widget properly ", () => { - entityExplorer.DragDropWidgetNVerify(draggableWidgets.JSONFORM, 450, 200); +describe( + "JSONForm widget one click binding feature", + { tags: ["@tag.Binding"] }, + () => { + let datasourceName: string; + it("1.Create flow: should check that queries are created and bound to table jsonform widget properly ", () => { + entityExplorer.DragDropWidgetNVerify(draggableWidgets.JSONFORM, 450, 200); + + dataSources.CreateDataSource("Postgres"); + + cy.get("@dsName").then((dsName) => { + datasourceName = dsName as unknown as string; + + EditorNavigation.SelectEntityByName("JSONForm1", EntityType.Widget); + + oneClickBinding.ChooseAndAssertForm( + `${datasourceName}`, + datasourceName, + "public.employees", + { + formType: "Create records", + }, + ); + }); + + agHelper.GetNClick(oneClickBindingLocator.connectData); + + agHelper.Sleep(2000); + + const columns = [ + "last_name", + "first_name", + "title", + "title_of_courtesy", + "birth_date", + "hire_date", + ]; + + columns.forEach((column) => { + agHelper.AssertElementExist(locators._draggableFieldConfig(column)); + }); + }); - dataSources.CreateDataSource("Postgres"); + it("2.Update flow: should check that queries are created and bound to table jsonform widget properly ", () => { + PageList.AddNewPage("New blank page"); - cy.get("@dsName").then((dsName) => { - datasourceName = dsName as unknown as string; + entityExplorer.DragDropWidgetNVerify(draggableWidgets.TABLE, 200, 200); + entityExplorer.DragDropWidgetNVerify(draggableWidgets.JSONFORM, 600, 400); - EditorNavigation.SelectEntityByName("JSONForm1", EntityType.Widget); + EditorNavigation.SelectEntityByName("Table1", EntityType.Widget); oneClickBinding.ChooseAndAssertForm( `${datasourceName}`, datasourceName, "public.employees", { - formType: "Create records", + searchableColumn: "first_name", }, ); - }); - - agHelper.GetNClick(oneClickBindingLocator.connectData); - - agHelper.Sleep(2000); - - const columns = [ - "last_name", - "first_name", - "title", - "title_of_courtesy", - "birth_date", - "hire_date", - ]; - - columns.forEach((column) => { - agHelper.AssertElementExist(locators._draggableFieldConfig(column)); - }); - }); - - it("2.Update flow: should check that queries are created and bound to table jsonform widget properly ", () => { - PageList.AddNewPage("New blank page"); - - entityExplorer.DragDropWidgetNVerify(draggableWidgets.TABLE, 200, 200); - entityExplorer.DragDropWidgetNVerify(draggableWidgets.JSONFORM, 600, 400); - - EditorNavigation.SelectEntityByName("Table1", EntityType.Widget); - oneClickBinding.ChooseAndAssertForm( - `${datasourceName}`, - datasourceName, - "public.employees", - { - searchableColumn: "first_name", - }, - ); + agHelper.GetNClick(oneClickBindingLocator.connectData); - agHelper.GetNClick(oneClickBindingLocator.connectData); + assertHelper.AssertNetworkStatus("@postExecute"); - assertHelper.AssertNetworkStatus("@postExecute"); + agHelper.Sleep(2000); - agHelper.Sleep(2000); + EditorNavigation.SelectEntityByName("JSONForm1", EntityType.Widget); - EditorNavigation.SelectEntityByName("JSONForm1", EntityType.Widget); + oneClickBinding.ChooseAndAssertForm( + `${datasourceName}`, + datasourceName, + "public.employees", + { + formType: "Edit records", + defaultValues: "Table1", + dataIdentifier: "id", + }, + ); - oneClickBinding.ChooseAndAssertForm( - `${datasourceName}`, - datasourceName, - "public.employees", - { - formType: "Edit records", - defaultValues: "Table1", - dataIdentifier: "id", - }, - ); + agHelper.GetNClick(oneClickBindingLocator.connectData); - agHelper.GetNClick(oneClickBindingLocator.connectData); + assertHelper.AssertNetworkStatus("@postExecute"); - assertHelper.AssertNetworkStatus("@postExecute"); + agHelper.Sleep(2000); - agHelper.Sleep(2000); + table.SelectTableRow(0, 1, true, "v2"); - table.SelectTableRow(0, 1, true, "v2"); + table.ReadTableRowColumnData(0, 1, "v2").then((cellData) => { + agHelper + .GetText(locators._jsonFormInputField("last_name"), "val") + .should("be.equal", cellData); + }); - table.ReadTableRowColumnData(0, 1, "v2").then((cellData) => { + agHelper + .GetElement(locators._jsonFormInputField("last_name")) + .clear() + .type("Doe"); agHelper .GetText(locators._jsonFormInputField("last_name"), "val") - .should("be.equal", cellData); - }); - - agHelper - .GetElement(locators._jsonFormInputField("last_name")) - .clear() - .type("Doe"); - agHelper - .GetText(locators._jsonFormInputField("last_name"), "val") - .should("be.equal", "Doe"); + .should("be.equal", "Doe"); - agHelper.GetNClick(locators._jsonFormSubmitBtn, 0, true); + agHelper.GetNClick(locators._jsonFormSubmitBtn, 0, true); - agHelper.Sleep(2000); + agHelper.Sleep(2000); - // reloading because we don't create select query with json form, so we need to reload the page to get the updated data - cy.reload(); + // reloading because we don't create select query with json form, so we need to reload the page to get the updated data + cy.reload(); - EditorNavigation.SelectEntityByName("Table1", EntityType.Widget); + EditorNavigation.SelectEntityByName("Table1", EntityType.Widget); - table.ReadTableRowColumnData(0, 1, "v2").then((cellData) => { - expect(cellData).to.eq("Doe"); + table.ReadTableRowColumnData(0, 1, "v2").then((cellData) => { + expect(cellData).to.eq("Doe"); + }); }); - }); -}); + }, +); diff --git a/app/client/cypress/e2e/Regression/ClientSide/OneClickBinding/MultiSelectWidget/mongoDB_spec.ts b/app/client/cypress/e2e/Regression/ClientSide/OneClickBinding/MultiSelectWidget/mongoDB_spec.ts index e2caefdf59b6..acc388fb74cc 100644 --- a/app/client/cypress/e2e/Regression/ClientSide/OneClickBinding/MultiSelectWidget/mongoDB_spec.ts +++ b/app/client/cypress/e2e/Regression/ClientSide/OneClickBinding/MultiSelectWidget/mongoDB_spec.ts @@ -16,80 +16,84 @@ import EditorNavigation, { const oneClickBinding = new OneClickBinding(); -describe("Table widget one click binding feature", () => { - it("should check that queries are created and bound to table widget properly", () => { - entityExplorer.DragDropWidgetNVerify( - draggableWidgets.MULTISELECT, - 450, - 200, - ); - - dataSources.CreateDataSource("Mongo"); - - cy.get("@dsName").then((dsName) => { - EditorNavigation.SelectEntityByName("MultiSelect1", EntityType.Widget); - - oneClickBinding.ChooseAndAssertForm(`${dsName}`, dsName, "netflix", { - label: "name", - value: "director", +describe( + "Table widget one click binding feature", + { tags: ["@tag.Binding"] }, + () => { + it("should check that queries are created and bound to table widget properly", () => { + entityExplorer.DragDropWidgetNVerify( + draggableWidgets.MULTISELECT, + 450, + 200, + ); + + dataSources.CreateDataSource("Mongo"); + + cy.get("@dsName").then((dsName) => { + EditorNavigation.SelectEntityByName("MultiSelect1", EntityType.Widget); + + oneClickBinding.ChooseAndAssertForm(`${dsName}`, dsName, "netflix", { + label: "name", + value: "director", + }); }); - }); - agHelper.GetNClick(oneClickBindingLocator.connectData); - - assertHelper.AssertNetworkStatus("@postExecute"); - - agHelper.Sleep(2000); - - entityExplorer.DragDropWidgetNVerify(draggableWidgets.TEXT, 450, 500); - - propPane.UpdatePropertyFieldValue( - "Text", - `{{MultiSelect1.selectedOptionLabels.toString()}}:{{MultiSelect1.selectedOptionValues.toString()}}`, - ); - - [ - { - label: "I Care a Lot", - text: "I Care a Lot:J Blakeson", - }, - { - label: "tick, tick...BOOM!", - text: "I Care a Lot,tick, tick...BOOM!:J Blakeson,Lin-Manuel Miranda", - }, - { - label: "Munich – The Edge of War", - text: "I Care a Lot,tick, tick...BOOM!,Munich – The Edge of War:J Blakeson,Lin-Manuel Miranda,Christian Schwochow", - }, - ].forEach((d) => { - cy.get(formWidgetsPage.multiSelectWidget) - .find(".rc-select-selector") - .click({ + agHelper.GetNClick(oneClickBindingLocator.connectData); + + assertHelper.AssertNetworkStatus("@postExecute"); + + agHelper.Sleep(2000); + + entityExplorer.DragDropWidgetNVerify(draggableWidgets.TEXT, 450, 500); + + propPane.UpdatePropertyFieldValue( + "Text", + `{{MultiSelect1.selectedOptionLabels.toString()}}:{{MultiSelect1.selectedOptionValues.toString()}}`, + ); + + [ + { + label: "I Care a Lot", + text: "I Care a Lot:J Blakeson", + }, + { + label: "tick, tick...BOOM!", + text: "I Care a Lot,tick, tick...BOOM!:J Blakeson,Lin-Manuel Miranda", + }, + { + label: "Munich – The Edge of War", + text: "I Care a Lot,tick, tick...BOOM!,Munich – The Edge of War:J Blakeson,Lin-Manuel Miranda,Christian Schwochow", + }, + ].forEach((d) => { + cy.get(formWidgetsPage.multiSelectWidget) + .find(".rc-select-selector") + .click({ + force: true, + }); + + cy.get(".rc-select-item").contains(d.label).click({ force: true, }); - - cy.get(".rc-select-item").contains(d.label).click({ - force: true, + cy.get(commonlocators.TextInside).first().should("have.text", d.text); }); - cy.get(commonlocators.TextInside).first().should("have.text", d.text); - }); - agHelper.Sleep(2000); + agHelper.Sleep(2000); - cy.get(formWidgetsPage.multiselectWidgetv2search) - .first() - .focus({ force: true } as any) - .type("Haunting", { force: true }); + cy.get(formWidgetsPage.multiselectWidgetv2search) + .first() + .focus({ force: true } as any) + .type("Haunting", { force: true }); - assertHelper.AssertNetworkStatus("@postExecute"); + assertHelper.AssertNetworkStatus("@postExecute"); - agHelper.Sleep(2000); + agHelper.Sleep(2000); - cy.get( - ".rc-select-item-option:contains('The Haunting of Hill House')", - ).should("have.length", 1); - cy.get(".rc-select-item") - .contains("The Haunting of Hill House") - .should("exist"); - }); -}); + cy.get( + ".rc-select-item-option:contains('The Haunting of Hill House')", + ).should("have.length", 1); + cy.get(".rc-select-item") + .contains("The Haunting of Hill House") + .should("exist"); + }); + }, +); diff --git a/app/client/cypress/e2e/Regression/ClientSide/OneClickBinding/MultiSelectWidget/postgres_spec.ts b/app/client/cypress/e2e/Regression/ClientSide/OneClickBinding/MultiSelectWidget/postgres_spec.ts index 8e6f326ab0ca..4c89d87377a3 100644 --- a/app/client/cypress/e2e/Regression/ClientSide/OneClickBinding/MultiSelectWidget/postgres_spec.ts +++ b/app/client/cypress/e2e/Regression/ClientSide/OneClickBinding/MultiSelectWidget/postgres_spec.ts @@ -16,79 +16,83 @@ import EditorNavigation, { const oneClickBinding = new OneClickBinding(); -describe("Table widget one click binding feature", () => { - it("should check that queries are created and bound to table widget properly", () => { - entityExplorer.DragDropWidgetNVerify( - draggableWidgets.MULTISELECT, - 450, - 200, - ); - - dataSources.CreateDataSource("Postgres"); - - cy.get("@dsName").then((dsName) => { - EditorNavigation.SelectEntityByName("MultiSelect1", EntityType.Widget); - - oneClickBinding.ChooseAndAssertForm( - `${dsName}`, - dsName, - "public.employees", - { - label: "first_name", - value: "last_name", - }, +describe( + "Table widget one click binding feature", + { tags: ["@tag.Binding"] }, + () => { + it("should check that queries are created and bound to table widget properly", () => { + entityExplorer.DragDropWidgetNVerify( + draggableWidgets.MULTISELECT, + 450, + 200, + ); + + dataSources.CreateDataSource("Postgres"); + + cy.get("@dsName").then((dsName) => { + EditorNavigation.SelectEntityByName("MultiSelect1", EntityType.Widget); + + oneClickBinding.ChooseAndAssertForm( + `${dsName}`, + dsName, + "public.employees", + { + label: "first_name", + value: "last_name", + }, + ); + }); + + agHelper.GetNClick(oneClickBindingLocator.connectData); + + assertHelper.AssertNetworkStatus("@postExecute"); + + agHelper.Sleep(2000); + + entityExplorer.DragDropWidgetNVerify(draggableWidgets.TEXT, 450, 500); + + propPane.UpdatePropertyFieldValue( + "Text", + `{{MultiSelect1.selectedOptionLabels.toString()}}:{{MultiSelect1.selectedOptionValues.toString()}}`, ); - }); - agHelper.GetNClick(oneClickBindingLocator.connectData); - - assertHelper.AssertNetworkStatus("@postExecute"); - - agHelper.Sleep(2000); - - entityExplorer.DragDropWidgetNVerify(draggableWidgets.TEXT, 450, 500); - - propPane.UpdatePropertyFieldValue( - "Text", - `{{MultiSelect1.selectedOptionLabels.toString()}}:{{MultiSelect1.selectedOptionValues.toString()}}`, - ); - - [ - { - label: "Andrew", - text: "Andrew:Fuller", - }, - { - label: "Janet", - text: "Andrew,Janet:Fuller,Leverling", - }, - { - label: "Margaret", - text: "Andrew,Janet,Margaret:Fuller,Leverling,Peacock", - }, - ].forEach((d) => { - cy.get(formWidgetsPage.multiSelectWidget) - .find(".rc-select-selector") - .click({ + [ + { + label: "Andrew", + text: "Andrew:Fuller", + }, + { + label: "Janet", + text: "Andrew,Janet:Fuller,Leverling", + }, + { + label: "Margaret", + text: "Andrew,Janet,Margaret:Fuller,Leverling,Peacock", + }, + ].forEach((d) => { + cy.get(formWidgetsPage.multiSelectWidget) + .find(".rc-select-selector") + .click({ + force: true, + }); + + cy.get(".rc-select-item").contains(d.label).click({ force: true, }); - - cy.get(".rc-select-item").contains(d.label).click({ - force: true, + cy.get(commonlocators.TextInside).first().should("have.text", d.text); }); - cy.get(commonlocators.TextInside).first().should("have.text", d.text); - }); - agHelper.Sleep(2000); + agHelper.Sleep(2000); - cy.get(formWidgetsPage.multiSelectWidgetSearch).type("Anne", { - force: true, - }); + cy.get(formWidgetsPage.multiSelectWidgetSearch).type("Anne", { + force: true, + }); - assertHelper.AssertNetworkStatus("@postExecute"); + assertHelper.AssertNetworkStatus("@postExecute"); - agHelper.Sleep(2000); + agHelper.Sleep(2000); - cy.get(".rc-select-item").contains("Anne").should("exist"); - }); -}); + cy.get(".rc-select-item").contains("Anne").should("exist"); + }); + }, +); diff --git a/app/client/cypress/e2e/Regression/ClientSide/OneClickBinding/SelectWidget/mongoDB_spec.ts b/app/client/cypress/e2e/Regression/ClientSide/OneClickBinding/SelectWidget/mongoDB_spec.ts index 607840e810fe..1610ab1b941c 100644 --- a/app/client/cypress/e2e/Regression/ClientSide/OneClickBinding/SelectWidget/mongoDB_spec.ts +++ b/app/client/cypress/e2e/Regression/ClientSide/OneClickBinding/SelectWidget/mongoDB_spec.ts @@ -17,81 +17,85 @@ import EditorNavigation, { const oneClickBinding = new OneClickBinding(); -describe("Table widget one click binding feature", () => { - it("should check that queries are created and bound to table widget properly", () => { - entityExplorer.DragDropWidgetNVerify(draggableWidgets.SELECT, 450, 200); +describe( + "Table widget one click binding feature", + { tags: ["@tag.Binding"] }, + () => { + it("should check that queries are created and bound to table widget properly", () => { + entityExplorer.DragDropWidgetNVerify(draggableWidgets.SELECT, 450, 200); - dataSources.CreateDataSource("Mongo"); + dataSources.CreateDataSource("Mongo"); - cy.get("@dsName").then((dsName) => { - EditorNavigation.SelectEntityByName("Select1", EntityType.Widget); + cy.get("@dsName").then((dsName) => { + EditorNavigation.SelectEntityByName("Select1", EntityType.Widget); - oneClickBinding.ChooseAndAssertForm(`${dsName}`, dsName, "netflix", { - label: "name", - value: "director", + oneClickBinding.ChooseAndAssertForm(`${dsName}`, dsName, "netflix", { + label: "name", + value: "director", + }); + }); + + agHelper.GetNClick(oneClickBindingLocator.connectData); + + assertHelper.AssertNetworkStatus("@postExecute"); + + agHelper.Sleep(2000); + + entityExplorer.DragDropWidgetNVerify(draggableWidgets.TEXT, 450, 500); + + propPane.UpdatePropertyFieldValue( + "Text", + `{{Select1.selectedOptionLabel}}:{{Select1.selectedOptionValue}}`, + ); + + [ + { + label: "I Care a Lot", + text: "I Care a Lot:J Blakeson", + }, + { + label: "tick, tick...BOOM!", + text: "tick, tick...BOOM!:Lin-Manuel Miranda", + }, + { + label: "Munich – The Edge of War", + text: "Munich – The Edge of War:Christian Schwochow", + }, + ].forEach((d) => { + cy.get(formWidgetsPage.selectWidget) + .find(widgetsPage.dropdownSingleSelect) + .click({ + force: true, + }); + + cy.get(commonlocators.singleSelectWidgetMenuItem) + .contains(d.label) + .click({ + force: true, + }); + + cy.get(commonlocators.TextInside).first().should("have.text", d.text); }); - }); - agHelper.GetNClick(oneClickBindingLocator.connectData); - - assertHelper.AssertNetworkStatus("@postExecute"); - - agHelper.Sleep(2000); - - entityExplorer.DragDropWidgetNVerify(draggableWidgets.TEXT, 450, 500); - - propPane.UpdatePropertyFieldValue( - "Text", - `{{Select1.selectedOptionLabel}}:{{Select1.selectedOptionValue}}`, - ); - - [ - { - label: "I Care a Lot", - text: "I Care a Lot:J Blakeson", - }, - { - label: "tick, tick...BOOM!", - text: "tick, tick...BOOM!:Lin-Manuel Miranda", - }, - { - label: "Munich – The Edge of War", - text: "Munich – The Edge of War:Christian Schwochow", - }, - ].forEach((d) => { cy.get(formWidgetsPage.selectWidget) .find(widgetsPage.dropdownSingleSelect) .click({ force: true, }); - cy.get(commonlocators.singleSelectWidgetMenuItem) - .contains(d.label) - .click({ - force: true, - }); + cy.get(commonlocators.selectInputSearch).type("I Care a Lot"); - cy.get(commonlocators.TextInside).first().should("have.text", d.text); - }); - - cy.get(formWidgetsPage.selectWidget) - .find(widgetsPage.dropdownSingleSelect) - .click({ - force: true, - }); + assertHelper.AssertNetworkStatus("@postExecute"); - cy.get(commonlocators.selectInputSearch).type("I Care a Lot"); + agHelper.Sleep(2000); - assertHelper.AssertNetworkStatus("@postExecute"); + cy.get(".select-popover-wrapper .menu-item-link") + .children() + .should("have.length", 1); - agHelper.Sleep(2000); - - cy.get(".select-popover-wrapper .menu-item-link") - .children() - .should("have.length", 1); - - agHelper.AssertElementExist( - commonlocators.singleSelectWidgetMenuItem + `:contains(I Care a Lot)`, - ); - }); -}); + agHelper.AssertElementExist( + commonlocators.singleSelectWidgetMenuItem + `:contains(I Care a Lot)`, + ); + }); + }, +); diff --git a/app/client/cypress/e2e/Regression/ClientSide/OneClickBinding/SelectWidget/postgres_spec.ts b/app/client/cypress/e2e/Regression/ClientSide/OneClickBinding/SelectWidget/postgres_spec.ts index c9b9b98ecf9b..6a26d630d996 100644 --- a/app/client/cypress/e2e/Regression/ClientSide/OneClickBinding/SelectWidget/postgres_spec.ts +++ b/app/client/cypress/e2e/Regression/ClientSide/OneClickBinding/SelectWidget/postgres_spec.ts @@ -17,86 +17,90 @@ import EditorNavigation, { const oneClickBinding = new OneClickBinding(); -describe("Table widget one click binding feature", () => { - it("should check that queries are created and bound to table widget properly", () => { - entityExplorer.DragDropWidgetNVerify(draggableWidgets.SELECT, 450, 200); +describe( + "Table widget one click binding feature", + { tags: ["@tag.Binding"] }, + () => { + it("should check that queries are created and bound to table widget properly", () => { + entityExplorer.DragDropWidgetNVerify(draggableWidgets.SELECT, 450, 200); + + dataSources.CreateDataSource("Postgres"); + + cy.get("@dsName").then((dsName) => { + EditorNavigation.SelectEntityByName("Select1", EntityType.Widget); + + oneClickBinding.ChooseAndAssertForm( + `${dsName}`, + dsName, + "public.employees", + { + label: "first_name", + value: "last_name", + }, + ); + }); + + agHelper.GetNClick(oneClickBindingLocator.connectData); + + assertHelper.AssertNetworkStatus("@postExecute"); - dataSources.CreateDataSource("Postgres"); + agHelper.Sleep(2000); - cy.get("@dsName").then((dsName) => { - EditorNavigation.SelectEntityByName("Select1", EntityType.Widget); + entityExplorer.DragDropWidgetNVerify(draggableWidgets.TEXT, 450, 500); - oneClickBinding.ChooseAndAssertForm( - `${dsName}`, - dsName, - "public.employees", + propPane.UpdatePropertyFieldValue( + "Text", + `{{Select1.selectedOptionLabel}}:{{Select1.selectedOptionValue}}`, + ); + + [ { - label: "first_name", - value: "last_name", + label: "Andrew", + text: "Andrew:Fuller", }, - ); - }); + { + label: "Janet", + text: "Janet:Leverling", + }, + { + label: "Margaret", + text: "Margaret:Peacock", + }, + ].forEach((d) => { + cy.get(formWidgetsPage.selectWidget) + .find(widgetsPage.dropdownSingleSelect) + .click({ + force: true, + }); + + cy.get(commonlocators.singleSelectWidgetMenuItem) + .contains(d.label) + .click({ + force: true, + }); + + cy.get(commonlocators.TextInside).first().should("have.text", d.text); + }); - agHelper.GetNClick(oneClickBindingLocator.connectData); - - assertHelper.AssertNetworkStatus("@postExecute"); - - agHelper.Sleep(2000); - - entityExplorer.DragDropWidgetNVerify(draggableWidgets.TEXT, 450, 500); - - propPane.UpdatePropertyFieldValue( - "Text", - `{{Select1.selectedOptionLabel}}:{{Select1.selectedOptionValue}}`, - ); - - [ - { - label: "Andrew", - text: "Andrew:Fuller", - }, - { - label: "Janet", - text: "Janet:Leverling", - }, - { - label: "Margaret", - text: "Margaret:Peacock", - }, - ].forEach((d) => { cy.get(formWidgetsPage.selectWidget) .find(widgetsPage.dropdownSingleSelect) .click({ force: true, }); - cy.get(commonlocators.singleSelectWidgetMenuItem) - .contains(d.label) - .click({ - force: true, - }); + cy.get(commonlocators.selectInputSearch).type("Anne"); - cy.get(commonlocators.TextInside).first().should("have.text", d.text); - }); + assertHelper.AssertNetworkStatus("@postExecute"); - cy.get(formWidgetsPage.selectWidget) - .find(widgetsPage.dropdownSingleSelect) - .click({ - force: true, - }); + agHelper.Sleep(2000); - cy.get(commonlocators.selectInputSearch).type("Anne"); + cy.get(".select-popover-wrapper .menu-item-link") + .children() + .should("have.length", 1); - assertHelper.AssertNetworkStatus("@postExecute"); - - agHelper.Sleep(2000); - - cy.get(".select-popover-wrapper .menu-item-link") - .children() - .should("have.length", 1); - - agHelper.AssertElementExist( - commonlocators.singleSelectWidgetMenuItem + `:contains(Anne)`, - ); - }); -}); + agHelper.AssertElementExist( + commonlocators.singleSelectWidgetMenuItem + `:contains(Anne)`, + ); + }); + }, +); diff --git a/app/client/cypress/e2e/Regression/ClientSide/OneClickBinding/TableWidget/index_spec.ts b/app/client/cypress/e2e/Regression/ClientSide/OneClickBinding/TableWidget/index_spec.ts index 30c9c969164f..250cc1365239 100644 --- a/app/client/cypress/e2e/Regression/ClientSide/OneClickBinding/TableWidget/index_spec.ts +++ b/app/client/cypress/e2e/Regression/ClientSide/OneClickBinding/TableWidget/index_spec.ts @@ -4,16 +4,20 @@ import EditorNavigation, { EntityType, } from "../../../../../support/Pages/EditorNavigation"; -describe("Table widget one click binding feature", () => { - it("1.should check that connect data overlay is shown on the table", () => { - _.entityExplorer.DragDropWidgetNVerify(_.draggableWidgets.TABLE); - _.agHelper.AssertElementExist(_.table._connectDataHeader); - _.agHelper.AssertElementExist(_.table._connectDataButton); - // should check that tableData one click property control" - EditorNavigation.SelectEntityByName("Table1", EntityType.Widget); +describe( + "Table widget one click binding feature", + { tags: ["@tag.Binding"] }, + () => { + it("1.should check that connect data overlay is shown on the table", () => { + _.entityExplorer.DragDropWidgetNVerify(_.draggableWidgets.TABLE); + _.agHelper.AssertElementExist(_.table._connectDataHeader); + _.agHelper.AssertElementExist(_.table._connectDataButton); + // should check that tableData one click property control" + EditorNavigation.SelectEntityByName("Table1", EntityType.Widget); - _.agHelper.AssertElementExist( - oneClickBindingLocator.datasourceDropdownSelector, - ); - }); -}); + _.agHelper.AssertElementExist( + oneClickBindingLocator.datasourceDropdownSelector, + ); + }); + }, +); diff --git a/app/client/cypress/e2e/Regression/ClientSide/OneClickBinding/TableWidget/mongoDB_spec.ts b/app/client/cypress/e2e/Regression/ClientSide/OneClickBinding/TableWidget/mongoDB_spec.ts index 528bc124cf5f..d0f63fc82cb1 100644 --- a/app/client/cypress/e2e/Regression/ClientSide/OneClickBinding/TableWidget/mongoDB_spec.ts +++ b/app/client/cypress/e2e/Regression/ClientSide/OneClickBinding/TableWidget/mongoDB_spec.ts @@ -14,86 +14,90 @@ import EditorNavigation, { const oneClickBinding = new OneClickBinding(); -describe("one click binding mongodb datasource", function () { - before(() => { - entityExplorer.DragDropWidgetNVerify(draggableWidgets.TABLE, 450, 200); - }); +describe( + "one click binding mongodb datasource", + { tags: ["@tag.Binding"] }, + function () { + before(() => { + entityExplorer.DragDropWidgetNVerify(draggableWidgets.TABLE, 450, 200); + }); - it("1. test connect datasource", () => { - //#region bind to mongoDB datasource - dataSources.CreateDataSource("Mongo"); + it("1. test connect datasource", () => { + //#region bind to mongoDB datasource + dataSources.CreateDataSource("Mongo"); - cy.get("@dsName").then((dsName) => { - EditorNavigation.SelectEntityByName("Table1", EntityType.Widget); + cy.get("@dsName").then((dsName) => { + EditorNavigation.SelectEntityByName("Table1", EntityType.Widget); - oneClickBinding.ChooseAndAssertForm(`${dsName}`, dsName, "netflix", { - searchableColumn: "creator", + oneClickBinding.ChooseAndAssertForm(`${dsName}`, dsName, "netflix", { + searchableColumn: "creator", + }); }); - }); - agHelper.GetNClick(oneClickBindingLocator.connectData); - - assertHelper.AssertNetworkStatus("@postExecute"); - - agHelper.Sleep(2000); - //#endregion - - //#region validate search through table is working - const rowWithAValidText = "Mike Flanagan"; - //enter a search text - agHelper.TypeText(table._searchInput, rowWithAValidText); - agHelper.Sleep(); - // check if the table rows are present for the given search entry - agHelper.GetNAssertContains( - oneClickBindingLocator.validTableRowData, - rowWithAValidText, - ); - //#endregion - - //#region table update operation is working - const someColumnIndex = 1; - const someUUID = Cypress._.random(0, 1e6); - const enteredSomeValue = "123" + someUUID; - - //update the first value of the row - table.EditTableCell(0, someColumnIndex, enteredSomeValue); - agHelper.Sleep(); - //commit that update - (cy as any).saveTableRow(12, 0); - - agHelper.Sleep(); - - // check if the updated value is present - (cy as any).readTableV2data(0, someColumnIndex).then((cellData: any) => { - expect(cellData).to.equal(enteredSomeValue); + agHelper.GetNClick(oneClickBindingLocator.connectData); + + assertHelper.AssertNetworkStatus("@postExecute"); + + agHelper.Sleep(2000); + //#endregion + + //#region validate search through table is working + const rowWithAValidText = "Mike Flanagan"; + //enter a search text + agHelper.TypeText(table._searchInput, rowWithAValidText); + agHelper.Sleep(); + // check if the table rows are present for the given search entry + agHelper.GetNAssertContains( + oneClickBindingLocator.validTableRowData, + rowWithAValidText, + ); + //#endregion + + //#region table update operation is working + const someColumnIndex = 1; + const someUUID = Cypress._.random(0, 1e6); + const enteredSomeValue = "123" + someUUID; + + //update the first value of the row + table.EditTableCell(0, someColumnIndex, enteredSomeValue); + agHelper.Sleep(); + //commit that update + (cy as any).saveTableRow(12, 0); + + agHelper.Sleep(); + + // check if the updated value is present + (cy as any).readTableV2data(0, someColumnIndex).then((cellData: any) => { + expect(cellData).to.equal(enteredSomeValue); + }); + //#endregion + + //#region check if the table insert operation works + //clear input + table.ResetSearch(); + + //lets create a new row and check to see the insert operation is working + table.AddNewRow(); + + const someText = "new row " + Cypress._.random(0, 1e6); + const searchColumnIndex = 3; + table.EditTableCell(0, searchColumnIndex, someText); + (cy as any).saveTableCellValue(searchColumnIndex, 0); + // save a row with some random text + agHelper.GetNClick(table._saveNewRow, 0, true); + + agHelper.Sleep(2000); + + //search the table for a row having the text used to create a new row + agHelper.ClearNType(table._searchInput, someText); + agHelper.Sleep(); + + //check if that row is present + agHelper.GetNAssertContains( + oneClickBindingLocator.validTableRowData, + someText, + ); + //#endregion }); - //#endregion - - //#region check if the table insert operation works - //clear input - table.ResetSearch(); - - //lets create a new row and check to see the insert operation is working - table.AddNewRow(); - - const someText = "new row " + Cypress._.random(0, 1e6); - const searchColumnIndex = 3; - table.EditTableCell(0, searchColumnIndex, someText); - (cy as any).saveTableCellValue(searchColumnIndex, 0); - // save a row with some random text - agHelper.GetNClick(table._saveNewRow, 0, true); - - agHelper.Sleep(2000); - - //search the table for a row having the text used to create a new row - agHelper.ClearNType(table._searchInput, someText); - agHelper.Sleep(); - - //check if that row is present - agHelper.GetNAssertContains( - oneClickBindingLocator.validTableRowData, - someText, - ); - //#endregion - }); -}); + }, +); diff --git a/app/client/cypress/e2e/Regression/ClientSide/OneClickBinding/TableWidget/postgres_spec.ts b/app/client/cypress/e2e/Regression/ClientSide/OneClickBinding/TableWidget/postgres_spec.ts index db7065847b17..91eb13fbe676 100644 --- a/app/client/cypress/e2e/Regression/ClientSide/OneClickBinding/TableWidget/postgres_spec.ts +++ b/app/client/cypress/e2e/Regression/ClientSide/OneClickBinding/TableWidget/postgres_spec.ts @@ -14,112 +14,116 @@ import EditorNavigation, { const oneClickBinding = new OneClickBinding(); -describe("Table widget one click binding feature", () => { - it("should check that queries are created and bound to table widget properly", () => { - entityExplorer.DragDropWidgetNVerify(draggableWidgets.TABLE, 450, 200); - - dataSources.CreateDataSource("Postgres"); - - cy.get("@dsName").then((dsName) => { - EditorNavigation.SelectEntityByName("Table1", EntityType.Widget); - - oneClickBinding.ChooseAndAssertForm( - `${dsName}`, - dsName, - "public.employees", - { - searchableColumn: "first_name", - }, - ); - }); +describe( + "Table widget one click binding feature", + { tags: ["@tag.Binding"] }, + () => { + it("should check that queries are created and bound to table widget properly", () => { + entityExplorer.DragDropWidgetNVerify(draggableWidgets.TABLE, 450, 200); - agHelper.GetNClick(oneClickBindingLocator.connectData); + dataSources.CreateDataSource("Postgres"); - assertHelper.AssertNetworkStatus("@postExecute"); + cy.get("@dsName").then((dsName) => { + EditorNavigation.SelectEntityByName("Table1", EntityType.Widget); - agHelper.Sleep(2000); + oneClickBinding.ChooseAndAssertForm( + `${dsName}`, + dsName, + "public.employees", + { + searchableColumn: "first_name", + }, + ); + }); - [ - "employee_id", - "last_name", - "first_name", - "title", - "title_of_courtesy", - "birth_date", - "hire_date", - ].forEach((column) => { - agHelper.AssertElementExist(table._headerCell(column)); - }); + agHelper.GetNClick(oneClickBindingLocator.connectData); + + assertHelper.AssertNetworkStatus("@postExecute"); - agHelper.AssertElementExist(table._showPageItemsCount); + agHelper.Sleep(2000); - table.AddNewRow(); + [ + "employee_id", + "last_name", + "first_name", + "title", + "title_of_courtesy", + "birth_date", + "hire_date", + ].forEach((column) => { + agHelper.AssertElementExist(table._headerCell(column)); + }); - //const randomNumber = Cypress._.random(10, 100, false); - //cy.log("randomeNumber: " + randomNumber); + agHelper.AssertElementExist(table._showPageItemsCount); - // table.EditTableCell(0, 0, randomNumber.toString(), false);//Bug 24623 - since 2 digit id is not typed properly - table.UpdateTableCell(0, 1, "_"); - table.UpdateTableCell(0, 2, "appsmith_"); + table.AddNewRow(); - agHelper.GetNClick(oneClickBindingLocator.dateInput, 0, true); - agHelper.GetNClick(oneClickBindingLocator.dayViewFromDate, 0, true); + //const randomNumber = Cypress._.random(10, 100, false); + //cy.log("randomeNumber: " + randomNumber); - agHelper.GetNClick(oneClickBindingLocator.dateInput, 1, true); - agHelper.GetNClick(oneClickBindingLocator.dayViewFromDate, 0, true); + // table.EditTableCell(0, 0, randomNumber.toString(), false);//Bug 24623 - since 2 digit id is not typed properly + table.UpdateTableCell(0, 1, "_"); + table.UpdateTableCell(0, 2, "appsmith_"); - table.UpdateTableCell(0, 16, "1"); + agHelper.GetNClick(oneClickBindingLocator.dateInput, 0, true); + agHelper.GetNClick(oneClickBindingLocator.dayViewFromDate, 0, true); - agHelper.Sleep(2000); + agHelper.GetNClick(oneClickBindingLocator.dateInput, 1, true); + agHelper.GetNClick(oneClickBindingLocator.dayViewFromDate, 0, true); - agHelper.GetNClick(table._saveNewRow, 0, true); + table.UpdateTableCell(0, 16, "1"); - assertHelper.AssertNetworkStatus("@postExecute"); + agHelper.Sleep(2000); - agHelper.TypeText(table._searchInput, "appsmith_"); + agHelper.GetNClick(table._saveNewRow, 0, true); - assertHelper.AssertNetworkStatus("@postExecute"); + assertHelper.AssertNetworkStatus("@postExecute"); - agHelper.AssertElementExist(table._bodyCell("appsmith_")); + agHelper.TypeText(table._searchInput, "appsmith_"); - agHelper.Sleep(); + assertHelper.AssertNetworkStatus("@postExecute"); - //(cy as any).editTableCell(1, 0); + agHelper.AssertElementExist(table._bodyCell("appsmith_")); - agHelper.Sleep(500); + agHelper.Sleep(); - table.EditTableCell(0, 2, "cypress"); + //(cy as any).editTableCell(1, 0); - //(cy as any).enterTableCellValue(1, 0, "automation@appsmith{enter}"); + agHelper.Sleep(500); - agHelper.Sleep(); + table.EditTableCell(0, 2, "cypress"); - (cy as any).AssertTableRowSavable(18, 0); + //(cy as any).enterTableCellValue(1, 0, "automation@appsmith{enter}"); - (cy as any).saveTableRow(18, 0); + agHelper.Sleep(); - assertHelper.AssertNetworkStatus("@postExecute"); + (cy as any).AssertTableRowSavable(18, 0); - assertHelper.AssertNetworkStatus("@postExecute"); + (cy as any).saveTableRow(18, 0); - agHelper.Sleep(500); - agHelper.ClearNType(table._searchInput, "cypress"); + assertHelper.AssertNetworkStatus("@postExecute"); - assertHelper.AssertNetworkStatus("@postExecute"); + assertHelper.AssertNetworkStatus("@postExecute"); - agHelper.Sleep(2000); + agHelper.Sleep(500); + agHelper.ClearNType(table._searchInput, "cypress"); - agHelper.AssertElementExist(table._bodyCell("cypress")); + assertHelper.AssertNetworkStatus("@postExecute"); - //TODO: Commenting out until cypress double click issue is resolved. - // agHelper.ClearTextField(table._searchInput); + agHelper.Sleep(2000); - // agHelper.TypeText(table._searchInput, "appsmith_"); + agHelper.AssertElementExist(table._bodyCell("cypress")); - // assertHelper.AssertNetworkStatus("@postExecute"); + //TODO: Commenting out until cypress double click issue is resolved. + // agHelper.ClearTextField(table._searchInput); - // agHelper.Sleep(2000); + // agHelper.TypeText(table._searchInput, "appsmith_"); - // agHelper.AssertElementAbsence(table._bodyCell("appsmith_")); - }); -}); + // assertHelper.AssertNetworkStatus("@postExecute"); + + // agHelper.Sleep(2000); + + // agHelper.AssertElementAbsence(table._bodyCell("appsmith_")); + }); + }, +);
529763484496c6f6c6022dae82b024071767091c
2023-06-20 18:17:47
Vijetha-Kaja
test: Cypress - Convert MongoDBShoppingCart_spec to Ts (#24667)
false
Cypress - Convert MongoDBShoppingCart_spec to Ts (#24667)
test
diff --git a/app/client/cypress/e2e/Regression/Apps/MongoDBShoppingCart_spec.js b/app/client/cypress/e2e/Regression/Apps/MongoDBShoppingCart_spec.js index c0ec88a7e5a0..a4f74ed7f1b0 100644 --- a/app/client/cypress/e2e/Regression/Apps/MongoDBShoppingCart_spec.js +++ b/app/client/cypress/e2e/Regression/Apps/MongoDBShoppingCart_spec.js @@ -1,8 +1,7 @@ -const queryLocators = require("../../../locators/QueryEditor.json"); const appPage = require("../../../locators/PgAdminlocators.json"); -const formControls = require("../../../locators/FormControl.json"); import { agHelper, + assertHelper, deployMode, homePage, gitSync, @@ -10,7 +9,7 @@ import { } from "../../../support/Objects/ObjectsCore"; let repoName; -describe.skip("Shopping cart App", function () { +describe("Shopping cart App", function () { let datasourceName; before(() => { @@ -23,64 +22,64 @@ describe.skip("Shopping cart App", function () { agHelper.AddDsl(val); }); }); - }); - - it("1. Create MongoDB datasource and add Insert, Find, Update and Delete queries", function () { dataSources.CreateDataSource("Mongo"); cy.get("@saveDatasource").then((httpResponse) => { datasourceName = httpResponse.response.body.data.name; }); - cy.NavigateToQueryEditor(); - cy.NavigateToActiveTab(); + }); + + it("1. Create MongoDB datasource and add Insert, Find, Update and Delete queries", function () { + dataSources.CreateQueryAfterDSSaved("", "GetProduct"); + dataSources.EnterJSContext({ + fieldProperty: dataSources._mongoCollectionPath, + fieldLabel: "Collection", + fieldValue: "Productnames", + }); // GetProduct query to fetch all products - cy.get(queryLocators.createQuery).last().click(); - cy.get(queryLocators.queryNameField).type("GetProduct"); - cy.get(".CodeEditorTarget").first().type("Productnames"); - cy.assertPageSave(); - cy.get(appPage.dropdownChevronLeft).click(); + agHelper.AssertAutoSave(); // EditProducts query to update the cart - cy.get(queryLocators.createQuery).last().click(); - cy.get(queryLocators.queryNameField).type("EditProducts"); - - // Clicking outside to trigger the save - cy.get("body").click(0, 0); - cy.TargetDropdownAndSelectOption( - formControls.commandDropdown, + dataSources.CreateQueryFromOverlay(datasourceName, "", "EditProducts"); + dataSources.ValidateNSelectDropdown( + "Commands", + "Find document(s)", "Update document(s)", ); - cy.get(".CodeEditorTarget").first().type("Productnames"); - cy.get(".CodeEditorTarget") - .eq(1) - .type('{"title": "{{Table1.selectedRow.title}}"}', { - parseSpecialCharSequences: false, - }); - cy.get(".CodeEditorTarget") - .eq(2) - .type( - `{"title" : "{{title.text}}", - "description" :"{{description.text}}", - "price" : {{price.text}}, - "quantity":{{quantity.text}}`, - { - parseSpecialCharSequences: false, - }, - ); - cy.assertPageSave(); - cy.get(appPage.dropdownChevronLeft).click(); - // Add product query - cy.get(queryLocators.createQuery).last().click(); - cy.wait(5000); - cy.get(queryLocators.queryNameField).type("AddProduct"); - // Clicking outside to trigger the save - cy.get("body").click(0, 0); - cy.TargetDropdownAndSelectOption( - formControls.commandDropdown, + dataSources.EnterJSContext({ + fieldProperty: dataSources._mongoCollectionPath, + fieldLabel: "Collection", + fieldValue: "Productnames", + }); + agHelper.EnterValue('{"title": "{{Table1.selectedRow.title}}"}', { + propFieldName: "", + directInput: false, + inputFieldName: "Query", + }); + agHelper.EnterValue( + `{"title" : "{{title.text}}", + "description" :"{{description.text}}", + "price" : {{price.text}}, + "quantity":{{quantity.text}}}`, + { + propFieldName: "", + directInput: false, + inputFieldName: "Update", + }, + ); + + agHelper.AssertAutoSave(); + + // AddProducts query to add to cart + dataSources.CreateQueryFromOverlay(datasourceName, "", "AddProduct"); + dataSources.ValidateNSelectDropdown( + "Commands", + "Find document(s)", "Insert document(s)", ); - // cy.get("[data-testid='actionConfiguration.formData.command.data']").click(); - // cy.get(".t--dropdown-option") - // .eq(1) - // .click(); + dataSources.EnterJSContext({ + fieldProperty: dataSources._mongoCollectionPath, + fieldLabel: "Collection", + fieldValue: "Productnames", + }); const documentText = [ { title: "{{Title.text}}", @@ -89,40 +88,34 @@ describe.skip("Shopping cart App", function () { quantity: "{{Quantity.text}}", }, ]; - cy.get(".CodeEditorTarget") - .first() - .type("Productnames", { parseSpecialCharSequences: false }); - cy.get(".CodeEditorTarget") - .eq(1) - .type(JSON.stringify(documentText), { parseSpecialCharSequences: false }); - cy.assertPageSave(); - cy.get(appPage.dropdownChevronLeft).click(); - // delete product - cy.get(queryLocators.createQuery).last().click(); - cy.wait(5000); - cy.get(queryLocators.queryNameField).type("DeleteProduct"); - // Clicking outside to trigger the save - cy.get("body").click(0, 0); - cy.TargetDropdownAndSelectOption( - formControls.commandDropdown, + agHelper.EnterValue(JSON.stringify(documentText), { + propFieldName: "", + directInput: false, + inputFieldName: "Documents", + }); + + agHelper.AssertAutoSave(); + + // Delete product + dataSources.CreateQueryFromOverlay(datasourceName, "", "DeleteProduct"); + dataSources.ValidateNSelectDropdown( + "Commands", + "Find document(s)", "Delete document(s)", ); - // cy.get("[data-testid='actionConfiguration.formData.command.data']").click(); - // cy.get(".t--dropdown-option") - // .eq(3) - // .click(); - cy.get(".CodeEditorTarget") - .first() - .type("Productnames", { parseSpecialCharSequences: false }); - cy.get(".CodeEditorTarget") - .eq(1) - .type('{"title":"{{Table1.selectedRow.title}}"}', { - parseSpecialCharSequences: false, - }); - cy.assertPageSave(); + dataSources.EnterJSContext({ + fieldProperty: dataSources._mongoCollectionPath, + fieldLabel: "Collection", + fieldValue: "Productnames", + }); + agHelper.EnterValue('{"title":"{{Table1.selectedRow.title}}"}', { + propFieldName: "", + directInput: false, + inputFieldName: "Query", + }); + + agHelper.AssertAutoSave(); - cy.get(appPage.dropdownChevronLeft).click(); - cy.get(".t--back-button").click(); deployMode.DeployApp(appPage.bookname); }); @@ -131,36 +124,27 @@ describe.skip("Shopping cart App", function () { agHelper.GetNClick(appPage.bookname); //Wait for element to be in DOM agHelper.Sleep(3000); + agHelper.AssertElementLength(appPage.inputValues, 9); agHelper.UpdateInput(appPage.bookname, "Atomic habits", true); agHelper.UpdateInput(appPage.bookgenre, "Self help", true); agHelper.UpdateInput(appPage.bookprice, 200, true); agHelper.UpdateInput(appPage.bookquantity, 2, true); agHelper.GetNClick(appPage.addButton, 0, true); - cy.wait("@postExecute"); - cy.wait(3000); + assertHelper.AssertNetworkStatus("@postExecute"); agHelper.UpdateInput(appPage.bookname, "A man called ove", true); agHelper.UpdateInput(appPage.bookgenre, "Fiction", true); agHelper.UpdateInput(appPage.bookprice, 100, true); agHelper.UpdateInput(appPage.bookquantity, 1, true); agHelper.GetNClick(appPage.addButton, 0, true); - cy.wait("@postExecute"); + assertHelper.AssertNetworkStatus("@postExecute"); // Deleting the book from the cart - cy.get(".tableWrap") - .children() - .first() - .within(() => { - agHelper.GetNClick(appPage.deleteButton, 1, false); - cy.wait("@postExecute"); - cy.wait(5000); - cy.wait("@postExecute") - .its("response.body.responseMeta.status") - .should("eq", 200); + agHelper.GetNClick(appPage.deleteButton, 1, false); + assertHelper.AssertNetworkStatus("@postExecute"); + agHelper.Sleep(3000); + assertHelper.AssertNetworkStatus("@postExecute"); - // validating that the book is deleted - cy.get("span:contains('Delete')") - .parent("button") - .should("have.length", 1); - }); + // validating that the book is deleted + agHelper.AssertElementLength(appPage.deleteButton + "/parent::div", 1); // Updating the book quantity from edit cart agHelper.UpdateInput(appPage.editbookquantity, 3, true); agHelper.GetNClick(appPage.editButton, 0, true); @@ -168,14 +152,12 @@ describe.skip("Shopping cart App", function () { //Wait for all post execute calls to finish agHelper.Sleep(3000); agHelper.AssertNetworkExecutionSuccess("@postExecute"); - cy.get("@postExecute.all").its("length").should("be.above", 8); - cy.get("@postExecute.last") - .its("response.body") - .then((user) => { - expect(user.data.body[0].quantity).to.equal("3"); - }); // validating updated value in the cart - cy.get(".selected-row").children().eq(3).should("have.text", "3"); + agHelper + .GetElement(dataSources._selectedRow) + .children() + .eq(3) + .should("have.text", "3"); }); it("3. Connect the appplication to git and validate data in deploy mode and edit mode", function () { @@ -185,17 +167,17 @@ describe.skip("Shopping cart App", function () { repoName = repName; }); cy.latestDeployPreview(); - cy.wait(2000); - cy.get(".selected-row") + agHelper + .GetElement(dataSources._selectedRow) .children() .eq(0) .should("have.text", "A man called ove"); deployMode.NavigateBacktoEditor(); - cy.get(".selected-row") + agHelper + .GetElement(dataSources._selectedRow) .children() .eq(0) .should("have.text", "A man called ove"); - cy.wait(1000); }); after(() => { diff --git a/app/client/cypress/locators/PgAdminlocators.json b/app/client/cypress/locators/PgAdminlocators.json index a61cd3ffc624..5c572d5c9bd3 100644 --- a/app/client/cypress/locators/PgAdminlocators.json +++ b/app/client/cypress/locators/PgAdminlocators.json @@ -1,6 +1,7 @@ { "dropdownChevronLeft": ".t--close-editor", "addNewtable": "//span[text()='New Table']", + "inputValues":"//div[@class='bp3-input-group']", "addTablename": "(//div[@class='bp3-input-group']//input)[2]", "addColumn": "//span[text()='Add Column']/parent::button/parent::div", "addColumnName": "div[data-testid='input-container']",
30f3d250c48cdd0bef8e507ec00f231bbadbf928
2023-04-13 15:38:46
Rajat Agrawal
fix: Table Widget property to specify if prev or next buttons were pressed (#21712)
false
Table Widget property to specify if prev or next buttons were pressed (#21712)
fix
diff --git a/app/client/cypress/fixtures/tableV2NewDslWithPagination.json b/app/client/cypress/fixtures/tableV2NewDslWithPagination.json index 2a7f865dd500..ed934969e99b 100644 --- a/app/client/cypress/fixtures/tableV2NewDslWithPagination.json +++ b/app/client/cypress/fixtures/tableV2NewDslWithPagination.json @@ -88,7 +88,7 @@ "key": "primaryColumns.orderAmount.computedValue" } ], - "leftColumn": 16, + "leftColumn": 1, "delimiter": ",", "defaultSelectedRowIndex": 0, "accentColor": "{{appsmith.theme.colors.primaryColor}}", @@ -136,7 +136,7 @@ ], "dynamicPropertyPathList": [], "displayName": "Table", - "bottomRow": 111, + "bottomRow": 132, "columnWidthMap": { "task": 245, "step": 62, @@ -273,7 +273,7 @@ "rightColumn": 50, "textSize": "0.875rem", "widgetId": "8o3mdylmxa", - "tableData": "{{[\n {\n \"id\": 2381224,\n \"email\": \"[email protected]\",\n \"userName\": \"Michael Lawson\",\n \"productName\": \"Chicken Sandwich\",\n \"orderAmount\": 4.99\n },\n {\n \"id\": 2736212,\n \"email\": \"[email protected]\",\n \"userName\": \"Lindsay Ferguson\",\n \"productName\": \"Tuna Salad\",\n \"orderAmount\": 9.99\n },\n {\n \"id\": 6788734,\n \"email\": \"[email protected]\",\n \"userName\": \"Tobias Funke\",\n \"productName\": \"Beef steak\",\n \"orderAmount\": 19.99\n },\n {\n \"id\": 7434532,\n \"email\": \"[email protected]\",\n \"userName\": \"Byron Fields\",\n \"productName\": \"Chicken Sandwich\",\n \"orderAmount\": 4.99\n },\n {\n \"id\": 7434532,\n \"email\": \"[email protected]\",\n \"userName\": \"Ryan Holmes\",\n \"productName\": \"Avocado Panini\",\n \"orderAmount\": 7.99\n },\n\t {\n \"id\": 7434532,\n \"email\": \"[email protected]\",\n \"userName\": \"Byron Fields\",\n \"productName\": \"Chicken Sandwich\",\n \"orderAmount\": 4.99\n },\n {\n \"id\": 7434532,\n \"email\": \"[email protected]\",\n \"userName\": \"Ryan Holmes\",\n \"productName\": \"Avocado Panini\",\n \"orderAmount\": 7.99\n },\n\t {\n \"id\": 7434532,\n \"email\": \"[email protected]\",\n \"userName\": \"Byron Fields\",\n \"productName\": \"Chicken Sandwich\",\n \"orderAmount\": 4.99\n },\n {\n \"id\": 7434532,\n \"email\": \"[email protected]\",\n \"userName\": \"Ryan Holmes\",\n \"productName\": \"Avocado Panini\",\n \"orderAmount\": 7.99\n },\n\t {\n \"id\": 7434532,\n \"email\": \"[email protected]\",\n \"userName\": \"Byron Fields\",\n \"productName\": \"Chicken Sandwich\",\n \"orderAmount\": 4.99\n },\n {\n \"id\": 7434532,\n \"email\": \"[email protected]\",\n \"userName\": \"Ryan Holmes\",\n \"productName\": \"Avocado Panini\",\n \"orderAmount\": 7.99\n },\n\t {\n \"id\": 7434532,\n \"email\": \"[email protected]\",\n \"userName\": \"Byron Fields\",\n \"productName\": \"Chicken Sandwich\",\n \"orderAmount\": 4.99\n },\n {\n \"id\": 7434532,\n \"email\": \"[email protected]\",\n \"userName\": \"Ryan Holmes\",\n \"productName\": \"Avocado Panini\",\n \"orderAmount\": 7.99\n }\n]}}", + "tableData": "{{[\n {\n \"id\": 2381224,\n \"email\": \"[email protected]\",\n \"userName\": \"Michael Lawson\",\n \"productName\": \"Chicken Sandwich\",\n \"orderAmount\": 4.99\n }, {\n \"id\": 2381224,\n \"email\": \"[email protected]\",\n \"userName\": \"Michael Lawson\",\n \"productName\": \"Chicken Sandwich\",\n \"orderAmount\": 4.99\n }, {\n \"id\": 2381224,\n \"email\": \"[email protected]\",\n \"userName\": \"Michael Lawson\",\n \"productName\": \"Chicken Sandwich\",\n \"orderAmount\": 4.99\n }, {\n \"id\": 2381224,\n \"email\": \"[email protected]\",\n \"userName\": \"Michael Lawson\",\n \"productName\": \"Chicken Sandwich\",\n \"orderAmount\": 4.99\n }, {\n \"id\": 2381224,\n \"email\": \"[email protected]\",\n \"userName\": \"Michael Lawson\",\n \"productName\": \"Chicken Sandwich\",\n \"orderAmount\": 4.99\n }, {\n \"id\": 2381224,\n \"email\": \"[email protected]\",\n \"userName\": \"Michael Lawson\",\n \"productName\": \"Chicken Sandwich\",\n \"orderAmount\": 4.99\n }, {\n \"id\": 2381224,\n \"email\": \"[email protected]\",\n \"userName\": \"Michael Lawson\",\n \"productName\": \"Chicken Sandwich\",\n \"orderAmount\": 4.99\n }, {\n \"id\": 2381224,\n \"email\": \"[email protected]\",\n \"userName\": \"Michael Lawson\",\n \"productName\": \"Chicken Sandwich\",\n \"orderAmount\": 4.99\n }, {\n \"id\": 2381224,\n \"email\": \"[email protected]\",\n \"userName\": \"Michael Lawson\",\n \"productName\": \"Chicken Sandwich\",\n \"orderAmount\": 4.99\n }, {\n \"id\": 2381224,\n \"email\": \"[email protected]\",\n \"userName\": \"Michael Lawson\",\n \"productName\": \"Chicken Sandwich\",\n \"orderAmount\": 4.99\n }, {\n \"id\": 2381224,\n \"email\": \"[email protected]\",\n \"userName\": \"Michael Lawson\",\n \"productName\": \"Chicken Sandwich\",\n \"orderAmount\": 4.99\n }, {\n \"id\": 2381224,\n \"email\": \"[email protected]\",\n \"userName\": \"Michael Lawson\",\n \"productName\": \"Chicken Sandwich\",\n \"orderAmount\": 4.99\n }, {\n \"id\": 2381224,\n \"email\": \"[email protected]\",\n \"userName\": \"Michael Lawson\",\n \"productName\": \"Chicken Sandwich\",\n \"orderAmount\": 4.99\n },\n {\n \"id\": 2736212,\n \"email\": \"[email protected]\",\n \"userName\": \"Lindsay Ferguson\",\n \"productName\": \"Tuna Salad\",\n \"orderAmount\": 9.99\n },\n {\n \"id\": 6788734,\n \"email\": \"[email protected]\",\n \"userName\": \"Tobias Funke\",\n \"productName\": \"Beef steak\",\n \"orderAmount\": 19.99\n },\n {\n \"id\": 7434532,\n \"email\": \"[email protected]\",\n \"userName\": \"Byron Fields\",\n \"productName\": \"Chicken Sandwich\",\n \"orderAmount\": 4.99\n },\n {\n \"id\": 7434532,\n \"email\": \"[email protected]\",\n \"userName\": \"Ryan Holmes\",\n \"productName\": \"Avocado Panini\",\n \"orderAmount\": 7.99\n },\n\t {\n \"id\": 7434532,\n \"email\": \"[email protected]\",\n \"userName\": \"Byron Fields\",\n \"productName\": \"Chicken Sandwich\",\n \"orderAmount\": 4.99\n },\n {\n \"id\": 7434532,\n \"email\": \"[email protected]\",\n \"userName\": \"Ryan Holmes\",\n \"productName\": \"Avocado Panini\",\n \"orderAmount\": 7.99\n },\n\t {\n \"id\": 7434532,\n \"email\": \"[email protected]\",\n \"userName\": \"Byron Fields\",\n \"productName\": \"Chicken Sandwich\",\n \"orderAmount\": 4.99\n },\n {\n \"id\": 7434532,\n \"email\": \"[email protected]\",\n \"userName\": \"Ryan Holmes\",\n \"productName\": \"Avocado Panini\",\n \"orderAmount\": 7.99\n },\n\t {\n \"id\": 7434532,\n \"email\": \"[email protected]\",\n \"userName\": \"Byron Fields\",\n \"productName\": \"Chicken Sandwich\",\n \"orderAmount\": 4.99\n },\n {\n \"id\": 7434532,\n \"email\": \"[email protected]\",\n \"userName\": \"Ryan Holmes\",\n \"productName\": \"Avocado Panini\",\n \"orderAmount\": 7.99\n },\n\t {\n \"id\": 7434532,\n \"email\": \"[email protected]\",\n \"userName\": \"Byron Fields\",\n \"productName\": \"Chicken Sandwich\",\n \"orderAmount\": 4.99\n },\n {\n \"id\": 7434532,\n \"email\": \"[email protected]\",\n \"userName\": \"Ryan Holmes\",\n \"productName\": \"Avocado Panini\",\n \"orderAmount\": 7.99\n }\n]}}", "label": "Data", "searchKey": "", "parentId": "0", @@ -282,6 +282,35 @@ "isVisibleSearch": true, "isVisiblePagination": true, "verticalAlignment": "CENTER" + }, + { + "widgetName": "Text1", + "rightColumn": 60, + "textAlign": "LEFT", + "displayName": "Text", + "widgetId": "16zkg2v0na", + "topRow": 83, + "bottomRow": 87, + "parentRowSpace": 10, + "isVisible": true, + "type": "TEXT_WIDGET", + "fontStyle": "BOLD", + "textColor": "#231F20", + "version": 1, + "hideCard": false, + "parentId": "0", + "isLoading": false, + "parentColumnSpace": 17.28125, + "dynamicTriggerPathList": [], + "leftColumn": 51, + "dynamicBindingPathList": [ + { + "key": "text" + } + ], + "fontSize": "PARAGRAPH", + "text": "{{Table1.previousPageVisited}} {{Table1.nextPageVisited}}", + "key": "r76o6tqjaz" } ] } diff --git a/app/client/cypress/integration/Regression_TestSuite/ClientSideTests/Widgets/TableV2/TableV2_PropertyPane_spec.js b/app/client/cypress/integration/Regression_TestSuite/ClientSideTests/Widgets/TableV2/TableV2_PropertyPane_spec.js index 30e964ccbdc9..088a4f63009f 100644 --- a/app/client/cypress/integration/Regression_TestSuite/ClientSideTests/Widgets/TableV2/TableV2_PropertyPane_spec.js +++ b/app/client/cypress/integration/Regression_TestSuite/ClientSideTests/Widgets/TableV2/TableV2_PropertyPane_spec.js @@ -215,7 +215,7 @@ describe("Table Widget V2 property pane feature validation", function () { cy.wait(500); cy.readTableV2dataPublish("1", "0").then((tabData2) => { expect(tabData2) - .to.equal("[email protected]") + .to.equal("[email protected]") .to.eq(actualEmail); cy.log("computed value of URL is " + tabData2); }); diff --git a/app/client/cypress/integration/Regression_TestSuite/ClientSideTests/Widgets/TableV2/TableV2_Widget_Copy_Paste_spec.js b/app/client/cypress/integration/Regression_TestSuite/ClientSideTests/Widgets/TableV2/TableV2_Widget_Copy_Paste_spec.js index 13c17715d910..44a6a873be1b 100644 --- a/app/client/cypress/integration/Regression_TestSuite/ClientSideTests/Widgets/TableV2/TableV2_Widget_Copy_Paste_spec.js +++ b/app/client/cypress/integration/Regression_TestSuite/ClientSideTests/Widgets/TableV2/TableV2_Widget_Copy_Paste_spec.js @@ -39,7 +39,7 @@ describe("Test Suite to validate copy/paste table Widget V2", function () { cy.selectAction("Show Bindings"); cy.wait(200); cy.get(apiwidget.propertyList).then(function ($lis) { - expect($lis).to.have.length(20); + expect($lis).to.have.length(22); expect($lis.eq(0)).to.contain("{{Table1Copy.selectedRow}}"); expect($lis.eq(1)).to.contain("{{Table1Copy.selectedRows}}"); }); diff --git a/app/client/cypress/integration/Regression_TestSuite/ClientSideTests/Widgets/TableV2/TableV2_pagination_spec.js b/app/client/cypress/integration/Regression_TestSuite/ClientSideTests/Widgets/TableV2/TableV2_pagination_spec.js index 1cd6424316a4..a9aa3433969b 100644 --- a/app/client/cypress/integration/Regression_TestSuite/ClientSideTests/Widgets/TableV2/TableV2_pagination_spec.js +++ b/app/client/cypress/integration/Regression_TestSuite/ClientSideTests/Widgets/TableV2/TableV2_pagination_spec.js @@ -1,5 +1,8 @@ const commonlocators = require("../../../../../locators/commonlocators.json"); const dsl = require("../../../../../fixtures/tableV2NewDslWithPagination.json"); +const { ObjectsRegistry } = require("../../../../../support/Objects/Registry"); + +const table = ObjectsRegistry.Table; describe("Table Widget property pane feature validation", function () { before(() => { @@ -13,10 +16,63 @@ describe("Table Widget property pane feature validation", function () { .click() .type("26"); cy.wait(1000); - cy.get(`.t--draggable-tablewidgetv2 span[data-pagecount="20"]`).should( + cy.get(`.t--draggable-tablewidgetv2 span[data-pagecount="11"]`).should( "exist", ); + // Cleanup + cy.UncheckWidgetProperties(commonlocators.serverSidePaginationCheckbox); cy.closePropertyPane(); }); + + it("2. updates previous and next pagination propeties properly in non server side pagination mode", function () { + cy.openPropertyPane("tablewidgetv2"); + + // The text field has two bindings in its text value, as below + // "{{Table1.previousPageVisited}} {{Table1.nextPageVisited}}" + + // Click on next page + cy.get(".t--table-widget-next-page").click(); + cy.get(commonlocators.bodyTextStyle).should("have.text", "false true"); + + // Click on previous page + cy.get(".t--table-widget-prev-page").click(); + cy.get(commonlocators.bodyTextStyle).should("have.text", "true false"); + + // Type and go to next page + cy.get(".t--table-widget-page-input .bp3-input").clear().type("2{enter}"); + cy.get(commonlocators.bodyTextStyle).should("have.text", "false true"); + + // Type and go to previous page + cy.get(".t--table-widget-page-input .bp3-input").clear().type("1{enter}"); + cy.get(commonlocators.bodyTextStyle).should("have.text", "true false"); + + // pagination flags should get reset whenever a user searches for any text + + table.SearchTable("Michael Lawson"); + cy.get(commonlocators.bodyTextStyle).should("have.text", "false false"); + table.resetSearch(); + + // Pagination properties should get reset when user filters for any criteria. + cy.get(".t--table-widget-next-page").click(); + cy.get(commonlocators.bodyTextStyle).should("have.text", "false true"); + table.OpenNFilterTable("userName", "contains", "Michael Lawson"); + cy.get(commonlocators.bodyTextStyle).should("have.text", "false false"); + table.RemoveFilter(); + + cy.get(".t--table-widget-next-page").click(); + cy.get(commonlocators.bodyTextStyle).should("have.text", "false true"); + + // pagination properties should work in server side mode + cy.CheckWidgetProperties(commonlocators.serverSidePaginationCheckbox); + cy.get(commonlocators.bodyTextStyle).should("have.text", "false false"); + + // Click on next page + cy.get(".t--table-widget-next-page").click(); + cy.get(commonlocators.bodyTextStyle).should("have.text", "false true"); + + // Click on previous page + cy.get(".t--table-widget-prev-page").click(); + cy.get(commonlocators.bodyTextStyle).should("have.text", "true false"); + }); }); diff --git a/app/client/cypress/support/Pages/Table.ts b/app/client/cypress/support/Pages/Table.ts index 8be7593647b0..9d8265dd1f91 100644 --- a/app/client/cypress/support/Pages/Table.ts +++ b/app/client/cypress/support/Pages/Table.ts @@ -350,11 +350,15 @@ export class Table { cy.get(this._searchText).eq(index).type(searchTxt); } + public resetSearch() { + this.agHelper.GetNClick(this._searchBoxCross); + } + public RemoveSearchTextNVerify( cellDataAfterSearchRemoved: string, tableVersion: "v1" | "v2" = "v1", ) { - this.agHelper.GetNClick(this._searchBoxCross); + this.resetSearch(); this.ReadTableRowColumnData(0, 0, tableVersion).then( (aftSearchRemoved: any) => { expect(aftSearchRemoved).to.eq(cellDataAfterSearchRemoved); @@ -394,6 +398,12 @@ export class Table { //this.agHelper.ClickButton("APPLY") } + public RemoveFilter(toClose = true, removeOne = false, index = 0) { + if (removeOne) this.agHelper.GetNClick(this._removeFilter, index); + else this.agHelper.GetNClick(this._clearAllFilter); + if (toClose) this.CloseFilter(); + } + public RemoveFilterNVerify( cellDataAfterFilterRemoved: string, toClose = true, @@ -401,9 +411,7 @@ export class Table { index = 0, tableVersion: "v1" | "v2" = "v1", ) { - if (removeOne) this.agHelper.GetNClick(this._removeFilter, index); - else this.agHelper.GetNClick(this._clearAllFilter); - if (toClose) this.CloseFilter(); + this.RemoveFilter(toClose, removeOne, index); this.ReadTableRowColumnData(0, 0, tableVersion).then( (aftFilterRemoved: any) => { expect(aftFilterRemoved).to.eq(cellDataAfterFilterRemoved); diff --git a/app/client/src/ce/utils/autocomplete/EntityDefinitions.ts b/app/client/src/ce/utils/autocomplete/EntityDefinitions.ts index 79066faf394d..5260c634696f 100644 --- a/app/client/src/ce/utils/autocomplete/EntityDefinitions.ts +++ b/app/client/src/ce/utils/autocomplete/EntityDefinitions.ts @@ -154,6 +154,8 @@ export const entityDefinitions = { tableHeaders: generateTypeDef(widget.tableHeaders), newRow: generateTypeDef(widget.newRow), isAddRowInProgress: "bool", + previousPageVisited: generateTypeDef(widget.previousPageVisited), + nextPageVisited: generateTypeDef(widget.nextPageButtonClicked), }), VIDEO_WIDGET: { "!doc": diff --git a/app/client/src/widgets/TableWidgetV2/constants.ts b/app/client/src/widgets/TableWidgetV2/constants.ts index 3fc13485980d..cf118ee0b7af 100644 --- a/app/client/src/widgets/TableWidgetV2/constants.ts +++ b/app/client/src/widgets/TableWidgetV2/constants.ts @@ -22,6 +22,12 @@ export type EditableCell = { inputValue: string; }; +export enum PaginationDirection { + INITIAL = "INITIAL", + PREVIOUS_PAGE = "PREVIOUS_PAGE", + NEXT_PAGE = "NEXT_PAGE", +} + export enum EditableCellActions { SAVE = "SAVE", DISCARD = "DISCARD", diff --git a/app/client/src/widgets/TableWidgetV2/widget/index.tsx b/app/client/src/widgets/TableWidgetV2/widget/index.tsx index 355dc4b828b1..b3add5253191 100644 --- a/app/client/src/widgets/TableWidgetV2/widget/index.tsx +++ b/app/client/src/widgets/TableWidgetV2/widget/index.tsx @@ -45,6 +45,7 @@ import { InlineEditingSaveOptions, ORIGINAL_INDEX_KEY, TABLE_COLUMN_ORDER_KEY, + PaginationDirection, } from "../constants"; import derivedProperties from "./parseDerivedProperties"; import { @@ -167,6 +168,8 @@ class TableWidgetV2 extends BaseWidget<TableWidgetProps, WidgetState> { isAddRowInProgress: false, newRowContent: undefined, newRow: undefined, + previousPageVisited: false, + nextPageVisited: false, }; } @@ -576,20 +579,24 @@ class TableWidgetV2 extends BaseWidget<TableWidgetProps, WidgetState> { if (!pageNo) { pushBatchMetaUpdates("pageNo", 1); + this.updatePaginationDirectionFlags(PaginationDirection.INITIAL); } //check if pageNo does not excede the max Page no, due to change of totalRecordsCount - if (serverSidePaginationEnabled && totalRecordsCount) { - const maxAllowedPageNumber = Math.ceil(totalRecordsCount / pageSize); - - if (pageNo > maxAllowedPageNumber) { - pushBatchMetaUpdates("pageNo", maxAllowedPageNumber); - } - } else if ( - serverSidePaginationEnabled !== prevProps.serverSidePaginationEnabled - ) { + if (serverSidePaginationEnabled !== prevProps.serverSidePaginationEnabled) { //reset pageNo when serverSidePaginationEnabled is toggled pushBatchMetaUpdates("pageNo", 1); + this.updatePaginationDirectionFlags(PaginationDirection.INITIAL); + } else { + //check if pageNo does not excede the max Page no, due to change of totalRecordsCount or change of pageSize + if (serverSidePaginationEnabled && totalRecordsCount) { + const maxAllowedPageNumber = Math.ceil(totalRecordsCount / pageSize); + + if (pageNo > maxAllowedPageNumber) { + pushBatchMetaUpdates("pageNo", maxAllowedPageNumber); + this.updatePaginationDirectionFlags(PaginationDirection.NEXT_PAGE); + } + } } /* @@ -614,6 +621,7 @@ class TableWidgetV2 extends BaseWidget<TableWidgetProps, WidgetState> { if (pageSize !== prevProps.pageSize) { if (onPageSizeChange) { + this.updatePaginationDirectionFlags(PaginationDirection.INITIAL); pushBatchMetaUpdates("pageNo", 1, { triggerPropertyName: "onPageSizeChange", dynamicString: onPageSizeChange, @@ -623,6 +631,7 @@ class TableWidgetV2 extends BaseWidget<TableWidgetProps, WidgetState> { }); } else { pushBatchMetaUpdates("pageNo", 1); + this.updatePaginationDirectionFlags(PaginationDirection.INITIAL); } } }; @@ -744,6 +753,7 @@ class TableWidgetV2 extends BaseWidget<TableWidgetProps, WidgetState> { // Reset Page only when a filter is added if (!isEmpty(xorWith(filters, [DEFAULT_FILTER], equal))) { pushBatchMetaUpdates("pageNo", 1); + this.updatePaginationDirectionFlags(PaginationDirection.INITIAL); } commitBatchMetaUpdates(); }; @@ -1063,6 +1073,8 @@ class TableWidgetV2 extends BaseWidget<TableWidgetProps, WidgetState> { } pushBatchMetaUpdates("pageNo", 1); + this.updatePaginationDirectionFlags(PaginationDirection.INITIAL); + pushBatchMetaUpdates("searchText", searchKey, { triggerPropertyName: "onSearchTextChanged", dynamicString: onSearchTextChanged, @@ -1215,6 +1227,12 @@ class TableWidgetV2 extends BaseWidget<TableWidgetProps, WidgetState> { updatePageNumber = (pageNo: number, event?: EventType) => { const { commitBatchMetaUpdates, pushBatchMetaUpdates } = this.props; + const paginationDirection = + event == EventType.ON_NEXT_PAGE + ? PaginationDirection.NEXT_PAGE + : PaginationDirection.PREVIOUS_PAGE; + this.updatePaginationDirectionFlags(paginationDirection); + if (event) { pushBatchMetaUpdates("pageNo", pageNo, { triggerPropertyName: "onPageChange", @@ -1233,10 +1251,40 @@ class TableWidgetV2 extends BaseWidget<TableWidgetProps, WidgetState> { commitBatchMetaUpdates(); }; + updatePaginationDirectionFlags = (direction?: PaginationDirection) => { + const { pushBatchMetaUpdates } = this.props; + + let previousButtonFlag = false; + let nextButtonFlag = false; + + if (direction) { + switch (direction) { + case PaginationDirection.INITIAL: { + previousButtonFlag = false; + nextButtonFlag = false; + break; + } + case PaginationDirection.NEXT_PAGE: { + nextButtonFlag = true; + break; + } + case PaginationDirection.PREVIOUS_PAGE: { + previousButtonFlag = true; + break; + } + } + } + + pushBatchMetaUpdates("previousPageVisited", previousButtonFlag); + pushBatchMetaUpdates("nextPageVisited", nextButtonFlag); + }; + handleNextPageClick = () => { const pageNo = (this.props.pageNo || 1) + 1; const { commitBatchMetaUpdates, pushBatchMetaUpdates } = this.props; + this.updatePaginationDirectionFlags(PaginationDirection.NEXT_PAGE); + pushBatchMetaUpdates("pageNo", pageNo, { triggerPropertyName: "onPageChange", dynamicString: this.props.onPageChange, @@ -1282,6 +1330,7 @@ class TableWidgetV2 extends BaseWidget<TableWidgetProps, WidgetState> { const { commitBatchMetaUpdates, pushBatchMetaUpdates } = this.props; if (pageNo >= 1) { + this.updatePaginationDirectionFlags(PaginationDirection.PREVIOUS_PAGE); pushBatchMetaUpdates("pageNo", pageNo, { triggerPropertyName: "onPageChange", dynamicString: this.props.onPageChange, @@ -2321,7 +2370,7 @@ class TableWidgetV2 extends BaseWidget<TableWidgetProps, WidgetState> { // New row gets added at the top of page 1 when client side pagination enabled if (!this.props.serverSidePaginationEnabled) { - pushBatchMetaUpdates("pageNo", 1); + this.updatePaginationDirectionFlags(PaginationDirection.INITIAL); } //Since we're adding a newRowContent thats not part of tableData, the index changes
dae3645f8d0864e73a54c0055c9137e68f098914
2023-11-17 16:51:18
Favour Ohanekwu
feat: Transform API/Query data based on widget's expected data type after 1-click binding (#28890)
false
Transform API/Query data based on widget's expected data type after 1-click binding (#28890)
feat
diff --git a/app/client/cypress/e2e/Regression/ClientSide/BugTests/Bug28731_Spec.ts b/app/client/cypress/e2e/Regression/ClientSide/BugTests/Bug28731_Spec.ts new file mode 100644 index 000000000000..c7fc42f39790 --- /dev/null +++ b/app/client/cypress/e2e/Regression/ClientSide/BugTests/Bug28731_Spec.ts @@ -0,0 +1,41 @@ +import OneClickBindingLocator from "../../../../locators/OneClickBindingLocator"; +import { + agHelper, + entityExplorer, + apiPage, + dataManager, + draggableWidgets, + propPane, +} from "../../../../support/Objects/ObjectsCore"; + +describe("transformed one-click binding", function () { + before(() => { + entityExplorer.NavigateToSwitcher("Explorer"); + }); + + it("Transforms API data to match widget exppected type ", function () { + // Create anAPI that mreturns object response + apiPage.CreateAndFillApi( + dataManager.dsValues[dataManager.defaultEnviorment].mockApiObjectUrl, + ); + apiPage.RunAPI(); + + // Table + entityExplorer.DragDropWidgetNVerify(draggableWidgets.TABLE, 300, 300); + + agHelper.GetNClick(OneClickBindingLocator.datasourceDropdownSelector); + agHelper.GetNClick(OneClickBindingLocator.datasourceQuerySelector("Api1")); + propPane.ToggleJSMode("Table Data", true); + agHelper.AssertContains("{{Api1.data.users}}"); + + // Select widget + entityExplorer.DragDropWidgetNVerify(draggableWidgets.SELECT, 100, 100); + + agHelper.GetNClick(OneClickBindingLocator.datasourceDropdownSelector); + agHelper.GetNClick(OneClickBindingLocator.datasourceQuerySelector("Api1")); + propPane.ToggleJSMode("Source Data", true); + agHelper.AssertContains( + "{{Api1.data.users.map( (obj) =>{ return {'label': obj.address, 'value': obj.avatar } })}}", + ); + }); +}); 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 d4952b806e2a..98ea15651143 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 @@ -13,7 +13,10 @@ import type { DropdownOptionType } from "../../../types"; import type { WidgetProps } from "widgets/BaseWidget"; import { WidgetQueryGeneratorFormContext } from "components/editorComponents/WidgetQueryGeneratorForm"; import { PluginPackageName } from "entities/Action"; -import type { ActionDataState } from "@appsmith/reducers/entityReducers/actionsReducer"; +import type { + ActionData, + ActionDataState, +} from "@appsmith/reducers/entityReducers/actionsReducer"; enum SortingWeights { alphabetical = 1, @@ -60,6 +63,16 @@ function sortQueries(queries: ActionDataState, expectedDatatype: string) { }); } +function getBindingValue(widget: WidgetProps, query: ActionData) { + const defaultBindingValue = `{{${query.config.name}.data}}`; + const querySuggestedWidgets = query.data?.suggestedWidgets; + if (!querySuggestedWidgets) return defaultBindingValue; + const suggestedWidget = querySuggestedWidgets.find( + (suggestedWidget) => suggestedWidget.type === widget.type, + ); + if (!suggestedWidget) return defaultBindingValue; + return `{{${query.config.name}.${suggestedWidget.bindingQuery}}}`; +} interface ConnectToOptionsProps { pluginImages: Record<string, string>; widget: WidgetProps; @@ -97,7 +110,7 @@ function useConnectToOptions(props: ConnectToOptionsProps) { return sortQueries(filteredQueries, expectedType).map((query) => ({ id: query.config.id, label: query.config.name, - value: `{{${query.config.name}.data}}`, + value: getBindingValue(widget, query), icon: ( <ImageWrapper> <DatasourceImage @@ -127,7 +140,7 @@ function useConnectToOptions(props: ConnectToOptionsProps) { }); }, })); - }, [filteredQueries, pluginImages, addBinding]); + }, [filteredQueries, pluginImages, addBinding, widget]); const currentPageWidgets = useSelector(getCurrentPageWidgets);
2b9299e2d305c6212d269b2ec6f38014114e04be
2025-02-06 11:20:08
Vemparala Surya Vamsi
chore: bypass immer for first evaluation, fixed cloneDeep issue and using mutative instead of immer (#38993)
false
bypass immer for first evaluation, fixed cloneDeep issue and using mutative instead of immer (#38993)
chore
diff --git a/app/client/package.json b/app/client/package.json index 1a4652a73863..8ae1f9249643 100644 --- a/app/client/package.json +++ b/app/client/package.json @@ -140,7 +140,6 @@ "fusioncharts": "^3.18.0", "graphql": "^16.8.1", "history": "^4.10.1", - "immer": "^9.0.6", "interweave": "^12.7.2", "interweave-autolink": "^4.4.2", "js-regex-pl": "^1.0.1", @@ -161,6 +160,7 @@ "mixpanel-browser": "^2.55.1", "moment": "2.29.4", "moment-timezone": "^0.5.35", + "mutative": "^1.1.0", "nanoid": "^2.0.4", "node-forge": "^1.3.0", "object-hash": "^3.0.0", @@ -331,6 +331,7 @@ "eslint-plugin-testing-library": "^6.2.0", "factory.ts": "^0.5.1", "husky": "^8.0.0", + "immer": "^9.0.6", "jest": "^29.6.1", "jest-canvas-mock": "^2.3.1", "jest-environment-jsdom": "^29.6.1", diff --git a/app/client/src/WidgetProvider/factory/index.tsx b/app/client/src/WidgetProvider/factory/index.tsx index 26e55f2a3f9f..f863b6530d88 100644 --- a/app/client/src/WidgetProvider/factory/index.tsx +++ b/app/client/src/WidgetProvider/factory/index.tsx @@ -35,7 +35,7 @@ import { import type { RegisteredWidgetFeatures } from "../../utils/WidgetFeatures"; import type { SetterConfig } from "entities/AppTheming"; import { freeze, memoize } from "./decorators"; -import produce from "immer"; +import { create } from "mutative"; import type { CanvasWidgetsReduxState } from "reducers/entityReducers/canvasWidgetsReducer"; import type { CopiedWidgetData, @@ -418,7 +418,7 @@ class WidgetFactory { if (dynamicProperties && dynamicProperties.length) { addPropertyConfigIds(dynamicProperties, false); - section = produce(section, (draft) => { + section = create(section, (draft) => { draft.children = [...dynamicProperties, ...section.children]; }); } diff --git a/app/client/src/ce/pages/Editor/Explorer/hooks.tsx b/app/client/src/ce/pages/Editor/Explorer/hooks.tsx index c9174bf94b70..f2d30d8779a1 100644 --- a/app/client/src/ce/pages/Editor/Explorer/hooks.tsx +++ b/app/client/src/ce/pages/Editor/Explorer/hooks.tsx @@ -6,7 +6,7 @@ import type { Datasource } from "entities/Datasource"; import { isStoredDatasource } from "entities/Action"; import type { WidgetProps } from "widgets/BaseWidget"; import log from "loglevel"; -import produce from "immer"; +import { create } from "mutative"; import type { CanvasStructure } from "reducers/uiReducers/pageCanvasStructureReducer"; import { getActions, getDatasources } from "ee/selectors/entitiesSelector"; import type { ActionData } from "ee/reducers/entityReducers/actionsReducer"; @@ -184,7 +184,7 @@ export const useActions = (searchKeyword?: string) => { return useMemo(() => { if (searchKeyword) { const start = performance.now(); - const filteredActions = produce(actions, (draft) => { + const filteredActions = create(actions, (draft) => { for (const [key, value] of Object.entries(draft)) { if (pageIds.includes(key)) { draft[key] = value; @@ -225,7 +225,7 @@ export const useWidgets = (searchKeyword?: string) => { return useMemo(() => { if (searchKeyword && pageCanvasStructures) { const start = performance.now(); - const filteredDSLs = produce(pageCanvasStructures, (draft) => { + const filteredDSLs = create(pageCanvasStructures, (draft) => { for (const [key, value] of Object.entries(draft)) { if (pageIds.includes(key)) { draft[key] = value; @@ -256,7 +256,7 @@ export const usePageIds = (searchKeyword?: string) => { return useMemo(() => { if (searchKeyword) { - const filteredPages = produce(pages, (draft) => { + const filteredPages = create(pages, (draft) => { draft.forEach((page, index) => { const searchMatches = page.pageName.toLowerCase().indexOf(searchKeyword.toLowerCase()) > diff --git a/app/client/src/ce/reducers/entityReducers/jsActionsReducer.tsx b/app/client/src/ce/reducers/entityReducers/jsActionsReducer.tsx index 60aad9fde696..4d267d75d041 100644 --- a/app/client/src/ce/reducers/entityReducers/jsActionsReducer.tsx +++ b/app/client/src/ce/reducers/entityReducers/jsActionsReducer.tsx @@ -6,7 +6,7 @@ import { ReduxActionErrorTypes, } from "ee/constants/ReduxActionConstants"; import { set, keyBy, findIndex, unset } from "lodash"; -import produce from "immer"; +import { create } from "mutative"; import { klona } from "klona"; export const initialState: JSCollectionDataState = []; @@ -400,7 +400,7 @@ export const handlers = { }> >, ) => { - return produce(state, (draft) => { + return create(state, (draft) => { const CollectionUpdateSearch = keyBy(action.payload, "collectionId"); const actionUpdateSearch = keyBy(action.payload, "id"); diff --git a/app/client/src/ce/reducers/uiReducers/applicationsReducer.tsx b/app/client/src/ce/reducers/uiReducers/applicationsReducer.tsx index 55c6327476ed..eaf285c6fe9e 100644 --- a/app/client/src/ce/reducers/uiReducers/applicationsReducer.tsx +++ b/app/client/src/ce/reducers/uiReducers/applicationsReducer.tsx @@ -22,7 +22,7 @@ import { defaultNavigationSetting, defaultThemeSetting, } from "constants/AppConstants"; -import produce from "immer"; +import { create } from "mutative"; import { isEmpty } from "lodash"; import type { ApplicationPayload } from "entities/Application"; import { gitConnectSuccess, type GitConnectSuccessPayload } from "git"; @@ -530,7 +530,7 @@ export const handlers = { state: ApplicationsReduxState, action: ReduxAction<NavigationSetting["logoAssetId"]>, ) => { - return produce(state, (draftState: ApplicationsReduxState) => { + return create(state, (draftState: ApplicationsReduxState) => { draftState.isUploadingNavigationLogo = false; if ( diff --git a/app/client/src/components/editorComponents/WidgetQueryGeneratorForm/index.tsx b/app/client/src/components/editorComponents/WidgetQueryGeneratorForm/index.tsx index aba8a7770462..db17e2747976 100644 --- a/app/client/src/components/editorComponents/WidgetQueryGeneratorForm/index.tsx +++ b/app/client/src/components/editorComponents/WidgetQueryGeneratorForm/index.tsx @@ -1,5 +1,5 @@ import React, { useCallback, useEffect, useMemo, useState } from "react"; -import produce from "immer"; +import { create } from "mutative"; import { noop, set } from "lodash"; import { CommonControls } from "./CommonControls"; @@ -179,7 +179,7 @@ function WidgetQueryGeneratorForm(props: Props) { setPristine(false); setConfig( - produce(config, (draftConfig) => { + create(config, (draftConfig) => { if ( property === "datasource" || (typeof property === "object" && diff --git a/app/client/src/components/propertyControls/ButtonTabControl.tsx b/app/client/src/components/propertyControls/ButtonTabControl.tsx index 7206d8b20ea4..db37f6645307 100644 --- a/app/client/src/components/propertyControls/ButtonTabControl.tsx +++ b/app/client/src/components/propertyControls/ButtonTabControl.tsx @@ -3,7 +3,7 @@ import type { ControlData, ControlProps } from "./BaseControl"; import BaseControl from "./BaseControl"; import type { ToggleGroupOption } from "@appsmith/ads"; import { ToggleButtonGroup } from "@appsmith/ads"; -import produce from "immer"; +import { create } from "mutative"; import type { DSEventDetail } from "utils/AppsmithUtils"; import { DSEventTypes, @@ -62,7 +62,7 @@ class ButtonTabControl extends BaseControl<ButtonTabControlProps> { isUpdatedViaKeyboard, ); } else { - const updatedValues: string[] = produce(values, (draft: string[]) => { + const updatedValues: string[] = create(values, (draft: string[]) => { draft.push(value); }); diff --git a/app/client/src/index.tsx b/app/client/src/index.tsx index 4f14d5f33a5a..2ebad23bccfa 100755 --- a/app/client/src/index.tsx +++ b/app/client/src/index.tsx @@ -23,15 +23,12 @@ import "./assets/styles/index.css"; import "./polyfills"; import GlobalStyles from "globalStyles"; // enable autofreeze only in development -import { setAutoFreeze } from "immer"; + import AppErrorBoundary from "./AppErrorBoundry"; import log from "loglevel"; import { FaroErrorBoundary } from "@grafana/faro-react"; import { isTracingEnabled } from "instrumentation/utils"; -const shouldAutoFreeze = process.env.NODE_ENV === "development"; - -setAutoFreeze(shouldAutoFreeze); runSagaMiddleware(); appInitializer(); diff --git a/app/client/src/reducers/entityReducers/datasourceReducer.ts b/app/client/src/reducers/entityReducers/datasourceReducer.ts index 1d20f11e5b94..f0c3d8f88153 100644 --- a/app/client/src/reducers/entityReducers/datasourceReducer.ts +++ b/app/client/src/reducers/entityReducers/datasourceReducer.ts @@ -13,7 +13,7 @@ import type { import { ToastMessageType } from "entities/Datasource"; import { TEMP_DATASOURCE_ID } from "constants/Datasource"; import type { DropdownOption } from "@appsmith/ads-old"; -import produce from "immer"; +import { create } from "mutative"; import { assign } from "lodash"; export interface DatasourceDataState { @@ -466,7 +466,7 @@ const datasourceReducer = createReducer(initialState, { state: DatasourceDataState, action: ReduxAction<Datasource>, ): DatasourceDataState => { - return produce(state, (draftState) => { + return create(state, (draftState) => { draftState.loading = false; draftState.list.forEach((datasource) => { if (datasource.id === action.payload.id) { @@ -656,7 +656,7 @@ const datasourceReducer = createReducer(initialState, { [ReduxActionTypes.FETCH_GSHEET_SPREADSHEETS]: ( state: DatasourceDataState, ) => { - return produce(state, (draftState) => { + return create(state, (draftState) => { draftState.gsheetStructure.isFetchingSpreadsheets = true; }); }, @@ -664,7 +664,7 @@ const datasourceReducer = createReducer(initialState, { state: DatasourceDataState, action: ReduxAction<{ id: string; data: DropdownOption[] }>, ) => { - return produce(state, (draftState) => { + return create(state, (draftState) => { draftState.gsheetStructure.spreadsheets[action.payload.id] = { value: action.payload.data, }; @@ -676,7 +676,7 @@ const datasourceReducer = createReducer(initialState, { state: DatasourceDataState, action: ReduxAction<{ id: string; error: string }>, ) => { - return produce(state, (draftState) => { + return create(state, (draftState) => { draftState.gsheetStructure.spreadsheets[action.payload.id] = { error: action.payload.error, }; @@ -685,7 +685,7 @@ const datasourceReducer = createReducer(initialState, { }); }, [ReduxActionTypes.FETCH_GSHEET_SHEETS]: (state: DatasourceDataState) => { - return produce(state, (draftState) => { + return create(state, (draftState) => { draftState.gsheetStructure.isFetchingSheets = true; }); }, @@ -693,7 +693,7 @@ const datasourceReducer = createReducer(initialState, { state: DatasourceDataState, action: ReduxAction<{ id: string; data: DropdownOption[] }>, ) => { - return produce(state, (draftState) => { + return create(state, (draftState) => { draftState.gsheetStructure.sheets[action.payload.id] = { value: action.payload.data, }; @@ -704,7 +704,7 @@ const datasourceReducer = createReducer(initialState, { state: DatasourceDataState, action: ReduxAction<{ id: string; error: string }>, ) => { - return produce(state, (draftState) => { + return create(state, (draftState) => { draftState.gsheetStructure.sheets[action.payload.id] = { error: action.payload.error, }; @@ -712,7 +712,7 @@ const datasourceReducer = createReducer(initialState, { }); }, [ReduxActionTypes.FETCH_GSHEET_COLUMNS]: (state: DatasourceDataState) => { - return produce(state, (draftState) => { + return create(state, (draftState) => { draftState.gsheetStructure.isFetchingColumns = true; }); }, @@ -720,7 +720,7 @@ const datasourceReducer = createReducer(initialState, { state: DatasourceDataState, action: ReduxAction<{ id: string; data: DropdownOption[] }>, ) => { - return produce(state, (draftState) => { + return create(state, (draftState) => { draftState.gsheetStructure.columns[action.payload.id] = { value: action.payload.data, }; @@ -731,7 +731,7 @@ const datasourceReducer = createReducer(initialState, { state: DatasourceDataState, action: ReduxAction<{ id: string; error: string }>, ) => { - return produce(state, (draftState) => { + return create(state, (draftState) => { draftState.gsheetStructure.columns[action.payload.id] = { error: action.payload.error, }; diff --git a/app/client/src/reducers/entityReducers/metaReducer/index.ts b/app/client/src/reducers/entityReducers/metaReducer/index.ts index 26f0db37810b..810201b449ef 100644 --- a/app/client/src/reducers/entityReducers/metaReducer/index.ts +++ b/app/client/src/reducers/entityReducers/metaReducer/index.ts @@ -11,7 +11,7 @@ import { ReduxActionTypes, WidgetReduxActionTypes, } from "ee/constants/ReduxActionConstants"; -import produce from "immer"; +import { create } from "mutative"; import type { EvalMetaUpdates } from "ee/workers/common/DataTreeEvaluator/types"; import { getMetaWidgetResetObj, @@ -38,7 +38,7 @@ export const metaReducer = createReducer(initialState, { state: MetaState, action: ReduxAction<UpdateWidgetMetaPropertyPayload>, ) => { - const nextState = produce(state, (draftMetaState) => { + const nextState = create(state, (draftMetaState) => { set( draftMetaState, `${action.payload.widgetId}.${action.payload.propertyName}`, @@ -54,7 +54,7 @@ export const metaReducer = createReducer(initialState, { state: MetaState, action: ReduxAction<BatchUpdateWidgetMetaPropertyPayload>, ) => { - const nextState = produce(state, (draftMetaState) => { + const nextState = create(state, (draftMetaState) => { const { batchMetaUpdates } = action.payload; batchMetaUpdates.forEach(({ propertyName, propertyValue, widgetId }) => { @@ -70,7 +70,7 @@ export const metaReducer = createReducer(initialState, { state: MetaState, action: ReduxAction<UpdateWidgetMetaPropertyPayload>, ) => { - const nextState = produce(state, (draftMetaState) => { + const nextState = create(state, (draftMetaState) => { set( draftMetaState, `${action.payload.widgetId}.${action.payload.propertyName}`, diff --git a/app/client/src/reducers/entityReducers/metaReducer/metaReducerUtils.ts b/app/client/src/reducers/entityReducers/metaReducer/metaReducerUtils.ts index 43ca882f5101..6bf8aeac0c3a 100644 --- a/app/client/src/reducers/entityReducers/metaReducer/metaReducerUtils.ts +++ b/app/client/src/reducers/entityReducers/metaReducer/metaReducerUtils.ts @@ -6,7 +6,7 @@ import type { import type { MetaState, WidgetMetaState } from "."; import type { ReduxAction } from "actions/ReduxActionTypes"; import type { EvalMetaUpdates } from "ee/workers/common/DataTreeEvaluator/types"; -import produce from "immer"; +import { create } from "mutative"; import { set, unset } from "lodash"; import { klonaRegularWithTelemetry } from "utils/helpers"; @@ -82,7 +82,7 @@ export function getNextMetaStateWithUpdates( if (!evalMetaUpdates.length) return state; // if metaObject is updated in dataTree we also update meta values, to keep meta state in sync. - const newMetaState = produce(state, (draftMetaState) => { + const newMetaState = create(state, (draftMetaState) => { evalMetaUpdates.forEach(({ metaPropertyPath, value, widgetId }) => { set(draftMetaState, [widgetId, ...metaPropertyPath], value); }); diff --git a/app/client/src/reducers/evaluationReducers/treeReducer.ts b/app/client/src/reducers/evaluationReducers/treeReducer.ts index 53f6c5034dbe..a8be85d9f1dd 100644 --- a/app/client/src/reducers/evaluationReducers/treeReducer.ts +++ b/app/client/src/reducers/evaluationReducers/treeReducer.ts @@ -1,10 +1,9 @@ import type { ReduxAction } from "actions/ReduxActionTypes"; import { ReduxActionTypes } from "ee/constants/ReduxActionConstants"; -import { applyChange } from "deep-diff"; +import { applyChange, type Diff } from "deep-diff"; import type { DataTree } from "entities/DataTree/dataTreeTypes"; import { createImmerReducer } from "utils/ReducerUtils"; import * as Sentry from "@sentry/react"; -import type { DiffWithNewTreeState } from "workers/Evaluation/helpers"; export type EvaluatedTreeState = DataTree; @@ -15,7 +14,7 @@ const evaluatedTreeReducer = createImmerReducer(initialState, { state: EvaluatedTreeState, action: ReduxAction<{ dataTree: DataTree; - updates: DiffWithNewTreeState[]; + updates: Diff<DataTree, DataTree>[]; removedPaths: [string]; }>, ) => { @@ -27,15 +26,11 @@ const evaluatedTreeReducer = createImmerReducer(initialState, { for (const update of updates) { try { - if (update.kind === "newTree") { - return update.rhs; - } else { - if (!update.path || update.path.length === 0) { - continue; - } - - applyChange(state, undefined, update); + if (!update.path || update.path.length === 0) { + continue; } + + applyChange(state, undefined, update); } catch (e) { Sentry.captureException(e, { extra: { diff --git a/app/client/src/sagas/WidgetAdditionSagas.ts b/app/client/src/sagas/WidgetAdditionSagas.ts index 7fd5792b583d..9f36040d190b 100644 --- a/app/client/src/sagas/WidgetAdditionSagas.ts +++ b/app/client/src/sagas/WidgetAdditionSagas.ts @@ -20,7 +20,7 @@ import { } from "constants/WidgetConstants"; import { toast } from "@appsmith/ads"; import type { DataTree } from "entities/DataTree/dataTreeTypes"; -import produce from "immer"; +import { create } from "mutative"; import { klona as clone } from "klona/full"; import { getWidgetMinMaxDimensionsInPixel } from "layoutSystems/autolayout/utils/flexWidgetUtils"; import { ResponsiveBehavior } from "layoutSystems/common/utils/constants"; @@ -112,7 +112,7 @@ function* getChildWidgetProps( // if (props) props.children = []; if (props) { - props = produce(props, (draft: WidgetProps) => { + props = create(props, (draft) => { if (!draft.children || !Array.isArray(draft.children)) { draft.children = []; } diff --git a/app/client/src/utils/ReducerUtils.ts b/app/client/src/utils/ReducerUtils.ts index 9a25f1dcfd0e..9a492352b847 100644 --- a/app/client/src/utils/ReducerUtils.ts +++ b/app/client/src/utils/ReducerUtils.ts @@ -1,5 +1,5 @@ import type { ReduxAction } from "actions/ReduxActionTypes"; -import produce from "immer"; +import { create } from "mutative"; export const createReducer = ( // TODO: Fix this the next time the file is edited @@ -32,7 +32,19 @@ export const createImmerReducer = ( // eslint-disable-next-line @typescript-eslint/no-explicit-any return function reducer(state = initialState, action: ReduxAction<any>) { if (handlers.hasOwnProperty(action.type)) { - return produce(handlers[action.type])(state, action); + if (action?.payload?.updates) { + const updates = action?.payload?.updates; + + for (const update of updates) { + if (update.kind === "newTree") { + return update.rhs; + } + } + } + + const fn = handlers[action.type]; + + return create(state, (draft) => fn(draft, action)); } else { return state; } diff --git a/app/client/src/widgets/TableWidgetV2/widget/index.tsx b/app/client/src/widgets/TableWidgetV2/widget/index.tsx index 586fcd9bc2d3..b81f652b779f 100644 --- a/app/client/src/widgets/TableWidgetV2/widget/index.tsx +++ b/app/client/src/widgets/TableWidgetV2/widget/index.tsx @@ -3,7 +3,6 @@ import log from "loglevel"; import memoizeOne from "memoize-one"; import _, { - cloneDeep, filter, isArray, isEmpty, @@ -142,6 +141,7 @@ import IconSVG from "../icon.svg"; import ThumbnailSVG from "../thumbnail.svg"; import { klonaRegularWithTelemetry } from "utils/helpers"; import HTMLCell from "../component/cellComponents/HTMLCell"; +import { objectKeys } from "@appsmith/utils"; const ReactTableComponent = lazy(async () => retryPromise(async () => import("../component")), @@ -928,16 +928,23 @@ class TableWidgetV2 extends BaseWidget<TableWidgetProps, WidgetState> { * @rahulbarwal Remove this once we remove the feature flag */ if (!TableWidgetV2.getFeatureFlag(HTML_COLUMN_TYPE_ENABLED)) { - const updatedPrimaryColumns = cloneDeep(this.props.primaryColumns); let hasHTMLColumns = false; + const { primaryColumns } = this.props; + + const updatedPrimaryColumns = objectKeys(primaryColumns).reduce( + (acc, widgetId) => { + const column = primaryColumns[widgetId]; - Object.values(updatedPrimaryColumns).forEach( - (column: ColumnProperties) => { if (column.columnType === ColumnTypes.HTML) { - column.columnType = ColumnTypes.TEXT; + acc[widgetId] = { ...column, columnType: ColumnTypes.TEXT }; hasHTMLColumns = true; + } else { + acc[widgetId] = column; } + + return acc; }, + {} as Record<string, ColumnProperties>, ); if (hasHTMLColumns) { diff --git a/app/client/src/workers/Evaluation/__tests__/generateOpimisedUpdates.test.ts b/app/client/src/workers/Evaluation/__tests__/generateOpimisedUpdates.test.ts index 5e8b07703770..cea35fb62d9a 100644 --- a/app/client/src/workers/Evaluation/__tests__/generateOpimisedUpdates.test.ts +++ b/app/client/src/workers/Evaluation/__tests__/generateOpimisedUpdates.test.ts @@ -1,6 +1,6 @@ import type { WidgetEntity } from "ee/entities/DataTree/types"; import { applyChange } from "deep-diff"; -import produce from "immer"; +import { create } from "mutative"; import { klona } from "klona/full"; import { range } from "lodash"; import moment from "moment"; @@ -110,7 +110,7 @@ const oldState: dataTreeWithWidget = { describe("generateOptimisedUpdates", () => { describe("regular diff", () => { test("should not generate any diff when the constrainedDiffPaths is empty", () => { - const newState = produce(oldState, (draft) => { + const newState = create(oldState, (draft) => { draft.Table1.pageSize = 17; }); const updates = generateOptimisedUpdates(oldState, newState, []); @@ -119,7 +119,7 @@ describe("generateOptimisedUpdates", () => { expect(updates).toEqual([]); }); test("should not generate any diff when the constrainedDiffPaths nodes are the same ", () => { - const newState = produce(oldState, (draft) => { + const newState = create(oldState, (draft) => { //making an unrelated change draft.Table1.triggerRowSelection = true; }); @@ -131,7 +131,7 @@ describe("generateOptimisedUpdates", () => { expect(updates).toEqual([]); }); test("should generate regular diff updates when a simple property changes in the widget property segment", () => { - const newState = produce(oldState, (draft) => { + const newState = create(oldState, (draft) => { draft.Table1.pageSize = 17; }); const updates = generateOptimisedUpdates(oldState, newState, [ @@ -145,7 +145,7 @@ describe("generateOptimisedUpdates", () => { test("should generate regular diff updates when a simple property changes in the __evaluation__ segment ", () => { const validationError = "Some validation error" as unknown as EvaluationError[]; - const newState = produce(oldState, (draft) => { + const newState = create(oldState, (draft) => { draft.Table1.__evaluation__.errors.tableData = validationError; }); const updates = generateOptimisedUpdates(oldState, newState, [ @@ -162,7 +162,7 @@ describe("generateOptimisedUpdates", () => { ]); }); test("should generate a replace collection patch when the size of the collection exceeds 100 instead of generating granular updates", () => { - const newState = produce(oldState, (draft) => { + const newState = create(oldState, (draft) => { draft.Table1.tableData = largeDataSet; }); const updates = generateOptimisedUpdates(oldState, newState, [ @@ -179,10 +179,10 @@ describe("generateOptimisedUpdates", () => { }); describe("undefined value updates in a collection", () => { test("should generate replace patch when a single node is set to undefined in a collection", () => { - const statWithLargeCollection = produce(oldState, (draft) => { + const statWithLargeCollection = create(oldState, (draft) => { draft.Table1.tableData = ["a", "b"]; }); - const newStateWithAnElementDeleted = produce( + const newStateWithAnElementDeleted = create( statWithLargeCollection, (draft) => { draft.Table1.tableData = ["a", undefined]; @@ -204,10 +204,10 @@ describe("generateOptimisedUpdates", () => { ]); }); test("should generate generate regular diff updates for non undefined updates in a collection", () => { - const statWithLargeCollection = produce(oldState, (draft) => { + const statWithLargeCollection = create(oldState, (draft) => { draft.Table1.tableData = ["a", "b"]; }); - const newStateWithAnElementDeleted = produce( + const newStateWithAnElementDeleted = create( statWithLargeCollection, (draft) => { draft.Table1.tableData = ["a", "e"]; @@ -244,7 +244,7 @@ describe("generateOptimisedUpdates", () => { expect(serialisedUpdates).toEqual(JSON.stringify(additionalUpdates)); }); it("should ignore undefined updates", () => { - const oldStateWithUndefinedValues = produce(oldState, (draft) => { + const oldStateWithUndefinedValues = create(oldState, (draft) => { draft.Table1.pageSize = undefined; }); @@ -260,7 +260,7 @@ describe("generateOptimisedUpdates", () => { expect(serialisedUpdates).toEqual(JSON.stringify(additionalUpdates)); }); it("should generate a delete patch when a property is transformed to undefined", () => { - const oldStateWithUndefinedValues = produce(oldState, (draft) => { + const oldStateWithUndefinedValues = create(oldState, (draft) => { draft.Table1.pageSize = undefined; }); @@ -281,7 +281,7 @@ describe("generateOptimisedUpdates", () => { ]); }); it("should generate an error when there is a serialisation error", () => { - const oldStateWithUndefinedValues = produce(oldState, (draft) => { + const oldStateWithUndefinedValues = create(oldState, (draft) => { //generate a cyclical object draft.Table1.filteredTableData = draft.Table1; }); @@ -302,7 +302,7 @@ describe("generateOptimisedUpdates", () => { const someEvalFn = (() => {}) as unknown as EvaluationError[]; it("should clean out new function properties added to the generated state", () => { - const newStateWithSomeFnProperty = produce(oldState, (draft) => { + const newStateWithSomeFnProperty = create(oldState, (draft) => { draft.Table1.someFn = () => {}; draft.Table1.__evaluation__.errors.someEvalFn = someEvalFn; }); @@ -320,7 +320,7 @@ describe("generateOptimisedUpdates", () => { //should delete all function updates expect(parsedUpdates).toEqual([]); - const parseAndApplyUpdatesToOldState = produce(oldState, (draft) => { + const parseAndApplyUpdatesToOldState = create(oldState, (draft) => { // TODO: Fix this the next time the file is edited // eslint-disable-next-line @typescript-eslint/no-explicit-any parsedUpdates.forEach((v: any) => { @@ -333,7 +333,7 @@ describe("generateOptimisedUpdates", () => { }); it("should delete properties which get updated to a function", () => { - const newStateWithSomeFnProperty = produce(oldState, (draft) => { + const newStateWithSomeFnProperty = create(oldState, (draft) => { draft.Table1.pageSize = () => {}; draft.Table1.__evaluation__.errors.transientTableData = someEvalFn; }); @@ -362,14 +362,14 @@ describe("generateOptimisedUpdates", () => { }, ]); - const parseAndApplyUpdatesToOldState = produce(oldState, (draft) => { + const parseAndApplyUpdatesToOldState = create(oldState, (draft) => { // TODO: Fix this the next time the file is edited // eslint-disable-next-line @typescript-eslint/no-explicit-any parsedUpdates.forEach((v: any) => { applyChange(draft, undefined, v); }); }); - const expectedState = produce(oldState, (draft) => { + const expectedState = create(oldState, (draft) => { delete draft.Table1.pageSize; delete draft.Table1.__evaluation__.errors.transientTableData; }); @@ -377,14 +377,14 @@ describe("generateOptimisedUpdates", () => { expect(parseAndApplyUpdatesToOldState).toEqual(expectedState); }); it("should delete function properties which get updated to undefined", () => { - const oldStateWithSomeFnProperty = produce(oldState, (draft) => { + const oldStateWithSomeFnProperty = create(oldState, (draft) => { // eslint-disable-next-line @typescript-eslint/no-empty-function draft.Table1.pageSize = () => {}; draft.Table1.__evaluation__.errors.transientTableData = // eslint-disable-next-line @typescript-eslint/no-empty-function someEvalFn; }); - const newStateWithFnsTransformedToUndefined = produce( + const newStateWithFnsTransformedToUndefined = create( oldState, (draft) => { draft.Table1.pageSize = undefined; @@ -417,14 +417,14 @@ describe("generateOptimisedUpdates", () => { }, ]); - const parseAndApplyUpdatesToOldState = produce(oldState, (draft) => { + const parseAndApplyUpdatesToOldState = create(oldState, (draft) => { // TODO: Fix this the next time the file is edited // eslint-disable-next-line @typescript-eslint/no-explicit-any parsedUpdates.forEach((v: any) => { applyChange(draft, undefined, v); }); }); - const expectedState = produce(oldState, (draft) => { + const expectedState = create(oldState, (draft) => { delete draft.Table1.pageSize; delete draft.Table1.__evaluation__.errors.transientTableData; }); @@ -443,7 +443,7 @@ describe("generateOptimisedUpdates", () => { rhs: { someOtherKey: BigInt(3323232) }, }, ]; - const newStateWithBigInt = produce(oldState, (draft) => { + const newStateWithBigInt = create(oldState, (draft) => { draft.Table1.pageSize = someBigInt; }); const { serialisedUpdates } = generateSerialisedUpdates( @@ -472,14 +472,14 @@ describe("generateOptimisedUpdates", () => { }, ]); - const parseAndApplyUpdatesToOldState = produce(oldState, (draft) => { + const parseAndApplyUpdatesToOldState = create(oldState, (draft) => { // TODO: Fix this the next time the file is edited // eslint-disable-next-line @typescript-eslint/no-explicit-any parsedUpdates.forEach((v: any) => { applyChange(draft, undefined, v); }); }); - const expectedState = produce(oldState, (draft) => { + const expectedState = create(oldState, (draft) => { draft.Table1.pageSize = "121221"; draft.Table1.someNewProp = { someOtherKey: "3323232" }; }); @@ -488,7 +488,7 @@ describe("generateOptimisedUpdates", () => { }); describe("serialise momement updates directly", () => { test("should generate a null update when it sees an invalid moment object", () => { - const newState = produce(oldState, (draft) => { + const newState = create(oldState, (draft) => { draft.Table1.pageSize = moment("invalid value"); }); const { serialisedUpdates } = generateSerialisedUpdates( @@ -504,7 +504,7 @@ describe("generateOptimisedUpdates", () => { }); test("should generate a regular update when it sees a valid moment object", () => { const validMoment = moment(); - const newState = produce(oldState, (draft) => { + const newState = create(oldState, (draft) => { draft.Table1.pageSize = validMoment; }); const { serialisedUpdates } = generateSerialisedUpdates( @@ -529,7 +529,7 @@ describe("generateOptimisedUpdates", () => { const parsedUpdates = parseUpdatesAndDeleteUndefinedUpdates(serialisedUpdates); - return produce(prevState, (draft) => { + return create(prevState, (draft) => { // TODO: Fix this the next time the file is edited // eslint-disable-next-line @typescript-eslint/no-explicit-any parsedUpdates.forEach((v: any) => { @@ -552,7 +552,7 @@ describe("generateOptimisedUpdates", () => { } //attaching a collection to some property in the workerState - workerStateWithCollection = produce(oldState, (draft) => { + workerStateWithCollection = create(oldState, (draft) => { draft.Table1.pageSize = largeCollection; }); //generate serialised diff updates @@ -569,7 +569,7 @@ describe("generateOptimisedUpdates", () => { oldState, ); - const expectedMainThreadState = produce(oldState, (draft) => { + const expectedMainThreadState = create(oldState, (draft) => { draft.Table1.pageSize = JSON.parse(JSON.stringify(largeCollection)); }); @@ -583,7 +583,7 @@ describe("generateOptimisedUpdates", () => { test("update in a single moment value in a collection should always be serialised ", () => { const someNewDate = "2023-12-07T19:05:11.930Z"; // updating a single value in the prev worker state - const updatedWorkerStateWithASingleValue = produce( + const updatedWorkerStateWithASingleValue = create( klona(workerStateWithCollection), (draft) => { draft.Table1.pageSize[0].c = moment(someNewDate); @@ -613,7 +613,7 @@ describe("generateOptimisedUpdates", () => { someNewDate, ); - const expectedMainThreadState = produce( + const expectedMainThreadState = create( mainThreadStateWithCollection, (draft) => { draft.Table1.pageSize[0].c = JSON.parse( @@ -628,7 +628,7 @@ describe("generateOptimisedUpdates", () => { //some garbage value const someNewDate = "fdfdfd"; // updating a single value in the prev worker state - const updatedWorkerStateWithASingleValue = produce( + const updatedWorkerStateWithASingleValue = create( klona(workerStateWithCollection), (draft) => { // TODO: Fix this the next time the file is edited @@ -658,7 +658,7 @@ describe("generateOptimisedUpdates", () => { // check if the main thread state has the updated invalid value which should be null expect(updatedMainThreadState.Table1.pageSize[0].c).toEqual(null); - const expectedMainThreadState = produce( + const expectedMainThreadState = create( mainThreadStateWithCollection, (draft) => { draft.Table1.pageSize[0].c = JSON.parse( diff --git a/app/client/src/workers/Evaluation/evalTreeWithChanges.test.ts b/app/client/src/workers/Evaluation/evalTreeWithChanges.test.ts index e4dc617bca57..a6da206ec989 100644 --- a/app/client/src/workers/Evaluation/evalTreeWithChanges.test.ts +++ b/app/client/src/workers/Evaluation/evalTreeWithChanges.test.ts @@ -4,7 +4,7 @@ import { RenderModes } from "constants/WidgetConstants"; import { ENTITY_TYPE } from "ee/entities/DataTree/types"; import type { ConfigTree } from "entities/DataTree/dataTreeTypes"; import { generateDataTreeWidget } from "entities/DataTree/dataTreeWidget"; -import produce from "immer"; +import { create } from "mutative"; import type { WidgetEntity } from "plugins/Linting/lib/entity/WidgetEntity"; import type { UpdateDataTreeMessageData } from "sagas/EvalWorkerActionSagas"; import DataTreeEvaluator from "workers/common/DataTreeEvaluator"; @@ -259,7 +259,7 @@ describe("evaluateAndGenerateResponse", () => { test("should generate updates based on the unEvalUpdates", () => { // TODO: Fix this the next time the file is edited // eslint-disable-next-line @typescript-eslint/no-explicit-any - const updatedLabelUnevalTree = produce(unEvalTree, (draft: any) => { + const updatedLabelUnevalTree = create(unEvalTree, (draft: any) => { draft.Text1.text = UPDATED_LABEL; draft.Text1.label = UPDATED_LABEL; }); @@ -311,7 +311,7 @@ describe("evaluateAndGenerateResponse", () => { test("should generate updates based on the evalOrder", () => { // TODO: Fix this the next time the file is edited // eslint-disable-next-line @typescript-eslint/no-explicit-any - const updatedLabelUnevalTree = produce(unEvalTree, (draft: any) => { + const updatedLabelUnevalTree = create(unEvalTree, (draft: any) => { draft.Text1.text = UPDATED_LABEL; }); const updateTreeResponse = evaluator.setupUpdateTree( @@ -346,7 +346,7 @@ describe("evaluateAndGenerateResponse", () => { test("should generate the correct updates to be sent to the main thread's state when the value tied to a binding changes ", () => { // TODO: Fix this the next time the file is edited // eslint-disable-next-line @typescript-eslint/no-explicit-any - const updatedLabelUnevalTree = produce(unEvalTree, (draft: any) => { + const updatedLabelUnevalTree = create(unEvalTree, (draft: any) => { if (draft.Text1?.text) { draft.Text1.text = UPDATED_LABEL; } @@ -386,7 +386,7 @@ describe("evaluateAndGenerateResponse", () => { test("should merge additional updates to the dataTree as well as push the updates back to the main thread's state when unEvalUpdates is ignored", () => { // TODO: Fix this the next time the file is edited // eslint-disable-next-line @typescript-eslint/no-explicit-any - const updatedLabelUnevalTree = produce(unEvalTree, (draft: any) => { + const updatedLabelUnevalTree = create(unEvalTree, (draft: any) => { if (draft.Text1?.text) { draft.Text1.text = UPDATED_LABEL; } @@ -426,7 +426,7 @@ describe("evaluateAndGenerateResponse", () => { test("should add metaUpdates in the webworker's response", () => { // TODO: Fix this the next time the file is edited // eslint-disable-next-line @typescript-eslint/no-explicit-any - const updatedLabelUnevalTree = produce(unEvalTree, (draft: any) => { + const updatedLabelUnevalTree = create(unEvalTree, (draft: any) => { if (draft.Text1?.text) { draft.Text1.text = UPDATED_LABEL; } @@ -456,7 +456,7 @@ describe("evaluateAndGenerateResponse", () => { test("should sanitise metaUpdates in the webworker's response and strip out non serialisable properties", () => { // TODO: Fix this the next time the file is edited // eslint-disable-next-line @typescript-eslint/no-explicit-any - const updatedLabelUnevalTree = produce(unEvalTree, (draft: any) => { + const updatedLabelUnevalTree = create(unEvalTree, (draft: any) => { if (draft.Text1?.text) { draft.Text1.text = UPDATED_LABEL; } @@ -495,7 +495,7 @@ describe("evaluateAndGenerateResponse", () => { test("should add unEvalUpdates to the web worker response", () => { // TODO: Fix this the next time the file is edited // eslint-disable-next-line @typescript-eslint/no-explicit-any - const updatedLabelUnevalTree = produce(unEvalTree, (draft: any) => { + const updatedLabelUnevalTree = create(unEvalTree, (draft: any) => { if (draft.Text1?.text) { draft.Text1.text = UPDATED_LABEL; } @@ -533,7 +533,7 @@ describe("evaluateAndGenerateResponse", () => { test("should ignore generating updates when unEvalUpdates is empty", () => { // TODO: Fix this the next time the file is edited // eslint-disable-next-line @typescript-eslint/no-explicit-any - const updatedLabelUnevalTree = produce(unEvalTree, (draft: any) => { + const updatedLabelUnevalTree = create(unEvalTree, (draft: any) => { if (draft.Text1?.text) { draft.Text1.text = UPDATED_LABEL; } diff --git a/app/client/src/workers/common/DataTreeEvaluator/utils.test.ts b/app/client/src/workers/common/DataTreeEvaluator/utils.test.ts index 2c0597760a23..fff436dd8982 100644 --- a/app/client/src/workers/common/DataTreeEvaluator/utils.test.ts +++ b/app/client/src/workers/common/DataTreeEvaluator/utils.test.ts @@ -6,7 +6,7 @@ import { getAllPathsBasedOnDiffPaths, type DataTreeDiff, } from "ee/workers/Evaluation/evaluationUtils"; -import produce from "immer"; +import { create } from "mutative"; describe("getOnlyAffectedJSObjects", () => { const dataTree = { @@ -170,7 +170,7 @@ describe("getAllPathsBasedOnDiffPaths", () => { expect(initialAllKeys).toEqual(updatedAllKeys); }); test("should delete the correct paths within allKeys when a node within a widget is deleted", () => { - const deletedWidgetName = produce(initialTree, (draft) => { + const deletedWidgetName = create(initialTree, (draft) => { // a property within the widget is deleted delete draft.WidgetName.name; }); @@ -187,7 +187,7 @@ describe("getAllPathsBasedOnDiffPaths", () => { // we have to make a copy since allKeys is mutable { ...initialAllKeys }, ); - const deletedWidgetNameInAllKeys = produce(initialAllKeys, (draft) => { + const deletedWidgetNameInAllKeys = create(initialAllKeys, (draft) => { delete draft["WidgetName.name"]; }); @@ -195,7 +195,7 @@ describe("getAllPathsBasedOnDiffPaths", () => { }); test("should add the correct paths to the allKeys when a node within a widget is added", () => { - const addedNewWidgetProperty = produce(initialTree, (draft) => { + const addedNewWidgetProperty = create(initialTree, (draft) => { // new property is added to the widget draft.WidgetName.widgetNewProperty = "newValue"; }); @@ -213,7 +213,7 @@ describe("getAllPathsBasedOnDiffPaths", () => { // we have to make a copy since allKeys is mutable { ...initialAllKeys }, ); - const addedNewWidgetPropertyInAllKeys = produce(initialAllKeys, (draft) => { + const addedNewWidgetPropertyInAllKeys = create(initialAllKeys, (draft) => { draft["WidgetName.widgetNewProperty"] = true; }); @@ -221,7 +221,7 @@ describe("getAllPathsBasedOnDiffPaths", () => { }); test("should generate the correct paths when the value changes form a simple primitive to a collection, this is for EDIT diffs", () => { - const addedNewWidgetProperty = produce(initialTree, (draft) => { + const addedNewWidgetProperty = create(initialTree, (draft) => { //existing property within the widget is edited draft.WidgetName.name = [{ a: 1 }]; }); @@ -239,7 +239,7 @@ describe("getAllPathsBasedOnDiffPaths", () => { // we have to make a copy since allKeys is mutable { ...initialAllKeys }, ); - const addedACollectionInAllKeys = produce(initialAllKeys, (draft) => { + const addedACollectionInAllKeys = create(initialAllKeys, (draft) => { draft["WidgetName.name[0]"] = true; draft["WidgetName.name[0].a"] = true; }); diff --git a/app/client/yarn.lock b/app/client/yarn.lock index 8afbadfbe275..d970e08f16ec 100644 --- a/app/client/yarn.lock +++ b/app/client/yarn.lock @@ -13338,6 +13338,7 @@ __metadata: moment: 2.29.4 moment-timezone: ^0.5.35 msw: ^0.28.0 + mutative: ^1.1.0 nanoid: ^2.0.4 node-forge: ^1.3.0 object-hash: ^3.0.0 @@ -25747,6 +25748,13 @@ __metadata: languageName: node linkType: hard +"mutative@npm:^1.1.0": + version: 1.1.0 + resolution: "mutative@npm:1.1.0" + checksum: 5eaf505a97c713ecb45bdadfe905045692414ff6f08e35d9cad0e6e27d9005a06e9696350c23bff70d39488973841384ed01d800d67f8b2957c7a1daf3d24d3c + languageName: node + linkType: hard + "mute-stream@npm:0.0.8": version: 0.0.8 resolution: "mute-stream@npm:0.0.8"
f7d41891b8b14ae2cb5c93468e29abf611e2dbf8
2024-02-15 11:00:57
Ashok Kumar M
fix: Anvil toggleable widgets not working when native callbacks are used for AnvilFlexComponent (#31125)
false
Anvil toggleable widgets not working when native callbacks are used for AnvilFlexComponent (#31125)
fix
diff --git a/app/client/cypress/e2e/Regression/ClientSide/Anvil/AnvilWidgetClicking_spec.ts b/app/client/cypress/e2e/Regression/ClientSide/Anvil/AnvilWidgetClicking_spec.ts new file mode 100644 index 000000000000..0cccd6ea65d7 --- /dev/null +++ b/app/client/cypress/e2e/Regression/ClientSide/Anvil/AnvilWidgetClicking_spec.ts @@ -0,0 +1,75 @@ +import { ANVIL_EDITOR_TEST } from "../../../../support/Constants"; +import { + agHelper, + homePage, + assertHelper, + anvilLayout, + locators, + wdsWidgets, +} from "../../../../support/Objects/ObjectsCore"; +import { featureFlagIntercept } from "../../../../support/Objects/FeatureFlags"; +import { WIDGET } from "../../../../locators/WidgetLocators"; + +describe( + `${ANVIL_EDITOR_TEST}: validating Widget clicks in Anvil Layout Mode`, + { tags: ["@tag.Anvil"] }, + function () { + before(() => { + // intercept features call for Anvil + WDS tests + featureFlagIntercept({ + release_anvil_enabled: true, + ab_wds_enabled: true, + }); + // Cleanup the canvas before each test + agHelper.SelectAllWidgets(); + agHelper.PressDelete(); + }); + it("1. Click on widget to Select Widget", () => { + anvilLayout.DragDropAnvilWidgetNVerify(WIDGET.WDSSWITCH, 5, 20, { + skipWidgetSearch: true, + }); + anvilLayout.DragDropAnvilWidgetNVerify(WIDGET.WDSSWITCH, 5, 20, { + skipWidgetSearch: true, + dropTargetDetails: { + name: "Zone1", + }, + }); + anvilLayout.DragDropAnvilWidgetNVerify(WIDGET.WDSBUTTON, 5, 20, { + skipWidgetSearch: true, + dropTargetDetails: { + name: "Zone1", + }, + }); + // deselect all widgets + agHelper.PressEscape(); + agHelper.AssertElementLength(locators._selectedWidget, 0); + agHelper.GetNClick(locators._widgetByName("Button1")); + agHelper.AssertElementLength(locators._selectedWidget, 1); + agHelper.GetNClick(locators._widgetByName("Switch1")); + agHelper.AssertElementLength(locators._selectedWidget, 1); + }); + it("2. Click on widgets like Switch, Checkbox to toggle selection", () => { + // deselect all widgets + agHelper.PressEscape(); + agHelper + .GetNClick(wdsWidgets._switchWidgetTargetSelector("Switch1")) + .then(() => { + wdsWidgets.verifySwitchWidgetState("Switch1", "checked"); + }); + agHelper + .GetNClick(wdsWidgets._switchWidgetTargetSelector("Switch1")) + .then(() => { + wdsWidgets.verifySwitchWidgetState("Switch1", "unchecked"); + }); + anvilLayout.DragDropAnvilWidgetNVerify(WIDGET.WDSCHECKBOX, 5, 20, { + skipWidgetSearch: true, + }); + wdsWidgets.verifyCheckboxWidgetState("Checkbox1", "checked"); + agHelper + .GetNClick(wdsWidgets._checkboxWidgetTargetSelector("Checkbox1")) + .then(() => { + wdsWidgets.verifyCheckboxWidgetState("Checkbox1", "unchecked"); + }); + }); + }, +); diff --git a/app/client/cypress/locators/WidgetLocators.ts b/app/client/cypress/locators/WidgetLocators.ts index 2636d9dc1a2e..adf589aa3675 100644 --- a/app/client/cypress/locators/WidgetLocators.ts +++ b/app/client/cypress/locators/WidgetLocators.ts @@ -8,6 +8,8 @@ export const WIDGET = { WDSBUTTON: "wdsbuttonwidget", WDSTABLE: "wdstablewidget", WDSINPUT: "wdsinputwidget", + WDSSWITCH: "wdsswitchwidget", + WDSCHECKBOX: "wdscheckboxwidget", BUTTONNAME: (index: string) => `Button${index}`, CODESCANNER: "codescannerwidget", CONTAINER: "containerwidget", diff --git a/app/client/cypress/support/Objects/ObjectsCore.ts b/app/client/cypress/support/Objects/ObjectsCore.ts index 29dd82bfcd12..ef5f74a097c0 100644 --- a/app/client/cypress/support/Objects/ObjectsCore.ts +++ b/app/client/cypress/support/Objects/ObjectsCore.ts @@ -36,4 +36,5 @@ export const gsheetHelper = ObjectsRegistry.GSheetHelper; export const widgetLocators = WIDGETSKIT; export const communityTemplates = ObjectsRegistry.CommunityTemplates; export const anvilLayout = ObjectsRegistry.AnvilLayout; +export const wdsWidgets = ObjectsRegistry.WDSWidgets; export const partialImportExport = ObjectsRegistry.PartialImportExport; diff --git a/app/client/cypress/support/Objects/Registry.ts b/app/client/cypress/support/Objects/Registry.ts index 5c701fea1ebe..57bc9892da6b 100644 --- a/app/client/cypress/support/Objects/Registry.ts +++ b/app/client/cypress/support/Objects/Registry.ts @@ -30,6 +30,7 @@ import { GsheetHelper } from "../Pages/GSheetHelper"; import { CommunityTemplates } from "../Pages/CommunityTemplates"; import { AnvilLayout } from "../Pages/AnvilLayout"; import PartialImportExport from "../Pages/PartialImportExport"; +import { WDSWidgets } from "../Pages/WDSWidgets"; export class ObjectsRegistry { private static aggregateHelper__: AggregateHelper; @@ -256,6 +257,14 @@ export class ObjectsRegistry { return ObjectsRegistry.anvilLayout__; } + private static wdsWidgets__: WDSWidgets; + static get WDSWidgets(): WDSWidgets { + if (ObjectsRegistry.wdsWidgets__ === undefined) { + ObjectsRegistry.wdsWidgets__ = new WDSWidgets(); + } + return ObjectsRegistry.wdsWidgets__; + } + private static dataManager__: DataManager; static get DataManager(): DataManager { if (ObjectsRegistry.dataManager__ === undefined) { diff --git a/app/client/cypress/support/Pages/WDSWidgets.ts b/app/client/cypress/support/Pages/WDSWidgets.ts new file mode 100644 index 000000000000..845e058065fb --- /dev/null +++ b/app/client/cypress/support/Pages/WDSWidgets.ts @@ -0,0 +1,22 @@ +import { ObjectsRegistry } from "../Objects/Registry"; + +export class WDSWidgets { + private locator = ObjectsRegistry.CommonLocators; + + public _switchWidgetTargetSelector = (name: string) => + `${this.locator._widgetByName(name)} label`; + public _checkboxWidgetTargetSelector = this._switchWidgetTargetSelector; + + public verifySwitchWidgetState = ( + name: string, + expectedState: "checked" | "unchecked", + ) => { + const switchLabelSelector = `${this.locator._widgetByName(name)} label`; + cy.get(switchLabelSelector).should( + "have.attr", + "data-state", + expectedState, + ); + }; + public verifyCheckboxWidgetState = this.verifySwitchWidgetState; +} diff --git a/app/client/src/layoutSystems/anvil/common/AnvilFlexComponent.tsx b/app/client/src/layoutSystems/anvil/common/AnvilFlexComponent.tsx index d37ef8fd9f97..e62650358e07 100644 --- a/app/client/src/layoutSystems/anvil/common/AnvilFlexComponent.tsx +++ b/app/client/src/layoutSystems/anvil/common/AnvilFlexComponent.tsx @@ -12,6 +12,7 @@ import type { WidgetProps } from "widgets/BaseWidget"; import type { WidgetConfigProps } from "WidgetProvider/constants"; import { getAnvilWidgetDOMId } from "layoutSystems/common/utils/LayoutElementPositionsObserver/utils"; import { Layers } from "constants/Layers"; +import { noop } from "utils/AppsmithUtils"; const anvilWidgetStyleProps: CSSProperties = { position: "relative", @@ -38,6 +39,8 @@ export const AnvilFlexComponent = forwardRef( children, className, flexGrow, + onClick = noop, + onClickCapture = noop, widgetId, widgetSize, widgetType, @@ -82,6 +85,8 @@ export const AnvilFlexComponent = forwardRef( {...flexProps} className={className} id={getAnvilWidgetDOMId(widgetId)} + onClick={onClick} + onClickCapture={onClickCapture} ref={ref} style={anvilWidgetStyleProps} > diff --git a/app/client/src/layoutSystems/anvil/editor/AnvilEditorFlexComponent.tsx b/app/client/src/layoutSystems/anvil/editor/AnvilEditorFlexComponent.tsx index 076f2b10701d..32e4f709808f 100644 --- a/app/client/src/layoutSystems/anvil/editor/AnvilEditorFlexComponent.tsx +++ b/app/client/src/layoutSystems/anvil/editor/AnvilEditorFlexComponent.tsx @@ -41,10 +41,23 @@ export const AnvilEditorFlexComponent = (props: AnvilFlexComponentProps) => { // Use custom hooks to manage styles, click, drag, and hover behavior exclusive for Edit mode useAnvilWidgetStyles(props.widgetId, props.widgetName, props.isVisible, ref); - useAnvilWidgetClick(props.widgetId, ref); useAnvilWidgetDrag(props.widgetId, props.layoutId, ref); useAnvilWidgetHover(props.widgetId, ref); + // Note: For some reason native click callback listeners are somehow hindering with events required for toggle-able widgets like checkbox, switch, etc. + // Hence supplying click and click capture callbacks to the AnvilFlexComponent + const { onClickCaptureFn, onClickFn } = useAnvilWidgetClick( + props.widgetId, + ref, + ); // Render the AnvilFlexComponent - return <AnvilFlexComponent {...props} className={className} ref={ref} />; + return ( + <AnvilFlexComponent + {...props} + className={className} + onClick={onClickFn} + onClickCapture={onClickCaptureFn} + ref={ref} + /> + ); }; diff --git a/app/client/src/layoutSystems/anvil/editor/hooks/useAnvilWidgetClick.ts b/app/client/src/layoutSystems/anvil/editor/hooks/useAnvilWidgetClick.ts index 1ce9b134a25e..dd65ad118034 100644 --- a/app/client/src/layoutSystems/anvil/editor/hooks/useAnvilWidgetClick.ts +++ b/app/client/src/layoutSystems/anvil/editor/hooks/useAnvilWidgetClick.ts @@ -1,8 +1,11 @@ import { SELECT_ANVIL_WIDGET_CUSTOM_EVENT } from "layoutSystems/anvil/utils/constants"; -import { useCallback, useEffect } from "react"; +import { useCallback, useEffect, useRef } from "react"; import { useSelector } from "react-redux"; import { snipingModeSelector } from "selectors/editorSelectors"; -import { isCurrentWidgetFocused } from "selectors/widgetSelectors"; +import { + isCurrentWidgetFocused, + isWidgetSelected, +} from "selectors/widgetSelectors"; export const useAnvilWidgetClick = ( widgetId: string, @@ -10,19 +13,26 @@ export const useAnvilWidgetClick = ( ) => { // Retrieve state from the Redux store const isFocused = useSelector(isCurrentWidgetFocused(widgetId)); + const isSelected = useSelector(isWidgetSelected(widgetId)); const isSnipingMode = useSelector(snipingModeSelector); - + const allowSelectionRef = useRef(false); + useEffect(() => { + allowSelectionRef.current = isFocused && !isSelected; + }, [isFocused, isSelected]); // Function to stop event propagation if not in sniping mode // Note: Sniping mode is irrelevant to the Anvil however it becomes relevant if we decide to make Anvil the default editor - const stopEventPropagation = (e: MouseEvent) => { - !isSnipingMode && e.stopPropagation(); - }; + const onClickFn = useCallback( + (e: MouseEvent) => { + !isSnipingMode && e.stopPropagation(); + }, + [isSnipingMode], + ); // Callback function for handling click events on AnvilFlexComponent in Edit mode - const onClickFn = useCallback( + const onClickCaptureFn = useCallback( function () { // Dispatch a custom event when the Anvil widget is clicked and focused - if (ref.current && isFocused) { + if (ref.current && allowSelectionRef.current) { ref.current.dispatchEvent( new CustomEvent(SELECT_ANVIL_WIDGET_CUSTOM_EVENT, { bubbles: true, @@ -32,29 +42,10 @@ export const useAnvilWidgetClick = ( ); } }, - [widgetId, isFocused], + [widgetId], ); - - // Effect hook to add and remove click event listeners - useEffect(() => { - if (ref.current) { - // Add click event listener to select the Anvil widget - ref.current.addEventListener("click", onClickFn, { capture: true }); - - // Add click event listener to stop event propagation in certain modes - ref.current.addEventListener("click", stopEventPropagation, { - capture: false, - }); - } - - // Clean up event listeners when the component unmounts - return () => { - if (ref.current) { - ref.current.removeEventListener("click", onClickFn, { capture: true }); - ref.current.removeEventListener("click", stopEventPropagation, { - capture: false, - }); - } - }; - }, [onClickFn, stopEventPropagation]); + return { + onClickFn, + onClickCaptureFn, + }; }; diff --git a/app/client/src/layoutSystems/anvil/editor/hooks/useAnvilWidgetStyles.ts b/app/client/src/layoutSystems/anvil/editor/hooks/useAnvilWidgetStyles.ts index aaa860bc8f55..102d33bd6b11 100644 --- a/app/client/src/layoutSystems/anvil/editor/hooks/useAnvilWidgetStyles.ts +++ b/app/client/src/layoutSystems/anvil/editor/hooks/useAnvilWidgetStyles.ts @@ -10,6 +10,11 @@ export const useAnvilWidgetStyles = ( isVisible = true, ref: React.RefObject<HTMLDivElement>, // Ref object to reference the AnvilFlexComponent ) => { + // Selectors to determine whether the widget is selected or dragging + const isSelected = useSelector(isWidgetSelected(widgetId)); + const isDragging = useSelector( + (state: AppState) => state.ui.widgetDragResize.isDragging, + ); // Get widget border styles using useWidgetBorderStyles const widgetBorderStyles = useWidgetBorderStyles(widgetId); @@ -27,14 +32,9 @@ export const useAnvilWidgetStyles = ( useEffect(() => { if (ref.current) { ref.current.setAttribute("data-widgetname-cy", widgetName); + ref.current.setAttribute("data-testid", isSelected ? "t--selected" : ""); } - }, [widgetName]); - - // Selectors to determine whether the widget is selected or dragging - const isSelected = useSelector(isWidgetSelected(widgetId)); - const isDragging = useSelector( - (state: AppState) => state.ui.widgetDragResize.isDragging, - ); + }, [widgetName, isSelected]); // Calculate whether the widget should fade based on dragging, selection, and visibility const shouldFadeWidget = (isDragging && isSelected) || !isVisible; diff --git a/app/client/src/layoutSystems/anvil/utils/types.ts b/app/client/src/layoutSystems/anvil/utils/types.ts index 18b4604dfa6f..913120c97934 100644 --- a/app/client/src/layoutSystems/anvil/utils/types.ts +++ b/app/client/src/layoutSystems/anvil/utils/types.ts @@ -17,6 +17,8 @@ export interface AnvilFlexComponentProps { widgetName: string; widgetSize?: SizeConfig; widgetType: WidgetType; + onClick?: (e: any) => void; + onClickCapture?: () => void; } export type PositionValues =
bed11f4eca36ef40cf1885adfe37d4bf751048b2
2022-03-24 14:47:17
arunvjn
fix: Open documentation CTA in omni-bar (#11954)
false
Open documentation CTA in omni-bar (#11954)
fix
diff --git a/app/client/src/components/ads/Icon.tsx b/app/client/src/components/ads/Icon.tsx index 53ea8fd8f642..d1310b4a5c15 100644 --- a/app/client/src/components/ads/Icon.tsx +++ b/app/client/src/components/ads/Icon.tsx @@ -69,6 +69,7 @@ import { ReactComponent as Snippet } from "assets/icons/ads/snippet.svg"; import { ReactComponent as WorkspaceIcon } from "assets/icons/ads/organizationIcon.svg"; import { ReactComponent as SettingIcon } from "assets/icons/control/settings.svg"; import { ReactComponent as DropdownIcon } from "assets/icons/ads/dropdown.svg"; +import { ReactComponent as ChatIcon } from "assets/icons/ads/app-icons/chat.svg"; import styled from "styled-components"; import { CommonComponentProps, Classes } from "./common"; @@ -311,6 +312,7 @@ const ICON_LOOKUP = { "view-less": <LeftArrowIcon />, "warning-line": <WarningLineIcon />, "warning-triangle": <WarningTriangleIcon />, + "chat-help": <ChatIcon />, billing: <BillingIcon />, book: <BookIcon />, bug: <BugIcon />, diff --git a/app/client/src/components/editorComponents/GlobalSearch/Description.tsx b/app/client/src/components/editorComponents/GlobalSearch/Description.tsx index 9b53529d5649..6194a3af7c81 100644 --- a/app/client/src/components/editorComponents/GlobalSearch/Description.tsx +++ b/app/client/src/components/editorComponents/GlobalSearch/Description.tsx @@ -59,6 +59,10 @@ const Container = styled.div` } table { + margin: 0.25rem 0; + th { + text-align: left; + } th:nth-child(1) { width: 150px; } @@ -104,6 +108,30 @@ const Container = styled.div` } `; +const StyledDocumentationDescription = styled.div` + h1 { + margin: 0.5rem 0; + font-size: 1.5rem; + } + h2 { + font-size: 1.25rem; + margin: 0.5rem 0 0.25rem; + } + h3 { + font-size: 1rem; + margin: 0.5rem 0 0.25rem; + } + img, + pre { + margin: 0.25rem 0; + } + td { + strong { + font-weight: 600; + } + } +`; + function DocumentationDescription({ item, query, @@ -152,7 +180,10 @@ function DocumentationDescription({ }; return content ? ( - <div dangerouslySetInnerHTML={{ __html: content }} ref={containerRef} /> + <StyledDocumentationDescription + dangerouslySetInnerHTML={{ __html: content }} + ref={containerRef} + /> ) : null; } diff --git a/app/client/src/components/editorComponents/GlobalSearch/ResultsNotFound.tsx b/app/client/src/components/editorComponents/GlobalSearch/ResultsNotFound.tsx index 054be106e570..6861678413b2 100644 --- a/app/client/src/components/editorComponents/GlobalSearch/ResultsNotFound.tsx +++ b/app/client/src/components/editorComponents/GlobalSearch/ResultsNotFound.tsx @@ -22,11 +22,14 @@ const Container = styled.div` } .discord { - margin-top: ${(props) => props.theme.spaces[3]}px; + margin: ${(props) => props.theme.spaces[3]}px 0; + display: flex; + gap: 0.25rem; } .discord-link { cursor: pointer; + display: flex; color: ${(props) => props.theme.colors.globalSearch.searchItemText}; font-weight: 700; } diff --git a/app/client/src/components/editorComponents/GlobalSearch/SnippetsDescription.tsx b/app/client/src/components/editorComponents/GlobalSearch/SnippetsDescription.tsx index ac143e33c593..4978a8e1761c 100644 --- a/app/client/src/components/editorComponents/GlobalSearch/SnippetsDescription.tsx +++ b/app/client/src/components/editorComponents/GlobalSearch/SnippetsDescription.tsx @@ -88,6 +88,8 @@ const SnippetContainer = styled.div` .snippet-title { color: ${(props) => props.theme.colors.globalSearch.primaryTextColor}; ${(props) => getTypographyByKey(props, "h3")} + font-size: 1.5rem; + line-height: 1.5rem; display: flex; justify-content: space-between; .action-msg { diff --git a/app/client/src/components/editorComponents/GlobalSearch/index.tsx b/app/client/src/components/editorComponents/GlobalSearch/index.tsx index 5da5f4cb5562..235b4f7628de 100644 --- a/app/client/src/components/editorComponents/GlobalSearch/index.tsx +++ b/app/client/src/components/editorComponents/GlobalSearch/index.tsx @@ -389,7 +389,7 @@ function GlobalSearch() { event?: SelectEvent, ) => { if (event && event.type === "click") return; - window.open(item.path.replace("master", HelpBaseURL), "_blank"); + window.open(`${HelpBaseURL}/${item.path}`, "_blank"); }; const handleWidgetClick = (activeItem: SearchItem) => { diff --git a/app/client/src/components/editorComponents/GlobalSearch/parseDocumentationContent.test.ts b/app/client/src/components/editorComponents/GlobalSearch/parseDocumentationContent.test.ts index 2f1e3be00f64..f3ae765a038c 100644 --- a/app/client/src/components/editorComponents/GlobalSearch/parseDocumentationContent.test.ts +++ b/app/client/src/components/editorComponents/GlobalSearch/parseDocumentationContent.test.ts @@ -36,7 +36,7 @@ describe("parseDocumentationContent", () => { const sampleItem = { rawTitle: sampleTitleResponse, rawDocument: sampleDocumentResponse, - path: "master/security", + path: "security", query: "Security", }; const result = parseDocumentationContent(sampleItem); diff --git a/app/client/src/components/editorComponents/GlobalSearch/parseDocumentationContent.ts b/app/client/src/components/editorComponents/GlobalSearch/parseDocumentationContent.ts index 17d3b30ead16..1cf6c9f17c86 100644 --- a/app/client/src/components/editorComponents/GlobalSearch/parseDocumentationContent.ts +++ b/app/client/src/components/editorComponents/GlobalSearch/parseDocumentationContent.ts @@ -49,7 +49,7 @@ const stripMarkdown = (text: string) => text.replace(/---\n[description]([\S\s]*?)---/gm, ""); const getDocumentationCTA = (path: any) => { - const href = path.replace("master", HelpBaseURL); + const href = `${HelpBaseURL}/${path}`; const htmlString = `<a class="documentation-cta" href="${href}" target="_blank">Open Documentation</a>`; return htmlToElement(htmlString); }; diff --git a/app/client/src/utils/AnalyticsUtil.tsx b/app/client/src/utils/AnalyticsUtil.tsx index 84926884bd7e..7535e0dda8bb 100644 --- a/app/client/src/utils/AnalyticsUtil.tsx +++ b/app/client/src/utils/AnalyticsUtil.tsx @@ -111,6 +111,7 @@ export type EventName = | "GSHEET_AUTH_COMPLETE" | "CYCLICAL_DEPENDENCY_ERROR" | "DISCORD_LINK_CLICK" + | "INTERCOM_CLICK" | "BINDING_SUCCESS" | "APP_MENU_OPTION_CLICK" | "SLASH_COMMAND"
d86c855ef25131e309f7a51dc0decdc2a41c8dda
2024-06-24 17:17:23
Shrikant Sharat Kandula
chore: Strict schema for datasource and action APIs (#34366)
false
Strict schema for datasource and action APIs (#34366)
chore
diff --git a/app/client/src/api/ActionAPI.tsx b/app/client/src/api/ActionAPI.tsx index 6d98cf6befea..4e16158c3c32 100644 --- a/app/client/src/api/ActionAPI.tsx +++ b/app/client/src/api/ActionAPI.tsx @@ -132,7 +132,18 @@ class ActionAPI extends API { static async createAction( apiConfig: Partial<Action>, ): Promise<AxiosPromise<ActionCreateUpdateResponse>> { - return API.post(ActionAPI.url, { ...apiConfig, eventData: undefined }); + const payload = { + ...apiConfig, + eventData: undefined, + isValid: undefined, + entityReferenceType: undefined, + datasource: { + ...apiConfig.datasource, + isValid: undefined, + new: undefined, + }, + }; + return API.post(ActionAPI.url, payload); } static async fetchActions( @@ -170,6 +181,7 @@ class ActionAPI extends API { ...(action as any).datasource, datasourceStorages: undefined, isValid: undefined, + new: undefined, }; } return API.put(`${ActionAPI.url}/${action.id}`, action, undefined, { diff --git a/app/client/src/api/DatasourcesApi.ts b/app/client/src/api/DatasourcesApi.ts index f47eda81123a..50c3f3203ff0 100644 --- a/app/client/src/api/DatasourcesApi.ts +++ b/app/client/src/api/DatasourcesApi.ts @@ -14,15 +14,6 @@ export interface CreateDatasourceConfig { appName?: string; } -export interface EmbeddedRestDatasourceRequest { - datasourceConfiguration: { url: string }; - invalids: Array<string>; - isValid: boolean; - name: string; - workspaceId: string; - pluginId: string; -} - // type executeQueryData = Array<{ key?: string; value?: string }>; type executeQueryData = Record<string, any>; @@ -43,6 +34,36 @@ class DatasourcesApi extends API { static async createDatasource( datasourceConfig: Partial<Datasource>, ): Promise<any> { + // This here abomination is to remove several fields that are not accepted by the server. + for (const [name, storage] of Object.entries( + datasourceConfig.datasourceStorages || {}, + )) { + datasourceConfig = { + ...datasourceConfig, + isValid: undefined, + datasourceStorages: { + ...datasourceConfig.datasourceStorages, + [name]: { + ...storage, + isValid: undefined, + toastMessage: undefined, + datasourceConfiguration: { + ...storage.datasourceConfiguration, + isValid: undefined, + connection: storage.datasourceConfiguration.connection && { + ...storage.datasourceConfiguration.connection, + ssl: { + ...storage.datasourceConfiguration.connection.ssl, + authTypeControl: undefined, + certificateType: undefined, + }, + }, + }, + }, + }, + } as any; + } + return API.post(DatasourcesApi.url, datasourceConfig); } @@ -52,14 +73,26 @@ class DatasourcesApi extends API { pluginId: string, workspaceId: string, ): Promise<any> { - return API.post( - `${DatasourcesApi.url}/test`, - { ...datasourceConfig, pluginId, workspaceId }, - undefined, - { - timeout: DEFAULT_TEST_DATA_SOURCE_TIMEOUT_MS, + const payload = { + ...datasourceConfig, + pluginId, + workspaceId, + isValid: undefined, + toastMessage: undefined, + datasourceConfiguration: datasourceConfig.datasourceConfiguration && { + ...datasourceConfig.datasourceConfiguration, + connection: datasourceConfig.datasourceConfiguration.connection && { + ...datasourceConfig.datasourceConfiguration.connection, + ssl: { + ...datasourceConfig.datasourceConfiguration.connection.ssl, + certificateType: undefined, + }, + }, }, - ); + }; + return API.post(`${DatasourcesApi.url}/test`, payload, undefined, { + timeout: DEFAULT_TEST_DATA_SOURCE_TIMEOUT_MS, + }); } // Api to update datasource name. @@ -72,12 +105,24 @@ class DatasourcesApi extends API { // Api to update specific datasource storage/environment configuration static async updateDatasourceStorage( - datasourceConfig: Partial<DatasourceStorage>, + datasourceStorage: Partial<DatasourceStorage>, ): Promise<any> { - return API.put( - DatasourcesApi.url + `/datasource-storages`, - datasourceConfig, - ); + const payload = { + ...datasourceStorage, + isValid: undefined, + toastMessage: undefined, + datasourceConfiguration: datasourceStorage.datasourceConfiguration && { + ...datasourceStorage.datasourceConfiguration, + connection: datasourceStorage.datasourceConfiguration.connection && { + ...datasourceStorage.datasourceConfiguration.connection, + ssl: { + ...datasourceStorage.datasourceConfiguration.connection.ssl, + authTypeControl: undefined, + }, + }, + }, + }; + return API.put(DatasourcesApi.url + `/datasource-storages`, payload); } static async deleteDatasource(id: string): Promise<any> { diff --git a/app/client/src/ce/api/ApplicationApi.tsx b/app/client/src/ce/api/ApplicationApi.tsx index 29f9a3666ffb..aac2706a98e4 100644 --- a/app/client/src/ce/api/ApplicationApi.tsx +++ b/app/client/src/ce/api/ApplicationApi.tsx @@ -368,7 +368,11 @@ export class ApplicationApi extends Api { request: UpdateApplicationRequest, ): Promise<AxiosPromise<ApiResponse<UpdateApplicationResponse>>> { const { id, ...rest } = request; - return Api.put(ApplicationApi.baseURL + "/" + id, rest); + const payload = { + ...rest, + currentApp: undefined, + }; + return Api.put(ApplicationApi.baseURL + "/" + id, payload); } static async deleteApplication(
60131403b2f9d7a398587a58efb19047f7c0041c
2021-09-27 11:30:40
Tolulope Adetula
feat: disable parsing link (#7075)
false
disable parsing link (#7075)
feat
diff --git a/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/DisplayWidgets/Text_new_feature_spec.js b/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/DisplayWidgets/Text_new_feature_spec.js index 478b99e9ac19..037aa6862637 100644 --- a/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/DisplayWidgets/Text_new_feature_spec.js +++ b/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/DisplayWidgets/Text_new_feature_spec.js @@ -12,6 +12,25 @@ describe("Text Widget color/font/alignment Functionality", function() { beforeEach(() => { cy.openPropertyPane("textwidget"); }); + it("Test to validate parsing link", function() { + // Add link to text widget + cy.testCodeMirror("https://app.appsmith.com"); + // check if it's parsed as link + cy.get(commonlocators.headingTextStyle); + cy.contains("a", "https://app.appsmith.com").should( + "have.attr", + "href", + "https://app.appsmith.com", + ); + // disable parsing as link + cy.get(".t--property-control-disablelink .bp3-switch").click({ + force: true, + }); + cy.wait("@updateLayout"); + // check if it's parsed as text + cy.contains("a", "https://app.appsmith.com").should("not.exist"); + cy.closePropertyPane(); + }); it("Text-TextStyle Heading, Text Name Validation", function() { //changing the Text Name and verifying @@ -105,11 +124,9 @@ describe("Text Widget color/font/alignment Functionality", function() { force: true, }); cy.get(commonlocators.headingTextStyle).scrollIntoView({ duration: 2000 }); + cy.closePropertyPane(); }); - it("Test border width, color and verity", function() { - cy.openPropertyPane("textwidget"); - cy.testJsontext("borderwidth", "10"); cy.get( `div[data-testid='container-wrapper-${dsl.dsl.children[0].widgetId}'] div`, diff --git a/app/client/src/widgets/TextWidget/component/index.tsx b/app/client/src/widgets/TextWidget/component/index.tsx index d028a8c1cd2f..3d4292af394f 100644 --- a/app/client/src/widgets/TextWidget/component/index.tsx +++ b/app/client/src/widgets/TextWidget/component/index.tsx @@ -61,12 +61,14 @@ export interface TextComponentProps extends ComponentProps { backgroundColor?: string; textColor?: string; fontStyle?: string; + disableLink: boolean; } class TextComponent extends React.Component<TextComponentProps> { render() { const { backgroundColor, + disableLink, ellipsize, fontSize, fontStyle, @@ -88,7 +90,11 @@ class TextComponent extends React.Component<TextComponentProps> { > <Interweave content={text} - matchers={[new EmailMatcher("email"), new UrlMatcher("url")]} + matchers={ + disableLink + ? [] + : [new EmailMatcher("email"), new UrlMatcher("url")] + } newWindow /> </StyledText> diff --git a/app/client/src/widgets/TextWidget/widget/index.tsx b/app/client/src/widgets/TextWidget/widget/index.tsx index d4ddcdc15c88..be0147b3556f 100644 --- a/app/client/src/widgets/TextWidget/widget/index.tsx +++ b/app/client/src/widgets/TextWidget/widget/index.tsx @@ -46,6 +46,16 @@ class TextWidget extends BaseWidget<TextWidgetProps, WidgetState> { isTriggerProperty: false, validation: { type: ValidationTypes.BOOLEAN }, }, + { + propertyName: "disableLink", + helpText: "Controls parsing text as Link", + label: "Disable Link", + controlType: "SWITCH", + isJSConvertible: true, + isBindProperty: true, + isTriggerProperty: false, + validation: { type: ValidationTypes.BOOLEAN }, + }, ], }, { @@ -194,6 +204,7 @@ class TextWidget extends BaseWidget<TextWidgetProps, WidgetState> { > <TextComponent backgroundColor={this.props.backgroundColor} + disableLink={this.props.disableLink || false} fontSize={this.props.fontSize} fontStyle={this.props.fontStyle} isLoading={this.props.isLoading} @@ -234,6 +245,7 @@ export interface TextWidgetProps text?: string; isLoading: boolean; shouldScroll: boolean; + disableLink: boolean; } export default TextWidget;
28e54fe10d92b28c54092babcd7fad77ccb766d9
2024-10-07 11:21:55
Apeksha Bhosale
chore: span push and sentry logs (#36682)
false
span push and sentry logs (#36682)
chore
diff --git a/app/client/src/ce/sagas/userSagas.tsx b/app/client/src/ce/sagas/userSagas.tsx index cbf80d702d57..4e881be6fc5e 100644 --- a/app/client/src/ce/sagas/userSagas.tsx +++ b/app/client/src/ce/sagas/userSagas.tsx @@ -88,7 +88,8 @@ import type { } from "reducers/uiReducers/usersReducer"; import { selectFeatureFlags } from "ee/selectors/featureFlagsSelectors"; import { getFromServerWhenNoPrefetchedResult } from "sagas/helper"; - +import * as Sentry from "@sentry/react"; +import { Severity } from "@sentry/react"; export function* createUserSaga( action: ReduxActionWithPromise<CreateUserRequest>, ) { @@ -129,6 +130,12 @@ export function* createUserSaga( error, }, }); + Sentry.captureException("Sign up failed", { + level: Severity.Error, + extra: { + error: error, + }, + }); } } diff --git a/app/client/src/pages/UserAuth/Login.tsx b/app/client/src/pages/UserAuth/Login.tsx index 2dde2eff9ce4..76f59aa5a50e 100644 --- a/app/client/src/pages/UserAuth/Login.tsx +++ b/app/client/src/pages/UserAuth/Login.tsx @@ -51,7 +51,8 @@ import Helmet from "react-helmet"; import { useFeatureFlag } from "utils/hooks/useFeatureFlag"; import { FEATURE_FLAG } from "ee/entities/FeatureFlag"; import { getHTMLPageTitle } from "ee/utils/BusinessFeatures/brandingPageHelpers"; - +import * as Sentry from "@sentry/react"; +import { Severity } from "@sentry/react"; const validate = (values: LoginFormValues, props: ValidateProps) => { const errors: LoginFormValues = {}; const email = values[LOGIN_FORM_EMAIL_FIELD_NAME] || ""; @@ -113,6 +114,12 @@ export function Login(props: LoginFormProps) { if (queryParams.get("error")) { errorMessage = queryParams.get("message") || queryParams.get("error") || ""; showError = true; + Sentry.captureException("Login failed", { + level: Severity.Error, + extra: { + error: new Error(errorMessage), + }, + }); } let loginURL = "/api/v1/" + LOGIN_SUBMIT_PATH; diff --git a/app/client/src/pages/UserAuth/SignUp.tsx b/app/client/src/pages/UserAuth/SignUp.tsx index fccce68f5e1f..0d5db6e3eec5 100644 --- a/app/client/src/pages/UserAuth/SignUp.tsx +++ b/app/client/src/pages/UserAuth/SignUp.tsx @@ -57,6 +57,8 @@ import { FEATURE_FLAG } from "ee/entities/FeatureFlag"; import { getHTMLPageTitle } from "ee/utils/BusinessFeatures/brandingPageHelpers"; import log from "loglevel"; import { SELF_HOSTING_DOC } from "constants/ThirdPartyConstants"; +import * as Sentry from "@sentry/react"; +import { Severity } from "@sentry/react"; declare global { interface Window { @@ -133,6 +135,12 @@ export function SignUp(props: SignUpFormProps) { if (queryParams.get("error")) { errorMessage = queryParams.get("error") || ""; showError = true; + Sentry.captureException("Sign up failed", { + level: Severity.Error, + extra: { + error: new Error(errorMessage), + }, + }); } const signupURL = new URL( diff --git a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/constants/spans/BaseSpan.java b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/constants/spans/BaseSpan.java index b654c4847947..d6612827ce58 100644 --- a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/constants/spans/BaseSpan.java +++ b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/constants/spans/BaseSpan.java @@ -9,4 +9,8 @@ public class BaseSpan { public static final String GIT_SPAN_PREFIX = "git."; public static final String APPLICATION_SPAN_PREFIX = "application."; + + public static final String AUTHENTICATE = "authenticate"; + + public static final String AUTHORIZE = "authorize"; } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/configurations/TracingConfig.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/configurations/TracingConfig.java index a6cb5092d50d..fc22c4af4790 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/configurations/TracingConfig.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/configurations/TracingConfig.java @@ -10,6 +10,8 @@ import org.springframework.http.server.reactive.observation.ServerRequestObservationContext; import static com.appsmith.external.constants.spans.BaseSpan.APPSMITH_SPAN_PREFIX; +import static com.appsmith.external.constants.spans.BaseSpan.AUTHENTICATE; +import static com.appsmith.external.constants.spans.BaseSpan.AUTHORIZE; /** * This configuration file creates beans that are required to filter just Appsmith specific spans @@ -45,8 +47,10 @@ ObservationPredicate noActuatorServerObservations() { SpanExportingPredicate onlyAppsmithSpans() { return (finishedSpan) -> { if ((finishedSpan.getKind() != null && finishedSpan.getKind().equals(Span.Kind.SERVER)) - || finishedSpan.getName().startsWith(APPSMITH_SPAN_PREFIX)) { - // A span is either an http server request root or Appsmith specific + || finishedSpan.getName().startsWith(APPSMITH_SPAN_PREFIX) + || finishedSpan.getName().startsWith(AUTHENTICATE) + || finishedSpan.getName().startsWith(AUTHORIZE)) { + // A span is either an http server request root or Appsmith specific or login related or signup related return true; } else { return false;
b6d5390754401e4e79f4d740b7fb8d79f7979cfd
2023-03-29 22:10:42
Vijetha-Kaja
test: Cypress - Flaky test fix (#21858)
false
Cypress - Flaky test fix (#21858)
test
diff --git a/app/client/cypress/integration/Regression_TestSuite/ClientSideTests/ExplorerTests/Entity_Explorer_Widgets_Copy_Paste_Delete_Undo_Keyboard_Event_spec.js b/app/client/cypress/integration/Regression_TestSuite/ClientSideTests/ExplorerTests/Entity_Explorer_Widgets_Copy_Paste_Delete_Undo_Keyboard_Event_spec.js index 95629303abf6..1f0571b3563a 100644 --- a/app/client/cypress/integration/Regression_TestSuite/ClientSideTests/ExplorerTests/Entity_Explorer_Widgets_Copy_Paste_Delete_Undo_Keyboard_Event_spec.js +++ b/app/client/cypress/integration/Regression_TestSuite/ClientSideTests/ExplorerTests/Entity_Explorer_Widgets_Copy_Paste_Delete_Undo_Keyboard_Event_spec.js @@ -4,7 +4,8 @@ const formWidgetsPage = require("../../../../locators/FormWidgets.json"); const dsl = require("../../../../fixtures/formWithInputdsl.json"); const widgetsPage = require("../../../../locators/Widgets.json"); import { ObjectsRegistry } from "../../../../support/Objects/Registry"; -let ee = ObjectsRegistry.EntityExplorer; +let ee = ObjectsRegistry.EntityExplorer, + agHelper = ObjectsRegistry.AggregateHelper; before(() => { cy.addDsl(dsl); @@ -37,7 +38,8 @@ describe("Test Suite to validate copy/delete/undo functionalites", function () { "response.body.responseMeta.status", 200, ); - cy.get("body").type(`{${modifierKey}}z`); + agHelper.Sleep(1000); + cy.get("body").type(`{${modifierKey}}z`, { force: true }); ee.ExpandCollapseEntity("Widgets"); ee.ExpandCollapseEntity("FormTest"); ee.ActionContextMenuByEntityName("FormTestCopy", "Show Bindings"); diff --git a/app/client/cypress/integration/Regression_TestSuite/ClientSideTests/Git/GitImport/GitImport_spec.js b/app/client/cypress/integration/Regression_TestSuite/ClientSideTests/Git/GitImport/GitImport_spec.js index 378b401fb394..2aefc546a297 100644 --- a/app/client/cypress/integration/Regression_TestSuite/ClientSideTests/Git/GitImport/GitImport_spec.js +++ b/app/client/cypress/integration/Regression_TestSuite/ClientSideTests/Git/GitImport/GitImport_spec.js @@ -200,6 +200,7 @@ describe("Git import flow ", function () { cy.wait(2000); // validate data binding in edit and deploy mode cy.latestDeployPreview(); + cy.get(".tbody").should("have.length", 2); cy.get(".tbody").first().should("contain.text", "Test user 7"); cy.xpath("//input[@value='this is a test']"); cy.xpath("//input[@value='Success']"); diff --git a/app/client/cypress/integration/Regression_TestSuite/ClientSideTests/Widgets/Form/Form_With_CheckBox_spec.js b/app/client/cypress/integration/Regression_TestSuite/ClientSideTests/Widgets/Form/Form_With_CheckBox_spec.js index 3f6ceb45afe5..4263f93f1329 100644 --- a/app/client/cypress/integration/Regression_TestSuite/ClientSideTests/Widgets/Form/Form_With_CheckBox_spec.js +++ b/app/client/cypress/integration/Regression_TestSuite/ClientSideTests/Widgets/Form/Form_With_CheckBox_spec.js @@ -12,9 +12,9 @@ describe("Checkbox Widget Functionality", function () { cy.openPropertyPane("checkboxwidget"); cy.togglebar(commonlocators.requiredjs + " " + "input"); cy.PublishtheApp(); - cy.wait(1500); + cy.wait(2000); cy.get(publish.checkboxWidget).click(); - cy.get(publish.checkboxWidget).should("not.be.checked"); + cy.get('[type="checkbox"]').eq(0).should("not.be.checked"); cy.get(widgetsPage.formButtonWidget) .contains("Submit") .should("have.class", "bp3-disabled");
a07f981f1de94bc90df29d39f20a9fcf18cf587c
2022-12-26 20:00:57
Ankita Kinger
chore: Updating invite user event (#19223)
false
Updating invite user event (#19223)
chore
diff --git a/app/client/src/ce/pages/workspace/WorkspaceInviteUsersForm.tsx b/app/client/src/ce/pages/workspace/WorkspaceInviteUsersForm.tsx index f16a7180c7ef..3862b1b47e09 100644 --- a/app/client/src/ce/pages/workspace/WorkspaceInviteUsersForm.tsx +++ b/app/client/src/ce/pages/workspace/WorkspaceInviteUsersForm.tsx @@ -451,13 +451,17 @@ function WorkspaceInviteUsersForm(props: any) { <StyledForm onSubmit={handleSubmit((values: any, dispatch: any) => { validateFormValues(values); - AnalyticsUtil.logEvent("INVITE_USER", values); const usersAsStringsArray = values.users.split(","); // update state to show success message correctly updateNumberOfUsersInvited(usersAsStringsArray.length); const users = usersAsStringsArray .filter((user: any) => isEmail(user)) .join(","); + AnalyticsUtil.logEvent("INVITE_USER", { + users: usersAsStringsArray, + role: values.role, + numberOfUsersInvited: usersAsStringsArray.length, + }); return inviteUsersToWorkspace( { ...(props.workspaceId ? { workspaceId: props.workspaceId } : {}),
cdb22f4dfdf258efb230730bad4936e7079ab4d5
2024-09-25 19:45:57
Raushan Kumar Gupta
fix: mongo schema collections order of mongo plugin (#36062)
false
mongo schema collections order of mongo plugin (#36062)
fix
diff --git a/app/server/appsmith-plugins/mongoPlugin/src/main/java/com/external/plugins/MongoPlugin.java b/app/server/appsmith-plugins/mongoPlugin/src/main/java/com/external/plugins/MongoPlugin.java index 060758fe1934..0eac9e46c32d 100644 --- a/app/server/appsmith-plugins/mongoPlugin/src/main/java/com/external/plugins/MongoPlugin.java +++ b/app/server/appsmith-plugins/mongoPlugin/src/main/java/com/external/plugins/MongoPlugin.java @@ -964,6 +964,7 @@ public Mono<DatasourceStructure> getStructure( } return true; }) + .sort((collectionName1, collectionName2) -> collectionName1.compareToIgnoreCase(collectionName2)) .flatMap(collectionName -> { final ArrayList<DatasourceStructure.Column> columns = new ArrayList<>(); final ArrayList<DatasourceStructure.Template> templates = new ArrayList<>(); diff --git a/app/server/appsmith-plugins/mongoPlugin/src/test/java/com/external/plugins/MongoPluginQueriesTest.java b/app/server/appsmith-plugins/mongoPlugin/src/test/java/com/external/plugins/MongoPluginQueriesTest.java index b221ac9e5cec..1ecb60056ca2 100644 --- a/app/server/appsmith-plugins/mongoPlugin/src/test/java/com/external/plugins/MongoPluginQueriesTest.java +++ b/app/server/appsmith-plugins/mongoPlugin/src/test/java/com/external/plugins/MongoPluginQueriesTest.java @@ -655,6 +655,26 @@ public void testStructure() { .verifyComplete(); } + @Test + public void testStructure_should_return_collections_in_order() { + DatasourceConfiguration dsConfig = createDatasourceConfiguration(); + Mono<DatasourceStructure> structureMono = pluginExecutor + .datasourceCreate(dsConfig) + .flatMap(connection -> pluginExecutor.getStructure(connection, dsConfig, null)); + + StepVerifier.create(structureMono) + .assertNext(structure -> { + assertNotNull(structure); + assertEquals(3, structure.getTables().size()); + + // Check that the tables are sorted in ascending order + assertEquals("address", structure.getTables().get(0).getName()); + assertEquals("teams", structure.getTables().get(1).getName()); + assertEquals("users", structure.getTables().get(2).getName()); + }) + .verifyComplete(); + } + @Test public void testCountCommand() { DatasourceConfiguration dsConfig = createDatasourceConfiguration();
4c69e15b29d102c8d20c26de6cb596f9eb4adbce
2022-09-24 01:56:13
Trisha Anand
chore: Replacing redis entry with in memory storage for anonymous user permission groups (#17031)
false
Replacing redis entry with in memory storage for anonymous user permission groups (#17031)
chore
diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/BaseAppsmithRepositoryImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/BaseAppsmithRepositoryImpl.java index e57cef506b7d..9c80d9e440d7 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/BaseAppsmithRepositoryImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/BaseAppsmithRepositoryImpl.java @@ -388,8 +388,7 @@ protected Mono<Set<String>> getAllPermissionGroupsForUser(User user) { } protected Mono<Set<String>> getAnonymousUserPermissionGroups() { - return cacheableRepositoryHelper.getAnonymousUser() - .flatMap(anonymousUser -> cacheableRepositoryHelper.getPermissionGroupsOfUser(anonymousUser)); + return cacheableRepositoryHelper.getPermissionGroupsOfAnonymousUser(); } } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/CacheableRepositoryHelperCE.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/CacheableRepositoryHelperCE.java index 8c8b48fec89d..4a6a08121ed1 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/CacheableRepositoryHelperCE.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/CacheableRepositoryHelperCE.java @@ -9,6 +9,8 @@ public interface CacheableRepositoryHelperCE { Mono<Set<String>> getPermissionGroupsOfUser(User user); + Mono<Set<String>> getPermissionGroupsOfAnonymousUser(); + Mono<Void> evictPermissionGroupsUser(String email, String tenantId); Mono<User> getAnonymousUser(String tenantId); diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/CacheableRepositoryHelperCEImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/CacheableRepositoryHelperCEImpl.java index b40a8dd16f7e..ac561d4f4057 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/CacheableRepositoryHelperCEImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/CacheableRepositoryHelperCEImpl.java @@ -3,12 +3,15 @@ import com.appsmith.caching.annotations.Cache; import com.appsmith.caching.annotations.CacheEvict; import com.appsmith.server.constants.FieldName; +import com.appsmith.server.domains.Config; import com.appsmith.server.domains.PermissionGroup; +import com.appsmith.server.domains.QConfig; import com.appsmith.server.domains.QPermissionGroup; import com.appsmith.server.domains.QTenant; import com.appsmith.server.domains.QUser; import com.appsmith.server.domains.Tenant; import com.appsmith.server.domains.User; +import lombok.extern.slf4j.Slf4j; import org.springframework.data.mongodb.core.ReactiveMongoOperations; import org.springframework.data.mongodb.core.query.Criteria; import org.springframework.data.mongodb.core.query.Query; @@ -19,21 +22,26 @@ import java.util.Set; import java.util.stream.Collectors; +import static com.appsmith.server.constants.FieldName.PERMISSION_GROUP_ID; import static com.appsmith.server.repositories.BaseAppsmithRepositoryImpl.fieldName; +@Slf4j public class CacheableRepositoryHelperCEImpl implements CacheableRepositoryHelperCE { private final ReactiveMongoOperations mongoOperations; private final Map<String, User> tenantAnonymousUserMap; + private Set<String> anonymousUserPermissionGroupIds; + private String defaultTenantId; public CacheableRepositoryHelperCEImpl(ReactiveMongoOperations mongoOperations) { this.mongoOperations = mongoOperations; this.defaultTenantId = null; this.tenantAnonymousUserMap = new HashMap<>(); + anonymousUserPermissionGroupIds = null; } - @Cache(cacheName = "permissionGroupsForUser", key="{#user.email + #user.tenantId}") + @Cache(cacheName = "permissionGroupsForUser", key = "{#user.email + #user.tenantId}") @Override public Mono<Set<String>> getPermissionGroupsOfUser(User user) { Criteria assignedToUserIdsCriteria = Criteria.where(fieldName(QPermissionGroup.permissionGroup.assignedToUserIds)).is(user.getId()); @@ -46,7 +54,22 @@ public Mono<Set<String>> getPermissionGroupsOfUser(User user) { .collect(Collectors.toSet()); } - @CacheEvict(cacheName = "permissionGroupsForUser", key="{#email + #tenantId}") + @Override + public Mono<Set<String>> getPermissionGroupsOfAnonymousUser() { + + if (anonymousUserPermissionGroupIds != null) { + return Mono.just(anonymousUserPermissionGroupIds); + } + + log.debug("In memory cache miss for anonymous user permission groups. Fetching from DB and adding it to in memory storage."); + + // All public access is via a single permission group. Fetch the same and set the cache with it. + return mongoOperations.findOne(Query.query(Criteria.where(fieldName(QConfig.config1.name)).is(FieldName.PUBLIC_PERMISSION_GROUP)), Config.class) + .map(publicPermissionGroupConfig -> Set.of(publicPermissionGroupConfig.getConfig().getAsString(PERMISSION_GROUP_ID))) + .doOnSuccess(permissionGroupIds -> anonymousUserPermissionGroupIds = permissionGroupIds); + } + + @CacheEvict(cacheName = "permissionGroupsForUser", key = "{#email + #tenantId}") @Override public Mono<Void> evictPermissionGroupsUser(String email, String tenantId) { return Mono.empty();
39db0552111b0e9d3ad058f66f5b60eb7b12bb41
2021-12-10 14:15:03
Vicky Bansal
fix: use defaultTab as selectedTab when selectedTab property is not available on page load (#9487)
false
use defaultTab as selectedTab when selectedTab property is not available on page load (#9487)
fix
diff --git a/app/client/src/widgets/TabsWidget/widget/derived.js b/app/client/src/widgets/TabsWidget/widget/derived.js new file mode 100644 index 000000000000..8e7aac37347b --- /dev/null +++ b/app/client/src/widgets/TabsWidget/widget/derived.js @@ -0,0 +1,20 @@ +/* eslint-disable @typescript-eslint/no-unused-vars*/ +export default { + getSelectedTab: (props, moment, _) => { + if (props.selectedTabWidgetId) { + return _.find(Object.values(props.tabsObj), { + widgetId: props.selectedTabWidgetId, + }).label; + } + + const isDefaultTabExist = Object.values(props.tabsObj).filter( + (tab) => tab.label === props.defaultTab, + ).length; + if (isDefaultTabExist) { + return props.defaultTab; + } + const tabLabels = Object.values(props.tabsObj); + return tabLabels.length ? tabLabels[0].label : ""; + }, + // +}; diff --git a/app/client/src/widgets/TabsWidget/widget/derived.test.js b/app/client/src/widgets/TabsWidget/widget/derived.test.js new file mode 100644 index 000000000000..2e81f7d371eb --- /dev/null +++ b/app/client/src/widgets/TabsWidget/widget/derived.test.js @@ -0,0 +1,113 @@ +import derivedProperty from "./derived"; +import moment from "moment"; +import _ from "lodash"; +describe("Validates Derived Properties", () => { + it("validates with selectedTabWidgetId", () => { + const { getSelectedTab } = derivedProperty; + const input = { + selectedTabWidgetId: "wy2ehwc35r", + tabsObj: { + tab1: { + label: "Tab 1", + id: "tab1", + widgetId: "wy2ehwc35r", + isVisible: true, + index: 0, + }, + tab2: { + label: "Tab 2", + id: "tab2", + widgetId: "4pity919kx", + isVisible: true, + index: 1, + }, + }, + defaultTab: "Tab 2", + }; + const expected = "Tab 1"; + + let result = getSelectedTab(input, moment, _); + expect(result).toStrictEqual(expected); + }); + it("validates without selectedTabWidgetId", () => { + const { getSelectedTab } = derivedProperty; + const input = { + selectedTabWidgetId: "", + tabsObj: { + tab1: { + label: "Tab 1", + id: "tab1", + widgetId: "wy2ehwc35r", + isVisible: true, + index: 0, + }, + tab2: { + label: "Tab 2", + id: "tab2", + widgetId: "4pity919kx", + isVisible: true, + index: 1, + }, + }, + defaultTab: "Tab 2", + }; + const expected = "Tab 2"; + + let result = getSelectedTab(input, moment, _); + expect(result).toStrictEqual(expected); + }); + it("validates without selectedTabWidgetId and defaultTab", () => { + const { getSelectedTab } = derivedProperty; + const input = { + selectedTabWidgetId: "", + tabsObj: { + tab1: { + label: "Tab 1", + id: "tab1", + widgetId: "wy2ehwc35r", + isVisible: true, + index: 0, + }, + tab2: { + label: "Tab 2", + id: "tab2", + widgetId: "4pity919kx", + isVisible: true, + index: 1, + }, + }, + defaultTab: "", + }; + const expected = "Tab 1"; + + let result = getSelectedTab(input, moment, _); + expect(result).toStrictEqual(expected); + }); + it("validates without selectedTabWidgetId and with defaultTab but not in tabs", () => { + const { getSelectedTab } = derivedProperty; + const input = { + selectedTabWidgetId: "", + tabsObj: { + tab1: { + label: "Tab 1", + id: "tab1", + widgetId: "wy2ehwc35r", + isVisible: true, + index: 0, + }, + tab2: { + label: "Tab 2", + id: "tab2", + widgetId: "4pity919kx", + isVisible: true, + index: 1, + }, + }, + defaultTab: "Tab 3", + }; + const expected = "Tab 1"; + + let result = getSelectedTab(input, moment, _); + expect(result).toStrictEqual(expected); + }); +}); diff --git a/app/client/src/widgets/TabsWidget/widget/index.tsx b/app/client/src/widgets/TabsWidget/widget/index.tsx index 9aeefd641ecb..ba7ce8ca0567 100644 --- a/app/client/src/widgets/TabsWidget/widget/index.tsx +++ b/app/client/src/widgets/TabsWidget/widget/index.tsx @@ -12,6 +12,7 @@ import { TabContainerWidgetProps, TabsWidgetProps } from "../constants"; import { AutocompleteDataType } from "utils/autocomplete/TernServer"; import { WidgetProperties } from "selectors/propertyPaneSelectors"; +import derivedProperties from "./parseDerivedProperties"; export function selectedTabValidation( value: unknown, @@ -184,9 +185,7 @@ class TabsWidget extends BaseWidget< static getDerivedPropertiesMap() { return { - selectedTab: `{{_.find(Object.values(this.tabsObj), { - widgetId: this.selectedTabWidgetId, - }).label}}`, + selectedTab: `{{(()=>{${derivedProperties.getSelectedTab}})()}}`, }; } diff --git a/app/client/src/widgets/TabsWidget/widget/parseDerivedProperties.ts b/app/client/src/widgets/TabsWidget/widget/parseDerivedProperties.ts new file mode 100644 index 000000000000..34eb14ebef28 --- /dev/null +++ b/app/client/src/widgets/TabsWidget/widget/parseDerivedProperties.ts @@ -0,0 +1,36 @@ +// eslint-disable-next-line @typescript-eslint/ban-ts-comment +//@ts-ignore +import widgetPropertyFns from "!!raw-loader!./derived.js"; + +// TODO(abhinav): +// Add unit test cases +// Handle edge cases +// Error out on wrong values +const derivedProperties: any = {}; +// const regex = /(\w+):\s?\(props\)\s?=>\s?{([\w\W]*?)},/gim; +const regex = /(\w+):\s?\(props, moment, _\)\s?=>\s?{([\w\W\n]*?)},\n?\s+?\/\//gim; + +let m; + +while ((m = regex.exec((widgetPropertyFns as unknown) as string)) !== null) { + // This is necessary to avoid infinite loops with zero-width matches + if (m.index === regex.lastIndex) { + regex.lastIndex++; + } + + let key = ""; + // The result can be accessed through the `m`-variable. + m.forEach((match, groupIndex) => { + if (groupIndex === 1) { + key = match; + } + if (groupIndex === 2) { + derivedProperties[key] = match + .trim() + .replace(/\n/g, "") + .replace(/props\./g, "this."); + } + }); +} + +export default derivedProperties;
d0382778db65d3291188ee3dee04abb171cefc44
2023-08-31 17:32:34
arunvjn
chore: Remove browser-image-compression library from recommended section (#26818)
false
Remove browser-image-compression library from recommended section (#26818)
chore
diff --git a/app/client/src/pages/Editor/Explorer/Libraries/recommendedLibraries.ts b/app/client/src/pages/Editor/Explorer/Libraries/recommendedLibraries.ts index 7972eeb12ec2..db64c2d001b0 100644 --- a/app/client/src/pages/Editor/Explorer/Libraries/recommendedLibraries.ts +++ b/app/client/src/pages/Editor/Explorer/Libraries/recommendedLibraries.ts @@ -122,16 +122,6 @@ export default [ docsURL: "https://github.com/dchester/jsonpath/#jsonpath", icon: "https://github.com/dchester.png?s=20", }, - { - name: "browser-image-compression", - url: "https://cdn.jsdelivr.net/npm/[email protected]/dist/browser-image-compression.min.js", - version: "2.0.0", - author: "Donaldcwl", - docsURL: - "https://github.com/Donaldcwl/browser-image-compression/#browser-image-compression", - description: "Compress images in the browser", - icon: "https://github.com/Donaldcwl.png?s=20", - }, // We'll be enabling support for segment soon // { // name: "@segment/analytics-next",
daaaa93b6175587d71405ef205895a57c318f234
2024-07-16 17:16:40
Nilesh Sarupriya
chore: refactor authentication failure redirect and retry (#34899)
false
refactor authentication failure redirect and retry (#34899)
chore
diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/authentication/handlers/AuthenticationFailureHandler.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/authentication/handlers/AuthenticationFailureHandler.java index b5003afdc364..c8fffa933f16 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/authentication/handlers/AuthenticationFailureHandler.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/authentication/handlers/AuthenticationFailureHandler.java @@ -1,9 +1,13 @@ package com.appsmith.server.authentication.handlers; import com.appsmith.server.authentication.handlers.ce.AuthenticationFailureHandlerCE; -import lombok.RequiredArgsConstructor; +import com.appsmith.server.authentication.helpers.AuthenticationFailureRetryHandler; import org.springframework.stereotype.Component; @Component -@RequiredArgsConstructor -public class AuthenticationFailureHandler extends AuthenticationFailureHandlerCE {} +public class AuthenticationFailureHandler extends AuthenticationFailureHandlerCE { + + public AuthenticationFailureHandler(AuthenticationFailureRetryHandler authenticationFailureRetryHandler) { + super(authenticationFailureRetryHandler); + } +} diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/authentication/handlers/ce/AuthenticationFailureHandlerCE.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/authentication/handlers/ce/AuthenticationFailureHandlerCE.java index c9dac2df77de..258ad6c16e1e 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/authentication/handlers/ce/AuthenticationFailureHandlerCE.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/authentication/handlers/ce/AuthenticationFailureHandlerCE.java @@ -1,110 +1,21 @@ package com.appsmith.server.authentication.handlers.ce; -import com.appsmith.server.constants.Security; -import com.appsmith.server.exceptions.AppsmithError; +import com.appsmith.server.authentication.helpers.AuthenticationFailureRetryHandler; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; -import org.springframework.security.authentication.InternalAuthenticationServiceException; import org.springframework.security.core.AuthenticationException; -import org.springframework.security.oauth2.core.OAuth2AuthenticationException; -import org.springframework.security.web.server.DefaultServerRedirectStrategy; -import org.springframework.security.web.server.ServerRedirectStrategy; import org.springframework.security.web.server.WebFilterExchange; import org.springframework.security.web.server.authentication.ServerAuthenticationFailureHandler; -import org.springframework.util.MultiValueMap; -import org.springframework.web.server.ServerWebExchange; import reactor.core.publisher.Mono; -import java.net.URI; -import java.net.URISyntaxException; -import java.net.URLEncoder; -import java.nio.charset.StandardCharsets; - -import static com.appsmith.server.helpers.RedirectHelper.REDIRECT_URL_QUERY_PARAM; - @Slf4j @RequiredArgsConstructor public class AuthenticationFailureHandlerCE implements ServerAuthenticationFailureHandler { - private final ServerRedirectStrategy redirectStrategy = new DefaultServerRedirectStrategy(); + private final AuthenticationFailureRetryHandler authenticationFailureRetryHandler; @Override public Mono<Void> onAuthenticationFailure(WebFilterExchange webFilterExchange, AuthenticationException exception) { - log.error("In the login failure handler. Cause: {}", exception.getMessage(), exception); - ServerWebExchange exchange = webFilterExchange.getExchange(); - // On authentication failure, we send a redirect to the client's login error page. The browser will re-load the - // login page again with an error message shown to the user. - MultiValueMap<String, String> queryParams = exchange.getRequest().getQueryParams(); - String state = queryParams.getFirst(Security.QUERY_PARAMETER_STATE); - String originHeader = "/"; - String redirectUrl = queryParams.getFirst(REDIRECT_URL_QUERY_PARAM); - - if (state != null && !state.isEmpty()) { - originHeader = getOriginFromState(state); - } else { - originHeader = - getOriginFromReferer(exchange.getRequest().getHeaders().getOrigin()); - } - - // Construct the redirect URL based on the exception type - String url = constructRedirectUrl(exception, originHeader, redirectUrl); - - return redirectWithUrl(exchange, url); - } - - private String getOriginFromState(String state) { - String[] stateArray = state.split(","); - for (int i = 0; i < stateArray.length; i++) { - String stateVar = stateArray[i]; - if (stateVar != null && stateVar.startsWith(Security.STATE_PARAMETER_ORIGIN) && stateVar.contains("=")) { - return stateVar.split("=")[1]; - } - } - return "/"; - } - - // this method extracts the origin from the referer header - private String getOriginFromReferer(String refererHeader) { - if (refererHeader != null && !refererHeader.isBlank()) { - try { - URI uri = new URI(refererHeader); - String authority = uri.getAuthority(); - String scheme = uri.getScheme(); - return scheme + "://" + authority; - } catch (URISyntaxException e) { - return "/"; - } - } - return "/"; - } - - // this method constructs the redirect URL based on the exception type - private String constructRedirectUrl(AuthenticationException exception, String originHeader, String redirectUrl) { - String url = ""; - if (exception instanceof OAuth2AuthenticationException - && AppsmithError.SIGNUP_DISABLED - .getAppErrorCode() - .toString() - .equals(((OAuth2AuthenticationException) exception) - .getError() - .getErrorCode())) { - url = "/user/signup?error=" + URLEncoder.encode(exception.getMessage(), StandardCharsets.UTF_8); - } else { - if (exception instanceof InternalAuthenticationServiceException) { - url = originHeader + "/user/login?error=true&message=" - + URLEncoder.encode(exception.getMessage(), StandardCharsets.UTF_8); - } else { - url = originHeader + "/user/login?error=true"; - } - } - if (redirectUrl != null && !redirectUrl.trim().isEmpty()) { - url = url + "&" + REDIRECT_URL_QUERY_PARAM + "=" + redirectUrl; - } - return url; - } - - private Mono<Void> redirectWithUrl(ServerWebExchange exchange, String url) { - URI defaultRedirectLocation = URI.create(url); - return this.redirectStrategy.sendRedirect(exchange, defaultRedirectLocation); + return authenticationFailureRetryHandler.retryAndRedirectOnAuthenticationFailure(webFilterExchange, exception); } } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/authentication/helpers/AuthenticationFailureRetryHandler.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/authentication/helpers/AuthenticationFailureRetryHandler.java new file mode 100644 index 000000000000..60d05ba79161 --- /dev/null +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/authentication/helpers/AuthenticationFailureRetryHandler.java @@ -0,0 +1,3 @@ +package com.appsmith.server.authentication.helpers; + +public interface AuthenticationFailureRetryHandler extends AuthenticationFailureRetryHandlerCE {} diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/authentication/helpers/AuthenticationFailureRetryHandlerCE.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/authentication/helpers/AuthenticationFailureRetryHandlerCE.java new file mode 100644 index 000000000000..02760a428022 --- /dev/null +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/authentication/helpers/AuthenticationFailureRetryHandlerCE.java @@ -0,0 +1,10 @@ +package com.appsmith.server.authentication.helpers; + +import org.springframework.security.core.AuthenticationException; +import org.springframework.security.web.server.WebFilterExchange; +import reactor.core.publisher.Mono; + +public interface AuthenticationFailureRetryHandlerCE { + Mono<Void> retryAndRedirectOnAuthenticationFailure( + WebFilterExchange webFilterExchange, AuthenticationException exception); +} diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/authentication/helpers/AuthenticationFailureRetryHandlerCEImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/authentication/helpers/AuthenticationFailureRetryHandlerCEImpl.java new file mode 100644 index 000000000000..4ba2efd2c473 --- /dev/null +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/authentication/helpers/AuthenticationFailureRetryHandlerCEImpl.java @@ -0,0 +1,114 @@ +package com.appsmith.server.authentication.helpers; + +import com.appsmith.server.constants.Security; +import com.appsmith.server.exceptions.AppsmithError; +import lombok.extern.slf4j.Slf4j; +import org.springframework.security.authentication.InternalAuthenticationServiceException; +import org.springframework.security.core.AuthenticationException; +import org.springframework.security.oauth2.core.OAuth2AuthenticationException; +import org.springframework.security.web.server.DefaultServerRedirectStrategy; +import org.springframework.security.web.server.ServerRedirectStrategy; +import org.springframework.security.web.server.WebFilterExchange; +import org.springframework.stereotype.Component; +import org.springframework.util.MultiValueMap; +import org.springframework.web.server.ServerWebExchange; +import reactor.core.publisher.Mono; + +import java.net.URI; +import java.net.URISyntaxException; +import java.net.URLEncoder; +import java.nio.charset.StandardCharsets; + +import static com.appsmith.server.helpers.RedirectHelper.REDIRECT_URL_QUERY_PARAM; + +@Slf4j +@Component +public class AuthenticationFailureRetryHandlerCEImpl implements AuthenticationFailureRetryHandlerCE { + + private final ServerRedirectStrategy redirectStrategy = new DefaultServerRedirectStrategy(); + protected final String LOGIN_ERROR_URL = "/user/login?error=true"; + protected final String LOGIN_ERROR_MESSAGE_URL = LOGIN_ERROR_URL + "&message="; + protected final String SIGNUP_ERROR_URL = "/user/signup?error="; + + @Override + public Mono<Void> retryAndRedirectOnAuthenticationFailure( + WebFilterExchange webFilterExchange, AuthenticationException exception) { + log.error("In the login failure handler. Cause: {}", exception.getMessage(), exception); + ServerWebExchange exchange = webFilterExchange.getExchange(); + // On authentication failure, we send a redirect to the client's login error page. The browser will re-load the + // login page again with an error message shown to the user. + MultiValueMap<String, String> queryParams = exchange.getRequest().getQueryParams(); + String state = queryParams.getFirst(Security.QUERY_PARAMETER_STATE); + String originHeader = "/"; + String redirectUrl = queryParams.getFirst(REDIRECT_URL_QUERY_PARAM); + + if (state != null && !state.isEmpty()) { + originHeader = getOriginFromState(state); + } else { + originHeader = + getOriginFromReferer(exchange.getRequest().getHeaders().getOrigin()); + } + + // Construct the redirect URL based on the exception type + String url = constructRedirectUrl(exception, originHeader, redirectUrl); + + return redirectWithUrl(exchange, url); + } + + private String getOriginFromState(String state) { + String[] stateArray = state.split(","); + for (int i = 0; i < stateArray.length; i++) { + String stateVar = stateArray[i]; + if (stateVar != null && stateVar.startsWith(Security.STATE_PARAMETER_ORIGIN) && stateVar.contains("=")) { + return stateVar.split("=")[1]; + } + } + return "/"; + } + + // this method extracts the origin from the referer header + private String getOriginFromReferer(String refererHeader) { + if (refererHeader != null && !refererHeader.isBlank()) { + try { + URI uri = new URI(refererHeader); + String authority = uri.getAuthority(); + String scheme = uri.getScheme(); + return scheme + "://" + authority; + } catch (URISyntaxException e) { + return "/"; + } + } + return "/"; + } + + // this method constructs the redirect URL based on the exception type + private String constructRedirectUrl(AuthenticationException exception, String originHeader, String redirectUrl) { + String url = ""; + if (exception instanceof OAuth2AuthenticationException + && AppsmithError.SIGNUP_DISABLED + .getAppErrorCode() + .toString() + .equals(((OAuth2AuthenticationException) exception) + .getError() + .getErrorCode())) { + url = SIGNUP_ERROR_URL + URLEncoder.encode(exception.getMessage(), StandardCharsets.UTF_8); + } else { + if (exception instanceof InternalAuthenticationServiceException) { + url = originHeader + + LOGIN_ERROR_MESSAGE_URL + + URLEncoder.encode(exception.getMessage(), StandardCharsets.UTF_8); + } else { + url = originHeader + LOGIN_ERROR_URL; + } + } + if (redirectUrl != null && !redirectUrl.trim().isEmpty()) { + url = url + "&" + REDIRECT_URL_QUERY_PARAM + "=" + redirectUrl; + } + return url; + } + + private Mono<Void> redirectWithUrl(ServerWebExchange exchange, String url) { + URI defaultRedirectLocation = URI.create(url); + return this.redirectStrategy.sendRedirect(exchange, defaultRedirectLocation); + } +} diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/authentication/helpers/AuthenticationFailureRetryHandlerImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/authentication/helpers/AuthenticationFailureRetryHandlerImpl.java new file mode 100644 index 000000000000..6a2df1218afc --- /dev/null +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/authentication/helpers/AuthenticationFailureRetryHandlerImpl.java @@ -0,0 +1,7 @@ +package com.appsmith.server.authentication.helpers; + +import org.springframework.stereotype.Component; + +@Component +public class AuthenticationFailureRetryHandlerImpl extends AuthenticationFailureRetryHandlerCEImpl + implements AuthenticationFailureRetryHandler {} diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/exceptions/GlobalExceptionHandler.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/exceptions/GlobalExceptionHandler.java index 74b82ffd6e2c..f9ef6a4dfb41 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/exceptions/GlobalExceptionHandler.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/exceptions/GlobalExceptionHandler.java @@ -1,9 +1,6 @@ package com.appsmith.server.exceptions; import com.appsmith.external.constants.AnalyticsEvents; -import com.appsmith.external.constants.MDCConstants; -import com.appsmith.external.exceptions.AppsmithErrorAction; -import com.appsmith.external.exceptions.BaseException; import com.appsmith.external.exceptions.ErrorDTO; import com.appsmith.external.exceptions.pluginExceptions.AppsmithPluginException; import com.appsmith.server.constants.FieldName; @@ -14,9 +11,6 @@ import com.appsmith.server.services.AnalyticsService; import com.appsmith.server.services.SessionUserService; import io.micrometer.core.instrument.util.StringUtils; -import io.sentry.Sentry; -import io.sentry.SentryLevel; -import io.sentry.protocol.User; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.eclipse.jgit.api.errors.JGitInternalException; @@ -35,12 +29,12 @@ import reactor.core.publisher.Mono; import java.io.File; -import java.io.PrintWriter; -import java.io.StringWriter; import java.nio.file.Path; import java.util.HashMap; import java.util.Map; +import static com.appsmith.server.exceptions.util.SentryLogger.doLog; + /** * This class catches all the Exceptions and formats them into a proper ResponseDTO<ErrorDTO> object before * sending it to the client. @@ -58,46 +52,6 @@ public class GlobalExceptionHandler { private final SessionUserService sessionUserService; - private void doLog(Throwable error) { - if (error instanceof BaseException baseException && baseException.isHideStackTraceInLogs()) { - log.error(baseException.getClass().getSimpleName() + ": " + baseException.getMessage()); - } else { - log.error("", error); - } - - StringWriter stringWriter = new StringWriter(); - PrintWriter printWriter = new PrintWriter(stringWriter); - error.printStackTrace(printWriter); - String stringStackTrace = stringWriter.toString(); - - Sentry.configureScope(scope -> { - /** - * Send stack trace as a string message. This is a work around till it is figured out why raw - * stack trace is not visible on Sentry dashboard. - * */ - scope.setExtra("Stack Trace", stringStackTrace); - scope.setLevel(SentryLevel.ERROR); - scope.setTag("source", "appsmith-internal-server"); - }); - - if (error instanceof BaseException) { - BaseException baseError = (BaseException) error; - if (baseError.getErrorAction() == AppsmithErrorAction.LOG_EXTERNALLY) { - Sentry.configureScope(scope -> { - baseError.getContextMap().forEach(scope::setTag); - scope.setExtra("downstreamErrorMessage", baseError.getDownstreamErrorMessage()); - scope.setExtra("downstreamErrorCode", baseError.getDownstreamErrorCode()); - }); - final User user = new User(); - user.setEmail(baseError.getContextMap().getOrDefault(MDCConstants.USER_EMAIL, "unknownUser")); - Sentry.setUser(user); - Sentry.captureException(error); - } - } else { - Sentry.captureException(error); - } - } - /** * This function only catches the AppsmithException type and formats it into ResponseEntity<ErrorDTO> object * Ideally, we should only be throwing AppsmithException from our code. This ensures that we can standardize diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/exceptions/util/SentryLogger.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/exceptions/util/SentryLogger.java new file mode 100644 index 000000000000..9e07c0421661 --- /dev/null +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/exceptions/util/SentryLogger.java @@ -0,0 +1,55 @@ +package com.appsmith.server.exceptions.util; + +import com.appsmith.external.constants.MDCConstants; +import com.appsmith.external.exceptions.AppsmithErrorAction; +import com.appsmith.external.exceptions.BaseException; +import io.sentry.Sentry; +import io.sentry.SentryLevel; +import io.sentry.protocol.User; +import lombok.extern.slf4j.Slf4j; + +import java.io.PrintWriter; +import java.io.StringWriter; + +@Slf4j +public class SentryLogger { + public static void doLog(Throwable error) { + if (error instanceof BaseException baseException && baseException.isHideStackTraceInLogs()) { + log.error(baseException.getClass().getSimpleName() + ": " + baseException.getMessage()); + } else { + log.error("", error); + } + + StringWriter stringWriter = new StringWriter(); + PrintWriter printWriter = new PrintWriter(stringWriter); + error.printStackTrace(printWriter); + String stringStackTrace = stringWriter.toString(); + + Sentry.configureScope(scope -> { + /** + * Send stack trace as a string message. This is a work around till it is figured out why raw + * stack trace is not visible on Sentry dashboard. + * */ + scope.setExtra("Stack Trace", stringStackTrace); + scope.setLevel(SentryLevel.ERROR); + scope.setTag("source", "appsmith-internal-server"); + }); + + if (error instanceof BaseException) { + BaseException baseError = (BaseException) error; + if (baseError.getErrorAction() == AppsmithErrorAction.LOG_EXTERNALLY) { + Sentry.configureScope(scope -> { + baseError.getContextMap().forEach(scope::setTag); + scope.setExtra("downstreamErrorMessage", baseError.getDownstreamErrorMessage()); + scope.setExtra("downstreamErrorCode", baseError.getDownstreamErrorCode()); + }); + final User user = new User(); + user.setEmail(baseError.getContextMap().getOrDefault(MDCConstants.USER_EMAIL, "unknownUser")); + Sentry.setUser(user); + Sentry.captureException(error); + } + } else { + Sentry.captureException(error); + } + } +}
2a9efbc5d1ab87521b07b5e51dafda49a9e2894a
2023-11-21 16:54:39
Nidhi
chore: Added context type handling for isNameAllowed (#29007)
false
Added context type handling for isNameAllowed (#29007)
chore
diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/refactors/applications/RefactoringSolutionCE.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/refactors/applications/RefactoringSolutionCE.java index 545f21cf8d44..fe5410476e79 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/refactors/applications/RefactoringSolutionCE.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/refactors/applications/RefactoringSolutionCE.java @@ -1,5 +1,6 @@ package com.appsmith.server.refactors.applications; +import com.appsmith.external.models.CreatorContextType; import com.appsmith.server.dtos.LayoutDTO; import com.appsmith.server.dtos.RefactorEntityNameDTO; import reactor.core.publisher.Mono; @@ -8,5 +9,5 @@ public interface RefactoringSolutionCE { Mono<LayoutDTO> refactorEntityName(RefactorEntityNameDTO refactorEntityNameDTO, String branchName); - Mono<Boolean> isNameAllowed(String pageId, String layoutId, String newName); + Mono<Boolean> isNameAllowed(String contextId, CreatorContextType contextType, String layoutId, String newName); } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/refactors/applications/RefactoringSolutionCEImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/refactors/applications/RefactoringSolutionCEImpl.java index 90e42329d745..1be5b1740541 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/refactors/applications/RefactoringSolutionCEImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/refactors/applications/RefactoringSolutionCEImpl.java @@ -170,6 +170,7 @@ public Mono<LayoutDTO> refactorEntityName(RefactorEntityNameDTO refactorEntityNa refactorEntityNameDTO.setPageId(branchedPageId); return this.isNameAllowed( branchedPageId, + CreatorContextType.PAGE, refactorEntityNameDTO.getLayoutId(), refactorEntityNameDTO.getNewFullyQualifiedName()) .zipWith(newPageService.getById(branchedPageId)); @@ -231,20 +232,23 @@ private Mono<Void> sendRefactorAnalytics( } @Override - public Mono<Boolean> isNameAllowed(String pageId, String layoutId, String newName) { + public Mono<Boolean> isNameAllowed( + String contextId, CreatorContextType contextType, String layoutId, String newName) { boolean isFQN = newName.contains("."); - Iterable<Flux<String>> existingEntityNamesFlux = getExistingEntityNamesFlux(pageId, layoutId, isFQN); + Iterable<Flux<String>> existingEntityNamesFlux = + getExistingEntityNamesFlux(contextId, layoutId, isFQN, contextType); return Flux.merge(existingEntityNamesFlux) .collect(Collectors.toSet()) .map(existingNames -> !existingNames.contains(newName)); } - protected Iterable<Flux<String>> getExistingEntityNamesFlux(String pageId, String layoutId, boolean isFQN) { + protected Iterable<Flux<String>> getExistingEntityNamesFlux( + String contextId, String layoutId, boolean isFQN, CreatorContextType contextType) { Flux<String> existingActionNamesFlux = - newActionEntityRefactoringService.getExistingEntityNames(pageId, CreatorContextType.PAGE, layoutId); + newActionEntityRefactoringService.getExistingEntityNames(contextId, contextType, layoutId); /* * TODO : Execute this check directly on the DB server. We can query array of arrays by: @@ -257,10 +261,10 @@ protected Iterable<Flux<String>> getExistingEntityNamesFlux(String pageId, Strin // Hence we can avoid unnecessary DB calls if (!isFQN) { existingWidgetNamesFlux = - widgetEntityRefactoringService.getExistingEntityNames(pageId, CreatorContextType.PAGE, layoutId); + widgetEntityRefactoringService.getExistingEntityNames(contextId, contextType, layoutId); - existingActionCollectionNamesFlux = actionCollectionEntityRefactoringService.getExistingEntityNames( - pageId, CreatorContextType.PAGE, layoutId); + existingActionCollectionNamesFlux = + actionCollectionEntityRefactoringService.getExistingEntityNames(contextId, contextType, layoutId); } ArrayList<Flux<String>> list = new ArrayList<>(); diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/LayoutActionServiceCEImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/LayoutActionServiceCEImpl.java index 093b1d1e4619..43a2f936b5d9 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/LayoutActionServiceCEImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/LayoutActionServiceCEImpl.java @@ -4,6 +4,7 @@ import com.appsmith.external.helpers.AppsmithEventContext; import com.appsmith.external.helpers.AppsmithEventContextType; import com.appsmith.external.models.ActionDTO; +import com.appsmith.external.models.CreatorContextType; import com.appsmith.external.models.Datasource; import com.appsmith.external.models.DefaultResources; import com.appsmith.server.acl.AclPermission; @@ -409,7 +410,9 @@ public Mono<ActionDTO> createAction(ActionDTO action, AppsmithEventContext event return pageMono.flatMap(page -> { Layout layout = page.getUnpublishedPage().getLayouts().get(0); String name = action.getValidName(); - return refactoringSolution.isNameAllowed(page.getId(), layout.getId(), name); + CreatorContextType contextType = + action.getContextType() == null ? CreatorContextType.PAGE : action.getContextType(); + return refactoringSolution.isNameAllowed(page.getId(), contextType, layout.getId(), name); }) .flatMap(nameAllowed -> { // If the name is allowed, return pageMono for further processing diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/LayoutCollectionServiceCEImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/LayoutCollectionServiceCEImpl.java index d1cd53dffcc0..b0bda45cc526 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/LayoutCollectionServiceCEImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/LayoutCollectionServiceCEImpl.java @@ -2,6 +2,7 @@ import com.appsmith.external.helpers.AppsmithBeanUtils; import com.appsmith.external.models.ActionDTO; +import com.appsmith.external.models.CreatorContextType; import com.appsmith.external.models.DefaultResources; import com.appsmith.server.actioncollections.base.ActionCollectionService; import com.appsmith.server.constants.FieldName; @@ -92,8 +93,11 @@ public Mono<ActionCollectionDTO> createCollection(ActionCollectionDTO collection // If the collection name is unique, the action name will be guaranteed to be unique within that collection return pageMono.flatMap(page -> { Layout layout = page.getUnpublishedPage().getLayouts().get(0); + CreatorContextType contextType = + collection.getContextType() == null ? CreatorContextType.PAGE : collection.getContextType(); // Check against widget names and action names - return refactoringSolution.isNameAllowed(page.getId(), layout.getId(), collection.getName()); + return refactoringSolution.isNameAllowed( + page.getId(), contextType, layout.getId(), collection.getName()); }) .flatMap(isNameAllowed -> { // If the name is allowed, return list of actionDTOs for further processing diff --git a/app/server/appsmith-server/src/test/java/com/appsmith/server/refactors/RefactoringSolutionTest.java b/app/server/appsmith-server/src/test/java/com/appsmith/server/refactors/RefactoringSolutionTest.java index a3a994a25d57..814b6b8d8013 100644 --- a/app/server/appsmith-server/src/test/java/com/appsmith/server/refactors/RefactoringSolutionTest.java +++ b/app/server/appsmith-server/src/test/java/com/appsmith/server/refactors/RefactoringSolutionTest.java @@ -1,6 +1,7 @@ package com.appsmith.server.refactors; import com.appsmith.external.models.ActionDTO; +import com.appsmith.external.models.CreatorContextType; import com.appsmith.external.models.Datasource; import com.appsmith.external.models.PluginType; import com.appsmith.server.actioncollections.base.ActionCollectionService; @@ -249,7 +250,10 @@ public void testIsNameAllowed_withRepeatedActionCollectionName_throwsError() { .thenReturn(Flux.just(mockActionCollectionDTO)); Mono<Boolean> nameAllowedMono = refactoringSolution.isNameAllowed( - testPage.getId(), testPage.getLayouts().get(0).getId(), "testCollection"); + testPage.getId(), + CreatorContextType.PAGE, + testPage.getLayouts().get(0).getId(), + "testCollection"); StepVerifier.create(nameAllowedMono).assertNext(Assertions::assertFalse).verifyComplete(); } @@ -281,7 +285,10 @@ public void jsActionWithoutCollectionIdShouldBeIgnoredDuringNameChecking() { .thenReturn(Flux.just(mockActionCollectionDTO)); Mono<Boolean> nameAllowedMono = refactoringSolution.isNameAllowed( - testPage.getId(), testPage.getLayouts().get(0).getId(), "testCollection.bar"); + testPage.getId(), + CreatorContextType.PAGE, + testPage.getLayouts().get(0).getId(), + "testCollection.bar"); StepVerifier.create(nameAllowedMono).assertNext(Assertions::assertTrue).verifyComplete(); } 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 ef58e70ed573..2f286d685cc3 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 @@ -234,7 +234,7 @@ public void testCreateCollection_withRepeatedActionName_throwsError() throws IOE final NewPage newPage = objectMapper.convertValue(jsonNode.get("newPage"), NewPage.class); Mockito.when(newPageService.findById(Mockito.any(), Mockito.<AclPermission>any())) .thenReturn(Mono.just(newPage)); - Mockito.when(refactoringSolution.isNameAllowed(Mockito.any(), Mockito.any(), Mockito.any())) + Mockito.when(refactoringSolution.isNameAllowed(Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any())) .thenReturn(Mono.just(false)); Mockito.when(actionCollectionRepository.findAllActionCollectionsByNamePageIdsViewModeAndBranch( @@ -275,7 +275,7 @@ public void testCreateCollection_createActionFailure_returnsWithIncompleteCollec Mockito.when(newPageService.findById(Mockito.any(), Mockito.<AclPermission>any())) .thenReturn(Mono.just(newPage)); - Mockito.when(refactoringSolution.isNameAllowed(Mockito.any(), Mockito.any(), Mockito.any())) + Mockito.when(refactoringSolution.isNameAllowed(Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any())) .thenReturn(Mono.just(true)); Mockito.when(actionCollectionRepository.findAllActionCollectionsByNamePageIdsViewModeAndBranch( @@ -340,7 +340,7 @@ public void testCreateCollection_validCollection_returnsPopulatedCollection() th Mockito.when(newPageService.findById(Mockito.any(), Mockito.<AclPermission>any())) .thenReturn(Mono.just(newPage)); - Mockito.when(refactoringSolution.isNameAllowed(Mockito.any(), Mockito.any(), Mockito.any())) + Mockito.when(refactoringSolution.isNameAllowed(Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any())) .thenReturn(Mono.just(true)); Mockito.when(actionCollectionRepository.findAllActionCollectionsByNamePageIdsViewModeAndBranch(
230c225d7ebc3b339fe244372655aa0da2c25c59
2024-06-14 13:00:54
Goutham Pratapa
fix: failing dp builder (#34247)
false
failing dp builder (#34247)
fix
diff --git a/scripts/deploy_preview.sh b/scripts/deploy_preview.sh index 7aa67287ab82..f121fd6b3452 100755 --- a/scripts/deploy_preview.sh +++ b/scripts/deploy_preview.sh @@ -100,7 +100,7 @@ helm upgrade -i $CHARTNAME appsmith-ee/$HELMCHART -n $NAMESPACE --create-namespa --set resources.requests.memory="2048Mi" \ --set applicationConfig.APPSMITH_SENTRY_DSN="https://[email protected]/1546547" \ --set applicationConfig.APPSMITH_SENTRY_ENVIRONMENT="$NAMESPACE" \ - --set applicationConfig.APPSMITH_DB_URL="mongodb+srv://$DB_USERNAME:$DB_PASSWORD@$DB_URL/$DBNAME?retryWrites=true&minPoolSize=1&maxPoolSize=10&maxIdleTimeMS=900000&authSource=admin" \ + --set applicationConfig.APPSMITH_MONGODB_URI="mongodb+srv://$DB_USERNAME:$DB_PASSWORD@$DB_URL/$DBNAME?retryWrites=true&minPoolSize=1&maxPoolSize=10&maxIdleTimeMS=900000&authSource=admin" \ --set applicationConfig.APPSMITH_DISABLE_EMBEDDED_KEYCLOAK=\"1\" \ --set applicationConfig.APPSMITH_CUSTOMER_PORTAL_URL="https://release-customer.appsmith.com" \ --version $HELMCHART_VERSION
94989d4bc34a784c541acea00e1811b1b0b9d47b
2022-12-30 17:34:31
Vaibhav Tanwar
fix: RestApiPlugin get request raw body fix (#18474)
false
RestApiPlugin get request raw body fix (#18474)
fix
diff --git a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/helpers/restApiUtils/helpers/DataUtils.java b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/helpers/restApiUtils/helpers/DataUtils.java index 77165a9af7e6..a87a506a444c 100644 --- a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/helpers/restApiUtils/helpers/DataUtils.java +++ b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/helpers/restApiUtils/helpers/DataUtils.java @@ -75,6 +75,8 @@ public DataUtils() { return BodyInserters.fromValue(formData); case MediaType.MULTIPART_FORM_DATA_VALUE: return parseMultipartFileData((List<Property>) body); + case MediaType.TEXT_PLAIN_VALUE: + return BodyInserters.fromValue((String) body); default: return BodyInserters.fromValue(((String) body).getBytes(StandardCharsets.ISO_8859_1)); } diff --git a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/ApiContentType.java b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/ApiContentType.java index cf8fb1b44e26..e58d580b9b1a 100644 --- a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/ApiContentType.java +++ b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/ApiContentType.java @@ -10,7 +10,7 @@ public enum ApiContentType { JSON("application/json"), FORM_URLENCODED("application/x-www-form-urlencoded"), MULTIPART_FORM_DATA("multipart/form-data"), - RAW("raw"), + RAW("text/plain"), GRAPHQL("application/graphql") ; diff --git a/app/server/appsmith-plugins/restApiPlugin/src/test/java/com/external/plugins/RestApiPluginTest.java b/app/server/appsmith-plugins/restApiPlugin/src/test/java/com/external/plugins/RestApiPluginTest.java index 0f5c78c1c438..90f4bf683829 100644 --- a/app/server/appsmith-plugins/restApiPlugin/src/test/java/com/external/plugins/RestApiPluginTest.java +++ b/app/server/appsmith-plugins/restApiPlugin/src/test/java/com/external/plugins/RestApiPluginTest.java @@ -12,8 +12,8 @@ import com.appsmith.external.models.AuthenticationDTO; import com.appsmith.external.models.DatasourceConfiguration; import com.appsmith.external.models.OAuth2; -import com.appsmith.external.models.PaginationField; import com.appsmith.external.models.PaginationType; +import com.appsmith.external.models.PaginationField; import com.appsmith.external.models.Param; import com.appsmith.external.models.Property; import com.appsmith.external.services.SharedConfig; @@ -26,7 +26,6 @@ import io.jsonwebtoken.Jwts; import io.jsonwebtoken.security.Keys; import io.jsonwebtoken.security.SignatureException; -import lombok.extern.slf4j.Slf4j; import mockwebserver3.MockResponse; import mockwebserver3.MockWebServer; import mockwebserver3.RecordedRequest; @@ -38,6 +37,7 @@ import org.junit.jupiter.api.Test; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; +import org.springframework.http.MediaType; import reactor.core.publisher.Mono; import reactor.test.StepVerifier; import reactor.util.function.Tuple2; @@ -475,6 +475,79 @@ public void testValidSignature() { .verifyComplete(); } + @Test + public void testHttpGetRequestRawBody() { + + ExecuteActionDTO executeActionDTO = new ExecuteActionDTO(); + + Param param = new Param(); + param.setKey("Input1.text"); + param.setValue("123"); + param.setClientDataType(ClientDataType.STRING); + param.setPseudoBindingName("k0"); + + executeActionDTO.setParams(Collections.singletonList(param)); + executeActionDTO.setParamProperties(Collections.singletonMap("k0","string")); + executeActionDTO.setParameterMap(Collections.singletonMap("Input1.text","k0")); + executeActionDTO.setInvertParameterMap(Collections.singletonMap("k0","Input1.text")); + + DatasourceConfiguration datasourceConfiguration = new DatasourceConfiguration(); + datasourceConfiguration.setUrl("https://postman-echo.com/get"); + + final List<Property> headers = List.of( + new Property("content-type",MediaType.TEXT_PLAIN_VALUE)); + + final List<Property> queryParameters = List.of(); + + ActionConfiguration actionConfiguration = new ActionConfiguration(); + actionConfiguration.setHeaders(headers); + actionConfiguration.setQueryParameters(queryParameters); + actionConfiguration.setHttpMethod(HttpMethod.GET); + + actionConfiguration.setTimeoutInMillisecond("10000"); + + actionConfiguration.setPaginationType(PaginationType.NONE); + + actionConfiguration.setEncodeParamsToggle(true); + + actionConfiguration.setPluginSpecifiedTemplates(List.of(new Property(null,true))); + + actionConfiguration.setFormData(Collections.singletonMap("apiContentType", MediaType.TEXT_PLAIN_VALUE)); + + String[] requestBodyList = {"abc is equals to {{Input1.text}}","{ \"abc\": {{Input1.text}} }",""}; + + String[] finalRequestBodyList = {"abc is equals to \"123\"","{ \"abc\": \"123\" }",""}; + + for (int requestBodyIndex = 0; requestBodyIndex < requestBodyList.length; requestBodyIndex++) { + + actionConfiguration.setBody(requestBodyList[requestBodyIndex]); + Mono<ActionExecutionResult> resultMono = pluginExecutor.executeParameterized(null, executeActionDTO, datasourceConfiguration, actionConfiguration); + + int currentIndex = requestBodyIndex; + StepVerifier.create(resultMono) + .assertNext(result -> { + assertTrue(result.getIsExecutionSuccess()); + JsonNode body = (JsonNode) result.getBody(); + assertNotNull(body); + JsonNode args = body.get("args"); + int index = 0; + StringBuilder actualRequestBody = new StringBuilder(); + while (true) { + if (!args.has(String.valueOf(index))) { + break; + } + JsonNode ans = args.get(String.valueOf(index)); + index++; + actualRequestBody.append(ans.asText()); + } + assertEquals(finalRequestBodyList[currentIndex],actualRequestBody.toString()); + final ActionExecutionRequest request = result.getRequest(); + assertEquals(HttpMethod.GET, request.getHttpMethod()); + }) + .verifyComplete(); + } + } + @Test public void testInvalidSignature() { DatasourceConfiguration dsConfig = new DatasourceConfiguration();
56b4671bafa380765af26528cf249cf781d8c39d
2023-11-28 14:25:46
arunvjn
chore: sunset assistive binding (#29119)
false
sunset assistive binding (#29119)
chore
diff --git a/app/client/cypress/e2e/Regression/ClientSide/AssistiveBinding/assistiveBinding_spec.ts b/app/client/cypress/e2e/Regression/ClientSide/AssistiveBinding/assistiveBinding_spec.ts deleted file mode 100644 index 856e9eddef34..000000000000 --- a/app/client/cypress/e2e/Regression/ClientSide/AssistiveBinding/assistiveBinding_spec.ts +++ /dev/null @@ -1,153 +0,0 @@ -import { - agHelper, - locators, - entityExplorer, - jsEditor, - propPane, - apiPage, - dataManager, -} from "../../../../support/Objects/ObjectsCore"; -import EditorNavigation, { - EntityType, -} from "../../../../support/Pages/EditorNavigation"; - -describe("Assistive Binding", function () { - before(() => { - // Button1 - entityExplorer.DragDropWidgetNVerify("buttonwidget", 200, 200); - - // Create JSObject1 - jsEditor.CreateJSObject( - `export default { - myFun1: ()=>{ - f; - return "yes" - } - }`, - { - paste: true, - completeReplace: true, - toRun: false, - shouldCreateNewJSObj: true, - prettify: false, - }, - ); - - // Create JSObject2 - jsEditor.CreateJSObject( - `export default { - myFun1: ()=>{ - f; - return "yes" - } - }`, - { - paste: true, - completeReplace: true, - toRun: false, - shouldCreateNewJSObj: true, - prettify: false, - }, - ); - - // Create Api1 - apiPage.CreateAndFillApi( - dataManager.dsValues[dataManager.defaultEnviorment].echoApiUrl, - ); - // Create Api2 - apiPage.CreateAndFillApi( - dataManager.dsValues[dataManager.defaultEnviorment].echoApiUrl, - ); - }); - it("1. Shows hints without curly braces when user types in data fields", () => { - EditorNavigation.SelectEntityByName("Button1", EntityType.Widget); - propPane.TypeTextIntoField("Label", "JS"); - // Assert that no hint shows up when length of text is less than 3 - agHelper.AssertElementAbsence(locators._hints); - propPane.TypeTextIntoField("Label", "JSo"); - // Assert that hints show up when length of text is equal to or greater than 3 - agHelper.AssertElementExist(locators._hints); - propPane.TypeTextIntoField("Label", "unknownVar"); - // Assert that no hint shows up text doesn't match any entity name within the app - agHelper.AssertElementAbsence(locators._hints); - propPane.TypeTextIntoField("Label", "API"); - // Assert that hints show up without considering capitalization - agHelper.AssertElementExist(locators._hints); - propPane.TypeTextIntoField("Label", "{"); - // Assert that hints show up when 1 curly brace is entered - agHelper.AssertElementExist(locators._hints); - }); - it("2. Selects correct value when hint is selected", () => { - EditorNavigation.SelectEntityByName("Button1", EntityType.Widget); - propPane.TypeTextIntoField("Label", "JSo"); - agHelper.GetNClickByContains(locators._hints, "JSObject1.myFun1"); - // After selecting "JSObject1.myFun1", expect "{{JSObject1.myFun1.data}}" in binding - propPane.ValidatePropertyFieldValue("Label", "{{JSObject1.myFun1.data}}"); - propPane.TypeTextIntoField("Label", "Api"); - agHelper.GetNClickByContains(locators._hints, "Api1"); - // After selecting "Api1", expect "{{Api1.data}}" in binding - propPane.ValidatePropertyFieldValue("Label", "{{Api1.data}}"); - }); - it("3. Shows hints after every white space", () => { - EditorNavigation.SelectEntityByName("Button1", EntityType.Widget); - propPane.TypeTextIntoField("Label", "JSo JSo"); - // Assert that hints show up when length of text after any previous blank space is equal to or greater than 3 - agHelper.AssertElementExist(locators._hints); - EditorNavigation.SelectEntityByName("Button1", EntityType.Widget); - propPane.TypeTextIntoField("Label", "JSo tab\tJSo"); - // Assert that hints show up when length of text after any previous tab is equal to or greater than 3 - agHelper.AssertElementExist(locators._hints); - propPane.TypeTextIntoField("Label", "JSo \nJSo"); - // Assert that hints show up when length of text after any previous new line is equal to or greater than 3 - agHelper.AssertElementExist(locators._hints); - }); - - it("4. Selects correct value and inserts in right place when hint is selected after whitespace ", () => { - EditorNavigation.SelectEntityByName("Button1", EntityType.Widget); - propPane.TypeTextIntoField("Label", "JSo JSo"); - agHelper.GetNClickByContains(locators._hints, "JSObject1.myFun1"); - // After selecting "JSObject1.myFun1", expect "JSo {{JSObject1.myFun1.data}}" in binding - propPane.ValidatePropertyFieldValue( - "Label", - "JSo {{JSObject1.myFun1.data}}", - ); - EditorNavigation.SelectEntityByName("Button1", EntityType.Widget); - propPane.TypeTextIntoField("Label", "JSo tab\tJSo"); - agHelper.GetNClickByContains(locators._hints, "JSObject1.myFun1"); - // After selecting "JSObject1.myFun1", expect "JSo tab {{JSObject1.myFun1.data}}" in binding - propPane.ValidatePropertyFieldValue( - "Label", - "JSo tab {{JSObject1.myFun1.data}}", - ); - EditorNavigation.SelectEntityByName("Button1", EntityType.Widget); - propPane.TypeTextIntoField("Label", `JSo \nJSo`); - agHelper.GetNClickByContains(locators._hints, "JSObject1.myFun1"); - // After selecting "JSObject1.myFun1", expect `JSo \n{{JSObject1.myFun1.data}}` in binding - propPane.ValidatePropertyFieldValue( - "Label", - `JSo {{JSObject1.myFun1.data}}`, - ); - }); - - it("5. Partial binding {} syntax is replaced with correct values ", () => { - EditorNavigation.SelectEntityByName("Button1", EntityType.Widget); - propPane.TypeTextIntoField("Label", "{"); - agHelper.GetNClickByContains(locators._hints, "JSObject1.myFun1"); - // After selecting "JSObject1.myFun1", expect "{{JSObject1.myFun1.data}}" in binding - propPane.ValidatePropertyFieldValue("Label", "{{JSObject1.myFun1.data}}"); - EditorNavigation.SelectEntityByName("Button1", EntityType.Widget); - propPane.TypeTextIntoField("Label", "{"); - agHelper.GetNClickByContains(locators._hints, "Add a binding"); - // After selecting "Add a binding", expect "{{}}" in binding - propPane.ValidatePropertyFieldValue("Label", "{{}}"); - }); - - it("6. Works correctly when user toggles JS", () => { - EditorNavigation.SelectEntityByName("Button1", EntityType.Widget); - propPane.ToggleJSMode("onClick"); - propPane.ValidatePropertyFieldValue("onClick", "{{}}"); - propPane.TypeTextIntoField("onClick", "hello", false); - // This asserts that cursor was originally between the curly braces after the user switched to js mode - propPane.ValidatePropertyFieldValue("onClick", "{{hello}}"); - }); -}); diff --git a/app/client/src/components/editorComponents/CodeEditor/assistiveBindingCommands.tsx b/app/client/src/components/editorComponents/CodeEditor/assistiveBindingCommands.tsx deleted file mode 100644 index 7c8317308b12..000000000000 --- a/app/client/src/components/editorComponents/CodeEditor/assistiveBindingCommands.tsx +++ /dev/null @@ -1,143 +0,0 @@ -import React from "react"; -import type { CommandsCompletion } from "utils/autocomplete/CodemirrorTernService"; -import ReactDOM from "react-dom"; -import type { SlashCommandPayload } from "entities/Action"; -import { - type ENTITY_TYPE, - ENTITY_TYPE_VALUE, -} from "entities/DataTree/dataTreeFactory"; -import { EntityIcon, JsFileIconV2 } from "pages/Editor/Explorer/ExplorerIcons"; -import { getAssetUrl } from "@appsmith/utils/airgapHelpers"; -import type { FeatureFlags } from "@appsmith/entities/FeatureFlag"; -import { - Command, - Shortcuts, - commandsHeader, - generateCreateNewCommand, - matchingCommands, -} from "./generateQuickCommands"; -import { AutocompleteDataType } from "utils/autocomplete/AutocompleteDataType"; -import type { NavigationData } from "selectors/navigationSelectors"; - -export const generateAssistiveBindingCommands = ( - entitiesForSuggestions: NavigationData[], - currentEntityType: ENTITY_TYPE, - searchText: string, - { - expectedType, - pluginIdToImageLocation, - }: { - executeCommand: (payload: SlashCommandPayload) => void; - pluginIdToImageLocation: Record<string, string>; - recentEntities: string[]; - featureFlags: FeatureFlags; - enableAIAssistance: boolean; - expectedType: AutocompleteDataType; - }, -) => { - const newBinding: CommandsCompletion = generateCreateNewCommand({ - text: "{{}}", - displayText: "Add a binding", - description: "Connect data using JS", - shortcut: Shortcuts.BINDING, - triggerCompletionsPostPick: true, - }); - - const actionEntities = entitiesForSuggestions.filter((suggestion) => { - return suggestion.type === ENTITY_TYPE_VALUE.ACTION; - }); - - const suggestionsAction = actionEntities.map((suggestion: any) => { - const name = suggestion.name; - const text = - expectedType === AutocompleteDataType.FUNCTION - ? `{{${name}.run()}}` - : `{{${name}.data}}`; - return { - text, - displayText: `${name}`, - className: "CodeMirror-commands", - data: suggestion, - triggerCompletionsPostPick: - suggestion.ENTITY_TYPE !== ENTITY_TYPE_VALUE.ACTION, - render: (element: HTMLElement, self: any, data: any) => { - const pluginId = data.data.pluginId; - let icon = null; - if (pluginId && pluginIdToImageLocation[pluginId]) { - icon = ( - <EntityIcon height="16px" width="16px"> - <img src={getAssetUrl(pluginIdToImageLocation[pluginId])} /> - </EntityIcon> - ); - } - ReactDOM.render( - <Command desc={text} icon={icon} name={data.displayText} />, - element, - ); - }, - }; - }); - - const jsActionEntities = entitiesForSuggestions.filter((suggestion) => { - return suggestion.type === ENTITY_TYPE_VALUE.JSACTION; - }); - - const suggestionsJSAction = jsActionEntities.flatMap((suggestion) => { - const name = suggestion.name; - const children = suggestion.children; - const icon = JsFileIconV2(16, 16); - return Object.keys(children).map((key: string) => { - const isFunction = children[key].isfunction; - const text = isFunction - ? expectedType === AutocompleteDataType.FUNCTION - ? `{{${name}.${key}()}}` - : `{{${name}.${key}.data}}` - : `{{${name}.${key}}}`; - return { - text, - displayText: `${name}.${key}`, - className: "CodeMirror-commands", - description: text, - data: suggestion, - triggerCompletionsPostPick: false, - render: ( - element: HTMLElement, - _: unknown, - data: CommandsCompletion, - ) => { - ReactDOM.render( - <Command - desc={text} - icon={icon} - name={data.displayText as string} - />, - element, - ); - }, - }; - }); - }); - - const suggestions = [...suggestionsAction, ...suggestionsJSAction]; - - const suggestionsMatchingSearchText = matchingCommands( - suggestions, - searchText, - 5, - ); - const actionCommands = [newBinding]; - - const actionCommandsMatchingSearchText = matchingCommands( - actionCommands, - searchText, - ); - - const list = actionCommandsMatchingSearchText; - - if (suggestionsMatchingSearchText.length) { - list.push(commandsHeader("Bind data", "", false)); - } - list.push(...suggestionsMatchingSearchText); - - return list; -}; diff --git a/app/client/src/components/editorComponents/CodeEditor/assistiveBindingHinter.ts b/app/client/src/components/editorComponents/CodeEditor/assistiveBindingHinter.ts deleted file mode 100644 index 86ace1571765..000000000000 --- a/app/client/src/components/editorComponents/CodeEditor/assistiveBindingHinter.ts +++ /dev/null @@ -1,200 +0,0 @@ -import CodeMirror from "codemirror"; -import type { - FieldEntityInformation, - HintHelper, -} from "components/editorComponents/CodeEditor/EditorConfig"; -import type { CommandsCompletion } from "utils/autocomplete/CodemirrorTernService"; -import { AutocompleteDataType } from "utils/autocomplete/AutocompleteDataType"; -import { generateAssistiveBindingCommands } from "./assistiveBindingCommands"; -import type { Datasource } from "entities/Datasource"; -import AnalyticsUtil from "utils/AnalyticsUtil"; -import { ENTITY_TYPE_VALUE } from "entities/DataTree/dataTreeFactory"; -import type { SlashCommandPayload } from "entities/Action"; -import type { FeatureFlags } from "@appsmith/entities/FeatureFlag"; -import type { - EntityNavigationData, - NavigationData, -} from "selectors/navigationSelectors"; - -const PARTIAL_BINDING = "{}"; - -export const assistiveBindingHinter: HintHelper = ( - _, - entitiesForNavigation: EntityNavigationData, -) => { - const entitiesForSuggestions: NavigationData[] = Object.values( - entitiesForNavigation || {}, - ); - return { - showHint: ( - editor: CodeMirror.Editor, - entityInfo: FieldEntityInformation, - { - enableAIAssistance, - executeCommand, - featureFlags, - focusEditor, - pluginIdToImageLocation, - recentEntities, - }: { - datasources: Datasource[]; - executeCommand: (payload: SlashCommandPayload) => void; - pluginIdToImageLocation: Record<string, string>; - recentEntities: string[]; - update: (value: string) => void; - entityId: string; - featureFlags: FeatureFlags; - enableAIAssistance: boolean; - focusEditor: (focusOnLine?: number, chOffset?: number) => void; - }, - ): boolean => { - // @ts-expect-error: Types are not available - editor.closeHint(); - const currentEntityName = entityInfo.entityName; - const currentEntityType = - entityInfo.entityType || ENTITY_TYPE_VALUE.WIDGET; - const expectedType = - entityInfo.expectedType || AutocompleteDataType.UNKNOWN; - - const filterEntityListForSuggestion = entitiesForSuggestions.filter( - (e) => e.name !== currentEntityName, - ); - - const word = editor.findWordAt(editor.getCursor()); - const value = editor.getRange(word.anchor, word.head); - - if (value.length < 3 && value !== PARTIAL_BINDING) return false; - const searchText = value === PARTIAL_BINDING ? "" : value; - const list = generateAssistiveBindingCommands( - filterEntityListForSuggestion, - currentEntityType, - searchText, - { - executeCommand, - pluginIdToImageLocation, - recentEntities, - featureFlags, - enableAIAssistance, - expectedType, - }, - ); - - if (list.length === 0) return false; - - AnalyticsUtil.logEvent("ASSISTIVE_JS_BINDING_TRIGGERED", { - query: value, - suggestedOptionCount: list.filter( - (item) => item.className === "CodeMirror-commands", - ).length, - entityType: entityInfo.entityType, - }); - - let currentSelection: CommandsCompletion = { - data: {}, - text: "", - shortcut: "", - }; - const cursor = editor.getCursor(); - const currentLine = cursor.line; - const currentCursorPosition = - value === PARTIAL_BINDING ? cursor.ch + 1 : cursor.ch; - - // CodeMirror hinter needs to have a selected hint. - // Assistive binding requires that we do not have any completion selected by default. - // Adds a hidden completion ("\n") that mocks the enter behavior. - list.unshift({ - text: "\n", - displayText: "", - from: cursor, - to: cursor, - render: (element: HTMLElement) => { - element.style.height = "0"; - element.style.marginBottom = "4px"; - }, - data: {}, - shortcut: "", - }); - const hints = { - list, - from: { - ch: currentCursorPosition - value.length, - line: currentLine, - }, - to: { - ch: currentCursorPosition, - line: currentLine, - }, - selectedHint: 0, - }; - editor.showHint({ - hint: () => { - function handleSelection(selected: CommandsCompletion) { - currentSelection = selected; - } - function handlePick(selected: CommandsCompletion) { - if (selected.displayText === "") { - return; - } - const cursor = editor.getCursor(); - const currentLine = cursor.line; - focusEditor(currentLine, 2); - // eslint-disable-next-line @typescript-eslint/no-unused-vars - const { data } = selected; - const { name, type } = data as NavigationData; - const jsLexicalName: string | undefined = - selected.displayText?.replace(name + ".", ""); //name of the variable of functions in JSAction - const selectedOptionType: string | undefined = - type !== "JSACTION" - ? entitiesForNavigation?.[name]?.actionType - : jsLexicalName !== undefined && - entitiesForNavigation?.[name]?.children?.[jsLexicalName] - .isfunction === true - ? "JSFunction" - : "JSVariable"; - AnalyticsUtil.logEvent("ASSISTIVE_JS_BINDING_OPTION_SELECTED", { - query: value, - suggestedOptionCount: list.filter( - (item) => item.className === "CodeMirror-commands", - ).length, //option count - selectedOptionType: selectedOptionType, - selectedOptionIndex: list.findIndex( - (item) => item.displayText === selected.displayText, - ), - entityType: entityInfo.entityType, - }); - - CodeMirror.off(hints, "pick", handlePick); - CodeMirror.off(hints, "select", handleSelection); - } - CodeMirror.on(hints, "pick", handlePick); - CodeMirror.on(hints, "select", handleSelection); - return hints; - }, - extraKeys: { - Up: (cm: CodeMirror.Editor, handle: any) => { - handle.moveFocus(-1); - if (currentSelection.isHeader) { - handle.moveFocus(-1); - if (currentSelection.displayText === "") handle.moveFocus(-1); - } else if (currentSelection.displayText === "") { - handle.moveFocus(-1); - if (currentSelection.isHeader) handle.moveFocus(-1); - } - }, - Down: (cm: CodeMirror.Editor, handle: any) => { - handle.moveFocus(1); - if (currentSelection.isHeader) { - handle.moveFocus(1); - if (currentSelection.displayText === "") handle.moveFocus(1); - } else if (currentSelection.displayText === "") { - handle.moveFocus(1); - if (currentSelection.isHeader) handle.moveFocus(1); - } - }, - }, - completeSingle: false, - }); - return true; - }, - }; -}; diff --git a/app/client/src/components/editorComponents/CodeEditor/index.tsx b/app/client/src/components/editorComponents/CodeEditor/index.tsx index ebd5c8273c54..3818364a7f61 100644 --- a/app/client/src/components/editorComponents/CodeEditor/index.tsx +++ b/app/client/src/components/editorComponents/CodeEditor/index.tsx @@ -1361,7 +1361,6 @@ class CodeEditor extends Component<Props, State> { const token = cm.getTokenAt(cursor); let showAutocomplete = false; const prevChar = line[cursor.ch - 1]; - const mode = cm.getModeAt(cursor); // If the token is a comment or string, do not show autocomplete if (token?.type && ["comment", "string"].includes(token.type)) return; @@ -1375,9 +1374,7 @@ class CodeEditor extends Component<Props, State> { showAutocomplete = !!prevChar && /[a-zA-Z_0-9.]/.test(prevChar); } else if (key === "{") { /* Autocomplete for { should show up only when a user attempts to write {{}} and not a code block. */ - showAutocomplete = - mode.name != EditorModes.JAVASCRIPT || // for JSmode donot show autocomplete - prevChar === "{"; // for non JSmode mode show autocomplete. This will endup showing assistiveBindignHinter. + showAutocomplete = prevChar === "{"; } else if (key === "'" || key === '"') { /* Autocomplete for [ should show up only when a user attempts to write {['']} for Object property suggestions. */ showAutocomplete = prevChar === "["; diff --git a/app/client/src/components/propertyControls/ChartDataControl.tsx b/app/client/src/components/propertyControls/ChartDataControl.tsx index 762ff5c76d3e..02f8ce07f593 100644 --- a/app/client/src/components/propertyControls/ChartDataControl.tsx +++ b/app/client/src/components/propertyControls/ChartDataControl.tsx @@ -17,7 +17,6 @@ import { generateReactKey } from "utils/generators"; import { AutocompleteDataType } from "utils/autocomplete/AutocompleteDataType"; import LazyCodeEditor from "components/editorComponents/LazyCodeEditor"; import ColorPickerComponent from "./ColorPickerComponentV2"; -import { assistiveBindingHinter } from "components/editorComponents/CodeEditor/assistiveBindingHinter"; import { bindingHintHelper } from "components/editorComponents/CodeEditor/hintHelpers"; import { slashCommandHintHelper } from "components/editorComponents/CodeEditor/commandsHelper"; @@ -147,11 +146,7 @@ function DataControlComponent(props: RenderComponentProps) { dataTreePath={`${dataTreePath}.seriesName`} evaluatedValue={evaluated?.seriesName} expected={expectedSeriesName} - hinting={[ - bindingHintHelper, - assistiveBindingHinter, - slashCommandHintHelper, - ]} + hinting={[bindingHintHelper, slashCommandHintHelper]} input={{ value: item.seriesName, onChange: ( @@ -202,11 +197,7 @@ function DataControlComponent(props: RenderComponentProps) { dataTreePath={`${dataTreePath}.data`} evaluatedValue={evaluated?.data} expected={expectedSeriesData} - hinting={[ - bindingHintHelper, - assistiveBindingHinter, - slashCommandHintHelper, - ]} + hinting={[bindingHintHelper, slashCommandHintHelper]} input={{ value: item.data, onChange: ( diff --git a/app/client/src/components/propertyControls/CodeEditorControl.tsx b/app/client/src/components/propertyControls/CodeEditorControl.tsx index 23c805039f85..b743ff8ed78d 100644 --- a/app/client/src/components/propertyControls/CodeEditorControl.tsx +++ b/app/client/src/components/propertyControls/CodeEditorControl.tsx @@ -9,7 +9,6 @@ import { TabBehaviour, } from "components/editorComponents/CodeEditor/EditorConfig"; import LazyCodeEditor from "components/editorComponents/LazyCodeEditor"; -import { assistiveBindingHinter } from "components/editorComponents/CodeEditor/assistiveBindingHinter"; import { bindingHintHelper } from "components/editorComponents/CodeEditor/hintHelpers"; import { slashCommandHintHelper } from "components/editorComponents/CodeEditor/commandsHelper"; @@ -32,11 +31,7 @@ class CodeEditorControl extends BaseControl<ControlProps> { return ( <LazyCodeEditor additionalDynamicData={this.props.additionalAutoComplete} - hinting={[ - bindingHintHelper, - assistiveBindingHinter, - slashCommandHintHelper, - ]} + hinting={[bindingHintHelper, slashCommandHintHelper]} input={{ value: propertyValue, onChange: this.onChange }} mode={EditorModes.TEXT_WITH_BINDING} positionCursorInsideBinding diff --git a/app/client/src/components/propertyControls/ComputeTablePropertyControl.tsx b/app/client/src/components/propertyControls/ComputeTablePropertyControl.tsx index 9f6b11be8450..8bf0173e93a7 100644 --- a/app/client/src/components/propertyControls/ComputeTablePropertyControl.tsx +++ b/app/client/src/components/propertyControls/ComputeTablePropertyControl.tsx @@ -15,7 +15,6 @@ import styled from "styled-components"; import { isString } from "utils/helpers"; import { JSToString, stringToJS } from "./utils"; import LazyCodeEditor from "components/editorComponents/LazyCodeEditor"; -import { assistiveBindingHinter } from "components/editorComponents/CodeEditor/assistiveBindingHinter"; import { bindingHintHelper } from "components/editorComponents/CodeEditor/hintHelpers"; import { slashCommandHintHelper } from "components/editorComponents/CodeEditor/commandsHelper"; @@ -67,11 +66,7 @@ export function InputText(props: { dataTreePath={dataTreePath} evaluatedValue={evaluatedValue} expected={expected} - hinting={[ - bindingHintHelper, - assistiveBindingHinter, - slashCommandHintHelper, - ]} + hinting={[bindingHintHelper, slashCommandHintHelper]} input={{ value: value, onChange: onChange, diff --git a/app/client/src/components/propertyControls/InputTextControl.tsx b/app/client/src/components/propertyControls/InputTextControl.tsx index 10c82975d590..4d948b2958e6 100644 --- a/app/client/src/components/propertyControls/InputTextControl.tsx +++ b/app/client/src/components/propertyControls/InputTextControl.tsx @@ -14,7 +14,6 @@ import { import { CollapseContext } from "pages/Editor/PropertyPane/PropertySection"; import LazyCodeEditor from "../editorComponents/LazyCodeEditor"; import type { AdditionalDynamicDataTree } from "utils/autocomplete/customTreeTypeDefCreator"; -import { assistiveBindingHinter } from "components/editorComponents/CodeEditor/assistiveBindingHinter"; import { bindingHintHelper } from "components/editorComponents/CodeEditor/hintHelpers"; import { slashCommandHintHelper } from "components/editorComponents/CodeEditor/commandsHelper"; @@ -60,11 +59,7 @@ export function InputText(props: { evaluatedValue={evaluatedValue} expected={expected} hideEvaluatedValue={hideEvaluatedValue} - hinting={[ - bindingHintHelper, - assistiveBindingHinter, - slashCommandHintHelper, - ]} + hinting={[bindingHintHelper, slashCommandHintHelper]} hoverInteraction input={{ value: value, diff --git a/app/client/src/components/propertyControls/JSONFormComputeControl.tsx b/app/client/src/components/propertyControls/JSONFormComputeControl.tsx index ed08cbde70e3..df28e7b3d5a7 100644 --- a/app/client/src/components/propertyControls/JSONFormComputeControl.tsx +++ b/app/client/src/components/propertyControls/JSONFormComputeControl.tsx @@ -23,7 +23,6 @@ import { ROOT_SCHEMA_KEY, } from "widgets/JSONFormWidget/constants"; import LazyCodeEditor from "components/editorComponents/LazyCodeEditor"; -import { assistiveBindingHinter } from "components/editorComponents/CodeEditor/assistiveBindingHinter"; import { bindingHintHelper } from "components/editorComponents/CodeEditor/hintHelpers"; import { slashCommandHintHelper } from "components/editorComponents/CodeEditor/commandsHelper"; @@ -141,11 +140,7 @@ export function InputText(props: { dataTreePath={dataTreePath} evaluatedValue={evaluatedValue} expected={expected} - hinting={[ - bindingHintHelper, - assistiveBindingHinter, - slashCommandHintHelper, - ]} + hinting={[bindingHintHelper, slashCommandHintHelper]} input={{ value: value, onChange: onChange, diff --git a/app/client/src/components/propertyControls/MenuButtonDynamicItemsControl.tsx b/app/client/src/components/propertyControls/MenuButtonDynamicItemsControl.tsx index aa0e5a541c08..b25f54666f53 100644 --- a/app/client/src/components/propertyControls/MenuButtonDynamicItemsControl.tsx +++ b/app/client/src/components/propertyControls/MenuButtonDynamicItemsControl.tsx @@ -20,7 +20,6 @@ import type { AdditionalDynamicDataTree } from "utils/autocomplete/customTreeTyp import type { ColumnProperties } from "widgets/TableWidgetV2/component/Constants"; import { getUniqueKeysFromSourceData } from "widgets/MenuButtonWidget/widget/helper"; import LazyCodeEditor from "components/editorComponents/LazyCodeEditor"; -import { assistiveBindingHinter } from "components/editorComponents/CodeEditor/assistiveBindingHinter"; import { bindingHintHelper } from "components/editorComponents/CodeEditor/hintHelpers"; import { slashCommandHintHelper } from "components/editorComponents/CodeEditor/commandsHelper"; @@ -74,11 +73,7 @@ function InputText(props: InputTextProp) { dataTreePath={dataTreePath} evaluatedValue={evaluatedValue} expected={expected} - hinting={[ - bindingHintHelper, - assistiveBindingHinter, - slashCommandHintHelper, - ]} + hinting={[bindingHintHelper, slashCommandHintHelper]} input={{ value: value, onChange: onChange, diff --git a/app/client/src/components/propertyControls/SelectDefaultValueControl.tsx b/app/client/src/components/propertyControls/SelectDefaultValueControl.tsx index 926164863a98..78f7c997adff 100644 --- a/app/client/src/components/propertyControls/SelectDefaultValueControl.tsx +++ b/app/client/src/components/propertyControls/SelectDefaultValueControl.tsx @@ -12,7 +12,6 @@ import { import { getDynamicBindings, isDynamicValue } from "utils/DynamicBindingUtils"; import { isString } from "utils/helpers"; import LazyCodeEditor from "components/editorComponents/LazyCodeEditor"; -import { assistiveBindingHinter } from "components/editorComponents/CodeEditor/assistiveBindingHinter"; import { bindingHintHelper } from "components/editorComponents/CodeEditor/hintHelpers"; import { slashCommandHintHelper } from "components/editorComponents/CodeEditor/commandsHelper"; @@ -76,11 +75,7 @@ function InputText(props: InputTextProp) { dataTreePath={dataTreePath} evaluatedValue={evaluatedValue} expected={expected} - hinting={[ - bindingHintHelper, - assistiveBindingHinter, - slashCommandHintHelper, - ]} + hinting={[bindingHintHelper, slashCommandHintHelper]} input={{ value: value, onChange: onChange, diff --git a/app/client/src/components/propertyControls/TableComputeValue.tsx b/app/client/src/components/propertyControls/TableComputeValue.tsx index a4f07e6f0ef6..65bdc4263535 100644 --- a/app/client/src/components/propertyControls/TableComputeValue.tsx +++ b/app/client/src/components/propertyControls/TableComputeValue.tsx @@ -16,7 +16,6 @@ import { isString } from "utils/helpers"; import { JSToString, stringToJS } from "./utils"; import type { AdditionalDynamicDataTree } from "utils/autocomplete/customTreeTypeDefCreator"; import LazyCodeEditor from "components/editorComponents/LazyCodeEditor"; -import { assistiveBindingHinter } from "components/editorComponents/CodeEditor/assistiveBindingHinter"; import { bindingHintHelper } from "components/editorComponents/CodeEditor/hintHelpers"; import { slashCommandHintHelper } from "components/editorComponents/CodeEditor/commandsHelper"; @@ -70,11 +69,7 @@ function InputText(props: InputTextProp) { dataTreePath={dataTreePath} evaluatedValue={evaluatedValue} expected={expected} - hinting={[ - bindingHintHelper, - assistiveBindingHinter, - slashCommandHintHelper, - ]} + hinting={[bindingHintHelper, slashCommandHintHelper]} input={{ value: value, onChange: onChange, diff --git a/app/client/src/components/propertyControls/TableInlineEditValidationControl.tsx b/app/client/src/components/propertyControls/TableInlineEditValidationControl.tsx index 75edcc5d5042..6cfdee366482 100644 --- a/app/client/src/components/propertyControls/TableInlineEditValidationControl.tsx +++ b/app/client/src/components/propertyControls/TableInlineEditValidationControl.tsx @@ -24,7 +24,6 @@ import { createMessage, TABLE_WIDGET_VALIDATION_ASSIST_PROMPT, } from "@appsmith/constants/messages"; -import { assistiveBindingHinter } from "components/editorComponents/CodeEditor/assistiveBindingHinter"; import { bindingHintHelper } from "components/editorComponents/CodeEditor/hintHelpers"; import { slashCommandHintHelper } from "components/editorComponents/CodeEditor/commandsHelper"; @@ -84,11 +83,7 @@ export function InputText(props: InputTextProp) { dataTreePath={dataTreePath} evaluatedValue={evaluatedValue} expected={expected} - hinting={[ - bindingHintHelper, - assistiveBindingHinter, - slashCommandHintHelper, - ]} + hinting={[bindingHintHelper, slashCommandHintHelper]} input={{ value: value, onChange: onChange, diff --git a/app/client/src/components/propertyControls/WrappedCodeEditorControl.tsx b/app/client/src/components/propertyControls/WrappedCodeEditorControl.tsx index f02df3e8e95e..d521a361d1be 100644 --- a/app/client/src/components/propertyControls/WrappedCodeEditorControl.tsx +++ b/app/client/src/components/propertyControls/WrappedCodeEditorControl.tsx @@ -15,7 +15,6 @@ import { JSToString, stringToJS } from "./utils"; import type { AdditionalDynamicDataTree } from "utils/autocomplete/customTreeTypeDefCreator"; import LazyCodeEditor from "components/editorComponents/LazyCodeEditor"; import type { WidgetProps } from "widgets/BaseWidget"; -import { assistiveBindingHinter } from "components/editorComponents/CodeEditor/assistiveBindingHinter"; import { bindingHintHelper } from "components/editorComponents/CodeEditor/hintHelpers"; import { slashCommandHintHelper } from "components/editorComponents/CodeEditor/commandsHelper"; @@ -50,11 +49,7 @@ function InputText(props: InputTextProp) { dataTreePath={dataTreePath} evaluatedValue={evaluatedValue} expected={expected} - hinting={[ - bindingHintHelper, - assistiveBindingHinter, - slashCommandHintHelper, - ]} + hinting={[bindingHintHelper, slashCommandHintHelper]} input={{ value: value, onChange: onChange,
76ea290301877e5339c5d894a04df5bc7eea8f46
2023-06-02 12:10:49
Ankit Srivastava
fix: excluding intercom test cases for airgap (#23974)
false
excluding intercom test cases for airgap (#23974)
fix
diff --git a/app/client/cypress/e2e/Regression/ClientSide/Editor/HelpButton_spec.ts b/app/client/cypress/e2e/Regression/ClientSide/Editor/HelpButton_spec.ts index 36c339c44388..699eae6884da 100644 --- a/app/client/cypress/e2e/Regression/ClientSide/Editor/HelpButton_spec.ts +++ b/app/client/cypress/e2e/Regression/ClientSide/Editor/HelpButton_spec.ts @@ -1,18 +1,27 @@ import * as _ from "../../../../support/Objects/ObjectsCore"; describe("Help Button on editor", function () { - it("1. Chat with us and Intercom consent should be visible on Help Menu", () => { - _.agHelper.GetNClick(_.debuggerHelper.locators._helpButton, 0, true, 1000); - _.agHelper.GetNClick( - _.debuggerHelper.locators._intercomOption, - 0, - true, - 1000, - ); - _.agHelper.GetNAssertElementText( - _.debuggerHelper.locators._intercomConsentText, - "Can we have your email for better support?", - "contain.text", - ); - }); + it( + "excludeForAirgap", + "1. Chat with us and Intercom consent should be visible on Help Menu", + () => { + _.agHelper.GetNClick( + _.debuggerHelper.locators._helpButton, + 0, + true, + 1000, + ); + _.agHelper.GetNClick( + _.debuggerHelper.locators._intercomOption, + 0, + true, + 1000, + ); + _.agHelper.GetNAssertElementText( + _.debuggerHelper.locators._intercomConsentText, + "Can we have your email for better support?", + "contain.text", + ); + }, + ); });
38c9bc0afc7a6eea0ed1695c15cf3efe966ae23a
2024-10-31 10:43:36
albinAppsmith
fix: datasource name not reflecting in schema pane (#37131)
false
datasource name not reflecting in schema pane (#37131)
fix
diff --git a/app/client/src/pages/Editor/QueryEditor/QueryDebuggerTabs.test.tsx b/app/client/src/pages/Editor/QueryEditor/QueryDebuggerTabs.test.tsx index 23de0834cd0d..6b6097e1b5b9 100644 --- a/app/client/src/pages/Editor/QueryEditor/QueryDebuggerTabs.test.tsx +++ b/app/client/src/pages/Editor/QueryEditor/QueryDebuggerTabs.test.tsx @@ -24,6 +24,7 @@ const storeState = { }, datasources: { structure: {}, + list: [], }, }, ui: { diff --git a/app/client/src/pages/Editor/QueryEditor/QueryDebuggerTabs.tsx b/app/client/src/pages/Editor/QueryEditor/QueryDebuggerTabs.tsx index 7d283d140f59..54d13072d079 100644 --- a/app/client/src/pages/Editor/QueryEditor/QueryDebuggerTabs.tsx +++ b/app/client/src/pages/Editor/QueryEditor/QueryDebuggerTabs.tsx @@ -21,6 +21,7 @@ import type { SourceEntity } from "entities/AppsmithConsole"; import type { Action } from "entities/Action"; import QueryResponseTab from "PluginActionEditor/components/PluginActionResponse/components/QueryResponseTab"; import { + getDatasource, getDatasourceStructureById, getPluginDatasourceComponentFromId, } from "ee/selectors/entitiesSelector"; @@ -97,6 +98,10 @@ function QueryDebuggerTabs({ ), ); + const datasource = useSelector((state) => + getDatasource(state, currentActionConfig?.datasource?.id ?? ""), + ); + useEffect(() => { if ( currentActionConfig?.datasource?.id && @@ -252,7 +257,7 @@ function QueryDebuggerTabs({ <Schema currentActionId={currentActionConfig.id} datasourceId={currentActionConfig.datasource.id || ""} - datasourceName={currentActionConfig.datasource.name || ""} + datasourceName={datasource?.name || ""} /> ), });
ab568573cf81b73788c604e4efa16bd34e17b392
2023-03-16 14:33:35
Nayan
chore: Refactored code for git discard flow (#21453)
false
Refactored code for git discard flow (#21453)
chore
diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/controllers/ce/GitControllerCE.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/controllers/ce/GitControllerCE.java index 910cc3938b16..a8a91366b20c 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/controllers/ce/GitControllerCE.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/controllers/ce/GitControllerCE.java @@ -227,10 +227,9 @@ public Mono<ResponseDTO<Application>> deleteBranch(@PathVariable String defaultA @PutMapping("/discard/app/{defaultApplicationId}") public Mono<ResponseDTO<Application>> discardChanges(@PathVariable String defaultApplicationId, - @RequestParam(required = false, defaultValue = "true") Boolean doPull, @RequestHeader(name = FieldName.BRANCH_NAME) String branchName) { log.debug("Going to discard changes for branch {} with defaultApplicationId {}", branchName, defaultApplicationId); - return service.discardChanges(defaultApplicationId, branchName, doPull) + return service.discardChanges(defaultApplicationId, branchName) .map(result -> new ResponseDTO<>((HttpStatus.OK.value()), result, null)); } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/GitServiceCE.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/GitServiceCE.java index 01868109d706..1ad4606217b3 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/GitServiceCE.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/GitServiceCE.java @@ -8,15 +8,14 @@ import com.appsmith.server.domains.GitApplicationMetadata; import com.appsmith.server.domains.GitAuth; import com.appsmith.server.domains.GitProfile; +import com.appsmith.server.dtos.ApplicationImportDTO; import com.appsmith.server.dtos.GitCommitDTO; import com.appsmith.server.dtos.GitConnectDTO; -import com.appsmith.server.dtos.ApplicationImportDTO; import com.appsmith.server.dtos.GitDocsDTO; import com.appsmith.server.dtos.GitMergeDTO; import com.appsmith.server.dtos.GitPullDTO; import reactor.core.publisher.Mono; -import java.util.EnumSet; import java.util.List; import java.util.Map; @@ -70,7 +69,7 @@ public interface GitServiceCE { Mono<Application> deleteBranch(String defaultApplicationId, String branchName); - Mono<Application> discardChanges(String defaultApplicationId, String branchName, Boolean doPull); + Mono<Application> discardChanges(String defaultApplicationId, String branchName); Mono<List<GitDocsDTO>> getGitDocUrls(); 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 4ae3a65eeebb..863ddfb1633a 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 @@ -83,7 +83,6 @@ import java.nio.file.Path; import java.nio.file.Paths; import java.time.Duration; -import java.util.ArrayList; import java.time.Instant; import java.util.ArrayList; import java.util.HashMap; @@ -2193,7 +2192,7 @@ public Mono<Application> deleteBranch(String defaultApplicationId, String branch } @Override - public Mono<Application> discardChanges(String defaultApplicationId, String branchName, Boolean doPull) { + public Mono<Application> discardChanges(String defaultApplicationId, String branchName) { if (StringUtils.isEmptyOrNull(defaultApplicationId)) { return Mono.error(new AppsmithException(AppsmithError.INVALID_PARAMETER, FieldName.APPLICATION_ID)); @@ -2204,42 +2203,33 @@ public Mono<Application> discardChanges(String defaultApplicationId, String bran Mono<Application> defaultApplicationMono = this.getApplicationById(defaultApplicationId); Mono<Application> discardChangeMono; - if (Boolean.TRUE.equals(doPull)) { - discardChangeMono = defaultApplicationMono - // Add file lock before proceeding with the git operation - .flatMap(application -> addFileLock(defaultApplicationId).thenReturn(application)) - .flatMap(defaultApplication -> this.pullAndRehydrateApplication(defaultApplication, branchName)) - .map(GitPullDTO::getApplication) - .flatMap(application -> releaseFileLock(defaultApplicationId) - .then(this.addAnalyticsForGitOperation(AnalyticsEvents.GIT_DISCARD_CHANGES.getEventName(), application, null))) - .map(responseUtils::updateApplicationWithDefaultResources); - } else { - // Rehydrate the application from local file system - discardChangeMono = branchedApplicationMono - // Add file lock before proceeding with the git operation - .flatMap(application -> addFileLock(defaultApplicationId).thenReturn(application)) - .flatMap(branchedApplication -> { - GitApplicationMetadata gitData = branchedApplication.getGitApplicationMetadata(); - if (gitData == null || StringUtils.isEmptyOrNull(gitData.getDefaultApplicationId())) { - return Mono.error(new AppsmithException(AppsmithError.INVALID_GIT_CONFIGURATION, GIT_CONFIG_ERROR)); - } - Path repoSuffix = Paths.get(branchedApplication.getWorkspaceId(), gitData.getDefaultApplicationId(), gitData.getRepoName()); - return gitExecutor.checkoutToBranch(repoSuffix, branchName) - .then(fileUtils.reconstructApplicationJsonFromGitRepo( - branchedApplication.getWorkspaceId(), - branchedApplication.getGitApplicationMetadata().getDefaultApplicationId(), - branchedApplication.getGitApplicationMetadata().getRepoName(), - branchName) - ) - .flatMap(applicationJson -> - importExportApplicationService - .importApplicationInWorkspace(branchedApplication.getWorkspaceId(), applicationJson, branchedApplication.getId(), branchName) - ); - }) - .flatMap(application -> releaseFileLock(defaultApplicationId) - .then(this.addAnalyticsForGitOperation(AnalyticsEvents.GIT_DISCARD_CHANGES.getEventName(), application, null))) - .map(responseUtils::updateApplicationWithDefaultResources); - } + + // Rehydrate the application from local file system + discardChangeMono = branchedApplicationMono + // Add file lock before proceeding with the git operation + .flatMap(application -> addFileLock(defaultApplicationId).thenReturn(application)) + .flatMap(branchedApplication -> { + GitApplicationMetadata gitData = branchedApplication.getGitApplicationMetadata(); + if (gitData == null || StringUtils.isEmptyOrNull(gitData.getDefaultApplicationId())) { + return Mono.error(new AppsmithException(AppsmithError.INVALID_GIT_CONFIGURATION, GIT_CONFIG_ERROR)); + } + Path repoSuffix = Paths.get(branchedApplication.getWorkspaceId(), gitData.getDefaultApplicationId(), gitData.getRepoName()); + return gitExecutor.checkoutToBranch(repoSuffix, branchName) + .then(fileUtils.reconstructApplicationJsonFromGitRepo( + branchedApplication.getWorkspaceId(), + branchedApplication.getGitApplicationMetadata().getDefaultApplicationId(), + branchedApplication.getGitApplicationMetadata().getRepoName(), + branchName) + ) + .flatMap(applicationJson -> + importExportApplicationService + .importApplicationInWorkspace(branchedApplication.getWorkspaceId(), applicationJson, branchedApplication.getId(), branchName) + ); + }) + .flatMap(application -> releaseFileLock(defaultApplicationId) + .then(this.addAnalyticsForGitOperation(AnalyticsEvents.GIT_DISCARD_CHANGES.getEventName(), application, null))) + .map(responseUtils::updateApplicationWithDefaultResources); + return Mono.create(sink -> discardChangeMono .subscribe(sink::success, sink::error, null, sink.currentContext()) 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 8f21344e4bd9..4892508724f1 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 @@ -10,9 +10,9 @@ import com.appsmith.external.models.DatasourceConfiguration; import com.appsmith.external.models.DefaultResources; import com.appsmith.external.models.JSValue; +import com.appsmith.external.models.PluginType; import com.appsmith.server.constants.FieldName; import com.appsmith.server.domains.ActionCollection; -import com.appsmith.external.models.PluginType; import com.appsmith.server.domains.Application; import com.appsmith.server.domains.ApplicationPage; import com.appsmith.server.domains.GitApplicationMetadata; @@ -59,9 +59,6 @@ import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mockito; -import org.mockito.internal.stubbing.answers.AnswersWithDelay; -import org.mockito.invocation.InvocationOnMock; -import org.mockito.stubbing.Answer; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.mock.mockito.MockBean; @@ -3161,7 +3158,7 @@ public void discardChanges_upstreamChangesAvailable_discardSuccess() throws IOEx Mockito.when(gitExecutor.resetToLastCommit(Mockito.any(Path.class), Mockito.anyString())) .thenReturn(Mono.just(true)); - Mono<Application> applicationMono = gitService.discardChanges(application.getId(), application.getGitApplicationMetadata().getBranchName(), true); + Mono<Application> applicationMono = gitService.discardChanges(application.getId(), application.getGitApplicationMetadata().getBranchName()); StepVerifier .create(applicationMono) @@ -3201,7 +3198,7 @@ public void discardChanges_cancelledMidway_discardSuccess() throws IOException, .thenReturn(Mono.just("fetched")); gitService - .discardChanges(application.getId(), application.getGitApplicationMetadata().getBranchName(), true) + .discardChanges(application.getId(), application.getGitApplicationMetadata().getBranchName()) .timeout(Duration.ofNanos(100)) .subscribe();
a1884e13363a7db69ff05fc452b471077c89d5d9
2022-03-30 18:52:01
Paul Li
feat: Hide shadows of hiddens objects during page loading in deploy view (#12184)
false
Hide shadows of hiddens objects during page loading in deploy view (#12184)
feat
diff --git a/app/client/src/widgets/CanvasWidget.tsx b/app/client/src/widgets/CanvasWidget.tsx index 6a2b7e905f9f..45f11a95804d 100644 --- a/app/client/src/widgets/CanvasWidget.tsx +++ b/app/client/src/widgets/CanvasWidget.tsx @@ -3,7 +3,7 @@ import { WidgetProps } from "widgets/BaseWidget"; import ContainerWidget, { ContainerWidgetProps, } from "widgets/ContainerWidget/widget"; -import { GridDefaults } from "constants/WidgetConstants"; +import { GridDefaults, RenderModes } from "constants/WidgetConstants"; import DropTargetComponent from "components/editorComponents/DropTargetComponent"; import { getCanvasSnapRows } from "utils/WidgetPropsUtils"; import { getCanvasClassName } from "utils/generators"; @@ -48,6 +48,15 @@ class CanvasWidget extends ContainerWidget { if (childWidgetData.detachFromLayout && !childWidgetData.isVisible) { return null; } + + // We don't render invisible widgets in view mode + if ( + this.props.renderMode === RenderModes.PAGE && + !childWidgetData.isVisible + ) { + return null; + } + const snapSpaces = this.getSnapSpaces(); childWidgetData.parentColumnSpace = snapSpaces.snapColumnSpace;
c7a7c3fa3f594c9224b078a7139a7f052624b97f
2024-07-30 19:45:48
Ilia
chore: upgrade typescript to 5.4 (#35181)
false
upgrade typescript to 5.4 (#35181)
chore
diff --git a/app/client/package.json b/app/client/package.json index ffa686d9ba01..33795134b191 100644 --- a/app/client/package.json +++ b/app/client/package.json @@ -235,7 +235,7 @@ "to-json-schema": "^0.2.5", "toposort": "^2.0.2", "tslib": "^2.3.1", - "typescript": "4.9.5", + "typescript": "5.4", "unescape-js": "^1.1.4", "url-search-params-polyfill": "^8.0.0", "uuid": "^9.0.0", @@ -373,7 +373,7 @@ "redux-devtools-extension": "^2.13.8", "redux-mock-store": "^1.5.4", "redux-saga-test-plan": "^4.0.6", - "ts-jest": "27.0.0", + "ts-jest": "29.1.0", "ts-jest-mock-import-meta": "^0.12.0", "ts-loader": "^9.4.1", "ts-node": "^10.9.1", diff --git a/app/client/packages/ast/package.json b/app/client/packages/ast/package.json index e7e50e549f82..78945646fa63 100644 --- a/app/client/packages/ast/package.json +++ b/app/client/packages/ast/package.json @@ -28,7 +28,7 @@ "rollup-plugin-generate-package-json": "^3.2.0", "rollup-plugin-peer-deps-external": "^2.2.4", "rollup-plugin-typescript2": "^0.32.0", - "typescript": "4.5.5", + "typescript": "5.4", "unescape-js": "^1.1.4" }, "devDependencies": { @@ -37,6 +37,6 @@ "@typescript-eslint/eslint-plugin": "^5.25.0", "@typescript-eslint/parser": "^5.25.0", "jest": "29.0.3", - "ts-jest": "29.0.1" + "ts-jest": "29.1.0" } } diff --git a/app/client/packages/design-system/ads/jest.config.js b/app/client/packages/design-system/ads/jest.config.js index ac214bc178d5..b9025f10e6db 100644 --- a/app/client/packages/design-system/ads/jest.config.js +++ b/app/client/packages/design-system/ads/jest.config.js @@ -5,7 +5,15 @@ module.exports = { setupFilesAfterEnv: ["<rootDir>/jest.setup.js"], // Optional: Additional setup testEnvironment: "jsdom", transform: { - "^.+\\.(ts|tsx)$": "ts-jest", // Use ts-jest for transforming TypeScript files + "^.+\\.(ts|tsx)$": [ + "ts-jest", + { + useESM: true, + tsconfig: { + verbatimModuleSyntax: false, + }, + }, + ], // Use ts-jest for transforming TypeScript files "\\.(svg)$": "<rootDir>/fileTransformer.js", // Create this file for SVG handling (see below) }, moduleNameMapper: { diff --git a/app/client/packages/design-system/ads/src/Icon/Icon.types.ts b/app/client/packages/design-system/ads/src/Icon/Icon.types.ts index d51723cb7c64..92fa1deb3ab7 100644 --- a/app/client/packages/design-system/ads/src/Icon/Icon.types.ts +++ b/app/client/packages/design-system/ads/src/Icon/Icon.types.ts @@ -18,4 +18,4 @@ export type IconProps = { wrapperColor?: string; } & React.HTMLAttributes<HTMLSpanElement>; -export { IconNames }; +export type { IconNames }; diff --git a/app/client/packages/design-system/theming/jest.config.js b/app/client/packages/design-system/theming/jest.config.js index c24244a0983d..fd6b5b15bda6 100644 --- a/app/client/packages/design-system/theming/jest.config.js +++ b/app/client/packages/design-system/theming/jest.config.js @@ -1,5 +1,15 @@ +const { globals } = require("@design-system/widgets-old/jest.config"); + module.exports = { preset: "ts-jest", roots: ["<rootDir>/src"], testEnvironment: "jsdom", + globals: { + "ts-jest": { + useESM: true, + tsconfig: { + verbatimModuleSyntax: false, + }, + }, + }, }; diff --git a/app/client/packages/design-system/widgets/jest.config.js b/app/client/packages/design-system/widgets/jest.config.js index c66c3f59cec8..7d00772a189a 100644 --- a/app/client/packages/design-system/widgets/jest.config.js +++ b/app/client/packages/design-system/widgets/jest.config.js @@ -6,4 +6,12 @@ module.exports = { "\\.(css)$": "<rootDir>../../../test/__mocks__/styleMock.js", "@design-system/widgets": "<rootDir>/src/", }, + globals: { + "ts-jest": { + useESM: true, + tsconfig: { + verbatimModuleSyntax: false, + }, + }, + }, }; diff --git a/app/client/packages/dsl/jest.config.js b/app/client/packages/dsl/jest.config.js index 29cf9f0a1dbd..0f3b397ad9fd 100644 --- a/app/client/packages/dsl/jest.config.js +++ b/app/client/packages/dsl/jest.config.js @@ -1,6 +1,14 @@ module.exports = { transform: { - "^.+\\.(png|js|ts|tsx)$": "ts-jest", + "^.+\\.(png|js|ts|tsx)$": [ + "ts-jest", + { + useESM: true, + tsconfig: { + verbatimModuleSyntax: false, + }, + }, + ], }, verbose: true, }; diff --git a/app/client/packages/dsl/package.json b/app/client/packages/dsl/package.json index 026d96ea787c..d22e40cbb519 100644 --- a/app/client/packages/dsl/package.json +++ b/app/client/packages/dsl/package.json @@ -21,7 +21,7 @@ "rollup-plugin-generate-package-json": "^3.2.0", "rollup-plugin-peer-deps-external": "^2.2.4", "rollup-plugin-typescript2": "^0.32.0", - "typescript": "4.5.5" + "typescript": "5.4" }, "devDependencies": { "@rollup/plugin-json": "^6.0.0", diff --git a/app/client/packages/rts/package.json b/app/client/packages/rts/package.json index 67a30f476b2e..08570fc176d4 100644 --- a/app/client/packages/rts/package.json +++ b/app/client/packages/rts/package.json @@ -35,8 +35,8 @@ "esbuild": "^0.19.4", "jest": "^29.3.1", "supertest": "^6.3.3", - "ts-jest": "^29.0.3", + "ts-jest": "29.1.0", "tsc-alias": "^1.8.2", - "typescript": "4.9.5" + "typescript": "5.4" } } diff --git a/app/client/packages/rts/src/controllers/Ast/AstController.ts b/app/client/packages/rts/src/controllers/Ast/AstController.ts index 02348b310176..d53424fc61ab 100644 --- a/app/client/packages/rts/src/controllers/Ast/AstController.ts +++ b/app/client/packages/rts/src/controllers/Ast/AstController.ts @@ -38,7 +38,7 @@ export default class AstController extends BaseController { } catch (err) { return super.sendError( res, - super.serverErrorMessaage, + this.serverErrorMessage, [err.message], StatusCodes.INTERNAL_SERVER_ERROR, ); @@ -65,7 +65,7 @@ export default class AstController extends BaseController { } catch (err) { return super.sendError( res, - super.serverErrorMessaage, + this.serverErrorMessage, [err.message], StatusCodes.INTERNAL_SERVER_ERROR, ); @@ -93,7 +93,7 @@ export default class AstController extends BaseController { } catch (err) { return super.sendError( res, - super.serverErrorMessaage, + this.serverErrorMessage, [err.message], StatusCodes.INTERNAL_SERVER_ERROR, ); diff --git a/app/client/packages/rts/src/controllers/BaseController.ts b/app/client/packages/rts/src/controllers/BaseController.ts index 389cc243f3cb..d6b03582df41 100644 --- a/app/client/packages/rts/src/controllers/BaseController.ts +++ b/app/client/packages/rts/src/controllers/BaseController.ts @@ -21,7 +21,7 @@ interface ResponseData { } export default class BaseController { - serverErrorMessaage = "Something went wrong"; + serverErrorMessage = "Something went wrong"; sendResponse( response: Response, result?: unknown, diff --git a/app/client/packages/rts/src/controllers/Dsl/DslController.ts b/app/client/packages/rts/src/controllers/Dsl/DslController.ts index d108a2c0bd93..8c5065396d84 100644 --- a/app/client/packages/rts/src/controllers/Dsl/DslController.ts +++ b/app/client/packages/rts/src/controllers/Dsl/DslController.ts @@ -15,7 +15,7 @@ export default class DSLController extends BaseController { } catch (err) { return super.sendError( res, - super.serverErrorMessaage, + this.serverErrorMessage, [err.message], StatusCodes.INTERNAL_SERVER_ERROR, ); @@ -28,7 +28,7 @@ export default class DSLController extends BaseController { } catch (err) { return super.sendError( res, - super.serverErrorMessaage, + this.serverErrorMessage, [err.message], StatusCodes.INTERNAL_SERVER_ERROR, ); diff --git a/app/client/packages/rts/src/controllers/healthCheck/HealthCheckController.ts b/app/client/packages/rts/src/controllers/healthCheck/HealthCheckController.ts index 5fab8d5c3972..207bacc101d8 100644 --- a/app/client/packages/rts/src/controllers/healthCheck/HealthCheckController.ts +++ b/app/client/packages/rts/src/controllers/healthCheck/HealthCheckController.ts @@ -14,7 +14,7 @@ export default class HealthCheckController extends BaseController { } catch (err) { return super.sendError( res, - super.serverErrorMessaage, + this.serverErrorMessage, [err.message], StatusCodes.INTERNAL_SERVER_ERROR, ); diff --git a/app/client/src/components/editorComponents/GlobalSearch/SearchModal.tsx b/app/client/src/components/editorComponents/GlobalSearch/SearchModal.tsx index df30d1f9f55a..a35460828f5e 100644 --- a/app/client/src/components/editorComponents/GlobalSearch/SearchModal.tsx +++ b/app/client/src/components/editorComponents/GlobalSearch/SearchModal.tsx @@ -55,6 +55,7 @@ function DocsSearchModal({ className={`${className}`} data-testid="t--global-search-modal" > + {/* @ts-expect-error Figure out how to pass string to constant className */} <ModalBody className={`${className}`}>{children}</ModalBody> </StyledDocsSearchModal> </Modal> diff --git a/app/client/src/pages/Editor/gitSync/Tabs/GitConnection.tsx b/app/client/src/pages/Editor/gitSync/Tabs/GitConnection.tsx index 1f21a5d69009..387ad8c186ae 100644 --- a/app/client/src/pages/Editor/gitSync/Tabs/GitConnection.tsx +++ b/app/client/src/pages/Editor/gitSync/Tabs/GitConnection.tsx @@ -351,6 +351,7 @@ function GitConnection({ isImport }: Props) { return ( <> + {/* @ts-expect-error Figure out how to pass string to constant className */} <ModalBody className={Classes.GIT_SYNC_MODAL}> <Container data-testid="t--git-connection-container" diff --git a/app/client/src/utils/helpers.tsx b/app/client/src/utils/helpers.tsx index 419ef131b624..2c998647b96a 100644 --- a/app/client/src/utils/helpers.tsx +++ b/app/client/src/utils/helpers.tsx @@ -524,7 +524,7 @@ export const removeFalsyEntries = (arr: any[]): any[] => { * ['Pawan', 'Goku'] -> false * { name: "Pawan"} -> false */ -export const isString = (str: any) => { +export const isString = (str: any): str is string => { return typeof str === "string" || str instanceof String; }; diff --git a/app/client/src/workers/Evaluation/indirectEval.ts b/app/client/src/workers/Evaluation/indirectEval.ts index 6a4e0089be5d..72a835621a97 100644 --- a/app/client/src/workers/Evaluation/indirectEval.ts +++ b/app/client/src/workers/Evaluation/indirectEval.ts @@ -1,5 +1,5 @@ export default function indirectEval(script: string) { - /* Indirect eval to prevent local scope access. - Ref. - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval#description */ + // @ts-expect-error We want evaluation to be done only on global scope and shouldn't have access to any local scope variable. + // Ref. - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval#description return (1, eval)(script); } diff --git a/app/client/tsconfig.json b/app/client/tsconfig.json index e0cc91421b6f..3796279b383a 100644 --- a/app/client/tsconfig.json +++ b/app/client/tsconfig.json @@ -32,7 +32,7 @@ "sourceMap": true, "baseUrl": "./src", "noFallthroughCasesInSwitch": true, - "importsNotUsedAsValues": "error" + "verbatimModuleSyntax": true }, "include": ["./src/**/*", "./packages"], "exclude": ["./packages/rts", "**/node_modules", "**/.*/"] diff --git a/app/client/yarn.lock b/app/client/yarn.lock index 65ac01e0ad1d..7259c7a908a9 100644 --- a/app/client/yarn.lock +++ b/app/client/yarn.lock @@ -8615,8 +8615,8 @@ __metadata: rollup-plugin-generate-package-json: ^3.2.0 rollup-plugin-peer-deps-external: ^2.2.4 rollup-plugin-typescript2: ^0.32.0 - ts-jest: 29.0.1 - typescript: 4.5.5 + ts-jest: 29.1.0 + typescript: 5.4 unescape-js: ^1.1.4 languageName: unknown linkType: soft @@ -8637,7 +8637,7 @@ __metadata: rollup-plugin-peer-deps-external: ^2.2.4 rollup-plugin-typescript2: ^0.32.0 ts-jest: ^29.1.0 - typescript: 4.5.5 + typescript: 5.4 languageName: unknown linkType: soft @@ -13174,9 +13174,9 @@ __metadata: socket.io-adapter: ^2.4.0 source-map-support: ^0.5.19 supertest: ^6.3.3 - ts-jest: ^29.0.3 + ts-jest: 29.1.0 tsc-alias: ^1.8.2 - typescript: 4.9.5 + typescript: 5.4 languageName: unknown linkType: soft @@ -13491,12 +13491,12 @@ __metadata: tinycolor2: ^1.4.2 to-json-schema: ^0.2.5 toposort: ^2.0.2 - ts-jest: 27.0.0 + ts-jest: 29.1.0 ts-jest-mock-import-meta: ^0.12.0 ts-loader: ^9.4.1 ts-node: ^10.9.1 tslib: ^2.3.1 - typescript: 4.9.5 + typescript: 5.4 unescape-js: ^1.1.4 url-search-params-polyfill: ^8.0.0 uuid: ^9.0.0 @@ -14892,7 +14892,7 @@ __metadata: languageName: node linkType: hard -"buffer-from@npm:1.x, buffer-from@npm:^1.0.0": +"buffer-from@npm:^1.0.0": version: 1.1.2 resolution: "buffer-from@npm:1.1.2" checksum: 0448524a562b37d4d7ed9efd91685a5b77a50672c556ea254ac9a6d30e3403a517d8981f10e565db24e8339413b43c97ca2951f10e399c6125a0d8911f5679bb @@ -23714,7 +23714,7 @@ __metadata: languageName: node linkType: hard -"jest-util@npm:^27.0.0, jest-util@npm:^27.5.1": +"jest-util@npm:^27.5.1": version: 27.5.1 resolution: "jest-util@npm:27.5.1" dependencies: @@ -24802,7 +24802,7 @@ __metadata: languageName: node linkType: hard -"lodash@npm:*, lodash@npm:4.x, lodash@npm:^4, lodash@npm:^4.17.10, lodash@npm:^4.17.15, lodash@npm:^4.17.19, lodash@npm:^4.17.20, lodash@npm:^4.17.21, lodash@npm:^4.17.4, lodash@npm:^4.7.0, lodash@npm:~4.17.21": +"lodash@npm:*, lodash@npm:^4, lodash@npm:^4.17.10, lodash@npm:^4.17.15, lodash@npm:^4.17.19, lodash@npm:^4.17.20, lodash@npm:^4.17.21, lodash@npm:^4.17.4, lodash@npm:^4.7.0, lodash@npm:~4.17.21": version: 4.17.21 resolution: "lodash@npm:4.17.21" checksum: eb835a2e51d381e561e508ce932ea50a8e5a68f4ebdd771ea240d3048244a8d13658acbd502cd4829768c56f2e16bdd4340b9ea141297d472517b83868e677f7 @@ -26000,15 +26000,6 @@ __metadata: languageName: node linkType: hard -"mkdirp@npm:1.x, mkdirp@npm:^1.0.3, mkdirp@npm:^1.0.4": - version: 1.0.4 - resolution: "mkdirp@npm:1.0.4" - bin: - mkdirp: bin/cmd.js - checksum: a96865108c6c3b1b8e1d5e9f11843de1e077e57737602de1b82030815f311be11f96f09cce59bd5b903d0b29834733e5313f9301e3ed6d6f6fba2eae0df4298f - languageName: node - linkType: hard - "mkdirp@npm:^0.5.1, mkdirp@npm:^0.5.5, mkdirp@npm:~0.5.1": version: 0.5.6 resolution: "mkdirp@npm:0.5.6" @@ -26020,6 +26011,15 @@ __metadata: languageName: node linkType: hard +"mkdirp@npm:^1.0.3, mkdirp@npm:^1.0.4": + version: 1.0.4 + resolution: "mkdirp@npm:1.0.4" + bin: + mkdirp: bin/cmd.js + checksum: a96865108c6c3b1b8e1d5e9f11843de1e077e57737602de1b82030815f311be11f96f09cce59bd5b903d0b29834733e5313f9301e3ed6d6f6fba2eae0df4298f + languageName: node + linkType: hard + "mochawesome-merge@npm:^4.2.1": version: 4.3.0 resolution: "mochawesome-merge@npm:4.3.0" @@ -34225,63 +34225,7 @@ __metadata: languageName: node linkType: hard -"ts-jest@npm:27.0.0": - version: 27.0.0 - resolution: "ts-jest@npm:27.0.0" - dependencies: - bs-logger: 0.x - buffer-from: 1.x - fast-json-stable-stringify: 2.x - jest-util: ^27.0.0 - json5: 2.x - lodash: 4.x - make-error: 1.x - mkdirp: 1.x - semver: 7.x - yargs-parser: 20.x - peerDependencies: - jest: ^27.0.0 - typescript: ">=3.8 <5.0" - bin: - ts-jest: cli.js - checksum: 02ef5ed2d444bb003f8e6bef1cf0fb1e45446f80a94e2673dd6a2c8ae35ae80b668c6ba09962add2962a27258dd79a67dd4cb062358769749d74ba9a81caad2c - languageName: node - linkType: hard - -"ts-jest@npm:29.0.1": - version: 29.0.1 - resolution: "ts-jest@npm:29.0.1" - dependencies: - bs-logger: 0.x - fast-json-stable-stringify: 2.x - jest-util: ^29.0.0 - json5: ^2.2.1 - lodash.memoize: 4.x - make-error: 1.x - semver: 7.x - yargs-parser: ^21.0.1 - peerDependencies: - "@babel/core": ">=7.0.0-beta.0 <8" - "@jest/types": ^29.0.0 - babel-jest: ^29.0.0 - jest: ^29.0.0 - typescript: ">=4.3" - peerDependenciesMeta: - "@babel/core": - optional: true - "@jest/types": - optional: true - babel-jest: - optional: true - esbuild: - optional: true - bin: - ts-jest: cli.js - checksum: f126675beb0d103d440b0297dc331ce37ba0f1e1a8002f4e97bfeb9043cf21b4de03deebf11ac1f08b7e4978d87f6a1c71e398b1c2f8535df3b684338786408e - languageName: node - linkType: hard - -"ts-jest@npm:^29.0.3, ts-jest@npm:^29.1.0": +"ts-jest@npm:29.1.0, ts-jest@npm:^29.1.0": version: 29.1.0 resolution: "ts-jest@npm:29.1.0" dependencies: @@ -34680,43 +34624,23 @@ __metadata: languageName: node linkType: hard -"typescript@npm:4.5.5": - version: 4.5.5 - resolution: "typescript@npm:4.5.5" +"typescript@npm:5.4": + version: 5.4.5 + resolution: "typescript@npm:5.4.5" bin: tsc: bin/tsc tsserver: bin/tsserver - checksum: 506f4c919dc8aeaafa92068c997f1d213b9df4d9756d0fae1a1e7ab66b585ab3498050e236113a1c9e57ee08c21ec6814ca7a7f61378c058d79af50a4b1f5a5e + checksum: 53c879c6fa1e3bcb194b274d4501ba1985894b2c2692fa079db03c5a5a7140587a1e04e1ba03184605d35f439b40192d9e138eb3279ca8eee313c081c8bcd9b0 languageName: node linkType: hard -"typescript@npm:4.9.5": - version: 4.9.5 - resolution: "typescript@npm:4.9.5" +"typescript@patch:[email protected]#~builtin<compat/typescript>": + version: 5.4.5 + resolution: "typescript@patch:typescript@npm%3A5.4.5#~builtin<compat/typescript>::version=5.4.5&hash=77c9e2" bin: tsc: bin/tsc tsserver: bin/tsserver - checksum: ee000bc26848147ad423b581bd250075662a354d84f0e06eb76d3b892328d8d4440b7487b5a83e851b12b255f55d71835b008a66cbf8f255a11e4400159237db - languageName: node - linkType: hard - -"typescript@patch:[email protected]#~builtin<compat/typescript>": - version: 4.5.5 - resolution: "typescript@patch:typescript@npm%3A4.5.5#~builtin<compat/typescript>::version=4.5.5&hash=bcec9a" - bin: - tsc: bin/tsc - tsserver: bin/tsserver - checksum: 858c61fa63f7274ca4aaaffeced854d550bf416cff6e558c4884041b3311fb662f476f167cf5c9f8680c607239797e26a2ee0bcc6467fbc05bfcb218e1c6c671 - languageName: node - linkType: hard - -"typescript@patch:[email protected]#~builtin<compat/typescript>": - version: 4.9.5 - resolution: "typescript@patch:typescript@npm%3A4.9.5#~builtin<compat/typescript>::version=4.9.5&hash=289587" - bin: - tsc: bin/tsc - tsserver: bin/tsserver - checksum: 1f8f3b6aaea19f0f67cba79057674ba580438a7db55057eb89cc06950483c5d632115c14077f6663ea76fd09fce3c190e6414bb98582ec80aa5a4eaf345d5b68 + checksum: 2373c693f3b328f3b2387c3efafe6d257b057a142f9a79291854b14ff4d5367d3d730810aee981726b677ae0fd8329b23309da3b6aaab8263dbdccf1da07a3ba languageName: node linkType: hard @@ -36542,13 +36466,6 @@ __metadata: languageName: node linkType: hard -"yargs-parser@npm:20.x, yargs-parser@npm:^20.2.2": - version: 20.2.9 - resolution: "yargs-parser@npm:20.2.9" - checksum: 8bb69015f2b0ff9e17b2c8e6bfe224ab463dd00ca211eece72a4cd8a906224d2703fb8a326d36fdd0e68701e201b2a60ed7cf81ce0fd9b3799f9fe7745977ae3 - languageName: node - linkType: hard - "yargs-parser@npm:^15.0.1": version: 15.0.1 resolution: "yargs-parser@npm:15.0.1" @@ -36569,6 +36486,13 @@ __metadata: languageName: node linkType: hard +"yargs-parser@npm:^20.2.2": + version: 20.2.9 + resolution: "yargs-parser@npm:20.2.9" + checksum: 8bb69015f2b0ff9e17b2c8e6bfe224ab463dd00ca211eece72a4cd8a906224d2703fb8a326d36fdd0e68701e201b2a60ed7cf81ce0fd9b3799f9fe7745977ae3 + languageName: node + linkType: hard + "yargs-parser@npm:^21.0.1, yargs-parser@npm:^21.1.1": version: 21.1.1 resolution: "yargs-parser@npm:21.1.1"
95869517f6c227d5c8f727a67dc4930c8f2662ff
2021-12-21 11:19:00
Abhijeet
fix: Replace default IDs for forked application with destination resource IDs (#9886)
false
Replace default IDs for forked application with destination resource IDs (#9886)
fix
diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ce/ExamplesOrganizationClonerCEImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ce/ExamplesOrganizationClonerCEImpl.java index 1c6ff18e304b..9b6150aebb96 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ce/ExamplesOrganizationClonerCEImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ce/ExamplesOrganizationClonerCEImpl.java @@ -7,6 +7,7 @@ import com.appsmith.external.models.Datasource; import com.appsmith.external.models.DefaultResources; import com.appsmith.server.constants.FieldName; +import com.appsmith.server.domains.ActionCollection; import com.appsmith.server.domains.Application; import com.appsmith.server.domains.ApplicationPage; import com.appsmith.server.domains.Layout; @@ -236,6 +237,7 @@ public Mono<List<String>> cloneApplications( ActionDTO action = newAction.getUnpublishedAction(); log.info("Preparing action for cloning {} {}.", action.getName(), newAction.getId()); action.setPageId(savedPage.getId()); + action.setDefaultResources(null); return newAction; }) .flatMap(newAction -> { @@ -244,7 +246,6 @@ public Mono<List<String>> cloneApplications( makePristine(newAction); newAction.setOrganizationId(toOrganizationId); ActionDTO action = newAction.getUnpublishedAction(); - final String originalCollectionId = action.getCollectionId(); action.setCollectionId(null); Mono<ActionDTO> actionMono = Mono.just(action); @@ -286,24 +287,55 @@ actionDTO, new AppsmithEventContext(AppsmithEventContextType.CLONE_PAGE)) makePristine(actionCollection); final ActionCollectionDTO unpublishedCollection = actionCollection.getUnpublishedCollection(); unpublishedCollection.setPageId(savedPage.getId()); + + DefaultResources defaultResources = new DefaultResources(); + defaultResources.setPageId(savedPage.getId()); + unpublishedCollection.setDefaultResources(defaultResources); + actionCollection.setOrganizationId(toOrganizationId); actionCollection.setApplicationId(savedPage.getApplicationId()); + + DefaultResources defaultResources1 = new DefaultResources(); + defaultResources1.setApplicationId(savedPage.getApplicationId()); + actionCollection.setDefaultResources(defaultResources1); + actionCollectionService.generateAndSetPolicies(savedPage, actionCollection); - // Replace all action Ids from map + // Replace all action Ids from map and replace with newly created actionIds final Map<String, String> newActionIds = new HashMap<>(); unpublishedCollection .getDefaultToBranchedActionIdsMap() - .forEach((defaultActionId, oldActionId) -> newActionIds - .put(defaultActionId, actionIdsMap.get(oldActionId))); + .forEach((defaultActionId, oldActionId) -> { + if (!StringUtils.isEmpty(actionIdsMap.get(oldActionId))) { + newActionIds + // As this is a new application and not connected + // through git branch, the default and newly + // created actionId will be same + .put(actionIdsMap.get(oldActionId), actionIdsMap.get(oldActionId)); + } else { + log.debug("Unable to find action {} while forking inside ID map: {}", oldActionId, actionIdsMap); + } + }); unpublishedCollection.setDefaultToBranchedActionIdsMap(newActionIds); return actionCollectionService.create(actionCollection) + .flatMap(newActionCollection -> { + if (StringUtils.isEmpty(newActionCollection.getDefaultResources().getCollectionId())) { + ActionCollection updates = new ActionCollection(); + DefaultResources defaultResources2 = newActionCollection.getDefaultResources(); + defaultResources2.setCollectionId(newActionCollection.getId()); + updates.setDefaultResources(defaultResources2); + return actionCollectionService.update(newActionCollection.getId(), updates); + } + return Mono.just(newActionCollection); + }) .flatMap(newlyCreatedActionCollection -> { return Flux.fromIterable(newActionIds.values()) .flatMap(newActionService::findById) .flatMap(newlyCreatedAction -> { - newlyCreatedAction.getUnpublishedAction().setCollectionId(newlyCreatedActionCollection.getId()); + ActionDTO unpublishedAction = newlyCreatedAction.getUnpublishedAction(); + unpublishedAction.setCollectionId(newlyCreatedActionCollection.getId()); + unpublishedAction.getDefaultResources().setCollectionId(newlyCreatedActionCollection.getId()); return newActionService.update(newlyCreatedAction.getId(), newlyCreatedAction); }) .collectList(); 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 2e3c26a77c6d..a8e8a1dc26a7 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 @@ -1,11 +1,19 @@ package com.appsmith.server.solutions; +import com.appsmith.external.models.ActionConfiguration; import com.appsmith.external.models.Datasource; +import com.appsmith.external.models.DatasourceConfiguration; +import com.appsmith.external.models.JSValue; import com.appsmith.external.services.EncryptionService; import com.appsmith.server.acl.AppsmithRole; import com.appsmith.server.constants.FieldName; +import com.appsmith.server.domains.ActionCollection; import com.appsmith.server.domains.Application; +import com.appsmith.server.domains.NewAction; import com.appsmith.server.domains.Organization; +import com.appsmith.server.domains.Plugin; +import com.appsmith.server.domains.PluginType; +import com.appsmith.server.dtos.ActionCollectionDTO; import com.appsmith.server.dtos.ActionDTO; import com.appsmith.server.dtos.InviteUsersDTO; import com.appsmith.server.exceptions.AppsmithError; @@ -18,12 +26,14 @@ import com.appsmith.server.services.ApplicationService; import com.appsmith.server.services.DatasourceService; import com.appsmith.server.services.LayoutActionService; +import com.appsmith.server.services.LayoutCollectionService; import com.appsmith.server.services.NewActionService; import com.appsmith.server.services.NewPageService; import com.appsmith.server.services.OrganizationService; import com.appsmith.server.services.SessionUserService; import com.appsmith.server.services.UserService; import lombok.extern.slf4j.Slf4j; +import org.apache.commons.lang.StringUtils; import org.junit.Before; import org.junit.FixMethodOrder; import org.junit.Test; @@ -34,6 +44,7 @@ import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.data.mongodb.core.MongoTemplate; +import org.springframework.http.HttpMethod; import org.springframework.security.test.context.support.WithUserDetails; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.junit4.SpringRunner; @@ -47,6 +58,7 @@ import java.util.List; import java.util.Map; +import static com.appsmith.server.acl.AclPermission.READ_ACTIONS; import static com.appsmith.server.acl.AclPermission.READ_APPLICATIONS; import static com.appsmith.server.acl.AclPermission.READ_DATASOURCES; import static com.appsmith.server.acl.AclPermission.READ_PAGES; @@ -111,6 +123,9 @@ public class ApplicationForkingServiceTests { @Autowired private UserService userService; + @Autowired + private LayoutCollectionService layoutCollectionService; + private static String sourceAppId; private static String testUserOrgId; @@ -119,13 +134,13 @@ public class ApplicationForkingServiceTests { @Before public void setup() { + Mockito.when(pluginExecutorHelper.getPluginExecutor(Mockito.any())).thenReturn(Mono.just(new MockPluginExecutor())); // Run setup only once if (isSetupDone) { return; } - Mockito.when(pluginExecutorHelper.getPluginExecutor(Mockito.any())).thenReturn(Mono.just(new MockPluginExecutor())); Organization sourceOrganization = new Organization(); sourceOrganization.setName("Source Organization"); @@ -135,9 +150,46 @@ public void setup() { app1.setName("1 - public app"); app1.setOrganizationId(sourceOrganization.getId()); app1.setForkingEnabled(true); - applicationPageService.createApplication(app1).block(); + app1 = applicationPageService.createApplication(app1).block(); sourceAppId = app1.getId(); + // Save action + Datasource datasource = new Datasource(); + datasource.setName("Default Database"); + datasource.setOrganizationId(app1.getOrganizationId()); + Plugin installed_plugin = pluginRepository.findByPackageName("installed-plugin").block(); + datasource.setPluginId(installed_plugin.getId()); + datasource.setDatasourceConfiguration(new DatasourceConfiguration()); + + ActionDTO action = new ActionDTO(); + action.setName("forkActionByTest"); + action.setPageId(app1.getPages().get(0).getId()); + action.setExecuteOnLoad(true); + ActionConfiguration actionConfiguration = new ActionConfiguration(); + actionConfiguration.setHttpMethod(HttpMethod.GET); + action.setActionConfiguration(actionConfiguration); + action.setDatasource(datasource); + + layoutActionService.createSingleAction(action).block(); + + // Save actionCollection + ActionCollectionDTO actionCollectionDTO = new ActionCollectionDTO(); + actionCollectionDTO.setName("deleteTestCollection1"); + actionCollectionDTO.setPageId(app1.getPages().get(0).getId()); + actionCollectionDTO.setApplicationId(sourceAppId); + actionCollectionDTO.setOrganizationId(sourceOrganization.getId()); + actionCollectionDTO.setPluginId(datasource.getPluginId()); + actionCollectionDTO.setVariables(List.of(new JSValue("test", "String", "test", true))); + actionCollectionDTO.setBody("collectionBody"); + ActionDTO action1 = new ActionDTO(); + action1.setName("deleteTestAction1"); + action1.setActionConfiguration(new ActionConfiguration()); + action1.getActionConfiguration().setBody("mockBody"); + actionCollectionDTO.setActions(List.of(action1)); + actionCollectionDTO.setPluginType(PluginType.JS); + + layoutCollectionService.createCollection(actionCollectionDTO).block(); + // Invite "[email protected]" with VIEW access, api_user will be the admin of sourceOrganization and we are // controlling this with @FixMethodOrder(MethodSorters.NAME_ASCENDING) to run the TCs in a sequence. // Running TC in a sequence is a bad practice for unit TCs but here we are testing the invite user and then fork @@ -192,10 +244,57 @@ public void test1_cloneOrganizationWithItsContents() { applicationForkingService.forkApplicationToOrganization(sourceAppId, targetOrganizationId) ); - StepVerifier.create(resultMono) - .assertNext(application -> { + StepVerifier.create(resultMono + .zipWhen(application -> Mono.zip( + newActionService.findAllByApplicationIdAndViewMode(application.getId(), false, READ_ACTIONS, null).collectList(), + actionCollectionService.findAllByApplicationIdAndViewMode(application.getId(), false, READ_ACTIONS, null).collectList() + ))) + .assertNext(tuple -> { + Application application = tuple.getT1(); + List<NewAction> actionList = tuple.getT2().getT1(); + List<ActionCollection> actionCollectionList = tuple.getT2().getT2(); + 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(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(); }
a6df101f45e817598210afc0c3e97ebca2d7e1f4
2023-03-27 15:06:03
Vijetha-Kaja
test: Cypress - Added AdminSettings Helper (#21741)
false
Cypress - Added AdminSettings Helper (#21741)
test
diff --git a/app/client/cypress/support/Objects/ObjectsCore.ts b/app/client/cypress/support/Objects/ObjectsCore.ts index a7d2a5851409..8b02253d2480 100644 --- a/app/client/cypress/support/Objects/ObjectsCore.ts +++ b/app/client/cypress/support/Objects/ObjectsCore.ts @@ -14,6 +14,7 @@ export const homePage = ObjectsRegistry.HomePage; export const theme = ObjectsRegistry.ThemeSettings; export const gitSync = ObjectsRegistry.GitSync; export const apiPage = ObjectsRegistry.ApiPage; +export const adminSettings = ObjectsRegistry.AdminSettings; export const dataSources = ObjectsRegistry.DataSources; export const inviteModal = ObjectsRegistry.InviteModal; export const table = ObjectsRegistry.Table; diff --git a/app/client/cypress/support/Objects/Registry.ts b/app/client/cypress/support/Objects/Registry.ts index b3416673d2b6..1293fec5d65d 100644 --- a/app/client/cypress/support/Objects/Registry.ts +++ b/app/client/cypress/support/Objects/Registry.ts @@ -3,6 +3,7 @@ import { JSEditor } from "../Pages/JSEditor"; import { EntityExplorer } from "../Pages/EntityExplorer"; import { CommonLocators } from "./CommonLocators"; import { ApiPage } from "../Pages/ApiPage"; +import { AdminSettings } from "../Pages/AdminSettings"; import { HomePage } from "../Pages/HomePage"; import { DataSources } from "../Pages/DataSources"; import { Table } from "../Pages/Table"; @@ -62,6 +63,14 @@ export class ObjectsRegistry { return ObjectsRegistry.apiPage__; } + private static adminSettings__: AdminSettings; + static get AdminSettings(): AdminSettings { + if (ObjectsRegistry.adminSettings__ === undefined) { + ObjectsRegistry.adminSettings__ = new AdminSettings(); + } + return ObjectsRegistry.adminSettings__; + } + private static homePage__: HomePage; static get HomePage(): HomePage { if (ObjectsRegistry.homePage__ === undefined) { diff --git a/app/client/cypress/support/Pages/AdminSettings.ts b/app/client/cypress/support/Pages/AdminSettings.ts new file mode 100644 index 000000000000..cbb74e2f628d --- /dev/null +++ b/app/client/cypress/support/Pages/AdminSettings.ts @@ -0,0 +1,21 @@ +import { ObjectsRegistry } from "../Objects/Registry"; + +export class AdminSettings { + public agHelper = ObjectsRegistry.AggregateHelper; + public locator = ObjectsRegistry.CommonLocators; + public homePage = ObjectsRegistry.HomePage; + + private _adminSettingsBtn = '[data-testid="t--admin-settings-menu-option"]'; + private _settingsList = ".t--settings-category-list"; + public _usersTab = ".t--settings-category-users"; + public _roles = (user: string) => + "//span[contains(text(), '" + + user + + "')]/parent::div/parent::a/parent::td/following-sibling::td[1]"; + + public NavigateToAdminSettings() { + this.homePage.NavigateToHome(); + this.agHelper.GetNClick(this._adminSettingsBtn); + this.agHelper.AssertElementVisible(this._settingsList); + } +} diff --git a/app/client/cypress/support/Pages/HomePage.ts b/app/client/cypress/support/Pages/HomePage.ts index f0f03fff909b..848fe97c18e7 100644 --- a/app/client/cypress/support/Pages/HomePage.ts +++ b/app/client/cypress/support/Pages/HomePage.ts @@ -39,6 +39,7 @@ export class HomePage { _searchUsersInput = ".search-input"; private _manageUsers = ".manageUsers"; + public _closeBtn = ".bp3-dialog-close-button"; private _appHome = "//a[@href='/applications']"; _applicationCard = ".t--application-card"; private _homeIcon = ".t--appsmith-logo";
63412af71bce2934009708f5724a679c02b54bc7
2023-03-02 02:28:48
Vijetha-Kaja
test: Flaky test fix (#21019)
false
Flaky test fix (#21019)
test
diff --git a/app/client/cypress/fixtures/CMSdsl.json b/app/client/cypress/fixtures/CMSdsl.json index 996e0dc1f35e..a370880f2111 100644 --- a/app/client/cypress/fixtures/CMSdsl.json +++ b/app/client/cypress/fixtures/CMSdsl.json @@ -186,7 +186,7 @@ "textSize": "PARAGRAPH", "widgetId": "h4mh57zrj1", "isVisibleFilters": true, - "tableData": "{{get_data.data.headers.info}}", + "tableData": "{{get_data.data.headers.Info}}", "isVisible": true, "label": "Data", "searchKey": "", diff --git a/app/client/cypress/fixtures/datasources.json b/app/client/cypress/fixtures/datasources.json index d961795b2b39..c7064b4d41ea 100644 --- a/app/client/cypress/fixtures/datasources.json +++ b/app/client/cypress/fixtures/datasources.json @@ -49,7 +49,7 @@ "mockDatabasePassword": "LimitedAccess123#", "readonly":"readonly", "authenticatedApiUrl": "https://fakeapi.com", - "graphqlApiUrl": "https://spacex-production.up.railway.app", + "graphqlApiUrl": "http://host.docker.internal:5000/graphql", "GITEA_API_BASE_TED" : "localhost", "GITEA_API_PORT_TED": "3001", "GITEA_API_URL_TED": "[email protected]:Cypress" diff --git a/app/client/cypress/integration/Regression_TestSuite/Application/EchoApiCMS_spec.js b/app/client/cypress/integration/Regression_TestSuite/Application/EchoApiCMS_spec.js index 875843226838..195458bd03af 100644 --- a/app/client/cypress/integration/Regression_TestSuite/Application/EchoApiCMS_spec.js +++ b/app/client/cypress/integration/Regression_TestSuite/Application/EchoApiCMS_spec.js @@ -1,76 +1,67 @@ -const dsl = require("../../../fixtures/CMSdsl.json"); -const apiwidget = require("../../../locators/apiWidgetslocator.json"); -import apiEditor from "../../../locators/ApiEditor"; import appPage from "../../../locators/CMSApplocators"; +import * as _ from "../../../support/Objects/ObjectsCore"; describe("Content Management System App", function() { before(() => { - cy.addDsl(dsl); + _.homePage.NavigateToHome(); + _.agHelper.GenerateUUID(); + cy.get("@guid").then((uid) => { + _.homePage.CreateNewWorkspace("EchoApiCMS" + uid); + _.homePage.CreateAppInWorkspace("EchoApiCMS" + uid, "EchoApiCMSApp"); + cy.fixture("CMSdsl").then((val) => { + _.agHelper.AddDsl(val); + }); + }); }); + let repoName; it("1.Create Get echo Api call", function() { - cy.NavigateToAPI_Panel(); - cy.CreateAPI("get_data"); + _.apiPage.CreateAndFillApi( + "http://host.docker.internal:5001/v1/mock-api/echo", + "get_data", + ); // creating get request using echo - cy.enterDatasourceAndPath("https://mock-api.appsmith.com/echo", "/get"); - cy.get(apiwidget.headerKey).type("info"); - cy.xpath("//span[text()='Key']").click(); - // entering the data in header - cy.get( - apiwidget.headerValue, - ).type( + _.apiPage.EnterHeader( + "info", '[{"due":"2021-11-23","assignee":"[email protected]","title":"Recusan","description":"Ut quisquam eum beatae facere eos aliquam laborum ea.","id":"1"},{"due":"2021-11-23","assignee":"[email protected]","title":"Dignissimos eaque","description":"Consequatur corrupti et possimus en.","id":"2"},{"due":"2021-11-24","assignee":"[email protected]","title":"Voluptas explicabo","description":"Quia ratione optio et maiores.","id":"3"},{"due":"2021-11-23","assignee":"[email protected]","title":"Aut omnis.","description":"Neque rerum numquam veniam voluptatum id. Aut daut.","id":"4"}]', - { parseSpecialCharSequences: false }, ); - cy.SaveAndRunAPI(); - cy.ResponseStatusCheck("200"); + // entering the data in header + _.apiPage.RunAPI(); + _.apiPage.ResponseStatusCheck("200"); }); it("2. Create Post echo Api call", function() { - cy.NavigateToAPI_Panel(); - cy.CreateAPI("send_mail"); - cy.get(apiEditor.ApiVerb).click(); - cy.xpath(appPage.selectPost).click(); + _.apiPage.CreateAndFillApi( + "http://host.docker.internal:5001/v1/mock-api/echo", + "send_mail", + 10000, + "POST", + ); + _.apiPage.SelectPaneTab("Body"); + _.apiPage.SelectSubTab("JSON"); // creating post request using echo - cy.enterDatasourceAndPath("https://mock-api.appsmith.com/echo", "/post"); - cy.contains(apiEditor.bodyTab).click({ force: true }); - cy.get(apiEditor.jsonBodyTab).click({ force: true }); - cy.xpath(apiwidget.postbody) - .click({ force: true }) - .clear(); - // binding the data with widgets in body tab - cy.xpath(apiwidget.postbody) - .click({ force: true }) - .focus() - .type( - '{"to":"{{to_input.text}}","subject":"{{subject.text}}","content":"{{content.text}}"}', - { parseSpecialCharSequences: false }, - ) - .type("{del}{del}{del}"); - cy.SaveAndRunAPI(); - cy.ResponseStatusCheck("201"); + _.dataSources.EnterQuery( + '{"to":"{{to_input.text}}","subject":"{{subject.text}}","content":"{{content.text}}"}', + ); + _.apiPage.RunAPI(); + _.apiPage.ResponseStatusCheck("200"); }); it("3. Create Delete echo Api call", function() { - cy.NavigateToAPI_Panel(); - cy.CreateAPI("delete_proposal"); - cy.get(apiEditor.ApiVerb).click(); - cy.xpath(appPage.selectDelete).click(); - // creating delete request using echo - cy.enterDatasourceAndPath("https://mock-api.appsmith.com/echo", "/delete"); - cy.contains(apiEditor.bodyTab).click({ force: true }); - cy.get(apiEditor.jsonBodyTab).click({ force: true }); - // binding the data with widgets in body tab - cy.xpath(apiwidget.postbody) - .click({ force: true }) - .focus() - .type( - '{"title":"{{title.text}}","due":"{{due.text}}","assignee":"{{assignee.text}}"}', - { parseSpecialCharSequences: false }, - ) - .type("{del}{del}{del}"); - cy.SaveAndRunAPI(); - //cy.ResponseStatusCheck("200"); + _.apiPage.CreateAndFillApi( + "http://host.docker.internal:5001/v1/mock-api/echo", + "delete_proposal", + 10000, + "DELETE", + ); + _.apiPage.SelectPaneTab("Body"); + _.apiPage.SelectSubTab("JSON"); + // creating post request using echo + _.dataSources.EnterQuery( + '{"title":"{{title.text}}","due":"{{due.text}}","assignee":"{{assignee.text}}"}', + ); + _.apiPage.RunAPI(); + _.apiPage.ResponseStatusCheck("200"); }); it("4. Send mail and verify post request body", function() { @@ -124,22 +115,27 @@ describe("Content Management System App", function() { cy.ResponseCheck("Recusan"); }); - /*it("6. Connect app to git, verify data binding in edit and deploy mode", ()=>{ + it("6. Connect app to git, verify data binding in edit and deploy mode", () => { cy.get(`.t--entity-name:contains("Page1")`) - .should("be.visible") - .click({ force: true }); - cy.generateUUID().then((uid) => { - repoName = uid; - - cy.createTestGithubRepo(repoName); - cy.connectToGitRepo(repoName); + .should("be.visible") + .click({ force: true }); + _.gitSync.CreateNConnectToGit(repoName); + cy.get("@gitRepoName").then((repName) => { + repoName = repName; }); - cy.latestDeployPreview() - cy.wait(2000) - cy.xpath("//span[text()='[email protected]']").should("be.visible").click({ force: true }); + cy.latestDeployPreview(); + cy.wait(2000); + cy.xpath("//span[text()='[email protected]']") + .should("be.visible") + .click({ force: true }); + cy.get(appPage.mailButton) + .closest("div") + .click(); + cy.xpath(appPage.sendMailText).should("be.visible"); cy.xpath(appPage.subjectField).type("Test"); - cy.xpath(appPage.contentField) + cy.get(appPage.contentField) .last() + .find("textarea") .type("Task completed", { force: true }); cy.get(appPage.confirmButton) .closest("div") @@ -147,7 +143,11 @@ describe("Content Management System App", function() { cy.get(appPage.closeButton) .closest("div") .click({ force: true }); - cy.get(commonlocators.backToEditor).click(); - cy.wait(1000); - }) */ + _.deployMode.NavigateBacktoEditor(); + }); + + after(() => { + //clean up + _.gitSync.DeleteTestGithubRepo(repoName); + }); }); diff --git a/app/client/cypress/integration/Regression_TestSuite/ClientSideTests/Autocomplete/Autocomplete_JS_spec.ts b/app/client/cypress/integration/Regression_TestSuite/ClientSideTests/Autocomplete/Autocomplete_JS_spec.ts index 44161e42770b..7ceaf2fb76c7 100644 --- a/app/client/cypress/integration/Regression_TestSuite/ClientSideTests/Autocomplete/Autocomplete_JS_spec.ts +++ b/app/client/cypress/integration/Regression_TestSuite/ClientSideTests/Autocomplete/Autocomplete_JS_spec.ts @@ -1,14 +1,7 @@ import { WIDGET } from "../../../../locators/WidgetLocators"; -import { ObjectsRegistry } from "../../../../support/Objects/Registry"; +import * as _ from "../../../../support/Objects/ObjectsCore"; -const { - AggregateHelper: agHelper, - ApiPage, - CommonLocators, - DataSources, - EntityExplorer, - JSEditor: jsEditor, -} = ObjectsRegistry; +let jsName: any; const jsObjectBody = `export default { myVar1: [], @@ -23,11 +16,11 @@ const jsObjectBody = `export default { describe("Autocomplete tests", () => { it("1. Bug #13613 Verify widgets autocomplete: ButtonGroup & Document viewer widget", () => { - EntityExplorer.DragDropWidgetNVerify(WIDGET.BUTTON_GROUP, 200, 200); - EntityExplorer.DragDropWidgetNVerify(WIDGET.DOCUMENT_VIEWER, 200, 500); + _.ee.DragDropWidgetNVerify(WIDGET.BUTTON_GROUP, 200, 200); + _.ee.DragDropWidgetNVerify(WIDGET.DOCUMENT_VIEWER, 200, 500); // create js object - jsEditor.CreateJSObject(jsObjectBody, { + _.jsEditor.CreateJSObject(jsObjectBody, { paste: true, completeReplace: true, toRun: false, @@ -36,31 +29,41 @@ describe("Autocomplete tests", () => { }); // focus on 5th line - agHelper.GetNClick(jsEditor._lineinJsEditor(5)); + _.agHelper.GetNClick(_.jsEditor._lineinJsEditor(5)); // 1. Button group widget autocomplete verification - agHelper.TypeText(CommonLocators._codeMirrorTextArea, "ButtonGroup1."); - agHelper.GetNAssertElementText(CommonLocators._hints, "isVisible"); - agHelper.Sleep(); - agHelper.GetNClickByContains(CommonLocators._hints, "isVisible"); + _.agHelper.TypeText(_.locators._codeMirrorTextArea, "ButtonGroup1."); + _.agHelper.GetNAssertElementText(_.locators._hints, "isVisible"); + _.agHelper.Sleep(); + _.agHelper.GetNClickByContains(_.locators._hints, "isVisible"); // 2. Document view widget autocomplete verification - agHelper.GetNClick(jsEditor._lineinJsEditor(5), 0, true); - agHelper.SelectNRemoveLineText(CommonLocators._codeMirrorTextArea); - - agHelper.TypeText(CommonLocators._codeMirrorTextArea, "DocumentViewer1."); - agHelper.GetNAssertElementText(CommonLocators._hints, "docUrl"); - agHelper.Sleep(); - agHelper.GetNClickByContains(CommonLocators._hints, "docUrl"); + _.agHelper.GetNClick(_.jsEditor._lineinJsEditor(5), 0, true); + _.agHelper.SelectNRemoveLineText(_.locators._codeMirrorTextArea); + + _.agHelper.TypeText(_.locators._codeMirrorTextArea, "DocumentViewer1."); + _.agHelper.GetNAssertElementText(_.locators._hints, "docUrl"); + _.agHelper.Sleep(); + _.agHelper.GetNClickByContains(_.locators._hints, "docUrl"); + cy.get("@jsObjName").then((jsObjName) => { + jsName = jsObjName; + _.ee.SelectEntityByName(jsName as string, "Queries/JS"); + _.ee.ActionContextMenuByEntityName( + jsName as string, + "Delete", + "Are you sure?", + true, + ); + }); }); it("2. Check for bindings not available in other page", () => { // dependent on above case: 1st page should have DocumentViewer widget - EntityExplorer.AddNewPage(); + _.ee.AddNewPage(); // create js object - jsEditor.CreateJSObject(jsObjectBody, { + _.jsEditor.CreateJSObject(jsObjectBody, { paste: true, completeReplace: true, toRun: false, @@ -69,24 +72,40 @@ describe("Autocomplete tests", () => { }); // focus on 5th line - agHelper.GetNClick(jsEditor._lineinJsEditor(5)); - agHelper.TypeText(CommonLocators._codeMirrorTextArea, "D"); - agHelper.GetNAssertElementText( - CommonLocators._hints, + _.agHelper.GetNClick(_.jsEditor._lineinJsEditor(5)); + _.agHelper.TypeText(_.locators._codeMirrorTextArea, "D"); + _.agHelper.GetNAssertElementText( + _.locators._hints, "docUrl", "not.have.text", ); - agHelper.TypeText( - CommonLocators._codeMirrorTextArea, + _.agHelper.TypeText( + _.locators._codeMirrorTextArea, "ocumentViewer.docUrl", ); + cy.get("@jsObjName").then((jsObjName) => { + jsName = jsObjName; + _.ee.SelectEntityByName(jsName as string, "Queries/JS"); + _.ee.ActionContextMenuByEntityName( + jsName as string, + "Delete", + "Are you sure?", + true, + ); + }); }); it("3. Bug #15568 Verify browser JavaScript APIs in autocomplete ", () => { - // Using same js object - agHelper.SelectNRemoveLineText(CommonLocators._codeMirrorTextArea); + _.jsEditor.CreateJSObject(jsObjectBody, { + paste: true, + completeReplace: true, + toRun: false, + shouldCreateNewJSObj: true, + prettify: false, + }); + // focus on 5th line - agHelper.GetNClick(jsEditor._lineinJsEditor(5)); + _.agHelper.GetNClick(_.jsEditor._lineinJsEditor(5)); const JSAPIsToTest = [ // console API verification @@ -125,91 +144,109 @@ describe("Autocomplete tests", () => { ]; JSAPIsToTest.forEach((test, index) => { - agHelper.TypeText(CommonLocators._codeMirrorTextArea, test.type); - agHelper.GetNAssertElementText( - CommonLocators._hints, + _.agHelper.TypeText(_.locators._codeMirrorTextArea, test.type); + _.agHelper.GetNAssertElementText( + _.locators._hints, test.expected, test.haveOrNotHave ? "have.text" : "not.have.text", ); - agHelper.SelectNRemoveLineText(CommonLocators._codeMirrorTextArea); + _.agHelper.SelectNRemoveLineText(_.locators._codeMirrorTextArea); }); }); it("4. JSObject this. autocomplete", () => { // Using same js object // focus on 5th line - agHelper.GetNClick(jsEditor._lineinJsEditor(5)); - agHelper.TypeText(CommonLocators._codeMirrorTextArea, "this."); + _.agHelper.GetNClick(_.jsEditor._lineinJsEditor(5)); + _.agHelper.TypeText(_.locators._codeMirrorTextArea, "this."); ["myFun2()", "myVar1", "myVar2"].forEach((element, index) => { - agHelper.AssertContains(element); + _.agHelper.AssertContains(element); }); }); it("5. Api data with array of object autocompletion test", () => { - ApiPage.CreateAndFillApi(agHelper.mockApiUrl); - agHelper.Sleep(2000); - ApiPage.RunAPI(); + _.apiPage.CreateAndFillApi(_.agHelper.mockApiUrl); + _.agHelper.Sleep(2000); + _.apiPage.RunAPI(); // Using same js object - EntityExplorer.SelectEntityByName("JSObject1", "Queries/JS"); - agHelper.GetNClick(jsEditor._lineinJsEditor(5), 0, true); - agHelper.SelectNRemoveLineText(CommonLocators._codeMirrorTextArea); - //agHelper.GetNClick(jsEditor._lineinJsEditor(5)); - agHelper.TypeText(CommonLocators._codeMirrorTextArea, "Api1.d"); - agHelper.GetNAssertElementText(CommonLocators._hints, "data"); - agHelper.Sleep(); - agHelper.TypeText(CommonLocators._codeMirrorTextArea, "ata[0].e"); - agHelper.GetNAssertElementText(CommonLocators._hints, "email"); - agHelper.Sleep(); - agHelper.TypeText(CommonLocators._codeMirrorTextArea, "mail"); + _.ee.SelectEntityByName("JSObject1", "Queries/JS"); + _.agHelper.GetNClick(_.jsEditor._lineinJsEditor(5), 0, true); + _.agHelper.SelectNRemoveLineText(_.locators._codeMirrorTextArea); + //_.agHelper.GetNClick(_.jsEditor._lineinJsEditor(5)); + _.agHelper.TypeText(_.locators._codeMirrorTextArea, "Api1.d"); + _.agHelper.GetNAssertElementText(_.locators._hints, "data"); + _.agHelper.Sleep(); + _.agHelper.TypeText(_.locators._codeMirrorTextArea, "ata[0].e"); + _.agHelper.GetNAssertElementText(_.locators._hints, "email"); + _.agHelper.Sleep(); + _.agHelper.TypeText(_.locators._codeMirrorTextArea, "mail"); + _.ee.SelectEntityByName(jsName as string, "Queries/JS"); + _.ee.ActionContextMenuByEntityName( + "JSObject1", + "Delete", + "Are you sure?", + true, + ) }); it("6. Local variables & complex data autocompletion test", () => { - // Using same js object - agHelper.SelectNRemoveLineText(CommonLocators._codeMirrorTextArea); + + _.jsEditor.CreateJSObject(jsObjectBody, { + paste: true, + completeReplace: true, + toRun: false, + shouldCreateNewJSObj: true, + prettify: false, + }); const users = [ { label: "a", value: "b" }, { label: "a", value: "b" }, ]; - const codeToType = `const users = ${JSON.stringify(users)}; + let codeToType = `const users = ${JSON.stringify(users)}; const data = { userCollection: [{ users }, { users }] }; users.map(callBack);`; // component re-render cause DOM element of cy.get to lost // added wait to finish re-render before cy.get - agHelper.Sleep(); - agHelper.GetNClick(jsEditor._lineinJsEditor(5)); - agHelper.TypeText(CommonLocators._codeMirrorTextArea, codeToType); - agHelper.GetNClick(jsEditor._lineinJsEditor(7)); - agHelper.TypeText( - CommonLocators._codeMirrorTextArea, + //_.agHelper.Sleep(); + _.agHelper.GetNClick(_.jsEditor._lineinJsEditor(5)); + _.agHelper.TypeText(_.locators._codeMirrorTextArea, codeToType); + _.agHelper.GetNClick(_.jsEditor._lineinJsEditor(7)); + _.agHelper.TypeText( + _.locators._codeMirrorTextArea, "const callBack = (user) => user.l", ); - agHelper.GetNAssertElementText(CommonLocators._hints, "label"); - agHelper.TypeText(CommonLocators._codeMirrorTextArea, "abel;"); - agHelper.TypeText(CommonLocators._codeMirrorTextArea, "data."); - agHelper.GetNAssertElementText(CommonLocators._hints, "userCollection"); - agHelper.Sleep(); - agHelper.TypeText(CommonLocators._codeMirrorTextArea, "userCollection[0]."); - agHelper.GetNAssertElementText(CommonLocators._hints, "users"); - agHelper.Sleep(); - agHelper.TypeText(CommonLocators._codeMirrorTextArea, "users[0]."); - agHelper.GetNAssertElementText(CommonLocators._hints, "label"); - agHelper.GetNAssertElementText( - CommonLocators._hints, + _.agHelper.GetNAssertElementText(_.locators._hints, "label"); + _.agHelper.TypeText(_.locators._codeMirrorTextArea, "abel;"); + _.agHelper.TypeText(_.locators._codeMirrorTextArea, "data."); + _.agHelper.GetNAssertElementText(_.locators._hints, "userCollection"); + _.agHelper.Sleep(); + _.agHelper.TypeText(_.locators._codeMirrorTextArea, "userCollection[0]."); + _.agHelper.GetNAssertElementText(_.locators._hints, "users"); + _.agHelper.Sleep(); + _.agHelper.TypeText(_.locators._codeMirrorTextArea, "users[0]."); + _.agHelper.GetNAssertElementText(_.locators._hints, "label"); + _.agHelper.GetNAssertElementText( + _.locators._hints, "value", "have.text", 1, ); - EntityExplorer.ActionContextMenuByEntityName( - "JSObject1", - "Delete", - "Are you sure?", - true, - ); - EntityExplorer.ActionContextMenuByEntityName( + + cy.get("@jsObjName").then((jsObjName) => { + jsName = jsObjName; + _.ee.SelectEntityByName(jsName as string, "Queries/JS"); + _.ee.ActionContextMenuByEntityName( + jsName as string, + "Delete", + "Are you sure?", + true, + ); + }); + _.ee.ActionContextMenuByEntityName( "Api1", "Delete", "Are you sure?", @@ -217,18 +254,18 @@ describe("Autocomplete tests", () => { }); it("7. Autocompletion for bindings inside array and objects", () => { - DataSources.CreateDataSource("Mongo", true, false); + _.dataSources.CreateDataSource("Mongo", true, false); cy.get("@dsName").then(($dsName) => { - DataSources.CreateNewQueryInDS(($dsName as unknown) as string); - DataSources.ValidateNSelectDropdown( + _.dataSources.CreateNewQueryInDS(($dsName as unknown) as string); + _.dataSources.ValidateNSelectDropdown( "Commands", "Find Document(s)", "Insert Document(s)", ); - cy.xpath(CommonLocators._inputFieldByName("Documents")).then( + cy.xpath(_.locators._inputFieldByName("Documents")).then( ($field: any) => { - agHelper.UpdateCodeInput($field, `{\n"_id": "{{appsmith}}"\n}`); + _.agHelper.UpdateCodeInput($field, `{\n"_id": "{{appsmith}}"\n}`); cy.wrap($field) .find(".CodeMirror") @@ -239,7 +276,7 @@ describe("Autocomplete tests", () => { const input = ins[0].CodeMirror; input.focus(); cy.wait(200); - cy.get(CommonLocators._codeMirrorTextArea) + cy.get(_.locators._codeMirrorTextArea) .eq(1) .focus() .type( @@ -247,8 +284,8 @@ describe("Autocomplete tests", () => { ) .type("."); - agHelper.GetNAssertElementText( - CommonLocators._hints, + _.agHelper.GetNAssertElementText( + _.locators._hints, "geolocation", ); @@ -260,26 +297,26 @@ describe("Autocomplete tests", () => { }); it("8. Multiple binding in single line", () => { - DataSources.CreateDataSource("Postgres", true, false); + _.dataSources.CreateDataSource("Postgres", true, false); cy.get("@dsName").then(($dsName) => { - DataSources.CreateNewQueryInDS( + _.dataSources.CreateNewQueryInDS( ($dsName as unknown) as string, "SELECT * FROM worldCountryInfo where {{appsmith.store}} {{appsmith}}", ); - cy.get(CommonLocators._codeMirrorTextArea) + cy.get(_.locators._codeMirrorTextArea) .eq(0) .focus() .type("{downArrow}{leftArrow}{leftArrow}"); - agHelper.TypeText(CommonLocators._codeMirrorTextArea, "."); - agHelper.GetNAssertElementText(CommonLocators._hints, "geolocation"); + _.agHelper.TypeText(_.locators._codeMirrorTextArea, "."); + _.agHelper.GetNAssertElementText(_.locators._hints, "geolocation"); }); }); it("9. Bug #17059 Autocomplete does not suggest same function name that belongs to a different object", () => { - // create js object - jsEditor.CreateJSObject(jsObjectBody, { + // create js object - JSObject1 + _.jsEditor.CreateJSObject(jsObjectBody, { paste: true, completeReplace: true, toRun: false, @@ -287,8 +324,8 @@ describe("Autocomplete tests", () => { prettify: false, }); - // create js object - jsEditor.CreateJSObject(jsObjectBody, { + // create js object - JSObject2 + _.jsEditor.CreateJSObject(jsObjectBody, { paste: true, completeReplace: true, toRun: false, @@ -296,46 +333,60 @@ describe("Autocomplete tests", () => { prettify: false, }); - agHelper.GetNClick(jsEditor._lineinJsEditor(5)); - agHelper.TypeText(CommonLocators._codeMirrorTextArea, "JSObject1."); + _.agHelper.GetNClick(_.jsEditor._lineinJsEditor(5)); + _.agHelper.TypeText(_.locators._codeMirrorTextArea, "JSObject1."); - agHelper.GetNAssertElementText( - CommonLocators._hints, + _.agHelper.GetNAssertElementText( + _.locators._hints, "myFun1.data", "have.text", 0, ); - agHelper.GetNAssertElementText( - CommonLocators._hints, + _.agHelper.GetNAssertElementText( + _.locators._hints, "myFun1()", "have.text", 4, ); // Same check in JSObject1 - EntityExplorer.SelectEntityByName("JSObject1", "Queries/JS"); - agHelper.GetNClick(jsEditor._lineinJsEditor(5)); - agHelper.TypeText(CommonLocators._codeMirrorTextArea, "JSObject2."); - - agHelper.GetNAssertElementText( - CommonLocators._hints, + _.ee.SelectEntityByName("JSObject1", "Queries/JS"); + _.agHelper.Sleep(); + _.agHelper.GetNClick(_.jsEditor._lineinJsEditor(5)); + _.agHelper.TypeText(_.locators._codeMirrorTextArea, "JSObject2"); + _.agHelper.TypeText(_.locators._codeMirrorTextArea, "."); + + _.agHelper.GetNAssertElementText( + _.locators._hints, "myFun1.data", "have.text", 0, ); - agHelper.GetNAssertElementText( - CommonLocators._hints, + _.agHelper.GetNAssertElementText( + _.locators._hints, "myFun1()", "have.text", 4, ); + _.ee.ActionContextMenuByEntityName( + "JSObject1", + "Delete", + "Are you sure?", + true, + ); + _.ee.ActionContextMenuByEntityName( + "JSObject2", + "Delete", + "Are you sure?", + true, + ); }); it("10. Bug #10115 Autocomplete needs to show async await keywords instead of showing 'no suggestions'", () => { // create js object - jsEditor.CreateJSObject(jsObjectBody, { + _.jsEditor.CreateJSObject(jsObjectBody, { paste: true, completeReplace: true, toRun: false, @@ -343,22 +394,32 @@ describe("Autocomplete tests", () => { prettify: false, }); - agHelper.GetNClick(jsEditor._lineinJsEditor(5)); - agHelper.TypeText(CommonLocators._codeMirrorTextArea, "aw"); + _.agHelper.GetNClick(_.jsEditor._lineinJsEditor(5)); + _.agHelper.TypeText(_.locators._codeMirrorTextArea, "aw"); - agHelper.GetNAssertElementText( - CommonLocators._hints, + _.agHelper.GetNAssertElementText( + _.locators._hints, "await", "have.text", 0, ); - agHelper.RemoveCharsNType(CommonLocators._codeMirrorTextArea, 2, "as"); - agHelper.GetNAssertElementText( - CommonLocators._hints, + _.agHelper.RemoveCharsNType(_.locators._codeMirrorTextArea, 2, "as"); + _.agHelper.GetNAssertElementText( + _.locators._hints, "async", "have.text", 0, ); + cy.get("@jsObjName").then((jsObjName) => { + jsName = jsObjName; + _.ee.SelectEntityByName(jsName as string, "Queries/JS"); + _.ee.ActionContextMenuByEntityName( + jsName as string, + "Delete", + "Are you sure?", + true, + ); + }); }); }); diff --git a/app/client/cypress/integration/Regression_TestSuite/ClientSideTests/ExplorerTests/Entity_Explorer_API_Pane_spec.js b/app/client/cypress/integration/Regression_TestSuite/ClientSideTests/ExplorerTests/Entity_Explorer_API_Pane_spec.js index c5c129150231..cabc9032cd8c 100644 --- a/app/client/cypress/integration/Regression_TestSuite/ClientSideTests/ExplorerTests/Entity_Explorer_API_Pane_spec.js +++ b/app/client/cypress/integration/Regression_TestSuite/ClientSideTests/ExplorerTests/Entity_Explorer_API_Pane_spec.js @@ -60,6 +60,7 @@ describe("Entity explorer API pane related testcases", function() { .should("be.visible"); cy.Createpage(pageid); ee.SelectEntityByName("Page1"); + agHelper.Sleep(); //for the selected entity to settle loading! ee.ExpandCollapseEntity("Queries/JS"); ee.ActionContextMenuByEntityName("FirstAPI", "Edit Name"); cy.EditApiNameFromExplorer("SecondAPI"); diff --git a/app/client/cypress/integration/Regression_TestSuite/ClientSideTests/Git/GitImport/GitImport_spec.js b/app/client/cypress/integration/Regression_TestSuite/ClientSideTests/Git/GitImport/GitImport_spec.js index 8174c00c95a2..0da6dc50cd2e 100644 --- a/app/client/cypress/integration/Regression_TestSuite/ClientSideTests/Git/GitImport/GitImport_spec.js +++ b/app/client/cypress/integration/Regression_TestSuite/ClientSideTests/Git/GitImport/GitImport_spec.js @@ -1,9 +1,6 @@ import gitSyncLocators from "../../../../../locators/gitSyncLocators"; import homePage from "../../../../../locators/HomePage"; -const explorer = require("../../../../../locators/explorerlocators.json"); import reconnectDatasourceModal from "../../../../../locators/ReconnectLocators"; -const apiwidget = require("../../../../../locators/apiWidgetslocator.json"); -const pages = require("../../../../../locators/Pages.json"); const commonlocators = require("../../../../../locators/commonlocators.json"); const datasourceEditor = require("../../../../../locators/DatasourcesEditor.json"); const jsObject = "JSObject1"; @@ -171,29 +168,17 @@ describe("Git import flow ", function() { cy.xpath("//input[@value='this is a test']"); // verify js object binded to input widget cy.xpath("//input[@value='Success']"); - cy.CheckAndUnfoldEntityItem("Pages"); - // clone the page1 and validate data binding - cy.get(".t--entity-name:contains(Page1)") - .trigger("mouseover") - .click({ force: true }); - cy.xpath(apiwidget.popover) - .first() - .should("be.hidden") - .invoke("show") - .click({ force: true }); - cy.get(pages.clonePage).click({ force: true }); - cy.wait("@clonePage").should( - "have.nested.property", - "response.body.responseMeta.status", - 201, - ); + + _.ee.ClonePage(); + // verify jsObject is not duplicated + _.agHelper.Sleep(2000); //for cloning of table data to finish _.ee.SelectEntityByName(jsObject, "Queries/JS"); //Also checking jsobject exists after cloning the page - _.jsEditor.RunJSObj(); //Running sync function due to open bug #20814 _.ee.SelectEntityByName("Page1 Copy"); cy.xpath("//input[@class='bp3-input' and @value='Success']").should( "be.visible", ); + // deploy the app and validate data binding cy.wait(2000); cy.get(homePage.publishButton).click(); diff --git a/app/client/cypress/integration/Regression_TestSuite/ClientSideTests/Widgets/Chart/Chart_Widget_Loading_spec.js b/app/client/cypress/integration/Regression_TestSuite/ClientSideTests/Widgets/Chart/Chart_Widget_Loading_spec.js index 1b0eed9e0c42..a2c0f10845aa 100644 --- a/app/client/cypress/integration/Regression_TestSuite/ClientSideTests/Widgets/Chart/Chart_Widget_Loading_spec.js +++ b/app/client/cypress/integration/Regression_TestSuite/ClientSideTests/Widgets/Chart/Chart_Widget_Loading_spec.js @@ -7,7 +7,7 @@ describe("Chart Widget Skeleton Loading Functionality", function() { cy.addDsl(dsl); }); - it("Test case while reloading and on submission", function() { + it("1. Test case while reloading and on submission", function() { /** * Use case: * 1. Open Datasource editor @@ -34,10 +34,11 @@ describe("Chart Widget Skeleton Loading Functionality", function() { //Step3 & 4 cy.get(`${datasource.datasourceCard}`) - .contains("Users") - .get(`${datasource.createQuery}`) - .last() - .click({ force: true }); + .filter(":contains('Users')") + .last() + .within(() => { + cy.get(`${datasource.createQuery}`).click({ force: true }); + }); //Step5.1: Click the editing field cy.get(".t--action-name-edit-field").click({ force: true }); diff --git a/app/client/cypress/integration/Regression_TestSuite/ClientSideTests/Widgets/ListV2/Listv2_BasicChildWidgetInteraction_spec.js b/app/client/cypress/integration/Regression_TestSuite/ClientSideTests/Widgets/ListV2/Listv2_BasicChildWidgetInteraction_spec.js index a0293c833931..b9b9fedaddd0 100644 --- a/app/client/cypress/integration/Regression_TestSuite/ClientSideTests/Widgets/ListV2/Listv2_BasicChildWidgetInteraction_spec.js +++ b/app/client/cypress/integration/Regression_TestSuite/ClientSideTests/Widgets/ListV2/Listv2_BasicChildWidgetInteraction_spec.js @@ -60,7 +60,7 @@ describe("List widget v2 - Basic Child Widget Interaction", () => { agHelper.SaveLocalStorageCache(); }); - it("1. Child widgets", () => { + it("1. Child widgets", () => { // Drop Input widget dragAndDropToWidget("inputwidgetv2", "containerwidget", { x: 250, @@ -162,13 +162,13 @@ describe("List widget v2 - Basic Child Widget Interaction", () => { // Verify checked cy.get(publishLocators.switchwidget) .find("input") - .should("be.checked"); - + .should("be.checked"); // Uncheck cy.get(publishLocators.switchwidget) .find("label") .first() - .click({ force: true }); + .click() + .wait(500); // Verify unchecked cy.get(publishLocators.switchwidget) diff --git a/app/client/cypress/integration/Regression_TestSuite/ClientSideTests/Widgets/Modal/Modal_focus_spec.js b/app/client/cypress/integration/Regression_TestSuite/ClientSideTests/Widgets/Modal/Modal_focus_spec.js index 2d624c65efc3..76ef79ecf209 100644 --- a/app/client/cypress/integration/Regression_TestSuite/ClientSideTests/Widgets/Modal/Modal_focus_spec.js +++ b/app/client/cypress/integration/Regression_TestSuite/ClientSideTests/Widgets/Modal/Modal_focus_spec.js @@ -46,7 +46,7 @@ describe("Modal focus", function() { cy.addDsl(dsl); }); - it("should focus on the input field when autofocus for the input field is enabled", () => { + it("1. Should focus on the input field when autofocus for the input field is enabled", () => { setupModalWithInputWidget(); cy.openPropertyPane("inputwidgetv2"); @@ -69,7 +69,7 @@ describe("Modal focus", function() { //check if the focus is on the input field cy.focused().should("have.value", someInputText); }); - it("should not focus on the input field if autofocus is disabled", () => { + it("2. Should not focus on the input field if autofocus is disabled", () => { cy.openPropertyPane("inputwidgetv2"); // autofocus for input field is disabled @@ -80,7 +80,7 @@ describe("Modal focus", function() { cy.get(widgets.modalCloseButton).click({ force: true }); //open the modal - + cy.get(widgets.modalWidget).should("not.exist"); cy.get(widgets.widgetBtn) .contains("Submit") .click({ force: true }); diff --git a/app/client/cypress/integration/Regression_TestSuite/ClientSideTests/Workspace/DeleteWorkspace_spec.js b/app/client/cypress/integration/Regression_TestSuite/ClientSideTests/Workspace/DeleteWorkspace_spec.js index 18a3e136f59b..281289e09f3b 100644 --- a/app/client/cypress/integration/Regression_TestSuite/ClientSideTests/Workspace/DeleteWorkspace_spec.js +++ b/app/client/cypress/integration/Regression_TestSuite/ClientSideTests/Workspace/DeleteWorkspace_spec.js @@ -1,49 +1,49 @@ /// <reference types="Cypress" /> -import { ObjectsRegistry } from "../../../../support/Objects/Registry"; import homePage from "../../../../locators/HomePage"; -let HomePage = ObjectsRegistry.HomePage; +import * as _ from "../../../../support/Objects/ObjectsCore"; describe("Delete workspace test spec", function() { - let newWorkspaceName; + let newWorkspaceName it("1. Should delete the workspace", function() { cy.visit("/applications"); - cy.createWorkspace(); - cy.wait("@createWorkspace").then((interception) => { - newWorkspaceName = interception.response.body.data.name; - cy.visit("/applications"); - cy.openWorkspaceOptionsPopup(newWorkspaceName); - cy.contains("Delete Workspace").click(); - cy.contains("Are you sure").click(); - cy.wait("@deleteWorkspaceApiCall").then((httpResponse) => { - expect(httpResponse.status).to.equal(200); - }); - cy.get(newWorkspaceName).should("not.exist"); + cy.generateUUID().then((uid) => { + newWorkspaceName = uid; + _.homePage.CreateNewWorkspace(newWorkspaceName); + cy.wait(500); + cy.contains("Delete Workspace").click(); + cy.contains("Are you sure").click(); + cy.wait("@deleteWorkspaceApiCall").then((httpResponse) => { + expect(httpResponse.status).to.equal(200); + }); + cy.get(newWorkspaceName).should("not.exist"); }); }); it("2. Should show option to delete workspace for an admin user", function() { cy.visit("/applications"); cy.wait(2000); - cy.createWorkspace(); - cy.wait("@createWorkspace").then((interception) => { - newWorkspaceName = interception.response.body.data.name; - cy.visit("/applications"); - cy.openWorkspaceOptionsPopup(newWorkspaceName); - cy.contains("Delete Workspace"); - HomePage.InviteUserToWorkspace( - newWorkspaceName, - Cypress.env("TESTUSERNAME1"), - "App Viewer", - ); - cy.LogOut(); - cy.LogintoApp(Cypress.env("TESTUSERNAME1"), Cypress.env("TESTPASSWORD1")); - cy.visit("/applications"); - cy.openWorkspaceOptionsPopup(newWorkspaceName); - cy.get(homePage.workspaceNamePopoverContent) - .contains("Delete Workspace") - .should("not.exist"); - cy.LogOut(); + cy.generateUUID().then((uid) => { + newWorkspaceName = uid; + _.homePage.CreateNewWorkspace(newWorkspaceName); + cy.wait(500); + cy.contains("Delete Workspace"); + _.homePage.InviteUserToWorkspace( + newWorkspaceName, + Cypress.env("TESTUSERNAME1"), + "App Viewer", + ); + cy.LogOut(); + cy.LogintoApp( + Cypress.env("TESTUSERNAME1"), + Cypress.env("TESTPASSWORD1"), + ); + cy.visit("/applications"); + cy.openWorkspaceOptionsPopup(newWorkspaceName); + cy.get(homePage.workspaceNamePopoverContent) + .contains("Delete Workspace") + .should("not.exist"); + cy.LogOut(); }); }); }); diff --git a/app/client/cypress/integration/Regression_TestSuite/ServerSideTests/Datasources/GraphQL_spec.ts b/app/client/cypress/integration/Regression_TestSuite/ServerSideTests/Datasources/GraphQL_spec.ts index 9b579421da84..aa4eb8bcfa9d 100644 --- a/app/client/cypress/integration/Regression_TestSuite/ServerSideTests/Datasources/GraphQL_spec.ts +++ b/app/client/cypress/integration/Regression_TestSuite/ServerSideTests/Datasources/GraphQL_spec.ts @@ -13,7 +13,7 @@ const GRAPHQL_QUERY = ` landings `; -const CAPSULE_ID = "5e9e2c5bf35918ed873b2664" +const CAPSULE_ID = "5e9e2c5bf35918ed873b2664"; const GRAPHQL_VARIABLES = ` { @@ -21,19 +21,19 @@ const GRAPHQL_VARIABLES = ` `; const GRAPHQL_LIMIT_QUERY = ` - query ($limit: Int, $offset: Int) { - launchesPast(limit: $limit, offset: $offset) { - mission_name - rocket { - rocket_name + query($offsetz:Int, $firstz:Int){ + allPosts(offset:$offsetz, first:$firstz) { + edges { + node { + id, + title, + content `; const GRAPHQL_LIMIT_DATA = [ + { title_name: "The truth about All" }, { - mission_name: "FalconSat", - }, - { - mission_name: "DemoSat", + title_name: "Right beautiful use.", }, ]; @@ -47,20 +47,17 @@ describe("GraphQL Datasource Implementation", function() { }); }); - it("1. Should create the Graphql datasource with Credentials", function() { + it("1. Should create the Graphql datasource & delete, Create new GraphQL DS & Rename", function() { // Navigate to Datasource Editor _.dataSources.CreateGraphqlDatasource(datasourceName); _.dataSources.DeleteDatasouceFromActiveTab(datasourceName); - }); - - it("2. Should create an GraphQL API with updated name", function() { _.dataSources.CreateGraphqlDatasource(datasourceName); _.dataSources.NavigateFromActiveDS(datasourceName, true); _.agHelper.ValidateNetworkStatus("@createNewApi", 201); _.agHelper.RenameWithInPane(apiName, true); }); - it("3. Should execute the API and validate the response", function() { + it.skip("2. Should execute the API and validate the response", function() { /* Create an API */ _.dataSources.NavigateFromActiveDS(datasourceName, true); @@ -76,7 +73,7 @@ describe("GraphQL Datasource Implementation", function() { }); }); - it("4. Pagination for limit based should work without offset", function() { + it("3. Pagination for limit based should work without offset", function() { /* Create an API */ _.dataSources.NavigateFromActiveDS(datasourceName, true); _.apiPage.SelectPaneTab("Body"); @@ -92,18 +89,19 @@ describe("GraphQL Datasource Implementation", function() { _.dataSources.UpdateGraphqlPaginationParams({ limit: { - variable: "limit", + variable: "firstz", value: "2", }, }); _.apiPage.RunAPI(false, 20, { - expectedPath: "response.body.data.body.data.launchesPast[0].mission_name", - expectedRes: GRAPHQL_LIMIT_DATA[0].mission_name, + expectedPath: + "response.body.data.body.data.allPosts.edges[0].node.title", + expectedRes: GRAPHQL_LIMIT_DATA[0].title_name, }); }); - it("5. Pagination for limit based should work with offset", function() { + it("4. Pagination for limit based should work with offset", function() { /* Create an API */ _.dataSources.NavigateFromActiveDS(datasourceName, true); _.apiPage.SelectPaneTab("Body"); @@ -119,18 +117,18 @@ describe("GraphQL Datasource Implementation", function() { _.dataSources.UpdateGraphqlPaginationParams({ limit: { - variable: "limit", + variable: "firstz", value: "5", }, offset: { - variable: "offset", - value: "1", + variable: "offsetz", + value: "10", }, }); _.apiPage.RunAPI(false, 20, { - expectedPath: "response.body.data.body.data.launchesPast[0].mission_name", - expectedRes: GRAPHQL_LIMIT_DATA[1].mission_name, + expectedPath: "response.body.data.body.data.allPosts.edges[0].node.title", + expectedRes: GRAPHQL_LIMIT_DATA[1].title_name, }); }); }); diff --git a/app/client/cypress/locators/CMSApplocators.js b/app/client/cypress/locators/CMSApplocators.js index f2ba3e0a1a2a..8fbbe4cd3250 100644 --- a/app/client/cypress/locators/CMSApplocators.js +++ b/app/client/cypress/locators/CMSApplocators.js @@ -8,7 +8,7 @@ export default { sendMailText: "//span[text()='Send Mail']", inputMail: "//input[@value='[email protected]']", subjectField: "(//div[@class='bp3-input-group']//input)[6]", - contentField: ".t--draggable-inputwidgetv2", + contentField: ".t--widget-inputwidgetv2", confirmButton: "span:contains('Confirm')", closeButton: "span:contains('Close')", datasourcesbutton: "//div[text()='Datasources']", diff --git a/app/client/cypress/support/Pages/AggregateHelper.ts b/app/client/cypress/support/Pages/AggregateHelper.ts index 21ea8dd2adfa..3b360fda9f5b 100644 --- a/app/client/cypress/support/Pages/AggregateHelper.ts +++ b/app/client/cypress/support/Pages/AggregateHelper.ts @@ -547,6 +547,13 @@ export class AggregateHelper { return locator.type(this.removeLine); } + public SelectAllRemoveCodeText(selector: string) { + const locator = selector.startsWith("//") + ? cy.xpath(selector) + : cy.get(selector); + return locator.type(this.selectAll+"{del}"); + } + public RemoveCharsNType(selector: string, charCount = 0, totype: string) { if (charCount > 0) this.GetElement(selector) diff --git a/app/client/cypress/support/Pages/ApiPage.ts b/app/client/cypress/support/Pages/ApiPage.ts index ed6debf10da8..845735099aa2 100644 --- a/app/client/cypress/support/Pages/ApiPage.ts +++ b/app/client/cypress/support/Pages/ApiPage.ts @@ -370,7 +370,7 @@ export class ApiPage { ResponseStatusCheck(statusCode: string) { this.agHelper.AssertElementVisible(this._responseStatus); - cy.get(this._responseStatus).contains(statusCode); + this.agHelper.GetNAssertContains(this._responseStatus, statusCode) } public SelectPaginationTypeViaIndex(index: number) { cy.get(this._paginationTypeLabels)