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
|
|---|---|---|---|---|---|---|---|
4b75f77caa045f98edbc1625bd2d5b7f1384c388
|
2021-12-23 19:46:49
|
Sumit Kumar
|
feat: add support for projection, sort and pagination. (#9712)
| false
|
add support for projection, sort and pagination. (#9712)
|
feat
|
diff --git a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/constants/SortType.java b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/constants/SortType.java
new file mode 100644
index 000000000000..02222825811d
--- /dev/null
+++ b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/constants/SortType.java
@@ -0,0 +1,20 @@
+package com.appsmith.external.constants;
+
+/**
+ * This enum is used to encapsulate the Sort type used in UQI Sort feature. For more info please check out
+ * `FilterDataServiceCE.java`
+ */
+public enum SortType {
+ ASCENDING{
+ @Override
+ public String toString() {
+ return "ASC";
+ }
+ },
+ DESCENDING {
+ @Override
+ public String toString() {
+ return "DESC";
+ }
+ }
+}
diff --git a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/UQIDataFilterParams.java b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/UQIDataFilterParams.java
new file mode 100644
index 000000000000..36313f2a62d2
--- /dev/null
+++ b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/UQIDataFilterParams.java
@@ -0,0 +1,29 @@
+package com.appsmith.external.models;
+
+import lombok.AllArgsConstructor;
+import lombok.Getter;
+import lombok.Setter;
+import lombok.ToString;
+
+import java.util.List;
+import java.util.Map;
+
+
+/**
+ * This class is supposed to enclose all the parameters that are required to filter data as per the UQI
+ * specifications. Currently, UQI specifies filtering data on the following parameters:
+ * o where clause
+ * o projection
+ * o pagination
+ * o sorting
+ */
+@Getter
+@Setter
+@ToString
+@AllArgsConstructor
+public class UQIDataFilterParams {
+ Condition condition; // where condition.
+ List<String> projectionColumns; // columns to show to user.
+ List<Map<String, Object>> sortBy; // columns to sort by in ascending or descending order.
+ Map<String, String> paginateBy; // limit and offset
+}
diff --git a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/services/ce/FilterDataServiceCE.java b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/services/ce/FilterDataServiceCE.java
index a40046b7e1af..e569711860ed 100644
--- a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/services/ce/FilterDataServiceCE.java
+++ b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/services/ce/FilterDataServiceCE.java
@@ -2,15 +2,18 @@
import com.appsmith.external.constants.ConditionalOperator;
import com.appsmith.external.constants.DataType;
+import com.appsmith.external.constants.SortType;
import com.appsmith.external.exceptions.pluginExceptions.AppsmithPluginError;
import com.appsmith.external.exceptions.pluginExceptions.AppsmithPluginException;
import com.appsmith.external.models.Condition;
+import com.appsmith.external.models.UQIDataFilterParams;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.bson.types.ObjectId;
+import org.springframework.util.CollectionUtils;
import java.io.IOException;
import java.math.BigDecimal;
@@ -22,6 +25,7 @@
import java.sql.SQLException;
import java.sql.Types;
import java.util.ArrayList;
+import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
@@ -39,10 +43,17 @@
@Slf4j
public class FilterDataServiceCE implements IFilterDataServiceCE {
+ public static final String SORT_BY_COLUMN_NAME_KEY = "columnName";
+ public static final String SORT_BY_TYPE_KEY = "type";
+ public static final String DATA_INFO_VALUE_KEY = "value";
+ public static final String DATA_INFO_TYPE_KEY = "type";
+ public static final String PAGINATE_LIMIT_KEY = "limit";
+ public static final String PAGINATE_OFFSET_KEY = "offset";
+
private ObjectMapper objectMapper;
private Connection connection;
- private static final String URL = "jdbc:h2:mem:filterDb";
+ private static final String URL = "jdbc:h2:mem:filterDb;DATABASE_TO_UPPER=FALSE";
private static final Map<DataType, String> SQL_DATATYPE_MAP = Map.of(
DataType.INTEGER, "INT",
@@ -110,28 +121,28 @@ public ArrayNode filterData(ArrayNode items, List<Condition> conditionList) {
}
/**
- * This filter method is using the new UQI format of
- * @param items
- * @param condition
- * @return
+ * This filter method is using the new UQI format.
+ * @param items - data
+ * @param uqiDataFilterParams - filter conditions to apply on data
+ * @return filtered data
*/
- public ArrayNode filterDataNew(ArrayNode items, Condition condition) {
-
+ public ArrayNode filterDataNew(ArrayNode items, UQIDataFilterParams uqiDataFilterParams) {
if (items == null || items.size() == 0) {
return items;
}
- Map<String, DataType> schema = generateSchema(items);
-
+ Condition condition = uqiDataFilterParams.getCondition();
Condition updatedCondition = addValueDataType(condition);
+ uqiDataFilterParams.setCondition(updatedCondition);
+ Map<String, DataType> schema = generateSchema(items);
String tableName = generateTable(schema);
// insert the data
insertAllData(tableName, items, schema);
// Filter the data
- List<Map<String, Object>> finalResults = executeFilterQueryNew(tableName, updatedCondition, schema);
+ List<Map<String, Object>> finalResults = executeFilterQueryNew(tableName, schema, uqiDataFilterParams);
// Now that the data has been filtered. Clean Up. Drop the table
dropTable(tableName);
@@ -141,12 +152,31 @@ public ArrayNode filterDataNew(ArrayNode items, Condition condition) {
return finalResultsNode;
}
- private List<Map<String, Object>> executeFilterQueryNew(String tableName, Condition condition, Map<String, DataType> schema) {
+ private List<Map<String, Object>> executeFilterQueryNew(String tableName, Map<String, DataType> schema,
+ UQIDataFilterParams uqiDataFilterParams) {
+
+ Condition condition = uqiDataFilterParams.getCondition();
+ List<String> projectionColumns = uqiDataFilterParams.getProjectionColumns();
+ List<Map<String, Object>> sortBy = uqiDataFilterParams.getSortBy();
+ Map<String, String> paginateBy = uqiDataFilterParams.getPaginateBy();
+
Connection conn = checkAndGetConnection();
- StringBuilder sb = new StringBuilder("SELECT * FROM " + tableName);
+ StringBuilder sb = new StringBuilder();
- LinkedHashMap<String, DataType> values = new LinkedHashMap<>();
+ // Add projection columns condition otherwise use `select *`
+ addProjectionCondition(sb, projectionColumns, tableName);
+
+ /**
+ * Moving this from a LinkedHashMap to an ArrayList of objects because with LinkedHashMap we were using
+ * the data value as key. Hence, if two identical data values existed then they would overwrite each other. E.g.
+ * if there was where clause like `Name == John` Or `Name != John, (which is a perfectly valid query) then
+ * the prepared statement substitution would fail because instead of two values to substitute it would only
+ * fine one i.e. {"John" -> DataType.String} is the only entry it would find whereas two entries are
+ * actually required {"John" -> DataType.String, "John" -> DataType.String} - one for each condition in the
+ * where clause. JUnit TC `testProjectionSortingAndPaginationTogether` takes care of this case as well.
+ */
+ List<Map<String, Object>> values = new ArrayList<>();
if (condition != null) {
ConditionalOperator operator = condition.getOperator();
@@ -160,6 +190,12 @@ private List<Map<String, Object>> executeFilterQueryNew(String tableName, Condit
}
}
+ // Add `order by` condition
+ addSortCondition(sb, sortBy);
+
+ // Add `limit <num> offset <num>` condition
+ addPaginationCondition(sb, paginateBy, values);
+
sb.append(";");
List<Map<String, Object>> rowsList = new ArrayList<>(50);
@@ -169,12 +205,11 @@ private List<Map<String, Object>> executeFilterQueryNew(String tableName, Condit
try {
PreparedStatement preparedStatement = conn.prepareStatement(selectQuery);
- Set<Map.Entry<String, DataType>> valueEntries = values.entrySet();
- Iterator<Map.Entry<String, DataType>> iterator = valueEntries.iterator();
+ Iterator<Map<String, Object>> iterator = values.iterator();
for (int i = 0; iterator.hasNext(); i++) {
- Map.Entry<String, DataType> valueEntry = iterator.next();
- String value = valueEntry.getKey();
- DataType dataType = valueEntry.getValue();
+ Map<String, Object> dataInfo = iterator.next();
+ String value = (String) dataInfo.get("value");
+ DataType dataType = (DataType) dataInfo.get("type");
setValueInStatement(preparedStatement, i + 1, value, dataType);
}
@@ -205,6 +240,95 @@ private List<Map<String, Object>> executeFilterQueryNew(String tableName, Condit
return rowsList;
}
+ /**
+ * This method adds the following clause to the SQL query: `LIMIT <num> OFFSET <num>`
+ *
+ * @param sb - SQL query builder
+ * @param paginateBy - values for limit and offset
+ * @param values - list to hold values to be substituted in prepared statement
+ */
+ private void addPaginationCondition(StringBuilder sb, Map<String, String> paginateBy,
+ List<Map<String, Object>> values) {
+ if (CollectionUtils.isEmpty(paginateBy)) {
+ return;
+ }
+
+ sb.append(" LIMIT ? OFFSET ?");
+
+ // Set limit value and data type for prepared statement substitution
+ String limit = paginateBy.get(PAGINATE_LIMIT_KEY);
+ Map limitDataInfo = new HashMap();
+ limitDataInfo.put(DATA_INFO_VALUE_KEY, limit);
+ limitDataInfo.put(DATA_INFO_TYPE_KEY, DataType.INTEGER);
+ values.add(limitDataInfo);
+
+ // Set offset value and data type for prepared statement substitution
+ String offset = paginateBy.get(PAGINATE_OFFSET_KEY);
+ Map offsetDataInfo = new HashMap();
+ offsetDataInfo.put(DATA_INFO_VALUE_KEY, offset);
+ offsetDataInfo.put(DATA_INFO_TYPE_KEY, DataType.INTEGER);
+ values.add(offsetDataInfo);
+ }
+
+ /**
+ * Display only those columns that the user has chosen to display.
+ * E.g. if the projectionColumns is a list that contains ["ID, Name"], then this method will add the following
+ * SQL line: `SELECT ID, Name from tableName`, otherwise it will add: `SELECT * FROM tableName`
+ *
+ * @param sb - SQL query builder
+ * @param projectionColumns - list of columns that need to be displayed
+ * @param tableName - table name in database
+ */
+ private void addProjectionCondition(StringBuilder sb, List<String> projectionColumns, String tableName) {
+ if (!CollectionUtils.isEmpty(projectionColumns)) {
+ sb.append("SELECT");
+ projectionColumns.stream()
+ .forEach(columnName -> sb.append(" " + columnName + ","));
+
+ sb.setLength(sb.length() - 1);
+ sb.append(" FROM " + tableName);
+ }
+ else {
+ sb.append("SELECT * FROM " + tableName);
+ }
+ }
+
+ /**
+ * This method adds `ORDER BY` clause to the SQL query. E.g. if the sortBy list is
+ * [
+ * {"columnName": "ID", "type": "ASCENDING"},
+ * {"columnName": "Name", "type": "DESCENDING"}
+ * ]
+ * then this method will add the following line to the SQL query: `ORDER BY ID ASC, Name DESC`
+ *
+ * @param sb - SQL query builder
+ * @param sortBy - list of columns to sort by and sort type (ascending / descending)
+ * @throws AppsmithPluginException
+ */
+ private void addSortCondition(StringBuilder sb, List<Map<String, Object>> sortBy) throws AppsmithPluginException {
+ if (CollectionUtils.isEmpty(sortBy)) {
+ return;
+ }
+
+ sb.append(" ORDER BY");
+ sortBy.stream()
+ .forEach(sortCondition -> {
+ String columnName = (String) sortCondition.get(SORT_BY_COLUMN_NAME_KEY);
+ SortType sortType;
+ try {
+ sortType = SortType.valueOf((String) sortCondition.get(SORT_BY_TYPE_KEY));
+ } catch (IllegalArgumentException e) {
+ throw new AppsmithPluginException(AppsmithPluginError.PLUGIN_ERROR, "Appsmith server failed " +
+ "to parse the type of sort condition. Please reach out to Appsmith customer support " +
+ "to resolve this.");
+ }
+ sb.append(" " + columnName + " " + sortType + ",");
+ });
+
+ sb.setLength(sb.length() - 1);
+ }
+
+
public List<Map<String, Object>> executeFilterQueryOldFormat(String tableName, List<Condition> conditions, Map<String, DataType> schema) {
Connection conn = checkAndGetConnection();
@@ -681,7 +805,8 @@ public boolean validConditionList(List<Condition> conditionList, Map<String, Dat
return true;
}
- public String generateLogicalExpression(List<Condition> conditions, LinkedHashMap<String, DataType> values, Map<String, DataType> schema, ConditionalOperator logicOp) {
+ public String generateLogicalExpression(List<Condition> conditions, List<Map<String, Object>> values,
+ Map<String, DataType> schema, ConditionalOperator logicOp) {
StringBuilder sb = new StringBuilder();
@@ -729,7 +854,10 @@ public String generateLogicalExpression(List<Condition> conditions, LinkedHashMa
List<String> updatedStringValues = arrayValues
.stream()
.map(fieldValue -> {
- values.put(String.valueOf(fieldValue), schema.get(path));
+ Map dataInfo = new HashMap();
+ dataInfo.put(DATA_INFO_VALUE_KEY, String.valueOf(fieldValue));
+ dataInfo.put(DATA_INFO_TYPE_KEY, schema.get(path));
+ values.add(dataInfo);
return "?";
})
.collect(Collectors.toList());
@@ -747,7 +875,10 @@ public String generateLogicalExpression(List<Condition> conditions, LinkedHashMa
} else {
// Not an array. Simply add a placeholder
sb.append("?");
- values.put(value, schema.get(path));
+ Map dataInfo = new HashMap();
+ dataInfo.put(DATA_INFO_VALUE_KEY, value);
+ dataInfo.put(DATA_INFO_TYPE_KEY, schema.get(path));
+ values.add(dataInfo);
}
sb.append(" ) ");
diff --git a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/services/ce/IFilterDataServiceCE.java b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/services/ce/IFilterDataServiceCE.java
index 2ca67f1a606b..b56a8b3e2d3c 100644
--- a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/services/ce/IFilterDataServiceCE.java
+++ b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/services/ce/IFilterDataServiceCE.java
@@ -3,6 +3,7 @@
import com.appsmith.external.constants.ConditionalOperator;
import com.appsmith.external.constants.DataType;
import com.appsmith.external.models.Condition;
+import com.appsmith.external.models.UQIDataFilterParams;
import com.fasterxml.jackson.databind.node.ArrayNode;
import java.util.LinkedHashMap;
@@ -14,9 +15,10 @@ public interface IFilterDataServiceCE {
ArrayNode filterData(ArrayNode items, List<Condition> conditionList);
- ArrayNode filterDataNew(ArrayNode items, Condition condition);
+ ArrayNode filterDataNew(ArrayNode items, UQIDataFilterParams uqiDataFilterParams);
- List<Map<String, Object>> executeFilterQueryOldFormat(String tableName, List<Condition> conditions, Map<String, DataType> schema);
+ List<Map<String, Object>> executeFilterQueryOldFormat(String tableName, List<Condition> conditions, Map<String,
+ DataType> schema);
void insertAllData(String tableName, ArrayNode items, Map<String, DataType> schema);
@@ -28,7 +30,8 @@ public interface IFilterDataServiceCE {
boolean validConditionList(List<Condition> conditionList, Map<String, DataType> schema);
- String generateLogicalExpression(List<Condition> conditions, LinkedHashMap<String, DataType> values, Map<String, DataType> schema, ConditionalOperator logicOp);
+ String generateLogicalExpression(List<Condition> conditions, List<Map<String, Object>> values,
+ Map<String, DataType> schema, ConditionalOperator logicOp);
}
diff --git a/app/server/appsmith-interfaces/src/test/java/com/appsmith/external/services/FilterDataServiceTest.java b/app/server/appsmith-interfaces/src/test/java/com/appsmith/external/services/FilterDataServiceTest.java
index 7be2e084b1b6..4a6577c71c43 100644
--- a/app/server/appsmith-interfaces/src/test/java/com/appsmith/external/services/FilterDataServiceTest.java
+++ b/app/server/appsmith-interfaces/src/test/java/com/appsmith/external/services/FilterDataServiceTest.java
@@ -4,6 +4,7 @@
import com.appsmith.external.constants.DataType;
import com.appsmith.external.exceptions.pluginExceptions.AppsmithPluginException;
import com.appsmith.external.models.Condition;
+import com.appsmith.external.models.UQIDataFilterParams;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import org.junit.Test;
@@ -12,7 +13,6 @@
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
-import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
@@ -573,7 +573,7 @@ public void generateLogicalOperatorTest() {
ConditionalOperator operator = condition.getOperator();
List<Condition> conditions = (List<Condition>) condition.getValue();
- String expression = filterDataService.generateLogicalExpression(conditions, new LinkedHashMap<>(), schema, operator);
+ String expression = filterDataService.generateLogicalExpression(conditions, new ArrayList<>(), schema, operator);
assertThat(expression.equals("( \"i\" >= ? ) and ( ( \"d\" <= ? ) and ( ( \"a\" <= ? ) ) ) and ( ( \"u\" <= ? ) ) "));
} catch (IOException e) {
@@ -630,7 +630,8 @@ public void testFilterSingleConditionWithWhereJson() {
Map<String, Object> unparsedWhereClause = (Map<String, Object>) whereClause.get("where");
Condition condition = parseWhereClause(unparsedWhereClause);
- ArrayNode filteredData = filterDataService.filterDataNew(items, condition);
+ ArrayNode filteredData = filterDataService.filterDataNew(items, new UQIDataFilterParams(condition, null,
+ null, null));
assertEquals(filteredData.size(), 2);
@@ -693,7 +694,8 @@ public void testFilterMultipleConditionsNew() {
Map<String, Object> unparsedWhereClause = (Map<String, Object>) whereClause.get("where");
Condition condition = parseWhereClause(unparsedWhereClause);
- ArrayNode filteredData = filterDataService.filterDataNew(items, condition);
+ ArrayNode filteredData = filterDataService.filterDataNew(items, new UQIDataFilterParams(condition, null,
+ null, null));
assertEquals(filteredData.size(), 1);
@@ -757,7 +759,8 @@ public void testFilterInConditionForStringsNew() {
Map<String, Object> unparsedWhereClause = (Map<String, Object>) whereClause.get("where");
Condition condition = parseWhereClause(unparsedWhereClause);
- ArrayNode filteredData = filterDataService.filterDataNew(items, condition);
+ ArrayNode filteredData = filterDataService.filterDataNew(items, new UQIDataFilterParams(condition, null,
+ null, null));
assertEquals(filteredData.size(), 2);
@@ -821,7 +824,8 @@ public void testFilterInConditionForNumbersNew() {
Map<String, Object> unparsedWhereClause = (Map<String, Object>) whereClause.get("where");
Condition condition = parseWhereClause(unparsedWhereClause);
- ArrayNode filteredData = filterDataService.filterDataNew(items, condition);
+ ArrayNode filteredData = filterDataService.filterDataNew(items, new UQIDataFilterParams(condition, null,
+ null, null));
assertEquals(filteredData.size(), 1);
@@ -884,7 +888,8 @@ public void testFilterNotInConditionForNumbersNew() {
Map<String, Object> unparsedWhereClause = (Map<String, Object>) whereClause.get("where");
Condition condition = parseWhereClause(unparsedWhereClause);
- ArrayNode filteredData = filterDataService.filterDataNew(items, condition);
+ ArrayNode filteredData = filterDataService.filterDataNew(items, new UQIDataFilterParams(condition, null,
+ null, null));
assertEquals(filteredData.size(), 2);
@@ -943,7 +948,8 @@ public void testMultiWordColumnNamesNew() {
Map<String, Object> unparsedWhereClause = (Map<String, Object>) whereClause.get("where");
Condition condition = parseWhereClause(unparsedWhereClause);
- ArrayNode filteredData = filterDataService.filterDataNew(items, condition);
+ ArrayNode filteredData = filterDataService.filterDataNew(items, new UQIDataFilterParams(condition, null,
+ null, null));
assertEquals(filteredData.size(), 2);
@@ -1011,7 +1017,8 @@ public void testEmptyValuesInSomeColumnsNew() {
Map<String, Object> unparsedWhereClause = (Map<String, Object>) whereClause.get("where");
Condition condition = parseWhereClause(unparsedWhereClause);
- ArrayNode filteredData = filterDataService.filterDataNew(items, condition);
+ ArrayNode filteredData = filterDataService.filterDataNew(items, new UQIDataFilterParams(condition, null,
+ null, null));
assertEquals(filteredData.size(), 2);
@@ -1073,7 +1080,8 @@ public void testValuesOfUnsupportedDataTypeNew() {
Map<String, Object> unparsedWhereClause = (Map<String, Object>) whereClause.get("where");
Condition condition = parseWhereClause(unparsedWhereClause);
- ArrayNode filteredData = filterDataService.filterDataNew(items, condition);
+ ArrayNode filteredData = filterDataService.filterDataNew(items, new UQIDataFilterParams(condition, null,
+ null, null));
assertEquals(filteredData.size(), 2);
@@ -1134,7 +1142,7 @@ public void testConditionTypeMismatch() {
// Since the data type expected for orderAmount is float, but the value given is String, assert exception
assertThrows(AppsmithPluginException.class,
- () -> filterDataService.filterDataNew(items, condition));
+ () -> filterDataService.filterDataNew(items, new UQIDataFilterParams(condition, null, null, null)));
} catch (IOException e) {
e.printStackTrace();
@@ -1184,7 +1192,8 @@ public void testEmptyConditions() {
Map<String, Object> unparsedWhereClause = (Map<String, Object>) whereClause.get("where");
Condition condition = parseWhereClause(unparsedWhereClause);
- ArrayNode filteredData = filterDataService.filterDataNew(items, condition);
+ ArrayNode filteredData = filterDataService.filterDataNew(items, new UQIDataFilterParams(condition, null,
+ null, null));
assertEquals(filteredData.size(), 3);
@@ -1242,7 +1251,8 @@ public void testConditionNullValueMatch() {
Map<String, Object> unparsedWhereClause = (Map<String, Object>) whereClause.get("where");
Condition condition = parseWhereClause(unparsedWhereClause);
- ArrayNode filteredData = filterDataService.filterDataNew(items, condition);
+ ArrayNode filteredData = filterDataService.filterDataNew(items, new UQIDataFilterParams(condition, null,
+ null, null));
// Since there are no null orderAmounts, the filtered data would be empty.
assertEquals(filteredData.size(), 0);
@@ -1301,7 +1311,8 @@ public void testDateCondition() {
Map<String, Object> unparsedWhereClause = (Map<String, Object>) whereClause.get("where");
Condition condition = parseWhereClause(unparsedWhereClause);
- ArrayNode filteredData = filterDataService.filterDataNew(items, condition);
+ ArrayNode filteredData = filterDataService.filterDataNew(items, new UQIDataFilterParams(condition, null,
+ null, null));
assertEquals(filteredData.size(), 2);
@@ -1359,7 +1370,8 @@ public void testFilterDataNew_withTimestampClause_returnsCorrectValues() {
Map<String, Object> unparsedWhereClause = (Map<String, Object>) whereClause.get("where");
Condition condition = parseWhereClause(unparsedWhereClause);
- ArrayNode filteredData = filterDataService.filterDataNew(items, condition);
+ ArrayNode filteredData = filterDataService.filterDataNew(items,new UQIDataFilterParams(condition, null,
+ null, null));
assertEquals(filteredData.size(), 2);
@@ -1367,4 +1379,279 @@ public void testFilterDataNew_withTimestampClause_returnsCorrectValues() {
e.printStackTrace();
}
}
+
+ @Test
+ public void testProjection() {
+ String data = "[\n" +
+ " {\n" +
+ " \"id\": 2381224,\n" +
+ " \"email\": \"[email protected]\",\n" +
+ " \"userName\": \"Michael Lawson\",\n" +
+ " \"productName\": \"Chicken Sandwich\",\n" +
+ " \"orderAmount\": 4.99,\n" +
+ " \"orderStatus\": \"READY\"\n" +
+ " },\n" +
+ " {\n" +
+ " \"id\": 2736212,\n" +
+ " \"email\": \"[email protected]\",\n" +
+ " \"userName\": \"Lindsay Ferguson\",\n" +
+ " \"productName\": \"Tuna Salad\",\n" +
+ " \"orderAmount\": 9.99,\n" +
+ " \"orderStatus\": \"READY\"\n" +
+ " },\n" +
+ " {\n" +
+ " \"id\": 6788734,\n" +
+ " \"email\": \"[email protected]\",\n" +
+ " \"userName\": \"Tobias Funke\",\n" +
+ " \"productName\": \"Beef steak\",\n" +
+ " \"orderAmount\": 19.99,\n" +
+ " \"orderStatus\": \"READY\"\n" +
+ " }\n" +
+ "]";
+
+ String whereJson = "{\n" +
+ " \"where\": {\n" +
+ " \"children\": [\n" +
+ " {\n" +
+ " \"key\": \"orderAmount\",\n" +
+ " \"condition\": \"LT\",\n" +
+ " \"value\": \"15\"\n" +
+ " }\n" +
+ " ],\n" +
+ " \"condition\": \"AND\"\n" +
+ " }\n" +
+ "}";
+
+ try {
+ ArrayNode items = (ArrayNode) objectMapper.readTree(data);
+
+ Map<String, Object> whereClause = objectMapper.readValue(whereJson, HashMap.class);
+ Map<String, Object> unparsedWhereClause = (Map<String, Object>) whereClause.get("where");
+ Condition condition = parseWhereClause(unparsedWhereClause);
+
+ ArrayNode filteredData = filterDataService.filterDataNew(items, new UQIDataFilterParams(condition,
+ List.of("id", "email"), null, null));
+
+ assertEquals(filteredData.size(), 2);
+
+ List<String> expectedColumns = List.of("id", "email");
+ List<String> returnedColumns = new ArrayList<>();
+ filteredData.get(0).fieldNames().forEachRemaining(columnName -> returnedColumns.add(columnName));
+ assertEquals(expectedColumns, returnedColumns);
+ } catch (IOException e) {
+ e.printStackTrace();
+ }
+ }
+
+ @Test
+ public void testSortBy() {
+ String data = "[\n" +
+ " {\n" +
+ " \"id\": 2381224,\n" +
+ " \"email\": \"[email protected]\",\n" +
+ " \"userName\": \"Michael Lawson\",\n" +
+ " \"productName\": \"Chicken Sandwich\",\n" +
+ " \"orderAmount\": 4.99,\n" +
+ " \"orderStatus\": \"READY\"\n" +
+ " },\n" +
+ " {\n" +
+ " \"id\": 2736212,\n" +
+ " \"email\": \"[email protected]\",\n" +
+ " \"userName\": \"Lindsay Ferguson\",\n" +
+ " \"productName\": \"Tuna Salad\",\n" +
+ " \"orderAmount\": 9.99,\n" +
+ " \"orderStatus\": \"READY\"\n" +
+ " },\n" +
+ " {\n" +
+ " \"id\": 6788734,\n" +
+ " \"email\": \"[email protected]\",\n" +
+ " \"userName\": \"Tobias Funke\",\n" +
+ " \"productName\": \"Beef steak\",\n" +
+ " \"orderAmount\": 19.99,\n" +
+ " \"orderStatus\": \"READY\"\n" +
+ " }\n" +
+ "]";
+
+ String whereJson = "{\n" +
+ " \"where\": {\n" +
+ " \"children\": [\n" +
+ " {\n" +
+ " \"key\": \"orderAmount\",\n" +
+ " \"condition\": \"LT\",\n" +
+ " \"value\": \"15\"\n" +
+ " }\n" +
+ " ],\n" +
+ " \"condition\": \"AND\"\n" +
+ " }\n" +
+ "}";
+
+ try {
+ ArrayNode items = (ArrayNode) objectMapper.readTree(data);
+
+ Map<String, Object> whereClause = objectMapper.readValue(whereJson, HashMap.class);
+ Map<String, Object> unparsedWhereClause = (Map<String, Object>) whereClause.get("where");
+ Condition condition = parseWhereClause(unparsedWhereClause);
+
+ List<Map<String, Object>> sortBy = new ArrayList<>();
+ Map<String, Object> sortCondition = new HashMap<>();
+ sortCondition.put("columnName", "orderAmount");
+ sortCondition.put("type", "DESCENDING");
+ sortBy.add(sortCondition);
+
+ ArrayNode filteredData = filterDataService.filterDataNew(items, new UQIDataFilterParams(condition, null,
+ sortBy, null));
+
+ assertEquals(filteredData.size(), 2);
+
+ List<String> expectedOrder = List.of("9.99", "4.99");
+ List<String> returnedOrder = new ArrayList<>();
+ returnedOrder.add(filteredData.get(0).get("orderAmount").asText());
+ returnedOrder.add(filteredData.get(1).get("orderAmount").asText());
+ assertEquals(expectedOrder, returnedOrder);
+ } catch (IOException e) {
+ e.printStackTrace();
+ }
+ }
+
+ @Test
+ public void testPagination() {
+ String data = "[\n" +
+ " {\n" +
+ " \"id\": 2381224,\n" +
+ " \"email\": \"[email protected]\",\n" +
+ " \"userName\": \"Michael Lawson\",\n" +
+ " \"productName\": \"Chicken Sandwich\",\n" +
+ " \"orderAmount\": 4.99,\n" +
+ " \"orderStatus\": \"READY\"\n" +
+ " },\n" +
+ " {\n" +
+ " \"id\": 2736212,\n" +
+ " \"email\": \"[email protected]\",\n" +
+ " \"userName\": \"Lindsay Ferguson\",\n" +
+ " \"productName\": \"Tuna Salad\",\n" +
+ " \"orderAmount\": 9.99,\n" +
+ " \"orderStatus\": \"READY\"\n" +
+ " },\n" +
+ " {\n" +
+ " \"id\": 6788734,\n" +
+ " \"email\": \"[email protected]\",\n" +
+ " \"userName\": \"Tobias Funke\",\n" +
+ " \"productName\": \"Beef steak\",\n" +
+ " \"orderAmount\": 19.99,\n" +
+ " \"orderStatus\": \"READY\"\n" +
+ " }\n" +
+ "]";
+
+ String whereJson = "{\n" +
+ " \"where\": {\n" +
+ " \"children\": [\n" +
+ " {\n" +
+ " \"key\": \"orderAmount\",\n" +
+ " \"condition\": \"LT\",\n" +
+ " \"value\": \"25\"\n" +
+ " }\n" +
+ " ],\n" +
+ " \"condition\": \"AND\"\n" +
+ " }\n" +
+ "}";
+
+ try {
+ ArrayNode items = (ArrayNode) objectMapper.readTree(data);
+
+ Map<String, Object> whereClause = objectMapper.readValue(whereJson, HashMap.class);
+ Map<String, Object> unparsedWhereClause = (Map<String, Object>) whereClause.get("where");
+ Condition condition = parseWhereClause(unparsedWhereClause);
+
+ HashMap<String, String> paginateBy = new HashMap<>();
+ paginateBy.put("limit", "2");
+ paginateBy.put("offset", "1");
+
+ ArrayNode filteredData = filterDataService.filterDataNew(items, new UQIDataFilterParams(condition, null,
+ null, paginateBy));
+
+ assertEquals(filteredData.size(), 2);
+
+ List<String> expectedOrderAmountValues = List.of("9.99", "19.99");
+ List<String> returnedOrderAmountValues = new ArrayList<>();
+ returnedOrderAmountValues.add(filteredData.get(0).get("orderAmount").asText());
+ returnedOrderAmountValues.add(filteredData.get(1).get("orderAmount").asText());
+ assertEquals(expectedOrderAmountValues, returnedOrderAmountValues);
+ } catch (IOException e) {
+ e.printStackTrace();
+ }
+ }
+
+ @Test
+ public void testProjectionSortingAndPaginationTogether() {
+ String data = "[\n" +
+ " {\n" +
+ " \"id\": 2381224,\n" +
+ " \"email\": \"[email protected]\",\n" +
+ " \"userName\": \"Michael Lawson\",\n" +
+ " \"productName\": \"Chicken Sandwich\",\n" +
+ " \"orderAmount\": 4.99,\n" +
+ " \"orderStatus\": \"READY\"\n" +
+ " },\n" +
+ " {\n" +
+ " \"id\": 2736212,\n" +
+ " \"email\": \"[email protected]\",\n" +
+ " \"userName\": \"Lindsay Ferguson\",\n" +
+ " \"productName\": \"Tuna Salad\",\n" +
+ " \"orderAmount\": 9.99,\n" +
+ " \"orderStatus\": \"READY\"\n" +
+ " },\n" +
+ " {\n" +
+ " \"id\": 6788734,\n" +
+ " \"email\": \"[email protected]\",\n" +
+ " \"userName\": \"Tobias Funke\",\n" +
+ " \"productName\": \"Beef steak\",\n" +
+ " \"orderAmount\": 19.99,\n" +
+ " \"orderStatus\": \"READY\"\n" +
+ " }\n" +
+ "]";
+
+ String whereJson = "{\n" +
+ " \"where\": {\n" +
+ " \"children\": [\n" +
+ " {\n" +
+ " \"key\": \"orderAmount\",\n" +
+ " \"condition\": \"LT\",\n" +
+ " \"value\": \"20\"\n" +
+ " }\n" +
+ " ],\n" +
+ " \"condition\": \"AND\"\n" +
+ " }\n" +
+ "}";
+
+ try {
+ ArrayNode items = (ArrayNode) objectMapper.readTree(data);
+
+ Map<String, Object> whereClause = objectMapper.readValue(whereJson, HashMap.class);
+ Map<String, Object> unparsedWhereClause = (Map<String, Object>) whereClause.get("where");
+ Condition condition = parseWhereClause(unparsedWhereClause);
+
+ List<String> projectColumns = List.of("id", "email", "orderAmount");
+
+ List<Map<String, Object>> sortBy = new ArrayList<>();
+ Map<String, Object> sortCondition = new HashMap<>();
+ sortCondition.put("columnName", "orderAmount");
+ sortCondition.put("type", "DESCENDING");
+ sortBy.add(sortCondition);
+
+ HashMap<String, String> paginateBy = new HashMap<>();
+ paginateBy.put("limit", "1");
+ paginateBy.put("offset", "1");
+
+ ArrayNode filteredData = filterDataService.filterDataNew(items, new UQIDataFilterParams(condition,
+ projectColumns, sortBy,paginateBy));
+
+ assertEquals(filteredData.size(), 1);
+
+ String expectedOrderAmount = "9.99";
+ String returnedOrderAmount = filteredData.get(0).get("orderAmount").asText();
+ assertEquals(expectedOrderAmount, returnedOrderAmount);
+ } catch (IOException e) {
+ e.printStackTrace();
+ }
+ }
}
diff --git a/app/server/appsmith-plugins/amazons3Plugin/src/main/java/com/external/plugins/AmazonS3Plugin.java b/app/server/appsmith-plugins/amazons3Plugin/src/main/java/com/external/plugins/AmazonS3Plugin.java
index 00bc20c68499..6aa6f721aceb 100644
--- a/app/server/appsmith-plugins/amazons3Plugin/src/main/java/com/external/plugins/AmazonS3Plugin.java
+++ b/app/server/appsmith-plugins/amazons3Plugin/src/main/java/com/external/plugins/AmazonS3Plugin.java
@@ -30,6 +30,7 @@
import com.appsmith.external.models.DatasourceTestResult;
import com.appsmith.external.models.Property;
import com.appsmith.external.models.RequestParamDTO;
+import com.appsmith.external.models.UQIDataFilterParams;
import com.appsmith.external.plugins.BasePlugin;
import com.appsmith.external.plugins.PluginExecutor;
import com.appsmith.external.plugins.SmartSubstitutionInterface;
@@ -629,7 +630,8 @@ private Mono<ActionExecutionResult> executeCommon(AmazonS3 connection,
Map<String, Object> whereForm = (Map<String, Object>) whereFormObject;
Condition condition = parseWhereClause(whereForm);
ArrayNode preFilteringResponse = objectMapper.valueToTree(actionResult);
- actionResult = filterDataService.filterDataNew(preFilteringResponse, condition);
+ actionResult = filterDataService.filterDataNew(preFilteringResponse,
+ new UQIDataFilterParams(condition, null, null, null));
}
|
f19ec6a183e24125dd31f5ccca6b7a53b997b364
|
2024-08-06 19:34:59
|
Goutham Pratapa
|
fix: failing backup and restore appsmithctl (#35162)
| false
|
failing backup and restore appsmithctl (#35162)
|
fix
|
diff --git a/deploy/docker/fs/opt/appsmith/utils/bin/backup.js b/deploy/docker/fs/opt/appsmith/utils/bin/backup.js
index e94c6e6407f0..a2ef2b85578f 100644
--- a/deploy/docker/fs/opt/appsmith/utils/bin/backup.js
+++ b/deploy/docker/fs/opt/appsmith/utils/bin/backup.js
@@ -125,7 +125,7 @@ function getEncryptionPasswordFromUser(){
async function exportDatabase(destFolder) {
console.log('Exporting database');
- await executeMongoDumpCMD(destFolder, process.env.APPSMITH_DB_URL)
+ await executeMongoDumpCMD(destFolder, utils.getDburl())
console.log('Exporting database done.');
}
@@ -141,7 +141,7 @@ async function createGitStorageArchive(destFolder) {
async function createManifestFile(path) {
const version = await utils.getCurrentAppsmithVersion()
- const manifest_data = { "appsmithVersion": version, "dbName": utils.getDatabaseNameFromMongoURI(process.env.APPSMITH_DB_URL) }
+ const manifest_data = { "appsmithVersion": version, "dbName": utils.getDatabaseNameFromMongoURI(utils.getDburl()) }
await fsPromises.writeFile(path + '/manifest.json', JSON.stringify(manifest_data));
}
@@ -259,4 +259,4 @@ module.exports = {
removeOldBackups,
getEncryptionPasswordFromUser,
encryptBackupArchive,
-};
+};
\ No newline at end of file
diff --git a/deploy/docker/fs/opt/appsmith/utils/bin/constants.js b/deploy/docker/fs/opt/appsmith/utils/bin/constants.js
index bbce704de5e3..369fd5042e45 100644
--- a/deploy/docker/fs/opt/appsmith/utils/bin/constants.js
+++ b/deploy/docker/fs/opt/appsmith/utils/bin/constants.js
@@ -9,6 +9,8 @@ const APPSMITHCTL_LOG_PATH = "/appsmith-stacks/logs/appsmithctl"
const LAST_ERROR_MAIL_TS = "/appsmith-stacks/data/backup/last-error-mail-ts"
+const ENV_PATH = "/appsmith-stacks/configuration/docker.env"
+
const MIN_REQUIRED_DISK_SPACE_IN_BYTES = 2147483648 // 2GB
const DURATION_BETWEEN_BACKUP_ERROR_MAILS_IN_MILLI_SEC = 21600000 // 6 hrs
@@ -23,5 +25,6 @@ module.exports = {
APPSMITHCTL_LOG_PATH,
MIN_REQUIRED_DISK_SPACE_IN_BYTES,
DURATION_BETWEEN_BACKUP_ERROR_MAILS_IN_MILLI_SEC,
- APPSMITH_DEFAULT_BACKUP_ARCHIVE_LIMIT
-}
+ APPSMITH_DEFAULT_BACKUP_ARCHIVE_LIMIT,
+ ENV_PATH
+}
\ No newline at end of file
diff --git a/deploy/docker/fs/opt/appsmith/utils/bin/export_db.js b/deploy/docker/fs/opt/appsmith/utils/bin/export_db.js
index f5e894b0c434..9072479450da 100644
--- a/deploy/docker/fs/opt/appsmith/utils/bin/export_db.js
+++ b/deploy/docker/fs/opt/appsmith/utils/bin/export_db.js
@@ -1,11 +1,13 @@
// Init function export mongodb
const shell = require('shelljs');
const Constants = require('./constants');
+const utils = require('./utils');
function export_database() {
console.log('export_database ....');
+ dbUrl = utils.getDburl();
shell.mkdir('-p', [Constants.BACKUP_PATH]);
- const cmd = `mongodump --uri='${process.env.APPSMITH_DB_URL}' --archive='${Constants.BACKUP_PATH}/${Constants.DUMP_FILE_NAME}' --gzip`;
+ const cmd = `mongodump --uri='${dbUrl}' --archive='${Constants.BACKUP_PATH}/${Constants.DUMP_FILE_NAME}' --gzip`;
shell.exec(cmd);
console.log('export_database done');
}
@@ -61,4 +63,4 @@ module.exports = {
exportDatabase: export_database,
stopApplication: stop_application,
startApplication: start_application,
-};
+};
\ No newline at end of file
diff --git a/deploy/docker/fs/opt/appsmith/utils/bin/import_db.js b/deploy/docker/fs/opt/appsmith/utils/bin/import_db.js
index 57c326a0ac9b..0d575e4ff16e 100644
--- a/deploy/docker/fs/opt/appsmith/utils/bin/import_db.js
+++ b/deploy/docker/fs/opt/appsmith/utils/bin/import_db.js
@@ -2,11 +2,14 @@
const shell = require('shelljs');
const readlineSync = require('readline-sync');
const process = require('process');
-const Constants = require('./constants')
+const Constants = require('./constants');
+const utils = require('./utils');
+
function import_database() {
console.log('import_database ....')
- const cmd = `mongorestore --uri='${process.env.APPSMITH_DB_URL}' --drop --archive='${Constants.RESTORE_PATH}/${Constants.DUMP_FILE_NAME}' --gzip`
+ dbUrl = utils.getDburl();
+ const cmd = `mongorestore --uri='${dbUrl}' --drop --archive='${Constants.RESTORE_PATH}/${Constants.DUMP_FILE_NAME}' --gzip`
shell.exec(cmd)
console.log('import_database done')
}
@@ -70,4 +73,4 @@ const main = (forceOption) => {
module.exports = {
runImportDatabase: main,
-};
+}
\ No newline at end of file
diff --git a/deploy/docker/fs/opt/appsmith/utils/bin/restore.js b/deploy/docker/fs/opt/appsmith/utils/bin/restore.js
index f79f84cf8f22..780ac3d0050c 100644
--- a/deploy/docker/fs/opt/appsmith/utils/bin/restore.js
+++ b/deploy/docker/fs/opt/appsmith/utils/bin/restore.js
@@ -57,12 +57,12 @@ async function extractArchive(backupFilePath, restoreRootPath) {
console.log('Extracting the backup archive completed');
}
-async function restoreDatabase(restoreContentsPath) {
+async function restoreDatabase(restoreContentsPath, dbUrl) {
console.log('Restoring database...');
- const cmd = ['mongorestore', `--uri=${process.env.APPSMITH_DB_URL}`, '--drop', `--archive=${restoreContentsPath}/mongodb-data.gz`, '--gzip']
+ const cmd = ['mongorestore', `--uri=${dbUrl}`, '--drop', `--archive=${restoreContentsPath}/mongodb-data.gz`, '--gzip']
try {
const fromDbName = await getBackupDatabaseName(restoreContentsPath);
- const toDbName = utils.getDatabaseNameFromMongoURI(process.env.APPSMITH_DB_URL);
+ const toDbName = utils.getDatabaseNameFromMongoURI(dbUrl);
console.log("Restoring database from " + fromDbName + " to " + toDbName)
cmd.push('--nsInclude=*', `--nsFrom=${fromDbName}.*`, `--nsTo=${toDbName}.*`)
} catch (error) {
@@ -75,6 +75,7 @@ async function restoreDatabase(restoreContentsPath) {
async function restoreDockerEnvFile(restoreContentsPath, backupName, overwriteEncryptionKeys) {
console.log('Restoring docker environment file');
const dockerEnvFile = '/appsmith-stacks/configuration/docker.env';
+ const updatedbUrl = utils.getDburl();
let encryptionPwd = process.env.APPSMITH_ENCRYPTION_PASSWORD;
let encryptionSalt = process.env.APPSMITH_ENCRYPTION_SALT;
await utils.execCommand(['mv', dockerEnvFile, dockerEnvFile + '.' + backupName]);
@@ -105,10 +106,10 @@ async function restoreDockerEnvFile(restoreContentsPath, backupName, overwriteEn
hideEchoBack: true
});
}
- await fsPromises.appendFile(dockerEnvFile, '\nAPPSMITH_ENCRYPTION_PASSWORD=' + encryptionPwd + '\nAPPSMITH_ENCRYPTION_SALT=' + encryptionSalt + '\nAPPSMITH_DB_URL=' + process.env.APPSMITH_DB_URL +
+ await fsPromises.appendFile(dockerEnvFile, '\nAPPSMITH_ENCRYPTION_PASSWORD=' + encryptionPwd + '\nAPPSMITH_ENCRYPTION_SALT=' + encryptionSalt + '\nAPPSMITH_DB_URL=' + utils.getDburl() +
'\nAPPSMITH_MONGODB_USER=' + process.env.APPSMITH_MONGODB_USER + '\nAPPSMITH_MONGODB_PASSWORD=' + process.env.APPSMITH_MONGODB_PASSWORD ) ;
} else {
- await fsPromises.appendFile(dockerEnvFile, '\nAPPSMITH_DB_URL=' + process.env.APPSMITH_DB_URL +
+ await fsPromises.appendFile(dockerEnvFile, '\nAPPSMITH_DB_URL=' + updatedbUrl +
'\nAPPSMITH_MONGODB_USER=' + process.env.APPSMITH_MONGODB_USER + '\nAPPSMITH_MONGODB_PASSWORD=' + process.env.APPSMITH_MONGODB_PASSWORD ) ;
}
console.log('Restoring docker environment file completed');
@@ -209,7 +210,7 @@ async function run() {
console.log('****************************************************************');
console.log('Restoring Appsmith instance from the backup at ' + backupFilePath);
utils.stop(['backend', 'rts']);
- await restoreDatabase(restoreContentsPath);
+ await restoreDatabase(restoreContentsPath, utils.getDburl());
await restoreDockerEnvFile(restoreContentsPath, backupName, overwriteEncryptionKeys);
await restoreGitStorageArchive(restoreContentsPath, backupName);
console.log('Appsmith instance successfully restored.');
diff --git a/deploy/docker/fs/opt/appsmith/utils/bin/utils.js b/deploy/docker/fs/opt/appsmith/utils/bin/utils.js
index 4e0ac665d406..997ab2fbaf6a 100644
--- a/deploy/docker/fs/opt/appsmith/utils/bin/utils.js
+++ b/deploy/docker/fs/opt/appsmith/utils/bin/utils.js
@@ -2,6 +2,7 @@ const shell = require("shelljs");
const fsPromises = require("fs/promises");
const Constants = require("./constants");
const childProcess = require("child_process");
+const fs = require('node:fs');
const { ConnectionString } = require("mongodb-connection-string-url");
function showHelp() {
@@ -31,6 +32,27 @@ function start(apps) {
console.log("Started " + appsStr);
}
+function getDburl() {
+ let dbUrl = '';
+ try {
+ let env_array = fs.readFileSync(Constants.ENV_PATH, 'utf8').toString().split("\n");
+ for (let i in env_array) {
+ if (env_array[i].startsWith("APPSMITH_MONGODB_URI") || env_array[i].startsWith("APPSMITH_DB_URL")) {
+ dbUrl = env_array[i].toString().split("=")[1];
+ break; // Break early when the desired line is found
+ }
+ }
+ } catch (err) {
+ console.error("Error reading the environment file:", err);
+ }
+ let dbEnvUrl = process.env.APPSMITH_DB_URL || process.env.APPSMITH_MONGO_DB_URI;
+ // Make sure dbEnvUrl takes precedence over dbUrl
+ if (dbEnvUrl && dbEnvUrl !== "undefined") {
+ dbUrl = dbEnvUrl;
+ }
+ return dbUrl;
+}
+
function execCommand(cmd, options) {
return new Promise((resolve, reject) => {
let isPromiseDone = false;
@@ -174,4 +196,5 @@ module.exports = {
preprocessMongoDBURI,
execCommandSilent,
getDatabaseNameFromMongoURI,
+ getDburl
};
|
b440798dcd9b9f121c7ed613dd2cbdf471eaef86
|
2022-04-01 11:54:59
|
dependabot[bot]
|
chore(deps): bump node-forge from 1.1.0 to 1.3.0 in /app/client (#12191)
| false
|
bump node-forge from 1.1.0 to 1.3.0 in /app/client (#12191)
|
chore
|
diff --git a/app/client/package.json b/app/client/package.json
index 811fdf8917d4..3c5867daa231 100644
--- a/app/client/package.json
+++ b/app/client/package.json
@@ -83,7 +83,7 @@
"moment": "^2.24.0",
"moment-timezone": "^0.5.27",
"nanoid": "^2.0.4",
- "node-forge": "^1.0.0",
+ "node-forge": "^1.3.0",
"node-sass": "^7.0.1",
"normalizr": "^3.3.0",
"path-to-regexp": "^6.2.0",
diff --git a/app/client/yarn.lock b/app/client/yarn.lock
index ec4369b9d74e..fba625b47682 100644
--- a/app/client/yarn.lock
+++ b/app/client/yarn.lock
@@ -11835,10 +11835,10 @@ node-forge@^0.10.0:
resolved "https://registry.yarnpkg.com/node-forge/-/node-forge-0.10.0.tgz#32dea2afb3e9926f02ee5ce8794902691a676bf3"
integrity sha512-PPmu8eEeG9saEUvI97fm4OYxXVB6bFvyNTyiUOBichBpFG8A1Ljw3bY62+5oOjDEMHRnd0Y7HQ+x7uzxOzC6JA==
-node-forge@^1.0.0:
- version "1.1.0"
- resolved "https://registry.yarnpkg.com/node-forge/-/node-forge-1.1.0.tgz#53e61b039eea78b442a4e13f9439dbd61b5cd3a8"
- integrity sha512-HeZMFB41cirRysIhIFFgORmR51/qhkjRTXXIH9QiwS3AjF9L9Kre9XvOnyE7NMubOSHDuN0GsrFpnqhlJcNWTA==
+node-forge@^1.3.0:
+ version "1.3.0"
+ resolved "https://registry.yarnpkg.com/node-forge/-/node-forge-1.3.0.tgz#37a874ea723855f37db091e6c186e5b67a01d4b2"
+ integrity sha512-08ARB91bUi6zNKzVmaj3QO7cr397uiDT2nJ63cHjyNtCTWIgvS47j3eT0WfzUwS9+6Z5YshRaoasFkXCKrIYbA==
node-gyp@^8.4.1:
version "8.4.1"
|
e5f9153346cfb27c694b0085ced14475ae90730c
|
2023-08-11 14:01:14
|
Ayangade Adeoluwa
|
fix: MsSQL count breaks app (#26076)
| false
|
MsSQL count breaks app (#26076)
|
fix
|
diff --git a/app/client/cypress/e2e/Sanity/Datasources/MsSQL_Basic_Spec.ts b/app/client/cypress/e2e/Sanity/Datasources/MsSQL_Basic_Spec.ts
index 4ef7aa1ae5e2..972fc42253ed 100644
--- a/app/client/cypress/e2e/Sanity/Datasources/MsSQL_Basic_Spec.ts
+++ b/app/client/cypress/e2e/Sanity/Datasources/MsSQL_Basic_Spec.ts
@@ -125,6 +125,9 @@ describe("Validate MsSQL connection & basic querying with UI flows", () => {
"IS_NULLABLE",
"SS_DATA_TYPE",
]);
+
+ runQueryNValidateResponseData("SELECT COUNT(*) FROM Amazon_Sales;", "10");
+
agHelper.ActionContextMenuWithInPane({
action: "Delete",
entityType: entityItems.Query,
@@ -290,4 +293,14 @@ describe("Validate MsSQL connection & basic querying with UI flows", () => {
dataSources.RunQuery();
dataSources.AssertQueryResponseHeaders(columnHeaders);
}
+
+ function runQueryNValidateResponseData(
+ query: string,
+ expectedResponse: string,
+ index = 0,
+ ) {
+ dataSources.EnterQuery(query);
+ dataSources.RunQuery();
+ dataSources.AssertQueryTableResponse(index, expectedResponse);
+ }
});
diff --git a/app/client/src/pages/Editor/QueryEditor/Table.tsx b/app/client/src/pages/Editor/QueryEditor/Table.tsx
index 2679b86ae984..dc637d2fd87d 100644
--- a/app/client/src/pages/Editor/QueryEditor/Table.tsx
+++ b/app/client/src/pages/Editor/QueryEditor/Table.tsx
@@ -210,28 +210,20 @@ function Table(props: TableProps) {
const tableBodyRef = React.useRef<HTMLElement>();
const data = React.useMemo(() => {
- const emptyString = "";
/* Check for length greater than 0 of rows returned from the query for mappings keys */
if (!!props.data && isArray(props.data) && props.data.length > 0) {
- const keys = Object.keys(props.data[0]);
- keys.forEach((key) => {
- if (key === emptyString) {
- const value = props.data[0][key];
- delete props.data[0][key];
- props.data[0][uniqueId()] = value;
- }
- });
-
return props.data;
}
return [];
}, [props.data]);
+
const columns = React.useMemo(() => {
if (data.length) {
return Object.keys(data[0]).map((key: any) => {
+ const uniqueKey = uniqueId();
return {
- Header: key,
+ Header: key === "" ? uniqueKey : key,
accessor: key,
Cell: renderCell,
};
|
f2733c67e924c82dfbc87e233f62bf79bf24b7f2
|
2024-12-24 15:20:07
|
Nidhi
|
test: Git integration tests (#38337)
| false
|
Git integration tests (#38337)
|
test
|
diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/domains/ce/ArtifactCE.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/domains/ce/ArtifactCE.java
index b7f4087621cf..de39973c8672 100644
--- a/app/server/appsmith-server/src/main/java/com/appsmith/server/domains/ce/ArtifactCE.java
+++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/domains/ce/ArtifactCE.java
@@ -13,6 +13,8 @@ default String getBaseId() {
String getName();
+ void setName(String artifactName);
+
String getWorkspaceId();
Boolean getExportWithConfiguration();
diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/git/common/CommonGitServiceCEImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/git/common/CommonGitServiceCEImpl.java
index e9d0c004f667..4e71a75088a4 100644
--- a/app/server/appsmith-server/src/main/java/com/appsmith/server/git/common/CommonGitServiceCEImpl.java
+++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/git/common/CommonGitServiceCEImpl.java
@@ -2187,13 +2187,17 @@ public Mono<? extends Artifact> deleteBranch(String baseArtifactId, String branc
.onErrorResume(throwable -> {
log.error("Delete branch failed {}", throwable.getMessage());
if (throwable instanceof CannotDeleteCurrentBranchException) {
- return Mono.error(new AppsmithException(
- AppsmithError.GIT_ACTION_FAILED,
- "delete branch",
- "Cannot delete current checked out branch"));
+ return releaseFileLock(baseArtifactId)
+ .then(Mono.error(new AppsmithException(
+ AppsmithError.GIT_ACTION_FAILED,
+ "delete branch",
+ "Cannot delete current checked out branch")));
}
- return Mono.error(new AppsmithException(
- AppsmithError.GIT_ACTION_FAILED, "delete branch", throwable.getMessage()));
+ return releaseFileLock(baseArtifactId)
+ .then(Mono.error(new AppsmithException(
+ AppsmithError.GIT_ACTION_FAILED,
+ "delete branch",
+ throwable.getMessage())));
})
.flatMap(isBranchDeleted ->
releaseFileLock(baseArtifactId).map(status -> isBranchDeleted))
diff --git a/app/server/appsmith-server/src/test/it/com/appsmith/server/git/GitBranchesIT.java b/app/server/appsmith-server/src/test/it/com/appsmith/server/git/GitBranchesIT.java
new file mode 100644
index 000000000000..02607420a8f6
--- /dev/null
+++ b/app/server/appsmith-server/src/test/it/com/appsmith/server/git/GitBranchesIT.java
@@ -0,0 +1,584 @@
+package com.appsmith.server.git;
+
+import com.appsmith.external.dtos.GitBranchDTO;
+import com.appsmith.external.dtos.GitStatusDTO;
+import com.appsmith.external.dtos.MergeStatusDTO;
+import com.appsmith.git.configurations.GitServiceConfig;
+import com.appsmith.server.applications.base.ApplicationService;
+import com.appsmith.server.configurations.ProjectProperties;
+import com.appsmith.server.constants.ArtifactType;
+import com.appsmith.server.constants.FieldName;
+import com.appsmith.server.constants.GitDefaultCommitMessage;
+import com.appsmith.server.domains.Application;
+import com.appsmith.server.domains.Artifact;
+import com.appsmith.server.domains.GitArtifactMetadata;
+import com.appsmith.server.domains.GitProfile;
+import com.appsmith.server.dtos.AutoCommitResponseDTO;
+import com.appsmith.server.dtos.GitCommitDTO;
+import com.appsmith.server.dtos.GitConnectDTO;
+import com.appsmith.server.dtos.GitMergeDTO;
+import com.appsmith.server.dtos.GitPullDTO;
+import com.appsmith.server.git.autocommit.AutoCommitService;
+import com.appsmith.server.git.common.CommonGitService;
+import com.appsmith.server.git.resolver.GitArtifactHelperResolver;
+import com.appsmith.server.git.templates.contexts.GitContext;
+import com.appsmith.server.git.templates.providers.GitBranchesTestTemplateProvider;
+import com.appsmith.server.services.GitArtifactHelper;
+import org.eclipse.jgit.api.Git;
+import org.eclipse.jgit.api.Status;
+import org.eclipse.jgit.api.errors.GitAPIException;
+import org.eclipse.jgit.lib.ObjectId;
+import org.eclipse.jgit.revwalk.RevCommit;
+import org.junit.jupiter.api.TestInstance;
+import org.junit.jupiter.api.TestTemplate;
+import org.junit.jupiter.api.extension.ExtensionContext;
+import org.junit.jupiter.api.extension.RegisterExtension;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.boot.test.context.SpringBootTest;
+import org.springframework.security.test.context.support.WithUserDetails;
+import org.testcontainers.junit.jupiter.Testcontainers;
+import reactor.core.publisher.Flux;
+import reactor.core.publisher.Mono;
+import reactor.test.StepVerifier;
+
+import java.io.IOException;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.Iterator;
+import java.util.List;
+
+import static com.appsmith.external.git.constants.GitConstants.DEFAULT_COMMIT_MESSAGE;
+import static com.appsmith.external.git.constants.GitConstants.EMPTY_COMMIT_ERROR_MESSAGE;
+import static com.appsmith.server.exceptions.AppsmithError.GIT_MERGE_FAILED_LOCAL_CHANGES;
+import static com.appsmith.server.git.autocommit.AutoCommitEventHandlerImpl.AUTO_COMMIT_MSG_FORMAT;
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.junit.jupiter.api.Assertions.fail;
+
+/**
+ * This integration test suite validates the end-to-end Git workflow for artifacts, performing a sequence of
+ * operations that test repository setup, branch management, status validation, and cleanup. The operations
+ * proceed as follows:
+ *
+ * 1. **Connect Artifact to Git**:
+ * - The artifact is connected to an empty Git repository using a remote URL provided by the Git server initializer.
+ * - A system-generated commit is created as part of the connection process.
+ * - Auto-commit is enabled by default, as verified in the artifact metadata.
+ * - The repository is checked to confirm a single system-generated commit and a clean working directory.
+ *
+ * 2. **Verify Initial Repository State**:
+ * - The default branch is initialized, and its name is verified to match the metadata.
+ * - The repository status is confirmed to be clean with no uncommitted changes.
+ *
+ * 3. **Trigger and Validate Auto-Commit**:
+ * - Auto-commit is triggered, and the resulting commit is validated in the Git log.
+ * - Commit history is checked to confirm the auto-commit appears as a second commit following the initial system-generated commit.
+ *
+ * 4. **Perform Status, Pull, and Commit Operations on the Default Branch (`master`)**:
+ * - The repository status is checked to confirm no changes (`isClean = true`).
+ * - A `pull` operation is executed to ensure synchronization, even when no updates are available.
+ * - A `commit` is attempted with no changes, and the response is validated to confirm no new commits were created.
+ *
+ * 5. **Create and Verify Branches**:
+ * - A new branch `foo` is created from the default branch (`master`).
+ * - Metadata for `foo` is validated, and the commit history confirms that `foo` starts from the latest commit on `master`.
+ * - A second branch `bar` is created from `foo`. Its metadata is verified, and the commit log confirms it starts from the latest commit on `foo`.
+ *
+ * 6. **Test Merging Scenarios**:
+ * - A merge from `bar` to `foo` is validated and shows no action required (`ALREADY_UP_TO_DATE`), as no changes exist.
+ * - Additional changes made to `bar` are merged back into `foo` successfully.
+ *
+ * 7. **Branch Deletion and Repopulation**:
+ * - The branch `foo` is deleted locally but repopulated from the remote repository.
+ * - The latest commit on `foo` is verified to match the changes made on `foo` before deletion.
+ * - An attempt to delete the currently checked-out branch (`master`) fails as expected.
+ *
+ * 8. **Make Changes and Validate Commits**:
+ * - Changes are made to the artifact on `foo` to trigger diffs.
+ * - The repository status is validated as `isClean = false` with pending changes.
+ * - A commit is created with a custom message, and the Git log confirms the commit as the latest on `foo`.
+ * - Changes are successfully discarded, restoring the repository to a clean state.
+ *
+ * 9. **Set and Test Branch Protection**:
+ * - The `master` branch is marked as protected. Commits directly to `master` are restricted.
+ * - Attempts to commit to `master` fail with the appropriate error message.
+ *
+ * 10. **Merge Branches (`baz` to `bar`)**:
+ * - A new branch `baz` is created from `bar`, and its commit log is verified.
+ * - Changes are made to `baz` and successfully merged into `bar` via a fast-forward merge.
+ * - The commit history confirms the merge, and the top commit matches the changes made in `baz`.
+ *
+ * 11. **Disconnect Artifact and Cleanup**:
+ * - The artifact is disconnected from the Git repository.
+ * - All repository branches (`foo`, `bar`, `baz`) except `master` are removed.
+ * - The file system is verified to confirm all repository data is cleaned up.
+ * - Applications associated with the deleted branches are also removed.
+ *
+ * This test suite ensures comprehensive coverage of Git workflows, including repository connection, branch creation,
+ * branch protection, merging, status validation, and repository cleanup. Each operation includes detailed assertions
+ * to validate expected outcomes and handle edge cases.
+ */
+
+@Testcontainers
+@SpringBootTest
+@TestInstance(TestInstance.Lifecycle.PER_CLASS)
+public class GitBranchesIT {
+
+ @Autowired
+ @RegisterExtension
+ GitBranchesTestTemplateProvider templateProvider;
+
+ @Autowired
+ @RegisterExtension
+ ArtifactBuilderExtension artifactBuilderExtension;
+
+ @Autowired
+ @RegisterExtension
+ GitServerInitializerExtension gitServerInitializerExtension;
+
+ @Autowired
+ CommonGitService commonGitService;
+ @Autowired
+ GitTestUtils gitTestUtils;
+ @Autowired
+ GitArtifactHelperResolver gitArtifactHelperResolver;
+ @Autowired
+ GitServiceConfig gitServiceConfig;
+ @Autowired
+ AutoCommitService autoCommitService;
+ @Autowired
+ ProjectProperties projectProperties;
+ @Autowired
+ ApplicationService applicationService;
+
+ final String ORIGIN = "https://foo.bar.com";
+
+ @TestTemplate
+ @WithUserDetails(value = "api_user")
+ void test(GitContext gitContext, ExtensionContext extensionContext) throws IOException, GitAPIException, InterruptedException {
+
+ ExtensionContext.Store contextStore = extensionContext.getStore(ExtensionContext.Namespace.create(ArtifactBuilderExtension.class));
+ String artifactId = contextStore.get(FieldName.ARTIFACT_ID, String.class);
+
+ GitConnectDTO connectDTO = new GitConnectDTO();
+ connectDTO.setRemoteUrl(gitServerInitializerExtension.getGitSshUrl("test" + artifactId));
+ GitProfile gitProfile = new GitProfile("foo bar", "[email protected]", null);
+ connectDTO.setGitProfile(gitProfile);
+
+ // TODO:
+ // - Move the filePath variable to be relative, so that template name and repo name is prettier
+ // - Is it possible to use controller layer here? Might help with also including web filters in IT
+ Artifact artifact = commonGitService.connectArtifactToGit(artifactId, connectDTO, ORIGIN, gitContext.getArtifactType())
+ .block();
+
+ assertThat(artifact).isNotNull();
+
+ ArtifactType artifactType = artifact.getArtifactType();
+ GitArtifactMetadata artifactMetadata = artifact.getGitArtifactMetadata();
+ GitArtifactHelper<?> artifactHelper = gitArtifactHelperResolver.getArtifactHelper(artifactType);
+ Path repoSuffix = artifactHelper.getRepoSuffixPath(
+ artifact.getWorkspaceId(),
+ artifactMetadata.getDefaultArtifactId(),
+ artifactMetadata.getRepoName());
+
+ // Auto-commit should be turned on by default
+ assertThat(artifactMetadata.getAutoCommitConfig().getEnabled()).isTrue();
+
+ Path path = Path.of(gitServiceConfig.getGitRootPath()).resolve(repoSuffix);
+ String branch;
+ ObjectId topOfCommits;
+
+ try (Git git = Git.open(path.toFile())) {
+ branch = git.log().getRepository().getBranch();
+ assertThat(branch).isEqualTo(artifactMetadata.getBranchName());
+
+ // Assert only single system generated commit exists on FS
+ Iterable<RevCommit> commits = git.log().call();
+ Iterator<RevCommit> commitIterator = commits.iterator();
+ assertThat(commitIterator.hasNext()).isTrue();
+
+ RevCommit firstCommit = commitIterator.next();
+ assertThat(firstCommit.getFullMessage()).isEqualTo(DEFAULT_COMMIT_MESSAGE + GitDefaultCommitMessage.CONNECT_FLOW.getReason());
+ topOfCommits = firstCommit.getId();
+
+ assertThat(commitIterator.hasNext()).isFalse();
+
+ // Assert that git directory is clean
+ Status status = git.status().call();
+ assertThat(status.isClean()).isTrue();
+ }
+
+ // Assert that the artifact does have auto-commit requirements, and auto-commit gets initiated
+ AutoCommitResponseDTO autoCommitResponseDTO = autoCommitService.autoCommitApplication(artifactId).block();
+
+ assertThat(autoCommitResponseDTO).isNotNull();
+ AutoCommitResponseDTO.AutoCommitResponse autoCommitProgress = autoCommitResponseDTO.getAutoCommitResponse();
+ assertThat(autoCommitProgress).isEqualTo(AutoCommitResponseDTO.AutoCommitResponse.PUBLISHED);
+
+ // Wait for auto-commit to complete
+ // This should not take more than 2 seconds, we're checking every 500 ms
+ long startTime = System.currentTimeMillis(), currentTime = System.currentTimeMillis();
+ while (!autoCommitProgress.equals(AutoCommitResponseDTO.AutoCommitResponse.IDLE)) {
+ Thread.sleep(500);
+ if (currentTime - startTime > 2000) {
+ fail("Auto-commit took too long");
+ }
+ autoCommitProgress = getAutocommitProgress(artifactId, artifact, artifactMetadata);
+ currentTime = System.currentTimeMillis();
+ }
+
+ // Now there should be two commits in the git log response
+ try (Git git = Git.open(path.toFile())) {
+ branch = git.log().getRepository().getBranch();
+ assertThat(branch).isEqualTo(artifactMetadata.getBranchName());
+
+ Iterable<RevCommit> commits = git.log().call();
+ Iterator<RevCommit> commitIterator = commits.iterator();
+ assertThat(commitIterator.hasNext()).isTrue();
+
+ RevCommit autoCommit = commitIterator.next();
+ assertThat(autoCommit.getFullMessage()).isEqualTo(String.format(AUTO_COMMIT_MSG_FORMAT, projectProperties.getVersion()));
+
+ assertThat(commitIterator.hasNext()).isTrue();
+ RevCommit firstCommit = commitIterator.next();
+ assertThat(firstCommit.getId()).isEqualTo(topOfCommits);
+
+ topOfCommits = autoCommit.getId();
+ }
+
+ // Assert that the initialized branch is set as default
+ assertThat(artifactMetadata.getBranchName()).isEqualTo(artifactMetadata.getDefaultBranchName());
+
+ // Assert that the branch is not protected by default
+ assertThat(artifactMetadata.getBranchProtectionRules()).isNullOrEmpty();
+
+ // Check that the status is clean
+ GitStatusDTO statusDTO = commonGitService.getStatus(artifactId, true, artifactType).block();
+ assertThat(statusDTO).isNotNull();
+ assertThat(statusDTO.getIsClean()).isTrue();
+ assertThat(statusDTO.getAheadCount()).isEqualTo(0);
+ assertThat(statusDTO.getBehindCount()).isEqualTo(0);
+
+ // Check that pull when not required, still goes through
+ GitPullDTO gitPullDTO = commonGitService.pullArtifact(artifactId, artifactType).block();
+ assertThat(gitPullDTO).isNotNull();
+
+ // Check that commit says that there is nothing to commit
+ GitCommitDTO commitDTO = new GitCommitDTO();
+ commitDTO.setCommitMessage("Unused message");
+ commitDTO.setDoPush(false);
+ String commitResponse = commonGitService.commitArtifact(commitDTO, artifactId, artifactType)
+ .block();
+
+ assertThat(commitResponse).contains(EMPTY_COMMIT_ERROR_MESSAGE);
+
+ // Check that the previous attempt didn't actually go through
+ try (Git git = Git.open(path.toFile())) {
+ branch = git.log().getRepository().getBranch();
+ assertThat(branch).isEqualTo(artifactMetadata.getBranchName());
+
+ Iterable<RevCommit> commits = git.log().call();
+ assertThat(commits.iterator().next().getId()).isEqualTo(topOfCommits);
+ }
+
+ // Check that discard, even when not required, goes through
+ Artifact discardedArtifact = commonGitService.discardChanges(artifactId, artifactType).block();
+ assertThat(discardedArtifact).isNotNull();
+
+ // Make a change in the artifact to trigger a diff
+ gitTestUtils.createADiffInArtifact(artifact).block();
+
+ // Check that the status is not clean
+ GitStatusDTO statusDTO2 = commonGitService.getStatus(artifactId, true, artifactType).block();
+ assertThat(statusDTO2).isNotNull();
+ assertThat(statusDTO2.getIsClean()).isFalse();
+ assertThat(statusDTO2.getAheadCount()).isEqualTo(0);
+ assertThat(statusDTO2.getBehindCount()).isEqualTo(0);
+
+ // Check that commit makes the custom message be the top of the log
+ GitCommitDTO commitDTO2 = new GitCommitDTO();
+ commitDTO2.setCommitMessage("Custom message");
+ commitDTO2.setDoPush(true);
+ String commitResponse2 = commonGitService.commitArtifact(commitDTO2, artifactId, artifactType)
+ .block();
+
+ assertThat(commitResponse2).contains("Committed successfully!");
+
+ try (Git git = Git.open(path.toFile())) {
+ branch = git.log().getRepository().getBranch();
+ assertThat(branch).isEqualTo(artifactMetadata.getBranchName());
+
+ Iterable<RevCommit> commits = git.log().call();
+ Iterator<RevCommit> commitIterator = commits.iterator();
+ RevCommit newCommit = commitIterator.next();
+ assertThat(newCommit.getFullMessage()).isEqualTo("Custom message");
+
+ assertThat(commitIterator.next().getId()).isEqualTo(topOfCommits);
+
+ topOfCommits = newCommit.getId();
+ }
+
+ // Check that status is clean again
+ GitStatusDTO statusDTO3 = commonGitService.getStatus(artifactId, true, artifactType).block();
+ assertThat(statusDTO3).isNotNull();
+ assertThat(statusDTO3.getIsClean()).isTrue();
+ assertThat(statusDTO3.getAheadCount()).isEqualTo(0);
+ assertThat(statusDTO3.getBehindCount()).isEqualTo(0);
+
+ // Make another change to trigger a diff
+ gitTestUtils.createADiffInArtifact(artifact).block();
+
+ // Check that status in not clean
+ GitStatusDTO statusDTO4 = commonGitService.getStatus(artifactId, true, artifactType).block();
+ assertThat(statusDTO4).isNotNull();
+ assertThat(statusDTO4.getIsClean()).isFalse();
+ assertThat(statusDTO4.getAheadCount()).isEqualTo(0);
+ assertThat(statusDTO4.getBehindCount()).isEqualTo(0);
+
+ // Protect the master branch
+ List<String> protectedBranches = commonGitService.updateProtectedBranches(artifactId, List.of(branch), artifactType).block();
+ assertThat(protectedBranches).containsExactly(branch);
+
+ // Now try to commit, and check that it fails
+ GitCommitDTO commitDTO3 = new GitCommitDTO();
+ commitDTO3.setCommitMessage("Failed commit");
+ commitDTO3.setDoPush(false);
+ Mono<String> commitResponse3Mono = commonGitService.commitArtifact(commitDTO3, artifactId, artifactType);
+ StepVerifier.create(commitResponse3Mono)
+ .expectErrorSatisfies(e -> assertThat(e.getMessage()).contains("Cannot commit to protected branch"))
+ .verify();
+
+ // Create a new branch foo from master, check that the commit for new branch is created as system generated
+ // On top of the previous custom commit
+ GitBranchDTO fooBranchDTO = new GitBranchDTO();
+ fooBranchDTO.setBranchName("foo");
+ Artifact fooArtifact = commonGitService.createBranch(artifactId, fooBranchDTO, artifactType).block();
+ assertThat(fooArtifact).isNotNull();
+
+ String fooArtifactId = fooArtifact.getId();
+ GitArtifactMetadata fooMetadata = fooArtifact.getGitArtifactMetadata();
+ assertThat(fooMetadata.getBranchName()).isEqualTo("foo");
+
+ try (Git git = Git.open(path.toFile())) {
+ branch = git.log().getRepository().getBranch();
+ assertThat(branch).isEqualTo(fooMetadata.getBranchName());
+
+ Iterable<RevCommit> commits = git.log().call();
+ Iterator<RevCommit> commitIterator = commits.iterator();
+ RevCommit newCommit = commitIterator.next();
+ assertThat(newCommit.getFullMessage()).contains("branch: foo");
+
+ assertThat(commitIterator.next().getId()).isEqualTo(topOfCommits);
+
+ topOfCommits = newCommit.getId();
+ }
+
+ // Check that status on foo is clean again
+ GitStatusDTO statusDTO5 = commonGitService.getStatus(fooArtifactId, true, artifactType).block();
+ assertThat(statusDTO5).isNotNull();
+ assertThat(statusDTO5.getIsClean()).isTrue();
+ assertThat(statusDTO5.getAheadCount()).isEqualTo(0);
+ assertThat(statusDTO5.getBehindCount()).isEqualTo(0);
+
+ // Create another branch bar from foo
+ GitBranchDTO barBranchDTO = new GitBranchDTO();
+ barBranchDTO.setBranchName("bar");
+ Artifact barArtifact = commonGitService.createBranch(fooArtifactId, barBranchDTO, artifactType).block();
+ assertThat(barArtifact).isNotNull();
+
+ String barArtifactId = barArtifact.getId();
+ GitArtifactMetadata barMetadata = barArtifact.getGitArtifactMetadata();
+ assertThat(barMetadata.getBranchName()).isEqualTo("bar");
+
+ try (Git git = Git.open(path.toFile())) {
+ branch = git.log().getRepository().getBranch();
+ assertThat(branch).isEqualTo(barMetadata.getBranchName());
+
+ Iterable<RevCommit> commits = git.log().call();
+ Iterator<RevCommit> commitIterator = commits.iterator();
+
+ assertThat(commitIterator.next().getId()).isEqualTo(topOfCommits);
+ }
+
+ // Check merge status to foo shows no action required
+ // bar -> foo
+ GitMergeDTO gitMergeDTO = new GitMergeDTO();
+ gitMergeDTO.setDestinationBranch("foo");
+ gitMergeDTO.setSourceBranch("bar");
+ MergeStatusDTO mergeStatusDTO = commonGitService.isBranchMergeable(barArtifactId, gitMergeDTO, artifactType).block();
+ assertThat(mergeStatusDTO).isNotNull();
+ assertThat(mergeStatusDTO.getStatus()).isEqualTo("ALREADY_UP_TO_DATE");
+
+ // Delete foo locally and re-populate from remote
+ List<String> branchList = commonGitService.listBranchForArtifact(artifactId, false, artifactType)
+ .flatMapMany(Flux::fromIterable)
+ .map(GitBranchDTO::getBranchName)
+ .collectList()
+ .block();
+ assertThat(branchList).containsExactlyInAnyOrder(
+ artifactMetadata.getBranchName(),
+ "origin/" + artifactMetadata.getBranchName(),
+ fooMetadata.getBranchName(),
+ "origin/" + fooMetadata.getBranchName(),
+ barMetadata.getBranchName(),
+ "origin/" + barMetadata.getBranchName());
+
+ Mono<? extends Artifact> deleteBranchAttemptMono = commonGitService.deleteBranch(artifactId, "foo", artifactType);
+ StepVerifier
+ .create(deleteBranchAttemptMono)
+ .expectErrorSatisfies(e -> assertThat(e.getMessage()).contains("Cannot delete current checked out branch"))
+ .verify();
+
+ // TODO: I'm having to checkout myself to be able to delete the branch.
+ // Are we relying on auto-commit check to do this otherwise?
+ // Is this a potential bug?
+ try (Git git = Git.open(path.toFile())) {
+ git.checkout().setName("bar").call();
+ }
+
+ commonGitService.deleteBranch(artifactId, "foo", artifactType).block();
+
+ List<String> branchList2 = commonGitService.listBranchForArtifact(artifactId, false, artifactType)
+ .flatMapMany(Flux::fromIterable)
+ .map(GitBranchDTO::getBranchName)
+ .collectList()
+ .block();
+ assertThat(branchList2).containsExactlyInAnyOrder(
+ artifactMetadata.getBranchName(),
+ "origin/" + artifactMetadata.getBranchName(),
+ "origin/" + fooMetadata.getBranchName(),
+ barMetadata.getBranchName(),
+ "origin/" + barMetadata.getBranchName());
+
+ Artifact checkedOutFooArtifact = commonGitService.checkoutBranch(artifactId, "origin/foo", true, artifactType).block();
+
+ assertThat(checkedOutFooArtifact).isNotNull();
+ List<String> branchList3 = commonGitService.listBranchForArtifact(artifactId, false, artifactType)
+ .flatMapMany(Flux::fromIterable)
+ .map(GitBranchDTO::getBranchName)
+ .collectList()
+ .block();
+ assertThat(branchList3).containsExactlyInAnyOrder(
+ artifactMetadata.getBranchName(),
+ "origin/" + artifactMetadata.getBranchName(),
+ fooMetadata.getBranchName(),
+ "origin/" + fooMetadata.getBranchName(),
+ barMetadata.getBranchName(),
+ "origin/" + barMetadata.getBranchName());
+
+ // Verify latest commit on foo should be same as changes made on foo previously
+ try (Git git = Git.open(path.toFile())) {
+ branch = git.log().getRepository().getBranch();
+ assertThat(branch).isEqualTo(fooMetadata.getBranchName());
+
+ Iterable<RevCommit> commits = git.log().call();
+ Iterator<RevCommit> commitIterator = commits.iterator();
+
+ assertThat(commitIterator.next().getId()).isEqualTo(topOfCommits);
+ }
+
+ // Make more changes on foo and attempt discard
+ gitTestUtils.createADiffInArtifact(checkedOutFooArtifact).block();
+
+ GitStatusDTO discardableStatus = commonGitService.getStatus(checkedOutFooArtifact.getId(), false, artifactType).block();
+
+ assertThat(discardableStatus).isNotNull();
+ assertThat(discardableStatus.getIsClean()).isFalse();
+
+ Artifact discardedFoo = commonGitService.discardChanges(checkedOutFooArtifact.getId(), artifactType).block();
+
+ GitStatusDTO discardedStatus = commonGitService.getStatus(checkedOutFooArtifact.getId(), false, artifactType).block();
+
+ assertThat(discardedStatus).isNotNull();
+ // TODO: Why is this not clean?
+ // There is an on page load that gets triggered here that is causing a diff
+ // This should ideally have already been fixed on initial artifact import
+// assertThat(discardedStatus.getIsClean()).isTrue();
+
+ // Make a change to trigger a diff on bar
+ gitTestUtils.createADiffInArtifact(barArtifact).block();
+
+ // Check merge status to master shows not merge-able
+ GitMergeDTO gitMergeDTO2 = new GitMergeDTO();
+ gitMergeDTO2.setSourceBranch("bar");
+ gitMergeDTO2.setDestinationBranch("master");
+ MergeStatusDTO mergeStatusDTO2 = commonGitService.isBranchMergeable(barArtifactId, gitMergeDTO2, artifactType).block();
+
+ assertThat(mergeStatusDTO2).isNotNull();
+ assertThat(mergeStatusDTO2.isMergeAble()).isFalse();
+ assertThat(mergeStatusDTO2.getMessage()).isEqualTo(GIT_MERGE_FAILED_LOCAL_CHANGES.getMessage("bar"));
+
+ // Create a new branch baz and check for new commit
+ GitBranchDTO gitBranchDTO = new GitBranchDTO();
+ gitBranchDTO.setBranchName("baz");
+ Artifact bazArtifact = commonGitService.createBranch(barArtifactId, gitBranchDTO, artifactType).block();
+
+ assertThat(bazArtifact).isNotNull();
+
+ try (Git git = Git.open(path.toFile())) {
+ Iterable<RevCommit> commits = git.log().call();
+ Iterator<RevCommit> commitIterator = commits.iterator();
+ RevCommit newCommit = commitIterator.next();
+ assertThat(newCommit.getFullMessage()).contains("branch: baz");
+
+ assertThat(commitIterator.next().getId()).isEqualTo(topOfCommits);
+
+ topOfCommits = newCommit.getId();
+ }
+
+ // TODO: We're having to discard on bar because
+ // create branch today retains uncommitted change on source branch as well
+ // We will need to update this line once that is fixed.
+ // It won't get caught in tests otherwise since this discard would be a redundant op
+ commonGitService.discardChanges(barArtifactId, artifactType).block();
+
+ GitMergeDTO gitMergeDTO3 = new GitMergeDTO();
+ gitMergeDTO3.setSourceBranch("baz");
+ gitMergeDTO3.setDestinationBranch("bar");
+
+ MergeStatusDTO mergeStatusDTO3 = commonGitService.isBranchMergeable(barArtifactId, gitMergeDTO3, artifactType).block();
+
+ assertThat(mergeStatusDTO3).isNotNull();
+ assertThat(mergeStatusDTO3.isMergeAble()).isTrue();
+
+ // Merge bar to master and check log of commits on foo is same as bar
+ MergeStatusDTO barToBazMergeStatus = commonGitService.mergeBranch(barArtifactId, gitMergeDTO3, artifactType).block();
+
+ assertThat(barToBazMergeStatus).isNotNull();
+ assertThat(barToBazMergeStatus.isMergeAble()).isTrue();
+ assertThat(barToBazMergeStatus.getStatus()).contains("FAST_FORWARD");
+
+ // Since fast-forward should succeed here, top of commit should not change
+ try (Git git = Git.open(path.toFile())) {
+ Iterable<RevCommit> commits = git.log().call();
+ Iterator<RevCommit> commitIterator = commits.iterator();
+ assertThat(commitIterator.next().getId()).isEqualTo(topOfCommits);
+ }
+
+ // Disconnect artifact and verify non-existence of `foo`, `bar` and `baz`
+ Artifact disconnectedArtifact = commonGitService.detachRemote(artifactId, artifactType).block();
+
+ assertThat(disconnectedArtifact).isNotNull();
+ assertThat(disconnectedArtifact.getGitArtifactMetadata()).isNull();
+
+ // TODO: This needs to be generified for artifacts
+ Application deletedFooArtifact = applicationService.findById(checkedOutFooArtifact.getId()).block();
+ assertThat(deletedFooArtifact).isNull();
+ Application deletedBarArtifact = applicationService.findById(barArtifactId).block();
+ assertThat(deletedBarArtifact).isNull();
+ Application deletedBazArtifact = applicationService.findById(bazArtifact.getId()).block();
+ assertThat(deletedBazArtifact).isNull();
+ Application existingMasterArtifact = applicationService.findById(artifactId).block();
+ assertThat(existingMasterArtifact).isNotNull();
+
+ // Verify FS is clean after disconnect
+ boolean repoDirectoryNotExists = Files.notExists(path);
+ assertThat(repoDirectoryNotExists).isTrue();
+ }
+
+ private AutoCommitResponseDTO.AutoCommitResponse getAutocommitProgress(String artifactId, Artifact artifact, GitArtifactMetadata artifactMetadata) {
+ AutoCommitResponseDTO autoCommitProgress = commonGitService.getAutoCommitProgress(artifactId, artifactMetadata.getBranchName(), artifact.getArtifactType()).block();
+
+ assertThat(autoCommitProgress).isNotNull();
+ return autoCommitProgress.getAutoCommitResponse();
+ }
+}
diff --git a/app/server/appsmith-server/src/test/it/com/appsmith/server/git/templates/contexts/GitContext.java b/app/server/appsmith-server/src/test/it/com/appsmith/server/git/templates/contexts/GitContext.java
new file mode 100644
index 000000000000..e383a0eadb92
--- /dev/null
+++ b/app/server/appsmith-server/src/test/it/com/appsmith/server/git/templates/contexts/GitContext.java
@@ -0,0 +1,69 @@
+package com.appsmith.server.git.templates.contexts;
+
+import com.appsmith.server.constants.ArtifactType;
+import com.appsmith.server.dtos.ArtifactExchangeJson;
+import com.appsmith.server.git.ArtifactBuilderExtension;
+import org.junit.jupiter.api.extension.Extension;
+import org.junit.jupiter.api.extension.ExtensionContext;
+import org.junit.jupiter.api.extension.ParameterContext;
+import org.junit.jupiter.api.extension.ParameterResolutionException;
+import org.junit.jupiter.api.extension.ParameterResolver;
+import org.junit.jupiter.api.extension.TestTemplateInvocationContext;
+
+import java.util.List;
+
+public class GitContext implements TestTemplateInvocationContext, ParameterResolver {
+
+ private final String fileName;
+
+ private final Class<? extends ArtifactExchangeJson> artifactExchangeJsonType;
+ private final ArtifactType artifactType;
+
+ public GitContext(
+ ExtensionContext extensionContext, String fileName, Class<? extends ArtifactExchangeJson> artifactExchangeJsonType, ArtifactType artifactType) {
+ this.artifactType = artifactType;
+ ExtensionContext.Store contextStore = extensionContext.getStore(ExtensionContext.Namespace.create(ArtifactBuilderExtension.class));
+ contextStore.put(ArtifactExchangeJson.class, artifactExchangeJsonType);
+ contextStore.put("filePath", fileName);
+ this.fileName = fileName;
+ this.artifactExchangeJsonType = artifactExchangeJsonType;
+ }
+
+ @Override
+ public String getDisplayName(int invocationIndex) {
+ return fileName;
+ }
+
+ @Override
+ public List<Extension> getAdditionalExtensions() {
+ return List.of(this);
+ }
+
+ public String getFileName() {
+ return fileName;
+ }
+
+ public Class<? extends ArtifactExchangeJson> getArtifactExchangeJsonType() {
+ return artifactExchangeJsonType;
+ }
+
+ @Override
+ public boolean supportsParameter(ParameterContext parameterContext, ExtensionContext extensionContext)
+ throws ParameterResolutionException {
+ return true;
+ }
+
+ @Override
+ public Object resolveParameter(ParameterContext parameterContext, ExtensionContext extensionContext)
+ throws ParameterResolutionException {
+ if (parameterContext.getParameter().getType().equals(ExtensionContext.class)) {
+ return extensionContext;
+ }
+
+ return this;
+ }
+
+ public ArtifactType getArtifactType() {
+ return artifactType;
+ }
+}
diff --git a/app/server/appsmith-server/src/test/it/com/appsmith/server/git/templates/providers/GitBranchesTestTemplateProvider.java b/app/server/appsmith-server/src/test/it/com/appsmith/server/git/templates/providers/GitBranchesTestTemplateProvider.java
new file mode 100644
index 000000000000..7b2e9fed686a
--- /dev/null
+++ b/app/server/appsmith-server/src/test/it/com/appsmith/server/git/templates/providers/GitBranchesTestTemplateProvider.java
@@ -0,0 +1,7 @@
+package com.appsmith.server.git.templates.providers;
+
+import com.appsmith.server.git.templates.providers.ce.GitBranchesTestTemplateProviderCE;
+import org.springframework.stereotype.Component;
+
+@Component
+public class GitBranchesTestTemplateProvider extends GitBranchesTestTemplateProviderCE {}
diff --git a/app/server/appsmith-server/src/test/it/com/appsmith/server/git/templates/providers/ce/GitBranchesTestTemplateProviderCE.java b/app/server/appsmith-server/src/test/it/com/appsmith/server/git/templates/providers/ce/GitBranchesTestTemplateProviderCE.java
new file mode 100644
index 000000000000..7c576b4c7768
--- /dev/null
+++ b/app/server/appsmith-server/src/test/it/com/appsmith/server/git/templates/providers/ce/GitBranchesTestTemplateProviderCE.java
@@ -0,0 +1,31 @@
+package com.appsmith.server.git.templates.providers.ce;
+
+import com.appsmith.server.constants.ArtifactType;
+import com.appsmith.server.dtos.ApplicationJson;
+import com.appsmith.server.git.templates.contexts.GitContext;
+import org.junit.jupiter.api.extension.ExtensionContext;
+import org.junit.jupiter.api.extension.TestTemplateInvocationContext;
+import org.junit.jupiter.api.extension.TestTemplateInvocationContextProvider;
+
+import java.util.stream.Stream;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+public class GitBranchesTestTemplateProviderCE implements TestTemplateInvocationContextProvider {
+
+ @Override
+ public boolean supportsTestTemplate(ExtensionContext extensionContext) {
+ return true;
+ }
+
+ @Override
+ public Stream<TestTemplateInvocationContext> provideTestTemplateInvocationContexts(
+ ExtensionContext extensionContext) {
+ GitContext context = new GitContext(
+ extensionContext,
+ "com/appsmith/server/git/application.json",
+ ApplicationJson.class,
+ ArtifactType.APPLICATION);
+ return Stream.of(context);
+ }
+}
diff --git a/app/server/appsmith-server/src/test/utils/com/appsmith/server/git/ArtifactBuilderContext.java b/app/server/appsmith-server/src/test/utils/com/appsmith/server/git/ArtifactBuilderContext.java
new file mode 100644
index 000000000000..193cb7a8f908
--- /dev/null
+++ b/app/server/appsmith-server/src/test/utils/com/appsmith/server/git/ArtifactBuilderContext.java
@@ -0,0 +1,22 @@
+package com.appsmith.server.git;
+
+import com.appsmith.server.constants.ArtifactType;
+import com.appsmith.server.dtos.ArtifactExchangeJson;
+import org.junit.jupiter.api.extension.ExtensionContext;
+
+public interface ArtifactBuilderContext extends ExtensionContext {
+
+ ArtifactType getArtifactType();
+
+ Class<? extends ArtifactExchangeJson> getArtifactJsonType();
+
+ String getArtifactJsonPath();
+
+ String getWorkspaceId();
+
+ void setWorkspaceId(String workspaceId);
+
+ String getArtifactId();
+
+ void setArtifactId(String artifactId);
+}
diff --git a/app/server/appsmith-server/src/test/utils/com/appsmith/server/git/ArtifactBuilderExtension.java b/app/server/appsmith-server/src/test/utils/com/appsmith/server/git/ArtifactBuilderExtension.java
new file mode 100644
index 000000000000..941265dbb432
--- /dev/null
+++ b/app/server/appsmith-server/src/test/utils/com/appsmith/server/git/ArtifactBuilderExtension.java
@@ -0,0 +1,117 @@
+package com.appsmith.server.git;
+
+import com.appsmith.server.applications.base.ApplicationService;
+import com.appsmith.server.constants.FieldName;
+import com.appsmith.server.domains.Artifact;
+import com.appsmith.server.domains.User;
+import com.appsmith.server.domains.Workspace;
+import com.appsmith.server.dtos.ArtifactExchangeJson;
+import com.appsmith.server.imports.internal.ImportService;
+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.appsmith.server.solutions.ApplicationPermission;
+import com.fasterxml.jackson.databind.MapperFeature;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import org.junit.jupiter.api.extension.AfterEachCallback;
+import org.junit.jupiter.api.extension.BeforeEachCallback;
+import org.junit.jupiter.api.extension.ExtensionContext;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.core.io.ClassPathResource;
+import org.springframework.stereotype.Component;
+import reactor.core.publisher.Mono;
+
+import java.io.IOException;
+import java.nio.charset.Charset;
+import java.util.UUID;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+/**
+ * This extension basically just creates a new workspace and initializes the artifact provided in context
+ * This artifact is provided in the form of a JSON file that is specified in the context itself
+ */
+@Component
+public class ArtifactBuilderExtension implements AfterEachCallback, BeforeEachCallback {
+
+ @Autowired
+ UserService userService;
+
+ @Autowired
+ WorkspaceService workspaceService;
+
+ @Autowired
+ ImportService importService;
+
+ @Autowired
+ ObjectMapper objectMapper;
+
+ @Autowired
+ JsonSchemaMigration jsonSchemaMigration;
+
+ @Autowired
+ ApplicationService applicationService;
+
+ @Autowired
+ ApplicationPermission applicationPermission;
+
+ @Autowired
+ ApplicationPageService applicationPageService;
+
+ @Override
+ public void beforeEach(ExtensionContext extensionContext) throws Exception {
+ ExtensionContext.Store parentContextStore = extensionContext.getParent().get().getStore(ExtensionContext.Namespace.create(ArtifactBuilderExtension.class));
+ Class<? extends ArtifactExchangeJson> aClass = parentContextStore.get(ArtifactExchangeJson.class, Class.class);
+ String filePath = parentContextStore.get("filePath", String.class);
+ ExtensionContext.Store contextStore = extensionContext.getStore(ExtensionContext.Namespace.create(ArtifactBuilderExtension.class));
+
+ ArtifactExchangeJson artifactExchangeJson = createArtifactJson(filePath, aClass).block();
+ assertThat(artifactExchangeJson).isNotNull();
+
+ artifactExchangeJson.getArtifact().setName(aClass.getSimpleName() + "_" + UUID.randomUUID());
+
+ 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();
+
+ Artifact artifact = importService.importNewArtifactInWorkspaceFromJson(workspace.getId(), artifactExchangeJson).block();
+ assertThat(artifact).isNotNull();
+
+ contextStore.put(FieldName.WORKSPACE_ID, (workspace.getId()));
+ contextStore.put(FieldName.ARTIFACT_ID, (artifact.getId()));
+ }
+
+
+ @Override
+ public void afterEach(ExtensionContext extensionContext) {
+
+ ExtensionContext.Store contextStore = extensionContext.getStore(ExtensionContext.Namespace.create(ArtifactBuilderExtension.class));
+ String workspaceId = contextStore.get(FieldName.WORKSPACE_ID, String.class);
+
+ // Because right now we only have checks for apps
+ // Move this to artifact based model when we fix that
+ applicationService
+ .findByWorkspaceId(workspaceId, applicationPermission.getDeletePermission())
+ .flatMap(remainingApplication -> applicationPageService.deleteApplication(remainingApplication.getId()))
+ .collectList()
+ .block();
+ workspaceService.archiveById(workspaceId).block();
+
+ }
+
+ private Mono<? extends ArtifactExchangeJson> createArtifactJson(String filePath, Class<? extends ArtifactExchangeJson> exchangeJsonType) throws IOException {
+
+ ClassPathResource classPathResource = new ClassPathResource(filePath);
+
+ String artifactJson = classPathResource.getContentAsString(Charset.defaultCharset());
+
+ ArtifactExchangeJson artifactExchangeJson =
+ objectMapper.copy().disable(MapperFeature.USE_ANNOTATIONS).readValue(artifactJson, exchangeJsonType);
+
+ return jsonSchemaMigration.migrateArtifactExchangeJsonToLatestSchema(artifactExchangeJson, null, null);
+ }
+}
diff --git a/app/server/appsmith-server/src/test/utils/com/appsmith/server/git/GitArtifactTestUtils.java b/app/server/appsmith-server/src/test/utils/com/appsmith/server/git/GitArtifactTestUtils.java
new file mode 100644
index 000000000000..b8c76ce38fd4
--- /dev/null
+++ b/app/server/appsmith-server/src/test/utils/com/appsmith/server/git/GitArtifactTestUtils.java
@@ -0,0 +1,52 @@
+package com.appsmith.server.git;
+
+import com.appsmith.external.constants.PluginConstants;
+import com.appsmith.external.models.ActionConfiguration;
+import com.appsmith.external.models.ActionDTO;
+import com.appsmith.external.models.Datasource;
+import com.appsmith.external.models.PluginType;
+import com.appsmith.server.domains.Application;
+import com.appsmith.server.domains.Artifact;
+import com.appsmith.server.domains.Plugin;
+import com.appsmith.server.plugins.base.PluginService;
+import com.appsmith.server.services.LayoutActionService;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.http.HttpMethod;
+import org.springframework.stereotype.Component;
+import reactor.core.publisher.Mono;
+
+import java.util.UUID;
+
+@Component
+public class GitArtifactTestUtils<T extends Artifact> {
+
+ @Autowired
+ LayoutActionService layoutActionService;
+ @Autowired
+ PluginService pluginService;
+
+ Mono<Void> createADiff(Artifact artifact) {
+
+ Application application = (Application) artifact;
+
+ String pageId = application.getPages().get(0).getId();
+ Plugin plugin = pluginService.findByPackageName("restapi-plugin").block();
+
+ Datasource datasource = new Datasource();
+ datasource.setName(PluginConstants.DEFAULT_REST_DATASOURCE);
+ datasource.setWorkspaceId(application.getWorkspaceId());
+ datasource.setPluginId(plugin.getId());
+
+ ActionDTO action = new ActionDTO();
+ action.setPluginType(PluginType.API);
+ action.setName("aGetAction_" + UUID.randomUUID());
+ action.setDatasource(datasource);
+ action.setActionConfiguration(new ActionConfiguration());
+ action.getActionConfiguration().setHttpMethod(HttpMethod.GET);
+ action.setPageId(pageId);
+
+ return layoutActionService
+ .createSingleAction(action, Boolean.FALSE)
+ .then();
+ }
+}
diff --git a/app/server/appsmith-server/src/test/utils/com/appsmith/server/git/GitServerInitializerExtension.java b/app/server/appsmith-server/src/test/utils/com/appsmith/server/git/GitServerInitializerExtension.java
new file mode 100644
index 000000000000..9605c769562a
--- /dev/null
+++ b/app/server/appsmith-server/src/test/utils/com/appsmith/server/git/GitServerInitializerExtension.java
@@ -0,0 +1,119 @@
+package com.appsmith.server.git;
+
+import com.appsmith.git.configurations.GitServiceConfig;
+import com.appsmith.server.applications.base.ApplicationService;
+import com.appsmith.server.constants.FieldName;
+import com.appsmith.server.domains.GitAuth;
+import com.appsmith.server.dtos.ArtifactExchangeJson;
+import com.appsmith.server.git.common.CommonGitService;
+import org.assertj.core.api.Assertions;
+import org.junit.jupiter.api.extension.AfterAllCallback;
+import org.junit.jupiter.api.extension.AfterEachCallback;
+import org.junit.jupiter.api.extension.BeforeAllCallback;
+import org.junit.jupiter.api.extension.BeforeEachCallback;
+import org.junit.jupiter.api.extension.ExtensionContext;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.http.ResponseEntity;
+import org.springframework.stereotype.Component;
+import org.springframework.util.FileSystemUtils;
+import org.springframework.web.reactive.function.client.WebClient;
+import org.testcontainers.containers.GenericContainer;
+import org.testcontainers.containers.wait.strategy.Wait;
+import org.testcontainers.junit.jupiter.Container;
+import org.testcontainers.junit.jupiter.Testcontainers;
+import reactor.core.publisher.Mono;
+
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import java.util.Map;
+import java.util.UUID;
+import java.util.concurrent.CompletableFuture;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+/**
+ * This extension is meant to set up the SSH keys for an artifact and link it to the git server.
+ * We'll also set up the repository based on the context,
+ * and ensure that all local FS directories for git are clean by the end of a suite
+ */
+@Component
+public class GitServerInitializerExtension implements BeforeAllCallback, BeforeEachCallback, AfterEachCallback, AfterAllCallback {
+
+ @Autowired
+ ApplicationService applicationService;
+
+ @Autowired
+ GitServiceConfig gitServiceConfig;
+
+ private static GenericContainer<?> gitContainer = new GenericContainer<>(
+ CompletableFuture.completedFuture("appsmith/test-event-driver"))
+ .withExposedPorts(4200, 22)
+ .waitingFor(Wait.forHttp("/").forPort(4200).forStatusCode(200));
+
+ @Override
+ public void beforeAll(ExtensionContext extensionContext) {
+ gitContainer.start();
+ assertThat(gitContainer.isRunning()).isTrue();
+ }
+
+ @Override
+ public void beforeEach(ExtensionContext extensionContext) {
+ ExtensionContext.Store parentContextStore = extensionContext.getParent().get().getStore(ExtensionContext.Namespace.create(ArtifactBuilderExtension.class));
+ Class<? extends ArtifactExchangeJson> aClass = parentContextStore.get(ArtifactExchangeJson.class, Class.class);
+ String filePath = parentContextStore.get("filePath", String.class);
+ ExtensionContext.Store contextStore = extensionContext.getStore(ExtensionContext.Namespace.create(ArtifactBuilderExtension.class));
+
+ String artifactId = contextStore.get(FieldName.ARTIFACT_ID, String.class);
+ String repoName = "test" + artifactId;
+
+ // TODO : Move this to artifact service to enable packages
+ // Generate RSA public key for the given artifact
+ Mono<GitAuth> gitAuthMono = applicationService.createOrUpdateSshKeyPair(artifactId, "RSA");
+
+ String tedGitApiPath = "http://" + gitContainer.getHost() + ":" + gitContainer.getMappedPort(4200) + "/api/v1/git/";
+
+ // Attach public key on TED git server
+ Mono<ResponseEntity<Void>> createRepoMono = WebClient.create(tedGitApiPath + "repos")
+ .post()
+ .bodyValue(Map.of("name", repoName, "private", false))
+ .retrieve()
+ .toBodilessEntity();
+
+ Mono.zip(gitAuthMono, createRepoMono)
+ .flatMap(tuple2 -> {
+ GitAuth auth = tuple2.getT1();
+ String generatedKey = auth.getPublicKey();
+ return WebClient.create(tedGitApiPath + "/keys/" + repoName)
+ .post()
+ .bodyValue(Map.of("title", "key_" + UUID.randomUUID(),
+ "key", generatedKey,
+ "read_only", false))
+ .retrieve()
+ .toBodilessEntity();
+ })
+ .block();
+
+ }
+
+ @Override
+ public void afterEach(ExtensionContext extensionContext) {
+ // Delete all repositories created in the current workspace
+ ExtensionContext.Store contextStore = extensionContext.getStore(ExtensionContext.Namespace.create(ArtifactBuilderExtension.class));
+ String workspaceId = contextStore.get(FieldName.WORKSPACE_ID, String.class);
+
+ Path path = Paths.get(gitServiceConfig.getGitRootPath()).resolve(workspaceId);
+ FileSystemUtils.deleteRecursively(path.toFile());
+ }
+
+ @Override
+ public void afterAll(ExtensionContext extensionContext) {
+ // Stop the TED container
+ gitContainer.stop();
+ assertThat(gitContainer.isRunning()).isFalse();
+
+ }
+
+ public String getGitSshUrl(String repoName) {
+ return "ssh://git@" + gitContainer.getHost() +":" + gitContainer.getMappedPort(22) +"/git-server/repos/Cypress/" + repoName + ".git";
+ }
+}
diff --git a/app/server/appsmith-server/src/test/utils/com/appsmith/server/git/GitTestUtils.java b/app/server/appsmith-server/src/test/utils/com/appsmith/server/git/GitTestUtils.java
new file mode 100644
index 000000000000..34780cec9e72
--- /dev/null
+++ b/app/server/appsmith-server/src/test/utils/com/appsmith/server/git/GitTestUtils.java
@@ -0,0 +1,27 @@
+package com.appsmith.server.git;
+
+import com.appsmith.server.constants.ArtifactType;
+import com.appsmith.server.domains.Application;
+import com.appsmith.server.domains.Artifact;
+import lombok.RequiredArgsConstructor;
+import org.springframework.stereotype.Component;
+import reactor.core.publisher.Mono;
+
+@RequiredArgsConstructor
+@Component
+public class GitTestUtils {
+
+ private final GitArtifactTestUtils<Application> gitApplicationTestUtils;
+
+ private GitArtifactTestUtils<?> getArtifactSpecificUtils(ArtifactType artifactType) {
+ // TODO For now just work with apps
+ return gitApplicationTestUtils;
+ }
+
+
+ public Mono<Void> createADiffInArtifact(Artifact artifact) {
+ GitArtifactTestUtils<?> artifactSpecificUtils = getArtifactSpecificUtils(artifact.getArtifactType());
+
+ return artifactSpecificUtils.createADiff(artifact);
+ }
+}
|
1eb7f0e171db2f9b7154adacaea6a35e4b66913c
|
2024-03-12 18:54:39
|
Shrikant Sharat Kandula
|
chore: Remove "Save theme" functionality (#31481)
| false
|
Remove "Save theme" functionality (#31481)
|
chore
|
diff --git a/app/client/cypress/e2e/Regression/ClientSide/ThemingTests/Basic_spec.js b/app/client/cypress/e2e/Regression/ClientSide/ThemingTests/Basic_spec.js
index a7848fc9635d..e62d1ec52918 100644
--- a/app/client/cypress/e2e/Regression/ClientSide/ThemingTests/Basic_spec.js
+++ b/app/client/cypress/e2e/Regression/ClientSide/ThemingTests/Basic_spec.js
@@ -167,247 +167,15 @@ describe("App Theming funtionality", { tags: ["@tag.Theme"] }, function () {
});
});
- it("3. Checks if the theme can be saved", () => {
- //Click on dropDown elipses
- cy.contains("Theme properties")
- .closest("div")
- .siblings()
- .first()
- .find("button")
- .click({ force: true });
-
- agHelper.AssertAutoSave();
-
- //Click on save theme dropdown option
- cy.contains("Save theme").click({ force: true });
-
- //Type the name of the theme:
- agHelper.TypeText("input[placeholder='My theme']", "testtheme");
- //Click on save theme button
- agHelper.ClickButton("Save theme");
- agHelper.ValidateToastMessage("Theme testtheme saved");
- appSettings.ClosePane();
- });
-
- it("4. Verify Save Theme after changing all properties & widgets conform to the selected theme", () => {
- cy.dragAndDropToCanvas("iconbuttonwidget", { x: 300, y: 300 });
- cy.assertPageSave();
- cy.get("canvas").first(0).trigger("click", { force: true });
-
- appSettings.OpenAppSettings();
- appSettings.GoToThemeSettings();
- //#region Change Font & verify widgets:
-
- agHelper.GetNClick(".rc-select-selection-search-input").then(($elem) => {
- cy.get($elem).click({ force: true });
- cy.wait(250);
- cy.get(".rc-virtual-list-holder div")
- .children()
- .eq(4)
- .then(($childElem) => {
- cy.get($childElem).click({ force: true });
- cy.get(widgetsPage.iconWidgetBtn).should(
- "have.css",
- "font-family",
- `${$childElem.children().last().text()}Inter, sans-serif`,
- );
- cy.get(widgetsPage.widgetBtn).should(
- "have.css",
- "font-family",
- `${$childElem.children().last().text()}Inter, sans-serif`,
- );
- });
- });
-
- cy.get(widgetsPage.colorPickerV2Popover).click({ force: true }).click();
- cy.get(widgetsPage.colorPickerV2Color)
- .eq(-15)
- .then(($elem) => {
- cy.get($elem).click({ force: true });
- cy.get(widgetsPage.iconWidgetBtn).should(
- "have.css",
- "background-color",
- $elem.css("background-color"),
- );
- cy.get(widgetsPage.widgetBtn).should(
- "have.css",
- "background-color",
- $elem.css("background-color"),
- );
- });
-
- //Change the background color:
- cy.get("[data-testid='theme-backgroundColor']").click({ force: true });
- cy.wait(500);
- cy.get(widgetsPage.colorPickerV2Popover).click({ force: true }).click();
- cy.get(widgetsPage.colorPickerV2TailwindColor)
- .eq(23)
- .then(($elem) => {
- cy.get($elem).click({ force: true });
- cy.get(commonlocators.canvas).should(
- "have.css",
- "background-color",
- $elem.css("background-color"),
- );
- });
-
- cy.get(commonlocators.themeAppBorderRadiusBtn).eq(2).click({ force: true });
- cy.get(`${commonlocators.themeAppBorderRadiusBtn}`)
- .eq(2)
- .invoke("css", "border-top-left-radius")
- .then((borderRadius) => {
- cy.get(widgetsPage.iconWidgetBtn).should(
- "have.css",
- "border-radius",
- borderRadius,
- );
- cy.get(widgetsPage.widgetBtn).should(
- "have.css",
- "border-radius",
- borderRadius,
- );
- });
-
- //#region Change the shadow & verify widgets
- cy.get("[data-value='L']").eq(1).click({ force: true });
- cy.get("[data-value='L']")
- .eq(1)
- .invoke("css", "box-shadow")
- .then((boxShadow) => {
- cy.get(containerShadowElement).should(
- "have.css",
- "box-shadow",
- boxShadow,
- );
- });
-
- //#region Click on dropDown elipses
- cy.contains("Theme properties")
- .closest("div")
- .siblings()
- .first()
- .find("button")
- .click({ force: true });
- cy.wait(300);
-
- //Click on save theme dropdown option & close it
- cy.contains("Save theme").click({ force: true });
- cy.wait(200);
- cy.get(".ads-v2-modal__content-header-close-button").click();
-
- //Click on save theme dropdown option & cancel it
- cy.contains("Theme properties")
- .closest("div")
- .siblings()
- .first()
- .find("button")
- .click({ force: true });
- cy.wait(300);
- cy.contains("Save theme").click({ force: true });
- cy.wait(200);
- cy.xpath("//span[text()='Cancel']/parent::div").click();
-
- //Click on save theme dropdown option, give duplicte name & save it
- cy.contains("Theme properties")
- .closest("div")
- .siblings()
- .first()
- .find("button")
- .click({ force: true });
- cy.wait(300);
- cy.contains("Save theme").click({ force: true });
- cy.wait(200);
- //Type the name of the theme:
- agHelper.TypeText("input[placeholder='My theme']", "testtheme");
- cy.contains("Name must be unique");
-
- cy.get("input[placeholder='My theme']").clear().type("VioletYellowTheme");
-
- //Click on save theme button
- agHelper.ClickButton("Save theme");
- agHelper.ValidateToastMessage("Theme VioletYellowTheme saved");
- });
-
- it("5. Verify Themes exists under respective section when ChangeTheme button is cicked in properties with Apply Theme & Trash as applicable", () => {
- //Click on change theme:
+ it("4. Verify user able to change between saved theme & already existing Featured themes", () => {
cy.get(commonlocators.changeThemeBtn).click({ force: true });
- cy.xpath(applyTheme("Your themes", "testtheme"))
- .click({ force: true })
- .wait(1000); //Changing to testtheme
-
- cy.contains("Applied theme")
- .click()
- .parent()
- .siblings()
- .find(".t--theme-card > main > main")
- .invoke("css", "background-color")
- .then((backgroudColor) => {
- expect(backgroudColor).to.eq("rgb(236, 72, 153)");
- });
-
- //Check if the saved theme is present under 'Yours Themes' section with Trash button
- cy.xpath(applyTheme("Your themes", "testtheme")).should("exist");
- cy.xpath(themesDeletebtn("Your themes", "testtheme")).should("exist");
-
- cy.xpath(applyTheme("Your themes", "VioletYellowTheme")).should("exist");
- cy.xpath(themesDeletebtn("Your themes", "VioletYellowTheme")).should(
- "exist",
- );
-
- cy.xpath(applyTheme("Featured themes", "Earth")).should("exist");
- cy.xpath(themesDeletebtn("Featured themes", "Earth")).should("not.exist");
-
- cy.xpath(applyTheme("Featured themes", "Sunrise")).should("exist");
- cy.xpath(themesDeletebtn("Featured themes", "Sunrise")).should("not.exist");
-
- cy.xpath(applyTheme("Featured themes", "Pacific")).should("exist");
- cy.xpath(themesDeletebtn("Featured themes", "Pacific")).should("not.exist");
-
- cy.xpath(applyTheme("Featured themes", "Pampas")).should("exist");
- cy.xpath(themesDeletebtn("Featured themes", "Pampas")).should("not.exist");
- });
-
- it("6. Verify the custom theme can be deleted", () => {
- //Delete the created theme
- cy.xpath(themesDeletebtn("Your themes", "testtheme"))
- .click({ force: true })
- .wait(200);
- cy.contains(
- "Do you really want to delete this theme? This process cannot be undone.",
- );
-
- //Click on Delete theme trash icon & close it
- cy.xpath("//*[text()='Are you sure?']/following-sibling::button").click();
- cy.get(commonlocators.toastMsg).should("not.exist");
-
- //Click on Delete theme trash icon & cancel it
- cy.xpath(themesDeletebtn("Your themes", "testtheme"))
- .click({ force: true })
- .wait(200);
- cy.xpath("//span[text()='No']/parent::div").click();
- cy.get(commonlocators.toastMsg).should("not.exist");
-
- //Click on Delete theme trash icon & delete it
- cy.xpath(themesDeletebtn("Your themes", "testtheme"))
- .click({ force: true })
- .wait(200);
- agHelper.ClickButton("Delete");
- // cy.contains("Delete").click({ force: true });
-
- //check for delete alert
- // cy.wait(500);
- agHelper.ValidateToastMessage("Theme testtheme deleted");
- //cy.get(commonlocators.toastMsg).contains("Theme testtheme deleted");
- cy.xpath(applyTheme("Your themes", "testtheme")).should("not.exist");
- });
- it("7. Verify user able to change between saved theme & already existing Featured themes", () => {
//#region Pampas
cy.xpath(applyTheme("Featured themes", "Pampas"))
.click({ force: true })
.wait(1000); //Changing to one of Featured themes
cy.contains("Applied theme")
- // .click()
+ .click()
.parent()
.siblings()
.find(".t--theme-card > main > section > div > main")
@@ -620,70 +388,38 @@ describe("App Theming funtionality", { tags: ["@tag.Theme"] }, function () {
expect(backgroudColor).to.eq("rgb(248, 250, 252)");
});
//#endregion
-
- //#region VioletYellowTheme
- cy.xpath(applyTheme("Your themes", "VioletYellowTheme"))
- .click({ force: true })
- .wait(1000); //Changing to created test theme
-
- cy.contains("Applied theme")
- // .click()
- .parent()
- .siblings()
- .find(".t--theme-card > main > section > div > main")
- .eq(0)
- .invoke("css", "background-color")
- .then((backgroudColor) => {
- expect(backgroudColor).to.eq("rgb(219, 234, 254)");
- });
-
- cy.contains("Applied theme")
- // .click()
- .parent()
- .siblings()
- .find(".t--theme-card > main > section > div > main")
- .eq(1)
- .invoke("css", "background-color")
- .then((backgroudColor) => {
- expect(backgroudColor).to.eq("rgb(29, 78, 216)");
- });
-
- //#endregion
});
- it("8. Verify widgets conform to the selected theme in Publish mode", () => {
+ it("5. Verify widgets conform to the selected theme in Publish mode", () => {
deployMode.DeployApp();
//cy.wait(4000); //for theme to settle
- cy.get("body").should("have.css", "font-family", "Inter, sans-serif"); //Font
+ cy.get("body").should(
+ "have.css",
+ "font-family",
+ `"Nunito Sans", sans-serif`,
+ ); //Font
cy.xpath("//div[@id='root']//section/parent::div").should(
"have.css",
"background-color",
- "rgb(29, 78, 216)",
+ "rgb(248, 250, 252)",
); //Background Color
cy.get(widgetsPage.widgetBtn).should(
"have.css",
"background-color",
- "rgb(219, 234, 254)",
- ); //Widget Color
- cy.get(publish.iconWidgetBtn).should(
- "have.css",
- "background-color",
- "rgb(219, 234, 254)",
+ "rgb(100, 116, 139)",
); //Widget Color
- cy.get(widgetsPage.widgetBtn).should("have.css", "border-radius", "24px"); //Border Radius
- cy.get(publish.iconWidgetBtn).should("have.css", "border-radius", "24px"); //Border Radius
+ cy.get(widgetsPage.widgetBtn).should("have.css", "border-radius", "0px"); //Border Radius
cy.get(widgetsPage.widgetBtn).should("have.css", "box-shadow", "none"); //Shadow
- cy.get(publish.iconWidgetBtn).should("have.css", "box-shadow", "none"); //Shadow
deployMode.NavigateBacktoEditor();
});
- it("9. Verify Adding new Individual widgets & it can change Color, Border radius, Shadow & can revert [Color/Border Radius] to already selected theme", () => {
+ it("6. Verify Adding new Individual widgets & it can change Color, Border radius, Shadow & can revert [Color/Border Radius] to already selected theme", () => {
cy.dragAndDropToCanvas("buttonwidget", { x: 200, y: 400 }); //another button widget
cy.moveToStyleTab();
//Change Color & verify
@@ -701,13 +437,8 @@ describe("App Theming funtionality", { tags: ["@tag.Theme"] }, function () {
cy.get(".t--widget-button1 button").should(
"have.css",
"background-color",
- "rgb(219, 234, 254)",
+ "rgb(100, 116, 139)",
); //old widgets still conforming to theme color
- cy.get(widgetsPage.iconWidgetBtn).should(
- "have.css",
- "background-color",
- "rgb(219, 234, 254)",
- );
});
//Change Border & verify
@@ -722,22 +453,16 @@ describe("App Theming funtionality", { tags: ["@tag.Theme"] }, function () {
"border-radius",
borderRadius, //0px
);
- cy.get(widgetsPage.iconWidgetBtn).should(
- "have.css",
- "border-radius",
- "24px",
- );
cy.get(".t--widget-button1 button").should(
"have.css",
"border-radius",
- "24px",
+ "0px",
);
});
//Change Shadow & verify
cy.contains(".ads-v2-segmented-control-value-0", "Large").click();
- cy.get(widgetsPage.iconWidgetBtn).should("have.css", "box-shadow", "none");
cy.get(".t--widget-button1 button").should(
"have.css",
"box-shadow",
@@ -748,23 +473,17 @@ describe("App Theming funtionality", { tags: ["@tag.Theme"] }, function () {
deployMode.DeployApp();
//Verify Background color
- cy.get(".t--widget-buttonwidget:nth-child(4) button").should(
+ cy.get(".t--widget-button2 button").should(
"have.css",
"background-color",
"rgb(190, 24, 93)",
); //new widget with its own color
////old widgets still conforming to theme color
- cy.get(".t--widget-buttonwidget button").should(
- "have.css",
- "background-color",
- "rgb(219, 234, 254)",
- );
-
- cy.get(publish.iconWidgetBtn).should(
+ cy.get(".t--widget-button1 button").should(
"have.css",
"background-color",
- "rgb(219, 234, 254)",
+ "rgb(100, 116, 139)",
);
//Verify Border radius
@@ -773,11 +492,10 @@ describe("App Theming funtionality", { tags: ["@tag.Theme"] }, function () {
"border-radius",
"0px",
);
- cy.get(publish.iconWidgetBtn).should("have.css", "border-radius", "24px");
cy.get(".t--widget-button1 button").should(
"have.css",
"border-radius",
- "24px",
+ "0px",
);
//Verify Box shadow
@@ -786,7 +504,6 @@ describe("App Theming funtionality", { tags: ["@tag.Theme"] }, function () {
"box-shadow",
"rgba(0, 0, 0, 0.1) 0px 10px 15px -3px, rgba(0, 0, 0, 0.05) 0px 4px 6px -2px",
);
- cy.get(publish.iconWidgetBtn).should("have.css", "box-shadow", "none");
cy.get(".t--widget-button1 button").should(
"have.css",
"box-shadow",
@@ -805,7 +522,7 @@ describe("App Theming funtionality", { tags: ["@tag.Theme"] }, function () {
cy.get(".t--widget-button2 button").should(
"have.css",
"background-color",
- "rgb(219, 234, 254)",
+ "rgb(100, 116, 139)",
); //verify widget reverted to theme color
cy.get(".t--property-control-borderradius .reset-button").then(($elem) => {
$elem[0].removeAttribute("display: none");
@@ -814,24 +531,28 @@ describe("App Theming funtionality", { tags: ["@tag.Theme"] }, function () {
cy.get(".t--widget-button2 button").should(
"have.css",
"border-radius",
- "24px",
+ "0px",
);
//the new widget with reverted styles also conforming to theme
deployMode.DeployApp();
cy.wait(4000); //for theme to settle
- cy.get("body").should("have.css", "font-family", "Inter, sans-serif"); //Font
+ cy.get("body").should(
+ "have.css",
+ "font-family",
+ `"Nunito Sans", sans-serif`,
+ ); //Font
cy.xpath("//div[@id='root']//section/parent::div").should(
"have.css",
"background-color",
- "rgb(29, 78, 216)",
+ "rgb(248, 250, 252)",
); //Background Color
cy.get(".t--widget-button1 button").should(
"have.css",
"background-color",
- "rgb(219, 234, 254)",
+ "rgb(100, 116, 139)",
); //Widget Color
cy.get("body").then(($ele) => {
if ($ele.find(widgetsPage.widgetBtn).length <= 1) {
@@ -842,25 +563,19 @@ describe("App Theming funtionality", { tags: ["@tag.Theme"] }, function () {
cy.get(".t--widget-button2 button").should(
"have.css",
"background-color",
- "rgb(219, 234, 254)",
- ); //Widget Color
- cy.get(publish.iconWidgetBtn).should(
- "have.css",
- "background-color",
- "rgb(219, 234, 254)",
+ "rgb(100, 116, 139)",
); //Widget Color
cy.get(".t--widget-button1 button").should(
"have.css",
"border-radius",
- "24px",
+ "0px",
); //Border Radius
cy.get(".t--widget-button2 button").should(
"have.css",
"border-radius",
- "24px",
+ "0px",
); //Border Radius
- cy.get(publish.iconWidgetBtn).should("have.css", "border-radius", "24px"); //Border Radius
cy.get(".t--widget-button1 button").should(
"have.css",
@@ -872,12 +587,10 @@ describe("App Theming funtionality", { tags: ["@tag.Theme"] }, function () {
"box-shadow",
"rgba(0, 0, 0, 0.1) 0px 10px 15px -3px, rgba(0, 0, 0, 0.05) 0px 4px 6px -2px",
); //Since Shadow revert option does not exixts
- cy.get(publish.iconWidgetBtn).should("have.css", "box-shadow", "none"); //Shadow
-
deployMode.NavigateBacktoEditor();
});
- it("10. Verify Chainging theme should not affect Individual widgets with changed Color, Border radius, Shadow & can revert to newly selected theme", () => {
+ it("7. Verify Chainging theme should not affect Individual widgets with changed Color, Border radius, Shadow & can revert to newly selected theme", () => {
cy.get("canvas").first(0).trigger("click", { force: true });
appSettings.OpenAppSettings();
@@ -911,11 +624,6 @@ describe("App Theming funtionality", { tags: ["@tag.Theme"] }, function () {
"background-color",
"rgb(239, 68, 68)",
); //old widgets still conforming to theme color
- cy.get(widgetsPage.iconWidgetBtn).should(
- "have.css",
- "background-color",
- "rgb(239, 68, 68)",
- );
});
//Change Border & verify
@@ -930,11 +638,7 @@ describe("App Theming funtionality", { tags: ["@tag.Theme"] }, function () {
"border-radius",
borderRadius, //6px
);
- cy.get(widgetsPage.iconWidgetBtn).should(
- "have.css",
- "border-radius",
- "24px",
- );
+
cy.get(".t--widget-button2 button").should(
"have.css",
"border-radius",
@@ -944,7 +648,6 @@ describe("App Theming funtionality", { tags: ["@tag.Theme"] }, function () {
//Change Shadow & verify
cy.contains(".ads-v2-segmented-control-value-0", "Small").click();
- cy.get(widgetsPage.iconWidgetBtn).should("have.css", "box-shadow", "none");
cy.get(".t--widget-button2 button").should(
"have.css",
"box-shadow",
@@ -971,11 +674,6 @@ describe("App Theming funtionality", { tags: ["@tag.Theme"] }, function () {
"background-color",
"rgb(239, 68, 68)",
);
- cy.get(publish.iconWidgetBtn).should(
- "have.css",
- "background-color",
- "rgb(239, 68, 68)",
- );
//Verify Border radius
cy.get(".t--widget-button1 button").should(
@@ -983,7 +681,6 @@ describe("App Theming funtionality", { tags: ["@tag.Theme"] }, function () {
"border-radius",
"6px",
);
- cy.get(publish.iconWidgetBtn).should("have.css", "border-radius", "24px");
cy.get(".t--widget-button2 button").should(
"have.css",
"border-radius",
@@ -996,7 +693,6 @@ describe("App Theming funtionality", { tags: ["@tag.Theme"] }, function () {
"box-shadow",
"rgba(0, 0, 0, 0.1) 0px 1px 3px 0px, rgba(0, 0, 0, 0.06) 0px 1px 2px 0px",
);
- cy.get(publish.iconWidgetBtn).should("have.css", "box-shadow", "none");
cy.get(".t--widget-button2 button").should(
"have.css",
"box-shadow",
@@ -1056,11 +752,6 @@ describe("App Theming funtionality", { tags: ["@tag.Theme"] }, function () {
"background-color",
"rgb(239, 68, 68)",
); //Widget Color
- cy.get(publish.iconWidgetBtn).should(
- "have.css",
- "background-color",
- "rgb(239, 68, 68)",
- ); //Widget Color
cy.get(".t--widget-button1 button").should(
"have.css",
@@ -1072,7 +763,6 @@ describe("App Theming funtionality", { tags: ["@tag.Theme"] }, function () {
"border-radius",
"24px",
); //Border Radius
- cy.get(publish.iconWidgetBtn).should("have.css", "border-radius", "24px"); //Border Radius
cy.get(".t--widget-button1 button").should(
"have.css",
@@ -1084,7 +774,6 @@ describe("App Theming funtionality", { tags: ["@tag.Theme"] }, function () {
"box-shadow",
"rgba(0, 0, 0, 0.1) 0px 10px 15px -3px, rgba(0, 0, 0, 0.05) 0px 4px 6px -2px",
); //Since Shadow revert option does not exixts
- cy.get(publish.iconWidgetBtn).should("have.css", "box-shadow", "none"); //Shadow
deployMode.NavigateBacktoEditor();
});
diff --git a/app/client/src/api/AppThemingApi.tsx b/app/client/src/api/AppThemingApi.tsx
index 39969d61355e..695c5b258307 100644
--- a/app/client/src/api/AppThemingApi.tsx
+++ b/app/client/src/api/AppThemingApi.tsx
@@ -68,23 +68,6 @@ class AppThemingApi extends API {
);
}
- /**
- * fires api for saving current theme
- *
- * @param applicationId
- * @param theme
- * @returns
- */
- static async saveTheme(
- applicationId: string,
- payload: { name: string },
- ): Promise<AxiosPromise<ApiResponse<AppTheme[]>>> {
- return API.patch(
- `${AppThemingApi.baseUrl}/themes/applications/${applicationId}`,
- payload,
- );
- }
-
/**
* fires api for deleting theme
*
diff --git a/app/client/src/ce/constants/ReduxActionConstants.tsx b/app/client/src/ce/constants/ReduxActionConstants.tsx
index b7374f14f6cd..4077a4ad755a 100644
--- a/app/client/src/ce/constants/ReduxActionConstants.tsx
+++ b/app/client/src/ce/constants/ReduxActionConstants.tsx
@@ -688,7 +688,6 @@ const ActionTypes = {
CHANGE_SELECTED_APP_THEME_SUCCESS: "CHANGE_SELECTED_APP_THEME_SUCCESS",
SET_PREVIEW_APP_THEME: "SET_PREVIEW_APP_THEME",
SAVE_APP_THEME_INIT: "SAVE_APP_THEME_INIT",
- SAVE_APP_THEME_SUCCESS: "SAVE_APP_THEME_SUCCESS",
DELETE_APP_THEME_INIT: "DELETE_APP_THEME_INIT",
DELETE_APP_THEME_SUCCESS: "DELETE_APP_THEME_SUCCESS",
RESET_APP_THEME_INIT: "RESET_APP_THEME_INIT",
@@ -1079,7 +1078,6 @@ export const ReduxActionErrorTypes = {
UPDATE_JS_FUNCTION_PROPERTY_ERROR: "UPDATE_JS_FUNCTION_PROPERTY_ERROR",
DELETE_WORKSPACE_ERROR: "DELETE_WORKSPACE_ERROR",
REFLOW_BETA_FLAGS_INIT_ERROR: "REFLOW_BETA_FLAGS_INIT_ERROR",
- SAVE_APP_THEME_ERROR: "SAVE_APP_THEME_ERROR",
DELETE_APP_THEME_ERROR: "DELETE_APP_THEME_ERROR",
GET_ALL_TEMPLATES_ERROR: "GET_ALL_TEMPLATES_ERROR",
GET_SIMILAR_TEMPLATES_ERROR: "GET_SIMILAR_TEMPLATES_ERROR",
diff --git a/app/client/src/pages/Editor/ThemePropertyPane/SaveThemeModal.tsx b/app/client/src/pages/Editor/ThemePropertyPane/SaveThemeModal.tsx
deleted file mode 100644
index f8b67ad7f6ff..000000000000
--- a/app/client/src/pages/Editor/ThemePropertyPane/SaveThemeModal.tsx
+++ /dev/null
@@ -1,178 +0,0 @@
-import React, { useState } from "react";
-import { useDispatch, useSelector } from "react-redux";
-
-import AnalyticsUtil from "utils/AnalyticsUtil";
-import { saveSelectedThemeAction } from "actions/appThemingActions";
-import { getCurrentApplicationId } from "selectors/editorSelectors";
-import { getAppThemes } from "selectors/appThemingSelectors";
-import {
- createMessage,
- ERROR_MESSAGE_NAME_EMPTY,
- APLHANUMERIC_HYPHEN_SLASH_SPACE_ERROR,
- UNIQUE_NAME_ERROR,
-} from "@appsmith/constants/messages";
-import {
- Button,
- Input,
- Text,
- Modal,
- ModalContent,
- ModalHeader,
- ModalFooter,
- ModalBody,
-} from "design-system";
-
-interface SaveThemeModalProps {
- isOpen: boolean;
- onClose(): void;
-}
-
-function SaveThemeModal(props: SaveThemeModalProps) {
- const { isOpen } = props;
- const dispatch = useDispatch();
- const [name, setName] = useState("");
- const [inputValidator, setInputValidator] = useState({
- isValid: false,
- message: "",
- isDirty: false,
- });
- const applicationId = useSelector(getCurrentApplicationId);
- const themes = useSelector(getAppThemes);
-
- /**
- * dispatches action to save selected theme
- *
- */
- const onSubmit = (event: any) => {
- event.preventDefault();
-
- // if input validations fails, don't do anything
- if (!inputValidator.isValid || inputValidator.isDirty === false) return;
-
- AnalyticsUtil.logEvent("APP_THEMING_SAVE_THEME_SUCCESS", {
- themeName: name,
- });
-
- dispatch(saveSelectedThemeAction({ applicationId, name }));
-
- // close the modal after submit
- onClose();
- };
-
- /**
- * theme creation validator
- *
- * @param value
- * @returns
- */
- const createThemeValidator = (value: string) => {
- let isValid = !!value;
-
- let errorMessage = !isValid ? createMessage(ERROR_MESSAGE_NAME_EMPTY) : "";
-
- if (
- isValid &&
- themes.find((theme) => value.toLowerCase() === theme.name.toLowerCase())
- ) {
- isValid = false;
- errorMessage = createMessage(UNIQUE_NAME_ERROR);
- }
-
- if (/[^a-zA-Z0-9\-\/\ ]/.test(value)) {
- isValid = false;
- errorMessage = createMessage(APLHANUMERIC_HYPHEN_SLASH_SPACE_ERROR);
- }
-
- return {
- isValid: isValid,
- message: errorMessage,
- isDirty: true,
- };
- };
-
- /**
- * on input change
- *
- * @param value
- */
- const onChangeName = (value: string) => {
- const validator = createThemeValidator(value);
-
- setInputValidator(validator);
- setName(value);
- };
-
- /**
- * on close modal
- */
- const onClose = () => {
- // reset validations
- setInputValidator({
- isValid: false,
- message: "",
- isDirty: false,
- });
-
- props.onClose();
- };
-
- return (
- <Modal
- onOpenChange={(isOpen) => {
- if (!isOpen) {
- onClose();
- }
- }}
- open={isOpen}
- >
- <ModalContent
- id="save-theme-modal"
- onInteractOutside={(e) => {
- e.preventDefault();
- }}
- style={{ width: "640px" }}
- >
- <ModalHeader>Save theme</ModalHeader>
- <ModalBody>
- <div className="flex flex-col gap-2">
- <Text kind="action-l">
- You can save your custom themes to use across applications and use
- them when you need.
- </Text>
- <form data-testid="save-theme-form" noValidate onSubmit={onSubmit}>
- <Input
- autoFocus
- errorMessage={
- !inputValidator.isValid ? inputValidator.message : undefined
- }
- isRequired
- label="Your theme name"
- name="name"
- onChange={onChangeName}
- placeholder="My theme"
- size="md"
- />
- </form>
- </div>
- </ModalBody>
- <ModalFooter>
- <div className="flex gap-3">
- <Button kind="secondary" onClick={onClose} size="md">
- Cancel
- </Button>
- <Button
- isDisabled={!name}
- onClick={onSubmit}
- size="md"
- type="submit"
- >
- Save theme
- </Button>
- </div>
- </ModalFooter>
- </ModalContent>
- </Modal>
- );
-}
-
-export default SaveThemeModal;
diff --git a/app/client/src/pages/Editor/ThemePropertyPane/ThemeEditor.tsx b/app/client/src/pages/Editor/ThemePropertyPane/ThemeEditor.tsx
index 3cab5935d5f5..635ddbcabce0 100644
--- a/app/client/src/pages/Editor/ThemePropertyPane/ThemeEditor.tsx
+++ b/app/client/src/pages/Editor/ThemePropertyPane/ThemeEditor.tsx
@@ -1,7 +1,7 @@
import styled, { createGlobalStyle } from "styled-components";
import { get, startCase } from "lodash";
import { useDispatch, useSelector } from "react-redux";
-import React, { useCallback, useState } from "react";
+import React, { useCallback } from "react";
import ThemeCard from "./ThemeCard";
import {
@@ -15,7 +15,6 @@ import {
updateSelectedAppThemeAction,
} from "actions/appThemingActions";
import SettingSection from "./SettingSection";
-import SaveThemeModal from "./SaveThemeModal";
import type { AppTheme } from "entities/AppTheming";
import AnalyticsUtil from "utils/AnalyticsUtil";
import ThemeFontControl from "./controls/ThemeFontControl";
@@ -64,7 +63,6 @@ function ThemeEditor() {
const applicationId = useSelector(getCurrentApplicationId);
const selectedTheme = useSelector(getSelectedAppTheme);
const themingStack = useSelector(getAppThemingStack);
- const [isSaveModalOpen, setSaveModalOpen] = useState(false);
/**
* customizes the current theme
@@ -95,22 +93,6 @@ function ThemeEditor() {
);
}, [setAppThemingModeStackAction]);
- /**
- * open the save modal
- */
- const onOpenSaveModal = useCallback(() => {
- AnalyticsUtil.logEvent("APP_THEMING_SAVE_THEME_START");
-
- setSaveModalOpen(true);
- }, [setSaveModalOpen]);
-
- /**
- * on close save modal
- */
- const onCloseSaveModal = useCallback(() => {
- setSaveModalOpen(false);
- }, [setSaveModalOpen]);
-
/**
* resets theme
*/
@@ -136,9 +118,6 @@ function ThemeEditor() {
/>
</MenuTrigger>
<MenuContent align="end" className="t--save-theme-menu">
- <MenuItem onClick={onOpenSaveModal} startIcon="save">
- Save theme
- </MenuItem>
<MenuItem onClick={onResetTheme} startIcon="arrow-go-back">
Reset widget styles
</MenuItem>
@@ -270,7 +249,6 @@ function ThemeEditor() {
)}
</SettingSection>
</main>
- <SaveThemeModal isOpen={isSaveModalOpen} onClose={onCloseSaveModal} />
<PopoverStyles />
</>
);
diff --git a/app/client/src/reducers/uiReducers/appThemingReducer.ts b/app/client/src/reducers/uiReducers/appThemingReducer.ts
index af37ad83386c..c26b40ff3dee 100644
--- a/app/client/src/reducers/uiReducers/appThemingReducer.ts
+++ b/app/client/src/reducers/uiReducers/appThemingReducer.ts
@@ -111,12 +111,6 @@ const themeReducer = createImmerReducer(initialState, {
(theme) => theme.id !== action.payload.themeId,
);
},
- [ReduxActionTypes.SAVE_APP_THEME_SUCCESS]: (
- state: AppThemingState,
- action: ReduxAction<AppTheme>,
- ) => {
- state.themes.push(action.payload);
- },
[ReduxActionTypes.UPDATE_BETA_CARD_SHOWN]: (
state: AppThemingState,
action: ReduxAction<boolean>,
diff --git a/app/client/src/sagas/AppThemingSaga.tsx b/app/client/src/sagas/AppThemingSaga.tsx
index 92b83d71d02e..476e2e1a8f71 100644
--- a/app/client/src/sagas/AppThemingSaga.tsx
+++ b/app/client/src/sagas/AppThemingSaga.tsx
@@ -3,7 +3,6 @@ import type {
DeleteAppThemeAction,
FetchAppThemesAction,
FetchSelectedAppThemeAction,
- SaveAppThemeAction,
UpdateSelectedAppThemeAction,
} from "actions/appThemingActions";
import { updateisBetaCardShownAction } from "actions/appThemingActions";
@@ -19,7 +18,6 @@ import {
CHANGE_APP_THEME,
createMessage,
DELETE_APP_THEME,
- SAVE_APP_THEME,
SET_DEFAULT_SELECTED_THEME,
} from "@appsmith/constants/messages";
import { ENTITY_TYPE } from "@appsmith/entities/AppsmithConsole/utils";
@@ -225,37 +223,6 @@ export function* changeSelectedTheme(
}
}
-/**
- * save and create new theme from selected theme
- *
- * @param action
- */
-export function* saveSelectedTheme(action: ReduxAction<SaveAppThemeAction>) {
- const { applicationId, name } = action.payload;
-
- try {
- const response: ApiResponse<AppTheme[]> = yield ThemingApi.saveTheme(
- applicationId,
- { name },
- );
-
- yield put({
- type: ReduxActionTypes.SAVE_APP_THEME_SUCCESS,
- payload: response.data,
- });
-
- // shows toast
- toast.show(createMessage(SAVE_APP_THEME, name), {
- kind: "success",
- });
- } catch (error) {
- yield put({
- type: ReduxActionErrorTypes.SAVE_APP_THEME_ERROR,
- payload: { error },
- });
- }
-}
-
/**
* deletes custom saved theme
*
@@ -359,7 +326,6 @@ export default function* appThemingSaga() {
ReduxActionTypes.CHANGE_SELECTED_APP_THEME_INIT,
changeSelectedTheme,
),
- takeLatest(ReduxActionTypes.SAVE_APP_THEME_INIT, saveSelectedTheme),
takeLatest(ReduxActionTypes.DELETE_APP_THEME_INIT, deleteTheme),
takeLatest(ReduxActionTypes.CLOSE_BETA_CARD_SHOWN, closeisBetaCardShown),
takeLatest(
diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/controllers/ce/ThemeControllerCE.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/controllers/ce/ThemeControllerCE.java
index 21505570c582..95c12e802077 100644
--- a/app/server/appsmith-server/src/main/java/com/appsmith/server/controllers/ce/ThemeControllerCE.java
+++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/controllers/ce/ThemeControllerCE.java
@@ -68,16 +68,6 @@ public Mono<ResponseDTO<Theme>> updateTheme(
.map(theme -> new ResponseDTO<>(HttpStatus.OK.value(), theme, null));
}
- @JsonView(Views.Public.class)
- @PatchMapping("applications/{applicationId}")
- public Mono<ResponseDTO<Theme>> publishCurrentTheme(
- @PathVariable String applicationId,
- @RequestBody Theme resource,
- @RequestHeader(name = FieldName.BRANCH_NAME, required = false) String branchName) {
- return service.persistCurrentTheme(applicationId, branchName, resource)
- .map(theme -> new ResponseDTO<>(HttpStatus.OK.value(), theme, null));
- }
-
@JsonView(Views.Public.class)
@PatchMapping("{themeId}")
public Mono<ResponseDTO<Theme>> updateName(@PathVariable String themeId, @Valid @RequestBody Theme resource) {
|
d48ac4fd81a98fa4c9dadcd8a9509321369e82a3
|
2023-10-17 10:53:55
|
ashit-rath
|
chore: action editors refactor (#27972)
| false
|
action editors refactor (#27972)
|
chore
|
diff --git a/app/client/src/actions/queryPaneActions.ts b/app/client/src/actions/queryPaneActions.ts
index c2288e17eedd..7074964120a2 100644
--- a/app/client/src/actions/queryPaneActions.ts
+++ b/app/client/src/actions/queryPaneActions.ts
@@ -2,18 +2,20 @@ import type { ReduxAction } from "@appsmith/constants/ReduxActionConstants";
import { ReduxActionTypes } from "@appsmith/constants/ReduxActionConstants";
import type { Action } from "entities/Action";
-export const changeQuery = (
- id: string,
- newQuery?: boolean,
- action?: Action,
-): ReduxAction<{
+export interface ChangeQueryPayload {
id: string;
+ packageId?: string;
+ applicationId?: string;
+ pageId?: string;
+ moduleId?: string;
newQuery?: boolean;
- action?: any;
-}> => {
+ action?: Action;
+}
+
+export const changeQuery = (payload: ChangeQueryPayload) => {
return {
type: ReduxActionTypes.QUERY_PANE_CHANGE,
- payload: { id, newQuery, action },
+ payload,
};
};
diff --git a/app/client/src/components/common/BackToCanvas.tsx b/app/client/src/components/common/BackToCanvas.tsx
new file mode 100644
index 000000000000..fcf0df3a893b
--- /dev/null
+++ b/app/client/src/components/common/BackToCanvas.tsx
@@ -0,0 +1,46 @@
+import React, { useCallback, useContext } from "react";
+import styled from "styled-components";
+import { Link } from "design-system";
+
+import history from "utils/history";
+import WalkthroughContext from "components/featureWalkthrough/walkthroughContext";
+import { BACK_TO_CANVAS, createMessage } from "@appsmith/constants/messages";
+import { builderURL } from "@appsmith/RouteBuilder";
+
+const BackToCanvasLink = styled(Link)`
+ margin-left: ${(props) => props.theme.spaces[1] + 1}px;
+ margin-top: ${(props) => props.theme.spaces[11]}px;
+ margin-bottom: ${(props) => props.theme.spaces[11]}px;
+`;
+
+interface BackToCanvasProps {
+ pageId: string;
+}
+
+function BackToCanvas({ pageId }: BackToCanvasProps) {
+ const { isOpened: isWalkthroughOpened, popFeature } =
+ useContext(WalkthroughContext) || {};
+
+ const handleCloseWalkthrough = useCallback(() => {
+ if (isWalkthroughOpened && popFeature) {
+ popFeature();
+ }
+ }, [isWalkthroughOpened, popFeature]);
+
+ return (
+ <BackToCanvasLink
+ id="back-to-canvas"
+ kind="secondary"
+ onClick={() => {
+ history.push(builderURL({ pageId }));
+
+ handleCloseWalkthrough();
+ }}
+ startIcon="arrow-left-line"
+ >
+ {createMessage(BACK_TO_CANVAS)}
+ </BackToCanvasLink>
+ );
+}
+
+export default BackToCanvas;
diff --git a/app/client/src/components/editorComponents/ActionNameEditor.tsx b/app/client/src/components/editorComponents/ActionNameEditor.tsx
index 88e301911a37..b666874452ee 100644
--- a/app/client/src/components/editorComponents/ActionNameEditor.tsx
+++ b/app/client/src/components/editorComponents/ActionNameEditor.tsx
@@ -21,6 +21,7 @@ import {
createMessage,
} from "@appsmith/constants/messages";
import { getAssetUrl } from "@appsmith/utils/airgapHelpers";
+import type { ReduxAction } from "@appsmith/constants/ReduxActionConstants";
const ApiNameWrapper = styled.div<{ page?: string }>`
min-width: 50%;
@@ -58,6 +59,11 @@ const ApiIconBox = styled.div`
margin-right: 8px;
flex-shrink: 0;
`;
+
+interface SaveActionNameParams {
+ id: string;
+ name: string;
+}
interface ActionNameEditorProps {
/*
This prop checks if page is API Pane or Query Pane or Curl Pane
@@ -67,6 +73,9 @@ interface ActionNameEditorProps {
*/
page?: string;
disabled?: boolean;
+ saveActionName?: (
+ params: SaveActionNameParams,
+ ) => ReduxAction<SaveActionNameParams>;
}
function ActionNameEditor(props: ActionNameEditorProps) {
@@ -84,7 +93,13 @@ function ActionNameEditor(props: ActionNameEditorProps) {
<NameEditorComponent
checkForGuidedTour
currentActionConfig={currentActionConfig}
- dispatchAction={saveActionName}
+ /**
+ * This component is used by module editor in EE which uses a different
+ * action to save the name of an action. The current callers of this component
+ * pass the existing saveAction action but as fallback the saveActionName is used here
+ * as a guard.
+ */
+ dispatchAction={props.saveActionName || saveActionName}
>
{({
forceUpdate,
diff --git a/app/client/src/components/editorComponents/ActionRightPane/index.tsx b/app/client/src/components/editorComponents/ActionRightPane/index.tsx
index 948c4d03989a..4bdcfda2acb8 100644
--- a/app/client/src/components/editorComponents/ActionRightPane/index.tsx
+++ b/app/client/src/components/editorComponents/ActionRightPane/index.tsx
@@ -2,7 +2,7 @@ import React, { useContext, useEffect, useMemo, useRef, useState } from "react";
import styled from "styled-components";
import { Collapse, Classes as BPClasses } from "@blueprintjs/core";
import { Classes, getTypographyByKey } from "design-system-old";
-import { Divider, Icon, Link, Text } from "design-system";
+import { Divider, Icon, Text } from "design-system";
import SuggestedWidgets from "./SuggestedWidgets";
import type { ReactNode, MutableRefObject } from "react";
import { useParams } from "react-router";
@@ -11,7 +11,6 @@ import { getWidgets } from "sagas/selectors";
import type { AppState } from "@appsmith/reducers";
import { getDependenciesFromInverseDependencies } from "../Debugger/helpers";
import {
- BACK_TO_CANVAS,
BINDINGS_DISABLED_TOOLTIP,
BINDING_SECTION_LABEL,
createMessage,
@@ -23,11 +22,7 @@ import type {
SuggestedWidget,
SuggestedWidget as SuggestedWidgetsType,
} from "api/ActionAPI";
-import {
- getCurrentPageId,
- getPagePermissions,
-} from "selectors/editorSelectors";
-import { builderURL } from "@appsmith/RouteBuilder";
+import { getPagePermissions } from "selectors/editorSelectors";
import DatasourceStructureHeader from "pages/Editor/Explorer/Datasources/DatasourceStructureHeader";
import {
DatasourceStructureContainer as DataStructureList,
@@ -55,7 +50,6 @@ import { Tooltip } from "design-system";
import { ASSETS_CDN_URL } from "constants/ThirdPartyConstants";
import { FEATURE_WALKTHROUGH_KEYS } from "constants/WalkthroughConstants";
import { getIsFirstTimeUserOnboardingEnabled } from "selectors/onboardingSelectors";
-import history from "utils/history";
import { SignpostingWalkthroughConfig } from "pages/Editor/FirstTimeUserOnboarding/Utils";
import { getAssetUrl } from "@appsmith/utils/airgapHelpers";
import { useFeatureFlag } from "utils/hooks/useFeatureFlag";
@@ -113,12 +107,6 @@ const SideBar = styled.div`
}
`;
-const BackToCanvasLink = styled(Link)`
- margin-left: ${(props) => props.theme.spaces[1] + 1}px;
- margin-top: ${(props) => props.theme.spaces[11]}px;
- margin-bottom: ${(props) => props.theme.spaces[11]}px;
-`;
-
const Label = styled.span`
cursor: pointer;
`;
@@ -291,6 +279,7 @@ export function useEntityDependencies(actionName: string) {
function ActionSidebar({
actionName,
+ actionRightPaneBackLink,
context,
datasourceId,
hasConnections,
@@ -305,16 +294,12 @@ function ActionSidebar({
datasourceId: string;
pluginId: string;
context: DatasourceStructureContext;
+ actionRightPaneBackLink: React.ReactNode;
}) {
const dispatch = useDispatch();
const widgets = useSelector(getWidgets);
- const pageId = useSelector(getCurrentPageId);
const user = useSelector(getCurrentUser);
- const {
- isOpened: isWalkthroughOpened,
- popFeature,
- pushFeature,
- } = useContext(WalkthroughContext) || {};
+ const { pushFeature } = useContext(WalkthroughContext) || {};
const schemaRef = useRef(null);
const params = useParams<{
pageId: string;
@@ -444,26 +429,9 @@ function ActionSidebar({
return <Placeholder>{createMessage(NO_CONNECTIONS)}</Placeholder>;
}
- const handleCloseWalkthrough = () => {
- if (isWalkthroughOpened && popFeature) {
- popFeature();
- }
- };
-
return (
<SideBar>
- <BackToCanvasLink
- id="back-to-canvas"
- kind="secondary"
- onClick={() => {
- history.push(builderURL({ pageId }));
-
- handleCloseWalkthrough();
- }}
- startIcon="arrow-left-line"
- >
- {createMessage(BACK_TO_CANVAS)}
- </BackToCanvasLink>
+ {actionRightPaneBackLink}
{showSchema && (
<CollapsibleSection
diff --git a/app/client/src/pages/Editor/APIEditor/ApiEditorContext.tsx b/app/client/src/pages/Editor/APIEditor/ApiEditorContext.tsx
new file mode 100644
index 000000000000..49ed1ac5dea5
--- /dev/null
+++ b/app/client/src/pages/Editor/APIEditor/ApiEditorContext.tsx
@@ -0,0 +1,65 @@
+import type { ReduxAction } from "@appsmith/constants/ReduxActionConstants";
+import type { PaginationField } from "api/ActionAPI";
+import React, { createContext, useMemo } from "react";
+
+interface SaveActionNameParams {
+ id: string;
+ name: string;
+}
+
+interface ApiEditorContextContextProps {
+ moreActionsMenu?: React.ReactNode;
+ handleDeleteClick: () => void;
+ handleRunClick: (paginationField?: PaginationField) => void;
+ actionRightPaneBackLink?: React.ReactNode;
+ settingsConfig: any;
+ saveActionName?: (
+ params: SaveActionNameParams,
+ ) => ReduxAction<SaveActionNameParams>;
+ closeEditorLink?: React.ReactNode;
+}
+
+type ApiEditorContextProviderProps =
+ React.PropsWithChildren<ApiEditorContextContextProps>;
+
+export const ApiEditorContext = createContext<ApiEditorContextContextProps>(
+ {} as ApiEditorContextContextProps,
+);
+
+export function ApiEditorContextProvider({
+ actionRightPaneBackLink,
+ children,
+ closeEditorLink,
+ handleDeleteClick,
+ handleRunClick,
+ moreActionsMenu,
+ saveActionName,
+ settingsConfig,
+}: ApiEditorContextProviderProps) {
+ const value = useMemo(
+ () => ({
+ actionRightPaneBackLink,
+ closeEditorLink,
+ handleDeleteClick,
+ handleRunClick,
+ moreActionsMenu,
+ saveActionName,
+ settingsConfig,
+ }),
+ [
+ actionRightPaneBackLink,
+ closeEditorLink,
+ handleDeleteClick,
+ handleRunClick,
+ moreActionsMenu,
+ saveActionName,
+ settingsConfig,
+ ],
+ );
+
+ return (
+ <ApiEditorContext.Provider value={value}>
+ {children}
+ </ApiEditorContext.Provider>
+ );
+}
diff --git a/app/client/src/pages/Editor/APIEditor/ApiRightPane.tsx b/app/client/src/pages/Editor/APIEditor/ApiRightPane.tsx
index 29baf5b6de7d..2b4ee57f3923 100644
--- a/app/client/src/pages/Editor/APIEditor/ApiRightPane.tsx
+++ b/app/client/src/pages/Editor/APIEditor/ApiRightPane.tsx
@@ -310,6 +310,7 @@ function ApiRightPane(props: any) {
<SomeWrapper>
<ActionRightPane
actionName={props.actionName}
+ actionRightPaneBackLink={props.actionRightPaneBackLink}
context={DatasourceStructureContext.API_EDITOR}
datasourceId={props.datasourceId}
hasConnections={hasDependencies}
diff --git a/app/client/src/pages/Editor/APIEditor/CommonEditorForm.tsx b/app/client/src/pages/Editor/APIEditor/CommonEditorForm.tsx
index 9d38957309db..346a02df5d29 100644
--- a/app/client/src/pages/Editor/APIEditor/CommonEditorForm.tsx
+++ b/app/client/src/pages/Editor/APIEditor/CommonEditorForm.tsx
@@ -1,4 +1,4 @@
-import React, { useState } from "react";
+import React, { useContext, useState } from "react";
import { useDispatch, useSelector } from "react-redux";
import {
API_EDITOR_TABS,
@@ -18,8 +18,6 @@ import type { AppState } from "@appsmith/reducers";
import ActionNameEditor from "components/editorComponents/ActionNameEditor";
import ActionSettings from "pages/Editor/ActionSettings";
import RequestDropdownField from "components/editorComponents/form/fields/RequestDropdownField";
-import type { ExplorerURLParams } from "@appsmith/pages/Editor/Explorer/helpers";
-import MoreActionsMenu from "../Explorer/Actions/MoreActionsMenu";
import { EditorTheme } from "components/editorComponents/CodeEditor/EditorConfig";
import { Classes } from "design-system-old";
import {
@@ -39,7 +37,6 @@ import {
API_PANE_DUPLICATE_HEADER,
createMessage,
} from "@appsmith/constants/messages";
-import CloseEditor from "components/editorComponents/CloseEditor";
import { useParams } from "react-router";
import DataSourceList from "./ApiRightPane";
import type { Datasource } from "entities/Datasource";
@@ -57,10 +54,10 @@ import { DEFAULT_DATASOURCE_NAME } from "constants/ApiEditorConstants/ApiEditorC
import { useFeatureFlag } from "utils/hooks/useFeatureFlag";
import { FEATURE_FLAG } from "@appsmith/entities/FeatureFlag";
import {
- getHasDeleteActionPermission,
getHasExecuteActionPermission,
getHasManageActionPermission,
} from "@appsmith/utils/BusinessFeatures/permissionPageHelpers";
+import { ApiEditorContext } from "./ApiEditorContext";
const Form = styled.form`
position: relative;
@@ -206,6 +203,7 @@ type CommonFormPropsWithExtraParams = CommonFormProps & {
handleSubmit: any;
// defaultSelectedTabIndex
defaultTabSelected?: number;
+ closeEditorLink?: React.ReactNode;
};
export const NameWrapper = styled.div`
@@ -498,12 +496,15 @@ function CommonEditorForm(props: CommonFormPropsWithExtraParams) {
const index = Object.values(API_EDITOR_TABS).indexOf(value);
dispatch(setApiPaneConfigSelectedTabIndex(index));
};
+ const { actionRightPaneBackLink, moreActionsMenu, saveActionName } =
+ useContext(ApiEditorContext);
const {
actionConfigurationHeaders,
actionConfigurationParams,
actionName,
autoGeneratedActionConfigHeaders,
+ closeEditorLink,
currentActionDatasourceId,
formName,
handleSubmit,
@@ -532,7 +533,6 @@ function CommonEditorForm(props: CommonFormPropsWithExtraParams) {
const currentActionConfig: Action | undefined = actions.find(
(action) => action.id === params.apiId || action.id === params.queryId,
);
- const { pageId } = useParams<ExplorerURLParams>();
const isFeatureEnabled = useFeatureFlag(FEATURE_FLAG.license_gac_enabled);
const isChangePermitted = getHasManageActionPermission(
isFeatureEnabled,
@@ -542,10 +542,6 @@ function CommonEditorForm(props: CommonFormPropsWithExtraParams) {
isFeatureEnabled,
currentActionConfig?.userPermissions,
);
- const isDeletePermitted = getHasDeleteActionPermission(
- isFeatureEnabled,
- currentActionConfig?.userPermissions,
- );
const plugin = useSelector((state: AppState) =>
getPlugin(state, pluginId ?? ""),
@@ -577,22 +573,19 @@ function CommonEditorForm(props: CommonFormPropsWithExtraParams) {
return (
<MainContainer>
- <CloseEditor />
+ {closeEditorLink}
<Form onSubmit={handleSubmit(noop)}>
<MainConfiguration>
<FormRow className="form-row-header">
<NameWrapper className="t--nameOfApi">
- <ActionNameEditor disabled={!isChangePermitted} page="API_PANE" />
+ <ActionNameEditor
+ disabled={!isChangePermitted}
+ page="API_PANE"
+ saveActionName={saveActionName}
+ />
</NameWrapper>
<ActionButtons className="t--formActionButtons">
- <MoreActionsMenu
- className="t--more-action-menu"
- id={currentActionConfig ? currentActionConfig.id : ""}
- isChangePermitted={isChangePermitted}
- isDeletePermitted={isDeletePermitted}
- name={currentActionConfig ? currentActionConfig.name : ""}
- pageId={pageId}
- />
+ {moreActionsMenu}
<Button
className="t--apiFormRunBtn"
isDisabled={blockExecution}
@@ -742,6 +735,7 @@ function CommonEditorForm(props: CommonFormPropsWithExtraParams) {
</SecondaryWrapper>
<DataSourceList
actionName={actionName}
+ actionRightPaneBackLink={actionRightPaneBackLink}
applicationId={props.applicationId}
currentActionDatasourceId={currentActionDatasourceId}
currentPageId={props.currentPageId}
diff --git a/app/client/src/pages/Editor/APIEditor/CurlImportEditor.tsx b/app/client/src/pages/Editor/APIEditor/CurlImportEditor.tsx
new file mode 100644
index 000000000000..b00baebfbec4
--- /dev/null
+++ b/app/client/src/pages/Editor/APIEditor/CurlImportEditor.tsx
@@ -0,0 +1,41 @@
+import React, { useMemo } from "react";
+
+import CurlImportForm from "./CurlImportForm";
+import { createNewApiName } from "utils/AppsmithUtils";
+import { curlImportSubmitHandler } from "./helpers";
+import { getActions } from "@appsmith/selectors/entitiesSelector";
+import { getIsImportingCurl } from "selectors/ui";
+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";
+
+type CurlImportEditorProps = RouteComponentProps<BuilderRouteParams>;
+
+function CurlImportEditor(props: CurlImportEditorProps) {
+ const actions = useSelector(getActions);
+ const { pageId } = props.match.params;
+
+ const showDebugger = useSelector(showDebuggerFlag);
+ const isImportingCurl = useSelector(getIsImportingCurl);
+
+ const initialFormValues = {
+ pageId,
+ name: createNewApiName(actions, pageId),
+ };
+
+ const closeEditorLink = useMemo(() => <CloseEditor />, []);
+
+ return (
+ <CurlImportForm
+ closeEditorLink={closeEditorLink}
+ curlImportSubmitHandler={curlImportSubmitHandler}
+ initialValues={initialFormValues}
+ isImportingCurl={isImportingCurl}
+ showDebugger={showDebugger}
+ />
+ );
+}
+
+export default CurlImportEditor;
diff --git a/app/client/src/pages/Editor/APIEditor/CurlImportForm.tsx b/app/client/src/pages/Editor/APIEditor/CurlImportForm.tsx
index 9c8f1b6240f9..24dc0cec5043 100644
--- a/app/client/src/pages/Editor/APIEditor/CurlImportForm.tsx
+++ b/app/client/src/pages/Editor/APIEditor/CurlImportForm.tsx
@@ -1,26 +1,17 @@
import React from "react";
import type { InjectedFormProps } from "redux-form";
import { reduxForm, Form, Field } from "redux-form";
-import { connect } from "react-redux";
-import type { RouteComponentProps } from "react-router";
-import { withRouter } from "react-router";
import styled from "styled-components";
-import type { AppState } from "@appsmith/reducers";
-import type { ActionDataState } from "@appsmith/reducers/entityReducers/actionsReducer";
import { CURL_IMPORT_FORM } from "@appsmith/constants/forms";
-import type { BuilderRouteParams } from "constants/routes";
import type { curlImportFormValues } from "./helpers";
import { curlImportSubmitHandler } from "./helpers";
-import { createNewApiName } from "utils/AppsmithUtils";
import CurlLogo from "assets/images/Curl-logo.svg";
-import CloseEditor from "components/editorComponents/CloseEditor";
import { Button } from "design-system";
import FormRow from "components/editorComponents/FormRow";
import Debugger, {
ResizerContentContainer,
ResizerMainContainer,
} from "../DataSourceEditor/Debugger";
-import { showDebuggerFlag } from "selectors/debuggerSelectors";
const MainConfiguration = styled.div`
padding: var(--ads-v2-spaces-4) var(--ads-v2-spaces-7);
@@ -99,25 +90,28 @@ const MainContainer = styled.div`
padding: 0px var(--ads-v2-spaces-7);
}
`;
-interface ReduxStateProps {
- actions: ActionDataState;
- initialValues: Record<string, unknown>;
+
+interface OwnProps {
isImportingCurl: boolean;
showDebugger: boolean;
+ curlImportSubmitHandler: (
+ values: curlImportFormValues,
+ dispatch: any,
+ ) => void;
+ initialValues: Record<string, unknown>;
+ closeEditorLink?: React.ReactNode;
}
-export type StateAndRouteProps = ReduxStateProps &
- RouteComponentProps<BuilderRouteParams>;
-
-type Props = StateAndRouteProps &
- InjectedFormProps<curlImportFormValues, StateAndRouteProps>;
+type Props = OwnProps & InjectedFormProps<curlImportFormValues, OwnProps>;
class CurlImportForm extends React.Component<Props> {
render() {
- const { handleSubmit, isImportingCurl, showDebugger } = this.props;
+ const { closeEditorLink, handleSubmit, isImportingCurl, showDebugger } =
+ this.props;
+
return (
<MainContainer>
- <CloseEditor />
+ {closeEditorLink}
<MainConfiguration>
<FormRow className="form-row-header">
<div
@@ -171,35 +165,6 @@ class CurlImportForm extends React.Component<Props> {
}
}
-const mapStateToProps = (state: AppState, props: Props): ReduxStateProps => {
- const { pageId: destinationPageId } = props.match.params;
-
- // Debugger render flag
- const showDebugger = showDebuggerFlag(state);
-
- if (destinationPageId) {
- return {
- actions: state.entities.actions,
- initialValues: {
- pageId: destinationPageId,
- name: createNewApiName(state.entities.actions, destinationPageId),
- },
- isImportingCurl: state.ui.imports.isImportingCurl,
- showDebugger,
- };
- }
- return {
- actions: state.entities.actions,
- initialValues: {},
- isImportingCurl: state.ui.imports.isImportingCurl,
- showDebugger,
- };
-};
-
-export default withRouter(
- connect(mapStateToProps)(
- reduxForm<curlImportFormValues, StateAndRouteProps>({
- form: CURL_IMPORT_FORM,
- })(CurlImportForm),
- ),
-);
+export default reduxForm<curlImportFormValues, OwnProps>({
+ form: CURL_IMPORT_FORM,
+})(CurlImportForm);
diff --git a/app/client/src/pages/Editor/APIEditor/Editor.tsx b/app/client/src/pages/Editor/APIEditor/Editor.tsx
new file mode 100644
index 000000000000..1ee0455fc624
--- /dev/null
+++ b/app/client/src/pages/Editor/APIEditor/Editor.tsx
@@ -0,0 +1,276 @@
+import React from "react";
+import { connect } from "react-redux";
+import { submit } from "redux-form";
+import RestApiEditorForm from "./RestAPIForm";
+import RapidApiEditorForm from "./RapidApiEditorForm";
+import type { AppState } from "@appsmith/reducers";
+import type { RouteComponentProps } from "react-router";
+import type {
+ ActionData,
+ ActionDataState,
+} from "@appsmith/reducers/entityReducers/actionsReducer";
+import _ from "lodash";
+import { getCurrentApplication } from "@appsmith/selectors/applicationSelectors";
+import {
+ getActionById,
+ getCurrentApplicationId,
+ getCurrentPageName,
+} from "selectors/editorSelectors";
+import type { Plugin } from "api/PluginApi";
+import type { Action, PaginationType, RapidApiAction } from "entities/Action";
+import { PluginPackageName } from "entities/Action";
+import { getApiName } from "selectors/formSelectors";
+import Spinner from "components/editorComponents/Spinner";
+import type { CSSProperties } from "styled-components";
+import styled from "styled-components";
+import CenteredWrapper from "components/designSystems/appsmith/CenteredWrapper";
+import { changeApi } from "actions/apiPaneActions";
+import PerformanceTracker, {
+ PerformanceTransactionName,
+} from "utils/PerformanceTracker";
+import * as Sentry from "@sentry/react";
+import EntityNotFoundPane from "pages/Editor/EntityNotFoundPane";
+import type { ApplicationPayload } from "@appsmith/constants/ReduxActionConstants";
+import { getPageList, getPlugins } from "@appsmith/selectors/entitiesSelector";
+import history from "utils/history";
+import { saasEditorApiIdURL } from "@appsmith/RouteBuilder";
+import GraphQLEditorForm from "./GraphQL/GraphQLEditorForm";
+import type { APIEditorRouteParams } from "constants/routes";
+import { ApiEditorContext } from "./ApiEditorContext";
+
+const LoadingContainer = styled(CenteredWrapper)`
+ height: 50%;
+`;
+
+interface ReduxStateProps {
+ actions: ActionDataState;
+ isRunning: boolean;
+ isDeleting: boolean;
+ isCreating: boolean;
+ apiName: string;
+ currentApplication?: ApplicationPayload;
+ currentPageName: string | undefined;
+ pages: any;
+ plugins: Plugin[];
+ pluginId: any;
+ apiAction: Action | ActionData | RapidApiAction | undefined;
+ paginationType: PaginationType;
+ applicationId: string;
+}
+
+interface OwnProps {
+ isEditorInitialized: boolean;
+}
+
+interface ReduxActionProps {
+ submitForm: (name: string) => void;
+ changeAPIPage: (apiId: string, isSaas: boolean) => void;
+}
+
+function getPackageNameFromPluginId(pluginId: string, plugins: Plugin[]) {
+ const plugin = plugins.find((plugin: Plugin) => plugin.id === pluginId);
+ return plugin?.packageName;
+}
+
+type Props = ReduxActionProps &
+ ReduxStateProps &
+ RouteComponentProps<APIEditorRouteParams> &
+ OwnProps;
+
+class ApiEditor extends React.Component<Props> {
+ static contextType = ApiEditorContext;
+ context!: React.ContextType<typeof ApiEditorContext>;
+
+ componentDidMount() {
+ PerformanceTracker.stopTracking(PerformanceTransactionName.OPEN_ACTION, {
+ actionType: "API",
+ });
+ const type = this.getFormName();
+ if (this.props.match.params.apiId) {
+ this.props.changeAPIPage(this.props.match.params.apiId, type === "SAAS");
+ }
+ }
+
+ getFormName = () => {
+ const plugins = this.props.plugins;
+ const pluginId = this.props.pluginId;
+ const plugin =
+ plugins &&
+ plugins.find((plug) => {
+ if (plug.id === pluginId) return plug;
+ });
+ return plugin && plugin.type;
+ };
+
+ componentDidUpdate(prevProps: Props) {
+ if (prevProps.isRunning && !this.props.isRunning) {
+ PerformanceTracker.stopTracking(PerformanceTransactionName.RUN_API_CLICK);
+ }
+ if (prevProps.match.params.apiId !== this.props.match.params.apiId) {
+ const type = this.getFormName();
+ this.props.changeAPIPage(
+ this.props.match.params.apiId || "",
+ type === "SAAS",
+ );
+ }
+ }
+
+ getPluginUiComponentOfId = (
+ id: string,
+ plugins: Plugin[],
+ ): string | undefined => {
+ const plugin = plugins.find((plugin) => plugin.id === id);
+ if (!plugin) return undefined;
+ return plugin.uiComponent;
+ };
+
+ getPluginUiComponentOfName = (plugins: Plugin[]): string | undefined => {
+ const plugin = plugins.find(
+ (plugin) => plugin.packageName === PluginPackageName.REST_API,
+ );
+ if (!plugin) return undefined;
+ return plugin.uiComponent;
+ };
+
+ render() {
+ const {
+ isCreating,
+ isDeleting,
+ isEditorInitialized,
+ isRunning,
+ match: {
+ params: { apiId },
+ },
+ paginationType,
+ pluginId,
+ plugins,
+ } = this.props;
+ if (!pluginId && apiId) {
+ return <EntityNotFoundPane />;
+ }
+ if (isCreating || !isEditorInitialized) {
+ return (
+ <LoadingContainer>
+ <Spinner size={30} />
+ </LoadingContainer>
+ );
+ }
+
+ let formUiComponent: string | undefined;
+ if (apiId) {
+ if (pluginId) {
+ formUiComponent = this.getPluginUiComponentOfId(pluginId, plugins);
+ } else {
+ formUiComponent = this.getPluginUiComponentOfName(plugins);
+ }
+ }
+
+ return (
+ <div style={formStyles}>
+ {formUiComponent === "ApiEditorForm" && (
+ <RestApiEditorForm
+ apiName={this.props.apiName}
+ appName={
+ this.props.currentApplication
+ ? this.props.currentApplication.name
+ : ""
+ }
+ isDeleting={isDeleting}
+ isRunning={isRunning}
+ onDeleteClick={this.context.handleDeleteClick}
+ onRunClick={this.context.handleRunClick}
+ paginationType={paginationType}
+ pluginId={pluginId}
+ settingsConfig={this.context.settingsConfig}
+ />
+ )}
+ {formUiComponent === "GraphQLEditorForm" && (
+ <GraphQLEditorForm
+ apiName={this.props.apiName}
+ appName={
+ this.props.currentApplication
+ ? this.props.currentApplication.name
+ : ""
+ }
+ isDeleting={isDeleting}
+ isRunning={isRunning}
+ match={this.props.match}
+ onDeleteClick={this.context.handleDeleteClick}
+ onRunClick={this.context.handleRunClick}
+ paginationType={paginationType}
+ pluginId={pluginId}
+ settingsConfig={this.context.settingsConfig}
+ />
+ )}
+ {formUiComponent === "RapidApiEditorForm" && (
+ <RapidApiEditorForm
+ apiId={this.props.match.params.apiId || ""}
+ apiName={this.props.apiName}
+ appName={
+ this.props.currentApplication
+ ? this.props.currentApplication.name
+ : ""
+ }
+ isDeleting={isDeleting}
+ isRunning={isRunning}
+ location={this.props.location}
+ onDeleteClick={this.context.handleDeleteClick}
+ onRunClick={this.context.handleRunClick}
+ paginationType={paginationType}
+ />
+ )}
+ {formUiComponent === "SaaSEditorForm" &&
+ history.push(
+ saasEditorApiIdURL({
+ pageId: this.props.match.params.pageId,
+ pluginPackageName:
+ getPackageNameFromPluginId(
+ this.props.pluginId,
+ this.props.plugins,
+ ) ?? "",
+ apiId: this.props.match.params.apiId || "",
+ }),
+ )}
+ </div>
+ );
+ }
+}
+
+const formStyles: CSSProperties = {
+ position: "relative",
+ height: "100%",
+ display: "flex",
+ flexDirection: "column",
+};
+
+const mapStateToProps = (state: AppState, props: any): ReduxStateProps => {
+ const apiAction = getActionById(state, props);
+ const apiName = getApiName(state, props.match.params.apiId);
+ const { isCreating, isDeleting, isRunning } = state.ui.apiPane;
+ const pluginId = _.get(apiAction, "pluginId", "");
+ return {
+ actions: state.entities.actions,
+ currentApplication: getCurrentApplication(state),
+ currentPageName: getCurrentPageName(state),
+ pages: getPageList(state),
+ apiName: apiName || "",
+ plugins: getPlugins(state),
+ pluginId,
+ paginationType: _.get(apiAction, "actionConfiguration.paginationType"),
+ apiAction,
+ isRunning: isRunning[props.match.params.apiId],
+ isDeleting: isDeleting[props.match.params.apiId],
+ isCreating: isCreating,
+ applicationId: getCurrentApplicationId(state),
+ };
+};
+
+const mapDispatchToProps = (dispatch: any): ReduxActionProps => ({
+ submitForm: (name: string) => dispatch(submit(name)),
+ changeAPIPage: (actionId: string, isSaas: boolean) =>
+ dispatch(changeApi(actionId, isSaas)),
+});
+
+export default Sentry.withProfiler(
+ connect(mapStateToProps, mapDispatchToProps)(ApiEditor),
+);
diff --git a/app/client/src/pages/Editor/APIEditor/GraphQL/GraphQLEditorForm.tsx b/app/client/src/pages/Editor/APIEditor/GraphQL/GraphQLEditorForm.tsx
index d953fd873583..15b07d90a136 100644
--- a/app/client/src/pages/Editor/APIEditor/GraphQL/GraphQLEditorForm.tsx
+++ b/app/client/src/pages/Editor/APIEditor/GraphQL/GraphQLEditorForm.tsx
@@ -1,4 +1,4 @@
-import React, { useCallback, useRef } from "react";
+import React, { useCallback, useContext, useRef } from "react";
import { connect } from "react-redux";
import type { InjectedFormProps } from "redux-form";
import { change, formValueSelector, reduxForm } from "redux-form";
@@ -21,6 +21,7 @@ import QueryEditor from "./QueryEditor";
import { tailwindLayers } from "constants/Layers";
import VariableEditor from "./VariableEditor";
import Pagination from "./Pagination";
+import { ApiEditorContext } from "../ApiEditorContext";
const ResizeableDiv = styled.div`
display: flex;
@@ -81,6 +82,8 @@ function GraphQLEditorForm(props: Props) {
DEFAULT_GRAPHQL_VARIABLE_WIDTH,
);
+ const { closeEditorLink } = useContext(ApiEditorContext);
+
/**
* Variable Editor's resizeable handler for the changing of width
*/
@@ -131,6 +134,7 @@ function GraphQLEditorForm(props: Props) {
</ResizeableDiv>
</BodyWrapper>
}
+ closeEditorLink={closeEditorLink}
defaultTabSelected={2}
formName={API_EDITOR_FORM_NAME}
paginationUIComponent={
diff --git a/app/client/src/pages/Editor/APIEditor/RapidApiEditorForm.tsx b/app/client/src/pages/Editor/APIEditor/RapidApiEditorForm.tsx
index 9f7649b4b14e..d8389cecf68f 100644
--- a/app/client/src/pages/Editor/APIEditor/RapidApiEditorForm.tsx
+++ b/app/client/src/pages/Editor/APIEditor/RapidApiEditorForm.tsx
@@ -1,4 +1,4 @@
-import React from "react";
+import React, { useContext } from "react";
import { connect } from "react-redux";
import type { InjectedFormProps } from "redux-form";
import { reduxForm, formValueSelector } from "redux-form";
@@ -22,6 +22,7 @@ import { getActionData } from "@appsmith/selectors/entitiesSelector";
import type { AppState } from "@appsmith/reducers";
import { Icon } from "design-system";
import { showDebuggerFlag } from "selectors/debuggerSelectors";
+import { ApiEditorContext } from "./ApiEditorContext";
const Form = styled.form`
display: flex;
@@ -142,6 +143,8 @@ function RapidApiEditorForm(props: Props) {
templateId,
} = props;
+ const { saveActionName } = useContext(ApiEditorContext);
+
const postbodyResponsePresent =
templateId &&
actionConfiguration &&
@@ -158,7 +161,7 @@ function RapidApiEditorForm(props: Props) {
<MainConfiguration>
<FormRow>
<NameWrapper>
- <ActionNameEditor />
+ <ActionNameEditor saveActionName={saveActionName} />
<a
className="t--apiDocumentationLink"
href={providerURL && `http://${providerURL}`}
diff --git a/app/client/src/pages/Editor/APIEditor/RestAPIForm.tsx b/app/client/src/pages/Editor/APIEditor/RestAPIForm.tsx
index 11a98c177573..b593c4e1f090 100644
--- a/app/client/src/pages/Editor/APIEditor/RestAPIForm.tsx
+++ b/app/client/src/pages/Editor/APIEditor/RestAPIForm.tsx
@@ -1,4 +1,4 @@
-import React from "react";
+import React, { useContext } from "react";
import { connect } from "react-redux";
import type { InjectedFormProps } from "redux-form";
import { change, formValueSelector, reduxForm } from "redux-form";
@@ -24,6 +24,7 @@ import type { CommonFormProps } from "./CommonEditorForm";
import CommonEditorForm from "./CommonEditorForm";
import Pagination from "./Pagination";
import { getCurrentEnvironmentId } from "@appsmith/selectors/environmentSelectors";
+import { ApiEditorContext } from "./ApiEditorContext";
const NoBodyMessage = styled.div`
margin-top: 20px;
@@ -42,6 +43,7 @@ type APIFormProps = {
type Props = APIFormProps & InjectedFormProps<Action, APIFormProps>;
function ApiEditorForm(props: Props) {
+ const { closeEditorLink } = useContext(ApiEditorContext);
const { actionName, httpMethodFromForm } = props;
const allowPostBody = httpMethodFromForm;
const theme = EditorTheme.LIGHT;
@@ -58,6 +60,7 @@ function ApiEditorForm(props: Props) {
</NoBodyMessage>
)
}
+ closeEditorLink={closeEditorLink}
formName={API_EDITOR_FORM_NAME}
paginationUIComponent={
<Pagination
diff --git a/app/client/src/pages/Editor/APIEditor/index.tsx b/app/client/src/pages/Editor/APIEditor/index.tsx
index 3dc41400b2a5..83465877622a 100644
--- a/app/client/src/pages/Editor/APIEditor/index.tsx
+++ b/app/client/src/pages/Editor/APIEditor/index.tsx
@@ -1,318 +1,129 @@
-import React from "react";
-import { connect } from "react-redux";
-import { submit } from "redux-form";
-import RestApiEditorForm from "./RestAPIForm";
-import RapidApiEditorForm from "./RapidApiEditorForm";
-import { deleteAction, runAction } from "actions/pluginActionActions";
-import type { PaginationField } from "api/ActionAPI";
-import type { AppState } from "@appsmith/reducers";
+import React, { useCallback, useMemo } from "react";
+import { useDispatch, useSelector } from "react-redux";
import type { RouteComponentProps } from "react-router";
-import type {
- ActionData,
- ActionDataState,
-} from "@appsmith/reducers/entityReducers/actionsReducer";
-import _ from "lodash";
-import { getCurrentApplication } from "@appsmith/selectors/applicationSelectors";
+
+import {
+ getPageList,
+ getPluginSettingConfigs,
+ getPlugins,
+} from "@appsmith/selectors/entitiesSelector";
+import { deleteAction, runAction } from "actions/pluginActionActions";
import AnalyticsUtil from "utils/AnalyticsUtil";
+import Editor from "./Editor";
+import BackToCanvas from "components/common/BackToCanvas";
+import MoreActionsMenu from "../Explorer/Actions/MoreActionsMenu";
+import { getIsEditorInitialized } from "selectors/editorSelectors";
+import { getAction } from "@appsmith/selectors/entitiesSelector";
+import type { APIEditorRouteParams } from "constants/routes";
import {
- getActionById,
- getCurrentApplicationId,
- getCurrentPageName,
- getIsEditorInitialized,
-} from "selectors/editorSelectors";
-import type { Plugin } from "api/PluginApi";
-import type { Action, PaginationType, RapidApiAction } from "entities/Action";
-import { PluginPackageName } from "entities/Action";
-import { getApiName } from "selectors/formSelectors";
-import Spinner from "components/editorComponents/Spinner";
-import type { CSSProperties } from "styled-components";
-import styled from "styled-components";
-import CenteredWrapper from "components/designSystems/appsmith/CenteredWrapper";
-import { changeApi } from "actions/apiPaneActions";
+ getHasDeleteActionPermission,
+ getHasManageActionPermission,
+} from "@appsmith/utils/BusinessFeatures/permissionPageHelpers";
+import { FEATURE_FLAG } from "@appsmith/entities/FeatureFlag";
+import { useFeatureFlag } from "utils/hooks/useFeatureFlag";
+import { ApiEditorContextProvider } from "./ApiEditorContext";
+import type { PaginationField } from "api/ActionAPI";
+import { get } from "lodash";
import PerformanceTracker, {
PerformanceTransactionName,
} from "utils/PerformanceTracker";
-import * as Sentry from "@sentry/react";
-import EntityNotFoundPane from "pages/Editor/EntityNotFoundPane";
-import type { ApplicationPayload } from "@appsmith/constants/ReduxActionConstants";
-import {
- getPageList,
- getPlugins,
- getPluginSettingConfigs,
-} from "@appsmith/selectors/entitiesSelector";
-import history from "utils/history";
-import { saasEditorApiIdURL } from "@appsmith/RouteBuilder";
-import GraphQLEditorForm from "./GraphQL/GraphQLEditorForm";
+import CloseEditor from "components/editorComponents/CloseEditor";
-const LoadingContainer = styled(CenteredWrapper)`
- height: 50%;
-`;
-
-interface ReduxStateProps {
- actions: ActionDataState;
- isRunning: boolean;
- isDeleting: boolean;
- isCreating: boolean;
- apiName: string;
- currentApplication?: ApplicationPayload;
- currentPageName: string | undefined;
- pages: any;
- plugins: Plugin[];
- pluginId: any;
- settingsConfig: any;
- apiAction: Action | ActionData | RapidApiAction | undefined;
- paginationType: PaginationType;
- isEditorInitialized: boolean;
- applicationId: string;
-}
-interface ReduxActionProps {
- submitForm: (name: string) => void;
- runAction: (id: string, paginationField?: PaginationField) => void;
- deleteAction: (id: string, name: string) => void;
- changeAPIPage: (apiId: string, isSaas: boolean) => void;
-}
+type ApiEditorWrapperProps = RouteComponentProps<APIEditorRouteParams>;
function getPageName(pages: any, pageId: string) {
const page = pages.find((page: any) => page.pageId === pageId);
return page ? page.pageName : "";
}
-function getPackageNameFromPluginId(pluginId: string, plugins: Plugin[]) {
- const plugin = plugins.find((plugin: Plugin) => plugin.id === pluginId);
- return plugin?.packageName;
-}
-
-type Props = ReduxActionProps &
- ReduxStateProps &
- RouteComponentProps<{ apiId: string; pageId: string }>;
-
-class ApiEditor extends React.Component<Props> {
- componentDidMount() {
- PerformanceTracker.stopTracking(PerformanceTransactionName.OPEN_ACTION, {
- actionType: "API",
- });
- const type = this.getFormName();
- this.props.changeAPIPage(this.props.match.params.apiId, type === "SAAS");
- }
- handleDeleteClick = () => {
- const pageName = getPageName(
- this.props.pages,
- this.props.match.params.pageId,
- );
- AnalyticsUtil.logEvent("DELETE_API_CLICK", {
- apiName: this.props.apiName,
- apiID: this.props.match.params.apiId,
- pageName: pageName,
- });
- this.props.deleteAction(this.props.match.params.apiId, this.props.apiName);
- };
-
- getFormName = () => {
- const plugins = this.props.plugins;
- const pluginId = this.props.pluginId;
- const plugin =
- plugins &&
- plugins.find((plug) => {
- if (plug.id === pluginId) return plug;
+function ApiEditorWrapper(props: ApiEditorWrapperProps) {
+ const { apiId = "", pageId } = props.match.params;
+ const dispatch = useDispatch();
+ const isEditorInitialized = useSelector(getIsEditorInitialized);
+ const action = useSelector((state) => getAction(state, apiId));
+ const apiName = action?.name || "";
+ const pluginId = get(action, "pluginId", "");
+ const datasourceId = action?.datasource.id || "";
+ const plugins = useSelector(getPlugins);
+ const pages = useSelector(getPageList);
+ const pageName = getPageName(pages, pageId);
+ const settingsConfig = useSelector((state) =>
+ getPluginSettingConfigs(state, pluginId),
+ );
+ const isFeatureEnabled = useFeatureFlag(FEATURE_FLAG.license_gac_enabled);
+
+ const isChangePermitted = getHasManageActionPermission(
+ isFeatureEnabled,
+ action?.userPermissions,
+ );
+ const isDeletePermitted = getHasDeleteActionPermission(
+ isFeatureEnabled,
+ action?.userPermissions,
+ );
+
+ const moreActionsMenu = useMemo(
+ () => (
+ <MoreActionsMenu
+ className="t--more-action-menu"
+ id={action ? action.id : ""}
+ isChangePermitted={isChangePermitted}
+ isDeletePermitted={isDeletePermitted}
+ name={action ? action.name : ""}
+ pageId={pageId}
+ />
+ ),
+ [action?.id, action?.name, isChangePermitted, isDeletePermitted, pageId],
+ );
+
+ const handleRunClick = useCallback(
+ (paginationField?: PaginationField) => {
+ const pluginName = plugins.find((plugin) => plugin.id === pluginId)?.name;
+ PerformanceTracker.startTracking(
+ PerformanceTransactionName.RUN_API_CLICK,
+ {
+ apiId,
+ },
+ );
+ AnalyticsUtil.logEvent("RUN_API_CLICK", {
+ apiName,
+ apiID: apiId,
+ pageName: pageName,
+ datasourceId,
+ pluginName: pluginName,
+ isMock: false, // as mock db exists only for postgres and mongo plugins
});
- return plugin && plugin.type;
- };
+ dispatch(runAction(apiId, paginationField));
+ },
+ [apiId, apiName, pageName, getPageName, plugins, pluginId, datasourceId],
+ );
- componentDidUpdate(prevProps: Props) {
- if (prevProps.isRunning && !this.props.isRunning) {
- PerformanceTracker.stopTracking(PerformanceTransactionName.RUN_API_CLICK);
- }
- if (prevProps.match.params.apiId !== this.props.match.params.apiId) {
- const type = this.getFormName();
- this.props.changeAPIPage(this.props.match.params.apiId, type === "SAAS");
- }
- }
+ const actionRightPaneBackLink = useMemo(() => {
+ return <BackToCanvas pageId={pageId} />;
+ }, [pageId]);
- handleRunClick = (paginationField?: PaginationField) => {
- const pageName = getPageName(
- this.props.pages,
- this.props.match.params.pageId,
- );
- const pluginName = this.props.plugins.find(
- (plugin) => plugin.id === this.props.pluginId,
- )?.name;
- PerformanceTracker.startTracking(PerformanceTransactionName.RUN_API_CLICK, {
- apiId: this.props.match.params.apiId,
- });
- AnalyticsUtil.logEvent("RUN_API_CLICK", {
- apiName: this.props.apiName,
- apiID: this.props.match.params.apiId,
- pageName: pageName,
- datasourceId: (this.props?.apiAction as any)?.datasource?.id,
- pluginName: pluginName,
- isMock: false, // as mock db exists only for postgres and mongo plugins
+ const handleDeleteClick = useCallback(() => {
+ AnalyticsUtil.logEvent("DELETE_API_CLICK", {
+ apiName,
+ apiID: apiId,
+ pageName,
});
- this.props.runAction(this.props.match.params.apiId, paginationField);
- };
-
- getPluginUiComponentOfId = (
- id: string,
- plugins: Plugin[],
- ): string | undefined => {
- const plugin = plugins.find((plugin) => plugin.id === id);
- if (!plugin) return undefined;
- return plugin.uiComponent;
- };
-
- getPluginUiComponentOfName = (plugins: Plugin[]): string | undefined => {
- const plugin = plugins.find(
- (plugin) => plugin.packageName === PluginPackageName.REST_API,
- );
- if (!plugin) return undefined;
- return plugin.uiComponent;
- };
-
- render() {
- const {
- isCreating,
- isDeleting,
- isEditorInitialized,
- isRunning,
- match: {
- params: { apiId },
- },
- paginationType,
- pluginId,
- plugins,
- } = this.props;
- if (!pluginId && apiId) {
- return <EntityNotFoundPane />;
- }
- if (isCreating || !isEditorInitialized) {
- return (
- <LoadingContainer>
- <Spinner size={30} />
- </LoadingContainer>
- );
- }
-
- let formUiComponent: string | undefined;
- if (apiId) {
- if (pluginId) {
- formUiComponent = this.getPluginUiComponentOfId(pluginId, plugins);
- } else {
- formUiComponent = this.getPluginUiComponentOfName(plugins);
- }
- }
-
- return (
- <div style={formStyles}>
- {formUiComponent === "ApiEditorForm" && (
- <RestApiEditorForm
- apiName={this.props.apiName}
- appName={
- this.props.currentApplication
- ? this.props.currentApplication.name
- : ""
- }
- isDeleting={isDeleting}
- isRunning={isRunning}
- onDeleteClick={this.handleDeleteClick}
- onRunClick={this.handleRunClick}
- paginationType={paginationType}
- pluginId={pluginId}
- settingsConfig={this.props.settingsConfig}
- />
- )}
- {formUiComponent === "GraphQLEditorForm" && (
- <GraphQLEditorForm
- apiName={this.props.apiName}
- appName={
- this.props.currentApplication
- ? this.props.currentApplication.name
- : ""
- }
- isDeleting={isDeleting}
- isRunning={isRunning}
- match={this.props.match}
- onDeleteClick={this.handleDeleteClick}
- onRunClick={this.handleRunClick}
- paginationType={paginationType}
- pluginId={pluginId}
- settingsConfig={this.props.settingsConfig}
- />
- )}
- {formUiComponent === "RapidApiEditorForm" && (
- <RapidApiEditorForm
- apiId={this.props.match.params.apiId}
- apiName={this.props.apiName}
- appName={
- this.props.currentApplication
- ? this.props.currentApplication.name
- : ""
- }
- isDeleting={isDeleting}
- isRunning={isRunning}
- location={this.props.location}
- onDeleteClick={this.handleDeleteClick}
- onRunClick={this.handleRunClick}
- paginationType={paginationType}
- />
- )}
- {formUiComponent === "SaaSEditorForm" &&
- history.push(
- saasEditorApiIdURL({
- pageId: this.props.match.params.pageId,
- pluginPackageName:
- getPackageNameFromPluginId(
- this.props.pluginId,
- this.props.plugins,
- ) ?? "",
- apiId: this.props.match.params.apiId,
- }),
- )}
- </div>
- );
- }
+ dispatch(deleteAction({ id: apiId, name: apiName }));
+ }, [getPageName, pages, pageId, apiName]);
+
+ const closeEditorLink = useMemo(() => <CloseEditor />, []);
+
+ return (
+ <ApiEditorContextProvider
+ actionRightPaneBackLink={actionRightPaneBackLink}
+ closeEditorLink={closeEditorLink}
+ handleDeleteClick={handleDeleteClick}
+ handleRunClick={handleRunClick}
+ moreActionsMenu={moreActionsMenu}
+ settingsConfig={settingsConfig}
+ >
+ <Editor {...props} isEditorInitialized={isEditorInitialized} />
+ </ApiEditorContextProvider>
+ );
}
-const formStyles: CSSProperties = {
- position: "relative",
- height: "100%",
- display: "flex",
- flexDirection: "column",
-};
-
-const mapStateToProps = (state: AppState, props: any): ReduxStateProps => {
- const apiAction = getActionById(state, props);
- const apiName = getApiName(state, props.match.params.apiId);
- const { isCreating, isDeleting, isRunning } = state.ui.apiPane;
- const pluginId = _.get(apiAction, "pluginId", "");
- const settingsConfig = getPluginSettingConfigs(state, pluginId);
- return {
- actions: state.entities.actions,
- currentApplication: getCurrentApplication(state),
- currentPageName: getCurrentPageName(state),
- pages: getPageList(state),
- apiName: apiName || "",
- plugins: getPlugins(state),
- pluginId,
- settingsConfig,
- paginationType: _.get(apiAction, "actionConfiguration.paginationType"),
- apiAction,
- isRunning: isRunning[props.match.params.apiId],
- isDeleting: isDeleting[props.match.params.apiId],
- isCreating: isCreating,
- isEditorInitialized: getIsEditorInitialized(state),
- applicationId: getCurrentApplicationId(state),
- };
-};
-
-const mapDispatchToProps = (dispatch: any): ReduxActionProps => ({
- submitForm: (name: string) => dispatch(submit(name)),
- runAction: (id: string, paginationField?: PaginationField) =>
- dispatch(runAction(id, paginationField)),
- deleteAction: (id: string, name: string) =>
- dispatch(deleteAction({ id, name })),
- changeAPIPage: (actionId: string, isSaas: boolean) =>
- dispatch(changeApi(actionId, isSaas)),
-});
-
-export default Sentry.withProfiler(
- connect(mapStateToProps, mapDispatchToProps)(ApiEditor),
-);
+export default ApiEditorWrapper;
diff --git a/app/client/src/pages/Editor/QueryEditor/Editor.tsx b/app/client/src/pages/Editor/QueryEditor/Editor.tsx
new file mode 100644
index 000000000000..789a427956ce
--- /dev/null
+++ b/app/client/src/pages/Editor/QueryEditor/Editor.tsx
@@ -0,0 +1,352 @@
+import React from "react";
+import type { RouteComponentProps } from "react-router";
+import { connect } from "react-redux";
+import { getFormValues } from "redux-form";
+import styled from "styled-components";
+import type { QueryEditorRouteParams } from "constants/routes";
+import QueryEditorForm from "./Form";
+import type { UpdateActionPropertyActionPayload } from "actions/pluginActionActions";
+import {
+ deleteAction,
+ runAction,
+ setActionResponseDisplayFormat,
+ setActionProperty,
+} from "actions/pluginActionActions";
+import type { AppState } from "@appsmith/reducers";
+import { getCurrentApplicationId } from "selectors/editorSelectors";
+import { QUERY_EDITOR_FORM_NAME } from "@appsmith/constants/forms";
+import type { Plugin } from "api/PluginApi";
+import { UIComponentTypes } from "api/PluginApi";
+import type { Datasource } from "entities/Datasource";
+import {
+ getPluginIdsOfPackageNames,
+ getPlugins,
+ getAction,
+ getActionResponses,
+ getDatasourceByPluginId,
+ getDBAndRemoteDatasources,
+} from "@appsmith/selectors/entitiesSelector";
+import { PLUGIN_PACKAGE_DBS } from "constants/QueryEditorConstants";
+import type { QueryAction, SaaSAction } from "entities/Action";
+import Spinner from "components/editorComponents/Spinner";
+import CenteredWrapper from "components/designSystems/appsmith/CenteredWrapper";
+import PerformanceTracker, {
+ PerformanceTransactionName,
+} from "utils/PerformanceTracker";
+import AnalyticsUtil from "utils/AnalyticsUtil";
+import { initFormEvaluations } from "@appsmith/actions/evaluationActions";
+import { getUIComponent } from "./helpers";
+import type { Diff } from "deep-diff";
+import { diff } from "deep-diff";
+import EntityNotFoundPane from "pages/Editor/EntityNotFoundPane";
+import { getConfigInitialValues } from "components/formControls/utils";
+import { merge } from "lodash";
+import { getPathAndValueFromActionDiffObject } from "../../../utils/getPathAndValueFromActionDiffObject";
+import { getCurrentEnvironmentDetails } from "@appsmith/selectors/environmentSelectors";
+import { QueryEditorContext } from "./QueryEditorContext";
+
+const EmptyStateContainer = styled.div`
+ display: flex;
+ height: 100%;
+ font-size: 20px;
+`;
+
+const LoadingContainer = styled(CenteredWrapper)`
+ height: 50%;
+`;
+
+interface ReduxDispatchProps {
+ runAction: (actionId: string) => void;
+ deleteAction: (id: string, name: string) => void;
+ initFormEvaluation: (
+ editorConfig: any,
+ settingConfig: any,
+ formId: string,
+ ) => void;
+ updateActionResponseDisplayFormat: ({
+ field,
+ id,
+ value,
+ }: UpdateActionPropertyActionPayload) => void;
+ setActionProperty: (
+ actionId: string,
+ propertyName: string,
+ value: string,
+ ) => void;
+}
+
+interface ReduxStateProps {
+ plugins: Plugin[];
+ dataSources: Datasource[];
+ isRunning: boolean;
+ isDeleting: boolean;
+ formData: QueryAction | SaaSAction;
+ runErrorMessage: Record<string, string>;
+ pluginId: string | undefined;
+ pluginIds: Array<string> | undefined;
+ responses: any;
+ isCreating: boolean;
+ editorConfig: any;
+ uiComponent: UIComponentTypes;
+ applicationId: string;
+ actionId: string;
+ actionObjectDiff?: any;
+ isSaas: boolean;
+ datasourceId?: string;
+ currentEnvironmentId: string;
+ currentEnvironmentName: string;
+}
+
+type StateAndRouteProps = RouteComponentProps<QueryEditorRouteParams>;
+type OwnProps = StateAndRouteProps & {
+ isEditorInitialized: boolean;
+ settingsConfig: any;
+};
+type Props = ReduxDispatchProps & ReduxStateProps & OwnProps;
+
+class QueryEditor extends React.Component<Props> {
+ static contextType = QueryEditorContext;
+ context!: React.ContextType<typeof QueryEditorContext>;
+
+ constructor(props: Props) {
+ super(props);
+ // Call the first evaluations when the page loads
+ // call evaluations only for queries and not google sheets (which uses apiId)
+ if (this.props.match.params.queryId) {
+ this.props.initFormEvaluation(
+ this.props.editorConfig,
+ this.props.settingsConfig,
+ this.props.match.params.queryId,
+ );
+ }
+ }
+
+ componentDidMount() {
+ // if the current action is non existent, do not dispatch change query page action
+ // this action should only be dispatched when switching from an existent action.
+ if (!this.props.pluginId) return;
+ this.context?.changeQueryPage?.(this.props.actionId);
+
+ // fixes missing where key issue by populating the action with a where object when the component is mounted.
+ if (this.props.isSaas) {
+ const { path = "", value = "" } = {
+ ...getPathAndValueFromActionDiffObject(this.props.actionObjectDiff),
+ };
+ if (value && path) {
+ this.props.setActionProperty(this.props.actionId, path, value);
+ }
+ }
+
+ PerformanceTracker.stopTracking(PerformanceTransactionName.OPEN_ACTION, {
+ actionType: "QUERY",
+ });
+ }
+
+ handleDeleteClick = () => {
+ const { formData } = this.props;
+
+ this.props.deleteAction(this.props.actionId, formData.name);
+ };
+
+ handleRunClick = () => {
+ const { dataSources } = this.props;
+ const datasource = dataSources.find(
+ (datasource) => datasource.id === this.props.datasourceId,
+ );
+ const pluginName = this.props.plugins.find(
+ (plugin) => plugin.id === this.props.pluginId,
+ )?.name;
+ PerformanceTracker.startTracking(
+ PerformanceTransactionName.RUN_QUERY_CLICK,
+ { actionId: this.props.actionId },
+ );
+ AnalyticsUtil.logEvent("RUN_QUERY_CLICK", {
+ actionId: this.props.actionId,
+ dataSourceSize: dataSources.length,
+ environmentId: this.props.currentEnvironmentId,
+ environmentName: this.props.currentEnvironmentName,
+ pluginName: pluginName,
+ datasourceId: datasource?.id,
+ isMock: !!datasource?.isMock,
+ });
+ this.props.runAction(this.props.actionId);
+ };
+
+ componentDidUpdate(prevProps: Props) {
+ if (prevProps.isRunning === true && this.props.isRunning === false) {
+ PerformanceTracker.stopTracking(
+ PerformanceTransactionName.RUN_QUERY_CLICK,
+ );
+ }
+ // Update the page when the queryID is changed by changing the
+ // URL or selecting new query from the query pane
+ // reusing same logic for changing query panes for switching query editor datasources, since the operations are similar.
+ if (
+ prevProps.actionId !== this.props.actionId ||
+ prevProps.pluginId !== this.props.pluginId
+ ) {
+ this.context?.changeQueryPage?.(this.props.actionId);
+ }
+ }
+
+ render() {
+ const {
+ actionId,
+ dataSources,
+ editorConfig,
+ isCreating,
+ isDeleting,
+ isEditorInitialized,
+ isRunning,
+ pluginId,
+ pluginIds,
+ responses,
+ runErrorMessage,
+ uiComponent,
+ updateActionResponseDisplayFormat,
+ } = this.props;
+ const { onCreateDatasourceClick, onEntityNotFoundBackClick } = this.context;
+
+ // if the action can not be found, generate a entity not found page
+ if (!pluginId && actionId) {
+ return <EntityNotFoundPane goBackFn={onEntityNotFoundBackClick} />;
+ }
+
+ if (!pluginIds?.length) {
+ return (
+ <EmptyStateContainer>{"Plugin is not installed"}</EmptyStateContainer>
+ );
+ }
+
+ if (isCreating || !isEditorInitialized) {
+ return (
+ <LoadingContainer>
+ <Spinner size={30} />
+ </LoadingContainer>
+ );
+ }
+
+ return (
+ <QueryEditorForm
+ dataSources={dataSources}
+ datasourceId={this.props.datasourceId}
+ editorConfig={editorConfig}
+ executedQueryData={responses[actionId]}
+ formData={this.props.formData}
+ isDeleting={isDeleting}
+ isRunning={isRunning}
+ location={this.props.location}
+ onCreateDatasourceClick={onCreateDatasourceClick}
+ onDeleteClick={this.handleDeleteClick}
+ onRunClick={this.handleRunClick}
+ pluginId={this.props.pluginId}
+ runErrorMessage={runErrorMessage[actionId]}
+ settingConfig={this.props.settingsConfig}
+ uiComponent={uiComponent}
+ updateActionResponseDisplayFormat={updateActionResponseDisplayFormat}
+ />
+ );
+ }
+}
+
+const mapStateToProps = (state: AppState, props: OwnProps): ReduxStateProps => {
+ const { apiId, queryId } = props.match.params;
+ const actionId = queryId || apiId || "";
+ const { runErrorMessage } = state.ui.queryPane;
+ const { plugins } = state.entities;
+
+ const { editorConfigs } = plugins;
+
+ const action = getAction(state, actionId) as QueryAction | SaaSAction;
+ const formData = getFormValues(QUERY_EDITOR_FORM_NAME)(state) as
+ | QueryAction
+ | SaaSAction;
+ let pluginId;
+ if (action) {
+ pluginId = action.pluginId;
+ }
+
+ let editorConfig: any;
+
+ if (editorConfigs && pluginId) {
+ editorConfig = editorConfigs[pluginId];
+ }
+
+ const initialValues = {};
+
+ if (editorConfig) {
+ merge(initialValues, getConfigInitialValues(editorConfig));
+ }
+
+ if (props.settingsConfig) {
+ merge(initialValues, getConfigInitialValues(props.settingsConfig));
+ }
+
+ // initialValues contains merge of action, editorConfig, settingsConfig and will be passed to redux form
+ merge(initialValues, action);
+
+ // @ts-expect-error: Types are not available
+ const actionObjectDiff: undefined | Diff<Action | undefined, Action>[] = diff(
+ action,
+ initialValues,
+ );
+
+ const allPlugins = getPlugins(state);
+ let uiComponent = UIComponentTypes.DbEditorForm;
+ if (!!pluginId) uiComponent = getUIComponent(pluginId, allPlugins);
+
+ const currentEnvDetails = getCurrentEnvironmentDetails(state);
+
+ return {
+ actionId,
+ currentEnvironmentId: currentEnvDetails?.id || "",
+ currentEnvironmentName: currentEnvDetails?.name || "",
+ pluginId,
+ plugins: allPlugins,
+ runErrorMessage,
+ pluginIds: getPluginIdsOfPackageNames(state, PLUGIN_PACKAGE_DBS),
+ dataSources: !!apiId
+ ? getDatasourceByPluginId(state, action?.pluginId)
+ : getDBAndRemoteDatasources(state),
+ responses: getActionResponses(state),
+ isRunning: state.ui.queryPane.isRunning[actionId],
+ isDeleting: state.ui.queryPane.isDeleting[actionId],
+ isSaas: !!apiId,
+ formData,
+ editorConfig,
+ isCreating: state.ui.apiPane.isCreating,
+ uiComponent,
+ applicationId: getCurrentApplicationId(state),
+ actionObjectDiff,
+ datasourceId: action?.datasource?.id,
+ };
+};
+
+const mapDispatchToProps = (dispatch: any): ReduxDispatchProps => ({
+ deleteAction: (id: string, name: string) =>
+ dispatch(deleteAction({ id, name })),
+ runAction: (actionId: string) => dispatch(runAction(actionId)),
+ initFormEvaluation: (
+ editorConfig: any,
+ settingsConfig: any,
+ formId: string,
+ ) => {
+ dispatch(initFormEvaluations(editorConfig, settingsConfig, formId));
+ },
+ updateActionResponseDisplayFormat: ({
+ field,
+ id,
+ value,
+ }: UpdateActionPropertyActionPayload) => {
+ dispatch(setActionResponseDisplayFormat({ id, field, value }));
+ },
+ setActionProperty: (
+ actionId: string,
+ propertyName: string,
+ value: string,
+ ) => {
+ dispatch(setActionProperty({ actionId, propertyName, value }));
+ },
+});
+
+export default connect(mapStateToProps, mapDispatchToProps)(QueryEditor);
diff --git a/app/client/src/pages/Editor/QueryEditor/EditorJSONtoForm.tsx b/app/client/src/pages/Editor/QueryEditor/EditorJSONtoForm.tsx
index 56ed44c91bfc..161d35461cea 100644
--- a/app/client/src/pages/Editor/QueryEditor/EditorJSONtoForm.tsx
+++ b/app/client/src/pages/Editor/QueryEditor/EditorJSONtoForm.tsx
@@ -1,3 +1,4 @@
+import { useContext } from "react";
import type { RefObject } from "react";
import React, { useCallback, useRef, useState } from "react";
import type { InjectedFormProps } from "redux-form";
@@ -42,7 +43,6 @@ import Resizable, {
ResizerCSS,
} from "components/editorComponents/Debugger/Resizer";
import AnalyticsUtil from "utils/AnalyticsUtil";
-import CloseEditor from "components/editorComponents/CloseEditor";
import EntityDeps from "components/editorComponents/Debugger/EntityDependecies";
import {
checkIfSectionCanRender,
@@ -67,8 +67,6 @@ import {
} from "@appsmith/constants/messages";
import { useParams } from "react-router";
import type { AppState } from "@appsmith/reducers";
-import type { ExplorerURLParams } from "@appsmith/pages/Editor/Explorer/helpers";
-import MoreActionsMenu from "../Explorer/Actions/MoreActionsMenu";
import { thinScrollbar } from "constants/DefaultTheme";
import ActionRightPane, {
useEntityDependencies,
@@ -132,12 +130,12 @@ import { DatasourceStructureContext } from "../Explorer/Datasources/DatasourceSt
import { selectFeatureFlags } from "@appsmith/selectors/featureFlagsSelectors";
import {
getHasCreateDatasourcePermission,
- getHasDeleteActionPermission,
getHasExecuteActionPermission,
getHasManageActionPermission,
} from "@appsmith/utils/BusinessFeatures/permissionPageHelpers";
import { useFeatureFlag } from "utils/hooks/useFeatureFlag";
import { FEATURE_FLAG } from "@appsmith/entities/FeatureFlag";
+import { QueryEditorContext } from "./QueryEditorContext";
const QueryFormContainer = styled.form`
flex: 1;
@@ -368,6 +366,7 @@ interface QueryFormProps {
value,
}: UpdateActionPropertyActionPayload) => void;
datasourceId: string;
+ showCloseEditor: boolean;
}
interface ReduxProps {
@@ -404,6 +403,13 @@ export function EditorJSONtoForm(props: Props) {
updateActionResponseDisplayFormat,
} = props;
+ const {
+ actionRightPaneBackLink,
+ closeEditorLink,
+ moreActionsMenu,
+ saveActionName,
+ } = useContext(QueryEditorContext);
+
let error = runErrorMessage;
let output: Record<string, any>[] | null = null;
let hintMessages: Array<string> = [];
@@ -421,8 +427,6 @@ export function EditorJSONtoForm(props: Props) {
const currentActionConfig: Action | undefined = actions.find(
(action) => action.id === params.apiId || action.id === params.queryId,
);
- const { pageId } = useParams<ExplorerURLParams>();
-
const isFeatureEnabled = useFeatureFlag(FEATURE_FLAG.license_gac_enabled);
const isChangePermitted = getHasManageActionPermission(
@@ -433,10 +437,6 @@ export function EditorJSONtoForm(props: Props) {
isFeatureEnabled,
currentActionConfig?.userPermissions,
);
- const isDeletePermitted = getHasDeleteActionPermission(
- isFeatureEnabled,
- currentActionConfig?.userPermissions,
- );
const userWorkspacePermissions = useSelector(
(state: AppState) => getCurrentAppWorkspace(state).userPermissions ?? [],
@@ -913,22 +913,18 @@ export function EditorJSONtoForm(props: Props) {
return (
<>
- {!guidedTourEnabled && <CloseEditor />}
+ {!guidedTourEnabled && closeEditorLink}
{guidedTourEnabled && <Guide className="query-page" />}
<QueryFormContainer onSubmit={handleSubmit(noop)}>
<StyledFormRow>
<NameWrapper>
- <ActionNameEditor disabled={!isChangePermitted} />
+ <ActionNameEditor
+ disabled={!isChangePermitted}
+ saveActionName={saveActionName}
+ />
</NameWrapper>
<ActionsWrapper>
- <MoreActionsMenu
- className="t--more-action-menu"
- id={currentActionConfig ? currentActionConfig.id : ""}
- isChangePermitted={isChangePermitted}
- isDeletePermitted={isDeletePermitted}
- name={currentActionConfig ? currentActionConfig.name : ""}
- pageId={pageId}
- />
+ {moreActionsMenu}
<DropdownSelect>
<DropdownField
className={"t--switch-datasource"}
@@ -1113,6 +1109,7 @@ export function EditorJSONtoForm(props: Props) {
<SidebarWrapper show={shouldOpenActionPaneByDefault}>
<ActionRightPane
actionName={actionName}
+ actionRightPaneBackLink={actionRightPaneBackLink}
context={DatasourceStructureContext.QUERY_EDITOR}
datasourceId={props.datasourceId}
hasConnections={hasDependencies}
diff --git a/app/client/src/pages/Editor/QueryEditor/QueryEditorContext.tsx b/app/client/src/pages/Editor/QueryEditor/QueryEditorContext.tsx
new file mode 100644
index 000000000000..6af1274eaeb9
--- /dev/null
+++ b/app/client/src/pages/Editor/QueryEditor/QueryEditorContext.tsx
@@ -0,0 +1,64 @@
+import type { ReduxAction } from "@appsmith/constants/ReduxActionConstants";
+import React, { createContext, useMemo } from "react";
+
+interface SaveActionNameParams {
+ id: string;
+ name: string;
+}
+
+interface QueryEditorContextContextProps {
+ moreActionsMenu?: React.ReactNode;
+ onCreateDatasourceClick?: () => void;
+ onEntityNotFoundBackClick?: () => void;
+ changeQueryPage?: (queryId: string) => void;
+ actionRightPaneBackLink?: React.ReactNode;
+ saveActionName?: (
+ params: SaveActionNameParams,
+ ) => ReduxAction<SaveActionNameParams>;
+ closeEditorLink?: React.ReactNode;
+}
+
+type QueryEditorContextProviderProps =
+ React.PropsWithChildren<QueryEditorContextContextProps>;
+
+export const QueryEditorContext = createContext<QueryEditorContextContextProps>(
+ {} as QueryEditorContextContextProps,
+);
+
+export function QueryEditorContextProvider({
+ actionRightPaneBackLink,
+ changeQueryPage,
+ children,
+ closeEditorLink,
+ moreActionsMenu,
+ onCreateDatasourceClick,
+ onEntityNotFoundBackClick,
+ saveActionName,
+}: QueryEditorContextProviderProps) {
+ const value = useMemo(
+ () => ({
+ actionRightPaneBackLink,
+ changeQueryPage,
+ closeEditorLink,
+ moreActionsMenu,
+ onCreateDatasourceClick,
+ onEntityNotFoundBackClick,
+ saveActionName,
+ }),
+ [
+ actionRightPaneBackLink,
+ changeQueryPage,
+ closeEditorLink,
+ moreActionsMenu,
+ onCreateDatasourceClick,
+ onEntityNotFoundBackClick,
+ saveActionName,
+ ],
+ );
+
+ return (
+ <QueryEditorContext.Provider value={value}>
+ {children}
+ </QueryEditorContext.Provider>
+ );
+}
diff --git a/app/client/src/pages/Editor/QueryEditor/index.tsx b/app/client/src/pages/Editor/QueryEditor/index.tsx
index 3e12a871a6c2..5c8df76a5a28 100644
--- a/app/client/src/pages/Editor/QueryEditor/index.tsx
+++ b/app/client/src/pages/Editor/QueryEditor/index.tsx
@@ -1,199 +1,87 @@
-import React from "react";
+import React, { useCallback, useMemo } from "react";
+import { useDispatch, useSelector } from "react-redux";
import type { RouteComponentProps } from "react-router";
-import { connect } from "react-redux";
-import { getFormValues } from "redux-form";
-import styled from "styled-components";
-import type { QueryEditorRouteParams } from "constants/routes";
-import { INTEGRATION_TABS } from "constants/routes";
+
+import AnalyticsUtil from "utils/AnalyticsUtil";
+import Editor from "./Editor";
import history from "utils/history";
-import QueryEditorForm from "./Form";
-import type { UpdateActionPropertyActionPayload } from "actions/pluginActionActions";
-import {
- deleteAction,
- runAction,
- setActionResponseDisplayFormat,
- setActionProperty,
-} from "actions/pluginActionActions";
-import type { AppState } from "@appsmith/reducers";
+import MoreActionsMenu from "../Explorer/Actions/MoreActionsMenu";
+import BackToCanvas from "components/common/BackToCanvas";
+import { INTEGRATION_TABS } from "constants/routes";
import {
getCurrentApplicationId,
+ getCurrentPageId,
getIsEditorInitialized,
} from "selectors/editorSelectors";
-import { QUERY_EDITOR_FORM_NAME } from "@appsmith/constants/forms";
-import type { Plugin } from "api/PluginApi";
-import { UIComponentTypes } from "api/PluginApi";
-import type { Datasource } from "entities/Datasource";
+import { changeQuery } from "actions/queryPaneActions";
+import { DatasourceCreateEntryPoints } from "constants/Datasource";
import {
- getPluginIdsOfPackageNames,
- getPlugins,
getAction,
- getActionResponses,
- getDatasourceByPluginId,
- getDBAndRemoteDatasources,
+ getPluginSettingConfigs,
} from "@appsmith/selectors/entitiesSelector";
-import { PLUGIN_PACKAGE_DBS } from "constants/QueryEditorConstants";
-import type { QueryAction, SaaSAction } from "entities/Action";
-import Spinner from "components/editorComponents/Spinner";
-import CenteredWrapper from "components/designSystems/appsmith/CenteredWrapper";
-import { changeQuery } from "actions/queryPaneActions";
-import PerformanceTracker, {
- PerformanceTransactionName,
-} from "utils/PerformanceTracker";
-import AnalyticsUtil from "utils/AnalyticsUtil";
-import { initFormEvaluations } from "@appsmith/actions/evaluationActions";
-import { getUIComponent } from "./helpers";
-import type { Diff } from "deep-diff";
-import { diff } from "deep-diff";
-import EntityNotFoundPane from "pages/Editor/EntityNotFoundPane";
import { integrationEditorURL } from "@appsmith/RouteBuilder";
-import { getConfigInitialValues } from "components/formControls/utils";
-import { merge } from "lodash";
-import { getPathAndValueFromActionDiffObject } from "../../../utils/getPathAndValueFromActionDiffObject";
-import { DatasourceCreateEntryPoints } from "constants/Datasource";
-import { getCurrentEnvironmentDetails } from "@appsmith/selectors/environmentSelectors";
-
-const EmptyStateContainer = styled.div`
- display: flex;
- height: 100%;
- font-size: 20px;
-`;
-
-const LoadingContainer = styled(CenteredWrapper)`
- height: 50%;
-`;
-
-interface ReduxDispatchProps {
- runAction: (actionId: string) => void;
- deleteAction: (id: string, name: string) => void;
- changeQueryPage: (queryId: string) => void;
- initFormEvaluation: (
- editorConfig: any,
- settingConfig: any,
- formId: string,
- ) => void;
- updateActionResponseDisplayFormat: ({
- field,
- id,
- value,
- }: UpdateActionPropertyActionPayload) => void;
- setActionProperty: (
- actionId: string,
- propertyName: string,
- value: string,
- ) => void;
-}
-
-interface ReduxStateProps {
- plugins: Plugin[];
- dataSources: Datasource[];
- isRunning: boolean;
- isDeleting: boolean;
- formData: QueryAction | SaaSAction;
- runErrorMessage: Record<string, string>;
- pluginId: string | undefined;
- pluginIds: Array<string> | undefined;
- responses: any;
- isCreating: boolean;
- editorConfig: any;
- settingConfig: any;
- isEditorInitialized: boolean;
- uiComponent: UIComponentTypes;
- applicationId: string;
- actionId: string;
- actionObjectDiff?: any;
- isSaas: boolean;
- datasourceId?: string;
- currentEnvironmentId: string;
- currentEnvironmentName: string;
-}
-
-type StateAndRouteProps = RouteComponentProps<QueryEditorRouteParams>;
-
-type Props = StateAndRouteProps & ReduxDispatchProps & ReduxStateProps;
+import { QueryEditorContextProvider } from "./QueryEditorContext";
+import type { QueryEditorRouteParams } from "constants/routes";
+import {
+ getHasDeleteActionPermission,
+ getHasManageActionPermission,
+} from "@appsmith/utils/BusinessFeatures/permissionPageHelpers";
+import { FEATURE_FLAG } from "@appsmith/entities/FeatureFlag";
+import { useFeatureFlag } from "utils/hooks/useFeatureFlag";
+import CloseEditor from "components/editorComponents/CloseEditor";
-class QueryEditor extends React.Component<Props> {
- constructor(props: Props) {
- super(props);
- // Call the first evaluations when the page loads
- // call evaluations only for queries and not google sheets (which uses apiId)
- if (this.props.match.params.queryId) {
- this.props.initFormEvaluation(
- this.props.editorConfig,
- this.props.settingConfig,
- this.props.match.params.queryId,
- );
- }
- }
+type QueryEditorProps = RouteComponentProps<QueryEditorRouteParams>;
- componentDidMount() {
- // if the current action is non existent, do not dispatch change query page action
- // this action should only be dispatched when switching from an existent action.
- if (!this.props.pluginId) return;
- this.props.changeQueryPage(this.props.actionId);
+function QueryEditor(props: QueryEditorProps) {
+ const { apiId, queryId } = props.match.params;
+ const actionId = queryId || apiId;
+ const dispatch = useDispatch();
+ const action = useSelector((state) => getAction(state, actionId || ""));
+ const pluginId = action?.pluginId || "";
+ const isEditorInitialized = useSelector(getIsEditorInitialized);
+ const applicationId: string = useSelector(getCurrentApplicationId);
+ const pageId: string = useSelector(getCurrentPageId);
+ const isFeatureEnabled = useFeatureFlag(FEATURE_FLAG.license_gac_enabled);
+ const settingsConfig = useSelector((state) =>
+ getPluginSettingConfigs(state, pluginId),
+ );
- // fixes missing where key issue by populating the action with a where object when the component is mounted.
- if (this.props.isSaas) {
- const { path = "", value = "" } = {
- ...getPathAndValueFromActionDiffObject(this.props.actionObjectDiff),
- };
- if (value && path) {
- this.props.setActionProperty(this.props.actionId, path, value);
- }
- }
+ const isDeletePermitted = getHasDeleteActionPermission(
+ isFeatureEnabled,
+ action?.userPermissions,
+ );
- PerformanceTracker.stopTracking(PerformanceTransactionName.OPEN_ACTION, {
- actionType: "QUERY",
- });
- }
+ const isChangePermitted = getHasManageActionPermission(
+ isFeatureEnabled,
+ action?.userPermissions,
+ );
- handleDeleteClick = () => {
- const { formData } = this.props;
- this.props.deleteAction(this.props.actionId, formData.name);
- };
+ const moreActionsMenu = useMemo(
+ () => (
+ <MoreActionsMenu
+ className="t--more-action-menu"
+ id={action ? action.id : ""}
+ isChangePermitted={isChangePermitted}
+ isDeletePermitted={isDeletePermitted}
+ name={action ? action.name : ""}
+ pageId={pageId}
+ />
+ ),
+ [action?.id, action?.name, isChangePermitted, isDeletePermitted, pageId],
+ );
- handleRunClick = () => {
- const { dataSources } = this.props;
- const datasource = dataSources.find(
- (datasource) => datasource.id === this.props.datasourceId,
- );
- const pluginName = this.props.plugins.find(
- (plugin) => plugin.id === this.props.pluginId,
- )?.name;
- PerformanceTracker.startTracking(
- PerformanceTransactionName.RUN_QUERY_CLICK,
- { actionId: this.props.actionId },
- );
- AnalyticsUtil.logEvent("RUN_QUERY_CLICK", {
- actionId: this.props.actionId,
- dataSourceSize: dataSources.length,
- environmentId: this.props.currentEnvironmentId,
- environmentName: this.props.currentEnvironmentName,
- pluginName: pluginName,
- datasourceId: datasource?.id,
- isMock: !!datasource?.isMock,
- });
- this.props.runAction(this.props.actionId);
- };
+ const actionRightPaneBackLink = useMemo(() => {
+ return <BackToCanvas pageId={pageId} />;
+ }, [pageId]);
- componentDidUpdate(prevProps: Props) {
- if (prevProps.isRunning === true && this.props.isRunning === false) {
- PerformanceTracker.stopTracking(
- PerformanceTransactionName.RUN_QUERY_CLICK,
- );
- }
- // Update the page when the queryID is changed by changing the
- // URL or selecting new query from the query pane
- // reusing same logic for changing query panes for switching query editor datasources, since the operations are similar.
- if (
- prevProps.actionId !== this.props.actionId ||
- prevProps.pluginId !== this.props.pluginId
- ) {
- this.props.changeQueryPage(this.props.actionId);
- }
- }
+ const changeQueryPage = useCallback(
+ (queryId: string) => {
+ dispatch(changeQuery({ id: queryId, pageId, applicationId }));
+ },
+ [pageId, applicationId],
+ );
- onCreateDatasourceClick = () => {
- const { pageId } = this.props.match.params;
+ const onCreateDatasourceClick = useCallback(() => {
history.push(
integrationEditorURL({
pageId,
@@ -205,187 +93,44 @@ class QueryEditor extends React.Component<Props> {
AnalyticsUtil.logEvent("NAVIGATE_TO_CREATE_NEW_DATASOURCE_PAGE", {
entryPoint,
});
- };
-
- render() {
- const {
- actionId,
- dataSources,
- editorConfig,
- isCreating,
- isDeleting,
- isEditorInitialized,
- isRunning,
- pluginId,
- pluginIds,
- responses,
- runErrorMessage,
- settingConfig,
- uiComponent,
- updateActionResponseDisplayFormat,
- } = this.props;
- const { pageId } = this.props.match.params;
-
- // custom function to return user to integrations page if action is not found
- const goToDatasourcePage = () =>
+ }, [
+ pageId,
+ history,
+ integrationEditorURL,
+ DatasourceCreateEntryPoints,
+ AnalyticsUtil,
+ ]);
+
+ // custom function to return user to integrations page if action is not found
+ const onEntityNotFoundBackClick = useCallback(
+ () =>
history.push(
integrationEditorURL({
pageId,
selectedTab: INTEGRATION_TABS.ACTIVE,
}),
- );
-
- // if the action can not be found, generate a entity not found page
- if (!pluginId && actionId) {
- return <EntityNotFoundPane goBackFn={goToDatasourcePage} />;
- }
-
- if (!pluginIds?.length) {
- return (
- <EmptyStateContainer>{"Plugin is not installed"}</EmptyStateContainer>
- );
- }
-
- if (isCreating || !isEditorInitialized) {
- return (
- <LoadingContainer>
- <Spinner size={30} />
- </LoadingContainer>
- );
- }
+ ),
+ [pageId, history, integrationEditorURL],
+ );
- return (
- <QueryEditorForm
- dataSources={dataSources}
- datasourceId={this.props.datasourceId}
- editorConfig={editorConfig}
- executedQueryData={responses[actionId]}
- formData={this.props.formData}
- isDeleting={isDeleting}
- isRunning={isRunning}
- location={this.props.location}
- onCreateDatasourceClick={this.onCreateDatasourceClick}
- onDeleteClick={this.handleDeleteClick}
- onRunClick={this.handleRunClick}
- pluginId={this.props.pluginId}
- runErrorMessage={runErrorMessage[actionId]}
- settingConfig={settingConfig}
- uiComponent={uiComponent}
- updateActionResponseDisplayFormat={updateActionResponseDisplayFormat}
+ const closeEditorLink = useMemo(() => <CloseEditor />, []);
+
+ return (
+ <QueryEditorContextProvider
+ actionRightPaneBackLink={actionRightPaneBackLink}
+ changeQueryPage={changeQueryPage}
+ closeEditorLink={closeEditorLink}
+ moreActionsMenu={moreActionsMenu}
+ onCreateDatasourceClick={onCreateDatasourceClick}
+ onEntityNotFoundBackClick={onEntityNotFoundBackClick}
+ >
+ <Editor
+ {...props}
+ isEditorInitialized={isEditorInitialized}
+ settingsConfig={settingsConfig}
/>
- );
- }
-}
-
-const mapStateToProps = (state: AppState, props: any): ReduxStateProps => {
- const { apiId, queryId } = props.match.params;
- const actionId = queryId || apiId;
- const { runErrorMessage } = state.ui.queryPane;
- const { plugins } = state.entities;
-
- const { editorConfigs, settingConfigs } = plugins;
-
- const action = getAction(state, actionId) as QueryAction | SaaSAction;
- const formData = getFormValues(QUERY_EDITOR_FORM_NAME)(state) as
- | QueryAction
- | SaaSAction;
- let pluginId;
- if (action) {
- pluginId = action.pluginId;
- }
-
- let editorConfig: any;
-
- if (editorConfigs && pluginId) {
- editorConfig = editorConfigs[pluginId];
- }
-
- let settingConfig: any;
-
- if (settingConfigs && pluginId) {
- settingConfig = settingConfigs[pluginId];
- }
-
- const initialValues = {};
-
- if (editorConfig) {
- merge(initialValues, getConfigInitialValues(editorConfig));
- }
-
- if (settingConfig) {
- merge(initialValues, getConfigInitialValues(settingConfig));
- }
-
- // initialValues contains merge of action, editorConfig, settingsConfig and will be passed to redux form
- merge(initialValues, action);
-
- // @ts-expect-error: Types are not available
- const actionObjectDiff: undefined | Diff<Action | undefined, Action>[] = diff(
- action,
- initialValues,
+ </QueryEditorContextProvider>
);
+}
- const allPlugins = getPlugins(state);
- let uiComponent = UIComponentTypes.DbEditorForm;
- if (!!pluginId) uiComponent = getUIComponent(pluginId, allPlugins);
-
- const currentEnvDetails = getCurrentEnvironmentDetails(state);
-
- return {
- actionId,
- currentEnvironmentId: currentEnvDetails?.id || "",
- currentEnvironmentName: currentEnvDetails?.name || "",
- pluginId,
- plugins: allPlugins,
- runErrorMessage,
- pluginIds: getPluginIdsOfPackageNames(state, PLUGIN_PACKAGE_DBS),
- dataSources: !!apiId
- ? getDatasourceByPluginId(state, action?.pluginId)
- : getDBAndRemoteDatasources(state),
- responses: getActionResponses(state),
- isRunning: state.ui.queryPane.isRunning[actionId],
- isDeleting: state.ui.queryPane.isDeleting[actionId],
- isSaas: !!apiId,
- formData,
- editorConfig,
- settingConfig,
- isCreating: state.ui.apiPane.isCreating,
- isEditorInitialized: getIsEditorInitialized(state),
- uiComponent,
- applicationId: getCurrentApplicationId(state),
- actionObjectDiff,
- datasourceId: action?.datasource?.id,
- };
-};
-
-const mapDispatchToProps = (dispatch: any): ReduxDispatchProps => ({
- deleteAction: (id: string, name: string) =>
- dispatch(deleteAction({ id, name })),
- runAction: (actionId: string) => dispatch(runAction(actionId)),
- changeQueryPage: (queryId: string) => {
- dispatch(changeQuery(queryId));
- },
- initFormEvaluation: (
- editorConfig: any,
- settingsConfig: any,
- formId: string,
- ) => {
- dispatch(initFormEvaluations(editorConfig, settingsConfig, formId));
- },
- updateActionResponseDisplayFormat: ({
- field,
- id,
- value,
- }: UpdateActionPropertyActionPayload) => {
- dispatch(setActionResponseDisplayFormat({ id, field, value }));
- },
- setActionProperty: (
- actionId: string,
- propertyName: string,
- value: string,
- ) => {
- dispatch(setActionProperty({ actionId, propertyName, value }));
- },
-});
-
-export default connect(mapStateToProps, mapDispatchToProps)(QueryEditor);
+export default QueryEditor;
diff --git a/app/client/src/pages/Editor/routes.tsx b/app/client/src/pages/Editor/routes.tsx
index 4061162b99a1..ce92d313dfa2 100644
--- a/app/client/src/pages/Editor/routes.tsx
+++ b/app/client/src/pages/Editor/routes.tsx
@@ -6,7 +6,6 @@ import IntegrationEditor from "./IntegrationEditor";
import QueryEditor from "./QueryEditor";
import JSEditor from "./JSEditor";
import GeneratePage from "./GeneratePage";
-import CurlImportForm from "./APIEditor/CurlImportForm";
import ProviderTemplates from "./APIEditor/ProviderTemplates";
import {
API_EDITOR_ID_PATH,
@@ -27,6 +26,7 @@ import * as Sentry from "@sentry/react";
import { SaaSEditorRoutes } from "./SaaSEditor/routes";
import OnboardingChecklist from "./FirstTimeUserOnboarding/Checklist";
import { DatasourceEditorRoutes } from "pages/routes";
+import CurlImportEditor from "./APIEditor/CurlImportEditor";
const SentryRoute = Sentry.withSentryRouting(Route);
@@ -91,7 +91,7 @@ function EditorsRouter() {
/>
<SentryRoute
- component={CurlImportForm}
+ component={CurlImportEditor}
exact
path={`${path}${CURL_IMPORT_PAGE_PATH}`}
/>
diff --git a/app/client/src/sagas/QueryPaneSagas.ts b/app/client/src/sagas/QueryPaneSagas.ts
index b11783ca038a..0ee5d2173582 100644
--- a/app/client/src/sagas/QueryPaneSagas.ts
+++ b/app/client/src/sagas/QueryPaneSagas.ts
@@ -24,10 +24,7 @@ import {
} from "@appsmith/constants/forms";
import history from "utils/history";
import { APPLICATIONS_URL, INTEGRATION_TABS } from "constants/routes";
-import {
- getCurrentApplicationId,
- getCurrentPageId,
-} from "selectors/editorSelectors";
+import { getCurrentPageId } from "selectors/editorSelectors";
import { autofill, change, initialize, reset } from "redux-form";
import {
getAction,
@@ -86,25 +83,28 @@ import type { FeatureFlags } from "@appsmith/entities/FeatureFlag";
import { selectFeatureFlags } from "@appsmith/selectors/featureFlagsSelectors";
import { isGACEnabled } from "@appsmith/utils/planHelpers";
import { getHasManageActionPermission } from "@appsmith/utils/BusinessFeatures/permissionPageHelpers";
+import type { ChangeQueryPayload } from "actions/queryPaneActions";
// Called whenever the query being edited is changed via the URL or query pane
-function* changeQuerySaga(actionPayload: ReduxAction<{ id: string }>) {
- const { id } = actionPayload.payload;
+function* changeQuerySaga(actionPayload: ReduxAction<ChangeQueryPayload>) {
+ const { applicationId, id, moduleId, packageId, pageId } =
+ actionPayload.payload;
let configInitialValues = {};
- const applicationId: string = yield select(getCurrentApplicationId);
- const pageId: string = yield select(getCurrentPageId);
- if (!applicationId || !pageId) {
+
+ if (!(packageId && moduleId) && !(applicationId && pageId)) {
history.push(APPLICATIONS_URL);
return;
}
const action: Action | undefined = yield select(getAction, id);
if (!action) {
- history.push(
- integrationEditorURL({
- pageId,
- selectedTab: INTEGRATION_TABS.ACTIVE,
- }),
- );
+ if (pageId) {
+ history.push(
+ integrationEditorURL({
+ pageId,
+ selectedTab: INTEGRATION_TABS.ACTIVE,
+ }),
+ );
+ }
return;
}
diff --git a/app/client/src/selectors/ui.tsx b/app/client/src/selectors/ui.tsx
index f806158ae4e3..244296e03807 100644
--- a/app/client/src/selectors/ui.tsx
+++ b/app/client/src/selectors/ui.tsx
@@ -54,3 +54,6 @@ export const getDatasourceCollapsibleState = createSelector(
return datasourceCollapsibleState[key];
},
);
+
+export const getIsImportingCurl = (state: AppState) =>
+ state.ui.imports.isImportingCurl;
|
f62ea28807180a2d1fa48b891a876bb3dbf41a5e
|
2023-08-02 13:13:04
|
Aishwarya-U-R
|
test: Cypress | Uncomment EE-Pin check in InputTruncateCheck_Spec.ts (#25936)
| false
|
Cypress | Uncomment EE-Pin check in InputTruncateCheck_Spec.ts (#25936)
|
test
|
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 a571b64ac45b..94055aa9e5a2 100644
--- a/app/client/cypress/e2e/Regression/ClientSide/BugTests/InputTruncateCheck_Spec.ts
+++ b/app/client/cypress/e2e/Regression/ClientSide/BugTests/InputTruncateCheck_Spec.ts
@@ -93,7 +93,7 @@ Object.entries(widgetsToTest).forEach(([widgetSelector, testConfig], index) => {
if (index === 0) {
configureApi();
}
- // entityExplorer.PinUnpinEntityExplorer(false);
+ entityExplorer.PinUnpinEntityExplorer(false);
entityExplorer.DragDropWidgetNVerify(widgetSelector, 300, 200);
entityExplorer.DragDropWidgetNVerify(draggableWidgets.BUTTON, 400, 400);
//entityExplorer.SelectEntityByName(draggableWidgets.BUTTONNAME("1"));
@@ -110,7 +110,7 @@ Object.entries(widgetsToTest).forEach(([widgetSelector, testConfig], index) => {
PROPERTY_SELECTOR.TextFieldName,
`{{appsmith.store.textPayloadOnSubmit}}`,
);
- // entityExplorer.PinUnpinEntityExplorer(true);
+ entityExplorer.PinUnpinEntityExplorer(true);
});
it("2. StoreValue should have complete input value", () => {
|
f5553ed2aff3c1510fc51a0c6922de332766f9e2
|
2024-03-26 12:50:00
|
Hetu Nandu
|
chore: Add IDE JS Rendering tests (#32056)
| false
|
Add IDE JS Rendering tests (#32056)
|
chore
|
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
new file mode 100644
index 000000000000..668cf9fa9bfa
--- /dev/null
+++ b/app/client/src/pages/Editor/IDE/EditorPane/JS/JSRender.test.tsx
@@ -0,0 +1,311 @@
+import localStorage from "utils/localStorage";
+import { render } from "test/testUtils";
+import { Route } from "react-router-dom";
+import { BUILDER_PATH } from "@appsmith/constants/routes/appRoutes";
+import IDE from "pages/Editor/IDE/index";
+import React from "react";
+import { createMessage, EDITOR_PANE_TEXTS } from "@appsmith/constants/messages";
+import { getIDETestState } from "test/factories/AppIDEFactoryUtils";
+import {
+ EditorEntityTab,
+ EditorViewMode,
+} from "@appsmith/entities/IDE/constants";
+import { PageFactory } from "test/factories/PageFactory";
+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");
+ describe("JS Blank State", () => {
+ it("Renders Fullscreen Blank State", () => {
+ const { getByRole, getByText } = render(
+ <Route path={BUILDER_PATH}>
+ <IDE />
+ </Route>,
+ {
+ url: "/app/applicationSlug/pageSlug-page_id/edit/jsObjects",
+ featureFlags: FeatureFlags,
+ },
+ );
+
+ // Main pane text
+ getByText(createMessage(EDITOR_PANE_TEXTS.js_blank_state));
+
+ // Left pane text
+ getByText(createMessage(EDITOR_PANE_TEXTS.js_blank_state_description));
+
+ // CTA button is rendered
+ getByRole("button", {
+ name: createMessage(EDITOR_PANE_TEXTS.js_add_button),
+ });
+ });
+
+ it("Renders Split Screen Blank State", () => {
+ const state = getIDETestState({ ideView: EditorViewMode.SplitScreen });
+ const { getByRole, getByTestId, getByText } = render(
+ <Route path={BUILDER_PATH}>
+ <IDE />
+ </Route>,
+ {
+ url: "/app/applicationSlug/pageSlug-page_id/edit/jsObjects",
+ initialState: state,
+ featureFlags: FeatureFlags,
+ },
+ );
+
+ // Check if editor is in split screen
+ getByTestId("t--ide-maximize");
+ getByTestId("t--widgets-editor");
+
+ // Left pane text
+ getByText(createMessage(EDITOR_PANE_TEXTS.js_blank_state_description));
+
+ // CTA button is rendered
+ getByRole("button", {
+ name: createMessage(EDITOR_PANE_TEXTS.js_add_button),
+ });
+ });
+
+ it("Renders Fullscreen Add in Blank State", () => {
+ const { getByRole, getByText } = render(
+ <Route path={BUILDER_PATH}>
+ <IDE />
+ </Route>,
+ {
+ url: "/app/applicationSlug/pageSlug-page_id/edit/jsObjects/add",
+ featureFlags: FeatureFlags,
+ },
+ );
+
+ // Main pane text
+ getByText(createMessage(EDITOR_PANE_TEXTS.js_blank_state));
+
+ // Left pane header
+ getByText(createMessage(EDITOR_PANE_TEXTS.js_create_tab_title));
+
+ // Create options are rendered
+ getByText(createMessage(EDITOR_PANE_TEXTS.js_blank_object_item));
+ // Close button is rendered
+ getByRole("button", { name: "Close pane" });
+ });
+
+ it("Renders Split Screen Add in Blank State", () => {
+ const state = getIDETestState({ ideView: EditorViewMode.SplitScreen });
+ const { getByRole, getByTestId, getByText } = render(
+ <Route path={BUILDER_PATH}>
+ <IDE />
+ </Route>,
+ {
+ url: "/app/applicationSlug/pageSlug-page_id/edit/jsObjects/add",
+ initialState: state,
+ featureFlags: FeatureFlags,
+ },
+ );
+
+ // Check if editor is in split screen
+ getByTestId("t--ide-maximize");
+ getByTestId("t--widgets-editor");
+
+ // Left pane header
+ getByText(createMessage(EDITOR_PANE_TEXTS.js_create_tab_title));
+
+ // Create options are rendered
+ getByText(createMessage(EDITOR_PANE_TEXTS.js_blank_object_item));
+ // Close button is rendered
+ getByRole("button", { name: "Close pane" });
+ });
+ });
+
+ describe("JS Edit Render", () => {
+ it("Renders JS routes in Full screen", () => {
+ const page = PageFactory.build();
+ const JS = JSObjectFactory.build({ id: "js_id", pageId: page.pageId });
+
+ const state = getIDETestState({
+ pages: [page],
+ js: [JS],
+ tabs: {
+ [EditorEntityTab.QUERIES]: [],
+ [EditorEntityTab.JS]: ["js_id"],
+ },
+ });
+
+ const { container, getAllByText, getByRole, getByTestId } = render(
+ <Route path={BUILDER_PATH}>
+ <IDE />
+ </Route>,
+ {
+ url: "/app/applicationSlug/pageSlug-page_id/edit/jsObjects/js_id",
+ initialState: state,
+ featureFlags: FeatureFlags,
+ },
+ );
+
+ // There will be 3 JSObject1 text (Left pane list, editor tab and Editor form)
+ expect(getAllByText("JSObject1").length).toEqual(3);
+ // Left pane active state
+ expect(
+ getByTestId("t--entity-item-JSObject1").classList.contains("active"),
+ ).toBe(true);
+ // Tabs active state
+ expect(
+ getByTestId("t--ide-tab-JSObject1").classList.contains("active"),
+ ).toBe(true);
+ // Check if the form is rendered
+ expect(container.querySelector(".js-editor-tab")).not.toBeNull();
+ // Check if the code and settings tabs is visible
+ getByRole("tab", { name: /code/i });
+ getByRole("tab", { name: /settings/i });
+ // Check if run button is visible
+ getByRole("button", { name: /run/i });
+ // Check if the Add new button is shown
+ getByRole("button", {
+ name: createMessage(EDITOR_PANE_TEXTS.js_add_button),
+ });
+ });
+
+ it("Renders JS routes in Split Screen", async () => {
+ const page = PageFactory.build();
+ const js2 = JSObjectFactory.build({
+ id: "js_id2",
+ pageId: page.pageId,
+ });
+ const state = getIDETestState({
+ js: [js2],
+ pages: [page],
+ tabs: {
+ [EditorEntityTab.QUERIES]: [],
+ [EditorEntityTab.JS]: ["js_id2"],
+ },
+ ideView: EditorViewMode.SplitScreen,
+ });
+
+ const { container, getAllByText, getByRole, getByTestId } = render(
+ <Route path={BUILDER_PATH}>
+ <IDE />
+ </Route>,
+ {
+ url: "/app/applicationSlug/pageSlug-page_id/edit/jsObjects/js_id2",
+ initialState: state,
+ featureFlags: FeatureFlags,
+ },
+ );
+
+ // Check if editor is in split screen
+ getByTestId("t--ide-maximize");
+ getByTestId("t--widgets-editor");
+
+ // Check if js is rendered in side by side
+ expect(getAllByText("JSObject2").length).toBe(2);
+ // Tabs active state
+ expect(
+ getByTestId("t--ide-tab-JSObject2").classList.contains("active"),
+ ).toBe(true);
+
+ // Check if the form is rendered
+ expect(container.querySelector(".js-editor-tab")).not.toBeNull();
+ // Check if the code and settings tabs is visible
+ getByRole("tab", { name: /code/i });
+ getByRole("tab", { name: /settings/i });
+ // Check if run button is visible
+ getByRole("button", { name: /run/i });
+ // Check if the Add new button is shown
+ getByTestId("t--ide-split-screen-add-button");
+ });
+
+ it("Renders JS add routes in Full Screen", () => {
+ const page = PageFactory.build();
+ const JS3 = JSObjectFactory.build({
+ id: "js_id3",
+ pageId: page.pageId,
+ });
+ const state = getIDETestState({
+ js: [JS3],
+ pages: [page],
+ tabs: {
+ [EditorEntityTab.QUERIES]: [],
+ [EditorEntityTab.JS]: ["js_id3"],
+ },
+ });
+
+ const { container, getAllByText, getByRole, getByTestId, getByText } =
+ render(
+ <Route path={BUILDER_PATH}>
+ <IDE />
+ </Route>,
+ {
+ url: "/app/applicationSlug/pageSlug-page_id/edit/jsObjects/js_id3/add",
+ initialState: state,
+ featureFlags: FeatureFlags,
+ },
+ );
+
+ // There will be 2 JSObject3 text (editor tab and Editor form)
+ expect(getAllByText("JSObject3").length).toEqual(2);
+ // Tabs active state
+ expect(
+ getByTestId("t--ide-tab-JSObject3").classList.contains("active"),
+ ).toBe(false);
+ // Check if the form is rendered
+ expect(container.querySelector(".js-editor-tab")).not.toBeNull();
+ // Check if the code and settings tabs is visible
+ getByRole("tab", { name: /code/i });
+ getByRole("tab", { name: /settings/i });
+ // Check if run button is visible
+ getByRole("button", { name: /run/i });
+ // Create options are rendered
+ getByText(createMessage(EDITOR_PANE_TEXTS.js_blank_object_item));
+ // Close button is rendered
+ getByRole("button", { name: "Close pane" });
+ });
+
+ it("Renders JS add routes in Split Screen", () => {
+ const page = PageFactory.build();
+ const js3 = JSObjectFactory.build({ id: "js_id4", pageId: page.pageId });
+ const state = getIDETestState({
+ js: [js3],
+ pages: [page],
+ tabs: {
+ [EditorEntityTab.QUERIES]: [],
+ [EditorEntityTab.JS]: ["js_id4"],
+ },
+ ideView: EditorViewMode.SplitScreen,
+ });
+
+ const { container, getAllByText, getByRole, getByTestId, getByText } =
+ render(
+ <Route path={BUILDER_PATH}>
+ <IDE />
+ </Route>,
+ {
+ url: "/app/applicationSlug/pageSlug-page_id/edit/jsObjects/js_id4/add",
+ initialState: state,
+ featureFlags: FeatureFlags,
+ },
+ );
+
+ // There will be 1 JSObject3 text ( The tab )
+ expect(getAllByText("JSObject4").length).toEqual(1);
+ // Tabs active state
+ expect(
+ getByTestId("t--ide-tab-JSObject4").classList.contains("active"),
+ ).toBe(false);
+ // Add button active state
+ expect(
+ getByTestId("t--ide-split-screen-add-button").getAttribute(
+ "data-selected",
+ ),
+ ).toBe("true");
+
+ // Check if the form is not rendered
+ expect(container.querySelector(".js-editor-tab")).toBeNull();
+ // Create options are rendered
+ getByText(createMessage(EDITOR_PANE_TEXTS.js_blank_object_item));
+ // Close button is rendered
+ getByRole("button", { name: "Close pane" });
+ });
+ });
+});
diff --git a/app/client/test/factories/Actions/JSObject.ts b/app/client/test/factories/Actions/JSObject.ts
new file mode 100644
index 000000000000..723c15ad0de4
--- /dev/null
+++ b/app/client/test/factories/Actions/JSObject.ts
@@ -0,0 +1,103 @@
+import * as Factory from "factory.ts";
+import type { JSCollection } from "entities/JSCollection";
+import { PluginPackageName, PluginType } from "entities/Action";
+import { PluginIDs } from "test/factories/MockPluginsState";
+
+export const JSObjectFactory = Factory.Sync.makeFactory<JSCollection>({
+ id: "js_id",
+ workspaceId: "workspaceId",
+ applicationId: "appId",
+ name: Factory.each((i) => `JSObject${i + 1}`),
+ pageId: "5ff4735253b64c03e830009b",
+ pluginId: PluginIDs[PluginPackageName.JS],
+ pluginType: PluginType.JS,
+ actions: [
+ {
+ id: "myFunc1_id",
+ workspaceId: "workspaceId",
+ pluginId: PluginIDs[PluginPackageName.JS],
+ name: "myFun1",
+ fullyQualifiedName: "JSObject1.myFun1",
+ pageId: "page_id",
+ collectionId: "js_id",
+ actionConfiguration: {
+ timeoutInMillisecond: 10000,
+ body: "function (){\n\t\t//\twrite code here\n\t\t//\tthis.myVar1 = [1,2,3]\n\t}",
+ jsArguments: [],
+ },
+ executeOnLoad: false,
+ clientSideExecution: true,
+ dynamicBindingPathList: [
+ {
+ key: "body",
+ },
+ ],
+ isValid: true,
+ invalids: [],
+ messages: [],
+ jsonPathKeys: [
+ "function (){\n\t\t//\twrite code here\n\t\t//\tthis.myVar1 = [1,2,3]\n\t}",
+ ],
+ confirmBeforeExecute: false,
+ userPermissions: [
+ "read:actions",
+ "delete:actions",
+ "execute:actions",
+ "manage:actions",
+ ],
+ cacheResponse: "",
+ },
+ {
+ id: "myFunc2_id",
+ workspaceId: "workspaceId",
+ pluginId: "613a26d921750e4b557a9241",
+ name: "myFun2",
+ fullyQualifiedName: "JSObject1.myFun2",
+ pageId: "5ff4735253b64c03e830009b",
+ collectionId: "660261174b59877d57fc3670",
+ actionConfiguration: {
+ timeoutInMillisecond: 10000,
+ body: "async function () {\n\t\t//\tuse async-await or promises\n\t\t//\tawait storeValue('varName', 'hello world')\n\t}",
+ jsArguments: [],
+ },
+ executeOnLoad: false,
+ clientSideExecution: true,
+ dynamicBindingPathList: [
+ {
+ key: "body",
+ },
+ ],
+ isValid: true,
+ invalids: [],
+ messages: [],
+ jsonPathKeys: [
+ "async function () {\n\t\t//\tuse async-await or promises\n\t\t//\tawait storeValue('varName', 'hello world')\n\t}",
+ ],
+ confirmBeforeExecute: false,
+ userPermissions: [
+ "read:actions",
+ "delete:actions",
+ "execute:actions",
+ "manage:actions",
+ ],
+ cacheResponse: "",
+ },
+ ],
+ body: "export default {\n\tmyVar1: [],\n\tmyVar2: {},\n\tmyFun1 () {\n\t\t//\twrite code here\n\t\t//\tthis.myVar1 = [1,2,3]\n\t},\n\tasync myFun2 () {\n\t\t//\tuse async-await or promises\n\t\t//\tawait storeValue('varName', 'hello world')\n\t}\n}",
+ variables: [
+ {
+ name: "myVar1",
+ value: [],
+ },
+ {
+ name: "myVar2",
+ value: {},
+ },
+ ],
+ userPermissions: [
+ "read:actions",
+ "delete:actions",
+ "execute:actions",
+ "manage:actions",
+ ],
+});
diff --git a/app/client/test/factories/AppIDEFactoryUtils.ts b/app/client/test/factories/AppIDEFactoryUtils.ts
index c65b3a87a0ea..b18a97e303c9 100644
--- a/app/client/test/factories/AppIDEFactoryUtils.ts
+++ b/app/client/test/factories/AppIDEFactoryUtils.ts
@@ -6,17 +6,20 @@ import type { Page } from "@appsmith/constants/ReduxActionConstants";
import type { Action } from "entities/Action";
import type { IDETabs } from "reducers/uiReducers/ideReducer";
import { IDETabsDefaultValue } from "reducers/uiReducers/ideReducer";
+import type { JSCollection } from "entities/JSCollection";
interface IDEStateArgs {
ideView?: EditorViewMode;
pages?: Page[];
actions?: Action[];
+ js?: JSCollection[];
tabs?: IDETabs;
}
export const getIDETestState = ({
actions = [],
ideView = EditorViewMode.FullScreen,
+ js = [],
pages = [],
tabs = IDETabsDefaultValue,
}: IDEStateArgs): AppState => {
@@ -33,6 +36,8 @@ export const getIDETestState = ({
const actionData = actions.map((a) => ({ isLoading: false, config: a }));
+ const jsData = js.map((a) => ({ isLoading: false, config: a }));
+
return {
...initialState,
entities: {
@@ -40,6 +45,7 @@ export const getIDETestState = ({
plugins: MockPluginsState,
pageList: pageList,
actions: actionData,
+ jsActions: jsData,
},
ui: {
...initialState.ui,
diff --git a/app/client/test/factories/MockPluginsState.ts b/app/client/test/factories/MockPluginsState.ts
index ce9004ebe992..586ccacecb86 100644
--- a/app/client/test/factories/MockPluginsState.ts
+++ b/app/client/test/factories/MockPluginsState.ts
@@ -6,6 +6,7 @@ export const PluginIDs = {
[PluginPackageName.REST_API]: "65e58df196506a506bd7069d",
[PluginPackageName.MONGO]: "65e58df196506a506bd7069e",
[PluginPackageName.GOOGLE_SHEETS]: "65e58df296506a506bd706a9",
+ [PluginPackageName.JS]: "65e58df296506a506bd706ad",
};
export default {
|
33da769afba58f3267ac194976cc0458f71c3c65
|
2024-02-13 16:46:38
|
Vemparala Surya Vamsi
|
chore: Removed sending redundant mode parameter in consolidated api (#31097)
| false
|
Removed sending redundant mode parameter in consolidated api (#31097)
|
chore
|
diff --git a/app/client/src/sagas/InitSagas.ts b/app/client/src/sagas/InitSagas.ts
index 6828eee77145..29faf1f4b6f8 100644
--- a/app/client/src/sagas/InitSagas.ts
+++ b/app/client/src/sagas/InitSagas.ts
@@ -224,7 +224,6 @@ export function* getInitResponses({
{
applicationId,
defaultPageId: pageId,
- mode,
},
identity,
);
@@ -270,7 +269,7 @@ export function* getInitResponses({
);
Sentry.captureMessage(
- `consolidated api failure for ${JSON.stringify(
+ `consolidated api failure for mode=${mode} ${JSON.stringify(
params,
)} errored message response ${e}`,
);
|
e9f7f9cc7f4067db16426677ad31f3b5487f6c1c
|
2025-03-06 12:47:30
|
Nidhi
|
chore: Slight clean up to avoid EE start up errors (#39585)
| false
|
Slight clean up to avoid EE start up errors (#39585)
|
chore
|
diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/configurations/ReactorNettyConfiguration.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/configurations/ReactorNettyConfiguration.java
index 233182b97165..76359038cae1 100644
--- a/app/server/appsmith-server/src/main/java/com/appsmith/server/configurations/ReactorNettyConfiguration.java
+++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/configurations/ReactorNettyConfiguration.java
@@ -11,8 +11,6 @@
@Component
public class ReactorNettyConfiguration implements WebServerFactoryCustomizer<NettyReactiveWebServerFactory> {
- private final CommonConfig commonConfig;
-
@Override
public void customize(NettyReactiveWebServerFactory factory) {
factory.addServerCustomizers(httpServer -> httpServer.metrics(true, Function.identity()));
|
81ac8efaefba353d6bd58b1652fc3683604e6bbb
|
2024-02-12 18:37:37
|
Hetu Nandu
|
fix: Entity Explorer Test (#31062)
| false
|
Entity Explorer Test (#31062)
|
fix
|
diff --git a/app/client/src/pages/Editor/Explorer/EntityExplorer.test.tsx b/app/client/src/pages/Editor/Explorer/EntityExplorer.test.tsx
index 42660da8b797..0a2f29044c1f 100644
--- a/app/client/src/pages/Editor/Explorer/EntityExplorer.test.tsx
+++ b/app/client/src/pages/Editor/Explorer/EntityExplorer.test.tsx
@@ -81,6 +81,13 @@ describe("Entity Explorer tests", () => {
<WidgetsEditorEntityExplorer />
</MockPageDSL>,
);
+ const widgetsTree: any = component.queryByText("Widgets", {
+ selector: "div.t--entity-name",
+ });
+ act(() => {
+ fireEvent.click(widgetsTree);
+ jest.runAllTimers();
+ });
const tabsWidget = component.queryByText(children[0].widgetName);
expect(tabsWidget).toBeTruthy();
});
@@ -106,13 +113,6 @@ describe("Entity Explorer tests", () => {
<WidgetsEditorEntityExplorer />
</MockPageDSL>,
);
- const widgetsTree: any = component.queryByText("Widgets", {
- selector: "div.t--entity-name",
- });
- act(() => {
- fireEvent.click(widgetsTree);
- jest.runAllTimers();
- });
const tabsWidget: any = component.queryByText(children[0].widgetName);
act(() => {
fireEvent.click(tabsWidget);
|
d313798e6f3824f4a978737e6acf7d5c91871e3e
|
2023-04-11 19:53:14
|
Keyur Paralkar
|
fix: null check before accessing accessing properties in table and phone input widget (#22218)
| false
|
null check before accessing accessing properties in table and phone input widget (#22218)
|
fix
|
diff --git a/app/client/src/widgets/PhoneInputWidget/widget/index.tsx b/app/client/src/widgets/PhoneInputWidget/widget/index.tsx
index 0feb4287aa91..6c944606e5dd 100644
--- a/app/client/src/widgets/PhoneInputWidget/widget/index.tsx
+++ b/app/client/src/widgets/PhoneInputWidget/widget/index.tsx
@@ -274,7 +274,7 @@ class PhoneInputWidget extends BaseInputWidget<
let formattedValue;
// Don't format, as value is typed, when user is deleting
- if (value && value.length > this.props.text.length) {
+ if (value && value.length > this.props.text?.length) {
formattedValue = this.getFormattedPhoneNumber(value);
} else {
formattedValue = value;
diff --git a/app/client/src/widgets/TableWidgetV2/widget/propertyUtils.ts b/app/client/src/widgets/TableWidgetV2/widget/propertyUtils.ts
index d316031a2574..2ea4e852978e 100644
--- a/app/client/src/widgets/TableWidgetV2/widget/propertyUtils.ts
+++ b/app/client/src/widgets/TableWidgetV2/widget/propertyUtils.ts
@@ -1,5 +1,6 @@
import { Alignment } from "@blueprintjs/core";
import type { ColumnProperties } from "../component/Constants";
+import { StickyType } from "../component/Constants";
import { CellAlignmentTypes } from "../component/Constants";
import type { TableWidgetProps } from "../constants";
import { ColumnTypes, InlineEditingSaveOptions } from "../constants";
@@ -193,7 +194,8 @@ export const updateColumnOrderHook = (
const rightColumnIndex = findIndex(
newColumnOrder,
- (colName: string) => props.primaryColumns[colName].sticky === "right",
+ (colName: string) =>
+ props.primaryColumns[colName]?.sticky === StickyType.RIGHT,
);
if (rightColumnIndex !== -1) {
|
4e0f593fbb0ff83f741b0f3c8262e314b1ee3c30
|
2023-05-29 13:05:14
|
Abhijeet Mishra
|
feat: add template metadata fields (#23491)
| false
|
add template metadata fields (#23491)
|
feat
|
diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/dtos/ApplicationTemplate.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/dtos/ApplicationTemplate.java
index 5793dc870e86..9c6f82fbc8f0 100644
--- a/app/server/appsmith-server/src/main/java/com/appsmith/server/dtos/ApplicationTemplate.java
+++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/dtos/ApplicationTemplate.java
@@ -27,4 +27,11 @@ public class ApplicationTemplate extends BaseDomain {
private Long downloadCount;
private Object appData;
private Boolean active;
+ // These fields will be used to display template metadata
+ private String mdText;
+ private String excerpt;
+ private String category;
+ private Boolean featured;
+ private List<String> tags;
+ private Boolean allowPageImport;
}
|
ea0f5e888dcd5cab224c87aa8fed4d42442f7e48
|
2021-08-25 16:15:09
|
Rishabh Saxena
|
feat: add merge page ui (#6836)
| false
|
add merge page ui (#6836)
|
feat
|
diff --git a/app/client/src/assets/icons/ads/arrow-left-1.svg b/app/client/src/assets/icons/ads/arrow-left-1.svg
new file mode 100644
index 000000000000..5cc8c171ee56
--- /dev/null
+++ b/app/client/src/assets/icons/ads/arrow-left-1.svg
@@ -0,0 +1,3 @@
+<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
+<path d="M3.828 7.00066H16V9.00066H3.828L9.192 14.3647L7.778 15.7787L0 8.00066L7.778 0.222656L9.192 1.63666L3.828 7.00066Z" fill="#A9A7A7"/>
+</svg>
diff --git a/app/client/src/assets/icons/ads/git-merge.svg b/app/client/src/assets/icons/ads/git-merge.svg
new file mode 100644
index 000000000000..62d54cc1d7c8
--- /dev/null
+++ b/app/client/src/assets/icons/ads/git-merge.svg
@@ -0,0 +1,3 @@
+<svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
+<path d="M14.9991 5H16.9991C17.5295 5 18.0382 5.21071 18.4133 5.58579C18.7883 5.96086 18.9991 6.46957 18.9991 7V15.17C19.6665 15.4059 20.2291 15.8702 20.5874 16.4808C20.9457 17.0914 21.0765 17.809 20.9569 18.5068C20.8372 19.2046 20.4747 19.8375 19.9334 20.2939C19.3922 20.7502 18.707 21.0005 17.9991 21.0005C17.2911 21.0005 16.6059 20.7502 16.0647 20.2939C15.5234 19.8375 15.1609 19.2046 15.0412 18.5068C14.9216 17.809 15.0524 17.0914 15.4107 16.4808C15.769 15.8702 16.3316 15.4059 16.9991 15.17V7H14.9991V10L10.4991 6L14.9991 2V5ZM4.99905 8.83C4.33156 8.59409 3.76896 8.1298 3.41069 7.51919C3.05243 6.90859 2.92157 6.19098 3.04124 5.49321C3.16092 4.79545 3.52342 4.16246 4.06468 3.70613C4.60594 3.2498 5.2911 2.99951 5.99905 2.99951C6.70701 2.99951 7.39217 3.2498 7.93342 3.70613C8.47468 4.16246 8.83719 4.79545 8.95686 5.49321C9.07654 6.19098 8.94568 6.90859 8.58741 7.51919C8.22915 8.1298 7.66655 8.59409 6.99905 8.83V15.17C7.66655 15.4059 8.22915 15.8702 8.58741 16.4808C8.94568 17.0914 9.07654 17.809 8.95686 18.5068C8.83719 19.2046 8.47468 19.8375 7.93342 20.2939C7.39217 20.7502 6.70701 21.0005 5.99905 21.0005C5.2911 21.0005 4.60594 20.7502 4.06468 20.2939C3.52342 19.8375 3.16092 19.2046 3.04124 18.5068C2.92157 17.809 3.05243 17.0914 3.41069 16.4808C3.76896 15.8702 4.33156 15.4059 4.99905 15.17V8.83ZM5.99905 7C6.26427 7 6.51862 6.89464 6.70616 6.70711C6.8937 6.51957 6.99905 6.26522 6.99905 6C6.99905 5.73478 6.8937 5.48043 6.70616 5.29289C6.51862 5.10536 6.26427 5 5.99905 5C5.73384 5 5.47948 5.10536 5.29195 5.29289C5.10441 5.48043 4.99905 5.73478 4.99905 6C4.99905 6.26522 5.10441 6.51957 5.29195 6.70711C5.47948 6.89464 5.73384 7 5.99905 7ZM5.99905 19C6.26427 19 6.51862 18.8946 6.70616 18.7071C6.8937 18.5196 6.99905 18.2652 6.99905 18C6.99905 17.7348 6.8937 17.4804 6.70616 17.2929C6.51862 17.1054 6.26427 17 5.99905 17C5.73384 17 5.47948 17.1054 5.29195 17.2929C5.10441 17.4804 4.99905 17.7348 4.99905 18C4.99905 18.2652 5.10441 18.5196 5.29195 18.7071C5.47948 18.8946 5.73384 19 5.99905 19ZM17.9991 19C18.2643 19 18.5186 18.8946 18.7062 18.7071C18.8937 18.5196 18.9991 18.2652 18.9991 18C18.9991 17.7348 18.8937 17.4804 18.7062 17.2929C18.5186 17.1054 18.2643 17 17.9991 17C17.7338 17 17.4795 17.1054 17.2919 17.2929C17.1044 17.4804 16.9991 17.7348 16.9991 18C16.9991 18.2652 17.1044 18.5196 17.2919 18.7071C17.4795 18.8946 17.7338 19 17.9991 19Z" fill="#A9A7A7"/>
+</svg>
diff --git a/app/client/src/components/ads/Dropdown.tsx b/app/client/src/components/ads/Dropdown.tsx
index cec3c89e9762..b31851f0842a 100644
--- a/app/client/src/components/ads/Dropdown.tsx
+++ b/app/client/src/components/ads/Dropdown.tsx
@@ -285,6 +285,14 @@ const HeaderWrapper = styled.div`
const SelectedDropDownHolder = styled.div`
display: flex;
align-items: center;
+ min-width: 0;
+ overflow: hidden;
+
+ & ${Text} {
+ max-width: 100%;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ }
`;
const SelectedIcon = styled(Icon)`
diff --git a/app/client/src/constants/messages.ts b/app/client/src/constants/messages.ts
index 472828d37587..50d7a316d0ec 100644
--- a/app/client/src/constants/messages.ts
+++ b/app/client/src/constants/messages.ts
@@ -450,3 +450,5 @@ export const DEPLOY_WITHOUT_GIT = () =>
export const DEPLOY_YOUR_APPLICATION = () => "Deploy your application";
export const COMMIT = () => "COMMIT";
export const PUSH = () => "PUSH";
+export const MERGE_CHANGES = () => "Merge Changes";
+export const SELECT_BRANCH_TO_MERGE = () => "Select branch to merge";
diff --git a/app/client/src/pages/Editor/gitSync/GitSyncModal.tsx b/app/client/src/pages/Editor/gitSync/GitSyncModal.tsx
index 5bd008c5bfd8..f62b3158fd40 100644
--- a/app/client/src/pages/Editor/gitSync/GitSyncModal.tsx
+++ b/app/client/src/pages/Editor/gitSync/GitSyncModal.tsx
@@ -9,6 +9,7 @@ import Menu from "./Menu";
import { MENU_ITEM, MENU_ITEMS } from "./constants";
import GitConnection from "./GitConnection";
import Deploy from "./Deploy/Deploy";
+import Merge from "./Merge";
import Icon from "components/ads/Icon";
import { Colors } from "constants/Colors";
import { Classes } from "./constants";
@@ -56,7 +57,7 @@ function NoopComponent() {
const ComponentsByTab = {
[MENU_ITEM.GIT_CONNECTION]: GitConnection,
[MENU_ITEM.DEPLOY]: Deploy,
- [MENU_ITEM.MERGE]: NoopComponent,
+ [MENU_ITEM.MERGE]: Merge,
[MENU_ITEM.SHARE_APPLICATION]: NoopComponent,
[MENU_ITEM.SETTINGS]: NoopComponent,
};
diff --git a/app/client/src/pages/Editor/gitSync/Merge.tsx b/app/client/src/pages/Editor/gitSync/Merge.tsx
new file mode 100644
index 000000000000..24b1c1b19bb1
--- /dev/null
+++ b/app/client/src/pages/Editor/gitSync/Merge.tsx
@@ -0,0 +1,73 @@
+import React from "react";
+import { Title, Caption, Space } from "./components/StyledComponents";
+import Dropdown from "components/ads/Dropdown";
+
+import {
+ createMessage,
+ MERGE_CHANGES,
+ SELECT_BRANCH_TO_MERGE,
+} from "constants/messages";
+import { ReactComponent as MergeIcon } from "assets/icons/ads/git-merge.svg";
+import { ReactComponent as LeftArrow } from "assets/icons/ads/arrow-left-1.svg";
+
+import styled from "styled-components";
+import * as log from "loglevel";
+import Button, { Size } from "components/ads/Button";
+
+const Row = styled.div`
+ display: flex;
+ align-items: center;
+`;
+
+// mock data
+const options = [
+ { label: "Master", value: "master" },
+ {
+ label: "Feature/new",
+ value: "Feature/new",
+ },
+];
+
+export default function Merge() {
+ return (
+ <>
+ <Title>{createMessage(MERGE_CHANGES)}</Title>
+ <Caption>{createMessage(SELECT_BRANCH_TO_MERGE)}</Caption>
+ <Space size={3} />
+ <Row>
+ <MergeIcon />
+ <Space horizontal size={3} />
+ <Dropdown
+ onSelect={() => {
+ log.debug("selected");
+ }}
+ options={options}
+ selected={{ label: "Master", value: "master" }}
+ showLabelOnly
+ width={"220px"}
+ />
+ <Space horizontal size={3} />
+ <LeftArrow />
+ <Space horizontal size={3} />
+ <Dropdown
+ onSelect={() => {
+ log.debug("selected");
+ }}
+ options={options}
+ selected={{
+ label: "Feature/new-feature",
+ value: "Feature/new-feature",
+ }}
+ showLabelOnly
+ width={"220px"}
+ />
+ </Row>
+ <Space size={3} />
+ <Button
+ size={Size.medium}
+ text={createMessage(MERGE_CHANGES)}
+ width="max-content"
+ />
+ </>
+ );
+}
|
31558082d9156ecadc47b0b730d59e05d3a97555
|
2023-08-01 18:27:21
|
Shrikant Sharat Kandula
|
fix: Update spring-security-config for CVE-2023-34034 (#25893)
| false
|
Update spring-security-config for CVE-2023-34034 (#25893)
|
fix
|
diff --git a/app/server/pom.xml b/app/server/pom.xml
index 0d8fae331140..c691140772d6 100644
--- a/app/server/pom.xml
+++ b/app/server/pom.xml
@@ -7,7 +7,7 @@
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
- <version>3.0.6</version>
+ <version>3.0.9</version>
<relativePath/>
<!-- lookup parent from repository -->
</parent>
@@ -45,7 +45,7 @@
<snakeyaml.version>2.0</snakeyaml.version>
<source.disabled>true</source.disabled>
<spotless.version>2.36.0</spotless.version>
- <spring-boot.version>3.0.6</spring-boot.version>
+ <spring-boot.version>3.0.9</spring-boot.version>
<testcontainers.version>1.17.3</testcontainers.version>
</properties>
|
1835e053fb4772459f395612cc6ec7c17a14f38c
|
2025-03-14 17:57:02
|
Rudraprasad Das
|
chore: git fixes - removing beta tag (#39733)
| false
|
git fixes - removing beta tag (#39733)
|
chore
|
diff --git a/app/client/src/ce/constants/messages.ts b/app/client/src/ce/constants/messages.ts
index b066fb375104..606505b1cf2c 100644
--- a/app/client/src/ce/constants/messages.ts
+++ b/app/client/src/ce/constants/messages.ts
@@ -688,8 +688,8 @@ export const IMPORT_FROM_GIT_DISABLED_IN_ANVIL = () =>
export const IMPORT_APP_FROM_FILE_TITLE = () => "Import from file";
export const UPLOADING_JSON = () => "Uploading JSON file";
export const UPLOADING_APPLICATION = () => "Uploading application";
-export const IMPORT_APP_FROM_GIT_TITLE = () =>
- "Import from Git repository (Beta)";
+export const IMPORT_APP_FROM_GIT_TITLE = (isBeta: boolean = true) =>
+ `Import from Git repository ${isBeta ? "(Beta)" : ""}`;
export const IMPORT_APP_FROM_FILE_MESSAGE = () =>
"Drag and drop your file or upload from your computer";
export const IMPORT_APP_FROM_GIT_MESSAGE = () =>
@@ -923,7 +923,6 @@ export const IS_MERGING = () => "Merging changes...";
export const MERGE_CHANGES = () => "Merge changes";
export const SELECT_BRANCH_TO_MERGE = () => "Select branch to merge";
-export const CONNECT_GIT = () => "Connect Git";
export const CONNECT_GIT_BETA = () => "Connect Git (Beta)";
export const RETRY = () => "Retry";
export const CREATE_NEW_BRANCH = () => "Create new branch";
diff --git a/app/client/src/git/ce/constants/messages.tsx b/app/client/src/git/ce/constants/messages.tsx
index 432d0dcd4cea..49d68fd6a894 100644
--- a/app/client/src/git/ce/constants/messages.tsx
+++ b/app/client/src/git/ce/constants/messages.tsx
@@ -1,3 +1,11 @@
+export const QUICK_ACTIONS = {
+ CONNECT_BTN_NOT_LIVE_YET: "It's not live for you yet",
+ CONNECT_BTN_COMING_SOON: "Coming Soon!",
+ CONNECT_BTN_CTA: "Connect Git",
+ CONNECT_BTN_CONTACT_ADMIN:
+ "Please contact your workspace admin to connect your artifact to a git repo",
+};
+
export const OPS_MODAL = {
TAB_RELEASE: "Release",
};
diff --git a/app/client/src/git/components/QuickActions/ConnectButton.test.tsx b/app/client/src/git/components/QuickActions/ConnectButton.test.tsx
index ee01a5af95da..316ad1d0a0f5 100644
--- a/app/client/src/git/components/QuickActions/ConnectButton.test.tsx
+++ b/app/client/src/git/components/QuickActions/ConnectButton.test.tsx
@@ -64,7 +64,7 @@ describe("ConnectButton Component", () => {
</ThemeProvider>,
);
- const button = screen.getByRole("button", { name: "Connect Git (Beta)" });
+ const button = screen.getByRole("button", { name: "Connect Git" });
fireEvent.click(button);
@@ -91,7 +91,7 @@ describe("ConnectButton Component", () => {
);
// Check that the button is rendered and disabled
- const button = screen.getByRole("button", { name: "Connect Git (Beta)" });
+ const button = screen.getByRole("button", { name: "Connect Git" });
expect(button).toBeInTheDocument();
expect(button).toBeDisabled();
@@ -101,7 +101,7 @@ describe("ConnectButton Component", () => {
expect(tooltipContent).toBeInTheDocument();
expect(tooltipContent).toHaveTextContent(
- "Please contact your workspace admin to connect your app to a git repo",
+ "Please contact your workspace admin to connect your artifact to a git repo",
);
// Icon should be rendered
@@ -118,7 +118,7 @@ describe("ConnectButton Component", () => {
</ThemeProvider>,
);
- const button = screen.getByRole("button", { name: "Connect Git (Beta)" });
+ const button = screen.getByRole("button", { name: "Connect Git" });
fireEvent.click(button);
diff --git a/app/client/src/git/components/QuickActions/ConnectButton.tsx b/app/client/src/git/components/QuickActions/ConnectButton.tsx
index b4f4f69647ae..49fa8aee7dc9 100644
--- a/app/client/src/git/components/QuickActions/ConnectButton.tsx
+++ b/app/client/src/git/components/QuickActions/ConnectButton.tsx
@@ -1,14 +1,7 @@
import React, { useMemo } from "react";
import styled from "styled-components";
-import {
- COMING_SOON,
- CONNECT_GIT_BETA,
- CONTACT_ADMIN_FOR_GIT,
- createMessage,
- NOT_LIVE_FOR_YOU_YET,
-} from "ee/constants/messages";
-
import { Button, Icon, Tooltip } from "@appsmith/ads";
+import { QUICK_ACTIONS } from "git/ee/constants/messages";
const CenterDiv = styled.div`
text-align: center;
@@ -41,13 +34,13 @@ function ConnectButton({ isConnectPermitted, onClick }: ConnectButtonProps) {
const isTooltipEnabled = !isConnectPermitted;
const tooltipContent = useMemo(() => {
if (!isConnectPermitted) {
- return <CenterDiv>{createMessage(CONTACT_ADMIN_FOR_GIT)}</CenterDiv>;
+ return <CenterDiv>{QUICK_ACTIONS.CONNECT_BTN_CONTACT_ADMIN}</CenterDiv>;
}
return (
<>
- <div>{createMessage(NOT_LIVE_FOR_YOU_YET)}</div>
- <div>{createMessage(COMING_SOON)}</div>
+ <div>{QUICK_ACTIONS.CONNECT_BTN_NOT_LIVE_YET}</div>
+ <div>{QUICK_ACTIONS.CONNECT_BTN_COMING_SOON}</div>
</>
);
}, [isConnectPermitted]);
@@ -68,7 +61,7 @@ function ConnectButton({ isConnectPermitted, onClick }: ConnectButtonProps) {
onClick={onClick}
size="sm"
>
- {createMessage(CONNECT_GIT_BETA)}
+ {QUICK_ACTIONS.CONNECT_BTN_CTA}
</Button>
</Container>
</Tooltip>
diff --git a/app/client/src/pages/common/ImportModal.tsx b/app/client/src/pages/common/ImportModal.tsx
index 5eb89e3d2daf..d22ddffd0e13 100644
--- a/app/client/src/pages/common/ImportModal.tsx
+++ b/app/client/src/pages/common/ImportModal.tsx
@@ -174,8 +174,9 @@ function GitImportCard(props: { children?: ReactNode; handler?: () => void }) {
AnalyticsUtil.logEvent("GS_IMPORT_VIA_GIT_CARD_CLICK");
props.handler && props.handler();
}, []);
+ const isGitModEnabled = useGitModEnabled();
const message = createMessage(IMPORT_APP_FROM_GIT_MESSAGE);
- const title = createMessage(IMPORT_APP_FROM_GIT_TITLE);
+ const title = createMessage(IMPORT_APP_FROM_GIT_TITLE, !isGitModEnabled);
return (
<CardWrapper onClick={onClick}>
|
e9cd435c96dc36fe6796106da955736ff7949e80
|
2021-12-14 13:32:06
|
Ayangade Adeoluwa
|
feat: UQI Pagination Component implementation (#9446)
| false
|
UQI Pagination Component implementation (#9446)
|
feat
|
diff --git a/app/client/src/components/formControls/PaginationControl.tsx b/app/client/src/components/formControls/PaginationControl.tsx
new file mode 100644
index 000000000000..0ef73c48b082
--- /dev/null
+++ b/app/client/src/components/formControls/PaginationControl.tsx
@@ -0,0 +1,126 @@
+import React from "react";
+import BaseControl, { ControlProps } from "./BaseControl";
+import { ControlType } from "constants/PropertyControlConstants";
+import FormControl from "pages/Editor/FormControl";
+import FormLabel from "components/editorComponents/FormLabel";
+import { Colors } from "constants/Colors";
+import styled from "styled-components";
+
+export const StyledFormLabel = styled(FormLabel)`
+ margin-top: 5px;
+ font-weight: 400;
+ font-size: 12px;
+ color: ${Colors.GREY_7};
+ line-height: 16px;
+`;
+
+export const FormControlContainer = styled.div`
+ display: flex;
+ flex-direction: column;
+ margin-bottom: 10px;
+`;
+
+// using query dynamic input text for both so user can dynamically change these values.
+const valueFieldConfig: any = {
+ key: "value",
+ controlType: "QUERY_DYNAMIC_INPUT_TEXT",
+ placeholderText: "value",
+};
+
+const limitFieldConfig: any = {
+ ...valueFieldConfig,
+ placeholderText: "20",
+};
+
+const offsetFieldConfig: any = {
+ ...valueFieldConfig,
+ placeholderText: "0",
+};
+
+export function Pagination(props: {
+ label: string;
+ isValid: boolean;
+ validationMessage?: string;
+ placeholder?: string;
+ isRequired?: boolean;
+ name: string;
+ disabled?: boolean;
+ customStyles?: any;
+ configProperty: string;
+ formName: string;
+}) {
+ const { configProperty, customStyles, formName, name } = props;
+
+ return (
+ <div data-cy={name} style={{ width: "50vh" }}>
+ {/* form control for Limit field */}
+ <FormControlContainer>
+ <FormControl
+ config={{
+ ...limitFieldConfig,
+ label: "Limit",
+ customStyles,
+ configProperty: `${configProperty}.limit`,
+ }}
+ formName={formName}
+ />
+ <StyledFormLabel>Limits the number of rows returned.</StyledFormLabel>
+ </FormControlContainer>
+
+ {/* form control for Offset field */}
+ <FormControlContainer>
+ <FormControl
+ config={{
+ ...offsetFieldConfig,
+ label: "Offset",
+ customStyles,
+ configProperty: `${configProperty}.offset`,
+ }}
+ formName={formName}
+ />
+ <StyledFormLabel>
+ No of rows that are skipped before starting to count.
+ </StyledFormLabel>
+ </FormControlContainer>
+ </div>
+ );
+}
+
+class PaginationControl extends BaseControl<PaginationControlProps> {
+ render() {
+ const {
+ configProperty, // JSON path for the pagination data
+ disabled,
+ formName, // Name of the form, used by redux-form lib to store the data in redux store
+ isValid,
+ label,
+ placeholderText,
+ validationMessage,
+ } = this.props;
+
+ return (
+ // pagination component
+ <Pagination
+ configProperty={configProperty}
+ disabled={disabled}
+ formName={formName}
+ isValid={isValid}
+ label={label}
+ name={configProperty}
+ placeholder={placeholderText}
+ validationMessage={validationMessage}
+ />
+ );
+ }
+
+ getControlType(): ControlType {
+ return "PAGINATION";
+ }
+}
+
+export interface PaginationControlProps extends ControlProps {
+ placeholderText: string;
+ disabled?: boolean;
+}
+
+export default PaginationControl;
diff --git a/app/client/src/utils/FormControlRegistry.tsx b/app/client/src/utils/FormControlRegistry.tsx
index eb9741f901e5..d9180d3f82fb 100644
--- a/app/client/src/utils/FormControlRegistry.tsx
+++ b/app/client/src/utils/FormControlRegistry.tsx
@@ -37,6 +37,9 @@ import FieldArrayControl, {
import WhereClauseControl, {
WhereClauseControlProps,
} from "components/formControls/WhereClauseControl";
+import PaginationControl, {
+ PaginationControlProps,
+} from "components/formControls/PaginationControl";
class FormControlRegistry {
static registerFormControlBuilders() {
@@ -109,6 +112,11 @@ class FormControlRegistry {
return <WhereClauseControl {...controlProps} />;
},
});
+ FormControlFactory.registerControlBuilder("PAGINATION", {
+ buildPropertyControl(controlProps: PaginationControlProps): JSX.Element {
+ return <PaginationControl {...controlProps} />;
+ },
+ });
}
}
|
d493fec1258be84c8d9a8b80158b164f614d5fda
|
2023-12-25 10:53:27
|
Nayan
|
fix: Clone git repo when file system is flushed or deleted (#29809)
| false
|
Clone git repo when file system is flushed or deleted (#29809)
|
fix
|
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 103660896121..1eee0c78d94c 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
@@ -1654,6 +1654,71 @@ private Flux<Application> updateDefaultBranchName(
}));
}
+ private Mono<List<GitBranchDTO>> handleRepoNotFoundException(String defaultApplicationId) {
+
+ // clone application to the local filesystem again and update the defaultBranch for the application
+ // list branch and compare with branch applications and checkout if not exists
+
+ return getApplicationById(defaultApplicationId).flatMap(application -> {
+ GitApplicationMetadata gitApplicationMetadata = application.getGitApplicationMetadata();
+ Path repoPath =
+ Paths.get(application.getWorkspaceId(), application.getId(), gitApplicationMetadata.getRepoName());
+ GitAuth gitAuth = gitApplicationMetadata.getGitAuth();
+ return gitExecutor
+ .cloneApplication(
+ repoPath,
+ gitApplicationMetadata.getRemoteUrl(),
+ gitAuth.getPrivateKey(),
+ gitAuth.getPublicKey())
+ .flatMap(defaultBranch -> gitExecutor.listBranches(repoPath))
+ .flatMap(gitBranchDTOList -> {
+ List<String> branchesToCheckout = new ArrayList<>();
+ for (GitBranchDTO gitBranchDTO : gitBranchDTOList) {
+ if (gitBranchDTO.getBranchName().startsWith("origin/")) {
+ // remove origin/ prefix from the remote branch name
+ String branchName = gitBranchDTO.getBranchName().replace("origin/", "");
+ // The root application is always there, no need to check out it again
+ if (!branchName.equals(gitApplicationMetadata.getBranchName())) {
+ branchesToCheckout.add(branchName);
+ }
+ } else if (gitBranchDTO
+ .getBranchName()
+ .equals(gitApplicationMetadata.getDefaultBranchName())) {
+ /*
+ We just cloned from the remote default branch.
+ Update the isDefault flag If it's also set as default in DB
+ */
+ gitBranchDTO.setDefault(true);
+ }
+ }
+
+ return Flux.fromIterable(branchesToCheckout)
+ .flatMap(branchName -> applicationService
+ .findByBranchNameAndDefaultApplicationId(
+ branchName,
+ application.getId(),
+ applicationPermission.getReadPermission())
+ // checkout the branch locally
+ .flatMap(application1 -> {
+ // Add the locally checked out branch to the branchList
+ GitBranchDTO gitBranchDTO = new GitBranchDTO();
+ gitBranchDTO.setBranchName(branchName);
+ // set the default branch flag if there's a match.
+ // This can happen when user has changed the default branch other than
+ // remote
+ gitBranchDTO.setDefault(gitApplicationMetadata
+ .getDefaultBranchName()
+ .equals(branchName));
+ gitBranchDTOList.add(gitBranchDTO);
+ return gitExecutor.checkoutRemoteBranch(repoPath, branchName);
+ })
+ // Return empty mono when the branched application is not in db
+ .onErrorResume(throwable -> Mono.empty()))
+ .then(Mono.just(gitBranchDTOList));
+ });
+ });
+ }
+
private Mono<String> syncDefaultBranchNameFromRemote(Path repoPath, Application rootApp) {
GitApplicationMetadata metadata = rootApp.getGitApplicationMetadata();
GitAuth gitAuth = metadata.getGitAuth();
@@ -1709,6 +1774,13 @@ protected Mono<List<GitBranchDTO>> getBranchList(
Path repoPath = objects.getT3();
return getBranchListWithDefaultBranchName(
rootApplication, repoPath, defaultBranchName, currentBranch, pruneBranches);
+ })
+ .onErrorResume(throwable -> {
+ if (throwable instanceof RepositoryNotFoundException) {
+ // this will clone the repo again
+ return handleRepoNotFoundException(defaultApplicationId);
+ }
+ return Mono.error(throwable);
});
return Mono.create(sink -> branchMono.subscribe(sink::success, sink::error, null, sink.currentContext()));
diff --git a/app/server/appsmith-server/src/test/java/com/appsmith/server/services/ce/GitServiceCETest.java b/app/server/appsmith-server/src/test/java/com/appsmith/server/services/ce/GitServiceCETest.java
index 504dd67fd6de..514c7ac26aed 100644
--- a/app/server/appsmith-server/src/test/java/com/appsmith/server/services/ce/GitServiceCETest.java
+++ b/app/server/appsmith-server/src/test/java/com/appsmith/server/services/ce/GitServiceCETest.java
@@ -4570,4 +4570,46 @@ public void toggleAutoCommit() {
})
.verifyComplete();
}
+
+ @Test
+ @WithUserDetails(value = "api_user")
+ public void listBranchForApplication_WhenLocalRepoDoesNotExist_RepoIsClonedFromRemote()
+ throws IOException, GitAPIException {
+ List<GitBranchDTO> branchList = List.of(
+ createGitBranchDTO("defaultBranch", false),
+ createGitBranchDTO("origin/defaultBranch", false),
+ createGitBranchDTO("origin/feature1", false));
+
+ Mockito.when(gitExecutor.listBranches(any(Path.class)))
+ .thenReturn(Mono.error(new RepositoryNotFoundException("repo not found"))) // throw exception first
+ .thenReturn(Mono.just(branchList)); // return list of branches later
+
+ Mockito.when(gitExecutor.cloneApplication(any(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString()))
+ .thenReturn(Mono.just("defaultBranch"));
+
+ Mockito.when(gitFileUtils.checkIfDirectoryIsEmpty(any(Path.class))).thenReturn(Mono.just(true));
+ Mockito.when(gitFileUtils.initializeReadme(any(Path.class), Mockito.anyString(), Mockito.anyString()))
+ .thenReturn(Mono.just(Paths.get("textPath")));
+
+ Mockito.when(gitExecutor.fetchRemote(
+ any(Path.class),
+ Mockito.anyString(),
+ Mockito.anyString(),
+ eq(false),
+ Mockito.anyString(),
+ Mockito.anyBoolean()))
+ .thenReturn(Mono.just("status"));
+
+ Application application1 = createApplicationConnectedToGit(
+ "listBranchForApplication_pruneBranchNoChangesInRemote_Success", "defaultBranch");
+
+ Mono<List<GitBranchDTO>> listMono =
+ gitService.listBranchForApplication(application1.getId(), false, "defaultBranch");
+
+ StepVerifier.create(listMono)
+ .assertNext(listBranch -> {
+ assertThat(listBranch.size()).isEqualTo(3);
+ })
+ .verifyComplete();
+ }
}
|
ca6ab330c5d364dcea1d70a6991141ff31373ced
|
2023-04-06 09:37:04
|
Aishwarya-U-R
|
test: test: Cypress - Automated tests for Elasticsearch datasource (#22101)
| false
|
test: Cypress - Automated tests for Elasticsearch datasource (#22101)
|
test
|
diff --git a/app/client/cypress/fixtures/datasources.json b/app/client/cypress/fixtures/datasources.json
index eaa385f1165d..217e55a4c198 100644
--- a/app/client/cypress/fixtures/datasources.json
+++ b/app/client/cypress/fixtures/datasources.json
@@ -29,6 +29,11 @@
"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": 5439,
"redshift-databaseName": "fakeapi",
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 a4746eaf7fbb..7e3c14f79536 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
@@ -12,9 +12,8 @@ before(() => {
});
describe("Test Suite to validate copy/delete/undo functionalites", function () {
- it.only("Drag and drop form widget and validate copy widget via toast message", function () {
+ it("Drag and drop form widget and validate copy widget via toast message", function () {
const modifierKey = Cypress.platform === "darwin" ? "meta" : "ctrl";
-
cy.openPropertyPane("formwidget");
cy.widgetText(
"FormTest",
@@ -32,6 +31,8 @@ describe("Test Suite to validate copy/delete/undo functionalites", function () {
"response.body.responseMeta.status",
200,
);
+ cy.wait(1000);
+ ee.SelectEntityByName("FormTestCopy");
cy.get("body").type("{del}", { force: true });
cy.wait("@updateLayout").should(
"have.nested.property",
diff --git a/app/client/cypress/integration/Regression_TestSuite/ServerSideTests/Datasources/ElasticSearch_Basic_Spec.ts b/app/client/cypress/integration/Regression_TestSuite/ServerSideTests/Datasources/ElasticSearch_Basic_Spec.ts
new file mode 100644
index 000000000000..0e530534d95c
--- /dev/null
+++ b/app/client/cypress/integration/Regression_TestSuite/ServerSideTests/Datasources/ElasticSearch_Basic_Spec.ts
@@ -0,0 +1,198 @@
+import * as _ from "../../../../support/Objects/ObjectsCore";
+
+let dsName: any, books: any;
+describe("Validate Elasticsearch DS", () => {
+ before("Create a new ElasticSearch DS", () => {
+ _.dataSources.CreateDataSource("Elasticsearch");
+ cy.get("@dsName").then(($dsName) => {
+ dsName = $dsName;
+ });
+ });
+
+ it("1. Validate POST/GET/PUT/DELETE", () => {
+ let singleBook = `{
+ "title": "The Lord of the Rings",
+ "author": "J.R.R. Tolkien",
+ "genre": ["Fantasy", "Adventure"],
+ "rating": 4.8,
+ "published_date": "1954-07-29",
+ "description": "The Lord of the Rings is an epic high fantasy novel written by English author and scholar J. R. R. Tolkien. The story began as a sequel to Tolkien's earlier fantasy book The Hobbit and soon developed into a much larger story."
+ }`;
+
+ let bulkBooks = `{ "index": {"_index": "books", "_id": "2"}}
+ { "title": "To Kill a Mockingbird", "author": "Harper Lee", "genre": ["Classic Literature", "Coming-of-Age"], "rating": 4.5, "published_date": "1960-07-11", "description": "To Kill a Mockingbird is a novel by Harper Lee, published in 1960. It is a coming-of-age story about a young girl named Scout Finch in a fictional town in Alabama during the Great Depression. The novel is renowned for its warmth and humor, despite dealing with serious issues of rape and racial inequality." }
+ { "index": {"_index": "books", "_id": "3"}}
+ { "title": "The Hitchhiker's Guide to the Galaxy", "author": "Douglas Adams", "genre": ["Science Fiction", "Comedy"], "rating": 4.4, "published_date": "1979-10-12", "description": "The Hitchhiker's Guide to the Galaxy is a comedy science fiction series created by Douglas Adams. It follows the misadventures of hapless human Arthur Dent and his alien friend Ford Prefect as they travel through space and time." }`;
+ _.dataSources.CreateQueryAfterDSSaved();
+
+ //POST - single record
+ _.dataSources.ValidateNSelectDropdown("Method", "GET", "POST");
+
+ _.agHelper.EnterValue("/books/_doc/1", {
+ propFieldName: "",
+ directInput: false,
+ inputFieldName: "Path",
+ });
+
+ _.agHelper.EnterValue(singleBook, {
+ propFieldName: "",
+ directInput: false,
+ inputFieldName: "Body",
+ });
+
+ _.dataSources.RunQuery();
+ cy.get("@postExecute").then((resObj: any) => {
+ books = JSON.parse(JSON.stringify(resObj.response.body.data.body.result));
+ expect(books).to.eq("created");
+ });
+
+ //GET - single record
+ _.dataSources.ValidateNSelectDropdown("Method", "POST", "GET");
+ _.agHelper.EnterValue("", {
+ propFieldName: "",
+ directInput: false,
+ inputFieldName: "Body",
+ });
+ _.dataSources.RunQuery();
+ cy.get("@postExecute").then((resObj: any) => {
+ books = JSON.parse(
+ JSON.stringify(resObj.response.body.data.body._source.title),
+ );
+ expect(books).to.eq("The Lord of the Rings");
+ });
+
+ //POST - bulk record
+ _.dataSources.ValidateNSelectDropdown("Method", "GET", "POST");
+
+ _.agHelper.EnterValue("/_bulk", {
+ propFieldName: "",
+ directInput: false,
+ inputFieldName: "Path",
+ });
+
+ //Not able to use below since, we need to enter new line at end
+ // _.agHelper.EnterValue(bulkBooks, {
+ // propFieldName: "",
+ // directInput: false,
+ // inputFieldName: "Body",
+ // });
+
+ _.agHelper.TypeIntoTextArea(_.dataSources._bodyCodeMirror, bulkBooks);
+
+ _.agHelper.PressEnter();
+
+ _.agHelper.Sleep();
+ _.dataSources.RunQuery();
+ cy.get("@postExecute").then((resObj: any) => {
+ expect(
+ JSON.parse(
+ JSON.stringify(resObj.response.body.data.body.items[0].index._id),
+ ),
+ ).to.eq("2");
+ expect(
+ JSON.parse(
+ JSON.stringify(resObj.response.body.data.body.items[1].index._id),
+ ),
+ ).to.eq("3");
+ });
+
+ //GET - All inserted record
+ _.dataSources.ValidateNSelectDropdown("Method", "POST", "GET");
+ _.agHelper.EnterValue("", {
+ propFieldName: "",
+ directInput: false,
+ inputFieldName: "Body",
+ });
+
+ _.agHelper.EnterValue("/books/_search", {
+ propFieldName: "",
+ directInput: false,
+ inputFieldName: "Path",
+ });
+ _.dataSources.RunQuery();
+ cy.get("@postExecute").then((resObj: any) => {
+ books = JSON.parse(
+ JSON.stringify(resObj.response.body.data.body.hits.total.value),
+ );
+ expect(books).to.eq(3);
+ });
+
+ //PUT - update
+ let updateBook = `{ "title": "Pride and Prejudice", "author": "Jane Austen", "genre": ["Romance", "Classic Literature"], "rating": 4.5, "published_date": "1813-01-28", "description": "Pride and Prejudice is a romantic novel by Jane Austen, first published in 1813. The story follows the main character Elizabeth Bennet as she deals with issues of manners, upbringing, morality, education, and marriage in the society of the landed gentry of the British Regency." }`;
+ _.dataSources.ValidateNSelectDropdown("Method", "GET", "PUT");
+
+ _.agHelper.EnterValue("/books/_doc/1", {
+ propFieldName: "",
+ directInput: false,
+ inputFieldName: "Path",
+ });
+
+ _.agHelper.EnterValue(updateBook, {
+ propFieldName: "",
+ directInput: false,
+ inputFieldName: "Body",
+ });
+ _.dataSources.RunQuery();
+
+ cy.get("@postExecute").then((resObj: any) => {
+ books = JSON.parse(JSON.stringify(resObj.response.body.data.body.result));
+ expect(books).to.eq("updated");
+ });
+
+ //GET - single record - after update
+ _.dataSources.ValidateNSelectDropdown("Method", "PUT", "GET");
+ _.agHelper.EnterValue("", {
+ propFieldName: "",
+ directInput: false,
+ inputFieldName: "Body",
+ });
+ _.dataSources.RunQuery();
+ cy.get("@postExecute").then((resObj: any) => {
+ books = JSON.parse(
+ JSON.stringify(resObj.response.body.data.body._source.title),
+ );
+ expect(books).to.eq("Pride and Prejudice");
+ });
+
+ //DELETE - single record
+ _.dataSources.ValidateNSelectDropdown("Method", "GET", "DELETE");
+
+ _.agHelper.EnterValue("/books/_doc/1", {
+ propFieldName: "",
+ directInput: false,
+ inputFieldName: "Path",
+ });
+ _.dataSources.RunQuery();
+
+ cy.get("@postExecute").then((resObj: any) => {
+ books = JSON.parse(JSON.stringify(resObj.response.body.data.body.result));
+ expect(books).to.eq("deleted");
+ });
+
+ //DELETE - all records
+ _.agHelper.EnterValue("/_all", {
+ propFieldName: "",
+ directInput: false,
+ inputFieldName: "Path",
+ });
+ _.dataSources.RunQuery();
+
+ cy.get("@postExecute").then((resObj: any) => {
+ books = JSON.parse(
+ JSON.stringify(resObj.response.body.data.body.acknowledged),
+ );
+ expect(books).to.be.true;
+ });
+ });
+
+ after("Delete the query & datasource", () => {
+ _.agHelper.ActionContextMenuWithInPane("Delete");
+ _.entityExplorer.SelectEntityByName(dsName, "Datasources");
+ _.entityExplorer.ActionContextMenuByEntityName(
+ dsName,
+ "Delete",
+ "Are you sure?",
+ );
+ _.agHelper.ValidateNetworkStatus("@deleteDatasource", 200);
+ });
+});
diff --git a/app/client/cypress/integration/Regression_TestSuite/ServerSideTests/Postgres_DataTypes/Binary_Spec.ts b/app/client/cypress/integration/Regression_TestSuite/ServerSideTests/Postgres_DataTypes/Binary_Spec.ts
index 487fabda18c6..7042c1e51c4e 100644
--- a/app/client/cypress/integration/Regression_TestSuite/ServerSideTests/Postgres_DataTypes/Binary_Spec.ts
+++ b/app/client/cypress/integration/Regression_TestSuite/ServerSideTests/Postgres_DataTypes/Binary_Spec.ts
@@ -173,7 +173,59 @@ describe("Binary Datatype tests", function () {
});
});
- it("6. Validating Binary (bytea) - escape, hex, base64 functions", () => {
+ it("6. Deleting records - binarytype", () => {
+ //_.entityExplorer.SelectEntityByName("Page1");//commenting 2 lines since case 6th is skipped!
+ //_.deployMode.DeployApp();
+ _.table.WaitUntilTableLoad();
+ _.table.SelectTableRow(1);
+ _.agHelper.ClickButton("DeleteQuery", 1);
+ _.agHelper.ValidateNetworkStatus("@postExecute", 200);
+ _.agHelper.ValidateNetworkStatus("@postExecute", 200);
+ _.agHelper.AssertElementAbsence(_.locators._spinner, 20000); //Allowing time for delete to be success
+ _.agHelper.Sleep(6000); //Allwowing time for delete to be success
+ _.table.ReadTableRowColumnData(1, 0).then(($cellData) => {
+ expect($cellData).not.to.eq("3"); //asserting 2nd record is deleted
+ });
+ _.table.ReadTableRowColumnData(1, 0, "v1", 200).then(($cellData) => {
+ expect($cellData).to.eq("2");
+ });
+
+ //Deleting all records from .table
+ _.agHelper.GetNClick(_.locators._deleteIcon);
+ _.agHelper.AssertElementVisible(_.locators._spanButton("Run InsertQuery"));
+ _.agHelper.Sleep(2000);
+ _.table.WaitForTableEmpty();
+ });
+
+ it("7. Inserting another record (to check serial column) - binarytype", () => {
+ imageNameToUpload = "Datatypes/Massachusetts.jpeg";
+
+ _.agHelper.ClickButton("Run InsertQuery");
+ _.agHelper.AssertElementVisible(_.locators._modal);
+
+ //_.agHelper.EnterInputText("Imagename", "Massachusetts");
+ _.agHelper.ClickButton("Select New Image");
+ _.agHelper.UploadFile(imageNameToUpload);
+
+ _.agHelper.ClickButton("Insert");
+ _.agHelper.AssertElementAbsence(_.locators._toastMsg); //Assert that Insert did not fail
+ _.agHelper.AssertElementVisible(_.locators._spanButton("Run InsertQuery"));
+ _.table.WaitUntilTableLoad();
+ _.agHelper.Sleep(2000); //for all rows with images to be populated
+ _.table.ReadTableRowColumnData(0, 0, "v1", 2000).then(($cellData) => {
+ expect($cellData).to.eq("4"); //asserting serial column is inserting fine in sequence
+ });
+ _.table.ReadTableRowColumnData(0, 1, "v1", 200).then(($cellData) => {
+ expect($cellData).to.eq("Massachusetts.jpeg");
+ });
+ _.table.AssertTableRowImageColumnIsLoaded(0, 2).then(($oldimage) => {
+ _.table.AssertTableRowImageColumnIsLoaded(0, 3).then(($newimage) => {
+ expect($oldimage).to.eq($newimage);
+ });
+ });
+ });
+
+ it("8. Validating Binary (bytea) - escape, hex, base64 functions", () => {
_.deployMode.NavigateBacktoEditor();
_.table.WaitUntilTableLoad();
_.entityExplorer.ExpandCollapseEntity("Queries/JS");
@@ -304,123 +356,71 @@ describe("Binary Datatype tests", function () {
_.entityExplorer.ExpandCollapseEntity("Queries/JS", false);
});
- it("7. Deleting records - binarytype", () => {
- _.entityExplorer.SelectEntityByName("Page1");
- _.deployMode.DeployApp();
- _.table.WaitUntilTableLoad();
- _.table.SelectTableRow(1);
- _.agHelper.ClickButton("DeleteQuery", 1);
- _.agHelper.ValidateNetworkStatus("@postExecute", 200);
- _.agHelper.ValidateNetworkStatus("@postExecute", 200);
- _.agHelper.AssertElementAbsence(_.locators._spinner, 20000); //Allowing time for delete to be success
- _.agHelper.Sleep(6000); //Allwowing time for delete to be success
- _.table.ReadTableRowColumnData(1, 0).then(($cellData) => {
- expect($cellData).not.to.eq("3"); //asserting 2nd record is deleted
- });
- _.table.ReadTableRowColumnData(1, 0, "v1", 200).then(($cellData) => {
- expect($cellData).to.eq("2");
- });
-
- //Deleting all records from .table
- _.agHelper.GetNClick(_.locators._deleteIcon);
- _.agHelper.AssertElementVisible(_.locators._spanButton("Run InsertQuery"));
- _.agHelper.Sleep(2000);
- _.table.WaitForTableEmpty();
- });
-
- it("8. Inserting another record (to check serial column) - binarytype", () => {
- imageNameToUpload = "Datatypes/Massachusetts.jpeg";
-
- _.agHelper.ClickButton("Run InsertQuery");
- _.agHelper.AssertElementVisible(_.locators._modal);
-
- //_.agHelper.EnterInputText("Imagename", "Massachusetts");
- _.agHelper.ClickButton("Select New Image");
- _.agHelper.UploadFile(imageNameToUpload);
-
- _.agHelper.ClickButton("Insert");
- _.agHelper.AssertElementAbsence(_.locators._toastMsg); //Assert that Insert did not fail
- _.agHelper.AssertElementVisible(_.locators._spanButton("Run InsertQuery"));
- _.table.WaitUntilTableLoad();
- _.agHelper.Sleep(2000); //for all rows with images to be populated
- _.table.ReadTableRowColumnData(0, 0, "v1", 2000).then(($cellData) => {
- expect($cellData).to.eq("4"); //asserting serial column is inserting fine in sequence
- });
- _.table.ReadTableRowColumnData(0, 1, "v1", 200).then(($cellData) => {
- expect($cellData).to.eq("Massachusetts.jpeg");
- });
- _.table.AssertTableRowImageColumnIsLoaded(0, 2).then(($oldimage) => {
- _.table.AssertTableRowImageColumnIsLoaded(0, 3).then(($newimage) => {
- expect($oldimage).to.eq($newimage);
- });
- });
- });
-
- after(
- "Validate Drop of the Newly Created - binarytype - Table & Verify Deletion of all created queries",
- () => {
- //Drop table
- _.deployMode.NavigateBacktoEditor();
- _.entityExplorer.ExpandCollapseEntity("Queries/JS");
- _.entityExplorer.SelectEntityByName("dropTable");
- _.dataSources.RunQuery();
- _.dataSources.ReadQueryTableResponse(0).then(($cellData) => {
- expect($cellData).to.eq("0"); //Success response for dropped _.table!
- });
- _.entityExplorer.ExpandCollapseEntity("Queries/JS", false);
- _.entityExplorer.ExpandCollapseEntity("Datasources");
- _.entityExplorer.ExpandCollapseEntity(dsName);
- _.entityExplorer.ActionContextMenuByEntityName(dsName, "Refresh");
- _.agHelper.AssertElementAbsence(
- _.entityExplorer._entityNameInExplorer("public.binarytype"),
- );
- _.entityExplorer.ExpandCollapseEntity(dsName, false);
- _.entityExplorer.ExpandCollapseEntity("Datasources", false);
-
- //Delete all queries
- _.dataSources.DeleteDatasouceFromWinthinDS(dsName, 409); //Since all queries exists
- _.entityExplorer.ExpandCollapseEntity("Queries/JS");
- _.entityExplorer.ActionContextMenuByEntityName(
- "createTable",
- "Delete",
- "Are you sure?",
- );
- _.entityExplorer.ActionContextMenuByEntityName(
- "deleteAllRecords",
- "Delete",
- "Are you sure?",
- );
- _.entityExplorer.ActionContextMenuByEntityName(
- "deleteRecord",
- "Delete",
- "Are you sure?",
- );
- _.entityExplorer.ActionContextMenuByEntityName(
- "dropTable",
- "Delete",
- "Are you sure?",
- );
- _.entityExplorer.ActionContextMenuByEntityName(
- "insertRecord",
- "Delete",
- "Are you sure?",
- );
- _.entityExplorer.ActionContextMenuByEntityName(
- "selectRecords",
- "Delete",
- "Are you sure?",
- );
- _.entityExplorer.ActionContextMenuByEntityName(
- "updateRecord",
- "Delete",
- "Are you sure?",
- );
-
- //Delete DS
- _.deployMode.DeployApp();
- _.deployMode.NavigateBacktoEditor();
- _.entityExplorer.ExpandCollapseEntity("Queries/JS");
- _.dataSources.DeleteDatasouceFromWinthinDS(dsName, 200);
- },
- );
+ // after(
+ // "Validate Drop of the Newly Created - binarytype - Table & Verify Deletion of all created queries",
+ // () => {
+ // //Drop table
+ // _.deployMode.NavigateBacktoEditor();
+ // _.entityExplorer.ExpandCollapseEntity("Queries/JS");
+ // _.entityExplorer.SelectEntityByName("dropTable");
+ // _.dataSources.RunQuery();
+ // _.dataSources.ReadQueryTableResponse(0).then(($cellData) => {
+ // expect($cellData).to.eq("0"); //Success response for dropped _.table!
+ // });
+ // _.entityExplorer.ExpandCollapseEntity("Queries/JS", false);
+ // _.entityExplorer.ExpandCollapseEntity("Datasources");
+ // _.entityExplorer.ExpandCollapseEntity(dsName);
+ // _.entityExplorer.ActionContextMenuByEntityName(dsName, "Refresh");
+ // _.agHelper.AssertElementAbsence(
+ // _.entityExplorer._entityNameInExplorer("public.binarytype"),
+ // );
+ // _.entityExplorer.ExpandCollapseEntity(dsName, false);
+ // _.entityExplorer.ExpandCollapseEntity("Datasources", false);
+
+ // //Delete all queries
+ // _.dataSources.DeleteDatasouceFromWinthinDS(dsName, 409); //Since all queries exists
+ // _.entityExplorer.ExpandCollapseEntity("Queries/JS");
+ // _.entityExplorer.ActionContextMenuByEntityName(
+ // "createTable",
+ // "Delete",
+ // "Are you sure?",
+ // );
+ // _.entityExplorer.ActionContextMenuByEntityName(
+ // "deleteAllRecords",
+ // "Delete",
+ // "Are you sure?",
+ // );
+ // _.entityExplorer.ActionContextMenuByEntityName(
+ // "deleteRecord",
+ // "Delete",
+ // "Are you sure?",
+ // );
+ // _.entityExplorer.ActionContextMenuByEntityName(
+ // "dropTable",
+ // "Delete",
+ // "Are you sure?",
+ // );
+ // _.entityExplorer.ActionContextMenuByEntityName(
+ // "insertRecord",
+ // "Delete",
+ // "Are you sure?",
+ // );
+ // _.entityExplorer.ActionContextMenuByEntityName(
+ // "selectRecords",
+ // "Delete",
+ // "Are you sure?",
+ // );
+ // _.entityExplorer.ActionContextMenuByEntityName(
+ // "updateRecord",
+ // "Delete",
+ // "Are you sure?",
+ // );
+
+ // //Delete DS
+ // _.deployMode.DeployApp();
+ // _.deployMode.NavigateBacktoEditor();
+ // _.entityExplorer.ExpandCollapseEntity("Queries/JS");
+ // _.dataSources.DeleteDatasouceFromWinthinDS(dsName, 200);
+ // },
+ // );
});
diff --git a/app/client/cypress/integration/Regression_TestSuite/ServerSideTests/QueryPane/S3_1_spec.js b/app/client/cypress/integration/Regression_TestSuite/ServerSideTests/QueryPane/S3_1_spec.js
index 11c50d793b73..8f07c558362a 100644
--- a/app/client/cypress/integration/Regression_TestSuite/ServerSideTests/QueryPane/S3_1_spec.js
+++ b/app/client/cypress/integration/Regression_TestSuite/ServerSideTests/QueryPane/S3_1_spec.js
@@ -620,15 +620,16 @@ describe("Validate CRUD queries for Amazon S3 along with UI flow verifications",
);
//verify Deletion of file is success from UI also
- //Deleting the page:
- cy.actionContextMenuByEntityName(
- "Assets-test.appsmith.com",
- "Delete",
- "Are you sure?",
- );
+ // //Deleting the page://Commenting below since during re-runs the page name can be com2, com3 etc
+ // cy.actionContextMenuByEntityName(
+ // "Assets-test.appsmith.com",
+ // "Delete",
+ // "Are you sure?",
+ // );
});
it("7. Verify 'Add to widget [Widget Suggestion]' functionality - S3", () => {
+ _.entityExplorer.SelectEntityByName("Page1");
cy.NavigateToActiveDSQueryPane(datasourceName);
_.agHelper.GetObjectName().then(($queryName) => {
diff --git a/app/client/cypress/integration/SanitySuite/Datasources/FirestoreStub_Spec.ts b/app/client/cypress/integration/SanitySuite/Datasources/FirestoreStub_Spec.ts
deleted file mode 100644
index 39d653076c8f..000000000000
--- a/app/client/cypress/integration/SanitySuite/Datasources/FirestoreStub_Spec.ts
+++ /dev/null
@@ -1,18 +0,0 @@
-import { ObjectsRegistry } from "../../../support/Objects/Registry";
-
-let dataSources = ObjectsRegistry.DataSources,
- agHelper = ObjectsRegistry.AggregateHelper;
-
-describe("Firestore stub", function () {
- before(() => {
- dataSources.StartInterceptRoutesForFirestore();
- });
- it("1. Create, test, save then delete a Firestore datasource", function () {
- dataSources.NavigateToDSCreateNew();
- dataSources.CreatePlugIn("Firestore");
- agHelper.RenameWithInPane("Firestore-Stub", false);
- dataSources.FillFirestoreDSForm();
- dataSources.TestSaveDatasource(false);
- dataSources.DeleteDatasouceFromActiveTab("Firestore-Stub", 200);
- });
-});
diff --git a/app/client/cypress/support/Pages/AggregateHelper.ts b/app/client/cypress/support/Pages/AggregateHelper.ts
index 0520d30edd02..e9382e1897b8 100644
--- a/app/client/cypress/support/Pages/AggregateHelper.ts
+++ b/app/client/cypress/support/Pages/AggregateHelper.ts
@@ -858,6 +858,14 @@ export class AggregateHelper {
this.Sleep(500); //for value set to settle
}
+ public TypeIntoTextArea(selector: string, value: string) {
+ this.GetElement(selector)
+ .find("textarea")
+ .first()
+ .type(value, { delay: 0, force: true, parseSpecialCharSequences: false });
+ this.Sleep(500); //for value set to settle
+ }
+
public UpdateInputValue(selector: string, value: string) {
this.GetElement(selector)
.closest("input")
diff --git a/app/client/cypress/support/Pages/DataSources.ts b/app/client/cypress/support/Pages/DataSources.ts
index 7b62dbc11569..438e8b102c10 100644
--- a/app/client/cypress/support/Pages/DataSources.ts
+++ b/app/client/cypress/support/Pages/DataSources.ts
@@ -11,6 +11,7 @@ const DataSourceKVP = {
Airtable: "Airtable",
Arango: "ArangoDB",
Firestore: "Firestore",
+ Elasticsearch: "Elasticsearch",
}; //DataSources KeyValuePair
export enum Widgets {
@@ -188,6 +189,8 @@ export class DataSources {
_whereDelete = (index: number) =>
"[data-cy='t--where-clause-delete-[" + index + "]']";
+ _bodyCodeMirror = "//div[contains(@class, 't--actionConfiguration.body')]";
+
public AssertDSEditViewMode(mode: "Edit" | "View") {
if (mode == "Edit") this.agHelper.AssertElementAbsence(this._editButton);
else if (mode == "View") this.agHelper.AssertElementExist(this._editButton);
@@ -512,6 +515,27 @@ export class DataSources {
//});
}
+ public FillElasticSearchDSForm() {
+ this.agHelper.UpdateInputValue(
+ this._host,
+ datasourceFormData["elastic-host"],
+ );
+
+ this.agHelper.UpdateInputValue(
+ this._port,
+ datasourceFormData["elastic-port"].toString(),
+ );
+ this.ExpandSectionByName(this._sectionAuthentication);
+ this.agHelper.UpdateInputValue(
+ this._username,
+ datasourceFormData["elastic-username"],
+ );
+ this.agHelper.UpdateInputValue(
+ this._password,
+ datasourceFormData["elastic-password"],
+ );
+ }
+
public FillUnAuthenticatedGraphQLDSForm() {
this.agHelper.GetNClick(this._createBlankGraphQL);
this.apiPage.EnterURL(datasourceFormData.GraphqlApiUrl_TED);
@@ -826,7 +850,8 @@ export class DataSources {
| "MsSql"
| "Airtable"
| "Arango"
- | "Firestore",
+ | "Firestore"
+ | "Elasticsearch",
navigateToCreateNewDs = true,
testNSave = true,
) {
@@ -850,6 +875,8 @@ export class DataSources {
else if (DataSourceKVP[dsType] == "ArangoDB") this.FillArangoDSForm();
else if (DataSourceKVP[dsType] == "Firestore")
this.FillFirestoreDSForm();
+ else if (DataSourceKVP[dsType] == "Elasticsearch")
+ this.FillElasticSearchDSForm();
if (testNSave) {
this.TestSaveDatasource();
diff --git a/app/client/cypress/support/Pages/EntityExplorer.ts b/app/client/cypress/support/Pages/EntityExplorer.ts
index c4c36c85efef..3025906809a9 100644
--- a/app/client/cypress/support/Pages/EntityExplorer.ts
+++ b/app/client/cypress/support/Pages/EntityExplorer.ts
@@ -118,6 +118,7 @@ export class EntityExplorer {
}
public ExpandCollapseEntity(entityName: string, expand = true, index = 0) {
+ this.agHelper.AssertElementVisible(this._expandCollapseArrow(entityName));
cy.xpath(this._expandCollapseArrow(entityName))
.eq(index)
.invoke("attr", "name")
diff --git a/app/client/cypress/support/Pages/PropertyPane.ts b/app/client/cypress/support/Pages/PropertyPane.ts
index 48e4ed513d1e..b02d11994f92 100644
--- a/app/client/cypress/support/Pages/PropertyPane.ts
+++ b/app/client/cypress/support/Pages/PropertyPane.ts
@@ -232,7 +232,7 @@ export class PropertyPane {
cy.wrap($field).find(".CodeMirror-code span").first().invoke("text");
});
} else {
- cy.xpath(this.locator._codeMirrorCode).click();
+ this.agHelper.GetNClick(this.locator._codeMirrorCode);
val = cy
.xpath(
"//div[@class='CodeMirror-code']//span[contains(@class,'cm-m-javascript')]",
diff --git a/app/client/cypress/support/commands.js b/app/client/cypress/support/commands.js
index e57192ba4026..dd108a5e1753 100644
--- a/app/client/cypress/support/commands.js
+++ b/app/client/cypress/support/commands.js
@@ -1291,12 +1291,14 @@ Cypress.Commands.add("createSuperUser", () => {
//cy.wait(1000); //for toggles to settle
cy.get(welcomePage.createButton).should("be.visible");
- //cy.get(welcomePage.createButton).trigger("mouseover").click();
+ cy.get(welcomePage.createButton).trigger("mouseover").click();
//Seeing issue with above also, trying multiple click as below
//cy.get(welcomePage.createButton).click({ multiple: true });
+ //cy.get(welcomePage.createButton).trigger("click");
//Submit also not working
- cy.get(welcomePage.createSuperUser).submit();
+ //cy.get(welcomePage.createSuperUser).submit();
+ //cy.wait(5000); //waiting a bit before attempting logout
// cy.get("body").then(($ele) => {
// if ($ele.find(locator._spanButton("Next").length) > 0) {
@@ -1310,13 +1312,13 @@ Cypress.Commands.add("createSuperUser", () => {
// $jQueryButton.trigger("click"); // click on the button using jQuery
// });
- //commenting below until solved
- // cy.wait("@createSuperUser").then((interception) => {
- // expect(interception.request.body).contains(
- // "allowCollectingAnonymousData=true",
- // );
- // expect(interception.request.body).contains("signupForNewsletter=true");
- // });
+ //uncommenting below to analyse
+ cy.wait("@createSuperUser").then((interception) => {
+ expect(interception.request.body).contains(
+ "allowCollectingAnonymousData=true",
+ );
+ expect(interception.request.body).contains("signupForNewsletter=true");
+ });
cy.LogOut();
cy.wait(2000);
});
|
6e7c29355fbb90dc3844963f8236cd55f6a5e202
|
2023-06-08 12:48:38
|
Nidhi
|
chore: Upgraded Snake YAML version to 2.0 (#23572)
| false
|
Upgraded Snake YAML version to 2.0 (#23572)
|
chore
|
diff --git a/app/server/appsmith-server/pom.xml b/app/server/appsmith-server/pom.xml
index e27c80dccc3e..b4c67998b836 100644
--- a/app/server/appsmith-server/pom.xml
+++ b/app/server/appsmith-server/pom.xml
@@ -16,7 +16,7 @@
<description>This is the API server for the Appsmith project</description>
<properties>
- <ff4j.version>1.9</ff4j.version>
+ <ff4j.version>2.0.0</ff4j.version>
<org.modelmapper.version>2.4.4</org.modelmapper.version>
<jmh.version>1.35</jmh.version>
</properties>
@@ -361,11 +361,6 @@
<artifactId>ff4j-core</artifactId>
<version>${ff4j.version}</version>
</dependency>
- <dependency>
- <groupId>org.ff4j</groupId>
- <artifactId>ff4j-config-yaml</artifactId>
- <version>${ff4j.version}</version>
- </dependency>
<dependency>
<groupId>com.appsmith</groupId>
<artifactId>reactiveCaching</artifactId>
diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/configurations/FeatureFlagConfig.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/configurations/FeatureFlagConfig.java
index e262917c2f8f..bf7f6083faf3 100644
--- a/app/server/appsmith-server/src/main/java/com/appsmith/server/configurations/FeatureFlagConfig.java
+++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/configurations/FeatureFlagConfig.java
@@ -1,7 +1,7 @@
package com.appsmith.server.configurations;
import org.ff4j.FF4j;
-import org.ff4j.parser.yaml.YamlParser;
+import org.ff4j.conf.XmlParser;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@@ -10,7 +10,7 @@ public class FeatureFlagConfig {
@Bean
public FF4j ff4j() {
- return new FF4j(new YamlParser(), "features/init-flags.yml")
+ return new FF4j(new XmlParser(), "features/init-flags.xml")
.audit(true)
.autoCreate(true);
}
diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/featureflags/FeatureFlagEnum.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/featureflags/FeatureFlagEnum.java
index 072668274c6f..22464cc05d42 100644
--- a/app/server/appsmith-server/src/main/java/com/appsmith/server/featureflags/FeatureFlagEnum.java
+++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/featureflags/FeatureFlagEnum.java
@@ -6,10 +6,10 @@
/**
* This enum lists all the feature flags available along with their flipping strategy.
- * In order to create a new feature flag, create another enum entry and add the same string to {@link features/init-flags.yml}
+ * In order to create a new feature flag, create another enum entry and add the same string to {@link features/init-flags.xml}
* <p>
* If you wish to define a custom flipping strategy, define a class that implements {@link FlippingStrategy} and
- * ensure that you've mentioned this custom class when defining the feature in {@link features/init-flags.yml}
+ * ensure that you've mentioned this custom class when defining the feature in {@link features/init-flags.xml}
* <p>
* The feature flag implementation class should extend an existing feature flag implementation like {@link PonderationStrategy},
* {@link OfficeHourStrategy} etc. These default classes provide a lot of basic functionality out of the box.
diff --git a/app/server/appsmith-server/src/main/resources/features/init-flags.xml b/app/server/appsmith-server/src/main/resources/features/init-flags.xml
new file mode 100644
index 000000000000..033928a766a6
--- /dev/null
+++ b/app/server/appsmith-server/src/main/resources/features/init-flags.xml
@@ -0,0 +1,36 @@
+<?xml version="1.0" encoding="UTF-8" ?>
+<ff4j>
+ <autocreate>false</autocreate>
+ <audit>false</audit>
+ <features>
+ <feature uid="DATASOURCE_ENVIRONMENTS" enable="true"
+ description="Introducing multiple execution environments for datasources">
+ <flipstrategy class="com.appsmith.server.featureflags.strategies.EmailBasedRolloutStrategy">
+ <param name="emails"
+ value="[email protected],[email protected],[email protected],[email protected],[email protected]"/>
+ </flipstrategy>
+ </feature>
+ <feature uid="MULTIPLE_PANES" enable="true" description="Have multiple panes in the Appsmith IDE">
+ <flipstrategy class="com.appsmith.server.featureflags.strategies.EmailBasedRolloutStrategy">
+ <param name="emails" value="[email protected],[email protected]"/>
+ </flipstrategy>
+ </feature>
+ <feature uid="AUTO_LAYOUT" enable="true" description="Enable auto layout editor for everyone">
+ <flipstrategy class="org.ff4j.strategy.PonderationStrategy">
+ <param name="weight" value="1"/>
+ </flipstrategy>
+ </feature>
+ <feature uid="APP_NAVIGATION_LOGO_UPLOAD" enable="true"
+ description="Logo upload feature for app viewer navigation">
+ <flipstrategy class="com.appsmith.server.featureflags.strategies.EmailBasedRolloutStrategy">
+ <param name="emailDomains" value="appsmith.com,moolya.com"/>
+ </flipstrategy>
+ </feature>
+ <feature uid="ONE_CLICK_BINDING" enable="true"
+ description="Show property controls to generate queries for table widget with just clicks">
+ <flipstrategy class="com.appsmith.server.featureflags.strategies.EmailBasedRolloutStrategy">
+ <param name="emails" value="[email protected],[email protected]"/>
+ </flipstrategy>
+ </feature>
+ </features>
+</ff4j>
\ No newline at end of file
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
deleted file mode 100644
index 22148aa01538..000000000000
--- a/app/server/appsmith-server/src/main/resources/features/init-flags.yml
+++ /dev/null
@@ -1,56 +0,0 @@
-# Check sample file at: https://github.com/ff4j/ff4j-samples/blob/master/spring-boot-2x/ff4j-sample-springboot2x/src/main/resources/ff4j-init-dataset.yml
-
-# -----------------------------
-# Core FF4J
-# -----------------------------
-ff4j:
- autocreate: false
- audit: false
-
- features:
- - uid: DATASOURCE_ENVIRONMENTS
- enable: true
- description: Introducing multiple execution environments for datasources
- flipstrategy:
- class: com.appsmith.server.featureflags.strategies.EmailBasedRolloutStrategy
- param:
- - name: emails
- value: [email protected],[email protected],[email protected],[email protected],[email protected]
-
- - uid: MULTIPLE_PANES
- enable: true
- description: Have multiple panes in the Appsmith IDE
- flipstrategy:
- class: com.appsmith.server.featureflags.strategies.EmailBasedRolloutStrategy
- param:
- - name: emails
- value: [email protected],[email protected]
-
- - uid: AUTO_LAYOUT
- enable: true
- description: Enable auto layout editor for everyone
- flipstrategy:
- class: org.ff4j.strategy.PonderationStrategy
- param:
- - name: weight
- value: 1
-
- - uid: APP_NAVIGATION_LOGO_UPLOAD
- enable: true
- description: Logo upload feature for app viewer navigation
- flipstrategy:
- class: com.appsmith.server.featureflags.strategies.EmailBasedRolloutStrategy
- param:
- - name: emailDomains
- value: appsmith.com,moolya.com
-
- # Put EE flags below this line, to avoid conflicts.
-
- - uid: ONE_CLICK_BINDING
- enable: true
- description: Show property controls to generate queries for table widget with just clicks
- flipstrategy:
- class: com.appsmith.server.featureflags.strategies.EmailBasedRolloutStrategy
- param:
- - name: emails
- value: [email protected],[email protected]
diff --git a/app/server/appsmith-server/src/test/java/com/appsmith/server/services/FeatureFlagServiceTest.java b/app/server/appsmith-server/src/test/java/com/appsmith/server/services/FeatureFlagServiceTest.java
index 2a75659acf05..3825a141b608 100644
--- a/app/server/appsmith-server/src/test/java/com/appsmith/server/services/FeatureFlagServiceTest.java
+++ b/app/server/appsmith-server/src/test/java/com/appsmith/server/services/FeatureFlagServiceTest.java
@@ -3,7 +3,7 @@
import com.appsmith.server.featureflags.FeatureFlagEnum;
import lombok.extern.slf4j.Slf4j;
import org.ff4j.FF4j;
-import org.ff4j.parser.yaml.YamlParser;
+import org.ff4j.conf.XmlParser;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
@@ -86,7 +86,7 @@ static class TestFeatureFlagConfig {
@Bean
FF4j ff4j() {
- FF4j ff4j = new FF4j(new YamlParser(), "features/init-flags-test.yml")
+ FF4j ff4j = new FF4j(new XmlParser(), "features/init-flags-test.xml")
.audit(true)
.autoCreate(false);
return ff4j;
diff --git a/app/server/appsmith-server/src/test/resources/features/init-flags-test.xml b/app/server/appsmith-server/src/test/resources/features/init-flags-test.xml
new file mode 100644
index 000000000000..5273ee9d2b4c
--- /dev/null
+++ b/app/server/appsmith-server/src/test/resources/features/init-flags-test.xml
@@ -0,0 +1,24 @@
+<?xml version="1.0" encoding="UTF-8" ?>
+<ff4j>
+ <autocreate>false</autocreate>
+ <audit>false</audit>
+ <features>
+ <feature uid="TEST_FEATURE_1" enable="true"
+ description="The test feature should only be visible to Appsmith users">
+ <flipstrategy class="com.appsmith.server.featureflags.strategies.AppsmithUserStrategy">
+ <param name="requiredKey" value="requiredValue"/>
+ </flipstrategy>
+ </feature>
+ <feature uid="TEST_FEATURE_2" enable="true" description="Enable this feature based on weight. It's randomized.">
+ <flipstrategy class="org.ff4j.strategy.PonderationStrategy">
+ <param name="weight" value="1"/>
+ </flipstrategy>
+ </feature>
+ <feature uid="TEST_FEATURE_3" enable="true"
+ description="The test feature should only be visible to certain users">
+ <flipstrategy class="com.appsmith.server.featureflags.strategies.EmailBasedRolloutStrategy">
+ <param name="emailDomains" value="[email protected]"/>
+ </flipstrategy>
+ </feature>
+ </features>
+</ff4j>
diff --git a/app/server/appsmith-server/src/test/resources/features/init-flags-test.yml b/app/server/appsmith-server/src/test/resources/features/init-flags-test.yml
deleted file mode 100644
index 944d2c6a85d7..000000000000
--- a/app/server/appsmith-server/src/test/resources/features/init-flags-test.yml
+++ /dev/null
@@ -1,37 +0,0 @@
-# Check sample file at: https://github.com/ff4j/ff4j-samples/blob/master/spring-boot-2x/ff4j-sample-springboot2x/src/main/resources/ff4j-init-dataset.yml
-
-# -----------------------------
-# Core FF4J configuration for testing. DO NOT USE THIS IN PRODUCTION
-# -----------------------------
-ff4j:
- autocreate: false
- audit: false
-
- features:
-
- - uid: TEST_FEATURE_1
- enable: true
- description: The test feature should only be visible to Appsmith users
- flipstrategy:
- class: com.appsmith.server.featureflags.strategies.AppsmithUserStrategy
- param:
- - name: requiredKey
- value: requiredValue
-
- - uid: TEST_FEATURE_2
- enable: true
- description: Enable this feature based on weight. It's randomized.
- flipstrategy:
- class: org.ff4j.strategy.PonderationStrategy
- param:
- - name: weight
- value: 1
-
- - uid: TEST_FEATURE_3
- enable: true
- description: The test feature should only be visible to certain users
- flipstrategy:
- class: com.appsmith.server.featureflags.strategies.EmailBasedRolloutStrategy
- param:
- - name: emailDomains
- value: [email protected]
\ No newline at end of file
diff --git a/app/server/pom.xml b/app/server/pom.xml
index e947ab879ec5..13cdbf09216f 100644
--- a/app/server/pom.xml
+++ b/app/server/pom.xml
@@ -35,6 +35,8 @@
<reactor-test.version>3.5.1</reactor-test.version>
<maven.compiler.source>${java.version}</maven.compiler.source>
<maven.compiler.target>${java.version}</maven.compiler.target>
+ <!-- We're forcing this version temporarily to fix CVE-2022-1471-->
+ <snakeyaml.version>2.0</snakeyaml.version>
</properties>
<build>
|
f2ae7695d84c2d707e7c3901e5fb8b70fa280437
|
2023-09-21 11:29:09
|
Vemparala Surya Vamsi
|
fix: revert skip klona (#27503)
| false
|
revert skip klona (#27503)
|
fix
|
diff --git a/app/client/src/workers/common/DataTreeEvaluator/index.ts b/app/client/src/workers/common/DataTreeEvaluator/index.ts
index cf1fb653d555..a87a3fb5da42 100644
--- a/app/client/src/workers/common/DataTreeEvaluator/index.ts
+++ b/app/client/src/workers/common/DataTreeEvaluator/index.ts
@@ -344,8 +344,7 @@ export default class DataTreeEvaluator {
const evaluationOrder = this.sortedDependencies;
// Evaluate
const { evalMetaUpdates, evaluatedTree, staleMetaIds } = this.evaluateTree(
- //we need to deep clone oldUnEvalTree because evaluateTree will mutate it
- klona(this.oldUnEvalTree),
+ this.oldUnEvalTree,
evaluationOrder,
undefined,
this.oldConfigTree,
@@ -782,7 +781,6 @@ export default class DataTreeEvaluator {
evaluatedTree: newEvalTree,
staleMetaIds,
} = this.evaluateTree(
- // should not clone evalTree unnessarily because it is anyways being overwritten in the subsequent statement
this.evalTree,
evaluationOrder,
{
@@ -924,7 +922,7 @@ export default class DataTreeEvaluator {
}
evaluateTree(
- dataTree: DataTree,
+ oldUnevalTree: DataTree,
evaluationOrder: Array<string>,
options: {
isFirstTree: boolean;
@@ -941,8 +939,10 @@ export default class DataTreeEvaluator {
evalMetaUpdates: EvalMetaUpdates;
staleMetaIds: string[];
} {
+ const tree = klona(oldUnevalTree);
+
errorModifier.updateAsyncFunctions(
- dataTree,
+ tree,
this.getConfigTree(),
this.dependencyMap,
);
@@ -1168,7 +1168,7 @@ export default class DataTreeEvaluator {
return set(currentTree, fullPropertyPath, evalPropertyValue);
}
},
- dataTree,
+ tree,
);
return {
@@ -1181,7 +1181,7 @@ export default class DataTreeEvaluator {
type: EvalErrorTypes.EVAL_TREE_ERROR,
message: (error as Error).message,
});
- return { evaluatedTree: dataTree, evalMetaUpdates, staleMetaIds: [] };
+ return { evaluatedTree: tree, evalMetaUpdates, staleMetaIds: [] };
}
}
@@ -1472,9 +1472,7 @@ export default class DataTreeEvaluator {
// setting parseValue in dataTree
set(currentTree, fullPropertyPath, parsedValue);
// setting evalPropertyValue in unParsedEvalTree
- // cloning evalPropertyValue because parsedValue and evalPropertyValue could be equal, they both could share the same reference
- //hence we are cloning evalPropertyValue to seperate them
- set(this.getUnParsedEvalTree(), fullPropertyPath, klona(evalPropertyValue));
+ set(this.getUnParsedEvalTree(), fullPropertyPath, evalPropertyValue);
}
reValidateWidgetDependentProperty({
diff --git a/app/client/src/workers/common/DataTreeEvaluator/test.ts b/app/client/src/workers/common/DataTreeEvaluator/test.ts
index 1c4dc3ae3c8c..7b78bbe6914c 100644
--- a/app/client/src/workers/common/DataTreeEvaluator/test.ts
+++ b/app/client/src/workers/common/DataTreeEvaluator/test.ts
@@ -16,7 +16,6 @@ import { replaceThisDotParams } from "./utils";
import { isDataField } from "./utils";
import widgets from "widgets";
import type { WidgetConfiguration } from "WidgetProvider/constants";
-import { klona } from "klona";
const widgetConfigMap: Record<
string,
@@ -360,7 +359,7 @@ describe("DataTreeEvaluator", () => {
nonDynamicFieldValidationOrder: nonDynamicFieldValidationOrder5,
unEvalUpdates,
} = dataTreeEvaluator.setupUpdateTree(
- klona(nestedArrayAccessorCyclicDependency.apiSuccessUnEvalTree),
+ nestedArrayAccessorCyclicDependency.apiSuccessUnEvalTree,
nestedArrayAccessorCyclicDependencyConfig.apiSuccessConfigTree,
);
dataTreeEvaluator.evalAndValidateSubTree(
@@ -424,7 +423,7 @@ describe("DataTreeEvaluator", () => {
nonDynamicFieldValidationOrder,
unEvalUpdates,
} = dataTreeEvaluator.setupUpdateTree(
- klona(nestedArrayAccessorCyclicDependency.apiSuccessUnEvalTree),
+ nestedArrayAccessorCyclicDependency.apiSuccessUnEvalTree,
nestedArrayAccessorCyclicDependencyConfig.apiSuccessConfigTree,
);
dataTreeEvaluator.evalAndValidateSubTree(
@@ -471,7 +470,7 @@ describe("DataTreeEvaluator", () => {
nonDynamicFieldValidationOrder: nonDynamicFieldValidationOrder2,
unEvalUpdates,
} = dataTreeEvaluator.setupUpdateTree(
- klona(nestedArrayAccessorCyclicDependency.apiSuccessUnEvalTree),
+ nestedArrayAccessorCyclicDependency.apiSuccessUnEvalTree,
nestedArrayAccessorCyclicDependencyConfig.apiSuccessConfigTree,
);
dataTreeEvaluator.evalAndValidateSubTree(
|
0e49c6efa9dc87f508c1664186c8adbd76e4f3e7
|
2022-08-31 23:38:42
|
Ayangade Adeoluwa
|
fix: replace action execution cancellation toast errors with a better one (#16277)
| false
|
replace action execution cancellation toast errors with a better one (#16277)
|
fix
|
diff --git a/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/BugTests/AbortAction_Spec.ts b/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/BugTests/AbortAction_Spec.ts
index 11163b064740..6bd0e42c81d0 100644
--- a/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/BugTests/AbortAction_Spec.ts
+++ b/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/BugTests/AbortAction_Spec.ts
@@ -1,6 +1,6 @@
import { ObjectsRegistry } from "../../../../support/Objects/Registry";
-let agHelper = ObjectsRegistry.AggregateHelper,
+const agHelper = ObjectsRegistry.AggregateHelper,
locator = ObjectsRegistry.CommonLocators,
apiPage = ObjectsRegistry.ApiPage,
dataSources = ObjectsRegistry.DataSources;
@@ -10,22 +10,23 @@ let dsName: any;
const largeResponseApiUrl = "https://api.publicapis.org/entries";
//"https://jsonplaceholder.typicode.com/photos";//Commenting since this is faster sometimes & case is failing
-const ERROR_ACTION_EXECUTE_FAIL = (actionName: any) =>
- `${actionName} action returned an error response`;
+export const ACTION_EXECUTION_CANCELLED = (actionName: string) =>
+ `${actionName} was cancelled`;
describe("Abort Action Execution", function() {
- it("1. Bug #14006 - Cancel Request button should abort API action execution", function() {
+ it("1. Bug #14006, #16093 - Cancel Request button should abort API action execution", function() {
apiPage.CreateAndFillApi(largeResponseApiUrl, "AbortApi", 0);
apiPage.RunAPI(false, 0);
agHelper.GetNClick(locator._cancelActionExecution, 0, true);
- agHelper.AssertContains(ERROR_ACTION_EXECUTE_FAIL("AbortApi"));
- agHelper.ActionContextMenuWithInPane("Delete", "Are you sure?")
+ agHelper.AssertContains(ACTION_EXECUTION_CANCELLED("AbortApi"));
+ agHelper.AssertElementAbsence(locator._specificToast("{}")); //Assert that empty toast does not appear - Bug #16093
+ agHelper.ActionContextMenuWithInPane("Delete", "Are you sure?");
});
// Queries were resolving quicker than we could cancel them
// Commenting this out till we can find a query that resolves slow enough for us to cancel its execution.
- it("2. Bug #14006 Cancel Request button should abort Query action execution", function() {
+ it("2. Bug #14006, #16093 Cancel Request button should abort Query action execution", function() {
dataSources.CreateDataSource("MySql");
cy.get("@dsName").then(($dsName) => {
dsName = $dsName;
@@ -37,8 +38,9 @@ describe("Abort Action Execution", function() {
dataSources.SetQueryTimeout(0);
dataSources.RunQuery(false, false, 0);
agHelper.GetNClick(locator._cancelActionExecution, 0, true);
- agHelper.AssertContains(ERROR_ACTION_EXECUTE_FAIL("AbortQuery"));
- agHelper.ActionContextMenuWithInPane("Delete", "Are you sure?")
+ agHelper.AssertContains(ACTION_EXECUTION_CANCELLED("AbortQuery"));
+ agHelper.AssertElementAbsence(locator._specificToast("{}")); //Assert that empty toast does not appear - Bug #16093
+ agHelper.ActionContextMenuWithInPane("Delete", "Are you sure?");
dataSources.DeleteDatasouceFromWinthinDS(dsName);
});
});
diff --git a/app/client/src/api/ApiUtils.ts b/app/client/src/api/ApiUtils.ts
index 524fe9676198..4d410ec53148 100644
--- a/app/client/src/api/ApiUtils.ts
+++ b/app/client/src/api/ApiUtils.ts
@@ -17,6 +17,7 @@ import { logoutUser } from "actions/userActions";
import { AUTH_LOGIN_URL } from "constants/routes";
import { getCurrentGitBranch } from "selectors/gitSyncSelectors";
import getQueryParamsObject from "utils/getQueryParamsObject";
+import { UserCancelledActionExecutionError } from "sagas/ActionExecution/errorUtils";
const executeActionRegex = /actions\/execute/;
const timeoutErrorRegex = /timeout of (\d+)ms exceeded/;
@@ -77,7 +78,7 @@ export const apiFailureResponseInterceptor = (error: any) => {
// Return if the call was cancelled via cancel token
if (axios.isCancel(error)) {
- return;
+ throw new UserCancelledActionExecutionError();
}
// Return modified response if action execution failed
diff --git a/app/client/src/ce/constants/messages.ts b/app/client/src/ce/constants/messages.ts
index 355b33b1a3a6..2980afc23068 100644
--- a/app/client/src/ce/constants/messages.ts
+++ b/app/client/src/ce/constants/messages.ts
@@ -222,6 +222,8 @@ export const ERROR_DATEPICKER_MAX_DATE = () =>
export const ERROR_WIDGET_DOWNLOAD = (err: string) => `Download failed. ${err}`;
export const ERROR_PLUGIN_ACTION_EXECUTE = (actionName: string) =>
`${actionName} failed to execute`;
+export const ACTION_EXECUTION_CANCELLED = (actionName: string) =>
+ `${actionName} was cancelled`;
export const ERROR_FAIL_ON_PAGE_LOAD_ACTIONS = () =>
`Failed to execute actions during page load`;
export const ERROR_ACTION_EXECUTE_FAIL = (actionName: string) =>
diff --git a/app/client/src/components/editorComponents/ApiResponseView.tsx b/app/client/src/components/editorComponents/ApiResponseView.tsx
index 6cd5d3a288ca..efed32f26bb3 100644
--- a/app/client/src/components/editorComponents/ApiResponseView.tsx
+++ b/app/client/src/components/editorComponents/ApiResponseView.tsx
@@ -216,7 +216,7 @@ type Props = ReduxStateProps &
export const EMPTY_RESPONSE: ActionResponse = {
statusCode: "",
duration: "",
- body: {},
+ body: "",
headers: {},
request: {
headers: {},
diff --git a/app/client/src/sagas/ActionExecution/PluginActionSaga.ts b/app/client/src/sagas/ActionExecution/PluginActionSaga.ts
index c78f5092c102..299f4a69408a 100644
--- a/app/client/src/sagas/ActionExecution/PluginActionSaga.ts
+++ b/app/client/src/sagas/ActionExecution/PluginActionSaga.ts
@@ -43,6 +43,7 @@ import {
ERROR_ACTION_EXECUTE_FAIL,
ERROR_FAIL_ON_PAGE_LOAD_ACTIONS,
ERROR_PLUGIN_ACTION_EXECUTE,
+ ACTION_EXECUTION_CANCELLED,
} from "@appsmith/constants/messages";
import { Variant } from "components/ads/common";
import {
@@ -561,6 +562,19 @@ function* runActionSaga(
// When running from the pane, we just want to end the saga if the user has
// cancelled the call. No need to log any errors
if (e instanceof UserCancelledActionExecutionError) {
+ // cancel action but do not throw any error.
+ yield put({
+ type: ReduxActionErrorTypes.RUN_ACTION_ERROR,
+ payload: {
+ error: e.name,
+ id: reduxAction.payload.id,
+ show: false,
+ },
+ });
+ Toaster.show({
+ text: createMessage(ACTION_EXECUTION_CANCELLED, actionObject.name),
+ variant: Variant.danger,
+ });
return;
}
log.error(e);
@@ -910,14 +924,14 @@ function* executePluginActionSaga(
params,
);
- const response: ActionExecutionResponse = yield ActionAPI.executeAction(
- formData,
- timeout,
- );
- PerformanceTracker.stopAsyncTracking(
- PerformanceTransactionName.EXECUTE_ACTION,
- );
try {
+ const response: ActionExecutionResponse = yield ActionAPI.executeAction(
+ formData,
+ timeout,
+ );
+ PerformanceTracker.stopAsyncTracking(
+ PerformanceTransactionName.EXECUTE_ACTION,
+ );
yield validateResponse(response);
const payload = createActionExecutionResponse(response);
@@ -949,7 +963,11 @@ function* executePluginActionSaga(
response: EMPTY_RESPONSE,
}),
);
- throw new PluginActionExecutionError("Response not valid", false, response);
+ if (e instanceof UserCancelledActionExecutionError) {
+ throw new UserCancelledActionExecutionError();
+ }
+
+ throw new PluginActionExecutionError("Response not valid", false);
}
}
|
35241621ddfa69746f1c891b38a790fab272b43c
|
2023-06-30 13:26:30
|
Nidhi
|
chore: Policy utils split constructor failures (#24950)
| false
|
Policy utils split constructor failures (#24950)
|
chore
|
diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/EnvManagerImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/EnvManagerImpl.java
index 31e1d5dbc99a..1687b0df932b 100644
--- a/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/EnvManagerImpl.java
+++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/EnvManagerImpl.java
@@ -27,7 +27,6 @@ public EnvManagerImpl(SessionUserService sessionUserService,
UserService userService,
AnalyticsService analyticsService,
UserRepository userRepository,
- PolicySolution policySolution,
EmailSender emailSender,
CommonConfig commonConfig,
EmailConfig emailConfig,
@@ -40,8 +39,8 @@ public EnvManagerImpl(SessionUserService sessionUserService,
TenantService tenantService,
ObjectMapper objectMapper) {
- super(sessionUserService, userService, analyticsService, userRepository, policySolution, emailSender, commonConfig,
- emailConfig, javaMailSender, googleRecaptchaConfig, fileUtils, permissionGroupService, configService,
- userUtils, tenantService, objectMapper);
+ super(sessionUserService, userService, analyticsService, userRepository, emailSender, commonConfig, emailConfig,
+ javaMailSender, googleRecaptchaConfig, fileUtils, permissionGroupService, configService, userUtils,
+ tenantService, objectMapper);
}
}
diff --git a/app/server/appsmith-server/src/test/java/com/appsmith/server/solutions/EnvManagerTest.java b/app/server/appsmith-server/src/test/java/com/appsmith/server/solutions/EnvManagerTest.java
index 85592d883d85..bab3ca1b3b4d 100644
--- a/app/server/appsmith-server/src/test/java/com/appsmith/server/solutions/EnvManagerTest.java
+++ b/app/server/appsmith-server/src/test/java/com/appsmith/server/solutions/EnvManagerTest.java
@@ -53,8 +53,6 @@ public class EnvManagerTest {
@MockBean
private UserRepository userRepository;
@MockBean
- private PolicySolution policySolution;
- @MockBean
private EmailSender emailSender;
@MockBean
private CommonConfig commonConfig;
@@ -83,7 +81,6 @@ public void setup() {
userService,
analyticsService,
userRepository,
- policySolution,
emailSender,
commonConfig,
emailConfig,
|
69ea40c65c5d40c89d15d077b71be6f36471fdb1
|
2025-03-18 19:24:35
|
Hetu Nandu
|
fix: Outside binding autocomplete rules update (#39772)
| false
|
Outside binding autocomplete rules update (#39772)
|
fix
|
diff --git a/app/client/src/components/editorComponents/CodeEditor/codeEditorUtils.ts b/app/client/src/components/editorComponents/CodeEditor/codeEditorUtils.ts
index 3a65273d024d..8ef9624d3ae8 100644
--- a/app/client/src/components/editorComponents/CodeEditor/codeEditorUtils.ts
+++ b/app/client/src/components/editorComponents/CodeEditor/codeEditorUtils.ts
@@ -187,5 +187,9 @@ export const shouldShowAutocompleteWithBindingBrackets = (
// Split the value by whitespace
const stringSegments = value.split(/\s+/);
- return stringSegments.length === 1;
+ const isOneWord = stringSegments.length === 1;
+
+ const hasDot = value.includes(".");
+
+ return isOneWord && !hasDot;
};
diff --git a/app/client/src/components/editorComponents/CodeEditor/hintHelpers.ts b/app/client/src/components/editorComponents/CodeEditor/hintHelpers.ts
index cafcc0f2db75..cbbee285e5e8 100644
--- a/app/client/src/components/editorComponents/CodeEditor/hintHelpers.ts
+++ b/app/client/src/components/editorComponents/CodeEditor/hintHelpers.ts
@@ -46,11 +46,13 @@ export const bindingHintHelper: HintHelper = (editor: CodeMirror.Editor) => {
CodemirrorTernService.setEntityInformation(editor, entityInformation);
}
- let shouldShow = true;
+ let shouldShow = false;
if (additionalData?.isJsEditor) {
if (additionalData?.enableAIAssistance) {
shouldShow = !isAISlashCommand(editor);
+ } else {
+ shouldShow = true;
}
} else if (shouldShowAutocompleteWithBindingBrackets(editor)) {
shouldShow = true;
diff --git a/app/client/src/utils/autocomplete/CodemirrorTernService.ts b/app/client/src/utils/autocomplete/CodemirrorTernService.ts
index 3b01bb5a757d..3a7a10fce49d 100644
--- a/app/client/src/utils/autocomplete/CodemirrorTernService.ts
+++ b/app/client/src/utils/autocomplete/CodemirrorTernService.ts
@@ -7,8 +7,10 @@ import {
getDynamicStringSegments,
isDynamicValue,
} from "utils/DynamicBindingUtils";
-import type { FieldEntityInformation } from "components/editorComponents/CodeEditor/EditorConfig";
-import { ENTITY_TYPE } from "ee/entities/DataTree/types";
+import {
+ EditorModes,
+ type FieldEntityInformation,
+} from "components/editorComponents/CodeEditor/EditorConfig";
import type { EntityTypeValue } from "ee/entities/DataTree/types";
import { AutocompleteSorter } from "./AutocompleteSortRules";
import { getCompletionsForKeyword } from "./keywordCompletion";
@@ -517,8 +519,8 @@ class CodeMirrorTernService {
const lineValue = this.lineValue(doc);
const cursor = cm.getCursor();
const { extraChars } = this.getFocusedDocValueAndPos(doc);
- const fieldIsJSAction =
- this.fieldEntityInformation.entityType === ENTITY_TYPE.JSACTION;
+ const fieldIsJSField =
+ this.fieldEntityInformation.mode === EditorModes.JAVASCRIPT;
let completions: Completion<TernCompletionResult>[] = [];
let after = "";
@@ -593,7 +595,7 @@ class CodeMirrorTernService {
isEntityName: isCompletionADataTreeEntityName,
};
- if (!isCursorInsideBinding && !fieldIsJSAction) {
+ if (!isCursorInsideBinding && !fieldIsJSField) {
codeMirrorCompletion.displayText = `{{${codeMirrorCompletion.displayText}}}`;
codeMirrorCompletion.text = `{{${codeMirrorCompletion.text}}}`;
}
@@ -645,7 +647,7 @@ class CodeMirrorTernService {
this.defEntityInformation.get(
this.fieldEntityInformation.entityName || "",
),
- !fieldIsJSAction,
+ !fieldIsJSField,
);
const indexToBeSelected =
completions.length && completions[0].isHeader ? 1 : 0;
|
b6443880234c2c67bc31c146715490bc29b60399
|
2023-02-15 21:57:27
|
Rishabh Rathod
|
chore: export batching method for ee PR (#20631)
| false
|
export batching method for ee PR (#20631)
|
chore
|
diff --git a/app/client/src/workers/Evaluation/fns/utils/TriggerEmitter.ts b/app/client/src/workers/Evaluation/fns/utils/TriggerEmitter.ts
index 2886d6de16ed..04dc39ab2a6c 100644
--- a/app/client/src/workers/Evaluation/fns/utils/TriggerEmitter.ts
+++ b/app/client/src/workers/Evaluation/fns/utils/TriggerEmitter.ts
@@ -21,7 +21,7 @@ const TriggerEmitter = new EventEmitter();
* @param task
* @returns
*/
-const priorityBatchedActionHandler = function(
+export const priorityBatchedActionHandler = function(
task: (batchedData: unknown[]) => void,
) {
let batchedData: unknown[] = [];
@@ -44,7 +44,7 @@ const priorityBatchedActionHandler = function(
* @param deferredTask
* @returns
*/
-const deferredBatchedActionHandler = function(
+export const deferredBatchedActionHandler = function(
deferredTask: (batchedData: unknown) => void,
) {
let batchedData: unknown[] = [];
|
9ef070d33a486a696b425b53935bed8a213af727
|
2023-06-09 15:14:58
|
Ivan Akulov
|
fix(eslint): fix direct `remixicon` imports in `packages/design-system/*` (#24010)
| false
|
fix direct `remixicon` imports in `packages/design-system/*` (#24010)
|
fix
|
diff --git a/app/client/.eslintrc.base.json b/app/client/.eslintrc.base.json
index 65a20d8f2780..6826984d32b4 100644
--- a/app/client/.eslintrc.base.json
+++ b/app/client/.eslintrc.base.json
@@ -54,7 +54,27 @@
{ "caseSensitive": false }
],
"no-console": "warn",
- "no-debugger": "warn"
+ "no-debugger": "warn",
+ "@typescript-eslint/no-restricted-imports": [
+ "error",
+ {
+ "patterns": [
+ {
+ "group": ["@blueprintjs/core/lib/esnext/*"],
+ "message": "Reason: @blueprintjs/core has both lib/esnext and lib/esm directories which export the same components. To avoid duplicating components in the bundle, please import only from the lib/esm directory."
+ },
+ {
+ "group": ["*.svg"],
+ "importNames": ["ReactComponent"],
+ "message": "Reason: Please don’t import SVG icons statically. (They won’t always be needed, but they *will* always be present in the bundle and will increase the bundle size.) Instead, please either import them as SVG paths (e.g. import starIconUrl from './star.svg'), or use the importSvg wrapper from design-system-old (e.g. const StarIcon = importSvg(() => import('./star.svg')))."
+ },
+ {
+ "group": ["remixicon-react/*"],
+ "message": "Reason: Please don’t import Remix icons statically. (They won’t always be needed, but they *will* always be present in the bundle and will increase the bundle size.) Instead, please use the importRemixIcon wrapper from design-system-old (e.g. const StarIcon = importRemixIcon(() => import('remixicon-react/Star')))."
+ }
+ ]
+ }
+ ]
},
"settings": {
"import/resolver": {
diff --git a/app/client/.eslintrc.js b/app/client/.eslintrc.js
index 7db2dd3ebe74..45bc21c710e8 100644
--- a/app/client/.eslintrc.js
+++ b/app/client/.eslintrc.js
@@ -1,5 +1,15 @@
// The `@type` comment improves auto-completion for VS Code users: https://github.com/appsmithorg/appsmith/pull/21602#discussion_r1144528505
/** @type {import('eslint').Linter.Config} */
+const fs = require("fs");
+const path = require("path");
+const JSON5 = require("json5");
+
+const baseEslintConfig = JSON5.parse(
+ fs.readFileSync(path.join(__dirname, "./.eslintrc.base.json"), "utf8"),
+);
+const baseNoRestrictedImports =
+ baseEslintConfig.rules["@typescript-eslint/no-restricted-imports"][1];
+
const eslintConfig = {
extends: ["./.eslintrc.base.json"],
rules: {
@@ -10,6 +20,7 @@ const eslintConfig = {
"error",
{
paths: [
+ ...(baseNoRestrictedImports.paths ?? []),
{
name: "codemirror",
message:
@@ -26,22 +37,7 @@ const eslintConfig = {
},
],
patterns: [
- {
- group: ["@blueprintjs/core/lib/esnext/*"],
- message:
- "Reason: @blueprintjs/core has both lib/esnext and lib/esm directories which export the same components. To avoid duplicating components in the bundle, please import only from the lib/esm directory.",
- },
- {
- group: ["*.svg"],
- importNames: ["ReactComponent"],
- message:
- "Reason: Please don’t import SVG icons statically. (They won’t always be needed, but they *will* always be present in the bundle and will increase the bundle size.) Instead, please either import them as SVG paths (e.g. import starIconUrl from './star.svg'), or use the importSvg wrapper from design-system-old (e.g. const StarIcon = importSvg(() => import('./star.svg'))).",
- },
- {
- group: ["remixicon-react/*"],
- message:
- "Reason: Please don’t import Remix icons statically. (They won’t always be needed, but they *will* always be present in the bundle and will increase the bundle size.) Instead, please use the importRemixIcon wrapper from design-system-old (e.g. const StarIcon = importRemixIcon(() => import('remixicon-react/Star'))).",
- },
+ ...(baseNoRestrictedImports.patterns ?? []),
{
group: ["**/ce/*"],
message: "Reason: Please use @appsmith import instead.",
diff --git a/app/client/package.json b/app/client/package.json
index 880f437fca0e..fe38d8c380d0 100644
--- a/app/client/package.json
+++ b/app/client/package.json
@@ -306,6 +306,7 @@
"jest-canvas-mock": "^2.3.1",
"jest-environment-jsdom": "^27.4.1",
"jest-styled-components": "^7.0.8",
+ "json5": "^2.2.3",
"lint-staged": "^13.2.0",
"msw": "^0.28.0",
"plop": "^3.1.1",
diff --git a/app/client/packages/design-system/headless/src/components/Checkbox/Checkbox.tsx b/app/client/packages/design-system/headless/src/components/Checkbox/Checkbox.tsx
index ae7ab969fc16..7bb5a7e064c6 100644
--- a/app/client/packages/design-system/headless/src/components/Checkbox/Checkbox.tsx
+++ b/app/client/packages/design-system/headless/src/components/Checkbox/Checkbox.tsx
@@ -1,18 +1,33 @@
import { mergeProps } from "@react-aria/utils";
import { useFocusRing } from "@react-aria/focus";
import { useHover } from "@react-aria/interactions";
-import CheckIcon from "remixicon-react/CheckLineIcon";
import { useToggleState } from "@react-stately/toggle";
import { useFocusableRef } from "@react-spectrum/utils";
-import SubtractIcon from "remixicon-react/SubtractLineIcon";
import React, { forwardRef, useContext, useRef } from "react";
import { useVisuallyHidden } from "@react-aria/visually-hidden";
import type { SpectrumCheckboxProps } from "@react-types/checkbox";
import type { FocusableRef, StyleProps } from "@react-types/shared";
import { useCheckbox, useCheckboxGroupItem } from "@react-aria/checkbox";
-
import { CheckboxGroupContext } from "./context";
+// Adapted from remixicon-react/CheckLineIcon (https://github.com/Remix-Design/RemixIcon/blob/f88a51b6402562c6c2465f61a3e845115992e4c6/icons/System/check-line.svg)
+const CheckIcon = ({ size }: { size: number }) => {
+ return (
+ <svg fill="currentColor" height={size} viewBox="0 0 24 24" width={size}>
+ <path d="m10 15.17 9.193-9.191 1.414 1.414-10.606 10.606-6.364-6.364 1.414-1.414 4.95 4.95Z" />
+ </svg>
+ );
+};
+
+// Adapted from remixicon-react/SubtractLineIcon (https://github.com/Remix-Design/RemixIcon/blob/f88a51b6402562c6c2465f61a3e845115992e4c6/icons/System/subtract-line.svg)
+const SubtractIcon = ({ size }: { size: number }) => {
+ return (
+ <svg fill="currentColor" height={size} viewBox="0 0 24 24" width={size}>
+ <path d="M5 11V13H19V11H5Z" />
+ </svg>
+ );
+};
+
export interface CheckboxProps
extends Omit<SpectrumCheckboxProps, keyof StyleProps> {
icon?: React.ReactNode;
diff --git a/app/client/packages/design-system/headless/src/components/Field/ErrorText.tsx b/app/client/packages/design-system/headless/src/components/Field/ErrorText.tsx
index 34d89074ba1c..27212c20283d 100644
--- a/app/client/packages/design-system/headless/src/components/Field/ErrorText.tsx
+++ b/app/client/packages/design-system/headless/src/components/Field/ErrorText.tsx
@@ -1,9 +1,17 @@
import React, { forwardRef } from "react";
import type { HTMLAttributes } from "react";
import { useDOMRef } from "@react-spectrum/utils";
-import AlertIcon from "remixicon-react/AlertFillIcon";
import type { DOMRef, SpectrumHelpTextProps } from "@react-types/shared";
+// Adapted from remixicon-react/AlertFillIcon (https://github.com/Remix-Design/RemixIcon/blob/f88a51b6402562c6c2465f61a3e845115992e4c6/icons/System/alert-fill.svg)
+const AlertIcon = () => {
+ return (
+ <svg fill="currentColor" height={24} viewBox="0 0 24 24" width={24}>
+ <path d="m12.865 3 9.526 16.5a1 1 0 0 1-.866 1.5H2.473a1 1 0 0 1-.866-1.5L11.133 3a1 1 0 0 1 1.732 0Zm-1.866 13v2h2v-2h-2Zm0-7v5h2V9h-2Z" />
+ </svg>
+ );
+};
+
interface HelpTextProps extends SpectrumHelpTextProps {
errorMessageProps?: HTMLAttributes<HTMLElement>;
}
diff --git a/app/client/packages/design-system/headless/src/components/Field/Label.tsx b/app/client/packages/design-system/headless/src/components/Field/Label.tsx
index 06b7573c99d7..fc0b3595314a 100644
--- a/app/client/packages/design-system/headless/src/components/Field/Label.tsx
+++ b/app/client/packages/design-system/headless/src/components/Field/Label.tsx
@@ -2,9 +2,23 @@ import React, { forwardRef } from "react";
import { useDOMRef } from "@react-spectrum/utils";
import type { DOMRef } from "@react-types/shared";
import { filterDOMProps } from "@react-aria/utils";
-import AsteriskIcon from "remixicon-react/AsteriskIcon";
import type { SpectrumLabelProps } from "@react-types/label";
+// Adapted from remixicon-react/AsteriskIcon (https://github.com/Remix-Design/RemixIcon/blob/f88a51b6402562c6c2465f61a3e845115992e4c6/icons/Editor/asterisk.svg)
+const AsteriskIcon = (props: { [key: string]: string | undefined }) => {
+ return (
+ <svg
+ fill="currentColor"
+ height={24}
+ viewBox="0 0 24 24"
+ width={24}
+ {...props}
+ >
+ <path d="M13 3v7.267l6.294-3.633 1 1.732L14 11.999l6.294 3.635-1 1.732-6.295-3.634V21h-2v-7.268l-6.294 3.634-1-1.732L9.998 12 3.705 8.366l1-1.732L11 10.267V3h2Z" />
+ </svg>
+ );
+};
+
export interface LabelProps extends SpectrumLabelProps {
isEmphasized?: boolean;
}
diff --git a/app/client/packages/design-system/widgets/src/components/Button/Button.test.tsx b/app/client/packages/design-system/widgets/src/components/Button/Button.test.tsx
index 558aa676aadf..3eba6bca2bb0 100644
--- a/app/client/packages/design-system/widgets/src/components/Button/Button.test.tsx
+++ b/app/client/packages/design-system/widgets/src/components/Button/Button.test.tsx
@@ -2,10 +2,24 @@ import React from "react";
import "@testing-library/jest-dom";
import { Icon } from "@design-system/headless";
import { render, screen } from "@testing-library/react";
-import EmotionHappyLineIcon from "remixicon-react/EmotionHappyLineIcon";
import { Button } from "./";
+// Adapted from remixicon-react/EmotionHappyLineIcon (https://github.com/Remix-Design/RemixIcon/blob/f88a51b6402562c6c2465f61a3e845115992e4c6/icons/User%20%26%20Faces/emotion-happy-line.svg)
+const EmotionHappyLineIcon = ({ ...props }: Record<string, any>) => {
+ return (
+ <svg
+ fill="currentColor"
+ height={24}
+ viewBox="0 0 24 24"
+ width={24}
+ {...props}
+ >
+ <path d="M12 22C6.477 22 2 17.523 2 12S6.477 2 12 2s10 4.477 10 10-4.477 10-10 10Zm0-2a8 8 0 1 0 0-16 8 8 0 0 0 0 16Zm-5-7h2a3 3 0 1 0 6 0h2a5 5 0 0 1-10 0Zm1-2a1.5 1.5 0 1 1 0-3 1.5 1.5 0 0 1 0 3Zm8 0a1.5 1.5 0 1 1 0-3 1.5 1.5 0 0 1 0 3Z" />
+ </svg>
+ );
+};
+
describe("@design-system/widgets/Button", () => {
it("renders children when passed", () => {
render(<Button>Click me</Button>);
diff --git a/app/client/packages/design-system/widgets/src/components/Checkbox/Checkbox.test.tsx b/app/client/packages/design-system/widgets/src/components/Checkbox/Checkbox.test.tsx
index 97b965fc9b74..91f6b3d87485 100644
--- a/app/client/packages/design-system/widgets/src/components/Checkbox/Checkbox.test.tsx
+++ b/app/client/packages/design-system/widgets/src/components/Checkbox/Checkbox.test.tsx
@@ -3,10 +3,24 @@ import "@testing-library/jest-dom";
import { Icon } from "@design-system/headless";
import { render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
-import EmotionHappyLineIcon from "remixicon-react/EmotionHappyLineIcon";
import { Checkbox } from "./Checkbox";
+// Adapted from remixicon-react/EmotionHappyLineIcon (https://github.com/Remix-Design/RemixIcon/blob/f88a51b6402562c6c2465f61a3e845115992e4c6/icons/User%20%26%20Faces/emotion-happy-line.svg)
+const EmotionHappyLineIcon = ({ ...props }: Record<string, any>) => {
+ return (
+ <svg
+ fill="currentColor"
+ height={24}
+ viewBox="0 0 24 24"
+ width={24}
+ {...props}
+ >
+ <path d="M12 22C6.477 22 2 17.523 2 12S6.477 2 12 2s10 4.477 10 10-4.477 10-10 10Zm0-2a8 8 0 1 0 0-16 8 8 0 0 0 0 16Zm-5-7h2a3 3 0 1 0 6 0h2a5 5 0 0 1-10 0Zm1-2a1.5 1.5 0 1 1 0-3 1.5 1.5 0 0 1 0 3Zm8 0a1.5 1.5 0 1 1 0-3 1.5 1.5 0 0 1 0 3Z" />
+ </svg>
+ );
+};
+
describe("@design-system/widgets/Checkbox", () => {
const onChangeSpy = jest.fn();
diff --git a/app/client/packages/design-system/widgets/src/components/Spinner/index.styled.tsx b/app/client/packages/design-system/widgets/src/components/Spinner/index.styled.tsx
index 59c2a0bc20e2..b7fbe84fe618 100644
--- a/app/client/packages/design-system/widgets/src/components/Spinner/index.styled.tsx
+++ b/app/client/packages/design-system/widgets/src/components/Spinner/index.styled.tsx
@@ -1,5 +1,27 @@
+import React from "react";
import styled from "styled-components";
-import LoaderIcon from "remixicon-react/Loader2FillIcon";
+
+// Adapted from remixicon-react/Loader2FillIcon (https://github.com/Remix-Design/RemixIcon/blob/f88a51b6402562c6c2465f61a3e845115992e4c6/icons/System/loader-2-fill.svg)
+function LoaderIcon({
+ className,
+ ...props
+}: {
+ className?: string;
+ [key: string]: any;
+}) {
+ return (
+ <svg
+ {...props}
+ className={className}
+ fill="currentColor"
+ height={24}
+ viewBox="0 0 24 24"
+ width={24}
+ >
+ <path d="M12 2a1 1 0 0 1 1 1v3a1 1 0 1 1-2 0V3a1 1 0 0 1 1-1Zm0 15a1 1 0 0 1 1 1v3a1 1 0 1 1-2 0v-3a1 1 0 0 1 1-1Zm10-5a1 1 0 0 1-1 1h-3a1 1 0 1 1 0-2h3a1 1 0 0 1 1 1ZM7 12a1 1 0 0 1-1 1H3a1 1 0 1 1 0-2h3a1 1 0 0 1 1 1Zm12.071 7.071a1 1 0 0 1-1.414 0l-2.121-2.121a1 1 0 0 1 1.414-1.414l2.121 2.12a1 1 0 0 1 0 1.415ZM8.464 8.464a1 1 0 0 1-1.414 0L4.93 6.344a1 1 0 0 1 1.414-1.415L8.464 7.05a1 1 0 0 1 0 1.414ZM4.93 19.071a1 1 0 0 1 0-1.414l2.121-2.121a1 1 0 0 1 1.414 1.414l-2.12 2.121a1 1 0 0 1-1.415 0ZM15.536 8.464a1 1 0 0 1 0-1.414l2.12-2.121a1 1 0 1 1 1.415 1.414L16.95 8.464a1 1 0 0 1-1.414 0Z" />
+ </svg>
+ );
+}
export const StyledSpinner = styled(LoaderIcon)`
animation: spin 1s linear infinite;
diff --git a/app/client/src/workers/Evaluation/fns/__tests__/interval.test.ts b/app/client/src/workers/Evaluation/fns/__tests__/interval.test.ts
index d474dd928efd..42963e86d4ad 100644
--- a/app/client/src/workers/Evaluation/fns/__tests__/interval.test.ts
+++ b/app/client/src/workers/Evaluation/fns/__tests__/interval.test.ts
@@ -80,7 +80,7 @@ describe("Tests for interval functions", () => {
// eslint-disable-next-line jest/no-disabled-tests
it.skip("Callback should have access to outer scope variables", async () => {
const stalker = jest.fn();
- function test() {
+ function runTest() {
let count = 0;
const interval = evalContext.setInterval(() => {
count++;
@@ -88,7 +88,7 @@ describe("Tests for interval functions", () => {
}, 100);
return interval;
}
- const interval = test();
+ const interval = runTest();
await new Promise((resolve) => setTimeout(resolve, 300));
clearInterval(interval);
expect(stalker).toBeCalledTimes(2);
diff --git a/app/client/yarn.lock b/app/client/yarn.lock
index 79dcc13bbce2..36c51842221b 100644
--- a/app/client/yarn.lock
+++ b/app/client/yarn.lock
@@ -9679,6 +9679,7 @@ __metadata:
js-regex-pl: ^1.0.1
js-sha256: ^0.9.0
jshint: ^2.13.4
+ json5: ^2.2.3
klona: ^2.0.5
libphonenumber-js: ^1.9.44
linkedom: ^0.14.20
|
dfff7c4a9fcd70ff99caa7e04bf49def3ed525ec
|
2023-09-12 11:18:03
|
Sumesh Pradhan
|
chore: disable allowprivilegeescalation in the securitycontext of helm chart (#27041)
| false
|
disable allowprivilegeescalation in the securitycontext of helm chart (#27041)
|
chore
|
diff --git a/deploy/helm/Chart.yaml b/deploy/helm/Chart.yaml
index 03cbfb3614f3..fbb6e0bc25d3 100644
--- a/deploy/helm/Chart.yaml
+++ b/deploy/helm/Chart.yaml
@@ -11,7 +11,7 @@ sources:
- https://github.com/appsmithorg/appsmith
home: https://www.appsmith.com/
icon: https://assets.appsmith.com/appsmith-icon.png
-version: 2.0.4
+version: 2.0.5
dependencies:
- condition: redis.enabled
name: redis
diff --git a/deploy/helm/Publish-helm-chart.md b/deploy/helm/Publish-helm-chart.md
index d33c33185ed1..4a1a41ae3ed6 100644
--- a/deploy/helm/Publish-helm-chart.md
+++ b/deploy/helm/Publish-helm-chart.md
@@ -8,6 +8,14 @@
* Create S3 bucket for Helm chart (naming as `helm.appsmith.com` \- Hosting S3 as Static web requires bucket name be the same with the domain\)
* Clone your Helm charts (ignore if already have Appsmith repo on machine)
+
+* Build Helm chart depencies
+
+```
+helm repo add bitnami https://charts.bitnami.com/bitnami
+helm dependency build ./deploy/helm
+```
+
* Package the local Helm chart
```
@@ -58,31 +66,55 @@ helm search repo appsmith --versions
helm install appsmith appsmith/appsmith --version 1.4.1
```
-## Upgrade your Helm repository (If need)
+## Upgrade your Helm repository
* Modify the chart
+
+* Change working directory
+
+```
+cd /deploy/helm
+```
+
+* Build Helm chart depencies
+
+```
+helm repo add bitnami https://charts.bitnami.com/bitnami
+helm dependency build .
+```
+
+* Note the latest appsmith helm-chart version
+```
+helm repo add appsmith http://helm.appsmith.com
+helm update
+helm search repo appsmith
+```
+
+* Update current iteration of helm chart version by editing `Chart.yaml`
+
* Package Helm chart
```
-helm package ./deploy/helm
+helm package .
```
* Push the new version to the Helm repository in Amazon S3
```
-aws s3 cp ./appsmith-1.4.1.tgz s3://helm.appsmith.com
+aws s3 cp ./appsmith-<version>.tgz s3://helm.appsmith.com
```
-* Create index file
+* Merge the index file with existing index
```
-helm repo index --url http://helm.appsmith.com
+curl http://helm.appsmith.com -o index.yaml
+helm repo index --url http://helm.appsmith.com --merge index.yaml
```
-* Push new `index.yaml` file into S3 bucket
+* Push updated `index.yaml` file into S3 bucket
```
-aws s3 cp ./index.yaml s3://helm.appsmith.com
+aws s3 cp index.yaml s3://helm.appsmith.com
```
* Verify the updated Helm chart
diff --git a/deploy/helm/templates/statefulset.yaml b/deploy/helm/templates/statefulset.yaml
index 240473ae0b28..c1cdcc219aa4 100644
--- a/deploy/helm/templates/statefulset.yaml
+++ b/deploy/helm/templates/statefulset.yaml
@@ -113,6 +113,8 @@ spec:
- secretRef:
name: {{ .Values.secretName }}
{{- end }}
+ securityContext:
+ allowPrivilegeEscalation: false
{{- if .Values.image.pullSecrets}}
imagePullSecrets:
- name: {{ .Values.image.pullSecrets }}
|
7b83973753aee382bde6607f994ee9e8229f5a10
|
2021-12-04 09:45:16
|
balajisoundar
|
chore: disable and assert disablility of teletry on CI (#9560)
| false
|
disable and assert disablility of teletry on CI (#9560)
|
chore
|
diff --git a/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/Auth/Analytics_spec.js b/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/Auth/Analytics_spec.js
index 1d1904df12d8..015a126c0e3f 100644
--- a/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/Auth/Analytics_spec.js
+++ b/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/Auth/Analytics_spec.js
@@ -4,12 +4,14 @@ let appId;
describe("Checks for analytics initialization", function() {
it("Should check analytics is not initialised when enableTelemtry is false", function() {
- cy.intercept("GET", "/api/v1/users/me", {
- body: { responseMeta: { status: 200, success: true }, data: User },
- }).as("getUsersWithoutTelemetry");
cy.visit("/applications");
cy.reload();
- cy.wait("@getUsersWithoutTelemetry");
+ cy.wait(3000);
+ cy.wait("@getUser").should(
+ "have.nested.property",
+ "response.body.data.enableTelemetry",
+ false,
+ );
cy.window().then((window) => {
expect(window.analytics).to.be.equal(undefined);
});
@@ -28,47 +30,12 @@ describe("Checks for analytics initialization", function() {
cy.wrap(interceptFlag).should("eq", false);
});
});
- it("Should check analytics is initialised when enableTelemtry is true", function() {
- cy.intercept("GET", "/api/v1/users/me", {
- body: {
- responseMeta: { status: 200, success: true },
- data: {
- ...User,
- enableTelemetry: true,
- },
- },
- }).as("getUsersWithTelemetry");
- cy.visit("/applications");
- cy.reload();
- cy.wait("@getUsersWithTelemetry");
- cy.wait(5000);
- cy.window().then((window) => {
- expect(window.analytics).not.to.be.undefined;
- });
- cy.wait(3000);
- let interceptFlag = false;
- cy.intercept("POST", "https://api.segment.io/**", (req) => {
- interceptFlag = true;
- req.continue();
- }).as("segment");
- cy.generateUUID().then((id) => {
- appId = id;
- cy.CreateAppInFirstListedOrg(id);
- localStorage.setItem("AppName", appId);
- });
- cy.wait("@segment");
- cy.window().then(() => {
- cy.wrap(interceptFlag).should("eq", true);
- });
- });
it("Should check smartlook is not initialised when enableTelemtry is false", function() {
- cy.intercept("GET", "/api/v1/users/me", {
- body: { responseMeta: { status: 200, success: true }, data: User },
- }).as("getUsersWithoutTelemetry");
cy.visit("/applications");
cy.reload();
- cy.wait("@getUsersWithoutTelemetry");
+ cy.wait(3000);
+ cy.wait("@getUser");
cy.window().then((window) => {
expect(window.smartlook).to.be.equal(undefined);
});
@@ -89,12 +56,10 @@ describe("Checks for analytics initialization", function() {
});
it("Should check Sentry is not initialised when enableTelemtry is false", function() {
- cy.intercept("GET", "/api/v1/users/me", {
- body: { responseMeta: { status: 200, success: true }, data: User },
- }).as("getUsersWithoutTelemetry");
cy.visit("/applications");
cy.reload();
- cy.wait("@getUsersWithoutTelemetry");
+ cy.wait(3000);
+ cy.wait("@getUser");
cy.window().then((window) => {
expect(window.Sentry).to.be.equal(undefined);
});
diff --git a/app/client/cypress/support/commands.js b/app/client/cypress/support/commands.js
index 9661c4ba5465..996249e69b35 100644
--- a/app/client/cypress/support/commands.js
+++ b/app/client/cypress/support/commands.js
@@ -3137,9 +3137,20 @@ Cypress.Commands.add("createSuperUser", () => {
cy.get(welcomePage.nextButton).click();
cy.get(welcomePage.newsLetter).should("be.visible");
cy.get(welcomePage.dataCollection).should("be.visible");
+ cy.get(welcomePage.dataCollection)
+ .trigger("mouseover")
+ .click();
+ cy.get(welcomePage.newsLetter)
+ .trigger("mouseover")
+ .click();
cy.get(welcomePage.createButton).should("be.visible");
cy.get(welcomePage.createButton).click();
- cy.wait("@createSuperUser");
+ cy.wait("@createSuperUser").then((interception) => {
+ expect(interception.request.body).not.contains(
+ "allowCollectingAnonymousData=true",
+ );
+ expect(interception.request.body).not.contains("signupForNewsletter=true");
+ });
cy.LogOut();
cy.wait(2000);
});
|
35774bb4f67c7421d45fd22a5e7416327e4658ea
|
2024-05-21 11:21:15
|
Shrikant Sharat Kandula
|
ci: Remove inert ADS compliance check (#33603)
| false
|
Remove inert ADS compliance check (#33603)
|
ci
|
diff --git a/.github/workflows/client-build.yml b/.github/workflows/client-build.yml
index 48b0f8fa26c9..01cb4bd9672f 100644
--- a/.github/workflows/client-build.yml
+++ b/.github/workflows/client-build.yml
@@ -70,6 +70,7 @@ jobs:
uses: actions/checkout@v4
with:
fetch-tags: true
+
- name: Get changed files in the client folder
id: changed-files-specific
uses: tj-actions/changed-files@v41
@@ -94,46 +95,6 @@ jobs:
script: |
await require("client-build-compliance.js")({core, github, context})
- - name: Get all the added or changed files in client/src folder
- if: inputs.ads-compliant-check == 'true' && inputs.pr != 0 && github.pull_request.base.ref == 'release' && (steps.changed-files-specific.outputs.any_changed == 'true' || github.event_name == 'push' || github.event_name == 'workflow_dispatch' || github.event_name == 'schedule')
- id: client_files
- uses: umani/[email protected]
- with:
- repo-token: ${{ secrets.APPSMITH_CI_TEST_PAT }}
- pattern: "app/client/src/.*"
- pr-number: ${{ inputs.pr }}
-
- # Check all the newly added files are in ts
- - name: ADS compliant check
- if: inputs.ads-compliant-check == 'true' && inputs.pr != 0 && github.pull_request.base.ref == 'release' && (steps.changed-files-specific.outputs.any_changed == 'true' || github.event_name == 'push' || github.event_name == 'workflow_dispatch' || github.event_name == 'schedule')
- id: ads_check
- run: |
- comment_files=""
- files=(${{steps.client_files.outputs.files_created}}${{steps.client_files.outputs.files_updated}})
- for file in "${files[@]}"; do
- while IFS= read -r line; do
- if echo "$line" | grep -q -E '(color|Color).*#|border.*#|(color|Color).*"'; then
- comment_files+=("$file")
- break
- fi
- done < ${file#app/client/}
- done
- unique_files=$(echo "${comment_files[@]}" | sort -u | sed '/^[[:space:]]*$/d' | sed 's/ / <li>/g')
- echo "ads_non_compliant_files=$unique_files" >> $GITHUB_OUTPUT
- echo "ads_non_compliant_count=${#unique_files[@]}" >> $GITHUB_OUTPUT
-
- # Comment in PR if test files are not written in ts and fail the workflow
- - name: Comment in PR if test files are not written in ts
- if: steps.ads_check.outputs.ads_non_compliant_count != 0 && inputs.ads-compliant-check == 'true' && inputs.pr != 0 && github.pull_request.base.ref == 'release' && (steps.changed-files-specific.outputs.any_changed == 'true' || github.event_name == 'push' || github.event_name == 'workflow_dispatch' || github.event_name == 'schedule')
- uses: peter-evans/create-or-update-comment@v3
- with:
- issue-number: ${{ inputs.pr }}
- body: |
- <b> 🔴 Below files are not compliant with ADS. Please fix and re-trigger ok-to-test </b>
- <ol>${{steps.ads_check.outputs.ads_non_compliant_files}}</ol>
- - if: steps.ads_check.outputs.ads_non_compliant_count != 0 && inputs.ads-compliant-check == 'true' && inputs.pr != 0 && github.pull_request.base.ref == 'release'
- run: exit 1
-
# In case this is second attempt try restoring status of the prior attempt from cache
- name: Restore the previous run result
if: steps.changed-files-specific.outputs.any_changed == 'true' || github.event_name == 'push' || github.event_name == 'workflow_dispatch' || github.event_name == 'schedule'
|
a73082d3700953942ec4edc3f38976a61e453afb
|
2024-06-06 10:57:55
|
Nidhi
|
ci: Comment hung test (#34006)
| false
|
Comment hung test (#34006)
|
ci
|
diff --git a/app/server/appsmith-server/src/test/java/com/appsmith/server/helpers/CacheableTemplateHelperTemplateJsonDataTest.java b/app/server/appsmith-server/src/test/java/com/appsmith/server/helpers/CacheableTemplateHelperTemplateJsonDataTest.java
index 588414615342..5da52cf69b41 100644
--- a/app/server/appsmith-server/src/test/java/com/appsmith/server/helpers/CacheableTemplateHelperTemplateJsonDataTest.java
+++ b/app/server/appsmith-server/src/test/java/com/appsmith/server/helpers/CacheableTemplateHelperTemplateJsonDataTest.java
@@ -1,36 +1,8 @@
package com.appsmith.server.helpers;
-import com.appsmith.server.configurations.CloudServicesConfig;
-import com.appsmith.server.constants.ArtifactType;
-import com.appsmith.server.domains.Application;
-import com.appsmith.server.dtos.ApplicationJson;
-import com.appsmith.server.dtos.ApplicationTemplate;
-import com.appsmith.server.dtos.CacheableApplicationJson;
-import com.appsmith.server.solutions.ApplicationPermission;
-import com.fasterxml.jackson.core.JsonProcessingException;
-import com.fasterxml.jackson.databind.ObjectMapper;
-import com.google.gson.Gson;
-import mockwebserver3.MockResponse;
-import mockwebserver3.MockWebServer;
-import org.junit.jupiter.api.AfterAll;
-import org.junit.jupiter.api.BeforeAll;
-import org.junit.jupiter.api.BeforeEach;
-import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
-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.MockBean;
-import org.springframework.boot.test.mock.mockito.SpyBean;
import org.springframework.test.context.junit.jupiter.SpringExtension;
-import reactor.core.publisher.Mono;
-import reactor.test.StepVerifier;
-
-import java.io.IOException;
-import java.time.Instant;
-
-import static org.assertj.core.api.Assertions.assertThat;
-import static org.mockito.ArgumentMatchers.any;
/**
* This test is written based on the inspiration from the tutorial:
@@ -39,153 +11,155 @@
@ExtendWith(SpringExtension.class)
@SpringBootTest
public class CacheableTemplateHelperTemplateJsonDataTest {
- private static final ObjectMapper objectMapper = new ObjectMapper();
- private static MockWebServer mockCloudServices;
-
- @MockBean
- ApplicationPermission applicationPermission;
-
- @MockBean
- private CloudServicesConfig cloudServicesConfig;
-
- @Autowired
- CacheableTemplateHelper cacheableTemplateHelper;
-
- @SpyBean
- CacheableTemplateHelper spyCacheableTemplateHelper;
-
- @BeforeAll
- public static void setUp() throws IOException {
- mockCloudServices = new MockWebServer();
- mockCloudServices.start();
- }
-
- @AfterAll
- public static void tearDown() throws IOException {
- mockCloudServices.shutdown();
- }
-
- @BeforeEach
- public void initialize() {
- String baseUrl = String.format("http://localhost:%s", mockCloudServices.getPort());
-
- // mock the cloud services config so that it returns mock server url as cloud
- // service base url
- Mockito.when(cloudServicesConfig.getBaseUrl()).thenReturn(baseUrl);
- }
-
- private ApplicationTemplate create(String id, String title) {
- ApplicationTemplate applicationTemplate = new ApplicationTemplate();
- applicationTemplate.setId(id);
- applicationTemplate.setTitle(title);
- return applicationTemplate;
- }
-
- /* Scenarios covered via this test:
- * 1. CacheableTemplateHelper doesn't have the POJO or has an empty POJO.
- * 2. Fetch the templates via the normal flow by mocking CS.
- * 3. Check if the CacheableTemplateHelper.getApplicationTemplateList() is the same as the object returned by the normal flow function. This will ensure that the cache is being set correctly.
- * 4. From the above steps we now have the cache set.
- * 5. Fetch the templates again, verify the data is the same as the one fetched in step 2.
- * 6. Verify the cache is used and not the mock. This is done by asserting the lastUpdated time of the cache.
- */
- @Test
- public void getApplicationJson_cacheIsEmpty_VerifyDataSavedInCache() throws JsonProcessingException {
- ApplicationJson applicationJson = new ApplicationJson();
- applicationJson.setArtifactJsonType(ArtifactType.APPLICATION);
- applicationJson.setExportedApplication(new Application());
-
- assertThat(cacheableTemplateHelper.getCacheableApplicationJsonMap().size())
- .isEqualTo(0);
-
- // mock the server to return a template when it's called
- mockCloudServices.enqueue(new MockResponse()
- .setBody(objectMapper.writeValueAsString(applicationJson))
- .addHeader("Content-Type", "application/json"));
-
- Mono<CacheableApplicationJson> templateListMono =
- cacheableTemplateHelper.getApplicationByTemplateId("templateId", cloudServicesConfig.getBaseUrl());
-
- final Instant[] timeFromCache = {Instant.now()};
- // make sure we've received the response returned by the mockCloudServices
- StepVerifier.create(templateListMono)
- .assertNext(cacheableApplicationJson1 -> {
- assertThat(cacheableApplicationJson1.getApplicationJson()).isNotNull();
- timeFromCache[0] = cacheableApplicationJson1.getCacheExpiryTime();
- })
- .verifyComplete();
-
- // Fetch the same application json again and verify the time stamp to confirm value is coming from POJO
- StepVerifier.create(cacheableTemplateHelper.getApplicationByTemplateId(
- "templateId", cloudServicesConfig.getBaseUrl()))
- .assertNext(cacheableApplicationJson1 -> {
- assertThat(cacheableApplicationJson1.getApplicationJson()).isNotNull();
- assertThat(cacheableApplicationJson1.getCacheExpiryTime()).isEqualTo(timeFromCache[0]);
- })
- .verifyComplete();
- assertThat(cacheableTemplateHelper.getCacheableApplicationJsonMap().size())
- .isEqualTo(1);
- }
-
- /* Scenarios covered via this test:
- * 1. Mock the cache isCacheValid to return false, so the cache is invalidated
- * 2. Fetch the templates again, verify the data is from the mock and not from the cache.
- */
- @Test
- public void getApplicationJson_cacheIsDirty_verifyDataIsFetchedFromSource() {
- ApplicationJson applicationJson = new ApplicationJson();
- Application test = new Application();
- test.setName("New Application");
- applicationJson.setArtifactJsonType(ArtifactType.APPLICATION);
- applicationJson.setExportedApplication(test);
-
- // mock the server to return the above three templates
- mockCloudServices.enqueue(new MockResponse()
- .setBody(new Gson().toJson(applicationJson))
- .addHeader("Content-Type", "application/json"));
-
- Mockito.doReturn(false).when(spyCacheableTemplateHelper).isCacheValid(any());
-
- // make sure we've received the response returned by the mock
- StepVerifier.create(spyCacheableTemplateHelper.getApplicationByTemplateId(
- "templateId", cloudServicesConfig.getBaseUrl()))
- .assertNext(cacheableApplicationJson1 -> {
- assertThat(cacheableApplicationJson1.getApplicationJson()).isNotNull();
- assertThat(cacheableApplicationJson1
- .getApplicationJson()
- .getExportedApplication()
- .getName())
- .isEqualTo("New Application");
- })
- .verifyComplete();
- }
-
- @Test
- public void getApplicationJson_cacheKeyIsMissing_verifyDataIsFetchedFromSource() {
- ApplicationJson applicationJson1 = new ApplicationJson();
- Application application = new Application();
- application.setName("Test Application");
- applicationJson1.setArtifactJsonType(ArtifactType.APPLICATION);
- applicationJson1.setExportedApplication(application);
-
- assertThat(cacheableTemplateHelper.getCacheableApplicationJsonMap().size())
- .isEqualTo(1);
-
- mockCloudServices.enqueue(new MockResponse()
- .setBody(new Gson().toJson(applicationJson1))
- .addHeader("Content-Type", "application/json"));
-
- // make sure we've received the response returned by the mock
- StepVerifier.create(cacheableTemplateHelper.getApplicationByTemplateId(
- "templateId1", cloudServicesConfig.getBaseUrl()))
- .assertNext(cacheableApplicationJson1 -> {
- assertThat(cacheableApplicationJson1.getApplicationJson()).isNotNull();
- assertThat(cacheableApplicationJson1
- .getApplicationJson()
- .getExportedApplication()
- .getName())
- .isEqualTo("Test Application");
- })
- .verifyComplete();
- }
+ // private static final ObjectMapper objectMapper = new ObjectMapper();
+ // private static MockWebServer mockCloudServices;
+ //
+ // @MockBean
+ // ApplicationPermission applicationPermission;
+ //
+ // @MockBean
+ // private CloudServicesConfig cloudServicesConfig;
+ //
+ // @Autowired
+ // CacheableTemplateHelper cacheableTemplateHelper;
+ //
+ // @SpyBean
+ // CacheableTemplateHelper spyCacheableTemplateHelper;
+ //
+ // @BeforeAll
+ // public static void setUp() throws IOException {
+ // mockCloudServices = new MockWebServer();
+ // mockCloudServices.start();
+ // }
+ //
+ // @AfterAll
+ // public static void tearDown() throws IOException {
+ // mockCloudServices.shutdown();
+ // }
+ //
+ // @BeforeEach
+ // public void initialize() {
+ // String baseUrl = String.format("http://localhost:%s", mockCloudServices.getPort());
+ //
+ // // mock the cloud services config so that it returns mock server url as cloud
+ // // service base url
+ // Mockito.when(cloudServicesConfig.getBaseUrl()).thenReturn(baseUrl);
+ // }
+ //
+ // private ApplicationTemplate create(String id, String title) {
+ // ApplicationTemplate applicationTemplate = new ApplicationTemplate();
+ // applicationTemplate.setId(id);
+ // applicationTemplate.setTitle(title);
+ // return applicationTemplate;
+ // }
+ //
+ // /* Scenarios covered via this test:
+ // * 1. CacheableTemplateHelper doesn't have the POJO or has an empty POJO.
+ // * 2. Fetch the templates via the normal flow by mocking CS.
+ // * 3. Check if the CacheableTemplateHelper.getApplicationTemplateList() is the same as the object returned by
+ // the normal flow function. This will ensure that the cache is being set correctly.
+ // * 4. From the above steps we now have the cache set.
+ // * 5. Fetch the templates again, verify the data is the same as the one fetched in step 2.
+ // * 6. Verify the cache is used and not the mock. This is done by asserting the lastUpdated time of the cache.
+ // */
+ // @Test
+ // public void getApplicationJson_cacheIsEmpty_VerifyDataSavedInCache() throws JsonProcessingException {
+ // ApplicationJson applicationJson = new ApplicationJson();
+ // applicationJson.setArtifactJsonType(ArtifactType.APPLICATION);
+ // applicationJson.setExportedApplication(new Application());
+ //
+ // assertThat(cacheableTemplateHelper.getCacheableApplicationJsonMap().size())
+ // .isEqualTo(0);
+ //
+ // // mock the server to return a template when it's called
+ // mockCloudServices.enqueue(new MockResponse()
+ // .setBody(objectMapper.writeValueAsString(applicationJson))
+ // .addHeader("Content-Type", "application/json"));
+ //
+ // Mono<CacheableApplicationJson> templateListMono =
+ // cacheableTemplateHelper.getApplicationByTemplateId("templateId",
+ // cloudServicesConfig.getBaseUrl());
+ //
+ // final Instant[] timeFromCache = {Instant.now()};
+ // // make sure we've received the response returned by the mockCloudServices
+ // StepVerifier.create(templateListMono)
+ // .assertNext(cacheableApplicationJson1 -> {
+ // assertThat(cacheableApplicationJson1.getApplicationJson()).isNotNull();
+ // timeFromCache[0] = cacheableApplicationJson1.getCacheExpiryTime();
+ // })
+ // .verifyComplete();
+ //
+ // // Fetch the same application json again and verify the time stamp to confirm value is coming from POJO
+ // StepVerifier.create(cacheableTemplateHelper.getApplicationByTemplateId(
+ // "templateId", cloudServicesConfig.getBaseUrl()))
+ // .assertNext(cacheableApplicationJson1 -> {
+ // assertThat(cacheableApplicationJson1.getApplicationJson()).isNotNull();
+ // assertThat(cacheableApplicationJson1.getCacheExpiryTime()).isEqualTo(timeFromCache[0]);
+ // })
+ // .verifyComplete();
+ // assertThat(cacheableTemplateHelper.getCacheableApplicationJsonMap().size())
+ // .isEqualTo(1);
+ // }
+ //
+ // /* Scenarios covered via this test:
+ // * 1. Mock the cache isCacheValid to return false, so the cache is invalidated
+ // * 2. Fetch the templates again, verify the data is from the mock and not from the cache.
+ // */
+ // @Test
+ // public void getApplicationJson_cacheIsDirty_verifyDataIsFetchedFromSource() {
+ // ApplicationJson applicationJson = new ApplicationJson();
+ // Application test = new Application();
+ // test.setName("New Application");
+ // applicationJson.setArtifactJsonType(ArtifactType.APPLICATION);
+ // applicationJson.setExportedApplication(test);
+ //
+ // // mock the server to return the above three templates
+ // mockCloudServices.enqueue(new MockResponse()
+ // .setBody(new Gson().toJson(applicationJson))
+ // .addHeader("Content-Type", "application/json"));
+ //
+ // Mockito.doReturn(false).when(spyCacheableTemplateHelper).isCacheValid(any());
+ //
+ // // make sure we've received the response returned by the mock
+ // StepVerifier.create(spyCacheableTemplateHelper.getApplicationByTemplateId(
+ // "templateId", cloudServicesConfig.getBaseUrl()))
+ // .assertNext(cacheableApplicationJson1 -> {
+ // assertThat(cacheableApplicationJson1.getApplicationJson()).isNotNull();
+ // assertThat(cacheableApplicationJson1
+ // .getApplicationJson()
+ // .getExportedApplication()
+ // .getName())
+ // .isEqualTo("New Application");
+ // })
+ // .verifyComplete();
+ // }
+ //
+ // @Test
+ // public void getApplicationJson_cacheKeyIsMissing_verifyDataIsFetchedFromSource() {
+ // ApplicationJson applicationJson1 = new ApplicationJson();
+ // Application application = new Application();
+ // application.setName("Test Application");
+ // applicationJson1.setArtifactJsonType(ArtifactType.APPLICATION);
+ // applicationJson1.setExportedApplication(application);
+ //
+ // assertThat(cacheableTemplateHelper.getCacheableApplicationJsonMap().size())
+ // .isEqualTo(1);
+ //
+ // mockCloudServices.enqueue(new MockResponse()
+ // .setBody(new Gson().toJson(applicationJson1))
+ // .addHeader("Content-Type", "application/json"));
+ //
+ // // make sure we've received the response returned by the mock
+ // StepVerifier.create(cacheableTemplateHelper.getApplicationByTemplateId(
+ // "templateId1", cloudServicesConfig.getBaseUrl()))
+ // .assertNext(cacheableApplicationJson1 -> {
+ // assertThat(cacheableApplicationJson1.getApplicationJson()).isNotNull();
+ // assertThat(cacheableApplicationJson1
+ // .getApplicationJson()
+ // .getExportedApplication()
+ // .getName())
+ // .isEqualTo("Test Application");
+ // })
+ // .verifyComplete();
+ // }
}
|
512108be4308eaa0b88182c47135e64beea83756
|
2023-07-05 13:27:36
|
Nilesh Sarupriya
|
chore: limit the number of users to 1 + number of system generated emails (#25096)
| false
|
limit the number of users to 1 + number of system generated emails (#25096)
|
chore
|
diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/CustomUserRepositoryCEImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/CustomUserRepositoryCEImpl.java
index f20c701b751a..1dfbc406a1bb 100644
--- a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/CustomUserRepositoryCEImpl.java
+++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/CustomUserRepositoryCEImpl.java
@@ -78,7 +78,8 @@ public Mono<User> findByEmailAndTenantId(String email, String tenantId) {
public Mono<Boolean> isUsersEmpty() {
final Query q = query(new Criteria());
q.fields().include(fieldName(QUser.user.email));
- q.limit(2);
+ // Basically limit to system generated emails plus 1 more.
+ q.limit(getSystemGeneratedUserEmails().size() + 1);
return mongoOperations.find(q, User.class)
.filter(user -> !getSystemGeneratedUserEmails().contains(user.getEmail()))
.count()
|
e5208b090e3450ba6fa64f2340ed193ab123f88f
|
2022-03-31 10:15:58
|
Bhavin K
|
fix: updated word-break for modal only (#12192)
| false
|
updated word-break for modal only (#12192)
|
fix
|
diff --git a/app/client/src/widgets/TextWidget/component/index.tsx b/app/client/src/widgets/TextWidget/component/index.tsx
index 117eb5a4a1ff..cd541cad5a49 100644
--- a/app/client/src/widgets/TextWidget/component/index.tsx
+++ b/app/client/src/widgets/TextWidget/component/index.tsx
@@ -169,6 +169,7 @@ const Content = styled.div<{
color: ${(props) => props?.textColor};
max-height: 70vh;
overflow: auto;
+ word-break: break-all;
text-align: ${(props) => props.textAlign.toLowerCase()};
font-style: ${(props) =>
props?.fontStyle?.includes(FontStyleTypes.ITALIC) ? "italic" : ""};
|
de23ea9d61e7c0ad267bea33533b65a64bfd5211
|
2022-07-30 00:42:56
|
Shrikant Sharat Kandula
|
feat: JSON Session serialization on Redis (#15368)
| false
|
JSON Session serialization on Redis (#15368)
|
feat
|
diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/configurations/RedisConfig.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/configurations/RedisConfig.java
index 671610b28ac9..c7743fe5e826 100644
--- a/app/server/appsmith-server/src/main/java/com/appsmith/server/configurations/RedisConfig.java
+++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/configurations/RedisConfig.java
@@ -1,5 +1,7 @@
package com.appsmith.server.configurations;
+import com.appsmith.server.domains.UserSession;
+import com.fasterxml.jackson.databind.json.JsonMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@@ -8,13 +10,19 @@
import org.springframework.data.redis.core.ReactiveRedisOperations;
import org.springframework.data.redis.core.ReactiveRedisTemplate;
import org.springframework.data.redis.listener.ChannelTopic;
+import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.JdkSerializationRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
+import org.springframework.data.redis.util.ByteUtils;
+import org.springframework.security.core.context.SecurityContext;
+import org.springframework.security.core.context.SecurityContextImpl;
import org.springframework.session.data.redis.config.annotation.web.server.EnableRedisWebSession;
+import java.util.Arrays;
+
@Configuration
@Slf4j
// Setting the maxInactiveInterval to 30 days
@@ -32,6 +40,11 @@ ChannelTopic topic() {
return new ChannelTopic("appsmith:queue");
}
+ @Bean
+ public RedisSerializer<Object> springSessionDefaultRedisSerializer() {
+ return new JSONSessionRedisSerializer();
+ }
+
@Primary
@Bean
ReactiveRedisOperations<String, String> reactiveRedisOperations(ReactiveRedisConnectionFactory factory) {
@@ -47,6 +60,7 @@ ReactiveRedisOperations<String, String> reactiveRedisOperations(ReactiveRedisCon
// Lifted from below and turned it into a bean. Wish Spring provided it as a bean.
// RedisWebSessionConfiguration.createReactiveRedisTemplate
+
@Bean
ReactiveRedisTemplate<String, Object> reactiveRedisTemplate(ReactiveRedisConnectionFactory factory) {
RedisSerializer<String> keySerializer = new StringRedisSerializer();
@@ -57,4 +71,40 @@ ReactiveRedisTemplate<String, Object> reactiveRedisTemplate(ReactiveRedisConnect
return new ReactiveRedisTemplate<>(factory, serializationContext);
}
+ private static class JSONSessionRedisSerializer implements RedisSerializer<Object> {
+
+ private final JdkSerializationRedisSerializer fallback = new JdkSerializationRedisSerializer();
+
+ private final GenericJackson2JsonRedisSerializer jsonSerializer = new GenericJackson2JsonRedisSerializer(new JsonMapper());
+
+ private static final byte[] SESSION_DATA_PREFIX = "appsmith-session:".getBytes();
+
+ @Override
+ public byte[] serialize(Object t) {
+ if (t instanceof SecurityContext) {
+ final UserSession session = UserSession.fromToken(((SecurityContext) t).getAuthentication());
+ final byte[] bytes = jsonSerializer.serialize(session);
+ return bytes == null ? null : ByteUtils.concat(SESSION_DATA_PREFIX, bytes);
+ }
+
+ return fallback.serialize(t);
+ }
+
+ @Override
+ public Object deserialize(byte[] bytes) {
+ if (ByteUtils.startsWith(bytes, SESSION_DATA_PREFIX)) {
+ final byte[] data = Arrays.copyOfRange(bytes, SESSION_DATA_PREFIX.length, bytes.length);
+ final UserSession session = jsonSerializer.deserialize(data, UserSession.class);
+
+ if (session == null) {
+ throw new IllegalArgumentException("Could not deserialize user session, got null");
+ }
+
+ return new SecurityContextImpl(session.makeToken());
+ }
+
+ return fallback.deserialize(bytes);
+ }
+ }
+
}
diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/domains/UserSession.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/domains/UserSession.java
new file mode 100644
index 000000000000..05d8cdd23613
--- /dev/null
+++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/domains/UserSession.java
@@ -0,0 +1,112 @@
+package com.appsmith.server.domains;
+
+import lombok.Data;
+import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
+import org.springframework.security.core.Authentication;
+import org.springframework.security.core.GrantedAuthority;
+import org.springframework.security.oauth2.client.authentication.OAuth2AuthenticationToken;
+
+import java.util.Collection;
+import java.util.Set;
+
+/**
+ * UserSession is a POJO class that represents a user's session. It is serialized to JSON and stored in Redis. That
+ * means that this class doesn't have to be serializable, and the serialVersionUID is not required. This class can
+ * change/evolve in the future, as long as pre-existing JSON session data can be safely deserialized.
+ */
+@Data
+public class UserSession {
+
+ private String userId;
+
+ private String email;
+
+ private LoginSource source;
+
+ private UserState state;
+
+ private Boolean isEnabled;
+
+ private String currentWorkspaceId;
+
+ private Set<String> workspaceIds;
+
+ private String tenantId;
+
+ private Object credentials;
+
+ private Collection<? extends GrantedAuthority> authorities;
+
+ private String authorizedClientRegistrationId;
+
+ private static final String PASSWORD_PROVIDER = "password";
+
+ private static final Set<String> ALLOWED_OAUTH_PROVIDERS = Set.of("google", "github");
+
+ /**
+ * We don't expect this class to be instantiated outside this class. Remove this constructor when needed.
+ */
+ private UserSession() {}
+
+ /**
+ * Given an authentication token, typically from a Spring Security context, create a UserSession object. This
+ * UserSession object can then be serialized to JSON and stored in Redis.
+ * @param authentication The token to create the UserSession from. Usually an instance of UsernamePasswordAuthenticationToken or Oauth2AuthenticationToken.
+ * @return A UserSession object representing the user's session, with details from the given token.
+ */
+ public static UserSession fromToken(Authentication authentication) {
+ final UserSession session = new UserSession();
+ final User user = (User) authentication.getPrincipal();
+
+ session.userId = user.getId();
+ session.email = user.getEmail();
+ session.source = user.getSource();
+ session.state = user.getState();
+ session.isEnabled = user.isEnabled();
+ session.currentWorkspaceId = user.getCurrentWorkspaceId();
+ session.workspaceIds = user.getWorkspaceIds();
+ session.tenantId = user.getTenantId();
+
+ session.credentials = authentication.getCredentials();
+ session.authorities = authentication.getAuthorities();
+
+ if (authentication instanceof OAuth2AuthenticationToken) {
+ session.authorizedClientRegistrationId = ((OAuth2AuthenticationToken) authentication).getAuthorizedClientRegistrationId();
+ } else if (authentication instanceof UsernamePasswordAuthenticationToken) {
+ session.authorizedClientRegistrationId = PASSWORD_PROVIDER;
+ } else {
+ throw new IllegalArgumentException("Unsupported authentication type: " + authentication.getClass().getName());
+ }
+
+ return session;
+ }
+
+ /**
+ * Performs the reverse of fromToken method. Given a UserSession object, create a Spring Security authentication
+ * token. This authentication token can then be wrapped in a SecurityContext and used as the user's session.
+ * @return A Spring Security authentication token representing the user's session. Usually an instance of UsernamePasswordAuthenticationToken or Oauth2AuthenticationToken.
+ */
+ public Authentication makeToken() {
+ final User user = new User();
+
+ user.setId(userId);
+ user.setEmail(email);
+ user.setSource(source);
+ user.setState(state);
+ user.setIsEnabled(isEnabled);
+ user.setCurrentWorkspaceId(currentWorkspaceId);
+ user.setWorkspaceIds(workspaceIds);
+ user.setTenantId(tenantId);
+
+ if (PASSWORD_PROVIDER.equals(authorizedClientRegistrationId)) {
+ return new UsernamePasswordAuthenticationToken(user, credentials, authorities);
+
+ } else if (ALLOWED_OAUTH_PROVIDERS.contains(authorizedClientRegistrationId)) {
+ return new OAuth2AuthenticationToken(user, authorities, authorizedClientRegistrationId);
+
+ }
+
+ throw new IllegalArgumentException("Invalid registration ID " + authorizedClientRegistrationId);
+ }
+
+}
|
04ac78ba1513277c61067b4a79057de7a74bf514
|
2022-04-20 19:26:01
|
Tolulope Adetula
|
fix: Primary column control visibility icon out of sync
| false
|
Primary column control visibility icon out of sync
|
fix
|
diff --git a/app/client/src/components/ads/DraggableListCard.tsx b/app/client/src/components/ads/DraggableListCard.tsx
index 0645c8c95d8a..01fc9fe4dab9 100644
--- a/app/client/src/components/ads/DraggableListCard.tsx
+++ b/app/client/src/components/ads/DraggableListCard.tsx
@@ -61,6 +61,10 @@ export function DraggableListCard(props: RenderComponentProps) {
const ref = useRef<HTMLInputElement | null>(null);
const debouncedUpdate = _.debounce(updateOption, 1000);
+ useEffect(() => {
+ setVisibility(item.isVisible);
+ }, [item.isVisible]);
+
useEffect(() => {
if (!isEditing && item && item.label) setValue(item.label);
}, [item?.label, isEditing]);
|
5995e4292a3d8d3533c4d79a9cb1f82b06d20da6
|
2024-09-27 19:48:05
|
Ankita Kinger
|
chore: Handling the updation of action name in the plugin action toolbar (#36560)
| false
|
Handling the updation of action name in the plugin action toolbar (#36560)
|
chore
|
diff --git a/app/client/src/PluginActionEditor/components/PluginActionNameEditor.tsx b/app/client/src/PluginActionEditor/components/PluginActionNameEditor.tsx
new file mode 100644
index 000000000000..a51d6006dec0
--- /dev/null
+++ b/app/client/src/PluginActionEditor/components/PluginActionNameEditor.tsx
@@ -0,0 +1,81 @@
+import React from "react";
+import { useSelector } from "react-redux";
+import ActionNameEditor from "components/editorComponents/ActionNameEditor";
+import { usePluginActionContext } from "PluginActionEditor/PluginActionContext";
+import { useFeatureFlag } from "utils/hooks/useFeatureFlag";
+import { getHasManageActionPermission } from "ee/utils/BusinessFeatures/permissionPageHelpers";
+import { FEATURE_FLAG } from "ee/entities/FeatureFlag";
+import { PluginType } from "entities/Action";
+import type { ReduxAction } from "ee/constants/ReduxActionConstants";
+import styled from "styled-components";
+import { getSavingStatusForActionName } from "selectors/actionSelectors";
+import { getAssetUrl } from "ee/utils/airgapHelpers";
+import { ActionUrlIcon } from "pages/Editor/Explorer/ExplorerIcons";
+
+export interface SaveActionNameParams {
+ id: string;
+ name: string;
+}
+
+export interface PluginActionNameEditorProps {
+ saveActionName: (
+ params: SaveActionNameParams,
+ ) => ReduxAction<SaveActionNameParams>;
+}
+
+const ActionNameEditorWrapper = styled.div`
+ & .ads-v2-box {
+ gap: var(--ads-v2-spaces-2);
+ }
+
+ && .t--action-name-edit-field {
+ font-size: 12px;
+
+ .bp3-editable-text-content {
+ height: unset !important;
+ line-height: unset !important;
+ }
+ }
+
+ & .t--plugin-icon-box {
+ height: 12px;
+ width: 12px;
+
+ img {
+ width: 12px;
+ height: auto;
+ }
+ }
+`;
+
+const PluginActionNameEditor = (props: PluginActionNameEditorProps) => {
+ const { action, plugin } = usePluginActionContext();
+
+ const isFeatureEnabled = useFeatureFlag(FEATURE_FLAG.license_gac_enabled);
+ const isChangePermitted = getHasManageActionPermission(
+ isFeatureEnabled,
+ action?.userPermissions,
+ );
+
+ const saveStatus = useSelector((state) =>
+ getSavingStatusForActionName(state, action?.id || ""),
+ );
+
+ const iconUrl = getAssetUrl(plugin?.iconLocation) || "";
+ const icon = ActionUrlIcon(iconUrl);
+
+ return (
+ <ActionNameEditorWrapper>
+ <ActionNameEditor
+ actionConfig={action}
+ disabled={!isChangePermitted}
+ enableFontStyling={plugin?.type === PluginType.API}
+ icon={icon}
+ saveActionName={props.saveActionName}
+ saveStatus={saveStatus}
+ />
+ </ActionNameEditorWrapper>
+ );
+};
+
+export default PluginActionNameEditor;
diff --git a/app/client/src/PluginActionEditor/index.ts b/app/client/src/PluginActionEditor/index.ts
index 20265c8bc5a9..e8083e1b0f06 100644
--- a/app/client/src/PluginActionEditor/index.ts
+++ b/app/client/src/PluginActionEditor/index.ts
@@ -6,3 +6,8 @@ export {
export { default as PluginActionToolbar } from "./components/PluginActionToolbar";
export { default as PluginActionForm } from "./components/PluginActionForm";
export { default as PluginActionResponse } from "./components/PluginActionResponse";
+export type {
+ SaveActionNameParams,
+ PluginActionNameEditorProps,
+} from "./components/PluginActionNameEditor";
+export { default as PluginActionNameEditor } from "./components/PluginActionNameEditor";
diff --git a/app/client/src/components/editorComponents/ActionNameEditor.tsx b/app/client/src/components/editorComponents/ActionNameEditor.tsx
index 8467855f479f..1d9bf01aa7cb 100644
--- a/app/client/src/components/editorComponents/ActionNameEditor.tsx
+++ b/app/client/src/components/editorComponents/ActionNameEditor.tsx
@@ -1,19 +1,13 @@
import React, { memo } from "react";
-import { useSelector } from "react-redux";
-import { useParams } from "react-router-dom";
import EditableText, {
EditInteractionKind,
} from "components/editorComponents/EditableText";
import { removeSpecialChars } from "utils/helpers";
-import type { AppState } from "ee/reducers";
-import { saveActionName } from "actions/pluginActionActions";
import { Flex } from "@appsmith/ads";
-import { getActionByBaseId, getPlugin } from "ee/selectors/entitiesSelector";
import NameEditorComponent, {
IconBox,
- IconWrapper,
NameWrapper,
} from "components/utils/NameEditorComponent";
import {
@@ -21,14 +15,13 @@ import {
ACTION_NAME_PLACEHOLDER,
createMessage,
} from "ee/constants/messages";
-import { getAssetUrl } from "ee/utils/airgapHelpers";
-import { getSavingStatusForActionName } from "selectors/actionSelectors";
import type { ReduxAction } from "ee/constants/ReduxActionConstants";
+import type { SaveActionNameParams } from "PluginActionEditor";
+import { useFeatureFlag } from "utils/hooks/useFeatureFlag";
+import { FEATURE_FLAG } from "ee/entities/FeatureFlag";
+import type { Action } from "entities/Action";
+import type { ModuleInstance } from "ee/constants/ModuleInstanceConstants";
-interface SaveActionNameParams {
- id: string;
- name: string;
-}
interface ActionNameEditorProps {
/*
This prop checks if page is API Pane or Query Pane or Curl Pane
@@ -38,38 +31,34 @@ interface ActionNameEditorProps {
*/
enableFontStyling?: boolean;
disabled?: boolean;
- saveActionName?: (
+ saveActionName: (
params: SaveActionNameParams,
) => ReduxAction<SaveActionNameParams>;
+ actionConfig?: Action | ModuleInstance;
+ icon?: JSX.Element;
+ saveStatus: { isSaving: boolean; error: boolean };
}
function ActionNameEditor(props: ActionNameEditorProps) {
- const params = useParams<{ baseApiId?: string; baseQueryId?: string }>();
-
- const currentActionConfig = useSelector((state: AppState) =>
- getActionByBaseId(state, params.baseApiId || params.baseQueryId || ""),
- );
-
- const currentPlugin = useSelector((state: AppState) =>
- getPlugin(state, currentActionConfig?.pluginId || ""),
- );
+ const {
+ actionConfig,
+ disabled = false,
+ enableFontStyling = false,
+ icon = "",
+ saveActionName,
+ saveStatus,
+ } = props;
- const saveStatus = useSelector((state) =>
- getSavingStatusForActionName(state, currentActionConfig?.id || ""),
+ const isActionRedesignEnabled = useFeatureFlag(
+ FEATURE_FLAG.release_actions_redesign_enabled,
);
return (
<NameEditorComponent
- /**
- * This component is used by module editor in EE which uses a different
- * action to save the name of an action. The current callers of this component
- * pass the existing saveAction action but as fallback the saveActionName is used here
- * as a guard.
- */
- dispatchAction={props.saveActionName || saveActionName}
- id={currentActionConfig?.id}
+ id={actionConfig?.id}
idUndefinedErrorMessage={ACTION_ID_NOT_FOUND_IN_URL}
- name={currentActionConfig?.name}
+ name={actionConfig?.name}
+ onSaveName={saveActionName}
saveStatus={saveStatus}
>
{({
@@ -85,28 +74,22 @@ function ActionNameEditor(props: ActionNameEditorProps) {
isNew: boolean;
saveStatus: { isSaving: boolean; error: boolean };
}) => (
- <NameWrapper enableFontStyling={props.enableFontStyling}>
+ <NameWrapper enableFontStyling={enableFontStyling}>
<Flex
alignItems="center"
gap="spaces-3"
overflow="hidden"
width="100%"
>
- {currentPlugin && (
- <IconBox>
- <IconWrapper
- alt={currentPlugin.name}
- src={getAssetUrl(currentPlugin?.iconLocation)}
- />
- </IconBox>
- )}
+ {icon && <IconBox className="t--plugin-icon-box">{icon}</IconBox>}
<EditableText
className="t--action-name-edit-field"
- defaultValue={currentActionConfig ? currentActionConfig.name : ""}
- disabled={props.disabled}
+ defaultValue={actionConfig ? actionConfig.name : ""}
+ disabled={disabled}
editInteractionKind={EditInteractionKind.SINGLE}
errorTooltipClass="t--action-name-edit-error"
forceDefault={forceUpdate}
+ iconSize={isActionRedesignEnabled ? "sm" : "md"}
isEditingDefault={isNew}
isInvalid={isInvalidNameForEntity}
onTextChanged={handleNameChange}
diff --git a/app/client/src/components/editorComponents/EditableText.tsx b/app/client/src/components/editorComponents/EditableText.tsx
index 8fc753750071..29b4439871af 100644
--- a/app/client/src/components/editorComponents/EditableText.tsx
+++ b/app/client/src/components/editorComponents/EditableText.tsx
@@ -6,7 +6,13 @@ import {
} from "@blueprintjs/core";
import styled from "styled-components";
import _ from "lodash";
-import { Button, Spinner, toast, Tooltip } from "@appsmith/ads";
+import {
+ Button,
+ Spinner,
+ toast,
+ Tooltip,
+ type ButtonSizes,
+} from "@appsmith/ads";
import { INVALID_NAME_ERROR, createMessage } from "ee/constants/messages";
export enum EditInteractionKind {
@@ -39,6 +45,7 @@ interface EditableTextProps {
minLines?: number;
customErrorTooltip?: string;
useFullWidth?: boolean;
+ iconSize?: ButtonSizes;
}
// using the !important keyword here is mandatory because a style is being applied to that element using the style attribute
@@ -129,6 +136,7 @@ export function EditableText(props: EditableTextProps) {
errorTooltipClass,
forceDefault,
hideEditIcon,
+ iconSize = "md",
isEditingDefault,
isInvalid,
maxLength,
@@ -275,7 +283,7 @@ export function EditableText(props: EditableTextProps) {
className="t--action-name-edit-icon"
isIconButton
kind="tertiary"
- size="md"
+ size={iconSize}
startIcon="pencil-line"
/>
))}
diff --git a/app/client/src/components/utils/NameEditorComponent.tsx b/app/client/src/components/utils/NameEditorComponent.tsx
index b7aa2e03ce4e..876a9c9d1fdf 100644
--- a/app/client/src/components/utils/NameEditorComponent.tsx
+++ b/app/client/src/components/utils/NameEditorComponent.tsx
@@ -11,6 +11,8 @@ import {
} from "ee/constants/messages";
import styled from "styled-components";
import { Classes } from "@blueprintjs/core";
+import type { SaveActionNameParams } from "PluginActionEditor";
+import type { ReduxAction } from "ee/constants/ReduxActionConstants";
export const NameWrapper = styled.div<{ enableFontStyling?: boolean }>`
min-width: 50%;
@@ -71,9 +73,9 @@ interface NameEditorProps {
children: (params: any) => JSX.Element;
id?: string;
name?: string;
- // TODO: Fix this the next time the file is edited
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
- dispatchAction: (a: any) => any;
+ onSaveName: (
+ params: SaveActionNameParams,
+ ) => ReduxAction<SaveActionNameParams>;
// TODO: Fix this the next time the file is edited
// eslint-disable-next-line @typescript-eslint/no-explicit-any
suffixErrorMessage?: (params?: any) => string;
@@ -90,10 +92,10 @@ interface NameEditorProps {
function NameEditor(props: NameEditorProps) {
const {
- dispatchAction,
id: entityId,
idUndefinedErrorMessage,
name: entityName,
+ onSaveName,
saveStatus,
suffixErrorMessage = ACTION_NAME_CONFLICT_ERROR,
} = props;
@@ -131,8 +133,8 @@ function NameEditor(props: NameEditorProps) {
const handleNameChange = useCallback(
(name: string) => {
- if (name !== entityName && !isInvalidNameForEntity(name)) {
- dispatch(dispatchAction({ id: entityId, name }));
+ if (name !== entityName && !isInvalidNameForEntity(name) && entityId) {
+ dispatch(onSaveName({ id: entityId, name }));
}
},
[dispatch, isInvalidNameForEntity, entityId, entityName],
diff --git a/app/client/src/pages/Editor/APIEditor/ApiEditorContext.tsx b/app/client/src/pages/Editor/APIEditor/ApiEditorContext.tsx
index a5d3aa5e235f..1a2d9d517898 100644
--- a/app/client/src/pages/Editor/APIEditor/ApiEditorContext.tsx
+++ b/app/client/src/pages/Editor/APIEditor/ApiEditorContext.tsx
@@ -1,11 +1,7 @@
import type { ReduxAction } from "ee/constants/ReduxActionConstants";
import type { PaginationField } from "api/ActionAPI";
import React, { createContext, useMemo } from "react";
-
-interface SaveActionNameParams {
- id: string;
- name: string;
-}
+import type { SaveActionNameParams } from "PluginActionEditor";
interface ApiEditorContextContextProps {
moreActionsMenu?: React.ReactNode;
@@ -15,7 +11,7 @@ interface ApiEditorContextContextProps {
// TODO: Fix this the next time the file is edited
// eslint-disable-next-line @typescript-eslint/no-explicit-any
settingsConfig: any;
- saveActionName?: (
+ saveActionName: (
params: SaveActionNameParams,
) => ReduxAction<SaveActionNameParams>;
closeEditorLink?: React.ReactNode;
diff --git a/app/client/src/pages/Editor/APIEditor/CommonEditorForm.tsx b/app/client/src/pages/Editor/APIEditor/CommonEditorForm.tsx
index b542cdfbd040..979c4edf1cb1 100644
--- a/app/client/src/pages/Editor/APIEditor/CommonEditorForm.tsx
+++ b/app/client/src/pages/Editor/APIEditor/CommonEditorForm.tsx
@@ -35,6 +35,9 @@ import {
InfoFields,
RequestTabs,
} from "PluginActionEditor/components/PluginActionForm/components/CommonEditorForm";
+import { getSavingStatusForActionName } from "selectors/actionSelectors";
+import { getAssetUrl } from "ee/utils/airgapHelpers";
+import { ActionUrlIcon } from "../Explorer/ExplorerIcons";
const Form = styled.form`
position: relative;
@@ -245,6 +248,18 @@ function CommonEditorForm(props: CommonFormPropsWithExtraParams) {
currentActionConfig?.userPermissions,
);
+ const currentPlugin = useSelector((state: AppState) =>
+ getPlugin(state, currentActionConfig?.pluginId || ""),
+ );
+
+ const saveStatus = useSelector((state) =>
+ getSavingStatusForActionName(state, currentActionConfig?.id || ""),
+ );
+
+ const iconUrl = getAssetUrl(currentPlugin?.iconLocation) || "";
+
+ const icon = ActionUrlIcon(iconUrl);
+
const plugin = useSelector((state: AppState) =>
getPlugin(state, pluginId ?? ""),
);
@@ -281,9 +296,12 @@ function CommonEditorForm(props: CommonFormPropsWithExtraParams) {
<FormRow className="form-row-header">
<NameWrapper className="t--nameOfApi">
<ActionNameEditor
+ actionConfig={currentActionConfig}
disabled={!isChangePermitted}
enableFontStyling
+ icon={icon}
saveActionName={saveActionName}
+ saveStatus={saveStatus}
/>
</NameWrapper>
<ActionButtons className="t--formActionButtons">
diff --git a/app/client/src/pages/Editor/APIEditor/index.tsx b/app/client/src/pages/Editor/APIEditor/index.tsx
index 247c2cfd408d..31328d250556 100644
--- a/app/client/src/pages/Editor/APIEditor/index.tsx
+++ b/app/client/src/pages/Editor/APIEditor/index.tsx
@@ -8,7 +8,11 @@ import {
getPluginSettingConfigs,
getPlugins,
} from "ee/selectors/entitiesSelector";
-import { deleteAction, runAction } from "actions/pluginActionActions";
+import {
+ deleteAction,
+ runAction,
+ saveActionName,
+} from "actions/pluginActionActions";
import AnalyticsUtil from "ee/utils/AnalyticsUtil";
import Editor from "./Editor";
import BackToCanvas from "components/common/BackToCanvas";
@@ -151,15 +155,7 @@ function ApiEditorWrapper(props: ApiEditorWrapperProps) {
});
dispatch(runAction(action?.id ?? "", paginationField));
},
- [
- action?.id,
- apiName,
- pageName,
- getPageName,
- plugins,
- pluginId,
- datasourceId,
- ],
+ [action?.id, apiName, pageName, plugins, pluginId, datasourceId, dispatch],
);
const actionRightPaneBackLink = useMemo(() => {
@@ -173,13 +169,13 @@ function ApiEditorWrapper(props: ApiEditorWrapperProps) {
pageName,
});
dispatch(deleteAction({ id: action?.id ?? "", name: apiName }));
- }, [getPageName, pages, basePageId, apiName]);
+ }, [pages, basePageId, apiName, action?.id, dispatch, pageName]);
const notification = useMemo(() => {
if (!isConverting) return null;
return <ConvertEntityNotification icon={icon} name={action?.name || ""} />;
- }, [action?.name, isConverting]);
+ }, [action?.name, isConverting, icon]);
const isActionRedesignEnabled = useFeatureFlag(
FEATURE_FLAG.release_actions_redesign_enabled,
@@ -196,6 +192,7 @@ function ApiEditorWrapper(props: ApiEditorWrapperProps) {
handleRunClick={handleRunClick}
moreActionsMenu={moreActionsMenu}
notification={notification}
+ saveActionName={saveActionName}
settingsConfig={settingsConfig}
>
<Disabler isDisabled={isConverting}>
diff --git a/app/client/src/pages/Editor/Explorer/Entity/Name.tsx b/app/client/src/pages/Editor/Explorer/Entity/Name.tsx
index de937dd86a11..e0fb005bc005 100644
--- a/app/client/src/pages/Editor/Explorer/Entity/Name.tsx
+++ b/app/client/src/pages/Editor/Explorer/Entity/Name.tsx
@@ -16,6 +16,8 @@ import {
import { Tooltip } from "@appsmith/ads";
import { useSelector } from "react-redux";
import { getSavingStatusForActionName } from "selectors/actionSelectors";
+import type { ReduxAction } from "ee/constants/ReduxActionConstants";
+import type { SaveActionNameParams } from "PluginActionEditor";
export const searchHighlightSpanClassName = "token";
export const searchTokenizationDelimiter = "!!";
@@ -84,7 +86,7 @@ export interface EntityNameProps {
name: string;
isEditing?: boolean;
onChange?: (name: string) => void;
- updateEntityName: (name: string) => void;
+ updateEntityName: (name: string) => ReduxAction<SaveActionNameParams>;
entityId: string;
searchKeyword?: string;
className?: string;
@@ -164,10 +166,10 @@ export const EntityName = React.memo(
return (
<NameEditorComponent
- dispatchAction={handleUpdateName}
id={props.entityId}
idUndefinedErrorMessage={ACTION_ID_NOT_FOUND_IN_URL}
name={updatedName}
+ onSaveName={handleUpdateName}
saveStatus={saveStatus}
suffixErrorMessage={ENTITY_EXPLORER_ACTION_NAME_CONFLICT_ERROR}
>
diff --git a/app/client/src/pages/Editor/JSEditor/JSObjectNameEditor.tsx b/app/client/src/pages/Editor/JSEditor/JSObjectNameEditor.tsx
index f82860f134b1..ff1a598bc1ba 100644
--- a/app/client/src/pages/Editor/JSEditor/JSObjectNameEditor.tsx
+++ b/app/client/src/pages/Editor/JSEditor/JSObjectNameEditor.tsx
@@ -25,11 +25,8 @@ import NameEditorComponent, {
} from "components/utils/NameEditorComponent";
import { getSavingStatusForJSObjectName } from "selectors/actionSelectors";
import type { ReduxAction } from "ee/constants/ReduxActionConstants";
+import type { SaveActionNameParams } from "PluginActionEditor";
-export interface SaveActionNameParams {
- id: string;
- name: string;
-}
export interface JSObjectNameEditorProps {
/*
This prop checks if page is API Pane or Query Pane or Curl Pane
@@ -64,10 +61,10 @@ export function JSObjectNameEditor(props: JSObjectNameEditorProps) {
return (
<NameEditorComponent
- dispatchAction={props.saveJSObjectName}
id={currentJSObjectConfig?.id}
idUndefinedErrorMessage={JSOBJECT_ID_NOT_FOUND_IN_URL}
name={currentJSObjectConfig?.name}
+ onSaveName={props.saveJSObjectName}
saveStatus={saveStatus}
>
{({
diff --git a/app/client/src/pages/Editor/QueryEditor/QueryEditorContext.tsx b/app/client/src/pages/Editor/QueryEditor/QueryEditorContext.tsx
index 03c46a99d0db..c5089fc6bdfc 100644
--- a/app/client/src/pages/Editor/QueryEditor/QueryEditorContext.tsx
+++ b/app/client/src/pages/Editor/QueryEditor/QueryEditorContext.tsx
@@ -1,18 +1,14 @@
import type { ReduxAction } from "ee/constants/ReduxActionConstants";
+import type { SaveActionNameParams } from "PluginActionEditor";
import React, { createContext, useMemo } from "react";
-interface SaveActionNameParams {
- id: string;
- name: string;
-}
-
interface QueryEditorContextContextProps {
moreActionsMenu?: React.ReactNode;
onCreateDatasourceClick?: () => void;
onEntityNotFoundBackClick?: () => void;
changeQueryPage?: (baseQueryId: string) => void;
actionRightPaneBackLink?: React.ReactNode;
- saveActionName?: (
+ saveActionName: (
params: SaveActionNameParams,
) => ReduxAction<SaveActionNameParams>;
closeEditorLink?: React.ReactNode;
diff --git a/app/client/src/pages/Editor/QueryEditor/QueryEditorHeader.tsx b/app/client/src/pages/Editor/QueryEditor/QueryEditorHeader.tsx
index af1d28c83a99..38f9a9b3d72e 100644
--- a/app/client/src/pages/Editor/QueryEditor/QueryEditorHeader.tsx
+++ b/app/client/src/pages/Editor/QueryEditor/QueryEditorHeader.tsx
@@ -13,6 +13,7 @@ import { useActiveActionBaseId } from "ee/pages/Editor/Explorer/hooks";
import { useSelector } from "react-redux";
import {
getActionByBaseId,
+ getPlugin,
getPluginNameFromId,
} from "ee/selectors/entitiesSelector";
import { QueryEditorContext } from "./QueryEditorContext";
@@ -21,6 +22,9 @@ import type { Datasource } from "entities/Datasource";
import type { AppState } from "ee/reducers";
import { SQL_DATASOURCES } from "constants/QueryEditorConstants";
import DatasourceSelector from "./DatasourceSelector";
+import { getSavingStatusForActionName } from "selectors/actionSelectors";
+import { getAssetUrl } from "ee/utils/airgapHelpers";
+import { ActionUrlIcon } from "../Explorer/ExplorerIcons";
const NameWrapper = styled.div`
display: flex;
@@ -79,6 +83,18 @@ const QueryEditorHeader = (props: Props) => {
currentActionConfig?.userPermissions,
);
+ const currentPlugin = useSelector((state: AppState) =>
+ getPlugin(state, currentActionConfig?.pluginId || ""),
+ );
+
+ const saveStatus = useSelector((state) =>
+ getSavingStatusForActionName(state, currentActionConfig?.id || ""),
+ );
+
+ const iconUrl = getAssetUrl(currentPlugin?.iconLocation) || "";
+
+ const icon = ActionUrlIcon(iconUrl);
+
// get the current action's plugin name
const currentActionPluginName = useSelector((state: AppState) =>
getPluginNameFromId(state, currentActionConfig?.pluginId || ""),
@@ -106,8 +122,11 @@ const QueryEditorHeader = (props: Props) => {
<StyledFormRow>
<NameWrapper>
<ActionNameEditor
+ actionConfig={currentActionConfig}
disabled={!isChangePermitted}
+ icon={icon}
saveActionName={saveActionName}
+ saveStatus={saveStatus}
/>
</NameWrapper>
<ActionsWrapper>
diff --git a/app/client/src/pages/Editor/QueryEditor/index.tsx b/app/client/src/pages/Editor/QueryEditor/index.tsx
index f76cbffe1b5f..03457a6228ea 100644
--- a/app/client/src/pages/Editor/QueryEditor/index.tsx
+++ b/app/client/src/pages/Editor/QueryEditor/index.tsx
@@ -42,6 +42,7 @@ import { ENTITY_ICON_SIZE, EntityIcon } from "../Explorer/ExplorerIcons";
import { getIDEViewMode } from "selectors/ideSelectors";
import { EditorViewMode } from "ee/entities/IDE/constants";
import { AppPluginActionEditor } from "../AppPluginActionEditor";
+import { saveActionName } from "actions/pluginActionActions";
type QueryEditorProps = RouteComponentProps<QueryEditorRouteParams>;
@@ -126,6 +127,7 @@ function QueryEditor(props: QueryEditorProps) {
}, [
action?.id,
action?.name,
+ action?.pluginType,
isChangePermitted,
isDeletePermitted,
basePageId,
@@ -143,7 +145,7 @@ function QueryEditor(props: QueryEditorProps) {
changeQuery({ baseQueryId: baseQueryId, basePageId, applicationId }),
);
},
- [basePageId, applicationId],
+ [basePageId, applicationId, dispatch],
);
const onCreateDatasourceClick = useCallback(() => {
@@ -159,13 +161,7 @@ function QueryEditor(props: QueryEditorProps) {
AnalyticsUtil.logEvent("NAVIGATE_TO_CREATE_NEW_DATASOURCE_PAGE", {
entryPoint,
});
- }, [
- basePageId,
- history,
- integrationEditorURL,
- DatasourceCreateEntryPoints,
- AnalyticsUtil,
- ]);
+ }, [basePageId]);
// custom function to return user to integrations page if action is not found
const onEntityNotFoundBackClick = useCallback(
@@ -176,7 +172,7 @@ function QueryEditor(props: QueryEditorProps) {
selectedTab: INTEGRATION_TABS.ACTIVE,
}),
),
- [basePageId, history, integrationEditorURL],
+ [basePageId],
);
const notification = useMemo(() => {
@@ -189,7 +185,7 @@ function QueryEditor(props: QueryEditorProps) {
withPadding
/>
);
- }, [action?.name, isConverting]);
+ }, [action?.name, isConverting, icon]);
const isActionRedesignEnabled = useFeatureFlag(
FEATURE_FLAG.release_actions_redesign_enabled,
@@ -207,6 +203,7 @@ function QueryEditor(props: QueryEditorProps) {
notification={notification}
onCreateDatasourceClick={onCreateDatasourceClick}
onEntityNotFoundBackClick={onEntityNotFoundBackClick}
+ saveActionName={saveActionName}
>
<Disabler isDisabled={isConverting}>
<Editor
|
0767a37a3a0913dd4bb0061a491bac251985b6c6
|
2024-05-21 15:39:09
|
Ashok Kumar M
|
feat: use zone elevatedBackground evaluated values and upgrade space distribution ux of borderless zones. (#33527)
| false
|
use zone elevatedBackground evaluated values and upgrade space distribution ux of borderless zones. (#33527)
|
feat
|
diff --git a/app/client/src/layoutSystems/anvil/common/hooks/useWidgetBorderStyles.ts b/app/client/src/layoutSystems/anvil/common/hooks/useWidgetBorderStyles.ts
index 958153468b5f..bc771ffd677b 100644
--- a/app/client/src/layoutSystems/anvil/common/hooks/useWidgetBorderStyles.ts
+++ b/app/client/src/layoutSystems/anvil/common/hooks/useWidgetBorderStyles.ts
@@ -4,12 +4,17 @@ import { getWidgetErrorCount } from "layoutSystems/anvil/editor/AnvilWidgetName/
import {
getAnvilHighlightShown,
getAnvilSpaceDistributionStatus,
+ getWidgetsDistributingSpace,
} from "layoutSystems/anvil/integrations/selectors";
import { useSelector } from "react-redux";
import { combinedPreviewModeSelector } from "selectors/editorSelectors";
import { isWidgetFocused, isWidgetSelected } from "selectors/widgetSelectors";
-export function useWidgetBorderStyles(widgetId: string, widgetType: string) {
+export function useWidgetBorderStyles(
+ widgetId: string,
+ widgetType: string,
+ elevatedBackground?: boolean,
+) {
/** Selectors */
const isFocused = useSelector(isWidgetFocused(widgetId));
const isSelected = useSelector(isWidgetSelected(widgetId));
@@ -28,7 +33,9 @@ export function useWidgetBorderStyles(widgetId: string, widgetType: string) {
const isDistributingSpace: boolean = useSelector(
getAnvilSpaceDistributionStatus,
);
-
+ const widgetsEffectedBySpaceDistribution = useSelector(
+ getWidgetsDistributingSpace,
+ );
const isPreviewMode = useSelector(combinedPreviewModeSelector);
/** EO selectors */
@@ -37,11 +44,14 @@ export function useWidgetBorderStyles(widgetId: string, widgetType: string) {
if (isPreviewMode) {
return {};
}
-
+ const isZoneDistributingSpace =
+ widgetsEffectedBySpaceDistribution.zones.includes(widgetId);
+ // If the widget is a zone and is distributing space and has no elevated background
+ const isZoneNotElevated = isZoneDistributingSpace && !elevatedBackground;
// Show the border if the widget has widgets being dragged or redistributed inside it
const showDraggedOnBorder =
(highlightShown && highlightShown.canvasId === widgetId) ||
- (isDistributingSpace && isSelected);
+ isZoneNotElevated;
const onCanvasUI = WidgetFactory.getConfig(widgetType)?.onCanvasUI;
diff --git a/app/client/src/layoutSystems/anvil/editor/AnvilEditorFlexComponent.tsx b/app/client/src/layoutSystems/anvil/editor/AnvilEditorFlexComponent.tsx
index 9ec2bdf280cf..a8a08e5420e6 100644
--- a/app/client/src/layoutSystems/anvil/editor/AnvilEditorFlexComponent.tsx
+++ b/app/client/src/layoutSystems/anvil/editor/AnvilEditorFlexComponent.tsx
@@ -47,6 +47,7 @@ export const AnvilEditorFlexComponent = (props: AnvilFlexComponentProps) => {
props.widgetName,
props.isVisible,
props.widgetType,
+ !!props.elevatedBackground,
ref,
);
useAnvilWidgetDrag(props.widgetId, props.widgetType, props.layoutId, ref);
diff --git a/app/client/src/layoutSystems/anvil/editor/AnvilEditorWidgetOnion.tsx b/app/client/src/layoutSystems/anvil/editor/AnvilEditorWidgetOnion.tsx
index 5075c75a88b2..415332c91533 100644
--- a/app/client/src/layoutSystems/anvil/editor/AnvilEditorWidgetOnion.tsx
+++ b/app/client/src/layoutSystems/anvil/editor/AnvilEditorWidgetOnion.tsx
@@ -37,6 +37,7 @@ export const AnvilEditorWidgetOnion = (props: BaseWidgetProps) => {
}, [isPreviewMode, props.type]);
return (
<WidgetWrapper
+ elevatedBackground={!!props.elevatedBackground}
flexGrow={props.flexGrow}
isVisible={!!props.isVisible}
layoutId={props.layoutId}
diff --git a/app/client/src/layoutSystems/anvil/editor/AnvilWidgetName/selectors.ts b/app/client/src/layoutSystems/anvil/editor/AnvilWidgetName/selectors.ts
index 8cc27e669282..84cc170b2103 100644
--- a/app/client/src/layoutSystems/anvil/editor/AnvilWidgetName/selectors.ts
+++ b/app/client/src/layoutSystems/anvil/editor/AnvilWidgetName/selectors.ts
@@ -4,7 +4,10 @@ import { EVAL_ERROR_PATH } from "utils/DynamicBindingUtils";
import get from "lodash/get";
import { createSelector } from "reselect";
import { getIsDragging } from "selectors/widgetDragSelectors";
-import { getAnvilHighlightShown } from "layoutSystems/anvil/integrations/selectors";
+import {
+ getAnvilHighlightShown,
+ getAnvilSpaceDistributionStatus,
+} from "layoutSystems/anvil/integrations/selectors";
import { isWidgetFocused, isWidgetSelected } from "selectors/widgetSelectors";
import { isEditOnlyModeSelector } from "selectors/editorSelectors";
@@ -58,14 +61,16 @@ export function shouldSelectOrFocus(widgetId: string) {
getAnvilHighlightShown,
isWidgetSelected(widgetId),
isWidgetFocused(widgetId),
+ getAnvilSpaceDistributionStatus,
(
isEditorOpen,
isDragging,
highlightShown,
isWidgetSelected,
isWidgetFocused,
+ isDistributingSpace,
) => {
- const baseCondition = isEditorOpen && !isDragging;
+ const baseCondition = isEditorOpen && !isDragging && !isDistributingSpace;
let onCanvasUIState: NameComponentStates = "none";
if (baseCondition) {
if (isWidgetSelected) onCanvasUIState = "select";
diff --git a/app/client/src/layoutSystems/anvil/editor/canvas/AnvilEditorCanvas.tsx b/app/client/src/layoutSystems/anvil/editor/canvas/AnvilEditorCanvas.tsx
index 7d5afc3dc0be..67319c5c0976 100644
--- a/app/client/src/layoutSystems/anvil/editor/canvas/AnvilEditorCanvas.tsx
+++ b/app/client/src/layoutSystems/anvil/editor/canvas/AnvilEditorCanvas.tsx
@@ -3,16 +3,14 @@ import { AnvilViewerCanvas } from "layoutSystems/anvil/viewer/canvas/AnvilViewer
import React, { useCallback, useEffect, useRef } from "react";
import { useSelectWidgetListener } from "./hooks/useSelectWidgetListener";
import { useClickToClearSelections } from "./hooks/useClickToClearSelections";
-import {
- useAnvilGlobalDnDStates,
- type AnvilGlobalDnDStates,
-} from "./hooks/useAnvilGlobalDnDStates";
+import type { AnvilGlobalDnDStates } from "./hooks/useAnvilGlobalDnDStates";
+import { useAnvilGlobalDnDStates } from "./hooks/useAnvilGlobalDnDStates";
import { AnvilDragPreview } from "../canvasArenas/AnvilDragPreview";
+import { AnvilWidgetElevationProvider } from "./providers/AnvilWidgetElevationProvider";
export const AnvilDnDStatesContext = React.createContext<
AnvilGlobalDnDStates | undefined
>(undefined);
-
/**
* Anvil Main Canvas is just a wrapper around AnvilCanvas.
* Why do we need this?
@@ -58,14 +56,16 @@ export const AnvilEditorCanvas = (props: BaseWidgetProps) => {
// using AnvilDnDStatesContext to provide the states to the child AnvilDraggingArena
const anvilGlobalDnDStates = useAnvilGlobalDnDStates();
return (
- <AnvilDnDStatesContext.Provider value={anvilGlobalDnDStates}>
- <AnvilViewerCanvas {...props} ref={canvasRef} />
- <AnvilDragPreview
- dragDetails={anvilGlobalDnDStates.dragDetails}
- draggedBlocks={anvilGlobalDnDStates.draggedBlocks}
- isDragging={anvilGlobalDnDStates.isDragging}
- isNewWidget={anvilGlobalDnDStates.isNewWidget}
- />
- </AnvilDnDStatesContext.Provider>
+ <AnvilWidgetElevationProvider>
+ <AnvilDnDStatesContext.Provider value={anvilGlobalDnDStates}>
+ <AnvilViewerCanvas {...props} ref={canvasRef} />
+ <AnvilDragPreview
+ dragDetails={anvilGlobalDnDStates.dragDetails}
+ draggedBlocks={anvilGlobalDnDStates.draggedBlocks}
+ isDragging={anvilGlobalDnDStates.isDragging}
+ isNewWidget={anvilGlobalDnDStates.isNewWidget}
+ />
+ </AnvilDnDStatesContext.Provider>
+ </AnvilWidgetElevationProvider>
);
};
diff --git a/app/client/src/layoutSystems/anvil/editor/canvas/hooks/useAnvilWidgetElevationSetter.ts b/app/client/src/layoutSystems/anvil/editor/canvas/hooks/useAnvilWidgetElevationSetter.ts
new file mode 100644
index 000000000000..1e44a37f8b1c
--- /dev/null
+++ b/app/client/src/layoutSystems/anvil/editor/canvas/hooks/useAnvilWidgetElevationSetter.ts
@@ -0,0 +1,15 @@
+import { useEffect } from "react";
+import { useAnvilWidgetElevation } from "../providers/AnvilWidgetElevationProvider";
+
+export const useAnvilWidgetElevationSetter = (
+ widgetId: string,
+ elevatedBackground: boolean,
+) => {
+ const anvilWidgetElevation = useAnvilWidgetElevation();
+ const { setWidgetElevation } = anvilWidgetElevation || {};
+ useEffect(() => {
+ if (setWidgetElevation) {
+ setWidgetElevation(widgetId, elevatedBackground);
+ }
+ }, [elevatedBackground, setWidgetElevation]);
+};
diff --git a/app/client/src/layoutSystems/anvil/editor/canvas/providers/AnvilWidgetElevationProvider.tsx b/app/client/src/layoutSystems/anvil/editor/canvas/providers/AnvilWidgetElevationProvider.tsx
new file mode 100644
index 000000000000..fc8252172153
--- /dev/null
+++ b/app/client/src/layoutSystems/anvil/editor/canvas/providers/AnvilWidgetElevationProvider.tsx
@@ -0,0 +1,66 @@
+import React, {
+ type ReactNode,
+ createContext,
+ useState,
+ useCallback,
+ useContext,
+} from "react";
+
+interface WidgetElevation {
+ [key: string]: boolean;
+}
+
+interface AnvilWidgetElevationContextType {
+ elevatedWidgets: WidgetElevation;
+ setWidgetElevation: (widgetId: string, isElevated: boolean) => void;
+}
+
+const AnvilWidgetElevationContext = createContext<
+ AnvilWidgetElevationContextType | undefined
+>(undefined);
+
+export const useAnvilWidgetElevation = () =>
+ useContext(AnvilWidgetElevationContext);
+/**
+ * AnvilWidgetElevationProvider indexes all sections and zones and records their evaluated value of elevation(Visual Separation).
+ *
+ * Why not just use the evaluated values directly?
+ * Because we need to keep track of the elevation of each widget in the editor to apply the correct elevation styles.
+ * elevation being a bindable property, we need to keep track of the evaluated value of elevation of each sections and zones in the editor.
+ *
+ * When adding compensators to the dragged widgets(useAnvilDnDCompensators), we need to know the elevation of the zone widget as well as its corresponding siblings
+ * to decide if the zone has to treated as a elevated zone or not.
+ *
+ * In-order to skip iterating the data tree every time we need to know the elevation of a widget, we are storing the elevation of each widget in this context.
+ * This way we do not have dependency on the data tree to know the elevation of a widget.
+ */
+export const AnvilWidgetElevationProvider = ({
+ children,
+}: {
+ children: ReactNode;
+}) => {
+ const [elevatedWidgets, setElevatedWidgets] = useState<WidgetElevation>({});
+
+ const setWidgetElevation = useCallback(
+ (widgetId: string, isElevated: boolean) => {
+ setElevatedWidgets((prev) => {
+ return {
+ ...prev,
+ [widgetId]: isElevated,
+ };
+ });
+ },
+ [setElevatedWidgets],
+ );
+
+ return (
+ <AnvilWidgetElevationContext.Provider
+ value={{
+ elevatedWidgets,
+ setWidgetElevation,
+ }}
+ >
+ {children}
+ </AnvilWidgetElevationContext.Provider>
+ );
+};
diff --git a/app/client/src/layoutSystems/anvil/editor/canvasArenas/AnvilModalDropArena.tsx b/app/client/src/layoutSystems/anvil/editor/canvasArenas/AnvilModalDropArena.tsx
index 62e2c1d5a216..c2f0ea988536 100644
--- a/app/client/src/layoutSystems/anvil/editor/canvasArenas/AnvilModalDropArena.tsx
+++ b/app/client/src/layoutSystems/anvil/editor/canvasArenas/AnvilModalDropArena.tsx
@@ -65,7 +65,7 @@ export const AnvilModalDropArena = ({
return (
<StyledModalEditorDropArenaWrapper
isModalEmpty={isModalEmpty}
- style={{ height: "100%" }}
+ style={{ height: isModalEmpty ? "100%" : "auto" }}
>
<StyledEmptyModalDropArena
isActive={isCurrentDraggedCanvas}
diff --git a/app/client/src/layoutSystems/anvil/editor/canvasArenas/hooks/useAnvilDnDListenerStates.ts b/app/client/src/layoutSystems/anvil/editor/canvasArenas/hooks/useAnvilDnDListenerStates.ts
index 7c11ef9d69ee..7d39902e6bf1 100644
--- a/app/client/src/layoutSystems/anvil/editor/canvasArenas/hooks/useAnvilDnDListenerStates.ts
+++ b/app/client/src/layoutSystems/anvil/editor/canvasArenas/hooks/useAnvilDnDListenerStates.ts
@@ -16,6 +16,7 @@ import type { AnvilGlobalDnDStates } from "../../canvas/hooks/useAnvilGlobalDnDS
import { getWidgets } from "sagas/selectors";
import { useMemo } from "react";
import { ZoneWidget } from "widgets/anvil/ZoneWidget";
+import { useAnvilWidgetElevation } from "../../canvas/providers/AnvilWidgetElevationProvider";
interface AnvilDnDListenerStatesProps {
anvilGlobalDragStates: AnvilGlobalDnDStates;
@@ -97,6 +98,8 @@ export const useAnvilDnDListenerStates = ({
mainCanvasLayoutId,
} = anvilGlobalDragStates;
const allWidgets = useSelector(getWidgets);
+ const anvilWidgetElevation = useAnvilWidgetElevation();
+ const elevatedWidgets = anvilWidgetElevation?.elevatedWidgets || {};
const widgetProps = allWidgets[widgetId];
const selectedWidgets = useSelector(getSelectedWidgets);
/**
@@ -134,22 +137,21 @@ export const useAnvilDnDListenerStates = ({
(each) => !allWidgets[each].detachFromLayout,
).length === 0;
- const allSiblingsWidgets = useMemo(() => {
- const allSiblings =
- (widgetProps.parentId && allWidgets[widgetProps.parentId]?.children) ||
- [];
- return allSiblings.map((each) => allWidgets[each]);
+ const allSiblingsWidgetIds = useMemo(() => {
+ return (
+ (widgetProps.parentId && allWidgets[widgetProps.parentId]?.children) || []
+ );
}, [widgetProps, allWidgets]);
const isElevatedWidget = useMemo(() => {
if (widgetProps.type === ZoneWidget.type) {
- const isAnyZoneElevated = allSiblingsWidgets.some(
- (each) => !!each.elevatedBackground,
+ const isAnyZoneElevated = allSiblingsWidgetIds.some(
+ (each) => !!elevatedWidgets[each],
);
return isAnyZoneElevated;
}
- return !!widgetProps.elevatedBackground;
- }, [widgetProps, allSiblingsWidgets]);
+ return !!elevatedWidgets[widgetId];
+ }, [widgetProps, elevatedWidgets, allSiblingsWidgetIds]);
const {
edgeCompensatorValues,
diff --git a/app/client/src/layoutSystems/anvil/editor/hooks/useAnvilWidgetStyles.ts b/app/client/src/layoutSystems/anvil/editor/hooks/useAnvilWidgetStyles.ts
index 54d3aee78dac..cc7b5204250e 100644
--- a/app/client/src/layoutSystems/anvil/editor/hooks/useAnvilWidgetStyles.ts
+++ b/app/client/src/layoutSystems/anvil/editor/hooks/useAnvilWidgetStyles.ts
@@ -10,6 +10,7 @@ export const useAnvilWidgetStyles = (
widgetName: string,
isVisible = true,
widgetType: string,
+ elevatedBackground: boolean,
ref: React.RefObject<HTMLDivElement>, // Ref object to reference the AnvilFlexComponent
) => {
// Selectors to determine whether the widget is selected or dragging
@@ -18,7 +19,11 @@ export const useAnvilWidgetStyles = (
(state: AppState) => state.ui.widgetDragResize.isDragging,
);
// Get widget border styles using useWidgetBorderStyles
- const widgetBorderStyles = useWidgetBorderStyles(widgetId, widgetType);
+ const widgetBorderStyles = useWidgetBorderStyles(
+ widgetId,
+ widgetType,
+ elevatedBackground,
+ );
// Effect hook to apply widget border styles to the widget
useEffect(() => {
diff --git a/app/client/src/layoutSystems/anvil/integrations/selectors.ts b/app/client/src/layoutSystems/anvil/integrations/selectors.ts
index 87f6249221d6..74a29723c04b 100644
--- a/app/client/src/layoutSystems/anvil/integrations/selectors.ts
+++ b/app/client/src/layoutSystems/anvil/integrations/selectors.ts
@@ -24,7 +24,11 @@ export function getDropTargetLayoutId(state: AppState, canvasId: string) {
* Returns a boolean indicating if space distribution is in progress
*/
export function getAnvilSpaceDistributionStatus(state: AppState) {
- return state.ui.widgetDragResize.anvil.isDistributingSpace;
+ return state.ui.widgetDragResize.anvil.spaceDistribution.isDistributingSpace;
+}
+
+export function getWidgetsDistributingSpace(state: AppState) {
+ return state.ui.widgetDragResize.anvil.spaceDistribution.widgetsEffected;
}
/**
diff --git a/app/client/src/layoutSystems/anvil/sectionSpaceDistributor/actions.ts b/app/client/src/layoutSystems/anvil/sectionSpaceDistributor/actions.ts
new file mode 100644
index 000000000000..3e524f77439f
--- /dev/null
+++ b/app/client/src/layoutSystems/anvil/sectionSpaceDistributor/actions.ts
@@ -0,0 +1,32 @@
+import { AnvilReduxActionTypes } from "../integrations/actions/actionTypes";
+
+export const startAnvilSpaceDistributionAction = (payload: {
+ section: string;
+ zones: string[];
+}) => {
+ return {
+ type: AnvilReduxActionTypes.ANVIL_SPACE_DISTRIBUTION_START,
+ payload,
+ };
+};
+
+export const stopAnvilSpaceDistributionAction = () => {
+ return {
+ type: AnvilReduxActionTypes.ANVIL_SPACE_DISTRIBUTION_STOP,
+ };
+};
+
+export const updateSpaceDistributionAction = (
+ sectionLayoutId: string,
+ zonesDistributed: {
+ [widgetId: string]: number;
+ },
+) => {
+ return {
+ type: AnvilReduxActionTypes.ANVIL_SPACE_DISTRIBUTION_UPDATE,
+ payload: {
+ zonesDistributed,
+ sectionLayoutId,
+ },
+ };
+};
diff --git a/app/client/src/layoutSystems/anvil/sectionSpaceDistributor/useSpaceDistributionEvents.ts b/app/client/src/layoutSystems/anvil/sectionSpaceDistributor/useSpaceDistributionEvents.ts
index 6af8e575ae9e..615ec6fd663d 100644
--- a/app/client/src/layoutSystems/anvil/sectionSpaceDistributor/useSpaceDistributionEvents.ts
+++ b/app/client/src/layoutSystems/anvil/sectionSpaceDistributor/useSpaceDistributionEvents.ts
@@ -1,7 +1,6 @@
import { getAnvilWidgetDOMId } from "layoutSystems/common/utils/LayoutElementPositionsObserver/utils";
import { useCallback, useEffect, useRef } from "react";
import { useDispatch, useSelector } from "react-redux";
-import { AnvilReduxActionTypes } from "../integrations/actions/actionTypes";
import {
getMouseSpeedTrackingCallback,
getPropertyPaneZoneId,
@@ -21,6 +20,11 @@ import {
updateWidgetCSSOnHandleMove,
updateWidgetCSSOnMinimumLimit,
} from "./utils/onMouseMoveUtils";
+import {
+ startAnvilSpaceDistributionAction,
+ stopAnvilSpaceDistributionAction,
+ updateSpaceDistributionAction,
+} from "./actions";
interface SpaceDistributionEventsProps {
ref: React.RefObject<HTMLDivElement>;
@@ -54,16 +58,19 @@ export const useSpaceDistributionEvents = ({
getMouseSpeedTrackingCallback(currentMouseSpeed);
const selectedWidgets = useSelector(getSelectedWidgets);
const { selectWidget } = useWidgetSelection();
+ const onSpaceDistributionStart = useCallback(() => {
+ dispatch(
+ startAnvilSpaceDistributionAction({
+ section: sectionWidgetId,
+ zones: zoneIds,
+ }),
+ );
+ }, [sectionWidgetId, zoneIds]);
const selectCorrespondingSectionWidget = useCallback(() => {
- if (
- !(
- selectedWidgets.includes(sectionWidgetId) ||
- zoneIds.some((each) => selectedWidgets.includes(each))
- )
- ) {
+ if (!selectedWidgets.includes(sectionWidgetId)) {
selectWidget(SelectionRequestType.One, [sectionWidgetId]);
}
- }, [sectionWidgetId, selectedWidgets, zoneIds]);
+ }, [sectionWidgetId, selectedWidgets]);
useEffect(() => {
if (ref.current) {
// Check if the ref to the DOM element exists
@@ -143,21 +150,15 @@ export const useSpaceDistributionEvents = ({
currentFlexGrow.rightZone !== currentGrowthFactor.rightZone
) {
// Dispatch action to update space distribution
- dispatch({
- type: AnvilReduxActionTypes.ANVIL_SPACE_DISTRIBUTION_UPDATE,
- payload: {
- zonesDistributed: {
- [leftZone]: currentGrowthFactor.leftZone,
- [rightZone]: currentGrowthFactor.rightZone,
- },
- sectionLayoutId,
- },
- });
+ dispatch(
+ updateSpaceDistributionAction(sectionWidgetId, {
+ [leftZone]: currentGrowthFactor.leftZone,
+ [rightZone]: currentGrowthFactor.rightZone,
+ }),
+ );
}
// Stop space distribution process
- dispatch({
- type: AnvilReduxActionTypes.ANVIL_SPACE_DISTRIBUTION_STOP,
- });
+ dispatch(stopAnvilSpaceDistributionAction());
resetCSSOnZones(spaceDistributed);
removeMouseMoveHandlers();
currentMouseSpeed.current = 0;
@@ -196,9 +197,7 @@ export const useSpaceDistributionEvents = ({
e.preventDefault();
x = e.clientX; // Store the initial mouse position
isCurrentHandleDistributingSpace.current = true; // Set distribution flag
- dispatch({
- type: AnvilReduxActionTypes.ANVIL_SPACE_DISTRIBUTION_START,
- });
+ onSpaceDistributionStart();
addMouseMoveHandlers();
};
@@ -331,5 +330,6 @@ export const useSpaceDistributionEvents = ({
sectionWidgetId,
spaceDistributed,
spaceToWorkWith,
+ onSpaceDistributionStart,
]);
};
diff --git a/app/client/src/layoutSystems/anvil/utils/types.ts b/app/client/src/layoutSystems/anvil/utils/types.ts
index c467a876542e..240ee9c292b8 100644
--- a/app/client/src/layoutSystems/anvil/utils/types.ts
+++ b/app/client/src/layoutSystems/anvil/utils/types.ts
@@ -5,6 +5,7 @@ import type { WidgetType } from "WidgetProvider/factory";
export interface AnvilFlexComponentProps {
children: ReactNode;
className?: string;
+ elevatedBackground?: boolean;
layoutId: string;
parentId?: string;
rowIndex: number;
diff --git a/app/client/src/reducers/uiReducers/dragResizeReducer.ts b/app/client/src/reducers/uiReducers/dragResizeReducer.ts
index 4303e711a819..5c5ddd21b7b1 100644
--- a/app/client/src/reducers/uiReducers/dragResizeReducer.ts
+++ b/app/client/src/reducers/uiReducers/dragResizeReducer.ts
@@ -19,7 +19,13 @@ const initialState: WidgetDragResizeState = {
isAutoCanvasResizing: false,
anvil: {
highlightShown: undefined,
- isDistributingSpace: false,
+ spaceDistribution: {
+ isDistributingSpace: false,
+ widgetsEffected: {
+ section: "",
+ zones: [],
+ },
+ },
},
isDraggingDisabled: false,
blockSelection: false,
@@ -138,13 +144,22 @@ export const widgetDraggingReducer = createImmerReducer(initialState, {
//space distribution redux
[AnvilReduxActionTypes.ANVIL_SPACE_DISTRIBUTION_START]: (
state: WidgetDragResizeState,
+ action: ReduxAction<{
+ section: string;
+ zones: string[];
+ }>,
) => {
- state.anvil.isDistributingSpace = true;
+ state.anvil.spaceDistribution.widgetsEffected.section =
+ action.payload.section;
+ state.anvil.spaceDistribution.widgetsEffected.zones = action.payload.zones;
+ state.anvil.spaceDistribution.isDistributingSpace = true;
},
[AnvilReduxActionTypes.ANVIL_SPACE_DISTRIBUTION_STOP]: (
state: WidgetDragResizeState,
) => {
- state.anvil.isDistributingSpace = false;
+ state.anvil.spaceDistribution.isDistributingSpace = false;
+ state.anvil.spaceDistribution.widgetsEffected.section = "";
+ state.anvil.spaceDistribution.widgetsEffected.zones = [];
},
[AnvilReduxActionTypes.ANVIL_SET_HIGHLIGHT_SHOWN]: (
state: WidgetDragResizeState,
@@ -175,7 +190,13 @@ export interface WidgetDragResizeState {
isResizing: boolean;
anvil: {
highlightShown?: AnvilHighlightInfo;
- isDistributingSpace: boolean;
+ spaceDistribution: {
+ isDistributingSpace: boolean;
+ widgetsEffected: {
+ section: string;
+ zones: string[];
+ };
+ };
};
lastSelectedWidget?: string;
focusedWidget?: string;
diff --git a/app/client/src/widgets/anvil/Container.tsx b/app/client/src/widgets/anvil/Container.tsx
index 26d3a68cef63..30e28e35c3ed 100644
--- a/app/client/src/widgets/anvil/Container.tsx
+++ b/app/client/src/widgets/anvil/Container.tsx
@@ -3,6 +3,7 @@ import React from "react";
import styled from "styled-components";
import { generateClassName } from "utils/generators";
import type { Elevations } from "./constants";
+import { useAnvilWidgetElevationSetter } from "layoutSystems/anvil/editor/canvas/hooks/useAnvilWidgetElevationSetter";
/**
* This container component wraps the Zone and Section widgets and allows Anvil to utilise tokens from the themes
@@ -22,6 +23,7 @@ const StyledContainerComponent = styled.div<
`;
export function ContainerComponent(props: ContainerComponentProps) {
+ useAnvilWidgetElevationSetter(props.widgetId, props.elevatedBackground);
return (
<StyledContainerComponent
className={`${generateClassName(props.widgetId)}`}
|
8fb6abfa126a8b92fd68ba20f44b8150b7651aea
|
2023-02-08 14:26:46
|
Rhitottam
|
fix: Add batching strategy to segment analytics tracking so that events are sent to segment in batches instead of individual (#20087)
| false
|
Add batching strategy to segment analytics tracking so that events are sent to segment in batches instead of individual (#20087)
|
fix
|
diff --git a/app/client/src/utils/AnalyticsUtil.tsx b/app/client/src/utils/AnalyticsUtil.tsx
index 9da944f4f239..c5a9afba4577 100644
--- a/app/client/src/utils/AnalyticsUtil.tsx
+++ b/app/client/src/utils/AnalyticsUtil.tsx
@@ -386,7 +386,20 @@ class AnalyticsUtil {
resolve(false);
}, 2000);
analytics.SNIPPET_VERSION = "4.1.0";
- analytics.load(key);
+ // Ref: https://segment.com/docs/connections/sources/catalog/libraries/website/javascript/#batching
+ analytics.load(key, {
+ integrations: {
+ "Segment.io": {
+ deliveryStrategy: {
+ strategy: "batching", // The delivery strategy used for sending events to Segment
+ config: {
+ size: 100, // The batch size is the threshold that forces all batched events to be sent once it’s reached.
+ timeout: 1000, // The number of milliseconds that forces all events queued for batching to be sent, regardless of the batch size, once it’s reached
+ },
+ },
+ },
+ },
+ });
analytics.page();
}
})(window);
|
39e9923b2d40ab8745989a964730122978d677f3
|
2023-02-22 21:02:05
|
Souma Ghosh
|
fix: Table breaks on adding binding to column name (#20686)
| false
|
Table breaks on adding binding to column name (#20686)
|
fix
|
diff --git a/app/client/cypress/integration/Regression_TestSuite/ClientSideTests/Widgets/TableV2/TableV2_misc.js b/app/client/cypress/integration/Regression_TestSuite/ClientSideTests/Widgets/TableV2/TableV2_misc.js
new file mode 100644
index 000000000000..683c03581bd3
--- /dev/null
+++ b/app/client/cypress/integration/Regression_TestSuite/ClientSideTests/Widgets/TableV2/TableV2_misc.js
@@ -0,0 +1,96 @@
+const dsl = require("../../../../../fixtures/tableV2NewDsl.json");
+import { DEFAULT_COLUMN_NAME } from "../../../../../../src/widgets/TableWidgetV2/constants";
+
+describe("tests bug 20663 TypeError: Cannot read properties of undefined", function() {
+ before(() => {
+ cy.addDsl(dsl);
+ });
+
+ it("when the column label value is a valid string should show the evaluated string", function() {
+ cy.openPropertyPane("tablewidgetv2");
+ cy.get(
+ ".tablewidgetv2-primarycolumn-list div[data-rbd-draggable-id='id'] input[type=text]",
+ ).clear();
+ cy.get(
+ ".tablewidgetv2-primarycolumn-list div[data-rbd-draggable-id='id'] input[type=text]",
+ // For escaping "{" in cypress refer to https://docs.cypress.io/api/commands/type#Arguments
+ // eslint-disable-next-line prettier/prettier
+ ).type("{{}{{}appsmith.mode{}}{}}");
+ cy.contains(
+ ".tableWrap .thead .tr div[role='columnheader']:first-child",
+ "EDIT",
+ );
+ });
+
+ it("when the column label value is a boolean replace column name with default column name", function() {
+ cy.openPropertyPane("tablewidgetv2");
+ cy.get(
+ ".tablewidgetv2-primarycolumn-list div[data-rbd-draggable-id='id'] input[type=text]",
+ ).clear();
+ cy.get(
+ ".tablewidgetv2-primarycolumn-list div[data-rbd-draggable-id='id'] input[type=text]",
+ // eslint-disable-next-line prettier/prettier
+ ).type("{{}{{}false{}}{}}");
+ cy.contains(
+ ".tableWrap .thead .tr div[role='columnheader']:first-child",
+ DEFAULT_COLUMN_NAME,
+ );
+ });
+
+ it("when the column label value is a number replace column name with default column name", function() {
+ cy.openPropertyPane("tablewidgetv2");
+ cy.get(
+ ".tablewidgetv2-primarycolumn-list div[data-rbd-draggable-id='id'] input[type=text]",
+ ).clear();
+ cy.get(
+ ".tablewidgetv2-primarycolumn-list div[data-rbd-draggable-id='id'] input[type=text]",
+ // eslint-disable-next-line prettier/prettier
+ ).type("{{}{{}0{}}{}}");
+ cy.contains(
+ ".tableWrap .thead .tr div[role='columnheader']:first-child",
+ DEFAULT_COLUMN_NAME,
+ );
+
+ cy.get(
+ ".tablewidgetv2-primarycolumn-list div[data-rbd-draggable-id='id'] input[type=text]",
+ ).clear();
+ cy.get(
+ ".tablewidgetv2-primarycolumn-list div[data-rbd-draggable-id='id'] input[type=text]",
+ // eslint-disable-next-line prettier/prettier
+ ).type("{{}{{}982{}}{}}");
+ cy.contains(
+ ".tableWrap .thead .tr div[role='columnheader']:first-child",
+ DEFAULT_COLUMN_NAME,
+ );
+ });
+
+ it("when the column label value is an object replace column name with default column name", function() {
+ cy.openPropertyPane("tablewidgetv2");
+ cy.get(
+ ".tablewidgetv2-primarycolumn-list div[data-rbd-draggable-id='id'] input[type=text]",
+ ).clear();
+ cy.get(
+ ".tablewidgetv2-primarycolumn-list div[data-rbd-draggable-id='id'] input[type=text]",
+ // eslint-disable-next-line prettier/prettier
+ ).type("{{}{{}appsmith{}}{}}");
+ cy.contains(
+ ".tableWrap .thead .tr div[role='columnheader']:first-child",
+ DEFAULT_COLUMN_NAME,
+ );
+ });
+
+ it("when the column label value is undefined replace column name with default column name", function() {
+ cy.openPropertyPane("tablewidgetv2");
+ cy.get(
+ ".tablewidgetv2-primarycolumn-list div[data-rbd-draggable-id='id'] input[type=text]",
+ ).clear();
+ cy.get(
+ ".tablewidgetv2-primarycolumn-list div[data-rbd-draggable-id='id'] input[type=text]",
+ // eslint-disable-next-line prettier/prettier
+ ).type("{{}{{}ap{}}{}}");
+ cy.contains(
+ ".tableWrap .thead .tr div[role='columnheader']:first-child",
+ DEFAULT_COLUMN_NAME,
+ );
+ });
+});
diff --git a/app/client/src/widgets/TableWidgetV2/constants.ts b/app/client/src/widgets/TableWidgetV2/constants.ts
index 179284aecc0f..4c32fc1cd6cc 100644
--- a/app/client/src/widgets/TableWidgetV2/constants.ts
+++ b/app/client/src/widgets/TableWidgetV2/constants.ts
@@ -214,3 +214,5 @@ export const defaultEditableCell = {
value: "",
initialValue: "",
};
+
+export const DEFAULT_COLUMN_NAME = "Table Column";
diff --git a/app/client/src/widgets/TableWidgetV2/widget/index.tsx b/app/client/src/widgets/TableWidgetV2/widget/index.tsx
index 39a4fb55a18d..314e9c492696 100644
--- a/app/client/src/widgets/TableWidgetV2/widget/index.tsx
+++ b/app/client/src/widgets/TableWidgetV2/widget/index.tsx
@@ -52,6 +52,7 @@ import {
TableWidgetProps,
TABLE_COLUMN_ORDER_KEY,
TransientDataPayload,
+ DEFAULT_COLUMN_NAME,
} from "../constants";
import derivedProperties from "./parseDerivedProperties";
import {
@@ -223,7 +224,10 @@ class TableWidgetV2 extends BaseWidget<TableWidgetProps, WidgetState> {
const columnData = {
id: column.id,
- Header: column.label,
+ Header:
+ column.hasOwnProperty("label") && typeof column.label === "string"
+ ? column.label
+ : DEFAULT_COLUMN_NAME,
alias: column.alias,
accessor: (row: any) => row[column.alias],
width: columnWidthMap[column.id] || DEFAULT_COLUMN_WIDTH,
|
3bf43dc73a463f110491f27821ee84d05dd80632
|
2021-12-29 10:29:47
|
Abhijeet
|
fix: Filter the action and collection with no pageIds to fix server error while importing the application (#10024)
| false
|
Filter the action and collection with no pageIds to fix server error while importing the application (#10024)
|
fix
|
diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ce/ImportExportApplicationServiceCEImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ce/ImportExportApplicationServiceCEImpl.java
index fd66ff2812fb..01abfdd52ccb 100644
--- a/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ce/ImportExportApplicationServiceCEImpl.java
+++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ce/ImportExportApplicationServiceCEImpl.java
@@ -660,6 +660,8 @@ public Mono<Application> importApplicationInOrganization(String organizationId,
assert importedNewActionList != null;
return Flux.fromIterable(importedNewActionList)
+ .filter(action -> action.getUnpublishedAction() != null
+ && !StringUtils.isEmpty(action.getUnpublishedAction().getPageId()))
.flatMap(newAction -> {
NewPage parentPage = new NewPage();
if (newAction.getDefaultResources() != null) {
@@ -767,6 +769,8 @@ public Mono<Application> importApplicationInOrganization(String organizationId,
}
return Flux.fromIterable(importedActionCollectionList)
+ .filter(actionCollection -> actionCollection.getUnpublishedCollection() != null
+ && !StringUtils.isEmpty(actionCollection.getUnpublishedCollection().getPageId()))
.flatMap(actionCollection -> {
if (actionCollection.getDefaultResources() != null) {
actionCollection.getDefaultResources().setBranchName(branchName);
diff --git a/app/server/appsmith-server/src/test/java/com/appsmith/server/solutions/ImportExportApplicationServiceTests.java b/app/server/appsmith-server/src/test/java/com/appsmith/server/solutions/ImportExportApplicationServiceTests.java
index 3b1dbc4c1fc7..27790e069d25 100644
--- a/app/server/appsmith-server/src/test/java/com/appsmith/server/solutions/ImportExportApplicationServiceTests.java
+++ b/app/server/appsmith-server/src/test/java/com/appsmith/server/solutions/ImportExportApplicationServiceTests.java
@@ -820,6 +820,52 @@ public void importApplication_withoutActionCollection_succeedsWithoutError() {
.verifyComplete();
}
+ @Test
+ @WithUserDetails(value = "api_user")
+ public void importApplication_withoutPageIdInActionCollection_succeeds() {
+
+ FilePart filePart = createFilePart("test_assets/ImportExportServiceTest/invalid-application-without-pageId-action-collection.json");
+
+ Organization newOrganization = new Organization();
+ newOrganization.setName("Template Organization");
+
+ final Mono<Application> resultMono = organizationService
+ .create(newOrganization)
+ .flatMap(organization -> importExportApplicationService
+ .extractFileAndSaveApplication(organization.getId(), filePart)
+ );
+
+ StepVerifier
+ .create(resultMono
+ .flatMap(application -> Mono.zip(
+ Mono.just(application),
+ datasourceService.findAllByOrganizationId(application.getOrganizationId(), MANAGE_DATASOURCES).collectList(),
+ getActionsInApplication(application).collectList(),
+ newPageService.findByApplicationId(application.getId(), MANAGE_PAGES, false).collectList(),
+ actionCollectionService
+ .findAllByApplicationIdAndViewMode(application.getId(), false, MANAGE_ACTIONS, null).collectList()
+ )))
+ .assertNext(tuple -> {
+ final Application application = tuple.getT1();
+ final List<Datasource> datasourceList = tuple.getT2();
+ final List<ActionDTO> actionDTOS = tuple.getT3();
+ final List<PageDTO> pageList = tuple.getT4();
+ final List<ActionCollection> actionCollectionList = tuple.getT5();
+
+
+ assertThat(datasourceList).isNotEmpty();
+
+ assertThat(actionDTOS).hasSize(1);
+ actionDTOS.forEach(actionDTO -> {
+ assertThat(actionDTO.getPageId()).isNotEqualTo(pageList.get(0).getName());
+
+ });
+
+ assertThat(actionCollectionList).isEmpty();
+ })
+ .verifyComplete();
+ }
+
@Test
@WithUserDetails(value = "api_user")
public void exportImportApplication_importWithBranchName_updateApplicationResourcesWithBranch() {
diff --git a/app/server/appsmith-server/src/test/resources/test_assets/ImportExportServiceTest/invalid-application-without-pageId-action-collection.json b/app/server/appsmith-server/src/test/resources/test_assets/ImportExportServiceTest/invalid-application-without-pageId-action-collection.json
new file mode 100644
index 000000000000..dd71ae2de922
--- /dev/null
+++ b/app/server/appsmith-server/src/test/resources/test_assets/ImportExportServiceTest/invalid-application-without-pageId-action-collection.json
@@ -0,0 +1,528 @@
+{
+ "exportedApplication": {
+ "userPermissions": [
+ "canComment:applications",
+ "manage:applications",
+ "read:applications",
+ "publish:applications",
+ "makePublic:applications"
+ ],
+ "name": "valid_application",
+ "isPublic": false,
+ "appIsExample": false,
+ "color": "#EA6179",
+ "icon": "medical",
+ "new": true
+ },
+ "datasourceList": [
+ {
+ "userPermissions": [
+ "execute:datasources",
+ "manage:datasources",
+ "read:datasources"
+ ],
+ "name": "api_ds_wo_auth",
+ "pluginId": "restapi-plugin",
+ "gitSyncId": "datasource2_git",
+ "datasourceConfiguration": {
+ "sshProxyEnabled": false,
+ "properties": [
+ {
+ "key": "isSendSessionEnabled",
+ "value": "N"
+ },
+ {
+ "key": "sessionSignatureKey",
+ "value": ""
+ }
+ ],
+ "url": "https://api-ds-wo-auth-uri.com",
+ "headers": []
+ },
+ "invalids": [],
+ "isValid": true,
+ "new": true
+ }
+ ],
+ "pageList": [
+ {
+ "userPermissions": [
+ "read:pages",
+ "manage:pages"
+ ],
+ "gitSyncId": "page1_git",
+ "applicationId": "valid_application",
+ "unpublishedPage": {
+ "name": "Page1",
+ "layouts": [
+ {
+ "id": "60aca056136c4b7178f67906",
+ "userPermissions": [],
+ "dsl": {
+ "widgetName": "MainContainer",
+ "backgroundColor": "none",
+ "rightColumn": 1280,
+ "snapColumns": 16,
+ "detachFromLayout": true,
+ "widgetId": "0",
+ "topRow": 0,
+ "bottomRow": 800,
+ "containerStyle": "none",
+ "snapRows": 33,
+ "parentRowSpace": 1,
+ "type": "CANVAS_WIDGET",
+ "canExtend": true,
+ "version": 4,
+ "minHeight": 840,
+ "parentColumnSpace": 1,
+ "dynamicTriggerPathList": [],
+ "dynamicBindingPathList": [],
+ "leftColumn": 0,
+ "children": [
+ {
+ "widgetName": "Table1",
+ "columnOrder": [
+ "_id",
+ "username",
+ "active"
+ ],
+ "dynamicPropertyPathList": [],
+ "topRow": 4,
+ "bottomRow": 15,
+ "parentRowSpace": 40,
+ "type": "TABLE_WIDGET",
+ "parentColumnSpace": 77.5,
+ "dynamicTriggerPathList": [],
+ "dynamicBindingPathList": [
+ {
+ "key": "tableData"
+ },
+ {
+ "key": "primaryColumns._id.computedValue"
+ },
+ {
+ "key": "primaryColumns.username.computedValue"
+ },
+ {
+ "key": "primaryColumns.active.computedValue"
+ }
+ ],
+ "leftColumn": 0,
+ "primaryColumns": {
+ "appsmith_mongo_escape_id": {
+ "isDerived": false,
+ "computedValue": "{{Table1.sanitizedTableData.map((currentRow) => ( currentRow._id ))}}",
+ "textSize": "PARAGRAPH",
+ "index": 4,
+ "isVisible": true,
+ "label": "_id",
+ "columnType": "text",
+ "horizontalAlignment": "LEFT",
+ "width": 150,
+ "enableFilter": true,
+ "enableSort": true,
+ "id": "_id",
+ "verticalAlignment": "CENTER"
+ },
+ "active": {
+ "isDerived": false,
+ "computedValue": "{{Table1.sanitizedTableData.map((currentRow) => ( currentRow.active ))}}",
+ "textSize": "PARAGRAPH",
+ "index": 8,
+ "isVisible": true,
+ "label": "active",
+ "columnType": "text",
+ "horizontalAlignment": "LEFT",
+ "width": 150,
+ "enableFilter": true,
+ "enableSort": true,
+ "id": "active",
+ "verticalAlignment": "CENTER"
+ },
+ "username": {
+ "isDerived": false,
+ "computedValue": "{{Table1.sanitizedTableData.map((currentRow) => ( currentRow.username ))}}",
+ "textSize": "PARAGRAPH",
+ "index": 7,
+ "isVisible": true,
+ "label": "username",
+ "columnType": "text",
+ "horizontalAlignment": "LEFT",
+ "width": 150,
+ "enableFilter": true,
+ "enableSort": true,
+ "id": "username",
+ "verticalAlignment": "CENTER"
+ }
+ },
+ "derivedColumns": {},
+ "rightColumn": 8,
+ "textSize": "PARAGRAPH",
+ "widgetId": "aisibaxwhb",
+ "tableData": "{{get_users.data}}",
+ "isVisible": true,
+ "label": "Data",
+ "searchKey": "",
+ "version": 1,
+ "parentId": "0",
+ "isLoading": false,
+ "horizontalAlignment": "LEFT",
+ "verticalAlignment": "CENTER",
+ "columnSizeMap": {
+ "task": 245,
+ "step": 62,
+ "status": 75
+ }
+ },
+ {
+ "widgetName": "Form1",
+ "backgroundColor": "white",
+ "rightColumn": 16,
+ "widgetId": "ut3l54pzqw",
+ "topRow": 4,
+ "bottomRow": 11,
+ "parentRowSpace": 40,
+ "isVisible": true,
+ "type": "FORM_WIDGET",
+ "parentId": "0",
+ "isLoading": false,
+ "parentColumnSpace": 77.5,
+ "leftColumn": 9,
+ "children": [
+ {
+ "widgetName": "Canvas1",
+ "rightColumn": 542.5,
+ "detachFromLayout": true,
+ "widgetId": "mcsltg1l0j",
+ "containerStyle": "none",
+ "topRow": 0,
+ "bottomRow": 320,
+ "parentRowSpace": 1,
+ "isVisible": true,
+ "canExtend": false,
+ "type": "CANVAS_WIDGET",
+ "version": 1,
+ "parentId": "ut3l54pzqw",
+ "minHeight": 520,
+ "isLoading": false,
+ "parentColumnSpace": 1,
+ "leftColumn": 0,
+ "children": [
+ {
+ "widgetName": "Text1",
+ "rightColumn": 6,
+ "textAlign": "LEFT",
+ "widgetId": "7b4x786lxp",
+ "topRow": 0,
+ "bottomRow": 1,
+ "isVisible": true,
+ "fontStyle": "BOLD",
+ "type": "TEXT_WIDGET",
+ "textColor": "#231F20",
+ "version": 1,
+ "parentId": "mcsltg1l0j",
+ "isLoading": false,
+ "leftColumn": 0,
+ "fontSize": "HEADING1",
+ "text": "Form"
+ },
+ {
+ "widgetName": "Text2",
+ "rightColumn": 16,
+ "textAlign": "LEFT",
+ "widgetId": "d0axuxiosp",
+ "topRow": 3,
+ "bottomRow": 6,
+ "parentRowSpace": 40,
+ "isVisible": true,
+ "fontStyle": "BOLD",
+ "type": "TEXT_WIDGET",
+ "textColor": "#231F20",
+ "version": 1,
+ "parentId": "mcsltg1l0j",
+ "isLoading": false,
+ "parentColumnSpace": 31.40625,
+ "dynamicTriggerPathList": [],
+ "leftColumn": 0,
+ "dynamicBindingPathList": [
+ {
+ "key": "text"
+ }
+ ],
+ "fontSize": "PARAGRAPH2",
+ "text": "{{api_wo_auth.data.body}}"
+ },
+ {
+ "widgetName": "Text3",
+ "rightColumn": 4,
+ "textAlign": "LEFT",
+ "widgetId": "lmfer0622c",
+ "topRow": 2,
+ "bottomRow": 3,
+ "parentRowSpace": 40,
+ "isVisible": true,
+ "fontStyle": "BOLD",
+ "type": "TEXT_WIDGET",
+ "textColor": "#231F20",
+ "version": 1,
+ "parentId": "mcsltg1l0j",
+ "isLoading": false,
+ "parentColumnSpace": 31.40625,
+ "dynamicTriggerPathList": [],
+ "leftColumn": 0,
+ "dynamicBindingPathList": [
+ {
+ "key": "text"
+ }
+ ],
+ "fontSize": "PARAGRAPH",
+ "text": "{{api_wo_auth.data.id}}"
+ }
+ ]
+ }
+ ]
+ }
+ ]
+ },
+ "layoutOnLoadActions": [
+ [
+ {
+ "id": "60aca24c136c4b7178f6790d",
+ "name": "api_wo_auth",
+ "pluginType": "API",
+ "jsonPathKeys": [],
+ "timeoutInMillisecond": 10000
+ }
+ ]
+ ],
+ "new": false
+ }
+ ],
+ "userPermissions": []
+ },
+ "publishedPage": {
+ "name": "Page1",
+ "layouts": [
+ {
+ "id": "60aca056136c4b7178f67906",
+ "userPermissions": [],
+ "dsl": {
+ "widgetName": "MainContainer",
+ "backgroundColor": "none",
+ "rightColumn": 1224,
+ "snapColumns": 16,
+ "detachFromLayout": true,
+ "widgetId": "0",
+ "topRow": 0,
+ "bottomRow": 1254,
+ "containerStyle": "none",
+ "snapRows": 33,
+ "parentRowSpace": 1,
+ "type": "CANVAS_WIDGET",
+ "canExtend": true,
+ "version": 4,
+ "minHeight": 1292,
+ "parentColumnSpace": 1,
+ "dynamicBindingPathList": [],
+ "leftColumn": 0,
+ "children": []
+ },
+ "new": false
+ }
+ ],
+ "userPermissions": []
+ },
+ "new": true
+ },
+ {
+ "userPermissions": [
+ "read:pages",
+ "manage:pages"
+ ],
+ "gitSyncId": "page2_git",
+ "applicationId": "valid_application",
+ "unpublishedPage": {
+ "name": "Page2",
+ "layouts": [
+ {
+ "id": "60aca056136c4b7178f67999",
+ "userPermissions": [],
+ "dsl": {
+ "widgetName": "MainContainer",
+ "backgroundColor": "none",
+ "rightColumn": 1280,
+ "snapColumns": 16,
+ "detachFromLayout": true,
+ "widgetId": "0",
+ "topRow": 0,
+ "bottomRow": 800,
+ "containerStyle": "none",
+ "snapRows": 33,
+ "parentRowSpace": 1,
+ "type": "CANVAS_WIDGET",
+ "canExtend": true,
+ "version": 4,
+ "minHeight": 840,
+ "parentColumnSpace": 1,
+ "dynamicTriggerPathList": [],
+ "dynamicBindingPathList": [],
+ "leftColumn": 0,
+ "children": []
+ },
+ "layoutOnLoadActions": [
+ []
+ ],
+ "new": false
+ }
+ ],
+ "userPermissions": []
+ },
+ "new": true
+ }
+ ],
+ "actionList": [
+ {
+ "id": "60aca092136c4b7178f6790a",
+ "userPermissions": [],
+ "applicationId": "valid_application",
+ "pluginType": "DB",
+ "pluginId": "mongo-plugin",
+ "gitSyncId": "action1_git",
+ "unpublishedAction": {
+ "name": "get_users",
+ "datasource": {
+ "id": "db-auth",
+ "userPermissions": [],
+ "isValid": true,
+ "new": false
+ },
+ "actionConfiguration": {
+ "timeoutInMillisecond": 10000,
+ "paginationType": "NONE",
+ "encodeParamsToggle": true,
+ "body": "{\n \"find\": \"users\",\n \"sort\": {\n \"id\": 1\n },\n \"limit\": 10\n}",
+ "pluginSpecifiedTemplates": [
+ {
+ "value": false
+ }
+ ]
+ },
+ "executeOnLoad": true,
+ "dynamicBindingPathList": [],
+ "isValid": true,
+ "invalids": [],
+ "jsonPathKeys": [],
+ "confirmBeforeExecute": false,
+ "userPermissions": []
+ },
+ "publishedAction": {
+ "datasource": {
+ "userPermissions": [],
+ "isValid": true,
+ "new": true
+ },
+ "confirmBeforeExecute": false,
+ "userPermissions": []
+ },
+ "new": false
+ },
+ {
+ "id": "60aca24c136c4b7178f6790d",
+ "userPermissions": [],
+ "applicationId": "valid_application",
+ "pluginType": "API",
+ "pluginId": "restapi-plugin",
+ "gitSyncId": "action2_git",
+ "unpublishedAction": {
+ "name": "api_wo_auth",
+ "datasource": {
+ "id": "api_ds_wo_auth",
+ "userPermissions": [],
+ "isValid": true,
+ "new": false
+ },
+ "pageId": "Page1",
+ "actionConfiguration": {
+ "timeoutInMillisecond": 10000,
+ "paginationType": "NONE",
+ "path": "/params",
+ "headers": [
+ {
+ "key": "",
+ "value": ""
+ },
+ {
+ "key": "",
+ "value": ""
+ }
+ ],
+ "encodeParamsToggle": true,
+ "queryParameters": [],
+ "body": "",
+ "httpMethod": "GET",
+ "pluginSpecifiedTemplates": [
+ {
+ "value": false
+ }
+ ]
+ },
+ "executeOnLoad": true,
+ "dynamicBindingPathList": [],
+ "isValid": true,
+ "invalids": [],
+ "jsonPathKeys": [],
+ "confirmBeforeExecute": false,
+ "userPermissions": []
+ },
+ "publishedAction": {
+ "datasource": {
+ "userPermissions": [],
+ "isValid": true,
+ "new": true
+ },
+ "confirmBeforeExecute": false,
+ "userPermissions": []
+ },
+ "new": false
+ }
+ ],
+ "actionCollectionList": [
+ {
+ "id": "61518b8548b30155375f5276",
+ "userPermissions": [
+ "read:actions",
+ "execute:actions",
+ "manage:actions"
+ ],
+ "unpublishedCollection": {
+ "name": "JSObject1",
+ "pluginId": "js-plugin",
+ "pluginType": "JS",
+ "actions": [],
+ "archivedActions": [],
+ "body": "export default {\n\tresults: [],\n\trun: () => {\n\t\t//write code here\n\t\treturn \"Hi\"\n\t}\n}",
+ "variables": [
+ {
+ "name": "results",
+ "value": []
+ }
+ ]
+ },
+ "new": false
+ }
+ ],
+ "decryptedFields": {
+ },
+ "publishedDefaultPageName": "Page1",
+ "unpublishedDefaultPageName": "Page1",
+ "publishedLayoutmongoEscapedWidgets": {
+ "60aca056136c4b7178f67906": [
+ "Table1"
+ ]
+ },
+ "unpublishedLayoutmongoEscapedWidgets": {
+ "60aca056136c4b7178f67906": [
+ "Table1"
+ ]
+ }
+}
\ No newline at end of file
|
63dc8123bb377ce87512a2452d63b7055b067195
|
2021-08-04 10:20:27
|
akash-codemonk
|
fix: Update debugger placeholder text for non-mac (#6142)
| false
|
Update debugger placeholder text for non-mac (#6142)
|
fix
|
diff --git a/app/client/src/components/editorComponents/Debugger/helpers.tsx b/app/client/src/components/editorComponents/Debugger/helpers.tsx
index 93f8cd3d1d54..aa2981b6be10 100644
--- a/app/client/src/components/editorComponents/Debugger/helpers.tsx
+++ b/app/client/src/components/editorComponents/Debugger/helpers.tsx
@@ -10,6 +10,7 @@ import {
QUERIES_EDITOR_URL,
} from "constants/routes";
import { getEntityNameAndPropertyPath } from "workers/evaluationUtils";
+import { isMac } from "utils/helpers";
const BlankStateWrapper = styled.div`
overflow: auto;
@@ -30,12 +31,14 @@ export function BlankState(props: {
placeholderText?: string;
hasShortCut?: boolean;
}) {
+ const shortcut = isMac() ? "Cmd + D" : "Ctrl + D";
+
return (
<BlankStateWrapper>
{props.hasShortCut ? (
<span>
{createMessage(PRESS)}
- <span className="debugger-shortcut">Cmd + D</span>
+ <span className="debugger-shortcut">{shortcut}</span>
{createMessage(OPEN_THE_DEBUGGER)}
</span>
) : (
diff --git a/app/client/src/constants/messages.ts b/app/client/src/constants/messages.ts
index 41bfe2543c3a..0a02dbd7ade1 100644
--- a/app/client/src/constants/messages.ts
+++ b/app/client/src/constants/messages.ts
@@ -338,7 +338,7 @@ export const BACK = () => "BACK";
// Debugger
export const CLICK_ON = () => "🙌 Click on ";
export const PRESS = () => "🎉 Press ";
-export const OPEN_THE_DEBUGGER = () => " to open the debugger";
+export const OPEN_THE_DEBUGGER = () => " to show / hide the debugger";
export const NO_LOGS = () => "No logs to show";
export const NO_ERRORS = () => "No signs of trouble here!";
export const DEBUGGER_ERRORS = () => "Errors";
|
705d275d12571cd87d576229dafa207af75879cf
|
2022-02-26 09:22:06
|
rashmi rai
|
fix: add binding paths for new UQI components (#11287)
| false
|
add binding paths for new UQI components (#11287)
|
fix
|
diff --git a/app/client/src/components/formControls/EntitySelectorControl.tsx b/app/client/src/components/formControls/EntitySelectorControl.tsx
index bfa5bab32b8b..99f7cf8daa62 100644
--- a/app/client/src/components/formControls/EntitySelectorControl.tsx
+++ b/app/client/src/components/formControls/EntitySelectorControl.tsx
@@ -5,6 +5,8 @@ import FormLabel from "components/editorComponents/FormLabel";
import { ControlProps } from "./BaseControl";
import { Colors } from "constants/Colors";
import Icon, { IconSize } from "components/ads/Icon";
+import { getBindingOrConfigPathsForEntitySelectorControl } from "entities/Action/actionProperties";
+import { allowedControlTypes } from "components/formControls/utils";
const dropDownFieldConfig: any = {
label: "",
@@ -18,8 +20,6 @@ const inputFieldConfig: any = {
controlType: "QUERY_DYNAMIC_INPUT_TEXT",
};
-const allowedControlTypes = ["DROP_DOWN", "QUERY_DYNAMIC_INPUT_TEXT"];
-
// Component for the icons
const CenteredIcon = styled(Icon)<{ noMarginLeft?: boolean }>`
margin: 13px;
@@ -64,8 +64,12 @@ function EntitySelectorComponent(props: any) {
<EntitySelectorContainer>
{schema &&
schema.length > 0 &&
- schema.map(
- (singleSchema: any, index: number) =>
+ schema.map((singleSchema: any, index: number) => {
+ const columnPath = getBindingOrConfigPathsForEntitySelectorControl(
+ configProperty,
+ index,
+ );
+ return (
allowedControlTypes.includes(singleSchema.controlType) && (
<>
{singleSchema.controlType === "DROP_DOWN" ? (
@@ -74,8 +78,8 @@ function EntitySelectorComponent(props: any) {
...dropDownFieldConfig,
...singleSchema,
customStyles,
- configProperty: `${configProperty}.column_${index + 1}`,
- key: `${configProperty}.column_${index + 1}`,
+ configProperty: columnPath,
+ key: columnPath,
}}
formName={props.formName}
/>
@@ -85,8 +89,8 @@ function EntitySelectorComponent(props: any) {
...inputFieldConfig,
...singleSchema,
customStyles,
- configProperty: `${configProperty}.column_${index + 1}`,
- key: `${configProperty}.column_${index + 1}`,
+ configProperty: columnPath,
+ key: columnPath,
}}
formName={props.formName}
/>
@@ -98,8 +102,9 @@ function EntitySelectorComponent(props: any) {
/>
)}
</>
- ),
- )}
+ )
+ );
+ })}
</EntitySelectorContainer>
);
}
diff --git a/app/client/src/components/formControls/PaginationControl.tsx b/app/client/src/components/formControls/PaginationControl.tsx
index 76c811c89aa0..74a93bc00451 100644
--- a/app/client/src/components/formControls/PaginationControl.tsx
+++ b/app/client/src/components/formControls/PaginationControl.tsx
@@ -5,6 +5,8 @@ import FormControl from "pages/Editor/FormControl";
import FormLabel from "components/editorComponents/FormLabel";
import { Colors } from "constants/Colors";
import styled from "styled-components";
+import { getBindingOrConfigPathsForPaginationControl } from "entities/Action/actionProperties";
+import { PaginationSubComponent } from "components/formControls/utils";
export const StyledFormLabel = styled(FormLabel)`
margin-top: 5px;
@@ -53,6 +55,15 @@ export function Pagination(props: {
}) {
const { configProperty, customStyles, formName, initialValue, name } = props;
+ const offsetPath = getBindingOrConfigPathsForPaginationControl(
+ PaginationSubComponent.Offset,
+ configProperty,
+ );
+ const limitPath = getBindingOrConfigPathsForPaginationControl(
+ PaginationSubComponent.Limit,
+ configProperty,
+ );
+
return (
<div
data-cy={name}
@@ -67,7 +78,7 @@ export function Pagination(props: {
...limitFieldConfig,
label: "Limit",
customStyles,
- configProperty: `${configProperty}.limit`,
+ configProperty: limitPath,
initialValue:
typeof initialValue === "object" ? initialValue.limit : null,
}}
@@ -83,7 +94,7 @@ export function Pagination(props: {
...offsetFieldConfig,
label: "Offset",
customStyles,
- configProperty: `${configProperty}.offset`,
+ configProperty: offsetPath,
initialValue:
typeof initialValue === "object" ? initialValue.offset : null,
}}
diff --git a/app/client/src/components/formControls/SortingControl.tsx b/app/client/src/components/formControls/SortingControl.tsx
index f8e2e840d034..7867e8162cf8 100644
--- a/app/client/src/components/formControls/SortingControl.tsx
+++ b/app/client/src/components/formControls/SortingControl.tsx
@@ -6,6 +6,8 @@ import { FieldArray } from "redux-form";
import FormLabel from "components/editorComponents/FormLabel";
import { ControlProps } from "./BaseControl";
import { Colors } from "constants/Colors";
+import { getBindingOrConfigPathsForSortingControl } from "entities/Action/actionProperties";
+import { SortingSubComponent } from "./utils";
// sorting's order dropdown values
enum OrderDropDownValues {
@@ -139,43 +141,55 @@ function SortingComponent(props: any) {
<SortingContainer>
{props.fields &&
props.fields.length > 0 &&
- props.fields.map((field: any, index: number) => (
- <SortingDropdownContainer key={index}>
- <ColumnDropdownContainer>
- <FormControl
- config={{
- ...columnFieldConfig,
- customStyles: columnCustomStyles,
- configProperty: `${field}.column`,
- nestedFormControl: true,
- }}
- formName={props.formName}
- />
- </ColumnDropdownContainer>
- <OrderDropdownContainer>
- <FormControl
- config={{
- ...orderFieldConfig,
- customStyles: orderCustomStyles,
- configProperty: `${field}.order`,
- nestedFormControl: true,
- }}
- formName={props.formName}
- />
- </OrderDropdownContainer>
- {/* Component to render the delete icon */}
- {index !== 0 && (
- <CenteredIcon
- name="cross"
- onClick={(e) => {
- e.stopPropagation();
- onDeletePressed(index);
- }}
- size={IconSize.SMALL}
- />
- )}
- </SortingDropdownContainer>
- ))}
+ props.fields.map((field: any, index: number) => {
+ const columnPath = getBindingOrConfigPathsForSortingControl(
+ SortingSubComponent.Column,
+ field,
+ undefined,
+ );
+ const OrderPath = getBindingOrConfigPathsForSortingControl(
+ SortingSubComponent.Order,
+ field,
+ undefined,
+ );
+ return (
+ <SortingDropdownContainer key={index}>
+ <ColumnDropdownContainer>
+ <FormControl
+ config={{
+ ...columnFieldConfig,
+ customStyles: columnCustomStyles,
+ configProperty: `${columnPath}`,
+ nestedFormControl: true,
+ }}
+ formName={props.formName}
+ />
+ </ColumnDropdownContainer>
+ <OrderDropdownContainer>
+ <FormControl
+ config={{
+ ...orderFieldConfig,
+ customStyles: orderCustomStyles,
+ configProperty: `${OrderPath}`,
+ nestedFormControl: true,
+ }}
+ formName={props.formName}
+ />
+ </OrderDropdownContainer>
+ {/* Component to render the delete icon */}
+ {index !== 0 && (
+ <CenteredIcon
+ name="cross"
+ onClick={(e) => {
+ e.stopPropagation();
+ onDeletePressed(index);
+ }}
+ size={IconSize.SMALL}
+ />
+ )}
+ </SortingDropdownContainer>
+ );
+ })}
<StyledBottomLabelContainer
onClick={() =>
diff --git a/app/client/src/components/formControls/WhereClauseControl.tsx b/app/client/src/components/formControls/WhereClauseControl.tsx
index e80ae22e29d4..3cefb405a603 100644
--- a/app/client/src/components/formControls/WhereClauseControl.tsx
+++ b/app/client/src/components/formControls/WhereClauseControl.tsx
@@ -8,6 +8,8 @@ import { FieldArray, getFormValues } from "redux-form";
import { ControlProps } from "./BaseControl";
import _ from "lodash";
import { useSelector } from "react-redux";
+import { getBindingOrConfigPathsForWhereClauseControl } from "entities/Action/actionProperties";
+import { WhereClauseSubComponent } from "./utils";
// Type of the value for each condition
export type whereClauseValueType = {
@@ -129,6 +131,20 @@ function ConditionComponent(props: any, index: number) {
valueLabel = "Value";
conditionLabel = "Operator";
}
+
+ const keyPath = getBindingOrConfigPathsForWhereClauseControl(
+ props.field,
+ WhereClauseSubComponent.Key,
+ );
+ const valuePath = getBindingOrConfigPathsForWhereClauseControl(
+ props.field,
+ WhereClauseSubComponent.Value,
+ );
+ const conditionPath = getBindingOrConfigPathsForWhereClauseControl(
+ props.field,
+ WhereClauseSubComponent.Condition,
+ );
+
return (
<ConditionBox key={index}>
{/* Component to input the LHS for single condition */}
@@ -137,7 +153,7 @@ function ConditionComponent(props: any, index: number) {
...keyFieldConfig,
label: keyLabel,
customStyles: { width: `${unitWidth * 2}vw` },
- configProperty: `${props.field}.key`,
+ configProperty: keyPath,
}}
formName={props.formName}
/>
@@ -147,7 +163,7 @@ function ConditionComponent(props: any, index: number) {
...conditionFieldConfig,
label: conditionLabel,
customStyles: { width: `${unitWidth * 1}vw` },
- configProperty: `${props.field}.condition`,
+ configProperty: conditionPath,
options: props.comparisonTypes,
initialValue: props.comparisonTypes[0].value,
}}
@@ -159,7 +175,7 @@ function ConditionComponent(props: any, index: number) {
...valueFieldConfig,
label: valueLabel,
customStyles: { width: `${unitWidth * 2}vw` },
- configProperty: `${props.field}.value`,
+ configProperty: valuePath,
}}
formName={props.formName}
/>
@@ -216,6 +232,11 @@ function ConditionBlock(props: any) {
if (props.logicalTypes.length === 1) {
isDisabled = true;
}
+ const conditionPath = getBindingOrConfigPathsForWhereClauseControl(
+ props.configProperty,
+ WhereClauseSubComponent.Condition,
+ );
+
return (
<PrimaryBox style={{ marginTop }}>
<SecondaryBox>
@@ -223,7 +244,7 @@ function ConditionBlock(props: any) {
<FormControl
config={{
...logicalFieldConfig,
- configProperty: `${props.configProperty}.condition`,
+ configProperty: conditionPath,
options: props.logicalTypes,
initialValue: props.logicalTypes[0].value,
isDisabled,
diff --git a/app/client/src/components/formControls/utils.ts b/app/client/src/components/formControls/utils.ts
index 3e50418fd0e1..408343f45d78 100644
--- a/app/client/src/components/formControls/utils.ts
+++ b/app/client/src/components/formControls/utils.ts
@@ -146,3 +146,22 @@ export const actionPathFromName = (
}
return `${actionName}.${path}`;
};
+
+export enum PaginationSubComponent {
+ Limit = "limit",
+ Offset = "offset",
+}
+
+export enum SortingSubComponent {
+ Column = "column",
+ Order = "order",
+}
+
+export enum WhereClauseSubComponent {
+ Condition = "condition",
+ Children = "children",
+ Key = "key",
+ Value = "value",
+}
+
+export const allowedControlTypes = ["DROP_DOWN", "QUERY_DYNAMIC_INPUT_TEXT"];
diff --git a/app/client/src/entities/Action/actionProperties.ts b/app/client/src/entities/Action/actionProperties.ts
index f4221d0fccc6..713822ca437b 100644
--- a/app/client/src/entities/Action/actionProperties.ts
+++ b/app/client/src/entities/Action/actionProperties.ts
@@ -2,6 +2,12 @@ import { Action } from "entities/Action/index";
import _ from "lodash";
import { EvaluationSubstitutionType } from "entities/DataTree/dataTreeFactory";
import { isHidden } from "components/formControls/utils";
+import {
+ PaginationSubComponent,
+ SortingSubComponent,
+ WhereClauseSubComponent,
+ allowedControlTypes,
+} from "components/formControls/utils";
const dynamicFields = ["QUERY_DYNAMIC_TEXT", "QUERY_DYNAMIC_INPUT_TEXT"];
@@ -73,24 +79,31 @@ export const getBindingPathsOfAction = (
Array.isArray(actionValue.children)
) {
actionValue.children.forEach((value: any, index: number) => {
- recursiveFindBindingPathsForWhereClause(
- `${newConfigPath}.children[${index}]`,
- value,
+ const childrenPath = getBindingOrConfigPathsForWhereClauseControl(
+ newConfigPath,
+ WhereClauseSubComponent.Children,
+ index,
);
+ recursiveFindBindingPathsForWhereClause(childrenPath, value);
});
} else {
if (actionValue.hasOwnProperty("key")) {
- bindingPaths[
- `${newConfigPath}.key`
- ] = getCorrectEvaluationSubstitutionType(
+ const keyPath = getBindingOrConfigPathsForWhereClauseControl(
+ newConfigPath,
+ WhereClauseSubComponent.Key,
+ undefined,
+ );
+ bindingPaths[keyPath] = getCorrectEvaluationSubstitutionType(
formConfig.evaluationSubstitutionType,
);
}
-
if (actionValue.hasOwnProperty("value")) {
- bindingPaths[
- `${newConfigPath}.value`
- ] = getCorrectEvaluationSubstitutionType(
+ const valuePath = getBindingOrConfigPathsForWhereClauseControl(
+ newConfigPath,
+ WhereClauseSubComponent.Value,
+ undefined,
+ );
+ bindingPaths[valuePath] = getCorrectEvaluationSubstitutionType(
formConfig.evaluationSubstitutionType,
);
}
@@ -104,20 +117,114 @@ export const getBindingPathsOfAction = (
Array.isArray(actionValue.children)
) {
actionValue.children.forEach((value: any, index: number) => {
- recursiveFindBindingPathsForWhereClause(
- `${configPath}.children[${index}]`,
- value,
+ const childrenPath = getBindingOrConfigPathsForWhereClauseControl(
+ configPath,
+ WhereClauseSubComponent.Children,
+ index,
);
+ recursiveFindBindingPathsForWhereClause(childrenPath, value);
+ });
+ }
+ } else if (formConfig.controlType === "PAGINATION") {
+ const limitPath = getBindingOrConfigPathsForPaginationControl(
+ PaginationSubComponent.Offset,
+ configPath,
+ );
+ const offsetPath = getBindingOrConfigPathsForPaginationControl(
+ PaginationSubComponent.Limit,
+ configPath,
+ );
+ bindingPaths[limitPath] = getCorrectEvaluationSubstitutionType(
+ formConfig.evaluationSubstitutionType,
+ );
+ bindingPaths[offsetPath] = getCorrectEvaluationSubstitutionType(
+ formConfig.evaluationSubstitutionType,
+ );
+ } else if (formConfig.controlType === "SORTING") {
+ const actionValue = _.get(action, formConfig.configProperty);
+ if (Array.isArray(actionValue)) {
+ actionValue.forEach((fieldConfig: any, index: number) => {
+ const columnPath = getBindingOrConfigPathsForSortingControl(
+ SortingSubComponent.Column,
+ configPath,
+ index,
+ );
+ bindingPaths[columnPath] = getCorrectEvaluationSubstitutionType(
+ formConfig.evaluationSubstitutionType,
+ );
+ const OrderPath = getBindingOrConfigPathsForSortingControl(
+ SortingSubComponent.Order,
+ configPath,
+ index,
+ );
+ bindingPaths[OrderPath] = getCorrectEvaluationSubstitutionType(
+ formConfig.evaluationSubstitutionType,
+ );
+ });
+ }
+ } else if (formConfig.controlType === "ENTITY_SELECTOR") {
+ if (Array.isArray(formConfig.schema)) {
+ formConfig.schema.forEach((schemaField: any, index: number) => {
+ if (allowedControlTypes.includes(schemaField.controlType)) {
+ const columnPath = getBindingOrConfigPathsForEntitySelectorControl(
+ configPath,
+ index,
+ );
+ bindingPaths[columnPath] = getCorrectEvaluationSubstitutionType(
+ formConfig.evaluationSubstitutionType,
+ );
+ }
});
}
}
}
};
-
formConfig.forEach(recursiveFindBindingPaths);
-
return bindingPaths;
};
+export const getBindingOrConfigPathsForSortingControl = (
+ fieldName: SortingSubComponent.Order | SortingSubComponent.Column,
+ baseConfigProperty: string,
+ index?: number,
+): string => {
+ if (_.isNumber(index)) {
+ return `${baseConfigProperty}[${index}].${fieldName}`;
+ } else {
+ return `${baseConfigProperty}.${fieldName}`;
+ }
+};
+
+export const getBindingOrConfigPathsForPaginationControl = (
+ fieldName: PaginationSubComponent.Limit | PaginationSubComponent.Offset,
+ baseConfigProperty: string,
+): string => {
+ return `${baseConfigProperty}.${fieldName}`;
+};
+
+export const getBindingOrConfigPathsForWhereClauseControl = (
+ configPath: string,
+ fieldName:
+ | WhereClauseSubComponent.Children
+ | WhereClauseSubComponent.Condition
+ | WhereClauseSubComponent.Key
+ | WhereClauseSubComponent.Value,
+ index?: number,
+): string => {
+ if (fieldName === "children" && _.isNumber(index)) {
+ return `${configPath}.${fieldName}[${index}]`;
+ } else if (configPath && fieldName) {
+ return `${configPath}.${fieldName}`;
+ }
+ return "";
+};
+
+export const getBindingOrConfigPathsForEntitySelectorControl = (
+ baseConfigProperty: string,
+ index: number,
+): string => {
+ return `${baseConfigProperty}.column_${index + 1}`;
+};
+
export const getDataTreeActionConfigPath = (propertyPath: string) =>
propertyPath.replace("actionConfiguration.", "config.");
diff --git a/app/client/src/utils/FormControlRegistry.tsx b/app/client/src/utils/FormControlRegistry.tsx
index 64b043dc1dd3..2ccbd39eaed4 100644
--- a/app/client/src/utils/FormControlRegistry.tsx
+++ b/app/client/src/utils/FormControlRegistry.tsx
@@ -49,6 +49,10 @@ import ProjectionSelectorControl, {
ProjectionSelectorControlProps,
} from "components/formControls/ProjectionSelectorControl";
+/**
+ * NOTE: If you are adding a component that uses FormControl
+ * then add logic for creating bindingPaths in recursiveFindBindingPaths() at entities/Action/actionProperties.ts
+ */
class FormControlRegistry {
static registerFormControlBuilders() {
FormControlFactory.registerControlBuilder("INPUT_TEXT", {
|
655548d948bc8212be3506c158329f52350644c1
|
2024-04-18 14:38:17
|
yatinappsmith
|
ci: Fix label Checker (#32770)
| false
|
Fix label Checker (#32770)
|
ci
|
diff --git a/.github/workflows/pr-automation.yml b/.github/workflows/pr-automation.yml
index f29356e2dd48..66dc91fade5f 100644
--- a/.github/workflows/pr-automation.yml
+++ b/.github/workflows/pr-automation.yml
@@ -20,6 +20,11 @@ jobs:
matrix: ${{ steps.checkAll.outputs.matrix }}
steps:
+ # Checkout the code in the current branch in case the workflow is called because of a branch push event
+ - name: Checkout the head commit of the branch
+ if: inputs.pr == 0
+ uses: actions/checkout@v4
+
# Checks for ok-to-test label presence in PR
- name: Check label
run: |
|
b961f6e2e3d1ff876900d043bea9625f1e03b1a4
|
2022-04-05 10:02:52
|
arunvjn
|
fix: Pages tab navigation in preview mode for git apps (#12567)
| false
|
Pages tab navigation in preview mode for git apps (#12567)
|
fix
|
diff --git a/app/client/src/pages/tests/slug.test.tsx b/app/client/src/pages/tests/slug.test.tsx
index d2ff8ef26ecc..35b01d475113 100644
--- a/app/client/src/pages/tests/slug.test.tsx
+++ b/app/client/src/pages/tests/slug.test.tsx
@@ -5,8 +5,12 @@ import {
getRouteBuilderParams,
updateURLFactory,
} from "RouteBuilder";
-import { ReduxActionTypes } from "constants/ReduxActionConstants";
-import { selectURLSlugs } from "selectors/editorSelectors";
+import { Page, ReduxActionTypes } from "constants/ReduxActionConstants";
+import {
+ getCurrentPageId,
+ getPageById,
+ selectURLSlugs,
+} from "selectors/editorSelectors";
import store from "store";
import { render } from "test/testUtils";
import { getUpdatedRoute, isURLDeprecated } from "utils/helpers";
@@ -19,6 +23,9 @@ import {
} from "./mockData";
import ManualUpgrades from "pages/Editor/BottomBar/ManualUpgrades";
import { updateCurrentPage } from "actions/pageActions";
+import { getCurrentApplication } from "selectors/applicationSelectors";
+import { getPageURL } from "utils/AppsmithUtils";
+import { APP_MODE } from "entities/App";
describe("URL slug names", () => {
beforeEach(async () => {
@@ -134,4 +141,25 @@ describe("URL slug names", () => {
}),
).toBe("/my-app/page-605c435a91dea93f0eaf91ba/edit");
});
+
+ it("tests getPageUrl utility method", () => {
+ const state = store.getState();
+ const currentApplication = getCurrentApplication(state);
+ const currentPageId = getCurrentPageId(state);
+ const page = getPageById(currentPageId)(state) as Page;
+
+ const editPageURL = getPageURL(page, APP_MODE.EDIT, currentApplication);
+ const viewPageURL = getPageURL(
+ page,
+ APP_MODE.PUBLISHED,
+ currentApplication,
+ );
+
+ expect(editPageURL).toBe(
+ `/${currentApplication?.slug}/${page.slug}-${page.pageId}/edit`,
+ );
+ expect(viewPageURL).toBe(
+ `/${currentApplication?.slug}/${page.slug}-${page.pageId}`,
+ );
+ });
});
diff --git a/app/client/src/utils/AppsmithUtils.tsx b/app/client/src/utils/AppsmithUtils.tsx
index 37217a6f3787..f09698b1762d 100644
--- a/app/client/src/utils/AppsmithUtils.tsx
+++ b/app/client/src/utils/AppsmithUtils.tsx
@@ -413,11 +413,13 @@ export const getPageURL = (
);
}
- return builderURL({
- applicationSlug: currentApplicationDetails?.slug || PLACEHOLDER_APP_SLUG,
- pageSlug: page.slug || PLACEHOLDER_PAGE_SLUG,
- pageId: page.pageId,
- });
+ return trimQueryString(
+ builderURL({
+ applicationSlug: currentApplicationDetails?.slug || PLACEHOLDER_APP_SLUG,
+ pageSlug: page.slug || PLACEHOLDER_PAGE_SLUG,
+ pageId: page.pageId,
+ }),
+ );
};
/**
|
01e3c57ba4c8247bc4b3821bc129c148fe66ab87
|
2023-11-03 14:08:40
|
Rishabh Rathod
|
chore: fix type errors in EE (#28620)
| false
|
fix type errors in EE (#28620)
|
chore
|
diff --git a/app/client/src/ce/workers/Evaluation/evaluationUtils.ts b/app/client/src/ce/workers/Evaluation/evaluationUtils.ts
index 5c3eceaf0ce2..1078bf6ac729 100644
--- a/app/client/src/ce/workers/Evaluation/evaluationUtils.ts
+++ b/app/client/src/ce/workers/Evaluation/evaluationUtils.ts
@@ -351,7 +351,7 @@ export const addDependantsOfNestedPropertyPaths = (
};
export function isWidget(
- entity: Partial<DataTreeEntity> | WidgetEntityConfig,
+ entity: Partial<DataTreeEntity> | DataTreeEntityConfig,
): entity is WidgetEntity | WidgetEntityConfig {
return (
typeof entity === "object" &&
|
8ec314f2334e3955fcd273f7afd9aa56c9f36ebc
|
2024-12-19 12:18:48
|
Hetu Nandu
|
fix: Wrong pageId used for segment navigation (#38247)
| false
|
Wrong pageId used for segment navigation (#38247)
|
fix
|
diff --git a/app/client/src/pages/Editor/IDE/hooks.ts b/app/client/src/pages/Editor/IDE/hooks.ts
index 25f724ef5f5c..c6cb404b919c 100644
--- a/app/client/src/pages/Editor/IDE/hooks.ts
+++ b/app/client/src/pages/Editor/IDE/hooks.ts
@@ -27,8 +27,6 @@ import { closeJSActionTab } from "actions/jsActionActions";
import { closeQueryActionTab } from "actions/pluginActionActions";
import { getCurrentBasePageId } from "selectors/editorSelectors";
import { getCurrentEntityInfo } from "../utils";
-import { useEditorType } from "ee/hooks";
-import { useParentEntityInfo } from "ee/hooks/datasourceEditorHooks";
export const useCurrentEditorState = () => {
const [selectedSegment, setSelectedSegment] = useState<EditorEntityTab>(
@@ -60,9 +58,7 @@ export const useCurrentEditorState = () => {
export const useSegmentNavigation = (): {
onSegmentChange: (value: string) => void;
} => {
- const editorType = useEditorType(location.pathname);
- const { parentEntityId: baseParentEntityId } =
- useParentEntityInfo(editorType);
+ const basePageId = useSelector(getCurrentBasePageId);
/**
* Callback to handle the segment change
@@ -74,17 +70,17 @@ export const useSegmentNavigation = (): {
const onSegmentChange = (value: string) => {
switch (value) {
case EditorEntityTab.QUERIES:
- history.push(queryListURL({ baseParentEntityId }), {
+ history.push(queryListURL({ basePageId }), {
invokedBy: NavigationMethod.SegmentControl,
});
break;
case EditorEntityTab.JS:
- history.push(jsCollectionListURL({ baseParentEntityId }), {
+ history.push(jsCollectionListURL({ basePageId }), {
invokedBy: NavigationMethod.SegmentControl,
});
break;
case EditorEntityTab.UI:
- history.push(widgetListURL({ baseParentEntityId }), {
+ history.push(widgetListURL({ basePageId }), {
invokedBy: NavigationMethod.SegmentControl,
});
break;
|
e26ea6b8cbdb59940f65c49ab58879f4cb4e5998
|
2023-08-04 15:30:35
|
dependabot[bot]
|
chore(deps-dev): bump tough-cookie from 4.0.0 to 4.1.3 in /app/server/scripts/node (#25220)
| false
|
bump tough-cookie from 4.0.0 to 4.1.3 in /app/server/scripts/node (#25220)
|
chore
|
diff --git a/app/server/scripts/node/package-lock.json b/app/server/scripts/node/package-lock.json
index f913c201ce99..8805f67549e4 100644
--- a/app/server/scripts/node/package-lock.json
+++ b/app/server/scripts/node/package-lock.json
@@ -115,15 +115,21 @@
"dev": true
},
"psl": {
- "version": "1.8.0",
- "resolved": "https://registry.npmjs.org/psl/-/psl-1.8.0.tgz",
- "integrity": "sha512-RIdOzyoavK+hA18OGGWDqUTsCLhtA7IcZ/6NCs4fFJaHBDab+pDDmDIByWFRQJq2Cd7r1OoQxBGKOaztq+hjIQ==",
+ "version": "1.9.0",
+ "resolved": "https://registry.npmjs.org/psl/-/psl-1.9.0.tgz",
+ "integrity": "sha512-E/ZsdU4HLs/68gYzgGTkMicWTLPdAftJLfJFlLUAAKZGkStNU72sZjT66SnMDVOfOWY/YAoiD7Jxa9iHvngcag==",
"dev": true
},
"punycode": {
- "version": "2.1.1",
- "resolved": "https://registry.npmjs.org/punycode/-/punycode-2.1.1.tgz",
- "integrity": "sha512-XRsRjdf+j5ml+y/6GKHPZbrF/8p2Yga0JPtdqTIY2Xe5ohJPD9saDJJLPvp9+NSBprVvevdXZybnj2cv8OEd0A==",
+ "version": "2.3.0",
+ "resolved": "https://registry.npmjs.org/punycode/-/punycode-2.3.0.tgz",
+ "integrity": "sha512-rRV+zQD8tVFys26lAGR9WUuS4iUAngJScM+ZRSKtvl5tKeZ2t5bvdNFdNHBW9FWR4guGHlgmsZ1G7BSm2wTbuA==",
+ "dev": true
+ },
+ "querystringify": {
+ "version": "2.2.0",
+ "resolved": "https://registry.npmjs.org/querystringify/-/querystringify-2.2.0.tgz",
+ "integrity": "sha512-FIqgj2EUvTa7R50u0rGsyTftzjYmv/a3hO345bZNrqabNqjtgiDMgmo4mkUjd+nzU5oF3dClKqFIPUKybUyqoQ==",
"dev": true
},
"readable-stream": {
@@ -159,6 +165,12 @@
"semver": "^5.1.0"
}
},
+ "requires-port": {
+ "version": "1.0.0",
+ "resolved": "https://registry.npmjs.org/requires-port/-/requires-port-1.0.0.tgz",
+ "integrity": "sha512-KigOCHcocU3XODJxsu8i/j8T9tzT4adHiecwORRQ0ZZFcp7ahwXuRU1m+yuO90C5ZUyGeGfocHDI14M3L3yDAQ==",
+ "dev": true
+ },
"resolve-from": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/resolve-from/-/resolve-from-2.0.0.tgz",
@@ -215,22 +227,33 @@
}
},
"tough-cookie": {
- "version": "4.0.0",
- "resolved": "https://registry.npmjs.org/tough-cookie/-/tough-cookie-4.0.0.tgz",
- "integrity": "sha512-tHdtEpQCMrc1YLrMaqXXcj6AxhYi/xgit6mZu1+EDWUn+qhUf8wMQoFIy9NXuq23zAwtcB0t/MjACGR18pcRbg==",
+ "version": "4.1.3",
+ "resolved": "https://registry.npmjs.org/tough-cookie/-/tough-cookie-4.1.3.tgz",
+ "integrity": "sha512-aX/y5pVRkfRnfmuX+OdbSdXvPe6ieKX/G2s7e98f4poJHnqH3281gDPm/metm6E/WRamfx7WC4HUqkWHfQHprw==",
"dev": true,
"requires": {
"psl": "^1.1.33",
"punycode": "^2.1.1",
- "universalify": "^0.1.2"
+ "universalify": "^0.2.0",
+ "url-parse": "^1.5.3"
}
},
"universalify": {
- "version": "0.1.2",
- "resolved": "https://registry.npmjs.org/universalify/-/universalify-0.1.2.tgz",
- "integrity": "sha512-rBJeI5CXAlmy1pV+617WB9J63U6XcazHHF2f2dbJix4XzpUF0RS3Zbj0FGIOCAva5P/d/GBOYaACQ1w+0azUkg==",
+ "version": "0.2.0",
+ "resolved": "https://registry.npmjs.org/universalify/-/universalify-0.2.0.tgz",
+ "integrity": "sha512-CJ1QgKmNg3CwvAv/kOFmtnEN05f0D/cn9QntgNOQlQF9dgvVTHj3t+8JPdjqawCHk7V/KA+fbUqzZ9XWhcqPUg==",
"dev": true
},
+ "url-parse": {
+ "version": "1.5.10",
+ "resolved": "https://registry.npmjs.org/url-parse/-/url-parse-1.5.10.tgz",
+ "integrity": "sha512-WypcfiRhfeUP9vvF0j6rw0J3hrWrw6iZv3+22h6iRMJ/8z1Tj6XfLP4DsUix5MhMPnXpiHDoKyoZ/bdCkwBCiQ==",
+ "dev": true,
+ "requires": {
+ "querystringify": "^2.1.1",
+ "requires-port": "^1.0.0"
+ }
+ },
"util-deprecate": {
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz",
diff --git a/app/server/scripts/node/package.json b/app/server/scripts/node/package.json
index a95d952b2106..0bcfa6c23226 100644
--- a/app/server/scripts/node/package.json
+++ b/app/server/scripts/node/package.json
@@ -14,6 +14,6 @@
"axios-cookiejar-support": "^1.0.0",
"crypto-js": "^4.0.0",
"mongodb": "^3.5.8",
- "tough-cookie": "^4.0.0"
+ "tough-cookie": "^4.1.3"
}
}
|
f65986c3514f085901ff13b2466bf237d63d6769
|
2023-01-27 16:05:00
|
Shrikant Sharat Kandula
|
fix: Use `mongosh` instead of mongo in entrypoint (#20055)
| false
|
Use `mongosh` instead of mongo in entrypoint (#20055)
|
fix
|
diff --git a/Dockerfile b/Dockerfile
index a8381c98cb5c..9ae91eb7df31 100644
--- a/Dockerfile
+++ b/Dockerfile
@@ -65,7 +65,6 @@ COPY ./app/rts/package.json ./app/rts/dist rts/
# Nginx & MongoDB config template - Configuration layer
COPY ./deploy/docker/templates/nginx/* \
- ./deploy/docker/templates/mongo-init.js.sh\
./deploy/docker/templates/docker.env.sh \
templates/
diff --git a/deploy/docker/entrypoint.sh b/deploy/docker/entrypoint.sh
index 6404ac8f2cf2..e1f1f8743491 100755
--- a/deploy/docker/entrypoint.sh
+++ b/deploy/docker/entrypoint.sh
@@ -1,6 +1,7 @@
#!/usr/bin/env bash
set -e
+set -o xtrace
stacks_path=/appsmith-stacks
@@ -153,14 +154,21 @@ init_replica_set() {
echo "Waiting 10s for MongoDB to start"
sleep 10
echo "Creating MongoDB user"
- bash "/opt/appsmith/templates/mongo-init.js.sh" "$APPSMITH_MONGODB_USER" "$APPSMITH_MONGODB_PASSWORD" > "/appsmith-stacks/configuration/mongo-init.js"
- mongo "127.0.0.1/appsmith" /appsmith-stacks/configuration/mongo-init.js
+ mongosh "127.0.0.1/appsmith" --eval "db.createUser({
+ user: '$APPSMITH_MONGODB_USER',
+ pwd: '$APPSMITH_MONGODB_PASSWORD',
+ roles: [{
+ role: 'root',
+ db: 'admin'
+ }, 'readWrite']
+ }
+ )"
echo "Enabling Replica Set"
mongod --dbpath "$MONGO_DB_PATH" --shutdown || true
mongod --fork --port 27017 --dbpath "$MONGO_DB_PATH" --logpath "$MONGO_LOG_PATH" --replSet mr1 --keyFile /mongodb-key --bind_ip localhost
echo "Waiting 10s for MongoDB to start with Replica Set"
sleep 10
- mongo "$APPSMITH_MONGODB_URI" --eval 'rs.initiate()'
+ mongosh "$APPSMITH_MONGODB_URI" --eval 'rs.initiate()'
mongod --dbpath "$MONGO_DB_PATH" --shutdown || true
fi
@@ -168,7 +176,7 @@ init_replica_set() {
# Check mongodb cloud Replica Set
echo "Checking Replica Set of external MongoDB"
- mongo_state="$(mongo --host "$APPSMITH_MONGODB_URI" --quiet --eval "rs.status().ok")"
+ mongo_state="$(mongosh "$APPSMITH_MONGODB_URI" --quiet --eval "rs.status().ok")"
if [[ ${mongo_state: -1} -eq 1 ]]; then
echo "Mongodb cloud Replica Set is enabled"
else
@@ -182,10 +190,10 @@ init_replica_set() {
}
use-mongodb-key() {
- # This is a little weird. We copy the MongoDB key file to `/mongodb-key`, so that we can reliably set its permissions to 600.
- # What affects the reliability of this? When the host machine of this Docker container is Windows, file permissions cannot be set on files in volumes.
- # So the key file should be somewhere inside the container, and not in a volume.
- cp -v "$1" /mongodb-key
+ # This is a little weird. We copy the MongoDB key file to `/mongodb-key`, so that we can reliably set its permissions to 600.
+ # What affects the reliability of this? When the host machine of this Docker container is Windows, file permissions cannot be set on files in volumes.
+ # So the key file should be somewhere inside the container, and not in a volume.
+ cp -v "$1" /mongodb-key
chmod 600 /mongodb-key
}
diff --git a/deploy/docker/templates/mongo-init.js.sh b/deploy/docker/templates/mongo-init.js.sh
deleted file mode 100644
index 42410f62da26..000000000000
--- a/deploy/docker/templates/mongo-init.js.sh
+++ /dev/null
@@ -1,33 +0,0 @@
-#!/bin/bash
-
-set -o nounset
-
-MONGO_ROOT_USER="$1"
-MONGO_ROOT_PASSWORD="$2"
-
-cat <<EOF
-let error = false
-print("**** Going to start Mongo seed ****")
-
-var admin = db.getSiblingDB("admin")
-admin.auth("$MONGO_ROOT_USER", "$MONGO_ROOT_PASSWORD")
-
-let res = [
- db.createUser(
- {
- user: "$MONGO_ROOT_USER",
- pwd: "$MONGO_ROOT_PASSWORD",
- roles: [{
- role: "root",
- db: "admin"
- }, "readWrite"]
- }
- )
-]
-
-printjson(res)
-
-if (error) {
- print('Error occurred while inserting the records')
-}
-EOF
|
0dcef48dc8c9cdaa0f930325e317cf97b2264555
|
2023-07-12 12:12:16
|
Ayangade Adeoluwa
|
feat: activation phase 1 (#25126)
| false
|
activation phase 1 (#25126)
|
feat
|
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 327291e2c0ca..c7ab7ea95269 100644
--- a/app/client/cypress/e2e/Regression/ClientSide/BugTests/ApiBugs_Spec.ts
+++ b/app/client/cypress/e2e/Regression/ClientSide/BugTests/ApiBugs_Spec.ts
@@ -13,8 +13,18 @@ import {
ERROR_ACTION_EXECUTE_FAIL,
createMessage,
} from "../../../../support/Objects/CommonErrorMessages";
+import { featureFlagIntercept } from "../../../../support/Objects/FeatureFlags";
describe("API Bugs", function () {
+ before(() => {
+ featureFlagIntercept(
+ {
+ ab_ds_binding_enabled: false,
+ },
+ false,
+ );
+ 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.RunAPI();
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 5368651420a6..5c0399bb3542 100644
--- a/app/client/cypress/e2e/Regression/ClientSide/BugTests/DatasourceSchema_spec.ts
+++ b/app/client/cypress/e2e/Regression/ClientSide/BugTests/DatasourceSchema_spec.ts
@@ -1,3 +1,4 @@
+import { featureFlagIntercept } from "../../../../support/Objects/FeatureFlags";
import { ObjectsRegistry } from "../../../../support/Objects/Registry";
const agHelper = ObjectsRegistry.AggregateHelper,
@@ -40,4 +41,24 @@ describe("Datasource form related tests", function () {
dataSources.DeleteQuery("Query1");
dataSources.DeleteDatasouceFromWinthinDS(dataSourceName);
});
+
+ it("3. Verify if schema (table and column) exist in query editor and searching works", () => {
+ featureFlagIntercept(
+ {
+ ab_ds_schema_enabled: true,
+ },
+ false,
+ );
+ agHelper.RefreshPage();
+ dataSources.CreateMockDB("Users");
+ dataSources.CreateQueryAfterDSSaved();
+ dataSources.VerifyTableSchemaOnQueryEditor("public.users");
+ ee.ExpandCollapseEntity("public.users");
+ dataSources.VerifyColumnSchemaOnQueryEditor("id");
+ dataSources.FilterAndVerifyDatasourceSchemaBySearch(
+ "gender",
+ true,
+ "column",
+ );
+ });
});
diff --git a/app/client/cypress/e2e/Regression/ClientSide/MobileResponsiveTests/SuggestedWidgets_spec.js b/app/client/cypress/e2e/Regression/ClientSide/MobileResponsiveTests/SuggestedWidgets_spec.js
index a55eea514e94..d485b4aaadc3 100644
--- a/app/client/cypress/e2e/Regression/ClientSide/MobileResponsiveTests/SuggestedWidgets_spec.js
+++ b/app/client/cypress/e2e/Regression/ClientSide/MobileResponsiveTests/SuggestedWidgets_spec.js
@@ -2,12 +2,21 @@ import {
autoLayout,
dataSources,
table,
+ agHelper,
} from "../../../../support/Objects/ObjectsCore";
import { Widgets } from "../../../../support/Pages/DataSources";
+import { featureFlagIntercept } from "../../../../support/Objects/FeatureFlags";
describe("Check Suggested Widgets Feature in auto-layout", function () {
before(() => {
autoLayout.ConvertToAutoLayoutAndVerify(false);
+ featureFlagIntercept(
+ {
+ ab_ds_binding_enabled: true,
+ },
+ false,
+ );
+ agHelper.RefreshPage();
});
it("1. Suggested widget", () => {
diff --git a/app/client/cypress/e2e/Regression/ClientSide/Widgets/Button/Button_onClickAction_spec.js b/app/client/cypress/e2e/Regression/ClientSide/Widgets/Button/Button_onClickAction_spec.js
index c18344cbe727..0d92b2f7cb76 100644
--- a/app/client/cypress/e2e/Regression/ClientSide/Widgets/Button/Button_onClickAction_spec.js
+++ b/app/client/cypress/e2e/Regression/ClientSide/Widgets/Button/Button_onClickAction_spec.js
@@ -38,7 +38,6 @@ describe("Button Widget Functionality", function () {
);
cy.SaveAndRunAPI();
- // Going to HomePage where the button widget is located and opening it's property pane.
_.entityExplorer.ExpandCollapseEntity("Widgets");
_.entityExplorer.ExpandCollapseEntity("Container3");
_.entityExplorer.SelectEntityByName("Button1");
@@ -69,8 +68,9 @@ describe("Button Widget Functionality", function () {
// Creating a mock query
// cy.CreateMockQuery("Query1");
_.dataSources.CreateDataSource("Postgres");
- _.entityExplorer.ActionTemplateMenuByEntityName("public.film", "SELECT");
- // Going to HomePage where the button widget is located and opeing it's property pane.
+ _.dataSources.CreateQueryAfterDSSaved(
+ `SELECT * FROM public."film" LIMIT 10;`,
+ );
_.entityExplorer.ExpandCollapseEntity("Container3");
_.entityExplorer.SelectEntityByName("Button1");
diff --git a/app/client/cypress/e2e/Regression/ServerSide/QueryPane/S3_2_spec.js b/app/client/cypress/e2e/Regression/ServerSide/QueryPane/S3_2_spec.js
index 1b80196a9f7e..a61205d92ee6 100644
--- a/app/client/cypress/e2e/Regression/ServerSide/QueryPane/S3_2_spec.js
+++ b/app/client/cypress/e2e/Regression/ServerSide/QueryPane/S3_2_spec.js
@@ -222,12 +222,6 @@ describe("Validate CRUD queries for Amazon S3 along with UI flow verifications",
_.entityExplorer.SelectEntityByName("Table1", "Widgets");
_.agHelper.GetNClick(_.propPane._deleteWidget);
- _.entityExplorer.SelectEntityByName($queryName, "Queries/JS");
- cy.xpath(queryLocators.suggestedWidgetText).click().wait(1000);
- cy.get(commonlocators.textWidget).validateWidgetExists();
- _.entityExplorer.SelectEntityByName("Text1", "Widgets");
- _.agHelper.GetNClick(_.propPane._deleteWidget);
-
_.entityExplorer.SelectEntityByName($queryName, "Queries/JS");
cy.deleteQueryUsingContext(); //exeute actions & 200 response is verified in this method
});
diff --git a/app/client/cypress/e2e/Sanity/Datasources/MsSQL_Basic_Spec.ts b/app/client/cypress/e2e/Sanity/Datasources/MsSQL_Basic_Spec.ts
index 895d1bad4e07..a6d10560f464 100644
--- a/app/client/cypress/e2e/Sanity/Datasources/MsSQL_Basic_Spec.ts
+++ b/app/client/cypress/e2e/Sanity/Datasources/MsSQL_Basic_Spec.ts
@@ -1,3 +1,4 @@
+import { featureFlagIntercept } from "../../../support/Objects/FeatureFlags";
import {
agHelper,
assertHelper,
@@ -87,6 +88,13 @@ describe("Validate MsSQL connection & basic querying with UI flows", () => {
dataSources.RunQuery();
});
//agHelper.ActionContextMenuWithInPane("Delete"); Since next case can continue in same template
+ featureFlagIntercept(
+ {
+ ab_ds_binding_enabled: false,
+ },
+ false,
+ );
+ agHelper.RefreshPage();
});
it("1. Validate simple queries - Show all existing tables, Describe table & verify query responses", () => {
diff --git a/app/client/cypress/support/Pages/DataSources.ts b/app/client/cypress/support/Pages/DataSources.ts
index 8661b8b33ee0..d5d413853cfd 100644
--- a/app/client/cypress/support/Pages/DataSources.ts
+++ b/app/client/cypress/support/Pages/DataSources.ts
@@ -231,6 +231,10 @@ export class DataSources {
_bodyCodeMirror = "//div[contains(@class, 't--actionConfiguration.body')]";
private _reconnectModalDSToolTip = ".t--ds-list .t--ds-list-title";
private _reconnectModalDSToopTipIcon = ".t--ds-list .ads-v2-icon";
+ private _datasourceTableSchemaInQueryEditor =
+ ".datasourceStructure-query-editor";
+ private _datasourceColumnSchemaInQueryEditor = ".t--datasource-column";
+ private _datasourceStructureSearchInput = ".datasourceStructure-search input";
public AssertDSEditViewMode(mode: "Edit" | "View") {
if (mode == "Edit") this.agHelper.AssertElementAbsence(this._editButton);
@@ -1198,6 +1202,35 @@ export class DataSources {
});
}
+ public VerifyTableSchemaOnQueryEditor(schema: string) {
+ this.agHelper
+ .GetElement(this._datasourceTableSchemaInQueryEditor)
+ .contains(schema);
+ }
+
+ public VerifyColumnSchemaOnQueryEditor(schema: string, index = 0) {
+ this.agHelper
+ .GetElement(this._datasourceColumnSchemaInQueryEditor)
+ .eq(index)
+ .contains(schema);
+ }
+
+ public FilterAndVerifyDatasourceSchemaBySearch(
+ search: string,
+ verifySearch = false,
+ filterBy: "table" | "column" = "column",
+ ) {
+ this.agHelper.TypeText(this._datasourceStructureSearchInput, search);
+
+ if (verifySearch) {
+ if (filterBy === "column") {
+ this.VerifyColumnSchemaOnQueryEditor(search);
+ } else {
+ this.VerifyTableSchemaOnQueryEditor(search);
+ }
+ }
+ }
+
public SaveDSFromDialog(save = true) {
this.agHelper.GoBack();
this.agHelper.AssertElementVisible(this._datasourceModalDoNotSave);
diff --git a/app/client/src/actions/datasourceActions.ts b/app/client/src/actions/datasourceActions.ts
index beafccdd1559..5607a12d73a3 100644
--- a/app/client/src/actions/datasourceActions.ts
+++ b/app/client/src/actions/datasourceActions.ts
@@ -14,6 +14,7 @@ import type { PluginType } from "entities/Action";
import type { executeDatasourceQueryRequest } from "api/DatasourcesApi";
import type { ResponseMeta } from "api/ApiResponses";
import { TEMP_DATASOURCE_ID } from "constants/Datasource";
+import type { DatasourceStructureContext } from "pages/Editor/Explorer/Datasources/DatasourceStructureContainer";
export const createDatasourceFromForm = (
payload: CreateDatasourceConfig & Datasource,
@@ -106,12 +107,17 @@ export const redirectAuthorizationCode = (
};
};
-export const fetchDatasourceStructure = (id: string, ignoreCache?: boolean) => {
+export const fetchDatasourceStructure = (
+ id: string,
+ ignoreCache?: boolean,
+ schemaFetchContext?: DatasourceStructureContext,
+) => {
return {
type: ReduxActionTypes.FETCH_DATASOURCE_STRUCTURE_INIT,
payload: {
id,
ignoreCache,
+ schemaFetchContext,
},
};
};
@@ -160,11 +166,15 @@ export const expandDatasourceEntity = (id: string) => {
};
};
-export const refreshDatasourceStructure = (id: string) => {
+export const refreshDatasourceStructure = (
+ id: string,
+ schemaRefreshContext?: DatasourceStructureContext,
+) => {
return {
type: ReduxActionTypes.REFRESH_DATASOURCE_STRUCTURE_INIT,
payload: {
id,
+ schemaRefreshContext,
},
};
};
diff --git a/app/client/src/ce/AppRouter.tsx b/app/client/src/ce/AppRouter.tsx
index 4c08885045f7..879dba287b16 100644
--- a/app/client/src/ce/AppRouter.tsx
+++ b/app/client/src/ce/AppRouter.tsx
@@ -62,6 +62,7 @@ import {
import useBrandingTheme from "utils/hooks/useBrandingTheme";
import RouteChangeListener from "RouteChangeListener";
import { initCurrentPage } from "../actions/initActions";
+import Walkthrough from "components/featureWalkthrough";
export const SentryRoute = Sentry.withSentryRouting(Route);
@@ -175,10 +176,10 @@ function AppRouter(props: {
<ErrorPage code={props.safeCrashCode} />
</>
) : (
- <>
+ <Walkthrough>
<AppHeader />
<Routes />
- </>
+ </Walkthrough>
)}
</Suspense>
</Router>
diff --git a/app/client/src/ce/constants/messages.ts b/app/client/src/ce/constants/messages.ts
index ec221cfe1503..7cc4ef0cf2de 100644
--- a/app/client/src/ce/constants/messages.ts
+++ b/app/client/src/ce/constants/messages.ts
@@ -647,6 +647,9 @@ export const BULK_WIDGET_REMOVED = (widgetName: string) =>
export const BULK_WIDGET_ADDED = (widgetName: string) =>
`${widgetName} widgets are added back`;
+export const ACTION_CONFIGURATION_CHANGED = (name: string) =>
+ `${name}'s configuration has changed`;
+
// Generate page from DB Messages
export const UNSUPPORTED_PLUGIN_DIALOG_TITLE = () =>
@@ -691,10 +694,37 @@ export const ADD_NEW_WIDGET = () => "Add new widget";
export const SUGGESTED_WIDGETS = () => "Suggested widgets";
export const SUGGESTED_WIDGET_TOOLTIP = () => "Add to canvas";
export const WELCOME_TOUR_STICKY_BUTTON_TEXT = () => "Next mission";
+export const BINDING_SECTION_LABEL = () => "Bindings";
+export const ADD_NEW_WIDGET_SUB_HEADING = () =>
+ "Select how you want to display data.";
+export const CONNECT_EXISTING_WIDGET_LABEL = () => "Select a Widget";
+export const CONNECT_EXISTING_WIDGET_SUB_HEADING = () =>
+ "Replace the data of an existing widget";
+export const NO_EXISTING_WIDGETS = () => "Display data in a new widget";
+export const BINDING_WALKTHROUGH_TITLE = () => "Display your data";
+export const BINDING_WALKTHROUGH_DESC = () =>
+ "You can replace data of an existing widget of your page or you can select a new widget.";
+export const BINDINGS_DISABLED_TOOLTIP = () =>
+ "You can display data when you have a successful response to your query";
// Data Sources pane
export const EMPTY_ACTIVE_DATA_SOURCES = () => "No active datasources found.";
+
+// Datasource structure
+
export const SCHEMA_NOT_AVAILABLE = () => "Schema not available";
+export const TABLE_OR_COLUMN_NOT_FOUND = () => "Table or column not found.";
+export const DATASOURCE_STRUCTURE_INPUT_PLACEHOLDER_TEXT = () =>
+ "Search for table or attribute";
+export const SCHEMA_LABEL = () => "Schema";
+export const STRUCTURE_NOT_FETCHED = () =>
+ "We could not fetch the schema of the database.";
+export const TEST_DATASOURCE_AND_FIX_ERRORS = () =>
+ "Test the datasource and fix the errors.";
+export const LOADING_SCHEMA = () => "Loading schema...";
+export const SCHEMA_WALKTHROUGH_TITLE = () => "Query data fast";
+export const SCHEMA_WALKTHROUGH_DESC = () =>
+ "Select a template from a database table to quickly create your first query. ";
// Git sync
export const CONNECTED_TO_GIT = () => "Connected to Git";
diff --git a/app/client/src/ce/entities/FeatureFlag.ts b/app/client/src/ce/entities/FeatureFlag.ts
index 5183ca780ad7..258f3c2e83fe 100644
--- a/app/client/src/ce/entities/FeatureFlag.ts
+++ b/app/client/src/ce/entities/FeatureFlag.ts
@@ -1,3 +1,4 @@
+// Please follow naming convention : https://www.notion.so/appsmith/Using-Feature-Flags-in-Appsmith-d362fe7acc7d4ef0aa12e1f5f9b83b5f?pvs=4#f6d4242e56284e84af25cadef71b7aeb to create feature flags.
export const FEATURE_FLAG = {
TEST_FLAG: "TEST_FLAG",
release_datasource_environments_enabled:
@@ -8,6 +9,8 @@ export const FEATURE_FLAG = {
ask_ai_js: "ask_ai_js",
APP_EMBED_VIEW_HIDE_SHARE_SETTINGS_VISIBILITY:
"APP_EMBED_VIEW_HIDE_SHARE_SETTINGS_VISIBILITY",
+ ab_ds_schema_enabled: "ab_ds_schema_enabled",
+ ab_ds_binding_enabled: "ab_ds_binding_enabled",
} as const;
export type FeatureFlag = keyof typeof FEATURE_FLAG;
@@ -22,4 +25,11 @@ export const DEFAULT_FEATURE_FLAG_VALUE: FeatureFlags = {
ask_ai_js: false,
ask_ai_sql: false,
APP_EMBED_VIEW_HIDE_SHARE_SETTINGS_VISIBILITY: false,
+ ab_ds_schema_enabled: false,
+ ab_ds_binding_enabled: false,
+};
+
+export const AB_TESTING_EVENT_KEYS = {
+ abTestingFlagLabel: "abTestingFlagLabel",
+ abTestingFlagValue: "abTestingFlagValue",
};
diff --git a/app/client/src/components/editorComponents/ActionRightPane/SuggestedWidgets.tsx b/app/client/src/components/editorComponents/ActionRightPane/SuggestedWidgets.tsx
index 33d3e532acee..0e7264436a53 100644
--- a/app/client/src/components/editorComponents/ActionRightPane/SuggestedWidgets.tsx
+++ b/app/client/src/components/editorComponents/ActionRightPane/SuggestedWidgets.tsx
@@ -1,4 +1,4 @@
-import React, { memo } from "react";
+import React, { memo, useContext, useEffect } from "react";
import { useDispatch, useSelector } from "react-redux";
import styled from "styled-components";
import { generateReactKey } from "utils/generators";
@@ -8,9 +8,16 @@ import { addSuggestedWidget } from "actions/widgetActions";
import AnalyticsUtil from "utils/AnalyticsUtil";
import {
ADD_NEW_WIDGET,
+ ADD_NEW_WIDGET_SUB_HEADING,
+ BINDING_SECTION_LABEL,
+ CONNECT_EXISTING_WIDGET_LABEL,
+ CONNECT_EXISTING_WIDGET_SUB_HEADING,
createMessage,
+ NO_EXISTING_WIDGETS,
SUGGESTED_WIDGETS,
SUGGESTED_WIDGET_TOOLTIP,
+ BINDING_WALKTHROUGH_TITLE,
+ BINDING_WALKTHROUGH_DESC,
} from "@appsmith/constants/messages";
import type { SuggestedWidget } from "api/ActionAPI";
@@ -20,8 +27,39 @@ import { getNextWidgetName } from "sagas/WidgetOperationUtils";
import { ASSETS_CDN_URL } from "constants/ThirdPartyConstants";
import { getAssetUrl } from "@appsmith/utils/airgapHelpers";
import { Tooltip } from "design-system";
+import type { TextKind } from "design-system";
+import { Text } from "design-system";
+import {
+ AB_TESTING_EVENT_KEYS,
+ FEATURE_FLAG,
+} from "@appsmith/entities/FeatureFlag";
+import { selectFeatureFlagCheck } from "selectors/featureFlagsSelectors";
+import type { FlattenedWidgetProps } from "reducers/entityReducers/canvasWidgetsStructureReducer";
+import { useParams } from "react-router";
+import { getCurrentApplicationId } from "selectors/editorSelectors";
+import { bindDataOnCanvas } from "actions/pluginActionActions";
+import { bindDataToWidget } from "actions/propertyPaneActions";
+import tableWidgetIconSvg from "../../../widgets/TableWidgetV2/icon.svg";
+import selectWidgetIconSvg from "../../../widgets/SelectWidget/icon.svg";
+import chartWidgetIconSvg from "../../../widgets/ChartWidget/icon.svg";
+import inputWidgetIconSvg from "../../../widgets/InputWidgetV2/icon.svg";
+import textWidgetIconSvg from "../../../widgets/TextWidget/icon.svg";
+import listWidgetIconSvg from "../../../widgets/ListWidget/icon.svg";
+import WalkthroughContext from "components/featureWalkthrough/walkthroughContext";
+import {
+ getFeatureFlagShownStatus,
+ isUserSignedUpFlagSet,
+ setFeatureFlagShownStatus,
+} from "utils/storage";
+import { getCurrentUser } from "selectors/usersSelectors";
+
+const BINDING_GUIDE_GIF = `${ASSETS_CDN_URL}/binding.gif`;
+
+const BINDING_SECTION_ID = "t--api-right-pane-binding";
const WidgetList = styled.div`
+ height: 100%;
+ overflow: auto;
${getTypographyByKey("p1")}
margin-left: ${(props) => props.theme.spaces[2] + 1}px;
@@ -33,6 +71,8 @@ const WidgetList = styled.div`
.image-wrapper {
position: relative;
margin-top: ${(props) => props.theme.spaces[1]}px;
+ display: flex;
+ flex-direction: column;
}
.widget:hover {
@@ -42,6 +82,76 @@ const WidgetList = styled.div`
.widget:not(:first-child) {
margin-top: 24px;
}
+
+ &.spacing {
+ .widget:not(:first-child) {
+ margin-top: 16px;
+ }
+ }
+`;
+
+const ExistingWidgetList = styled.div`
+ display: flex;
+ flex-wrap: wrap;
+
+ .image-wrapper {
+ position: relative;
+ display: flex;
+ flex-direction: column;
+ width: 110px;
+ margin: 4px;
+ border: 1px solid var(--ads-v2-color-gray-300);
+ border-radius: var(--ads-v2-border-radius);
+
+ &:hover {
+ border: 1px solid var(--ads-v2-color-gray-600);
+ }
+ }
+
+ img {
+ height: 54px;
+ }
+
+ .widget:hover {
+ cursor: pointer;
+ }
+`;
+
+const ItemWrapper = styled.div`
+ display: flex;
+ align-items: center;
+ padding: 4px;
+
+ .widget-name {
+ padding-left: 8px;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ }
+
+ img {
+ height: 16px;
+ width: 16px;
+ }
+`;
+
+const SubSection = styled.div`
+ margin-bottom: ${(props) => props.theme.spaces[7]}px;
+ overflow-y: scroll;
+ height: 100%;
+`;
+
+const HeadingWrapper = styled.div`
+ display: flex;
+ flex-direction: column;
+ margin-left: ${(props) => props.theme.spaces[2] + 1}px;
+ padding-bottom: 12px;
+`;
+
+const SuggestedWidgetContainer = styled.div`
+ display: flex;
+ flex-direction: column;
+ flex-grow: 1;
+ overflow: hidden;
`;
type WidgetBindingInfo = {
@@ -49,6 +159,8 @@ type WidgetBindingInfo = {
propertyName: string;
widgetName: string;
image?: string;
+ icon?: string;
+ existingImage?: string;
};
export const WIDGET_DATA_FIELD_MAP: Record<string, WidgetBindingInfo> = {
@@ -57,42 +169,56 @@ export const WIDGET_DATA_FIELD_MAP: Record<string, WidgetBindingInfo> = {
propertyName: "listData",
widgetName: "List",
image: `${ASSETS_CDN_URL}/widgetSuggestion/list.svg`,
+ existingImage: `${ASSETS_CDN_URL}/widgetSuggestion/list.svg`,
+ icon: listWidgetIconSvg,
},
TABLE_WIDGET: {
label: "tabledata",
propertyName: "tableData",
widgetName: "Table",
image: `${ASSETS_CDN_URL}/widgetSuggestion/table.svg`,
+ existingImage: `${ASSETS_CDN_URL}/widgetSuggestion/existing_table.svg`,
+ icon: tableWidgetIconSvg,
},
TABLE_WIDGET_V2: {
label: "tabledata",
propertyName: "tableData",
widgetName: "Table",
image: `${ASSETS_CDN_URL}/widgetSuggestion/table.svg`,
+ existingImage: `${ASSETS_CDN_URL}/widgetSuggestion/existing_table.svg`,
+ icon: tableWidgetIconSvg,
},
CHART_WIDGET: {
label: "chart-series-data-control",
propertyName: "chartData",
widgetName: "Chart",
image: `${ASSETS_CDN_URL}/widgetSuggestion/chart.svg`,
+ existingImage: `${ASSETS_CDN_URL}/widgetSuggestion/chart.svg`,
+ icon: chartWidgetIconSvg,
},
SELECT_WIDGET: {
label: "options",
propertyName: "options",
widgetName: "Select",
image: `${ASSETS_CDN_URL}/widgetSuggestion/dropdown.svg`,
+ existingImage: `${ASSETS_CDN_URL}/widgetSuggestion/dropdown.svg`,
+ icon: selectWidgetIconSvg,
},
TEXT_WIDGET: {
label: "text",
propertyName: "text",
widgetName: "Text",
image: `${ASSETS_CDN_URL}/widgetSuggestion/text.svg`,
+ existingImage: `${ASSETS_CDN_URL}/widgetSuggestion/text.svg`,
+ icon: textWidgetIconSvg,
},
INPUT_WIDGET_V2: {
label: "text",
propertyName: "defaultText",
widgetName: "Input",
image: `${ASSETS_CDN_URL}/widgetSuggestion/input.svg`,
+ existingImage: `${ASSETS_CDN_URL}/widgetSuggestion/input.svg`,
+ icon: inputWidgetIconSvg,
},
};
@@ -179,10 +305,66 @@ type SuggestedWidgetProps = {
hasWidgets: boolean;
};
+function renderHeading(heading: string, subHeading: string) {
+ return (
+ <HeadingWrapper>
+ <Text kind="heading-xs">{heading}</Text>
+ <Text kind="body-s">{subHeading}</Text>
+ </HeadingWrapper>
+ );
+}
+
+function renderWidgetItem(
+ icon: string | undefined,
+ name: string | undefined,
+ textKind: TextKind,
+) {
+ return (
+ <ItemWrapper>
+ {icon && <img alt="widget-icon" src={icon} />}
+ <Text className="widget-name" kind={textKind}>
+ {name}
+ </Text>
+ </ItemWrapper>
+ );
+}
+
+function renderWidgetImage(image: string | undefined) {
+ if (!!image) {
+ return <img alt="widget-info-image" src={getAssetUrl(image)} />;
+ }
+ return null;
+}
+
function SuggestedWidgets(props: SuggestedWidgetProps) {
const dispatch = useDispatch();
const dataTree = useSelector(getDataTree);
const canvasWidgets = useSelector(getWidgets);
+ const applicationId = useSelector(getCurrentApplicationId);
+ const user = useSelector(getCurrentUser);
+ const {
+ isOpened: isWalkthroughOpened,
+ popFeature,
+ pushFeature,
+ } = useContext(WalkthroughContext) || {};
+
+ // A/B feature flag for query binding.
+ const isEnabledForQueryBinding = useSelector((state) =>
+ selectFeatureFlagCheck(state, FEATURE_FLAG.ab_ds_binding_enabled),
+ );
+
+ const params = useParams<{
+ pageId: string;
+ apiId?: string;
+ queryId?: string;
+ }>();
+
+ const closeWalkthrough = async () => {
+ if (isWalkthroughOpened) {
+ popFeature && popFeature();
+ await setFeatureFlagShownStatus(FEATURE_FLAG.ab_ds_binding_enabled, true);
+ }
+ };
const addWidget = (
suggestedWidget: SuggestedWidget,
@@ -202,45 +384,216 @@ function SuggestedWidgets(props: SuggestedWidgetProps) {
AnalyticsUtil.logEvent("SUGGESTED_WIDGET_CLICK", {
widget: suggestedWidget.type,
+ [AB_TESTING_EVENT_KEYS.abTestingFlagLabel]:
+ FEATURE_FLAG.ab_ds_binding_enabled,
+ [AB_TESTING_EVENT_KEYS.abTestingFlagValue]: isEnabledForQueryBinding,
+ isWalkthroughOpened,
});
+ closeWalkthrough();
dispatch(addSuggestedWidget(payload));
};
- const label = props.hasWidgets
+ const handleBindData = (widgetId: string) => {
+ dispatch(
+ bindDataOnCanvas({
+ queryId: (params.apiId || params.queryId) as string,
+ applicationId: applicationId as string,
+ pageId: params.pageId,
+ }),
+ );
+
+ closeWalkthrough();
+ dispatch(
+ bindDataToWidget({
+ widgetId: widgetId,
+ }),
+ );
+ };
+
+ const isTableWidgetPresentOnCanvas = () => {
+ const canvasWidgetLength = Object.keys(canvasWidgets).length;
+ return (
+ // widgetKey == 0 condition represents MainContainer
+ canvasWidgetLength > 1 &&
+ Object.keys(canvasWidgets).some((widgetKey: string) => {
+ return (
+ canvasWidgets[widgetKey]?.type === "TABLE_WIDGET_V2" &&
+ parseInt(widgetKey, 0) !== 0
+ );
+ })
+ );
+ };
+
+ const labelOld = props.hasWidgets
? createMessage(ADD_NEW_WIDGET)
: createMessage(SUGGESTED_WIDGETS);
+ const labelNew = createMessage(BINDING_SECTION_LABEL);
+ const addNewWidgetLabel = createMessage(ADD_NEW_WIDGET);
+ const addNewWidgetSubLabel = createMessage(ADD_NEW_WIDGET_SUB_HEADING);
+ const connectExistingWidgetLabel = createMessage(
+ CONNECT_EXISTING_WIDGET_LABEL,
+ );
+ const connectExistingWidgetSubLabel = createMessage(
+ CONNECT_EXISTING_WIDGET_SUB_HEADING,
+ );
+ const isWidgetsPresentOnCanvas = Object.keys(canvasWidgets).length > 0;
+
+ const checkAndShowWalkthrough = async () => {
+ const isFeatureWalkthroughShown = await getFeatureFlagShownStatus(
+ FEATURE_FLAG.ab_ds_binding_enabled,
+ );
+
+ const isNewUser = user && (await isUserSignedUpFlagSet(user.email));
+ // Adding walkthrough tutorial
+ isNewUser &&
+ !isFeatureWalkthroughShown &&
+ pushFeature &&
+ pushFeature({
+ targetId: BINDING_SECTION_ID,
+ onDismiss: async () => {
+ AnalyticsUtil.logEvent("WALKTHROUGH_DISMISSED", {
+ [AB_TESTING_EVENT_KEYS.abTestingFlagLabel]:
+ FEATURE_FLAG.ab_ds_binding_enabled,
+ [AB_TESTING_EVENT_KEYS.abTestingFlagValue]:
+ isEnabledForQueryBinding,
+ });
+ await setFeatureFlagShownStatus(
+ FEATURE_FLAG.ab_ds_binding_enabled,
+ true,
+ );
+ },
+ details: {
+ title: createMessage(BINDING_WALKTHROUGH_TITLE),
+ description: createMessage(BINDING_WALKTHROUGH_DESC),
+ imageURL: BINDING_GUIDE_GIF,
+ },
+ offset: {
+ position: "left",
+ left: -40,
+ highlightPad: 5,
+ indicatorLeft: -3,
+ },
+ eventParams: {
+ [AB_TESTING_EVENT_KEYS.abTestingFlagLabel]:
+ FEATURE_FLAG.ab_ds_binding_enabled,
+ [AB_TESTING_EVENT_KEYS.abTestingFlagValue]: isEnabledForQueryBinding,
+ },
+ });
+ };
+
+ useEffect(() => {
+ if (isEnabledForQueryBinding) checkAndShowWalkthrough();
+ }, [isEnabledForQueryBinding]);
return (
- <Collapsible label={label}>
- <WidgetList>
- {props.suggestedWidgets.map((suggestedWidget) => {
- const widgetInfo: WidgetBindingInfo | undefined =
- WIDGET_DATA_FIELD_MAP[suggestedWidget.type];
-
- if (!widgetInfo) return null;
-
- return (
- <div
- className={`widget t--suggested-widget-${suggestedWidget.type}`}
- key={suggestedWidget.type}
- onClick={() => addWidget(suggestedWidget, widgetInfo)}
- >
- <Tooltip content={createMessage(SUGGESTED_WIDGET_TOOLTIP)}>
- <div className="image-wrapper">
- {widgetInfo.image && (
- <img
- alt="widget-info-image"
- src={getAssetUrl(widgetInfo.image)}
- />
- )}
+ <SuggestedWidgetContainer id={BINDING_SECTION_ID}>
+ {!!isEnabledForQueryBinding ? (
+ <Collapsible label={labelNew}>
+ {isTableWidgetPresentOnCanvas() && (
+ <SubSection>
+ {renderHeading(
+ connectExistingWidgetLabel,
+ connectExistingWidgetSubLabel,
+ )}
+ {!isWidgetsPresentOnCanvas && (
+ <Text kind="body-s">{createMessage(NO_EXISTING_WIDGETS)}</Text>
+ )}
+
+ {/* Table Widget condition is added temporarily as connect to existing
+ functionality is currently working only for Table Widget,
+ in future we want to support it for all widgets */}
+ {
+ <ExistingWidgetList>
+ {Object.keys(canvasWidgets).map((widgetKey) => {
+ const widget: FlattenedWidgetProps | undefined =
+ canvasWidgets[widgetKey];
+ const widgetInfo: WidgetBindingInfo | undefined =
+ WIDGET_DATA_FIELD_MAP[widget.type];
+
+ if (!widgetInfo || widget?.type !== "TABLE_WIDGET_V2")
+ return null;
+
+ return (
+ <div
+ className={`widget t--suggested-widget-${widget.type}`}
+ key={widget.type + widget.widgetId}
+ onClick={() => handleBindData(widgetKey)}
+ >
+ <Tooltip
+ content={createMessage(SUGGESTED_WIDGET_TOOLTIP)}
+ >
+ <div className="image-wrapper">
+ {renderWidgetImage(widgetInfo.existingImage)}
+ {renderWidgetItem(
+ widgetInfo.icon,
+ widget.widgetName,
+ "body-s",
+ )}
+ </div>
+ </Tooltip>
+ </div>
+ );
+ })}
+ </ExistingWidgetList>
+ }
+ </SubSection>
+ )}
+ <SubSection>
+ {renderHeading(addNewWidgetLabel, addNewWidgetSubLabel)}
+ <WidgetList className="spacing">
+ {props.suggestedWidgets.map((suggestedWidget) => {
+ const widgetInfo: WidgetBindingInfo | undefined =
+ WIDGET_DATA_FIELD_MAP[suggestedWidget.type];
+
+ if (!widgetInfo) return null;
+
+ return (
+ <div
+ className={`widget t--suggested-widget-${suggestedWidget.type}`}
+ key={suggestedWidget.type}
+ onClick={() => addWidget(suggestedWidget, widgetInfo)}
+ >
+ <Tooltip content={createMessage(SUGGESTED_WIDGET_TOOLTIP)}>
+ {renderWidgetItem(
+ widgetInfo.icon,
+ widgetInfo.widgetName,
+ "body-m",
+ )}
+ </Tooltip>
+ </div>
+ );
+ })}
+ </WidgetList>
+ </SubSection>
+ </Collapsible>
+ ) : (
+ <Collapsible label={labelOld}>
+ <WidgetList>
+ {props.suggestedWidgets.map((suggestedWidget) => {
+ const widgetInfo: WidgetBindingInfo | undefined =
+ WIDGET_DATA_FIELD_MAP[suggestedWidget.type];
+
+ if (!widgetInfo) return null;
+
+ return (
+ <div
+ className={`widget t--suggested-widget-${suggestedWidget.type}`}
+ key={suggestedWidget.type}
+ onClick={() => addWidget(suggestedWidget, widgetInfo)}
+ >
+ <Tooltip content={createMessage(SUGGESTED_WIDGET_TOOLTIP)}>
+ <div className="image-wrapper">
+ {renderWidgetImage(widgetInfo.image)}
+ </div>
+ </Tooltip>
</div>
- </Tooltip>
- </div>
- );
- })}
- </WidgetList>
- </Collapsible>
+ );
+ })}
+ </WidgetList>
+ </Collapsible>
+ )}
+ </SuggestedWidgetContainer>
);
}
diff --git a/app/client/src/components/editorComponents/ActionRightPane/index.tsx b/app/client/src/components/editorComponents/ActionRightPane/index.tsx
index 619f98415b6c..561befe2141d 100644
--- a/app/client/src/components/editorComponents/ActionRightPane/index.tsx
+++ b/app/client/src/components/editorComponents/ActionRightPane/index.tsx
@@ -1,8 +1,8 @@
-import React, { useMemo } from "react";
+import React, { useContext, useMemo } from "react";
import styled from "styled-components";
import { Collapse, Classes as BPClasses } from "@blueprintjs/core";
import { Classes, getTypographyByKey } from "design-system-old";
-import { Button, Icon, Link } from "design-system";
+import { Button, Divider, Icon, Link, Text } from "design-system";
import { useState } from "react";
import Connections from "./Connections";
import SuggestedWidgets from "./SuggestedWidgets";
@@ -17,8 +17,12 @@ import type { AppState } from "@appsmith/reducers";
import { getDependenciesFromInverseDependencies } from "../Debugger/helpers";
import {
BACK_TO_CANVAS,
+ BINDINGS_DISABLED_TOOLTIP,
+ BINDING_SECTION_LABEL,
createMessage,
NO_CONNECTIONS,
+ SCHEMA_WALKTHROUGH_DESC,
+ SCHEMA_WALKTHROUGH_TITLE,
} from "@appsmith/constants/messages";
import type {
SuggestedWidget,
@@ -31,16 +35,39 @@ import {
} from "selectors/editorSelectors";
import { builderURL } from "RouteBuilder";
import { hasManagePagePermission } from "@appsmith/utils/permissionHelpers";
+import DatasourceStructureHeader from "pages/Editor/Explorer/Datasources/DatasourceStructureHeader";
+import { DatasourceStructureContainer as DataStructureList } from "pages/Editor/Explorer/Datasources/DatasourceStructureContainer";
+import { DatasourceStructureContext } from "pages/Editor/Explorer/Datasources/DatasourceStructureContainer";
+import { selectFeatureFlagCheck } from "selectors/featureFlagsSelectors";
+import {
+ AB_TESTING_EVENT_KEYS,
+ FEATURE_FLAG,
+} from "@appsmith/entities/FeatureFlag";
+import {
+ getDatasourceStructureById,
+ getPluginDatasourceComponentFromId,
+ getPluginNameFromId,
+} from "selectors/entitiesSelector";
+import { DatasourceComponentTypes } from "api/PluginApi";
+import { fetchDatasourceStructure } from "actions/datasourceActions";
+import WalkthroughContext from "components/featureWalkthrough/walkthroughContext";
+import {
+ getFeatureFlagShownStatus,
+ isUserSignedUpFlagSet,
+ setFeatureFlagShownStatus,
+} from "utils/storage";
+import { PluginName } from "entities/Action";
+import { getCurrentUser } from "selectors/usersSelectors";
+import { Tooltip } from "design-system";
+import { ASSETS_CDN_URL } from "constants/ThirdPartyConstants";
+
+const SCHEMA_GUIDE_GIF = `${ASSETS_CDN_URL}/schema.gif`;
+
+const SCHEMA_SECTION_ID = "t--api-right-pane-schema";
const SideBar = styled.div`
height: 100%;
width: 100%;
- -webkit-animation: slide-left 0.2s cubic-bezier(0.25, 0.46, 0.45, 0.94) both;
- animation: slide-left 0.2s cubic-bezier(0.25, 0.46, 0.45, 0.94) both;
-
- & > div {
- margin-top: ${(props) => props.theme.spaces[11]}px;
- }
& > a {
margin-top: 0;
@@ -90,15 +117,30 @@ const SideBar = styled.div`
const BackToCanvasLink = styled(Link)`
margin-left: ${(props) => props.theme.spaces[1] + 1}px;
margin-top: ${(props) => props.theme.spaces[11]}px;
+ margin-bottom: ${(props) => props.theme.spaces[11]}px;
`;
const Label = styled.span`
cursor: pointer;
`;
-const CollapsibleWrapper = styled.div<{ isOpen: boolean }>`
+const CollapsibleWrapper = styled.div<{
+ isOpen: boolean;
+ isDisabled?: boolean;
+}>`
+ display: flex;
+ flex-direction: column;
+ overflow: hidden;
+ ${(props) => !!props.isDisabled && `opacity: 0.6`};
+
+ &&&&&& .${BPClasses.COLLAPSE} {
+ flex-grow: 1;
+ overflow-y: auto !important;
+ }
+
.${BPClasses.COLLAPSE_BODY} {
padding-top: ${(props) => props.theme.spaces[3]}px;
+ height: 100%;
}
& > .icon-text:first-child {
@@ -142,14 +184,36 @@ const Placeholder = styled.div`
text-align: center;
`;
+const DataStructureListWrapper = styled.div`
+ overflow-y: scroll;
+ height: 100%;
+`;
+
+const SchemaSideBarSection = styled.div<{ height: number; marginTop?: number }>`
+ margin-top: ${(props) => props?.marginTop && `${props.marginTop}px`};
+ height: auto;
+ display: flex;
+ width: 100%;
+ flex-direction: column;
+ ${(props) => props.height && `max-height: ${props.height}%;`}
+`;
+
type CollapsibleProps = {
expand?: boolean;
children: ReactNode;
label: string;
+ customLabelComponent?: JSX.Element;
+ isDisabled?: boolean;
+};
+
+type DisabledCollapsibleProps = {
+ label: string;
+ tooltipLabel?: string;
};
export function Collapsible({
children,
+ customLabelComponent,
expand = true,
label,
}: CollapsibleProps) {
@@ -162,8 +226,14 @@ export function Collapsible({
return (
<CollapsibleWrapper isOpen={isOpen}>
<Label className="icon-text" onClick={() => setIsOpen(!isOpen)}>
- <Icon name="down-arrow" size="lg" />
- <span className="label">{label}</span>
+ <Icon name={isOpen ? "down-arrow" : "arrow-right-s-line"} size="lg" />
+ {!!customLabelComponent ? (
+ customLabelComponent
+ ) : (
+ <Text className="label" kind="heading-xs">
+ {label}
+ </Text>
+ )}
</Label>
<Collapse isOpen={isOpen} keepChildrenMounted>
{children}
@@ -172,6 +242,24 @@ export function Collapsible({
);
}
+export function DisabledCollapsible({
+ label,
+ tooltipLabel = "",
+}: DisabledCollapsibleProps) {
+ return (
+ <Tooltip content={tooltipLabel}>
+ <CollapsibleWrapper isDisabled isOpen={false}>
+ <Label className="icon-text">
+ <Icon name="arrow-right-s-line" size="lg" />
+ <Text className="label" kind="heading-xs">
+ {label}
+ </Text>
+ </Label>
+ </CollapsibleWrapper>
+ </Tooltip>
+ );
+}
+
export function useEntityDependencies(actionName: string) {
const deps = useSelector((state: AppState) => state.evaluations.dependencies);
const entityDependencies = useMemo(
@@ -194,9 +282,12 @@ export function useEntityDependencies(actionName: string) {
function ActionSidebar({
actionName,
+ context,
+ datasourceId,
entityDependencies,
hasConnections,
hasResponse,
+ pluginId,
suggestedWidgets,
}: {
actionName: string;
@@ -207,11 +298,16 @@ function ActionSidebar({
directDependencies: string[];
inverseDependencies: string[];
} | null;
+ datasourceId: string;
+ pluginId: string;
+ context: DatasourceStructureContext;
}) {
const dispatch = useDispatch();
const widgets = useSelector(getWidgets);
const applicationId = useSelector(getCurrentApplicationId);
const pageId = useSelector(getCurrentPageId);
+ const user = useSelector(getCurrentUser);
+ const { pushFeature } = useContext(WalkthroughContext) || {};
const params = useParams<{
pageId: string;
apiId?: string;
@@ -232,6 +328,100 @@ function ActionSidebar({
);
};
+ const pluginName = useSelector((state) =>
+ getPluginNameFromId(state, pluginId || ""),
+ );
+
+ const pluginDatasourceForm = useSelector((state) =>
+ getPluginDatasourceComponentFromId(state, pluginId || ""),
+ );
+
+ // A/B feature flag for datasource structure.
+ const isEnabledForDSSchema = useSelector((state) =>
+ selectFeatureFlagCheck(state, FEATURE_FLAG.ab_ds_schema_enabled),
+ );
+
+ // A/B feature flag for query binding.
+ const isEnabledForQueryBinding = useSelector((state) =>
+ selectFeatureFlagCheck(state, FEATURE_FLAG.ab_ds_binding_enabled),
+ );
+
+ const datasourceStructure = useSelector((state) =>
+ getDatasourceStructureById(state, datasourceId),
+ );
+
+ useEffect(() => {
+ if (
+ datasourceId &&
+ datasourceStructure === undefined &&
+ pluginDatasourceForm !== DatasourceComponentTypes.RestAPIDatasourceForm
+ ) {
+ dispatch(
+ fetchDatasourceStructure(
+ datasourceId,
+ true,
+ DatasourceStructureContext.QUERY_EDITOR,
+ ),
+ );
+ }
+ }, []);
+
+ const checkAndShowWalkthrough = async () => {
+ const isFeatureWalkthroughShown = await getFeatureFlagShownStatus(
+ FEATURE_FLAG.ab_ds_schema_enabled,
+ );
+
+ const isNewUser = user && (await isUserSignedUpFlagSet(user.email));
+ // Adding walkthrough tutorial
+ isNewUser &&
+ !isFeatureWalkthroughShown &&
+ pushFeature &&
+ pushFeature({
+ targetId: SCHEMA_SECTION_ID,
+ onDismiss: async () => {
+ AnalyticsUtil.logEvent("WALKTHROUGH_DISMISSED", {
+ [AB_TESTING_EVENT_KEYS.abTestingFlagLabel]:
+ FEATURE_FLAG.ab_ds_schema_enabled,
+ [AB_TESTING_EVENT_KEYS.abTestingFlagValue]: isEnabledForDSSchema,
+ });
+ await setFeatureFlagShownStatus(
+ FEATURE_FLAG.ab_ds_schema_enabled,
+ true,
+ );
+ },
+ details: {
+ title: createMessage(SCHEMA_WALKTHROUGH_TITLE),
+ description: createMessage(SCHEMA_WALKTHROUGH_DESC),
+ imageURL: SCHEMA_GUIDE_GIF,
+ },
+ offset: {
+ position: "left",
+ left: -40,
+ highlightPad: 5,
+ indicatorLeft: -3,
+ style: {
+ transform: "none",
+ },
+ },
+ eventParams: {
+ [AB_TESTING_EVENT_KEYS.abTestingFlagLabel]:
+ FEATURE_FLAG.ab_ds_schema_enabled,
+ [AB_TESTING_EVENT_KEYS.abTestingFlagValue]: isEnabledForDSSchema,
+ },
+ });
+ };
+
+ const showSchema =
+ isEnabledForDSSchema &&
+ pluginDatasourceForm !== DatasourceComponentTypes.RestAPIDatasourceForm &&
+ pluginName !== PluginName.SMTP;
+
+ useEffect(() => {
+ if (showSchema) {
+ checkAndShowWalkthrough();
+ }
+ }, [showSchema]);
+
const hasWidgets = Object.keys(widgets).length > 1;
const pagePermissions = useSelector(getPagePermissions);
@@ -242,7 +432,13 @@ function ActionSidebar({
canEditPage && hasResponse && suggestedWidgets && !!suggestedWidgets.length;
const showSnipingMode = hasResponse && hasWidgets;
- if (!hasConnections && !showSuggestedWidgets && !showSnipingMode) {
+ if (
+ !hasConnections &&
+ !showSuggestedWidgets &&
+ !showSnipingMode &&
+ // putting this here to make the placeholder only appear for rest APIs.
+ pluginDatasourceForm === DatasourceComponentTypes.RestAPIDatasourceForm
+ ) {
return <Placeholder>{createMessage(NO_CONNECTIONS)}</Placeholder>;
}
@@ -257,33 +453,69 @@ function ActionSidebar({
{createMessage(BACK_TO_CANVAS)}
</BackToCanvasLink>
- {hasConnections && (
+ {showSchema && (
+ <SchemaSideBarSection height={50} id={SCHEMA_SECTION_ID}>
+ <Collapsible
+ customLabelComponent={
+ <DatasourceStructureHeader datasourceId={datasourceId || ""} />
+ }
+ expand={!showSuggestedWidgets}
+ label="Schema"
+ >
+ <DataStructureListWrapper>
+ <DataStructureList
+ context={context}
+ currentActionId={params?.queryId || ""}
+ datasourceId={datasourceId || ""}
+ datasourceStructure={datasourceStructure}
+ pluginName={pluginName}
+ step={0}
+ />
+ </DataStructureListWrapper>
+ </Collapsible>
+ </SchemaSideBarSection>
+ )}
+
+ {showSchema && isEnabledForQueryBinding && <Divider />}
+
+ {hasConnections && !isEnabledForQueryBinding && (
<Connections
actionName={actionName}
entityDependencies={entityDependencies}
/>
)}
- {canEditPage && hasResponse && Object.keys(widgets).length > 1 && (
- <Collapsible label="Connect widget">
- {/*<div className="description">Go to canvas and select widgets</div>*/}
- <SnipingWrapper>
- <Button
- className={"t--select-in-canvas"}
- kind="secondary"
- onClick={handleBindData}
- size="md"
- >
- Select widget
- </Button>
- </SnipingWrapper>
- </Collapsible>
- )}
- {showSuggestedWidgets && (
- <SuggestedWidgets
- actionName={actionName}
- hasWidgets={hasWidgets}
- suggestedWidgets={suggestedWidgets as SuggestedWidget[]}
- />
+ {!isEnabledForQueryBinding &&
+ canEditPage &&
+ hasResponse &&
+ Object.keys(widgets).length > 1 && (
+ <Collapsible label="Connect widget">
+ <SnipingWrapper>
+ <Button
+ className={"t--select-in-canvas"}
+ kind="secondary"
+ onClick={handleBindData}
+ size="md"
+ >
+ Select widget
+ </Button>
+ </SnipingWrapper>
+ </Collapsible>
+ )}
+ {showSuggestedWidgets ? (
+ <SchemaSideBarSection height={40} marginTop={12}>
+ <SuggestedWidgets
+ actionName={actionName}
+ hasWidgets={hasWidgets}
+ suggestedWidgets={suggestedWidgets as SuggestedWidget[]}
+ />
+ </SchemaSideBarSection>
+ ) : (
+ isEnabledForQueryBinding && (
+ <DisabledCollapsible
+ label={createMessage(BINDING_SECTION_LABEL)}
+ tooltipLabel={createMessage(BINDINGS_DISABLED_TOOLTIP)}
+ />
+ )
)}
</SideBar>
);
diff --git a/app/client/src/components/editorComponents/WidgetQueryGeneratorForm/CommonControls/TableOrSpreadsheetDropdown/useTableOrSpreadsheet.tsx b/app/client/src/components/editorComponents/WidgetQueryGeneratorForm/CommonControls/TableOrSpreadsheetDropdown/useTableOrSpreadsheet.tsx
index 3b323493a444..258bd9cddefd 100644
--- a/app/client/src/components/editorComponents/WidgetQueryGeneratorForm/CommonControls/TableOrSpreadsheetDropdown/useTableOrSpreadsheet.tsx
+++ b/app/client/src/components/editorComponents/WidgetQueryGeneratorForm/CommonControls/TableOrSpreadsheetDropdown/useTableOrSpreadsheet.tsx
@@ -45,8 +45,8 @@ export function useTableOrSpreadsheet() {
const isFetchingSpreadsheets = useSelector(getIsFetchingGsheetSpreadsheets);
- const isFetchingDatasourceStructure = useSelector(
- getIsFetchingDatasourceStructure,
+ const isFetchingDatasourceStructure = useSelector((state: AppState) =>
+ getIsFetchingDatasourceStructure(state, config.datasource),
);
const selectedDatasourcePluginPackageName = useSelector((state: AppState) =>
diff --git a/app/client/src/components/featureWalkthrough/index.tsx b/app/client/src/components/featureWalkthrough/index.tsx
new file mode 100644
index 000000000000..eedbbd6195fa
--- /dev/null
+++ b/app/client/src/components/featureWalkthrough/index.tsx
@@ -0,0 +1,82 @@
+import React, { lazy, useEffect, useState, Suspense } from "react";
+import type { FeatureParams } from "./walkthroughContext";
+import WalkthroughContext from "./walkthroughContext";
+import { createPortal } from "react-dom";
+import { hideIndicator } from "pages/Editor/GuidedTour/utils";
+import { retryPromise } from "utils/AppsmithUtils";
+import { useLocation } from "react-router-dom";
+
+const WalkthroughRenderer = lazy(() => {
+ return retryPromise(
+ () =>
+ import(
+ /* webpackChunkName: "walkthrough-renderer" */ "./walkthroughRenderer"
+ ),
+ );
+});
+
+const LoadingFallback = () => null;
+
+export default function Walkthrough({ children }: any) {
+ const [activeWalkthrough, setActiveWalkthrough] =
+ useState<FeatureParams | null>();
+ const [feature, setFeature] = useState<FeatureParams[]>([]);
+ const location = useLocation();
+
+ const pushFeature = (value: FeatureParams) => {
+ const alreadyExists = feature.some((f) => f.targetId === value.targetId);
+ if (!alreadyExists) {
+ if (Array.isArray(value)) {
+ setFeature((e) => [...e, ...value]);
+ } else {
+ setFeature((e) => [...e, value]);
+ }
+ }
+ updateActiveWalkthrough();
+ };
+
+ const popFeature = () => {
+ hideIndicator();
+ setFeature((e) => {
+ e.shift();
+ return [...e];
+ });
+ };
+
+ const updateActiveWalkthrough = () => {
+ if (feature.length > 0) {
+ const highlightArea = document.querySelector(`#${feature[0].targetId}`);
+ if (highlightArea) {
+ setActiveWalkthrough(feature[0]);
+ } else {
+ setActiveWalkthrough(null);
+ }
+ } else {
+ setActiveWalkthrough(null);
+ }
+ };
+
+ useEffect(() => {
+ if (feature.length > -1) updateActiveWalkthrough();
+ }, [feature.length, location]);
+
+ return (
+ <WalkthroughContext.Provider
+ value={{
+ pushFeature,
+ popFeature,
+ feature,
+ isOpened: !!activeWalkthrough,
+ }}
+ >
+ {children}
+ {activeWalkthrough &&
+ createPortal(
+ <Suspense fallback={<LoadingFallback />}>
+ <WalkthroughRenderer {...activeWalkthrough} />
+ </Suspense>,
+ document.body,
+ )}
+ </WalkthroughContext.Provider>
+ );
+}
diff --git a/app/client/src/components/featureWalkthrough/utils.ts b/app/client/src/components/featureWalkthrough/utils.ts
new file mode 100644
index 000000000000..9f737542eaa3
--- /dev/null
+++ b/app/client/src/components/featureWalkthrough/utils.ts
@@ -0,0 +1,92 @@
+import type { OffsetType, PositionType } from "./walkthroughContext";
+
+const DEFAULT_POSITION: PositionType = "top";
+export const PADDING_HIGHLIGHT = 10;
+
+type PositionCalculator = {
+ offset?: OffsetType;
+ targetId: string;
+};
+
+export function getPosition({ offset, targetId }: PositionCalculator) {
+ const target = document.querySelector(`#${targetId}`);
+ const bodyCoordinates = document.body.getBoundingClientRect();
+ if (!target) return null;
+ let coordinates;
+ if (target) {
+ coordinates = target.getBoundingClientRect();
+ }
+
+ if (!coordinates) return null;
+
+ const offsetValues = { top: offset?.top || 0, left: offset?.left || 0 };
+ const extraStyles = offset?.style || {};
+
+ /**
+ * . - - - - - - - - - - - - - - - - - .
+ * | Body |
+ * | |
+ * | . - - - - - - - - - - . |
+ * | | Offset | |
+ * | | . - - - - - - - . | |
+ * | | | / / / / / / / | | |
+ * | | | / / /Target/ /| | |
+ * | | | / / / / / / / | | |
+ * | | . - - - - - - - . | |
+ * | | | |
+ * | . _ _ _ _ _ _ _ _ _ _ . |
+ * | |
+ * . - - - - - - - - - - - - - - - - - .
+ */
+
+ switch (offset?.position || DEFAULT_POSITION) {
+ case "top":
+ return {
+ bottom:
+ bodyCoordinates.height -
+ coordinates.top -
+ offsetValues.top +
+ PADDING_HIGHLIGHT +
+ "px",
+ left: coordinates.left + offsetValues.left + PADDING_HIGHLIGHT + "px",
+ transform: "translateX(-50%)",
+ ...extraStyles,
+ };
+ case "bottom":
+ return {
+ top:
+ coordinates.height +
+ coordinates.top +
+ offsetValues.top +
+ PADDING_HIGHLIGHT +
+ "px",
+ left: coordinates.left + offsetValues.left - PADDING_HIGHLIGHT + "px",
+ transform: "translateX(-50%)",
+ ...extraStyles,
+ };
+ case "left":
+ return {
+ top: coordinates.top + offsetValues.top - PADDING_HIGHLIGHT + "px",
+ right:
+ bodyCoordinates.width -
+ coordinates.left -
+ offsetValues.left +
+ PADDING_HIGHLIGHT +
+ "px",
+ transform: "translateY(-50%)",
+ ...extraStyles,
+ };
+ case "right":
+ return {
+ top: coordinates.top + offsetValues.top - PADDING_HIGHLIGHT + "px",
+ left:
+ coordinates.left +
+ coordinates.width +
+ offsetValues.left +
+ PADDING_HIGHLIGHT +
+ "px",
+ transform: "translateY(-50%)",
+ ...extraStyles,
+ };
+ }
+}
diff --git a/app/client/src/components/featureWalkthrough/walkthroughContext.tsx b/app/client/src/components/featureWalkthrough/walkthroughContext.tsx
new file mode 100644
index 000000000000..9d31d38eef24
--- /dev/null
+++ b/app/client/src/components/featureWalkthrough/walkthroughContext.tsx
@@ -0,0 +1,54 @@
+import React from "react";
+
+export type PositionType = "top" | "bottom" | "left" | "right";
+
+export type OffsetType = {
+ // Position for the instructions and indicator
+ position?: PositionType;
+ // Adds an offset to top or bottom properties (of Instruction div) depending upon the position
+ top?: number;
+ // Adds an offset to left or right properties (of Instruction div) depending upon the position
+ left?: number;
+ // Style for the Instruction div overrides all other styles
+ style?: any;
+ // Indicator top and left offsets
+ indicatorTop?: number;
+ indicatorLeft?: number;
+ // container offset for highlight
+ highlightPad?: number;
+};
+
+export type FeatureDetails = {
+ // Title to show on the instruction screen
+ title: string;
+ // Description to show on the instruction screen
+ description: string;
+ // Gif or Image to give a walkthrough
+ imageURL?: string;
+};
+
+export type FeatureParams = {
+ // To execute a function on dismissing the tutorial walkthrough.
+ onDismiss?: () => void;
+ // Target Id without # to highlight the feature
+ targetId: string;
+ // Details for the instruction screen
+ details?: FeatureDetails;
+ // Offsets for the instruction screen and the indicator
+ offset?: OffsetType;
+ // Event params
+ eventParams?: Record<string, any>;
+};
+
+type WalkthroughContextType = {
+ pushFeature: (feature: FeatureParams) => void;
+ popFeature: () => void;
+ feature: FeatureParams[];
+ isOpened: boolean;
+};
+
+const WalkthroughContext = React.createContext<
+ WalkthroughContextType | undefined
+>(undefined);
+
+export default WalkthroughContext;
diff --git a/app/client/src/components/featureWalkthrough/walkthroughRenderer.tsx b/app/client/src/components/featureWalkthrough/walkthroughRenderer.tsx
new file mode 100644
index 000000000000..97f52dfec25f
--- /dev/null
+++ b/app/client/src/components/featureWalkthrough/walkthroughRenderer.tsx
@@ -0,0 +1,258 @@
+import { Icon, Text } from "design-system";
+import { showIndicator } from "pages/Editor/GuidedTour/utils";
+import React, { useContext, useEffect, useState } from "react";
+import styled from "styled-components";
+import { PADDING_HIGHLIGHT, getPosition } from "./utils";
+import type {
+ FeatureDetails,
+ FeatureParams,
+ OffsetType,
+} from "./walkthroughContext";
+import WalkthroughContext from "./walkthroughContext";
+import AnalyticsUtil from "utils/AnalyticsUtil";
+
+const CLIPID = "clip__feature";
+const Z_INDEX = 1000;
+
+const WalkthroughWrapper = styled.div`
+ left: 0px;
+ top: 0px;
+ position: fixed;
+ width: 100%;
+ height: 100%;
+ color: rgb(0, 0, 0, 0.7);
+ z-index: ${Z_INDEX};
+ // This allows the user to click on the target element rather than the overlay div
+ pointer-events: none;
+`;
+
+const SvgWrapper = styled.svg`
+ position: absolute;
+ width: 100%;
+ height: 100%;
+ top: 0;
+ left: 0;
+`;
+
+const InstructionsWrapper = styled.div`
+ padding: var(--ads-v2-spaces-4);
+ position: absolute;
+ background: white;
+ display: flex;
+ flex-direction: column;
+ width: 296px;
+ pointer-events: auto;
+ border-radius: var(--ads-radius-1);
+`;
+
+const ImageWrapper = styled.div`
+ border-radius: var(--ads-radius-1);
+ background: #f1f5f9;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ margin-top: 8px;
+ padding: var(--ads-v2-spaces-7);
+ img {
+ max-height: 220px;
+ }
+`;
+
+const InstructionsHeaderWrapper = styled.div`
+ display: flex;
+ p {
+ flex-grow: 1;
+ }
+ span {
+ align-self: flex-start;
+ margin-top: 5px;
+ cursor: pointer;
+ }
+`;
+
+type RefRectParams = {
+ // body params
+ bh: number;
+ bw: number;
+ // target params
+ th: number;
+ tw: number;
+ tx: number;
+ ty: number;
+};
+
+/*
+ * Clip Path Polygon :
+ * 1) 0 0 ----> (body start) (body start)
+ * 2) 0 ${boundingRect.bh} ----> (body start) (body end)
+ * 3) ${boundingRect.tx} ${boundingRect.bh} ----> (target start) (body end)
+ * 4) ${boundingRect.tx} ${boundingRect.ty} ----> (target start) (target start)
+ * 5) ${boundingRect.tx + boundingRect.tw} ${boundingRect.ty} ----> (target end) (target start)
+ * 6) ${boundingRect.tx + boundingRect.tw} ${boundingRect.ty + boundingRect.th} ----> (target end) (target end)
+ * 7) ${boundingRect.tx} ${boundingRect.ty + boundingRect.th} ----> (target start) (target end)
+ * 8) ${boundingRect.tx} ${boundingRect.bh} ----> (target start) (body end)
+ * 9) ${boundingRect.bw} ${boundingRect.bh} ----> (body end) (body end)
+ * 10) ${boundingRect.bw} 0 ----> (body end) (body start)
+ *
+ *
+ * 1 ← ← ← ← ← ← ← ← ← ← ← ← ← ← ← ← ←10
+ * ↓ ↑
+ * ↓ Body ↑
+ * ↓ ↑
+ * ↓ ↑
+ * ↓ 4 → → → → → → → 5 ↑
+ * ↓ ↑ / / / / / / / ↓ ↑
+ * ↓ ↑ / / /Target/ /↓ ↑
+ * ↓ ↑ / / / / / / / ↓ ↑
+ * ↓ 7 ← ← ← ← ← ← ← 6 ↑
+ * ↓ ↑↓ ↑
+ * ↓ ↑↓ ↑
+ * 2 → → → → 3,8 → → → → → → → → → → → 9
+ */
+
+/**
+ * Creates a Highlighting Clipping mask around a target container
+ * @param targetId Id for the target container to show highlighting around it
+ */
+
+const WalkthroughRenderer = ({
+ details,
+ offset,
+ onDismiss,
+ targetId,
+ eventParams = {},
+}: FeatureParams) => {
+ const [boundingRect, setBoundingRect] = useState<RefRectParams | null>(null);
+ const { popFeature } = useContext(WalkthroughContext) || {};
+ const updateBoundingRect = () => {
+ const highlightArea = document.querySelector(`#${targetId}`);
+ if (highlightArea) {
+ const boundingRect = highlightArea.getBoundingClientRect();
+ const bodyRect = document.body.getBoundingClientRect();
+ const offsetHighlightPad =
+ typeof offset?.highlightPad === "number"
+ ? offset?.highlightPad
+ : PADDING_HIGHLIGHT;
+ setBoundingRect({
+ bw: bodyRect.width,
+ bh: bodyRect.height,
+ tw: boundingRect.width + 2 * offsetHighlightPad,
+ th: boundingRect.height + 2 * offsetHighlightPad,
+ tx: boundingRect.x - offsetHighlightPad,
+ ty: boundingRect.y - offsetHighlightPad,
+ });
+ showIndicator(`#${targetId}`, offset?.position, {
+ top: offset?.indicatorTop || 0,
+ left: offset?.indicatorLeft || 0,
+ zIndex: Z_INDEX + 1,
+ });
+ }
+ };
+
+ useEffect(() => {
+ updateBoundingRect();
+ const highlightArea = document.querySelector(`#${targetId}`);
+ AnalyticsUtil.logEvent("WALKTHROUGH_SHOWN", eventParams);
+ window.addEventListener("resize", updateBoundingRect);
+ const resizeObserver = new ResizeObserver(updateBoundingRect);
+ if (highlightArea) {
+ resizeObserver.observe(highlightArea);
+ }
+ return () => {
+ window.removeEventListener("resize", updateBoundingRect);
+ if (highlightArea) resizeObserver.unobserve(highlightArea);
+ };
+ }, [targetId]);
+
+ const onDismissWalkthrough = () => {
+ onDismiss && onDismiss();
+ popFeature && popFeature();
+ };
+
+ if (!boundingRect) return null;
+
+ return (
+ <WalkthroughWrapper className="t--walkthrough-overlay">
+ <SvgWrapper
+ height={boundingRect.bh}
+ width={boundingRect.bw}
+ xmlns="http://www.w3.org/2000/svg"
+ >
+ <defs>
+ <clipPath id={CLIPID}>
+ <polygon
+ // See the comments above the component declaration to understand the below points assignment.
+ points={`
+ 0 0,
+ 0 ${boundingRect.bh},
+ ${boundingRect.tx} ${boundingRect.bh},
+ ${boundingRect.tx} ${boundingRect.ty},
+ ${boundingRect.tx + boundingRect.tw} ${boundingRect.ty},
+ ${boundingRect.tx + boundingRect.tw} ${
+ boundingRect.ty + boundingRect.th
+ },
+ ${boundingRect.tx} ${boundingRect.ty + boundingRect.th},
+ ${boundingRect.tx} ${boundingRect.bh},
+ ${boundingRect.bw} ${boundingRect.bh},
+ ${boundingRect.bw} 0
+ `}
+ />
+ </clipPath>
+ </defs>
+ <rect
+ style={{
+ clipPath: 'url("#' + CLIPID + '")',
+ fill: "currentcolor",
+ height: boundingRect.bh,
+ pointerEvents: "auto",
+ width: boundingRect.bw,
+ }}
+ />
+ </SvgWrapper>
+ <InstructionsComponent
+ details={details}
+ offset={offset}
+ onClose={onDismissWalkthrough}
+ targetId={targetId}
+ />
+ </WalkthroughWrapper>
+ );
+};
+
+const InstructionsComponent = ({
+ details,
+ offset,
+ onClose,
+ targetId,
+}: {
+ details?: FeatureDetails;
+ offset?: OffsetType;
+ targetId: string;
+ onClose: () => void;
+}) => {
+ if (!details) return null;
+
+ const positionAttr = getPosition({
+ targetId,
+ offset,
+ });
+
+ return (
+ <InstructionsWrapper style={{ ...positionAttr }}>
+ <InstructionsHeaderWrapper>
+ <Text kind="heading-s" renderAs="p">
+ {details.title}
+ </Text>
+ <Icon name="close" onClick={onClose} size="md" />
+ </InstructionsHeaderWrapper>
+ <Text>{details.description}</Text>
+ {details.imageURL && (
+ <ImageWrapper>
+ <img src={details.imageURL} />
+ </ImageWrapper>
+ )}
+ </InstructionsWrapper>
+ );
+};
+
+export default WalkthroughRenderer;
diff --git a/app/client/src/components/formControls/WhereClauseControl.tsx b/app/client/src/components/formControls/WhereClauseControl.tsx
index 99008248c699..9e5f622fdc49 100644
--- a/app/client/src/components/formControls/WhereClauseControl.tsx
+++ b/app/client/src/components/formControls/WhereClauseControl.tsx
@@ -282,7 +282,7 @@ function ConditionComponent(props: any, index: number) {
props.onDeletePressed(index);
}}
size="md"
- startIcon="cross-line"
+ startIcon="close"
/>
</ConditionBox>
);
@@ -397,7 +397,7 @@ function ConditionBlock(props: any) {
onDeletePressed(index);
}}
size="md"
- startIcon="cross-line"
+ startIcon="close"
top={"24px"}
/>
</GroupConditionBox>
diff --git a/app/client/src/constants/Datasource.ts b/app/client/src/constants/Datasource.ts
index 3cb14ebb6b9f..422899646961 100644
--- a/app/client/src/constants/Datasource.ts
+++ b/app/client/src/constants/Datasource.ts
@@ -24,6 +24,7 @@ export const DatasourceCreateEntryPoints = {
export const DatasourceEditEntryPoints = {
DATASOURCE_CARD_EDIT: "DATASOURCE_CARD_EDIT",
DATASOURCE_FORM_EDIT: "DATASOURCE_FORM_EDIT",
+ QUERY_EDITOR_DATASOURCE_SCHEMA: "QUERY_EDITOR_DATASOURCE_SCHEMA",
};
export const DB_QUERY_DEFAULT_TABLE_NAME = "<<your_table_name>>";
diff --git a/app/client/src/constants/DefaultTheme.tsx b/app/client/src/constants/DefaultTheme.tsx
index b456935216c9..a00e9542f6e1 100644
--- a/app/client/src/constants/DefaultTheme.tsx
+++ b/app/client/src/constants/DefaultTheme.tsx
@@ -3015,7 +3015,7 @@ export const theme: Theme = {
},
},
actionSidePane: {
- width: 265,
+ width: 280,
},
onboarding: {
statusBarHeight: 92,
diff --git a/app/client/src/entities/Action/index.ts b/app/client/src/entities/Action/index.ts
index 558a9c174218..faef9e3fb9e1 100644
--- a/app/client/src/entities/Action/index.ts
+++ b/app/client/src/entities/Action/index.ts
@@ -40,6 +40,7 @@ export enum PluginName {
SNOWFLAKE = "Snowflake",
ARANGODB = "ArangoDB",
REDSHIFT = "Redshift",
+ SMTP = "SMTP",
}
export enum PaginationType {
diff --git a/app/client/src/pages/Editor/APIEditor/ApiRightPane.tsx b/app/client/src/pages/Editor/APIEditor/ApiRightPane.tsx
index 48ce5ac3333b..fc3908231ade 100644
--- a/app/client/src/pages/Editor/APIEditor/ApiRightPane.tsx
+++ b/app/client/src/pages/Editor/APIEditor/ApiRightPane.tsx
@@ -15,6 +15,7 @@ import { useDispatch, useSelector } from "react-redux";
import { getApiRightPaneSelectedTab } from "selectors/apiPaneSelectors";
import isUndefined from "lodash/isUndefined";
import { Button, Tab, TabPanel, Tabs, TabsList, Tag } from "design-system";
+import { DatasourceStructureContext } from "../Explorer/Datasources/DatasourceStructureContainer";
import type { Datasource } from "entities/Datasource";
import { getCurrentEnvironment } from "@appsmith/utils/Environments";
@@ -125,7 +126,7 @@ const DataSourceNameContainer = styled.div`
const SomeWrapper = styled.div`
height: 100%;
- padding: 0 var(--ads-v2-spaces-6);
+ padding: 0 var(--ads-v2-spaces-4);
`;
const NoEntityFoundWrapper = styled.div`
@@ -311,9 +312,12 @@ function ApiRightPane(props: any) {
<SomeWrapper>
<ActionRightPane
actionName={props.actionName}
+ context={DatasourceStructureContext.API_EDITOR}
+ datasourceId={props.datasourceId}
entityDependencies={entityDependencies}
hasConnections={hasDependencies}
hasResponse={props.hasResponse}
+ pluginId={props.pluginId}
suggestedWidgets={props.suggestedWidgets}
/>
</SomeWrapper>
diff --git a/app/client/src/pages/Editor/APIEditor/CommonEditorForm.tsx b/app/client/src/pages/Editor/APIEditor/CommonEditorForm.tsx
index 5ec1d3ba8db4..e123b6278deb 100644
--- a/app/client/src/pages/Editor/APIEditor/CommonEditorForm.tsx
+++ b/app/client/src/pages/Editor/APIEditor/CommonEditorForm.tsx
@@ -735,9 +735,11 @@ function CommonEditorForm(props: CommonFormPropsWithExtraParams) {
applicationId={props.applicationId}
currentActionDatasourceId={currentActionDatasourceId}
currentPageId={props.currentPageId}
+ datasourceId={props.currentActionDatasourceId}
datasources={props.datasources}
hasResponse={props.hasResponse}
onClick={updateDatasource}
+ pluginId={props.pluginId}
suggestedWidgets={props.suggestedWidgets}
/>
</Wrapper>
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 cc03bc7eb36e..607977e41635 100644
--- a/app/client/src/pages/Editor/AppSettingsPane/AppSettings/NavigationSettings/index.tsx
+++ b/app/client/src/pages/Editor/AppSettingsPane/AppSettings/NavigationSettings/index.tsx
@@ -24,7 +24,7 @@ import { Spinner } from "design-system";
import LogoInput from "@appsmith/pages/Editor/NavigationSettings/LogoInput";
import SwitchSettingForLogoConfiguration from "./SwitchSettingForLogoConfiguration";
import { FEATURE_FLAG } from "@appsmith/entities/FeatureFlag";
-import { useFeatureFlagCheck } from "selectors/featureFlagsSelectors";
+import { selectFeatureFlagCheck } from "selectors/featureFlagsSelectors";
/**
* TODO - @Dhruvik - ImprovedAppNav
@@ -48,8 +48,8 @@ export type LogoConfigurationSwitches = {
function NavigationSettings() {
const application = useSelector(getCurrentApplication);
const applicationId = useSelector(getCurrentApplicationId);
- const isAppLogoEnabled = useFeatureFlagCheck(
- FEATURE_FLAG.APP_NAVIGATION_LOGO_UPLOAD,
+ const isAppLogoEnabled = useSelector((state) =>
+ selectFeatureFlagCheck(state, FEATURE_FLAG.APP_NAVIGATION_LOGO_UPLOAD),
);
const dispatch = useDispatch();
const [navigationSetting, setNavigationSetting] = useState(
diff --git a/app/client/src/pages/Editor/DataSourceEditor/DBForm.tsx b/app/client/src/pages/Editor/DataSourceEditor/DBForm.tsx
index 79c083396fbf..21bc0fe54d00 100644
--- a/app/client/src/pages/Editor/DataSourceEditor/DBForm.tsx
+++ b/app/client/src/pages/Editor/DataSourceEditor/DBForm.tsx
@@ -38,12 +38,13 @@ type Props = DatasourceDBEditorProps &
export const Form = styled.form<{
showFilterComponent: boolean;
+ viewMode: boolean;
}>`
display: flex;
flex-direction: column;
- height: ${({ theme }) => `calc(100% - ${theme.backBanner})`};
+ ${(props) =>
+ !props.viewMode && `height: ${`calc(100% - ${props?.theme.backBanner})`};`}
overflow-y: scroll;
- flex: 8 8 80%;
padding-bottom: 20px;
margin-left: ${(props) => (props.showFilterComponent ? "24px" : "0px")};
`;
@@ -90,6 +91,7 @@ class DatasourceDBEditor extends JSONtoForm<Props> {
e.preventDefault();
}}
showFilterComponent={showFilterComponent}
+ viewMode={viewMode}
>
{messages &&
messages.map((msg, i) => {
diff --git a/app/client/src/pages/Editor/DataSourceEditor/RestAPIDatasourceForm.tsx b/app/client/src/pages/Editor/DataSourceEditor/RestAPIDatasourceForm.tsx
index 71206ca1eab7..ebf309e138f3 100644
--- a/app/client/src/pages/Editor/DataSourceEditor/RestAPIDatasourceForm.tsx
+++ b/app/client/src/pages/Editor/DataSourceEditor/RestAPIDatasourceForm.tsx
@@ -72,6 +72,7 @@ interface DatasourceRestApiEditorProps {
toggleSaveActionFlag: (flag: boolean) => void;
triggerSave?: boolean;
datasourceDeleteTrigger: () => void;
+ viewMode: boolean;
}
type Props = DatasourceRestApiEditorProps &
@@ -247,6 +248,7 @@ class DatasourceRestAPIEditor extends React.Component<Props> {
e.preventDefault();
}}
showFilterComponent={this.props.showFilterComponent}
+ viewMode={this.props.viewMode}
>
{this.renderEditor()}
</Form>
diff --git a/app/client/src/pages/Editor/DataSourceEditor/index.tsx b/app/client/src/pages/Editor/DataSourceEditor/index.tsx
index 34881681b946..36050495bdd4 100644
--- a/app/client/src/pages/Editor/DataSourceEditor/index.tsx
+++ b/app/client/src/pages/Editor/DataSourceEditor/index.tsx
@@ -32,7 +32,6 @@ import type { RouteComponentProps } from "react-router";
import EntityNotFoundPane from "pages/Editor/EntityNotFoundPane";
import { DatasourceComponentTypes } from "api/PluginApi";
import DatasourceSaasForm from "../SaaSEditor/DatasourceForm";
-
import {
getCurrentApplicationId,
getPagePermissions,
@@ -493,51 +492,49 @@ 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}
- 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 (
<>
- <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}
- />
+ {
+ // 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}
+ />
+ )
+ }
{this.renderSaveDisacardModal()}
</>
);
diff --git a/app/client/src/pages/Editor/Explorer/Datasources.tsx b/app/client/src/pages/Editor/Explorer/Datasources.tsx
index b4741526be40..fbdf4adb9eec 100644
--- a/app/client/src/pages/Editor/Explorer/Datasources.tsx
+++ b/app/client/src/pages/Editor/Explorer/Datasources.tsx
@@ -123,11 +123,11 @@ const Datasources = React.memo(() => {
<Entity
addButtonHelptext={createMessage(CREATE_DATASOURCE_TOOLTIP)}
className={"group datasources"}
- entityId="datasources_section"
+ entityId={pageId + "_datasources"}
icon={null}
isDefaultExpanded={
isDatasourcesOpen === null || isDatasourcesOpen === undefined
- ? false
+ ? true
: isDatasourcesOpen
}
isSticky
diff --git a/app/client/src/pages/Editor/Explorer/Datasources/DataSourceContextMenu.tsx b/app/client/src/pages/Editor/Explorer/Datasources/DataSourceContextMenu.tsx
index 8385906d0459..5517062cc982 100644
--- a/app/client/src/pages/Editor/Explorer/Datasources/DataSourceContextMenu.tsx
+++ b/app/client/src/pages/Editor/Explorer/Datasources/DataSourceContextMenu.tsx
@@ -21,6 +21,7 @@ import {
import { getDatasource } from "selectors/entitiesSelector";
import type { TreeDropdownOption } from "pages/Editor/Explorer/ContextMenu";
import ContextMenu from "pages/Editor/Explorer/ContextMenu";
+import { DatasourceStructureContext } from "./DatasourceStructureContainer";
export function DataSourceContextMenu(props: {
datasourceId: string;
@@ -36,7 +37,12 @@ export function DataSourceContextMenu(props: {
[dispatch, props.entityId],
);
const dispatchRefresh = useCallback(() => {
- dispatch(refreshDatasourceStructure(props.datasourceId));
+ dispatch(
+ refreshDatasourceStructure(
+ props.datasourceId,
+ DatasourceStructureContext.EXPLORER,
+ ),
+ );
}, [dispatch, props.datasourceId]);
const [confirmDelete, setConfirmDelete] = useState(false);
diff --git a/app/client/src/pages/Editor/Explorer/Datasources/DatasourceEntity.tsx b/app/client/src/pages/Editor/Explorer/Datasources/DatasourceEntity.tsx
index d18e39cf78ea..c6616c49f664 100644
--- a/app/client/src/pages/Editor/Explorer/Datasources/DatasourceEntity.tsx
+++ b/app/client/src/pages/Editor/Explorer/Datasources/DatasourceEntity.tsx
@@ -13,9 +13,16 @@ import {
} from "actions/datasourceActions";
import { useDispatch, useSelector } from "react-redux";
import type { AppState } from "@appsmith/reducers";
-import { DatasourceStructureContainer } from "./DatasourceStructureContainer";
+import {
+ DatasourceStructureContainer,
+ DatasourceStructureContext,
+} from "./DatasourceStructureContainer";
import { isStoredDatasource, PluginType } from "entities/Action";
-import { getAction } from "selectors/entitiesSelector";
+import {
+ getAction,
+ getDatasourceStructureById,
+ getIsFetchingDatasourceStructure,
+} from "selectors/entitiesSelector";
import {
datasourcesEditorIdURL,
saasEditorDatasourceIdURL,
@@ -81,13 +88,13 @@ const ExplorerDatasourceEntity = React.memo(
const updateDatasourceNameCall = (id: string, name: string) =>
updateDatasourceName({ id: props.datasource.id, name });
- const datasourceStructure = useSelector((state: AppState) => {
- return state.entities.datasources.structure[props.datasource.id];
- });
+ const datasourceStructure = useSelector((state: AppState) =>
+ getDatasourceStructureById(state, props.datasource.id),
+ );
- const isFetchingDatasourceStructure = useSelector((state: AppState) => {
- return state.entities.datasources.fetchingDatasourceStructure;
- });
+ const isFetchingDatasourceStructure = useSelector((state: AppState) =>
+ getIsFetchingDatasourceStructure(state, props.datasource.id),
+ );
const expandDatasourceId = useSelector((state: AppState) => {
return state.ui.datasourcePane.expandDatasourceId;
@@ -95,7 +102,13 @@ const ExplorerDatasourceEntity = React.memo(
//Debounce fetchDatasourceStructure request.
const debounceFetchDatasourceRequest = debounce(async () => {
- dispatch(fetchDatasourceStructure(props.datasource.id, true));
+ dispatch(
+ fetchDatasourceStructure(
+ props.datasource.id,
+ true,
+ DatasourceStructureContext.EXPLORER,
+ ),
+ );
}, 300);
const getDatasourceStructure = useCallback(
@@ -155,6 +168,7 @@ const ExplorerDatasourceEntity = React.memo(
updateEntityName={updateDatasourceNameCall}
>
<DatasourceStructureContainer
+ context={DatasourceStructureContext.EXPLORER}
datasourceId={props.datasource.id}
datasourceStructure={datasourceStructure}
step={props.step}
diff --git a/app/client/src/pages/Editor/Explorer/Datasources/DatasourceStructure.tsx b/app/client/src/pages/Editor/Explorer/Datasources/DatasourceStructure.tsx
index de73e3de48b3..13a5123b12d6 100644
--- a/app/client/src/pages/Editor/Explorer/Datasources/DatasourceStructure.tsx
+++ b/app/client/src/pages/Editor/Explorer/Datasources/DatasourceStructure.tsx
@@ -1,4 +1,4 @@
-import React, { useState } from "react";
+import React, { useState, useContext } from "react";
import Entity, { EntityClassNames } from "../Entity";
import { datasourceTableIcon } from "../ExplorerIcons";
import QueryTemplates from "./QueryTemplates";
@@ -9,16 +9,26 @@ import { SIDEBAR_ID } from "constants/Explorer";
import { hasCreateDatasourceActionPermission } from "@appsmith/utils/permissionHelpers";
import { useSelector } from "react-redux";
import type { AppState } from "@appsmith/reducers";
-import { getDatasource } from "selectors/entitiesSelector";
+import { getDatasource, getPlugin } from "selectors/entitiesSelector";
import { getPagePermissions } from "selectors/editorSelectors";
import { Menu, MenuTrigger, Button, Tooltip, MenuContent } from "design-system";
import { SHOW_TEMPLATES, createMessage } from "@appsmith/constants/messages";
import styled from "styled-components";
+import { DatasourceStructureContext } from "./DatasourceStructureContainer";
+import AnalyticsUtil from "utils/AnalyticsUtil";
+import type { Plugin } from "api/PluginApi";
+import WalkthroughContext from "components/featureWalkthrough/walkthroughContext";
+import { setFeatureFlagShownStatus } from "utils/storage";
+import { FEATURE_FLAG } from "@appsmith/entities/FeatureFlag";
type DatasourceStructureProps = {
dbStructure: DatasourceTable;
step: number;
datasourceId: string;
+ context: DatasourceStructureContext;
+ isDefaultOpen?: boolean;
+ forceExpand?: boolean;
+ currentActionId: string;
};
const StyledMenuContent = styled(MenuContent)`
@@ -32,10 +42,17 @@ export function DatasourceStructure(props: DatasourceStructureProps) {
const [active, setActive] = useState(false);
useCloseMenuOnScroll(SIDEBAR_ID, active, () => setActive(false));
+ const { isOpened: isWalkthroughOpened, popFeature } =
+ useContext(WalkthroughContext) || {};
+
const datasource = useSelector((state: AppState) =>
getDatasource(state, props.datasourceId),
);
+ const plugin: Plugin | undefined = useSelector((state) =>
+ getPlugin(state, datasource?.pluginId || ""),
+ );
+
const datasourcePermissions = datasource?.userPermissions || [];
const pagePermissions = useSelector(getPagePermissions);
@@ -44,62 +61,98 @@ export function DatasourceStructure(props: DatasourceStructureProps) {
...pagePermissions,
]);
- const lightningMenu = canCreateDatasourceActions ? (
- <Menu open={active}>
- <Tooltip
- content={createMessage(SHOW_TEMPLATES)}
- isDisabled={active}
- mouseLeaveDelay={0}
- placement="right"
- >
- <MenuTrigger>
- <Button
- className={`button-icon t--template-menu-trigger ${EntityClassNames.CONTEXT_MENU}`}
- isIconButton
- kind="tertiary"
- onClick={() => setActive(!active)}
- startIcon="increase-control-v2"
+ const onSelect = () => {
+ setActive(false);
+ };
+
+ const onEntityClick = () => {
+ AnalyticsUtil.logEvent("DATASOURCE_SCHEMA_TABLE_SELECT", {
+ datasourceId: props.datasourceId,
+ pluginName: plugin?.name,
+ });
+
+ canCreateDatasourceActions && setActive(!active);
+
+ dbStructure.templates.length === 0 &&
+ isWalkthroughOpened &&
+ closeWalkthrough();
+ };
+
+ const closeWalkthrough = () => {
+ popFeature && popFeature();
+ setFeatureFlagShownStatus(FEATURE_FLAG.ab_ds_schema_enabled, true);
+ };
+
+ const lightningMenu =
+ canCreateDatasourceActions && dbStructure.templates.length > 0 ? (
+ <Menu open={active}>
+ <Tooltip
+ content={createMessage(SHOW_TEMPLATES)}
+ isDisabled={active}
+ mouseLeaveDelay={0}
+ placement="right"
+ >
+ <MenuTrigger>
+ <Button
+ className={`button-icon t--template-menu-trigger ${EntityClassNames.CONTEXT_MENU}`}
+ isIconButton
+ kind="tertiary"
+ onClick={() => setActive(!active)}
+ startIcon={
+ props.context !== DatasourceStructureContext.EXPLORER
+ ? "add-line"
+ : "increase-control-v2"
+ }
+ />
+ </MenuTrigger>
+ </Tooltip>
+ <StyledMenuContent
+ align="start"
+ className="t--structure-template-menu-popover"
+ onInteractOutside={() => setActive(false)}
+ side="right"
+ >
+ <QueryTemplates
+ context={props.context}
+ currentActionId={props.currentActionId}
+ datasourceId={props.datasourceId}
+ onSelect={onSelect}
+ templates={dbStructure.templates}
/>
- </MenuTrigger>
- </Tooltip>
- <StyledMenuContent
- align="start"
- className="t--structure-template-menu-popover"
- onInteractOutside={() => setActive(false)}
- side="right"
- >
- <QueryTemplates
- datasourceId={props.datasourceId}
- onSelect={() => setActive(false)}
- templates={dbStructure.templates}
- />
- </StyledMenuContent>
- </Menu>
- ) : null;
+ </StyledMenuContent>
+ </Menu>
+ ) : null;
if (dbStructure.templates) templateMenu = lightningMenu;
const columnsAndKeys = dbStructure.columns.concat(dbStructure.keys);
return (
<Entity
- action={() => canCreateDatasourceActions && setActive(!active)}
+ action={onEntityClick}
active={active}
- className={`datasourceStructure`}
+ className={`datasourceStructure${
+ props.context !== DatasourceStructureContext.EXPLORER &&
+ `-${props.context}`
+ }`}
contextMenu={templateMenu}
- entityId={"DatasourceStructure"}
+ entityId={`${props.datasourceId}-${dbStructure.name}-${props.context}`}
+ forceExpand={props.forceExpand}
icon={datasourceTableIcon}
+ isDefaultExpanded={props?.isDefaultOpen}
name={dbStructure.name}
step={props.step}
>
- {columnsAndKeys.map((field, index) => {
- return (
- <DatasourceField
- field={field}
- key={`${field.name}${index}`}
- step={props.step + 1}
- />
- );
- })}
+ <>
+ {columnsAndKeys.map((field, index) => {
+ return (
+ <DatasourceField
+ field={field}
+ key={`${field.name}${index}`}
+ step={props.step + 1}
+ />
+ );
+ })}
+ </>
</Entity>
);
}
diff --git a/app/client/src/pages/Editor/Explorer/Datasources/DatasourceStructureContainer.tsx b/app/client/src/pages/Editor/Explorer/Datasources/DatasourceStructureContainer.tsx
index 955f7c218b51..9a69b4cbe4a9 100644
--- a/app/client/src/pages/Editor/Explorer/Datasources/DatasourceStructureContainer.tsx
+++ b/app/client/src/pages/Editor/Explorer/Datasources/DatasourceStructureContainer.tsx
@@ -1,57 +1,205 @@
import {
createMessage,
+ DATASOURCE_STRUCTURE_INPUT_PLACEHOLDER_TEXT,
SCHEMA_NOT_AVAILABLE,
+ TABLE_OR_COLUMN_NOT_FOUND,
} from "@appsmith/constants/messages";
import type {
DatasourceStructure as DatasourceStructureType,
DatasourceTable,
} from "entities/Datasource";
import type { ReactElement } from "react";
-import React, { memo } from "react";
+import React, { memo, useEffect, useMemo, useState } from "react";
import EntityPlaceholder from "../Entity/Placeholder";
-import { useEntityUpdateState } from "../hooks";
import DatasourceStructure from "./DatasourceStructure";
+import { Input, Text } from "design-system";
+import styled from "styled-components";
+import { getIsFetchingDatasourceStructure } from "selectors/entitiesSelector";
+import { useSelector } from "react-redux";
+import type { AppState } from "@appsmith/reducers";
+import DatasourceStructureLoadingContainer from "./DatasourceStructureLoadingContainer";
+import DatasourceStructureNotFound from "./DatasourceStructureNotFound";
+import AnalyticsUtil from "utils/AnalyticsUtil";
type Props = {
datasourceId: string;
datasourceStructure?: DatasourceStructureType;
step: number;
+ context: DatasourceStructureContext;
+ pluginName?: string;
+ currentActionId?: string;
};
+export enum DatasourceStructureContext {
+ EXPLORER = "entity-explorer",
+ QUERY_EDITOR = "query-editor",
+ // this does not exist yet, but in case it does in the future.
+ API_EDITOR = "api-editor",
+}
+
+const DatasourceStructureSearchContainer = styled.div`
+ margin-bottom: 8px;
+ position: sticky;
+ top: 0;
+ overflow: hidden;
+ z-index: 10;
+ background: white;
+`;
+
const Container = (props: Props) => {
- const isLoading = useEntityUpdateState(props.datasourceId);
- let view: ReactElement<Props> = <div />;
+ const isLoading = useSelector((state: AppState) =>
+ getIsFetchingDatasourceStructure(state, props.datasourceId),
+ );
+ let view: ReactElement<Props> | JSX.Element = <div />;
+
+ const [datasourceStructure, setDatasourceStructure] = useState<
+ DatasourceStructureType | undefined
+ >(props.datasourceStructure);
+ const [hasSearchedOccured, setHasSearchedOccured] = useState(false);
+
+ useEffect(() => {
+ if (datasourceStructure !== props.datasourceStructure) {
+ setDatasourceStructure(props.datasourceStructure);
+ }
+ }, [props.datasourceStructure]);
+
+ const flatStructure = useMemo(() => {
+ if (!props.datasourceStructure?.tables?.length) return [];
+ const list: string[] = [];
+
+ props.datasourceStructure.tables.map((table) => {
+ table.columns.forEach((column) => {
+ list.push(`${table.name}~${column.name}`);
+ });
+ });
+
+ return list;
+ }, [props.datasourceStructure]);
+
+ const handleOnChange = (value: string) => {
+ if (!props.datasourceStructure?.tables?.length) return;
+
+ if (value.length > 0) {
+ !hasSearchedOccured && setHasSearchedOccured(true);
+ } else {
+ hasSearchedOccured && setHasSearchedOccured(false);
+ }
+
+ const tables = new Set();
+ const columns = new Set();
+
+ flatStructure.forEach((structure) => {
+ const segments = structure.split("~");
+ // if the value is present in the columns, add the column and its parent table.
+ if (segments[1].toLowerCase().includes(value)) {
+ tables.add(segments[0]);
+ columns.add(segments[1]);
+ return;
+ }
+
+ // if the value is present in the table but not in the columns, add the table
+ if (segments[0].toLowerCase().includes(value)) {
+ tables.add(segments[0]);
+ return;
+ }
+ });
+
+ const filteredDastasourceStructure = props.datasourceStructure.tables
+ .map((structure) => ({
+ ...structure,
+ columns:
+ // if the size of the columns set is 0, then simply default to the entire column
+ columns.size === 0
+ ? structure.columns
+ : structure.columns.filter((column) => columns.has(column.name)),
+ keys:
+ columns.size === 0
+ ? structure.keys
+ : structure.keys.filter((key) => columns.has(key.name)),
+ }))
+ .filter((table) => tables.has(table.name));
+
+ setDatasourceStructure({ tables: filteredDastasourceStructure });
+
+ AnalyticsUtil.logEvent("DATASOURCE_SCHEMA_SEARCH", {
+ datasourceId: props.datasourceId,
+ pluginName: props.pluginName,
+ });
+ };
if (!isLoading) {
if (props.datasourceStructure?.tables?.length) {
view = (
<>
- {props.datasourceStructure.tables.map(
- (structure: DatasourceTable) => {
+ {props.context !== DatasourceStructureContext.EXPLORER && (
+ <DatasourceStructureSearchContainer>
+ <Input
+ className="datasourceStructure-search"
+ onChange={(value) => handleOnChange(value)}
+ placeholder={createMessage(
+ DATASOURCE_STRUCTURE_INPUT_PLACEHOLDER_TEXT,
+ )}
+ size={"md"}
+ startIcon="search"
+ type="text"
+ />
+ </DatasourceStructureSearchContainer>
+ )}
+ {!!datasourceStructure?.tables?.length &&
+ datasourceStructure.tables.map((structure: DatasourceTable) => {
return (
<DatasourceStructure
+ context={props.context}
+ currentActionId={props.currentActionId || ""}
datasourceId={props.datasourceId}
dbStructure={structure}
- key={`${props.datasourceId}${structure.name}`}
+ forceExpand={hasSearchedOccured}
+ key={`${props.datasourceId}${structure.name}-${props.context}`}
step={props.step + 1}
/>
);
- },
+ })}
+
+ {!datasourceStructure?.tables?.length && (
+ <Text kind="body-s" renderAs="p">
+ {createMessage(TABLE_OR_COLUMN_NOT_FOUND)}
+ </Text>
)}
</>
);
} else {
- view = (
- <EntityPlaceholder step={props.step + 1}>
- {props.datasourceStructure &&
- props.datasourceStructure.error &&
- props.datasourceStructure.error.message &&
- props.datasourceStructure.error.message !== "null"
- ? props.datasourceStructure.error.message
- : createMessage(SCHEMA_NOT_AVAILABLE)}
- </EntityPlaceholder>
- );
+ if (props.context !== DatasourceStructureContext.EXPLORER) {
+ view = (
+ <DatasourceStructureNotFound
+ datasourceId={props.datasourceId}
+ error={
+ !!props.datasourceStructure &&
+ "error" in props.datasourceStructure
+ ? props.datasourceStructure.error
+ : { message: createMessage(SCHEMA_NOT_AVAILABLE) }
+ }
+ pluginName={props?.pluginName || ""}
+ />
+ );
+ } else {
+ view = (
+ <EntityPlaceholder step={props.step + 1}>
+ {props.datasourceStructure &&
+ props.datasourceStructure.error &&
+ props.datasourceStructure.error.message &&
+ props.datasourceStructure.error.message !== "null"
+ ? props.datasourceStructure.error.message
+ : createMessage(SCHEMA_NOT_AVAILABLE)}
+ </EntityPlaceholder>
+ );
+ }
}
+ } else if (
+ // intentionally leaving this here in case we want to show loading states in the explorer or query editor page
+ props.context !== DatasourceStructureContext.EXPLORER &&
+ isLoading
+ ) {
+ view = <DatasourceStructureLoadingContainer />;
}
return view;
diff --git a/app/client/src/pages/Editor/Explorer/Datasources/DatasourceStructureHeader.tsx b/app/client/src/pages/Editor/Explorer/Datasources/DatasourceStructureHeader.tsx
new file mode 100644
index 000000000000..bc3fa6d08998
--- /dev/null
+++ b/app/client/src/pages/Editor/Explorer/Datasources/DatasourceStructureHeader.tsx
@@ -0,0 +1,46 @@
+import React, { useCallback } from "react";
+import { useDispatch } from "react-redux";
+import { Icon, Text } from "design-system";
+import styled from "styled-components";
+import { refreshDatasourceStructure } from "actions/datasourceActions";
+import { SCHEMA_LABEL, createMessage } from "@appsmith/constants/messages";
+import { DatasourceStructureContext } from "./DatasourceStructureContainer";
+
+type Props = {
+ datasourceId: string;
+};
+
+const HeaderWrapper = styled.div`
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ width: 100%;
+`;
+
+export default function DatasourceStructureHeader(props: Props) {
+ const dispatch = useDispatch();
+
+ const dispatchRefresh = useCallback(
+ (event: React.MouseEvent<HTMLDivElement, MouseEvent>) => {
+ event.stopPropagation();
+ dispatch(
+ refreshDatasourceStructure(
+ props.datasourceId,
+ DatasourceStructureContext.QUERY_EDITOR,
+ ),
+ );
+ },
+ [dispatch, props.datasourceId],
+ );
+
+ return (
+ <HeaderWrapper>
+ <Text kind="heading-xs" renderAs="h3">
+ {createMessage(SCHEMA_LABEL)}
+ </Text>
+ <div onClick={(event) => dispatchRefresh(event)}>
+ <Icon name="refresh" size={"md"} />
+ </div>
+ </HeaderWrapper>
+ );
+}
diff --git a/app/client/src/pages/Editor/Explorer/Datasources/DatasourceStructureLoadingContainer.tsx b/app/client/src/pages/Editor/Explorer/Datasources/DatasourceStructureLoadingContainer.tsx
new file mode 100644
index 000000000000..4b81c7bf8ed3
--- /dev/null
+++ b/app/client/src/pages/Editor/Explorer/Datasources/DatasourceStructureLoadingContainer.tsx
@@ -0,0 +1,36 @@
+import React from "react";
+import { createMessage, LOADING_SCHEMA } from "@appsmith/constants/messages";
+import { Spinner, Text } from "design-system";
+import styled from "styled-components";
+
+const LoadingContainer = styled.div`
+ display: flex;
+ flex-direction: row;
+ justify-content: flex-start;
+ align-items: center;
+
+ & > p {
+ margin-left: 0.5rem;
+ }
+`;
+
+const SpinnerWrapper = styled.div`
+ display: flex;
+ justify-content: center;
+ align-items: center;
+`;
+
+const DatasourceStructureLoadingContainer = () => {
+ return (
+ <LoadingContainer>
+ <SpinnerWrapper>
+ <Spinner size={"sm"} />
+ </SpinnerWrapper>
+ <Text kind="body-m" renderAs="p">
+ {createMessage(LOADING_SCHEMA)}
+ </Text>
+ </LoadingContainer>
+ );
+};
+
+export default DatasourceStructureLoadingContainer;
diff --git a/app/client/src/pages/Editor/Explorer/Datasources/DatasourceStructureNotFound.tsx b/app/client/src/pages/Editor/Explorer/Datasources/DatasourceStructureNotFound.tsx
new file mode 100644
index 000000000000..607d456e42e6
--- /dev/null
+++ b/app/client/src/pages/Editor/Explorer/Datasources/DatasourceStructureNotFound.tsx
@@ -0,0 +1,73 @@
+import React from "react";
+import { useSelector } from "react-redux";
+import styled from "styled-components";
+import { Text, Button } from "design-system";
+import type { APIResponseError } from "api/ApiResponses";
+import { EDIT_DATASOURCE, createMessage } from "@appsmith/constants/messages";
+import AnalyticsUtil from "utils/AnalyticsUtil";
+import { DatasourceEditEntryPoints } from "constants/Datasource";
+import history from "utils/history";
+import { getQueryParams } from "utils/URLUtils";
+import { datasourcesEditorIdURL } from "RouteBuilder";
+import { omit } from "lodash";
+import { getCurrentPageId } from "selectors/editorSelectors";
+
+export type Props = {
+ error: APIResponseError | { message: string } | undefined;
+ datasourceId: string;
+ pluginName?: string;
+};
+
+const NotFoundContainer = styled.div`
+ display: flex;
+ height: 100%;
+ width: 100%;
+ flex-direction: column;
+`;
+
+const NotFoundText = styled(Text)`
+ margin-bottom: 1rem;
+ margin-top: 0.3rem;
+`;
+
+const ButtonWrapper = styled.div`
+ width: fit-content;
+`;
+
+const DatasourceStructureNotFound = (props: Props) => {
+ const { datasourceId, error, pluginName } = props;
+
+ const pageId = useSelector(getCurrentPageId);
+
+ const editDatasource = () => {
+ AnalyticsUtil.logEvent("EDIT_DATASOURCE_CLICK", {
+ datasourceId: datasourceId,
+ pluginName: pluginName,
+ entryPoint: DatasourceEditEntryPoints.QUERY_EDITOR_DATASOURCE_SCHEMA,
+ });
+
+ const url = datasourcesEditorIdURL({
+ pageId,
+ datasourceId: datasourceId,
+ params: { ...omit(getQueryParams(), "viewMode"), viewMode: false },
+ });
+ history.push(url);
+ };
+
+ return (
+ <NotFoundContainer>
+ {error?.message && (
+ <NotFoundText kind="body-s" renderAs="p">
+ {error.message}
+ </NotFoundText>
+ )}
+ <ButtonWrapper>
+ <Button kind="secondary" onClick={editDatasource} size={"md"}>
+ {createMessage(EDIT_DATASOURCE)}
+ </Button>
+ </ButtonWrapper>
+ </NotFoundContainer>
+ );
+};
+
+export default DatasourceStructureNotFound;
diff --git a/app/client/src/pages/Editor/Explorer/Datasources/QueryTemplates.tsx b/app/client/src/pages/Editor/Explorer/Datasources/QueryTemplates.tsx
index 4f01fc0de843..14503131945b 100644
--- a/app/client/src/pages/Editor/Explorer/Datasources/QueryTemplates.tsx
+++ b/app/client/src/pages/Editor/Explorer/Datasources/QueryTemplates.tsx
@@ -1,4 +1,4 @@
-import React, { useCallback } from "react";
+import React, { useCallback, useContext } from "react";
import { useDispatch, useSelector } from "react-redux";
import { createActionRequest } from "actions/pluginActionActions";
import type { AppState } from "@appsmith/reducers";
@@ -11,25 +11,66 @@ import type { QueryAction } from "entities/Action";
import history from "utils/history";
import type { Datasource, QueryTemplate } from "entities/Datasource";
import { INTEGRATION_TABS } from "constants/routes";
-import { getDatasource, getPlugin } from "selectors/entitiesSelector";
+import {
+ getAction,
+ getDatasource,
+ getPlugin,
+} from "selectors/entitiesSelector";
import { integrationEditorURL } from "RouteBuilder";
import { MenuItem } from "design-system";
import type { Plugin } from "api/PluginApi";
+import { DatasourceStructureContext } from "./DatasourceStructureContainer";
+import WalkthroughContext from "components/featureWalkthrough/walkthroughContext";
+import { FEATURE_FLAG } from "@appsmith/entities/FeatureFlag";
+import { setFeatureFlagShownStatus } from "utils/storage";
+import styled from "styled-components";
+import { change, getFormValues } from "redux-form";
+import { QUERY_EDITOR_FORM_NAME } from "@appsmith/constants/forms";
+import { diff } from "deep-diff";
+import { UndoRedoToastContext, showUndoRedoToast } from "utils/replayHelpers";
+import AnalyticsUtil from "utils/AnalyticsUtil";
type QueryTemplatesProps = {
templates: QueryTemplate[];
datasourceId: string;
onSelect: () => void;
+ context: DatasourceStructureContext;
+ currentActionId: string;
};
+enum QueryTemplatesEvent {
+ EXPLORER_TEMPLATE = "explorer-template",
+ QUERY_EDITOR_TEMPLATE = "query-editor-template",
+}
+
+const TemplateMenuItem = styled(MenuItem)`
+ & > span {
+ text-transform: lowercase;
+ }
+
+ & > span:first-letter {
+ text-transform: capitalize;
+ }
+`;
+
export function QueryTemplates(props: QueryTemplatesProps) {
const dispatch = useDispatch();
+ const { isOpened: isWalkthroughOpened, popFeature } =
+ useContext(WalkthroughContext) || {};
const applicationId = useSelector(getCurrentApplicationId);
const actions = useSelector((state: AppState) => state.entities.actions);
const currentPageId = useSelector(getCurrentPageId);
const dataSource: Datasource | undefined = useSelector((state: AppState) =>
getDatasource(state, props.datasourceId),
);
+
+ const currentAction = useSelector((state) =>
+ getAction(state, props.currentActionId),
+ );
+ const formName = QUERY_EDITOR_FORM_NAME;
+
+ const formValues = useSelector((state) => getFormValues(formName)(state));
+
const plugin: Plugin | undefined = useSelector((state: AppState) =>
getPlugin(state, !!dataSource?.pluginId ? dataSource.pluginId : ""),
);
@@ -55,14 +96,24 @@ export function QueryTemplates(props: QueryTemplatesProps) {
},
eventData: {
actionType: "Query",
- from: "explorer-template",
+ from:
+ props?.context === DatasourceStructureContext.EXPLORER
+ ? QueryTemplatesEvent.EXPLORER_TEMPLATE
+ : QueryTemplatesEvent.QUERY_EDITOR_TEMPLATE,
dataSource: dataSource?.name,
datasourceId: props.datasourceId,
pluginName: plugin?.name,
+ queryType: template.title,
},
...queryactionConfiguration,
}),
);
+
+ if (isWalkthroughOpened) {
+ popFeature && popFeature();
+ setFeatureFlagShownStatus(FEATURE_FLAG.ab_ds_schema_enabled, true);
+ }
+
history.push(
integrationEditorURL({
pageId: currentPageId,
@@ -80,19 +131,84 @@ export function QueryTemplates(props: QueryTemplatesProps) {
],
);
+ const updateQueryAction = useCallback(
+ (template: QueryTemplate) => {
+ if (!currentAction) return;
+
+ const queryactionConfiguration: Partial<QueryAction> = {
+ actionConfiguration: {
+ body: template.body,
+ pluginSpecifiedTemplates: template.pluginSpecifiedTemplates,
+ formData: template.configuration,
+ ...template.actionConfiguration,
+ },
+ };
+
+ const newFormValueState = {
+ ...formValues,
+ ...queryactionConfiguration,
+ };
+
+ const differences = diff(formValues, newFormValueState) || [];
+
+ differences.forEach((diff) => {
+ if (diff.kind === "E" || diff.kind === "N") {
+ const path = diff?.path?.join(".") || "";
+ const value = diff?.rhs;
+
+ if (path) {
+ dispatch(change(QUERY_EDITOR_FORM_NAME, path, value));
+ }
+ }
+ });
+
+ AnalyticsUtil.logEvent("AUTOMATIC_QUERY_GENERATION", {
+ datasourceId: props.datasourceId,
+ pluginName: plugin?.name || "",
+ templateCommand: template?.title,
+ isWalkthroughOpened,
+ });
+
+ if (isWalkthroughOpened) {
+ popFeature && popFeature();
+ setFeatureFlagShownStatus(FEATURE_FLAG.ab_ds_schema_enabled, true);
+ }
+
+ showUndoRedoToast(
+ currentAction.name,
+ false,
+ false,
+ true,
+ UndoRedoToastContext.QUERY_TEMPLATES,
+ );
+ },
+ [
+ dispatch,
+ actions,
+ currentPageId,
+ applicationId,
+ props.datasourceId,
+ dataSource,
+ ],
+ );
+
return (
<>
{props.templates.map((template) => {
return (
- <MenuItem
+ <TemplateMenuItem
key={template.title}
onSelect={() => {
- createQueryAction(template);
+ if (props.currentActionId) {
+ updateQueryAction(template);
+ } else {
+ createQueryAction(template);
+ }
props.onSelect();
}}
>
{template.title}
- </MenuItem>
+ </TemplateMenuItem>
);
})}
</>
diff --git a/app/client/src/pages/Editor/Explorer/Entity/index.tsx b/app/client/src/pages/Editor/Explorer/Entity/index.tsx
index d302f48aca6b..4dced477904e 100644
--- a/app/client/src/pages/Editor/Explorer/Entity/index.tsx
+++ b/app/client/src/pages/Editor/Explorer/Entity/index.tsx
@@ -255,7 +255,7 @@ export type EntityProps = {
export const Entity = forwardRef(
(props: EntityProps, ref: React.Ref<HTMLDivElement>) => {
const isEntityOpen = useSelector((state: AppState) =>
- getEntityCollapsibleState(state, props.name),
+ getEntityCollapsibleState(state, props.entityId),
);
const isDefaultExpanded = useMemo(() => !!props.isDefaultExpanded, []);
const { canEditEntityName = false, showAddButton = false } = props;
@@ -270,7 +270,7 @@ export const Entity = forwardRef(
const open = (shouldOpen: boolean | undefined) => {
if (!!props.children && props.name && isOpen !== shouldOpen) {
- dispatch(setEntityCollapsibleState(props.name, !!shouldOpen));
+ dispatch(setEntityCollapsibleState(props.entityId, !!shouldOpen));
}
};
diff --git a/app/client/src/pages/Editor/Explorer/Files/index.tsx b/app/client/src/pages/Editor/Explorer/Files/index.tsx
index 8128823b9360..7199240b8ab0 100644
--- a/app/client/src/pages/Editor/Explorer/Files/index.tsx
+++ b/app/client/src/pages/Editor/Explorer/Files/index.tsx
@@ -118,13 +118,13 @@ function Files() {
openMenu={isMenuOpen}
/>
}
- entityId={pageId + "_widgets"}
+ entityId={pageId + "_actions"}
icon={null}
isDefaultExpanded={
- isFilesOpen === null || isFilesOpen === undefined ? false : isFilesOpen
+ isFilesOpen === null || isFilesOpen === undefined ? true : isFilesOpen
}
isSticky
- key={pageId + "_widgets"}
+ key={pageId + "_actions"}
name="Queries/JS"
onCreate={onCreate}
onToggle={onFilesToggle}
diff --git a/app/client/src/pages/Editor/Explorer/Libraries/index.tsx b/app/client/src/pages/Editor/Explorer/Libraries/index.tsx
index 4b2789da67a9..22828a03e8ba 100644
--- a/app/client/src/pages/Editor/Explorer/Libraries/index.tsx
+++ b/app/client/src/pages/Editor/Explorer/Libraries/index.tsx
@@ -22,7 +22,10 @@ import {
} from "actions/JSLibraryActions";
import EntityAddButton from "../Entity/AddButton";
import type { TJSLibrary } from "workers/common/JSLibrary";
-import { getPagePermissions } from "selectors/editorSelectors";
+import {
+ getCurrentPageId,
+ getPagePermissions,
+} from "selectors/editorSelectors";
import { hasCreateActionPermission } from "@appsmith/utils/permissionHelpers";
import recommendedLibraries from "./recommendedLibraries";
import { useTransition, animated } from "react-spring";
@@ -266,6 +269,7 @@ function LibraryEntity({ lib }: { lib: TJSLibrary }) {
}
function JSDependencies() {
+ const pageId = useSelector(getCurrentPageId) || "";
const libraries = useSelector(selectLibrariesForExplorer);
const transitions = useTransition(libraries, {
keys: (lib) => lib.name,
@@ -311,7 +315,7 @@ function JSDependencies() {
</AddButtonWrapper>
</Tooltip>
}
- entityId="library_section"
+ entityId={pageId + "_library_section"}
icon={null}
isDefaultExpanded={isOpen}
isSticky
diff --git a/app/client/src/pages/Editor/Explorer/hooks.ts b/app/client/src/pages/Editor/Explorer/hooks.ts
index 364e92fe1d13..3502f52e22e0 100644
--- a/app/client/src/pages/Editor/Explorer/hooks.ts
+++ b/app/client/src/pages/Editor/Explorer/hooks.ts
@@ -345,9 +345,8 @@ export const useFilteredEntities = (
};
export const useEntityUpdateState = (entityId: string) => {
- return useSelector(
- (state: AppState) =>
- get(state, "ui.explorer.entity.updatingEntity") === entityId,
+ return useSelector((state: AppState) =>
+ get(state, "ui.explorer.entity.updatingEntity")?.includes(entityId),
);
};
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 8d5b8f44e4bc..6ee2bf26c49b 100644
--- a/app/client/src/pages/Editor/GeneratePage/components/GeneratePageForm/GeneratePageForm.tsx
+++ b/app/client/src/pages/Editor/GeneratePage/components/GeneratePageForm/GeneratePageForm.tsx
@@ -231,10 +231,6 @@ function GeneratePageForm() {
useState<string>("");
const datasourcesStructure = useSelector(getDatasourcesStructure);
- const isFetchingDatasourceStructure = useSelector(
- getIsFetchingDatasourceStructure,
- );
-
const generateCRUDSupportedPlugin: GenerateCRUDEnabledPluginMap = useSelector(
getGenerateCRUDEnabledPluginMap,
);
@@ -249,6 +245,10 @@ function GeneratePageForm() {
DEFAULT_DROPDOWN_OPTION,
);
+ const isFetchingDatasourceStructure = useSelector((state: AppState) =>
+ getIsFetchingDatasourceStructure(state, selectedDatasource.id || ""),
+ );
+
const [isSelectedTableEmpty, setIsSelectedTableEmpty] =
useState<boolean>(false);
diff --git a/app/client/src/pages/Editor/GuidedTour/utils.ts b/app/client/src/pages/Editor/GuidedTour/utils.ts
index 5ce5fe4c06e4..685feb86d6f7 100644
--- a/app/client/src/pages/Editor/GuidedTour/utils.ts
+++ b/app/client/src/pages/Editor/GuidedTour/utils.ts
@@ -59,7 +59,12 @@ class IndicatorHelper {
this.indicatorWidthOffset +
"px";
} else if (position === "bottom") {
- this.indicatorWrapper.style.top = coordinates.height + offset.top + "px";
+ this.indicatorWrapper.style.top =
+ coordinates.top +
+ coordinates.height -
+ this.indicatorHeightOffset +
+ offset.top +
+ "px";
this.indicatorWrapper.style.left =
coordinates.width / 2 +
coordinates.left -
@@ -68,7 +73,7 @@ class IndicatorHelper {
"px";
} else if (position === "left") {
this.indicatorWrapper.style.top =
- coordinates.top + this.indicatorHeightOffset + offset.top + "px";
+ coordinates.top - this.indicatorHeightOffset + offset.top + "px";
this.indicatorWrapper.style.left =
coordinates.left - this.indicatorWidthOffset + offset.left + "px";
} else {
@@ -90,6 +95,7 @@ class IndicatorHelper {
offset: {
top: number;
left: number;
+ zIndex?: number;
},
) {
if (this.timerId || this.indicatorWrapper) this.destroy();
@@ -111,6 +117,9 @@ class IndicatorHelper {
loop: true,
});
+ if (offset.zIndex) {
+ this.indicatorWrapper.style.zIndex = `${offset.zIndex}`;
+ }
// This is to invoke at the start and then recalculate every 3 seconds
// 3 seconds is an arbitrary value here to avoid calling getBoundingClientRect to many times
this.calculate(primaryReference, position, offset);
@@ -237,7 +246,7 @@ export function highlightSection(
export function showIndicator(
selector: string,
position = "right",
- offset = { top: 0, left: 0 },
+ offset: { top: number; left: number; zIndex?: number } = { top: 0, left: 0 },
) {
let primaryReference: Element | null = null;
diff --git a/app/client/src/pages/Editor/QueryEditor/EditorJSONtoForm.tsx b/app/client/src/pages/Editor/QueryEditor/EditorJSONtoForm.tsx
index e27ccf6a6e38..1516d1d0fb01 100644
--- a/app/client/src/pages/Editor/QueryEditor/EditorJSONtoForm.tsx
+++ b/app/client/src/pages/Editor/QueryEditor/EditorJSONtoForm.tsx
@@ -9,7 +9,12 @@ import {
getPluginNameFromId,
} from "selectors/entitiesSelector";
import FormControl from "../FormControl";
-import type { Action, QueryAction, SaaSAction } from "entities/Action";
+import {
+ PluginName,
+ type Action,
+ type QueryAction,
+ type SaaSAction,
+} from "entities/Action";
import { useDispatch, useSelector } from "react-redux";
import ActionNameEditor from "components/editorComponents/ActionNameEditor";
import DropdownField from "components/editorComponents/form/fields/DropdownField";
@@ -126,6 +131,9 @@ import { ENTITY_TYPE as SOURCE_ENTITY_TYPE } from "entities/AppsmithConsole";
import { DocsLink, openDoc } from "../../../constants/DocumentationLinks";
import ActionExecutionInProgressView from "components/editorComponents/ActionExecutionInProgressView";
import { CloseDebugger } from "components/editorComponents/Debugger/DebuggerTabs";
+import { DatasourceStructureContext } from "../Explorer/Datasources/DatasourceStructureContainer";
+import { selectFeatureFlagCheck } from "selectors/featureFlagsSelectors";
+import { FEATURE_FLAG } from "@appsmith/entities/FeatureFlag";
const QueryFormContainer = styled.form`
flex: 1;
@@ -304,12 +312,12 @@ const DocumentationButton = styled(Button)`
const SidebarWrapper = styled.div<{ show: boolean }>`
border-left: 1px solid var(--ads-v2-color-border);
- padding: 0 var(--ads-v2-spaces-7) var(--ads-v2-spaces-7);
- overflow: auto;
+ padding: 0 var(--ads-v2-spaces-4) var(--ads-v2-spaces-4);
+ overflow: hidden;
border-bottom: 0;
display: ${(props) => (props.show ? "flex" : "none")};
width: ${(props) => props.theme.actionSidePane.width}px;
- margin-top: 38px;
+ margin-top: 10px;
/* margin-left: var(--ads-v2-spaces-7); */
`;
@@ -354,6 +362,7 @@ type QueryFormProps = {
id,
value,
}: UpdateActionPropertyActionPayload) => void;
+ datasourceId: string;
};
type ReduxProps = {
@@ -870,6 +879,23 @@ export function EditorJSONtoForm(props: Props) {
//TODO: move this to a common place
const onClose = () => dispatch(showDebugger(false));
+ // A/B feature flag for datasource structure.
+ const isEnabledForDSSchema = useSelector((state) =>
+ selectFeatureFlagCheck(state, FEATURE_FLAG.ab_ds_schema_enabled),
+ );
+
+ // A/B feature flag for query binding.
+ const isEnabledForQueryBinding = useSelector((state) =>
+ selectFeatureFlagCheck(state, FEATURE_FLAG.ab_ds_binding_enabled),
+ );
+
+ // here we check for normal conditions for opening action pane
+ // or if any of the flags are true, We should open the actionpane by default.
+ const shouldOpenActionPaneByDefault =
+ ((hasDependencies || !!output) && !guidedTourEnabled) ||
+ ((isEnabledForDSSchema || isEnabledForQueryBinding) &&
+ currentActionPluginName !== PluginName.SMTP);
+
// when switching between different redux forms, make sure this redux form has been initialized before rendering anything.
// the initialized prop below comes from redux-form.
if (!props.initialized) {
@@ -1070,14 +1096,15 @@ export function EditorJSONtoForm(props: Props) {
)}
</SecondaryWrapper>
</div>
- <SidebarWrapper
- show={(hasDependencies || !!output) && !guidedTourEnabled}
- >
+ <SidebarWrapper show={shouldOpenActionPaneByDefault}>
<ActionRightPane
actionName={actionName}
+ context={DatasourceStructureContext.QUERY_EDITOR}
+ datasourceId={props.datasourceId}
entityDependencies={entityDependencies}
hasConnections={hasDependencies}
hasResponse={!!output}
+ pluginId={props.pluginId}
suggestedWidgets={executedQueryData?.suggestedWidgets}
/>
</SidebarWrapper>
diff --git a/app/client/src/pages/Editor/QueryEditor/index.tsx b/app/client/src/pages/Editor/QueryEditor/index.tsx
index f6fb8d8e9131..020276eedec7 100644
--- a/app/client/src/pages/Editor/QueryEditor/index.tsx
+++ b/app/client/src/pages/Editor/QueryEditor/index.tsx
@@ -252,6 +252,7 @@ class QueryEditor extends React.Component<Props> {
return (
<QueryEditorForm
dataSources={dataSources}
+ datasourceId={this.props.datasourceId}
editorConfig={editorConfig}
executedQueryData={responses[actionId]}
formData={this.props.formData}
@@ -261,6 +262,7 @@ class QueryEditor extends React.Component<Props> {
onCreateDatasourceClick={this.onCreateDatasourceClick}
onDeleteClick={this.handleDeleteClick}
onRunClick={this.handleRunClick}
+ pluginId={this.props.pluginId}
runErrorMessage={runErrorMessage[actionId]}
settingConfig={settingConfig}
uiComponent={uiComponent}
diff --git a/app/client/src/pages/Editor/SaaSEditor/DatasourceForm.tsx b/app/client/src/pages/Editor/SaaSEditor/DatasourceForm.tsx
index 3482b3f17b8f..5b25436e52c5 100644
--- a/app/client/src/pages/Editor/SaaSEditor/DatasourceForm.tsx
+++ b/app/client/src/pages/Editor/SaaSEditor/DatasourceForm.tsx
@@ -437,6 +437,7 @@ class DatasourceSaaSEditor extends JSONtoForm<Props, State> {
e.preventDefault();
}}
showFilterComponent={false}
+ viewMode={viewMode}
>
{(!viewMode || createFlow || isInsideReconnectModal) && (
<>
diff --git a/app/client/src/pages/Editor/utils.ts b/app/client/src/pages/Editor/utils.ts
index 3d3ec92d56c5..c2a3d2b5440d 100644
--- a/app/client/src/pages/Editor/utils.ts
+++ b/app/client/src/pages/Editor/utils.ts
@@ -1,5 +1,5 @@
import { getDependenciesFromInverseDependencies } from "components/editorComponents/Debugger/helpers";
-import _, { debounce } from "lodash";
+import _, { debounce, random } from "lodash";
import { useEffect, useMemo, useState } from "react";
import ReactDOM from "react-dom";
import { useLocation } from "react-router";
@@ -296,3 +296,12 @@ export function useHref<T extends URLBuilderParams>(
return href;
}
+
+// Ended up not using it, but leaving it here, incase anyone needs a helper function to generate random numbers.
+export const generateRandomNumbers = (
+ lowerBound = 1000,
+ upperBound = 9000,
+ allowFloating = false,
+) => {
+ return random(lowerBound, upperBound, allowFloating);
+};
diff --git a/app/client/src/pages/setup/SignupSuccess.tsx b/app/client/src/pages/setup/SignupSuccess.tsx
index 3d49fe218bbb..1429a067ab44 100644
--- a/app/client/src/pages/setup/SignupSuccess.tsx
+++ b/app/client/src/pages/setup/SignupSuccess.tsx
@@ -14,6 +14,7 @@ import { Center } from "pages/setup/common";
import { Spinner } from "design-system";
import { isValidLicense } from "@appsmith/selectors/tenantSelectors";
import { redirectUserAfterSignup } from "@appsmith/utils/signupHelpers";
+import { setUserSignedUpFlag } from "utils/storage";
export function SignupSuccess() {
const dispatch = useDispatch();
@@ -23,8 +24,11 @@ export function SignupSuccess() {
"enableFirstTimeUserExperience",
);
const validLicense = useSelector(isValidLicense);
+ const user = useSelector(getCurrentUser);
+
useEffect(() => {
PerformanceTracker.stopTracking(PerformanceTransactionName.SIGN_UP);
+ user?.email && setUserSignedUpFlag(user?.email);
}, []);
const redirectUsingQueryParam = useCallback(
@@ -49,7 +53,6 @@ export function SignupSuccess() {
redirectUsingQueryParam();
}, []);
- const user = useSelector(getCurrentUser);
const { cloudHosting } = getAppsmithConfigs();
const isCypressEnv = !!(window as any).Cypress;
diff --git a/app/client/src/reducers/entityReducers/datasourceReducer.ts b/app/client/src/reducers/entityReducers/datasourceReducer.ts
index a1ab5cb1a24c..16aa383b7de1 100644
--- a/app/client/src/reducers/entityReducers/datasourceReducer.ts
+++ b/app/client/src/reducers/entityReducers/datasourceReducer.ts
@@ -20,8 +20,7 @@ export interface DatasourceDataState {
loading: boolean;
isTesting: boolean;
isListing: boolean; // fetching unconfigured datasource list
- fetchingDatasourceStructure: boolean;
- isRefreshingStructure: boolean;
+ fetchingDatasourceStructure: Record<string, boolean>;
structure: Record<string, DatasourceStructure>;
isFetchingMockDataSource: false;
mockDatasourceList: any[];
@@ -48,8 +47,7 @@ const initialState: DatasourceDataState = {
loading: false,
isTesting: false,
isListing: false,
- fetchingDatasourceStructure: false,
- isRefreshingStructure: false,
+ fetchingDatasourceStructure: {},
structure: {},
isFetchingMockDataSource: false,
mockDatasourceList: [],
@@ -143,8 +141,15 @@ const datasourceReducer = createReducer(initialState, {
},
[ReduxActionTypes.REFRESH_DATASOURCE_STRUCTURE_INIT]: (
state: DatasourceDataState,
+ action: ReduxAction<{ id: string }>,
) => {
- return { ...state, isRefreshingStructure: true };
+ return {
+ ...state,
+ fetchingDatasourceStructure: {
+ ...state.fetchingDatasourceStructure,
+ [action.payload.id]: true,
+ },
+ };
},
[ReduxActionTypes.EXECUTE_DATASOURCE_QUERY_INIT]: (
state: DatasourceDataState,
@@ -158,8 +163,15 @@ const datasourceReducer = createReducer(initialState, {
},
[ReduxActionTypes.FETCH_DATASOURCE_STRUCTURE_INIT]: (
state: DatasourceDataState,
+ action: ReduxAction<{ id: string }>,
) => {
- return { ...state, fetchingDatasourceStructure: true };
+ return {
+ ...state,
+ fetchingDatasourceStructure: {
+ ...state.fetchingDatasourceStructure,
+ [action.payload.id]: true,
+ },
+ };
},
[ReduxActionTypes.FETCH_DATASOURCE_STRUCTURE_SUCCESS]: (
state: DatasourceDataState,
@@ -167,7 +179,10 @@ const datasourceReducer = createReducer(initialState, {
) => {
return {
...state,
- fetchingDatasourceStructure: false,
+ fetchingDatasourceStructure: {
+ ...state.fetchingDatasourceStructure,
+ [action.payload.datasourceId]: false,
+ },
structure: {
...state.structure,
[action.payload.datasourceId]: action.payload.data,
@@ -180,7 +195,10 @@ const datasourceReducer = createReducer(initialState, {
) => {
return {
...state,
- isRefreshingStructure: false,
+ fetchingDatasourceStructure: {
+ ...state.fetchingDatasourceStructure,
+ [action.payload.datasourceId]: false,
+ },
structure: {
...state.structure,
[action.payload.datasourceId]: action.payload.data,
@@ -189,10 +207,14 @@ const datasourceReducer = createReducer(initialState, {
},
[ReduxActionErrorTypes.FETCH_DATASOURCE_STRUCTURE_ERROR]: (
state: DatasourceDataState,
+ action: ReduxAction<{ datasourceId: string }>,
) => {
return {
...state,
- fetchingDatasourceStructure: false,
+ fetchingDatasourceStructure: {
+ ...state.fetchingDatasourceStructure,
+ [action.payload.datasourceId]: false,
+ },
};
},
[ReduxActionTypes.FETCH_DATASOURCES_SUCCESS]: (
@@ -464,10 +486,14 @@ const datasourceReducer = createReducer(initialState, {
},
[ReduxActionErrorTypes.REFRESH_DATASOURCE_STRUCTURE_ERROR]: (
state: DatasourceDataState,
+ action: ReduxAction<{ datasourceId: string }>,
) => {
return {
...state,
- isRefreshingStructure: false,
+ fetchingDatasourceStructure: {
+ ...state.fetchingDatasourceStructure,
+ [action.payload.datasourceId]: false,
+ },
};
},
[ReduxActionErrorTypes.EXECUTE_DATASOURCE_QUERY_ERROR]: (
diff --git a/app/client/src/sagas/DatasourcesSagas.ts b/app/client/src/sagas/DatasourcesSagas.ts
index 8b9a2000f987..f99460a63ff2 100644
--- a/app/client/src/sagas/DatasourcesSagas.ts
+++ b/app/client/src/sagas/DatasourcesSagas.ts
@@ -150,6 +150,7 @@ import {
isGoogleSheetPluginDS,
} from "utils/editorContextUtils";
import { getDefaultEnvId } from "@appsmith/api/ApiUtils";
+import type { DatasourceStructureContext } from "pages/Editor/Explorer/Datasources/DatasourceStructureContainer";
function* fetchDatasourcesSaga(
action: ReduxAction<{ workspaceId?: string } | undefined>,
@@ -1173,17 +1174,19 @@ function* updateDatasourceSuccessSaga(action: UpdateDatasourceSuccessAction) {
}
function* fetchDatasourceStructureSaga(
- action: ReduxAction<{ id: string; ignoreCache: boolean }>,
+ action: ReduxAction<{
+ id: string;
+ ignoreCache: boolean;
+ schemaFetchContext: DatasourceStructureContext;
+ }>,
) {
const datasource = shouldBeDefined<Datasource>(
yield select(getDatasource, action.payload.id),
`Datasource not found for id - ${action.payload.id}`,
);
const plugin: Plugin = yield select(getPlugin, datasource?.pluginId);
- AnalyticsUtil.logEvent("DATASOURCE_SCHEMA_FETCH", {
- datasourceId: datasource?.id,
- pluginName: plugin?.name,
- });
+ let errorMessage = "";
+ let isSuccess = false;
try {
const response: ApiResponse = yield DatasourcesApi.fetchDatasourceStructure(
@@ -1201,11 +1204,7 @@ function* fetchDatasourceStructureSaga(
});
if (isEmpty(response.data)) {
- AnalyticsUtil.logEvent("DATASOURCE_SCHEMA_FETCH_FAILURE", {
- datasourceId: datasource?.id,
- pluginName: plugin?.name,
- errorMessage: createMessage(DATASOURCE_SCHEMA_NOT_AVAILABLE),
- });
+ errorMessage = createMessage(DATASOURCE_SCHEMA_NOT_AVAILABLE);
AppsmithConsole.warning({
text: "Datasource structure could not be retrieved",
source: {
@@ -1215,10 +1214,7 @@ function* fetchDatasourceStructureSaga(
},
});
} else {
- AnalyticsUtil.logEvent("DATASOURCE_SCHEMA_FETCH_SUCCESS", {
- datasourceId: datasource?.id,
- pluginName: plugin?.name,
- });
+ isSuccess = true;
AppsmithConsole.info({
text: "Datasource structure retrieved",
source: {
@@ -1229,25 +1225,17 @@ function* fetchDatasourceStructureSaga(
});
}
if (!!(response.data as any)?.error) {
- AnalyticsUtil.logEvent("DATASOURCE_SCHEMA_FETCH_FAILURE", {
- datasourceId: datasource?.id,
- pluginName: plugin?.name,
- errorCode: (response.data as any).error?.code,
- errorMessage: (response.data as any).error?.message,
- });
+ errorMessage = (response.data as any).error?.message;
}
}
} catch (error) {
- AnalyticsUtil.logEvent("DATASOURCE_SCHEMA_FETCH_FAILURE", {
- datasourceId: datasource?.id,
- pluginName: plugin?.name,
- errorMessage: (error as any)?.message,
- });
+ errorMessage = (error as any)?.message;
yield put({
type: ReduxActionErrorTypes.FETCH_DATASOURCE_STRUCTURE_ERROR,
payload: {
error,
show: false,
+ datasourceId: action.payload.id,
},
});
AppsmithConsole.error({
@@ -1259,6 +1247,13 @@ function* fetchDatasourceStructureSaga(
},
});
}
+ AnalyticsUtil.logEvent("DATASOURCE_SCHEMA_FETCH", {
+ datasourceId: datasource?.id,
+ pluginName: plugin?.name,
+ errorMessage: errorMessage,
+ isSuccess: isSuccess,
+ source: action.payload.schemaFetchContext,
+ });
}
function* addAndFetchDatasourceStructureSaga(
@@ -1291,16 +1286,19 @@ function* addAndFetchDatasourceStructureSaga(
}
}
-function* refreshDatasourceStructure(action: ReduxAction<{ id: string }>) {
+function* refreshDatasourceStructure(
+ action: ReduxAction<{
+ id: string;
+ schemaRefreshContext: DatasourceStructureContext;
+ }>,
+) {
const datasource = shouldBeDefined<Datasource>(
yield select(getDatasource, action.payload.id),
`Datasource is not found for it - ${action.payload.id}`,
);
const plugin: Plugin = yield select(getPlugin, datasource?.pluginId);
- AnalyticsUtil.logEvent("DATASOURCE_SCHEMA_FETCH", {
- datasourceId: datasource?.id,
- pluginName: plugin?.name,
- });
+ let errorMessage = "";
+ let isSuccess = false;
try {
const response: ApiResponse = yield DatasourcesApi.fetchDatasourceStructure(
@@ -1318,11 +1316,7 @@ function* refreshDatasourceStructure(action: ReduxAction<{ id: string }>) {
});
if (isEmpty(response.data)) {
- AnalyticsUtil.logEvent("DATASOURCE_SCHEMA_FETCH_FAILURE", {
- datasourceId: datasource?.id,
- pluginName: plugin?.name,
- errorMessage: createMessage(DATASOURCE_SCHEMA_NOT_AVAILABLE),
- });
+ errorMessage = createMessage(DATASOURCE_SCHEMA_NOT_AVAILABLE);
AppsmithConsole.warning({
text: "Datasource structure could not be retrieved",
source: {
@@ -1332,10 +1326,7 @@ function* refreshDatasourceStructure(action: ReduxAction<{ id: string }>) {
},
});
} else {
- AnalyticsUtil.logEvent("DATASOURCE_SCHEMA_FETCH_SUCCESS", {
- datasourceId: datasource?.id,
- pluginName: plugin?.name,
- });
+ isSuccess = true;
AppsmithConsole.info({
text: "Datasource structure retrieved",
source: {
@@ -1346,25 +1337,17 @@ function* refreshDatasourceStructure(action: ReduxAction<{ id: string }>) {
});
}
if (!!(response.data as any)?.error) {
- AnalyticsUtil.logEvent("DATASOURCE_SCHEMA_FETCH_FAILURE", {
- datasourceId: datasource?.id,
- pluginName: plugin?.name,
- errorCode: (response.data as any).error?.code,
- errorMessage: (response.data as any).error?.message,
- });
+ errorMessage = (response.data as any)?.message;
}
}
} catch (error) {
- AnalyticsUtil.logEvent("DATASOURCE_SCHEMA_FETCH_FAILURE", {
- datasourceId: datasource?.id,
- pluginName: plugin?.name,
- errorMessage: (error as any)?.message,
- });
+ errorMessage = (error as any)?.message;
yield put({
type: ReduxActionErrorTypes.REFRESH_DATASOURCE_STRUCTURE_ERROR,
payload: {
error,
show: false,
+ datasourceId: action.payload.id,
},
});
AppsmithConsole.error({
@@ -1376,6 +1359,14 @@ function* refreshDatasourceStructure(action: ReduxAction<{ id: string }>) {
},
});
}
+
+ AnalyticsUtil.logEvent("DATASOURCE_SCHEMA_FETCH", {
+ datasourceId: datasource?.id,
+ pluginName: plugin?.name,
+ errorMessage: errorMessage,
+ isSuccess: isSuccess,
+ source: action.payload.schemaRefreshContext,
+ });
}
function* executeDatasourceQuerySaga(
diff --git a/app/client/src/sagas/ReplaySaga.ts b/app/client/src/sagas/ReplaySaga.ts
index e723ad5fa9fe..bdad4bbe4824 100644
--- a/app/client/src/sagas/ReplaySaga.ts
+++ b/app/client/src/sagas/ReplaySaga.ts
@@ -46,8 +46,10 @@ import {
} from "./EvaluationsSaga";
import { createBrowserHistory } from "history";
import {
+ getDatasource,
getEditorConfig,
getPluginForm,
+ getPlugins,
getSettingConfig,
} from "selectors/entitiesSelector";
import type { Action } from "entities/Action";
@@ -73,6 +75,11 @@ import {
import { AppThemingMode } from "selectors/appThemingSelectors";
import { generateAutoHeightLayoutTreeAction } from "actions/autoHeightActions";
import { SelectionRequestType } from "sagas/WidgetSelectUtils";
+import { startFormEvaluations } from "actions/evaluationActions";
+import { getCurrentEnvironment } from "@appsmith/utils/Environments";
+import { getUIComponent } from "pages/Editor/QueryEditor/helpers";
+import type { Plugin } from "api/PluginApi";
+import { UIComponentTypes } from "api/PluginApi";
export type UndoRedoPayload = {
operation: ReplayReduxActionTypes;
@@ -309,18 +316,49 @@ function* replayActionSaga(
/**
* Update all the diffs in the action object.
* We need this for debugger logs, dynamicBindingPathList and to call relevant APIs */
+
+ const currentEnvironment = getCurrentEnvironment();
+ const plugins: Plugin[] = yield select(getPlugins);
+ const uiComponent = getUIComponent(replayEntity.pluginId, plugins);
+ const datasource: Datasource | undefined = yield select(
+ getDatasource,
+ replayEntity.datasource?.id || "",
+ );
+
yield all(
- updates.map((u) =>
- put(
- setActionProperty({
- actionId: replayEntity.id,
- propertyName: u.modifiedProperty,
- value:
- u.kind === "A" ? _.get(replayEntity, u.modifiedProperty) : u.update,
- skipSave: true,
- }),
- ),
- ),
+ updates.map((u) => {
+ // handle evaluations after update.
+ const postEvalActions =
+ uiComponent === UIComponentTypes.UQIDbEditorForm
+ ? [
+ startFormEvaluations(
+ replayEntity.id,
+ replayEntity.actionConfiguration,
+ replayEntity.datasource.id || "",
+ replayEntity.pluginId,
+ u.modifiedProperty,
+ true,
+ datasource?.datasourceStorages[currentEnvironment]
+ .datasourceConfiguration,
+ ),
+ ]
+ : [];
+
+ return put(
+ setActionProperty(
+ {
+ actionId: replayEntity.id,
+ propertyName: u.modifiedProperty,
+ value:
+ u.kind === "A"
+ ? _.get(replayEntity, u.modifiedProperty)
+ : u.update,
+ skipSave: true,
+ },
+ postEvalActions,
+ ),
+ );
+ }),
);
//Save the updated action object
diff --git a/app/client/src/sagas/SnipingModeSagas.ts b/app/client/src/sagas/SnipingModeSagas.ts
index 00d79ea7c7f8..a79f3e3ba7c1 100644
--- a/app/client/src/sagas/SnipingModeSagas.ts
+++ b/app/client/src/sagas/SnipingModeSagas.ts
@@ -21,6 +21,11 @@ import { setSnipingMode } from "actions/propertyPaneActions";
import { selectWidgetInitAction } from "actions/widgetSelectionActions";
import { SelectionRequestType } from "sagas/WidgetSelectUtils";
import { toast } from "design-system";
+import {
+ AB_TESTING_EVENT_KEYS,
+ FEATURE_FLAG,
+} from "@appsmith/entities/FeatureFlag";
+import { selectFeatureFlagCheck } from "selectors/featureFlagsSelectors";
const WidgetTypes = WidgetFactory.widgetTypes;
@@ -36,6 +41,10 @@ export function* bindDataToWidgetSaga(
),
);
const widgetState: CanvasWidgetsReduxState = yield select(getCanvasWidgets);
+ const isDSBindingEnabled: boolean = yield select(
+ selectFeatureFlagCheck,
+ FEATURE_FLAG.ab_ds_binding_enabled,
+ );
const selectedWidget = widgetState[action.payload.widgetId];
if (!selectedWidget || !selectedWidget.type) {
@@ -149,6 +158,9 @@ export function* bindDataToWidgetSaga(
apiId: queryId,
propertyPath,
propertyValue,
+ [AB_TESTING_EVENT_KEYS.abTestingFlagLabel]:
+ FEATURE_FLAG.ab_ds_binding_enabled,
+ [AB_TESTING_EVENT_KEYS.abTestingFlagValue]: isDSBindingEnabled,
});
if (queryId && isValidProperty) {
// set the property path to dynamic, i.e. enable JS mode
diff --git a/app/client/src/selectors/entitiesSelector.ts b/app/client/src/selectors/entitiesSelector.ts
index 122822646e1c..c05dfe54e0d8 100644
--- a/app/client/src/selectors/entitiesSelector.ts
+++ b/app/client/src/selectors/entitiesSelector.ts
@@ -117,8 +117,11 @@ export const getDatasourceFirstTableName = (
return "";
};
-export const getIsFetchingDatasourceStructure = (state: AppState): boolean => {
- return state.entities.datasources.fetchingDatasourceStructure;
+export const getIsFetchingDatasourceStructure = (
+ state: AppState,
+ datasourceId: string,
+): boolean => {
+ return state.entities.datasources.fetchingDatasourceStructure[datasourceId];
};
export const getMockDatasources = (state: AppState): MockDatasource[] => {
@@ -222,6 +225,30 @@ export const getPluginNameFromId = (
return plugin.name;
};
+export const getPluginPackageNameFromId = (
+ state: AppState,
+ pluginId: string,
+): string => {
+ const plugin = state.entities.plugins.list.find(
+ (plugin) => plugin.id === pluginId,
+ );
+
+ if (!plugin) return "";
+ return plugin.packageName;
+};
+
+export const getPluginDatasourceComponentFromId = (
+ state: AppState,
+ pluginId: string,
+): string => {
+ const plugin = state.entities.plugins.list.find(
+ (plugin) => plugin.id === pluginId,
+ );
+
+ if (!plugin) return "";
+ return plugin.datasourceComponent;
+};
+
export const getPluginTypeFromDatasourceId = (
state: AppState,
datasourceId: string,
diff --git a/app/client/src/selectors/featureFlagsSelectors.ts b/app/client/src/selectors/featureFlagsSelectors.ts
index 00f78b647d3d..004a15a8c005 100644
--- a/app/client/src/selectors/featureFlagsSelectors.ts
+++ b/app/client/src/selectors/featureFlagsSelectors.ts
@@ -1,14 +1,17 @@
import type { AppState } from "@appsmith/reducers";
-import { useSelector } from "react-redux";
import type { FeatureFlag } from "@appsmith/entities/FeatureFlag";
export const selectFeatureFlags = (state: AppState) =>
state.ui.users.featureFlag.data;
-export function useFeatureFlagCheck(flagName: FeatureFlag): boolean {
- const flagValues = useSelector(selectFeatureFlags);
+// React hooks should not be placed in a selectors file.
+export const selectFeatureFlagCheck = (
+ state: AppState,
+ flagName: FeatureFlag,
+): boolean => {
+ const flagValues = selectFeatureFlags(state);
if (flagName in flagValues) {
return flagValues[flagName];
}
return false;
-}
+};
diff --git a/app/client/src/utils/AnalyticsUtil.tsx b/app/client/src/utils/AnalyticsUtil.tsx
index 82d28217ef3f..7c2adaadc3fe 100644
--- a/app/client/src/utils/AnalyticsUtil.tsx
+++ b/app/client/src/utils/AnalyticsUtil.tsx
@@ -310,8 +310,6 @@ export type EventName =
| "DISCARD_DATASOURCE_CHANGES"
| "TEST_DATA_SOURCE_FAILED"
| "DATASOURCE_SCHEMA_FETCH"
- | "DATASOURCE_SCHEMA_FETCH_SUCCESS"
- | "DATASOURCE_SCHEMA_FETCH_FAILURE"
| "EDIT_ACTION_CLICK"
| "QUERY_TEMPLATE_SELECTED"
| "RUN_API_FAILURE"
@@ -335,7 +333,16 @@ export type EventName =
| "JS_VARIABLE_MUTATED"
| "EXPLORER_WIDGET_CLICK"
| "WIDGET_SEARCH"
- | "MAKE_APPLICATION_PUBLIC";
+ | "MAKE_APPLICATION_PUBLIC"
+ | WALKTHROUGH_EVENTS
+ | DATASOURCE_SCHEMA_EVENTS;
+
+export type DATASOURCE_SCHEMA_EVENTS =
+ | "DATASOURCE_SCHEMA_SEARCH"
+ | "DATASOURCE_SCHEMA_TABLE_SELECT"
+ | "AUTOMATIC_QUERY_GENERATION";
+
+type WALKTHROUGH_EVENTS = "WALKTHROUGH_DISMISSED" | "WALKTHROUGH_SHOWN";
export type AI_EVENTS =
| "AI_QUERY_SENT"
diff --git a/app/client/src/utils/replayHelpers.tsx b/app/client/src/utils/replayHelpers.tsx
index 00ef26b26213..8f6043db06ae 100644
--- a/app/client/src/utils/replayHelpers.tsx
+++ b/app/client/src/utils/replayHelpers.tsx
@@ -13,6 +13,7 @@ import {
BULK_WIDGET_ADDED,
WIDGET_REMOVED,
BULK_WIDGET_REMOVED,
+ ACTION_CONFIGURATION_CHANGED,
} from "@appsmith/constants/messages";
import { toast } from "design-system";
import { setApiPaneConfigSelectedTabIndex } from "../actions/apiPaneActions";
@@ -47,25 +48,51 @@ export const processUndoRedoToasts = (
showUndoRedoToast(widgetName, isMultipleToasts, isCreated, !isUndo);
};
+// context can be extended.
+export enum UndoRedoToastContext {
+ WIDGET = "widget",
+ QUERY_TEMPLATES = "query-templates",
+}
+
/**
* shows a toast for undo/redo
*
- * @param widgetName
+ * @param actionName
* @param isMultiple
* @param isCreated
* @param shouldUndo
+ * @param toastContext
* @returns
*/
export const showUndoRedoToast = (
- widgetName: string | undefined,
+ actionName: string | undefined,
isMultiple: boolean,
isCreated: boolean,
shouldUndo: boolean,
+ toastContext = UndoRedoToastContext.WIDGET,
) => {
- if (shouldDisallowToast(shouldUndo)) return;
+ if (
+ shouldDisallowToast(shouldUndo) &&
+ toastContext === UndoRedoToastContext.WIDGET
+ )
+ return;
+
+ let actionDescription;
+ let actionText = "";
+
+ switch (toastContext) {
+ case UndoRedoToastContext.WIDGET:
+ actionDescription = getWidgetDescription(isCreated, isMultiple);
+ actionText = createMessage(actionDescription, actionName);
+ break;
+ case UndoRedoToastContext.QUERY_TEMPLATES:
+ actionDescription = ACTION_CONFIGURATION_CHANGED;
+ actionText = createMessage(actionDescription, actionName);
+ break;
+ default:
+ actionText = "";
+ }
- const actionDescription = getActionDescription(isCreated, isMultiple);
- const widgetText = createMessage(actionDescription, widgetName);
const action = shouldUndo ? "undo" : "redo";
const actionKey = shouldUndo
? `${modText()} Z`
@@ -73,10 +100,10 @@ export const showUndoRedoToast = (
? `${modText()} ${shiftText()} Z`
: `${modText()} Y`;
- toast.show(`${widgetText}. Press ${actionKey} to ${action}`);
+ toast.show(`${actionText}. Press ${actionKey} to ${action}`);
};
-function getActionDescription(isCreated: boolean, isMultiple: boolean) {
+function getWidgetDescription(isCreated: boolean, isMultiple: boolean) {
if (isCreated) return isMultiple ? BULK_WIDGET_ADDED : WIDGET_ADDED;
else return isMultiple ? BULK_WIDGET_REMOVED : WIDGET_REMOVED;
}
diff --git a/app/client/src/utils/storage.ts b/app/client/src/utils/storage.ts
index 8ae2aa402cab..b53e7c5b36e6 100644
--- a/app/client/src/utils/storage.ts
+++ b/app/client/src/utils/storage.ts
@@ -23,6 +23,8 @@ export const STORAGE_KEYS: {
FIRST_TIME_USER_ONBOARDING_TELEMETRY_CALLOUT_VISIBILITY:
"FIRST_TIME_USER_ONBOARDING_TELEMETRY_CALLOUT_VISIBILITY",
SIGNPOSTING_APP_STATE: "SIGNPOSTING_APP_STATE",
+ FEATURE_WALKTHROUGH: "FEATURE_WALKTHROUGH",
+ USER_SIGN_UP: "USER_SIGN_UP",
};
const store = localforage.createInstance({
@@ -418,3 +420,77 @@ export const setFirstTimeUserOnboardingTelemetryCalloutVisibility = async (
log.error(error);
}
};
+
+export const setFeatureFlagShownStatus = async (key: string, value: any) => {
+ try {
+ let flagsJSON: Record<string, any> | null = await store.getItem(
+ STORAGE_KEYS.FEATURE_WALKTHROUGH,
+ );
+
+ if (typeof flagsJSON === "object" && flagsJSON) {
+ flagsJSON[key] = value;
+ } else {
+ flagsJSON = { [key]: value };
+ }
+
+ await store.setItem(STORAGE_KEYS.FEATURE_WALKTHROUGH, flagsJSON);
+ return true;
+ } catch (error) {
+ log.error("An error occurred while updating FEATURE_WALKTHROUGH");
+ log.error(error);
+ }
+};
+
+export const getFeatureFlagShownStatus = async (key: string) => {
+ try {
+ const flagsJSON: Record<string, any> | null = await store.getItem(
+ STORAGE_KEYS.FEATURE_WALKTHROUGH,
+ );
+
+ if (typeof flagsJSON === "object" && flagsJSON) {
+ return !!flagsJSON[key];
+ }
+
+ return false;
+ } catch (error) {
+ log.error("An error occurred while reading FEATURE_WALKTHROUGH");
+ log.error(error);
+ }
+};
+
+export const setUserSignedUpFlag = async (email: string) => {
+ try {
+ let userSignedUp: Record<string, any> | null = await store.getItem(
+ STORAGE_KEYS.USER_SIGN_UP,
+ );
+
+ if (typeof userSignedUp === "object" && userSignedUp) {
+ userSignedUp[email] = Date.now();
+ } else {
+ userSignedUp = { [email]: Date.now() };
+ }
+
+ await store.setItem(STORAGE_KEYS.USER_SIGN_UP, userSignedUp);
+ return true;
+ } catch (error) {
+ log.error("An error occurred while updating USER_SIGN_UP");
+ log.error(error);
+ }
+};
+
+export const isUserSignedUpFlagSet = async (email: string) => {
+ try {
+ const userSignedUp: Record<string, any> | null = await store.getItem(
+ STORAGE_KEYS.USER_SIGN_UP,
+ );
+
+ if (typeof userSignedUp === "object" && userSignedUp) {
+ return !!userSignedUp[email];
+ }
+
+ return false;
+ } catch (error) {
+ log.error("An error occurred while reading USER_SIGN_UP");
+ log.error(error);
+ }
+};
diff --git a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/constants/AnalyticsEvents.java b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/constants/AnalyticsEvents.java
index 379631c8362e..f1c136cc4051 100644
--- a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/constants/AnalyticsEvents.java
+++ b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/constants/AnalyticsEvents.java
@@ -79,8 +79,6 @@ public enum AnalyticsEvents {
UPDATE_EXISTING_LICENSE("Update_Existing_License"),
DS_SCHEMA_FETCH_EVENT("Datasource_Schema_Fetch"),
- DS_SCHEMA_FETCH_EVENT_SUCCESS("Datasource_Schema_Fetch_Success"),
- DS_SCHEMA_FETCH_EVENT_FAILED("Datasource_Schema_Fetch_Failed"),
DS_TEST_EVENT("Test_Datasource_Clicked"),
DS_TEST_EVENT_SUCCESS("Test_Datasource_Success"),
diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/helpers/WidgetSuggestionHelper.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/helpers/WidgetSuggestionHelper.java
index 41ce1723502a..1080ad708d5d 100644
--- a/app/server/appsmith-server/src/main/java/com/appsmith/server/helpers/WidgetSuggestionHelper.java
+++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/helpers/WidgetSuggestionHelper.java
@@ -43,8 +43,6 @@ public static List<WidgetSuggestionDTO> getSuggestedWidgets(Object data) {
widgetTypeList = handleJsonNode((JsonNode) data);
} else if (data instanceof List && !((List) data).isEmpty()) {
widgetTypeList = handleList((List) data);
- } else if (data != null) {
- widgetTypeList.add(getWidget(WidgetType.TEXT_WIDGET));
}
return widgetTypeList;
}
@@ -93,13 +91,9 @@ private static List<WidgetSuggestionDTO> handleJsonNode(JsonNode node) {
* Get fields from nested object
* use the for table, list, chart and Select
*/
- if (dataFields.objectFields.isEmpty()) {
- widgetTypeList.add(getWidget(WidgetType.TEXT_WIDGET));
- } else {
+ if (!dataFields.objectFields.isEmpty()) {
String nestedFieldName = dataFields.getObjectFields().get(0);
- if (node.get(nestedFieldName).size() == 0) {
- widgetTypeList.add(getWidget(WidgetType.TEXT_WIDGET));
- } else {
+ if (node.get(nestedFieldName).size() != 0) {
dataFields = collectFieldsFromData(
node.get(nestedFieldName).get(0).fields());
widgetTypeList = getWidgetsForTypeNestedObject(
@@ -134,7 +128,7 @@ private static List<WidgetSuggestionDTO> handleList(List dataList) {
}
return getWidgetsForTypeArray(fields, numericFields);
}
- return List.of(getWidget(WidgetType.TABLE_WIDGET_V2), getWidget(WidgetType.TEXT_WIDGET));
+ return List.of(getWidget(WidgetType.TABLE_WIDGET_V2));
}
/*
@@ -170,7 +164,6 @@ private static List<WidgetSuggestionDTO> getWidgetsForTypeString(List<String> fi
if (length > 1 && !fields.isEmpty()) {
widgetTypeList.add(getWidget(WidgetType.SELECT_WIDGET, fields.get(0), fields.get(0)));
} else {
- widgetTypeList.add(getWidget(WidgetType.TEXT_WIDGET));
widgetTypeList.add(getWidget(WidgetType.INPUT_WIDGET));
}
return widgetTypeList;
@@ -178,6 +171,7 @@ private static List<WidgetSuggestionDTO> getWidgetsForTypeString(List<String> fi
private static List<WidgetSuggestionDTO> getWidgetsForTypeArray(List<String> fields, List<String> numericFields) {
List<WidgetSuggestionDTO> widgetTypeList = new ArrayList<>();
+ widgetTypeList.add(getWidget(WidgetType.TABLE_WIDGET_V2));
if (!fields.isEmpty()) {
if (fields.size() < 2) {
widgetTypeList.add(getWidget(WidgetType.SELECT_WIDGET, fields.get(0), fields.get(0)));
@@ -188,14 +182,11 @@ private static List<WidgetSuggestionDTO> getWidgetsForTypeArray(List<String> fie
widgetTypeList.add(getWidget(WidgetType.CHART_WIDGET, fields.get(0), numericFields.get(0)));
}
}
- widgetTypeList.add(getWidget(WidgetType.TABLE_WIDGET_V2));
- widgetTypeList.add(getWidget(WidgetType.TEXT_WIDGET));
return widgetTypeList;
}
private static List<WidgetSuggestionDTO> getWidgetsForTypeNumber() {
List<WidgetSuggestionDTO> widgetTypeList = new ArrayList<>();
- widgetTypeList.add(getWidget(WidgetType.TEXT_WIDGET));
widgetTypeList.add(getWidget(WidgetType.INPUT_WIDGET));
return widgetTypeList;
}
@@ -213,6 +204,7 @@ private static List<WidgetSuggestionDTO> getWidgetsForTypeNestedObject(
* For the CHART widget we need at least one field of type int and one string type field
* For the DROP_DOWN at least one String type field
* */
+ widgetTypeList.add(getWidgetNestedData(WidgetType.TABLE_WIDGET_V2, nestedFieldName));
if (!fields.isEmpty()) {
if (fields.size() < 2) {
widgetTypeList.add(
@@ -226,8 +218,6 @@ private static List<WidgetSuggestionDTO> getWidgetsForTypeNestedObject(
WidgetType.CHART_WIDGET, nestedFieldName, fields.get(0), numericFields.get(0)));
}
}
- widgetTypeList.add(getWidgetNestedData(WidgetType.TABLE_WIDGET_V2, nestedFieldName));
- widgetTypeList.add(getWidgetNestedData(WidgetType.TEXT_WIDGET, nestedFieldName));
return widgetTypeList;
}
diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/AnalyticsServiceCEImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/AnalyticsServiceCEImpl.java
index ad69135f1ab3..317653ea6a76 100644
--- a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/AnalyticsServiceCEImpl.java
+++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/AnalyticsServiceCEImpl.java
@@ -360,9 +360,7 @@ public List<AnalyticsEvents> getNonResourceEvents() {
AnalyticsEvents.DS_TEST_EVENT,
AnalyticsEvents.DS_TEST_EVENT_SUCCESS,
AnalyticsEvents.DS_TEST_EVENT_FAILED,
- AnalyticsEvents.DS_SCHEMA_FETCH_EVENT,
- AnalyticsEvents.DS_SCHEMA_FETCH_EVENT_SUCCESS,
- AnalyticsEvents.DS_SCHEMA_FETCH_EVENT_FAILED);
+ AnalyticsEvents.DS_SCHEMA_FETCH_EVENT);
}
public <T extends BaseDomain> Mono<T> sendCreateEvent(T object, Map<String, Object> extraProperties) {
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 f8c87c458a05..5fdc7f18510a 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
@@ -78,7 +78,7 @@ public Mono<DatasourceStructure> getStructure(DatasourceStorage datasourceStorag
if (Boolean.FALSE.equals(datasourceStorage.getIsValid())) {
return analyticsService
.sendObjectEvent(
- AnalyticsEvents.DS_SCHEMA_FETCH_EVENT_FAILED,
+ AnalyticsEvents.DS_SCHEMA_FETCH_EVENT,
datasourceStorage,
getAnalyticsPropertiesForTestEventStatus(datasourceStorage, false))
.then(Mono.just(new DatasourceStructure()));
@@ -128,7 +128,7 @@ public Mono<DatasourceStructure> getStructure(DatasourceStorage datasourceStorag
})
.onErrorResume(error -> analyticsService
.sendObjectEvent(
- AnalyticsEvents.DS_SCHEMA_FETCH_EVENT_FAILED,
+ AnalyticsEvents.DS_SCHEMA_FETCH_EVENT,
datasourceStorage,
getAnalyticsPropertiesForTestEventStatus(datasourceStorage, false, error))
.then(Mono.error(error)))
@@ -138,7 +138,7 @@ public Mono<DatasourceStructure> getStructure(DatasourceStorage datasourceStorag
return analyticsService
.sendObjectEvent(
- AnalyticsEvents.DS_SCHEMA_FETCH_EVENT_SUCCESS,
+ AnalyticsEvents.DS_SCHEMA_FETCH_EVENT,
datasourceStorage,
getAnalyticsPropertiesForTestEventStatus(datasourceStorage, true, null))
.then(
diff --git a/app/server/appsmith-server/src/test/java/com/appsmith/server/solutions/ce/ActionExecutionSolutionCETest.java b/app/server/appsmith-server/src/test/java/com/appsmith/server/solutions/ce/ActionExecutionSolutionCETest.java
index 232f7bc76f23..b78c94248a4c 100644
--- a/app/server/appsmith-server/src/test/java/com/appsmith/server/solutions/ce/ActionExecutionSolutionCETest.java
+++ b/app/server/appsmith-server/src/test/java/com/appsmith/server/solutions/ce/ActionExecutionSolutionCETest.java
@@ -369,7 +369,6 @@ public void testActionExecute() {
mockResult.setHeaders(objectMapper.valueToTree(Map.of("response-header-key", "response-header-value")));
List<WidgetSuggestionDTO> widgetTypeList = new ArrayList<>();
- widgetTypeList.add(WidgetSuggestionHelper.getWidget(WidgetType.TEXT_WIDGET));
mockResult.setSuggestedWidgets(widgetTypeList);
ActionDTO action = new ActionDTO();
@@ -405,7 +404,6 @@ public void testActionExecuteNullRequestBody() {
mockResult.setHeaders(objectMapper.valueToTree(Map.of("response-header-key", "response-header-value")));
List<WidgetSuggestionDTO> widgetTypeList = new ArrayList<>();
- widgetTypeList.add(WidgetSuggestionHelper.getWidget(WidgetType.TEXT_WIDGET));
mockResult.setSuggestedWidgets(widgetTypeList);
ActionDTO action = new ActionDTO();
@@ -438,7 +436,6 @@ public void testActionExecuteDbQuery() {
mockResult.setBody("response-body");
List<WidgetSuggestionDTO> widgetTypeList = new ArrayList<>();
- widgetTypeList.add(WidgetSuggestionHelper.getWidget(WidgetType.TEXT_WIDGET));
mockResult.setSuggestedWidgets(widgetTypeList);
ActionDTO action = new ActionDTO();
@@ -743,7 +740,6 @@ public void testActionExecuteWithTableReturnType() {
mockResult.setHeaders(objectMapper.valueToTree(Map.of("response-header-key", "response-header-value")));
List<WidgetSuggestionDTO> widgetTypeList = new ArrayList<>();
- widgetTypeList.add(WidgetSuggestionHelper.getWidget(WidgetType.TEXT_WIDGET));
mockResult.setSuggestedWidgets(widgetTypeList);
ActionDTO action = new ActionDTO();
@@ -792,7 +788,6 @@ public void testActionExecuteWithJsonReturnType() {
mockResult.setHeaders(objectMapper.valueToTree(Map.of("response-header-key", "response-header-value")));
List<WidgetSuggestionDTO> widgetTypeList = new ArrayList<>();
- widgetTypeList.add(WidgetSuggestionHelper.getWidget(WidgetType.TEXT_WIDGET));
mockResult.setSuggestedWidgets(widgetTypeList);
ActionDTO action = new ActionDTO();
@@ -839,7 +834,6 @@ public void testActionExecuteWithPreAssignedReturnType() {
mockResult.setDataTypes(List.of(new ParsedDataType(DisplayDataType.RAW)));
List<WidgetSuggestionDTO> widgetTypeList = new ArrayList<>();
- widgetTypeList.add(WidgetSuggestionHelper.getWidget(WidgetType.TEXT_WIDGET));
mockResult.setSuggestedWidgets(widgetTypeList);
ActionDTO action = new ActionDTO();
@@ -943,10 +937,9 @@ public void testWidgetSuggestionAfterExecutionWithChartWidgetData() throws JsonP
mockResult.setDataTypes(List.of(new ParsedDataType(DisplayDataType.RAW)));
List<WidgetSuggestionDTO> widgetTypeList = new ArrayList<>();
- widgetTypeList.add(WidgetSuggestionHelper.getWidget(WidgetType.CHART_WIDGET, "x", "y"));
- widgetTypeList.add(WidgetSuggestionHelper.getWidget(WidgetType.SELECT_WIDGET, "x", "x"));
widgetTypeList.add(WidgetSuggestionHelper.getWidget(WidgetType.TABLE_WIDGET_V2));
- widgetTypeList.add(WidgetSuggestionHelper.getWidget(WidgetType.TEXT_WIDGET));
+ widgetTypeList.add(WidgetSuggestionHelper.getWidget(WidgetType.SELECT_WIDGET, "x", "x"));
+ widgetTypeList.add(WidgetSuggestionHelper.getWidget(WidgetType.CHART_WIDGET, "x", "y"));
mockResult.setSuggestedWidgets(widgetTypeList);
ActionDTO action = new ActionDTO();
@@ -1054,10 +1047,9 @@ public void testWidgetSuggestionAfterExecutionWithTableWidgetData() throws JsonP
mockResult.setDataTypes(List.of(new ParsedDataType(DisplayDataType.RAW)));
List<WidgetSuggestionDTO> widgetTypeList = new ArrayList<>();
- widgetTypeList.add(WidgetSuggestionHelper.getWidget(WidgetType.CHART_WIDGET, "id", "ppu"));
- widgetTypeList.add(WidgetSuggestionHelper.getWidget(WidgetType.SELECT_WIDGET, "id", "type"));
widgetTypeList.add(WidgetSuggestionHelper.getWidget(WidgetType.TABLE_WIDGET_V2));
- widgetTypeList.add(WidgetSuggestionHelper.getWidget(WidgetType.TEXT_WIDGET));
+ widgetTypeList.add(WidgetSuggestionHelper.getWidget(WidgetType.SELECT_WIDGET, "id", "type"));
+ widgetTypeList.add(WidgetSuggestionHelper.getWidget(WidgetType.CHART_WIDGET, "id", "ppu"));
mockResult.setSuggestedWidgets(widgetTypeList);
ActionDTO action = new ActionDTO();
@@ -1157,10 +1149,9 @@ public void testWidgetSuggestionAfterExecutionWithListWidgetData() throws JsonPr
mockResult.setDataTypes(List.of(new ParsedDataType(DisplayDataType.RAW)));
List<WidgetSuggestionDTO> widgetTypeList = new ArrayList<>();
- widgetTypeList.add(WidgetSuggestionHelper.getWidget(WidgetType.CHART_WIDGET, "url", "width"));
- widgetTypeList.add(WidgetSuggestionHelper.getWidget(WidgetType.SELECT_WIDGET, "url", "url"));
widgetTypeList.add(WidgetSuggestionHelper.getWidget(WidgetType.TABLE_WIDGET_V2));
- widgetTypeList.add(WidgetSuggestionHelper.getWidget(WidgetType.TEXT_WIDGET));
+ widgetTypeList.add(WidgetSuggestionHelper.getWidget(WidgetType.SELECT_WIDGET, "url", "url"));
+ widgetTypeList.add(WidgetSuggestionHelper.getWidget(WidgetType.CHART_WIDGET, "url", "width"));
mockResult.setSuggestedWidgets(widgetTypeList);
ActionDTO action = new ActionDTO();
@@ -1216,9 +1207,8 @@ public void testWidgetSuggestionAfterExecutionWithDropdownWidgetData() throws Js
mockResult.setDataTypes(List.of(new ParsedDataType(DisplayDataType.RAW)));
List<WidgetSuggestionDTO> widgetTypeList = new ArrayList<>();
- widgetTypeList.add(WidgetSuggestionHelper.getWidget(WidgetType.SELECT_WIDGET, "CarType", "carID"));
widgetTypeList.add(WidgetSuggestionHelper.getWidget(WidgetType.TABLE_WIDGET_V2));
- widgetTypeList.add(WidgetSuggestionHelper.getWidget(WidgetType.TEXT_WIDGET));
+ widgetTypeList.add(WidgetSuggestionHelper.getWidget(WidgetType.SELECT_WIDGET, "CarType", "carID"));
mockResult.setSuggestedWidgets(widgetTypeList);
ActionDTO action = new ActionDTO();
@@ -1258,7 +1248,6 @@ public void testWidgetSuggestionAfterExecutionWithArrayOfStringsDropDownWidget()
mockResult.setDataTypes(List.of(new ParsedDataType(DisplayDataType.RAW)));
List<WidgetSuggestionDTO> widgetTypeList = new ArrayList<>();
widgetTypeList.add(WidgetSuggestionHelper.getWidget(WidgetType.INPUT_WIDGET));
- widgetTypeList.add(WidgetSuggestionHelper.getWidget(WidgetType.TEXT_WIDGET));
mockResult.setSuggestedWidgets(widgetTypeList);
ActionDTO action = new ActionDTO();
@@ -1301,7 +1290,6 @@ public void testWidgetSuggestionAfterExecutionWithArrayOfArray() throws JsonProc
List<WidgetSuggestionDTO> widgetTypeList = new ArrayList<>();
widgetTypeList.add(WidgetSuggestionHelper.getWidget(WidgetType.TABLE_WIDGET_V2));
- widgetTypeList.add(WidgetSuggestionHelper.getWidget(WidgetType.TEXT_WIDGET));
mockResult.setSuggestedWidgets(widgetTypeList);
ActionDTO action = new ActionDTO();
@@ -1381,7 +1369,6 @@ public void testWidgetSuggestionAfterExecutionWithNumericData() throws JsonProce
List<WidgetSuggestionDTO> widgetTypeList = new ArrayList<>();
widgetTypeList.add(WidgetSuggestionHelper.getWidget(WidgetType.INPUT_WIDGET));
- widgetTypeList.add(WidgetSuggestionHelper.getWidget(WidgetType.TEXT_WIDGET));
mockResult.setSuggestedWidgets(widgetTypeList);
ActionDTO action = new ActionDTO();
@@ -1448,11 +1435,10 @@ public void testWidgetSuggestionAfterExecutionWithJsonNodeData() throws JsonProc
mockResult.setDataTypes(List.of(new ParsedDataType(DisplayDataType.RAW)));
List<WidgetSuggestionDTO> widgetTypeList = new ArrayList<>();
- widgetTypeList.add(WidgetSuggestionHelper.getWidgetNestedData(WidgetType.TEXT_WIDGET, "users"));
- widgetTypeList.add(WidgetSuggestionHelper.getWidgetNestedData(WidgetType.CHART_WIDGET, "users", "name", "id"));
widgetTypeList.add(WidgetSuggestionHelper.getWidgetNestedData(WidgetType.TABLE_WIDGET_V2, "users"));
widgetTypeList.add(
WidgetSuggestionHelper.getWidgetNestedData(WidgetType.SELECT_WIDGET, "users", "name", "status"));
+ widgetTypeList.add(WidgetSuggestionHelper.getWidgetNestedData(WidgetType.CHART_WIDGET, "users", "name", "id"));
mockResult.setSuggestedWidgets(widgetTypeList);
ActionDTO action = new ActionDTO();
@@ -1501,7 +1487,6 @@ public void testWidgetSuggestionAfterExecutionWithJsonObjectData() throws JsonPr
mockResult.setDataTypes(List.of(new ParsedDataType(DisplayDataType.RAW)));
List<WidgetSuggestionDTO> widgetTypeList = new ArrayList<>();
- widgetTypeList.add(WidgetSuggestionHelper.getWidget(WidgetType.TEXT_WIDGET));
mockResult.setSuggestedWidgets(widgetTypeList);
ActionDTO action = new ActionDTO();
@@ -1561,7 +1546,6 @@ public void testWidgetSuggestionAfterExecutionWithJsonArrayObjectData() throws J
mockResult.setDataTypes(List.of(new ParsedDataType(DisplayDataType.RAW)));
List<WidgetSuggestionDTO> widgetTypeList = new ArrayList<>();
- widgetTypeList.add(WidgetSuggestionHelper.getWidget(WidgetType.TEXT_WIDGET));
mockResult.setSuggestedWidgets(widgetTypeList);
ActionDTO action = new ActionDTO();
@@ -1605,7 +1589,6 @@ public void testWidgetSuggestionNestedData() throws JsonProcessingException {
mockResult.setDataTypes(List.of(new ParsedDataType(DisplayDataType.RAW)));
List<WidgetSuggestionDTO> widgetTypeList = new ArrayList<>();
- widgetTypeList.add(WidgetSuggestionHelper.getWidgetNestedData(WidgetType.TEXT_WIDGET, "users"));
widgetTypeList.add(WidgetSuggestionHelper.getWidgetNestedData(WidgetType.TABLE_WIDGET_V2, "users"));
mockResult.setSuggestedWidgets(widgetTypeList);
@@ -1650,7 +1633,6 @@ public void testWidgetSuggestionNestedDataEmpty() throws JsonProcessingException
mockResult.setDataTypes(List.of(new ParsedDataType(DisplayDataType.RAW)));
List<WidgetSuggestionDTO> widgetTypeList = new ArrayList<>();
- widgetTypeList.add(WidgetSuggestionHelper.getWidgetNestedData(WidgetType.TEXT_WIDGET, null));
mockResult.setSuggestedWidgets(widgetTypeList);
ActionDTO action = new ActionDTO();
@@ -1695,10 +1677,9 @@ public void suggestWidget_ArrayListData_SuggestTableTextChartDropDownWidget() {
mockResult.setDataTypes(List.of(new ParsedDataType(DisplayDataType.RAW)));
List<WidgetSuggestionDTO> widgetTypeList = new ArrayList<>();
- widgetTypeList.add(WidgetSuggestionHelper.getWidget(WidgetType.CHART_WIDGET, "url", "width"));
- widgetTypeList.add(WidgetSuggestionHelper.getWidget(WidgetType.SELECT_WIDGET, "url", "url"));
widgetTypeList.add(WidgetSuggestionHelper.getWidget(WidgetType.TABLE_WIDGET_V2));
- widgetTypeList.add(WidgetSuggestionHelper.getWidget(WidgetType.TEXT_WIDGET));
+ widgetTypeList.add(WidgetSuggestionHelper.getWidget(WidgetType.SELECT_WIDGET, "url", "url"));
+ widgetTypeList.add(WidgetSuggestionHelper.getWidget(WidgetType.CHART_WIDGET, "url", "width"));
mockResult.setSuggestedWidgets(widgetTypeList);
ActionDTO action = new ActionDTO();
@@ -1745,9 +1726,8 @@ public void suggestWidget_ArrayListData_SuggestTableTextDropDownWidget() {
mockResult.setDataTypes(List.of(new ParsedDataType(DisplayDataType.RAW)));
List<WidgetSuggestionDTO> widgetTypeList = new ArrayList<>();
- widgetTypeList.add(WidgetSuggestionHelper.getWidget(WidgetType.SELECT_WIDGET, "width", "url"));
widgetTypeList.add(WidgetSuggestionHelper.getWidget(WidgetType.TABLE_WIDGET_V2));
- widgetTypeList.add(WidgetSuggestionHelper.getWidget(WidgetType.TEXT_WIDGET));
+ widgetTypeList.add(WidgetSuggestionHelper.getWidget(WidgetType.SELECT_WIDGET, "width", "url"));
mockResult.setSuggestedWidgets(widgetTypeList);
ActionDTO action = new ActionDTO();
@@ -1784,7 +1764,6 @@ public void suggestWidget_ArrayListDataEmpty_SuggestTextWidget() {
mockResult.setDataTypes(List.of(new ParsedDataType(DisplayDataType.RAW)));
List<WidgetSuggestionDTO> widgetTypeList = new ArrayList<>();
- widgetTypeList.add(WidgetSuggestionHelper.getWidget(WidgetType.TEXT_WIDGET));
mockResult.setSuggestedWidgets(widgetTypeList);
ActionDTO action = new ActionDTO();
@@ -1830,7 +1809,6 @@ public void executeAction_actionOnMockDatasource_success() {
.block();
List<WidgetSuggestionDTO> widgetTypeList = new ArrayList<>();
- widgetTypeList.add(WidgetSuggestionHelper.getWidget(WidgetType.TEXT_WIDGET));
mockResult.setSuggestedWidgets(widgetTypeList);
ActionDTO action = new ActionDTO();
|
97166581d383da149ebd85b0327134bb18a743f7
|
2023-10-16 17:58:31
|
Nilesh Sarupriya
|
chore: populate user management roles with default domain (#26803)
| false
|
populate user management roles with default domain (#26803)
|
chore
|
diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/exceptions/AppsmithError.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/exceptions/AppsmithError.java
index 9de15ba27ec2..8985b52e3954 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
@@ -969,6 +969,14 @@ public enum AppsmithError {
"Invalid usage for custom annotation",
ErrorType.CONFIGURATION_ERROR,
null),
+ MIGRATION_FAILED(
+ 500,
+ AppsmithErrorCode.MIGRATION_FAILED.getCode(),
+ "Migration {0} failed. Reason: {1}. Note: {2}",
+ AppsmithErrorAction.DEFAULT,
+ "Migration failed",
+ ErrorType.INTERNAL_ERROR,
+ null),
FeatureFlagMigrationFailure(
500,
diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/exceptions/AppsmithErrorCode.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/exceptions/AppsmithErrorCode.java
index e47cb2ad6ace..9cd8a99b387b 100644
--- a/app/server/appsmith-server/src/main/java/com/appsmith/server/exceptions/AppsmithErrorCode.java
+++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/exceptions/AppsmithErrorCode.java
@@ -66,6 +66,7 @@ public enum AppsmithErrorCode {
PLUGIN_EXECUTION_TIMEOUT("AE-APP-5040", "Plugin execution timeout"),
MARKETPLACE_TIMEOUT("AE-APP-5041", "Marketplace timeout"),
GOOGLE_RECAPTCHA_TIMEOUT("AE-APP-5042", "Google recaptcha timeout"),
+ MIGRATION_FAILED("AE-APP-5043", "Migration failed"),
INVALID_PROPERTIES_CONFIGURATION("AE-APP-5044", "Property configuration is wrong or malformed"),
NAME_CLASH_NOT_ALLOWED_IN_REFACTOR("AE-AST-4009", "Name clash not allowed in refactor"),
GENERIC_BAD_REQUEST("AE-BAD-4000", "Generic bad request"),
diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/migrations/db/ce/Migration028TagUserManagementRolesWithoutDefaultDomainTypeAndId.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/migrations/db/ce/Migration028TagUserManagementRolesWithoutDefaultDomainTypeAndId.java
new file mode 100644
index 000000000000..49d163b95f06
--- /dev/null
+++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/migrations/db/ce/Migration028TagUserManagementRolesWithoutDefaultDomainTypeAndId.java
@@ -0,0 +1,88 @@
+package com.appsmith.server.migrations.db.ce;
+
+import com.appsmith.external.models.Policy;
+import com.appsmith.server.domains.PermissionGroup;
+import com.appsmith.server.domains.QPermissionGroup;
+import com.appsmith.server.domains.QUser;
+import com.appsmith.server.domains.User;
+import com.appsmith.server.helpers.CollectionUtils;
+import io.mongock.api.annotations.ChangeUnit;
+import io.mongock.api.annotations.Execution;
+import io.mongock.api.annotations.RollbackExecution;
+import lombok.RequiredArgsConstructor;
+import lombok.extern.slf4j.Slf4j;
+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.HashSet;
+import java.util.List;
+import java.util.Optional;
+import java.util.Set;
+
+import static com.appsmith.server.acl.AclPermission.RESET_PASSWORD_USERS;
+import static com.appsmith.server.repositories.ce.BaseAppsmithRepositoryCEImpl.fieldName;
+import static com.appsmith.server.repositories.ce.BaseAppsmithRepositoryCEImpl.notDeleted;
+
+@Slf4j
+@RequiredArgsConstructor
+@ChangeUnit(order = "028", id = "tag-user-management-roles-without-default-domain-type-and-id")
+public class Migration028TagUserManagementRolesWithoutDefaultDomainTypeAndId {
+ private final MongoTemplate mongoTemplate;
+
+ public static final String MIGRATION_FLAG_028_TAG_USER_MANAGEMENT_ROLE_WITHOUT_DEFAULT_DOMAIN_TYPE_AND_ID =
+ "tagUserManagementRoleWithoutDefaultDomainTypeAndId";
+
+ @RollbackExecution
+ public void rollbackExecution() {}
+
+ @Execution
+ public void tagUserManagementRolesWithoutDefaultDomainTypeAndId() {
+ Criteria resetPasswordPolicyExistsAndNotDeleted = Criteria.where("policies.permission")
+ .is(RESET_PASSWORD_USERS.getValue())
+ .andOperator(notDeleted());
+ Query queryExistingUsersWithResetPasswordPolicy = new Query(resetPasswordPolicyExistsAndNotDeleted);
+ queryExistingUsersWithResetPasswordPolicy.fields().include(fieldName(QUser.user.policies));
+
+ List<User> existingUsers = mongoTemplate.find(queryExistingUsersWithResetPasswordPolicy, User.class);
+
+ /*
+ * At the moment, RESET_PASSWORD_USERS policy for the user resource only contains 1 permission group ID, i.e.
+ * the ID of user management role for that user resource. Hence, we pick the ID present at the 0th index below.
+ */
+ Set<String> userManagementRoleIds = new HashSet<>();
+ existingUsers.forEach(existingUser -> {
+ Optional<Policy> resetPasswordPolicyOptional = existingUser.getPolicies().stream()
+ .filter(policy1 -> RESET_PASSWORD_USERS.getValue().equals(policy1.getPermission()))
+ .findFirst();
+ resetPasswordPolicyOptional.ifPresent(resetPasswordPolicy -> {
+ List<String> roleIdList =
+ resetPasswordPolicy.getPermissionGroups().stream().toList();
+ if (!CollectionUtils.isNullOrEmpty(roleIdList)) {
+ userManagementRoleIds.add(roleIdList.get(0));
+ }
+ });
+ });
+
+ Criteria criteriaUserManagementRoleIds =
+ Criteria.where(fieldName(QPermissionGroup.permissionGroup.id)).in(userManagementRoleIds);
+ Criteria criteriaDefaultDomainIdDoesNotExist = new Criteria()
+ .orOperator(
+ Criteria.where(fieldName(QPermissionGroup.permissionGroup.defaultDomainId))
+ .isNull(),
+ Criteria.where(fieldName(QPermissionGroup.permissionGroup.defaultDomainId))
+ .exists(false));
+ Criteria criteriaUserManagementRolesWithDefaultDomainIdDoesNotExist =
+ new Criteria().andOperator(criteriaUserManagementRoleIds, criteriaDefaultDomainIdDoesNotExist);
+ Query queryUserManagementRolesWithDefaultDomainIdDoesNotExist =
+ new Query(criteriaUserManagementRolesWithDefaultDomainIdDoesNotExist);
+
+ Update updateSetMigrationFlag = new Update();
+ updateSetMigrationFlag.set(
+ MIGRATION_FLAG_028_TAG_USER_MANAGEMENT_ROLE_WITHOUT_DEFAULT_DOMAIN_TYPE_AND_ID, Boolean.TRUE);
+
+ mongoTemplate.updateMulti(
+ queryUserManagementRolesWithDefaultDomainIdDoesNotExist, updateSetMigrationFlag, PermissionGroup.class);
+ }
+}
diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/migrations/db/ce/Migration029PopulateDefaultDomainIdInUserManagementRoles.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/migrations/db/ce/Migration029PopulateDefaultDomainIdInUserManagementRoles.java
new file mode 100644
index 000000000000..332f76a5291c
--- /dev/null
+++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/migrations/db/ce/Migration029PopulateDefaultDomainIdInUserManagementRoles.java
@@ -0,0 +1,117 @@
+package com.appsmith.server.migrations.db.ce;
+
+import com.appsmith.external.models.Policy;
+import com.appsmith.server.domains.PermissionGroup;
+import com.appsmith.server.domains.QPermissionGroup;
+import com.appsmith.server.domains.QUser;
+import com.appsmith.server.domains.User;
+import com.appsmith.server.exceptions.AppsmithError;
+import com.appsmith.server.exceptions.AppsmithException;
+import io.mongock.api.annotations.ChangeUnit;
+import io.mongock.api.annotations.Execution;
+import io.mongock.api.annotations.RollbackExecution;
+import lombok.RequiredArgsConstructor;
+import lombok.extern.slf4j.Slf4j;
+import org.apache.commons.lang3.StringUtils;
+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.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+
+import static com.appsmith.server.acl.AclPermission.RESET_PASSWORD_USERS;
+import static com.appsmith.server.repositories.ce.BaseAppsmithRepositoryCEImpl.fieldName;
+import static com.appsmith.server.repositories.ce.BaseAppsmithRepositoryCEImpl.notDeleted;
+
+@Slf4j
+@RequiredArgsConstructor
+@ChangeUnit(order = "029", id = "populate-default-domain-id-in-user-management-roles")
+public class Migration029PopulateDefaultDomainIdInUserManagementRoles {
+
+ private final MongoTemplate mongoTemplate;
+
+ private static final int migrationRetries = 5;
+ private static final String migrationId = "populate-default-domain-id-in-user-management-roles";
+ private static final String migrationNote = "This will not have any adverse effects on the Data. Restarting the "
+ + "server will begin the migration from where it left.";
+
+ @RollbackExecution
+ public void rollbackExecution() {}
+
+ @Execution
+ public void populateDefaultDomainIdInUserManagementRoles() {
+ Criteria resetPasswordPolicyExistsAndNotDeleted = Criteria.where("policies.permission")
+ .is(RESET_PASSWORD_USERS.getValue())
+ .andOperator(notDeleted());
+ Query queryExistingUsersWithResetPasswordPolicy = new Query(resetPasswordPolicyExistsAndNotDeleted);
+ queryExistingUsersWithResetPasswordPolicy.fields().include(fieldName(QUser.user.policies));
+ Map<String, String> userManagementRoleIdToUserIdMap = new HashMap<>();
+ mongoTemplate.stream(queryExistingUsersWithResetPasswordPolicy, User.class)
+ .forEach(existingUser -> {
+ Optional<Policy> resetPasswordPolicyOptional = existingUser.getPolicies().stream()
+ .filter(policy1 -> RESET_PASSWORD_USERS.getValue().equals(policy1.getPermission()))
+ .findFirst();
+ resetPasswordPolicyOptional.ifPresent(resetPasswordPolicy -> {
+ List<String> roleIdList = resetPasswordPolicy.getPermissionGroups().stream()
+ .toList();
+ roleIdList.forEach(roleId -> userManagementRoleIdToUserIdMap.put(roleId, existingUser.getId()));
+ });
+ });
+
+ Criteria criteriaUserManagementRolesWithMigrationFlag028Set = Criteria.where(
+ Migration028TagUserManagementRolesWithoutDefaultDomainTypeAndId
+ .MIGRATION_FLAG_028_TAG_USER_MANAGEMENT_ROLE_WITHOUT_DEFAULT_DOMAIN_TYPE_AND_ID)
+ .exists(Boolean.TRUE);
+ Query queryUserManagementRolesWithWithMigrationFlag028Set =
+ new Query(criteriaUserManagementRolesWithMigrationFlag028Set);
+
+ queryUserManagementRolesWithWithMigrationFlag028Set
+ .fields()
+ .include(fieldName(QPermissionGroup.permissionGroup.id));
+ long countOfUserManagementRolesWithMigrationFlag028Set =
+ mongoTemplate.count(queryUserManagementRolesWithWithMigrationFlag028Set, PermissionGroup.class);
+ int attempt = 0;
+
+ while (countOfUserManagementRolesWithMigrationFlag028Set > 0 && attempt < migrationRetries) {
+ List<PermissionGroup> userManagementRolesWithMigrationFlag028Set =
+ mongoTemplate.find(queryUserManagementRolesWithWithMigrationFlag028Set, PermissionGroup.class);
+ userManagementRolesWithMigrationFlag028Set.parallelStream().forEach(userManagementRole -> {
+ if (userManagementRoleIdToUserIdMap.containsKey(userManagementRole.getId())
+ && StringUtils.isNotEmpty(userManagementRoleIdToUserIdMap.get(userManagementRole.getId()))) {
+ Criteria criteriaUserManagementRoleById = Criteria.where(
+ fieldName(QPermissionGroup.permissionGroup.id))
+ .is(userManagementRole.getId());
+ Query queryUserManagementRoleById = new Query(criteriaUserManagementRoleById);
+ Update updateDefaultDomainIdOfUserManagementRole = new Update();
+
+ updateDefaultDomainIdOfUserManagementRole.set(
+ fieldName(QPermissionGroup.permissionGroup.defaultDomainId),
+ userManagementRoleIdToUserIdMap.get(userManagementRole.getId()));
+
+ updateDefaultDomainIdOfUserManagementRole.set(
+ fieldName(QPermissionGroup.permissionGroup.defaultDomainType), User.class.getSimpleName());
+
+ updateDefaultDomainIdOfUserManagementRole.unset(
+ Migration028TagUserManagementRolesWithoutDefaultDomainTypeAndId
+ .MIGRATION_FLAG_028_TAG_USER_MANAGEMENT_ROLE_WITHOUT_DEFAULT_DOMAIN_TYPE_AND_ID);
+ mongoTemplate.updateFirst(
+ queryUserManagementRoleById,
+ updateDefaultDomainIdOfUserManagementRole,
+ PermissionGroup.class);
+ }
+ });
+ countOfUserManagementRolesWithMigrationFlag028Set =
+ mongoTemplate.count(queryUserManagementRolesWithWithMigrationFlag028Set, PermissionGroup.class);
+ attempt += 1;
+ }
+
+ if (countOfUserManagementRolesWithMigrationFlag028Set != 0) {
+ String reasonForFailure = "All user management roles were not tagged.";
+ throw new AppsmithException(AppsmithError.MIGRATION_FAILED, migrationId, reasonForFailure, migrationNote);
+ }
+ }
+}
diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/migrations/db/ce/Migration030TagUsersWithNoUserManagementRoles.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/migrations/db/ce/Migration030TagUsersWithNoUserManagementRoles.java
new file mode 100644
index 000000000000..11555cc0bdac
--- /dev/null
+++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/migrations/db/ce/Migration030TagUsersWithNoUserManagementRoles.java
@@ -0,0 +1,70 @@
+package com.appsmith.server.migrations.db.ce;
+
+import com.appsmith.external.models.QBaseDomain;
+import com.appsmith.server.domains.PermissionGroup;
+import com.appsmith.server.domains.User;
+import io.mongock.api.annotations.ChangeUnit;
+import io.mongock.api.annotations.Execution;
+import io.mongock.api.annotations.RollbackExecution;
+import lombok.RequiredArgsConstructor;
+import lombok.extern.slf4j.Slf4j;
+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 static com.appsmith.server.repositories.ce.BaseAppsmithRepositoryCEImpl.fieldName;
+
+@Slf4j
+@RequiredArgsConstructor
+@ChangeUnit(order = "030", id = "tag-users-with-no-user-management-roles")
+public class Migration030TagUsersWithNoUserManagementRoles {
+
+ private final MongoTemplate mongoTemplate;
+
+ public static final String MIGRATION_FLAG_030_TAG_USER_WITHOUT_USER_MANAGEMENT_ROLE =
+ "tagUserWithoutUserManagementRole";
+
+ @RollbackExecution
+ public void rollbackExecution() {}
+
+ @Execution
+ public void tagUsersWithNoUserManagementRoles() {
+ Criteria criteriaDefaultDomainTypeExists =
+ Criteria.where("defaultDomainType").exists(true);
+ Criteria criteriaDefaultDomainTypeIsUser =
+ Criteria.where("defaultDomainType").is(User.class.getSimpleName());
+
+ Criteria criteriaUserManagementRoles =
+ new Criteria().andOperator(criteriaDefaultDomainTypeExists, criteriaDefaultDomainTypeIsUser);
+ Query queryUserManagementRoles = new Query(criteriaUserManagementRoles);
+ queryUserManagementRoles.fields().include("defaultDomainId");
+
+ List<PermissionGroup> userManagementRoles = mongoTemplate.find(queryUserManagementRoles, PermissionGroup.class);
+
+ List<String> userIdsWithUserManagementRoles = userManagementRoles.stream()
+ .map(PermissionGroup::getDefaultDomainId)
+ .toList();
+
+ Criteria criteriaUsersWithNoUserManagementRoles =
+ Criteria.where(fieldName(QBaseDomain.baseDomain.id)).nin(userIdsWithUserManagementRoles);
+ Criteria criteriaUsersPoliciesExists =
+ Criteria.where(fieldName(QBaseDomain.baseDomain.policies)).exists(true);
+ Criteria criteriaUsersPoliciesNotEmpty =
+ Criteria.where(fieldName(QBaseDomain.baseDomain.policies)).not().size(0);
+ Criteria criteriaUsersWithNoUserManagementRolesAndUserPoliciesExists = new Criteria()
+ .andOperator(
+ criteriaUsersWithNoUserManagementRoles,
+ criteriaUsersPoliciesExists,
+ criteriaUsersPoliciesNotEmpty);
+ Query queryUsersWithNoUserManagementRoles =
+ new Query(criteriaUsersWithNoUserManagementRolesAndUserPoliciesExists);
+
+ Update updateSetMigrationFlag = new Update();
+ updateSetMigrationFlag.set(MIGRATION_FLAG_030_TAG_USER_WITHOUT_USER_MANAGEMENT_ROLE, Boolean.TRUE);
+
+ mongoTemplate.updateMulti(queryUsersWithNoUserManagementRoles, updateSetMigrationFlag, User.class);
+ }
+}
diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/migrations/db/ce/Migration031CreateUserManagementRolesForUsersTaggedIn030.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/migrations/db/ce/Migration031CreateUserManagementRolesForUsersTaggedIn030.java
new file mode 100644
index 000000000000..b450af9dafd6
--- /dev/null
+++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/migrations/db/ce/Migration031CreateUserManagementRolesForUsersTaggedIn030.java
@@ -0,0 +1,110 @@
+package com.appsmith.server.migrations.db.ce;
+
+import com.appsmith.external.models.Policy;
+import com.appsmith.external.models.QBaseDomain;
+import com.appsmith.server.constants.FieldName;
+import com.appsmith.server.domains.PermissionGroup;
+import com.appsmith.server.domains.QUser;
+import com.appsmith.server.domains.User;
+import com.appsmith.server.dtos.Permission;
+import com.appsmith.server.exceptions.AppsmithError;
+import com.appsmith.server.exceptions.AppsmithException;
+import com.appsmith.server.migrations.utils.CompatibilityUtils;
+import com.appsmith.server.solutions.PolicySolution;
+import io.mongock.api.annotations.ChangeUnit;
+import io.mongock.api.annotations.Execution;
+import io.mongock.api.annotations.RollbackExecution;
+import lombok.RequiredArgsConstructor;
+import lombok.extern.slf4j.Slf4j;
+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.Map;
+import java.util.Set;
+
+import static com.appsmith.server.acl.AclPermission.MANAGE_USERS;
+import static com.appsmith.server.repositories.ce.BaseAppsmithRepositoryCEImpl.fieldName;
+import static java.lang.Boolean.TRUE;
+
+@Slf4j
+@RequiredArgsConstructor
+@ChangeUnit(order = "031", id = "create-user-management-roles-for-users-tagged-in-migration-030")
+public class Migration031CreateUserManagementRolesForUsersTaggedIn030 {
+ private final MongoTemplate mongoTemplate;
+ private final PolicySolution policySolution;
+
+ private static final int migrationRetries = 5;
+ private static final String migrationNote = "This will not have any adverse effects on the Data. Restarting the "
+ + "server will begin the migration from where it left.";
+ private static final String migrationId = "create-user-management-roles-for-users-tagged-in-migration-030";
+
+ @RollbackExecution
+ public void rollbackExecution() {}
+
+ @Execution
+ public void createUserManagementRolesForUsersTaggedInMigration030() {
+ Criteria criteriaUsersTaggedInMigration030 = Criteria.where(
+ Migration030TagUsersWithNoUserManagementRoles
+ .MIGRATION_FLAG_030_TAG_USER_WITHOUT_USER_MANAGEMENT_ROLE)
+ .is(TRUE);
+
+ Query queryUsersTaggedInMigration030 = new Query(criteriaUsersTaggedInMigration030);
+ queryUsersTaggedInMigration030.fields().include(fieldName(QUser.user.id));
+ queryUsersTaggedInMigration030.fields().include(fieldName(QUser.user.policies));
+ queryUsersTaggedInMigration030.fields().include(fieldName(QUser.user.email));
+
+ Query optimisedQueryUsersTaggedInMigration030 = CompatibilityUtils.optimizeQueryForNoCursorTimeout(
+ mongoTemplate, queryUsersTaggedInMigration030, User.class);
+
+ int attempt = 0;
+ long countUsersTaggedInMigration030 = mongoTemplate.count(optimisedQueryUsersTaggedInMigration030, User.class);
+
+ while (attempt < migrationRetries && countUsersTaggedInMigration030 > 0) {
+ mongoTemplate.stream(optimisedQueryUsersTaggedInMigration030, User.class)
+ .forEach(user -> {
+ User userWithUpdatedPolicies = createUserManagementRoleAndGetUserWithUpdatedPolicies(user);
+ Update updateMigrationFlagAndPoliciesForUser = new Update();
+ updateMigrationFlagAndPoliciesForUser.unset(
+ Migration030TagUsersWithNoUserManagementRoles
+ .MIGRATION_FLAG_030_TAG_USER_WITHOUT_USER_MANAGEMENT_ROLE);
+ updateMigrationFlagAndPoliciesForUser.set(
+ fieldName(QUser.user.policies), userWithUpdatedPolicies.getPolicies());
+ Criteria criteriaUserId = Criteria.where(fieldName(QBaseDomain.baseDomain.id))
+ .is(user.getId());
+ Query queryUserId = new Query(criteriaUserId);
+ mongoTemplate.updateFirst(queryUserId, updateMigrationFlagAndPoliciesForUser, User.class);
+ });
+ attempt += 1;
+ countUsersTaggedInMigration030 = mongoTemplate.count(optimisedQueryUsersTaggedInMigration030, User.class);
+ }
+
+ if (countUsersTaggedInMigration030 > 0) {
+ String reasonForFailure = "All user management roles were not created.";
+ throw new AppsmithException(AppsmithError.MIGRATION_FAILED, migrationId, reasonForFailure, migrationNote);
+ }
+ }
+
+ private User createUserManagementRoleAndGetUserWithUpdatedPolicies(User user) {
+ // Create user management permission group
+ PermissionGroup userManagementRole = new PermissionGroup();
+ userManagementRole.setName(user.getUsername() + FieldName.SUFFIX_USER_MANAGEMENT_ROLE);
+ // Add CRUD permissions for user to the group
+ userManagementRole.setPermissions(Set.of(new Permission(user.getId(), MANAGE_USERS)));
+ userManagementRole.setDefaultDomainId(user.getId());
+ userManagementRole.setDefaultDomainType(User.class.getSimpleName());
+
+ // Assign the permission group to the user
+ userManagementRole.setAssignedToUserIds(Set.of(user.getId()));
+
+ PermissionGroup savedUserManagementRole = mongoTemplate.save(userManagementRole);
+
+ Map<String, Policy> crudUserPolicies =
+ policySolution.generatePolicyFromPermissionGroupForObject(savedUserManagementRole, user.getId());
+
+ User updatedWithPolicies = policySolution.addPoliciesToExistingObject(crudUserPolicies, user);
+
+ return updatedWithPolicies;
+ }
+}
|
6aeb456c624d13e5df57247f1aad0ae1208f27a4
|
2024-05-20 10:49:27
|
Arpit Mohan
|
ci: Upgrade GitHub Action steps to github-script@v7 and pload-artifact@v4 (#33554)
| false
|
Upgrade GitHub Action steps to github-script@v7 and pload-artifact@v4 (#33554)
|
ci
|
diff --git a/.github/workflows/build-client-server.yml b/.github/workflows/build-client-server.yml
index 8531a6ab283f..be764f610389 100644
--- a/.github/workflows/build-client-server.yml
+++ b/.github/workflows/build-client-server.yml
@@ -174,7 +174,7 @@ jobs:
DB_PWD: ${{ secrets.CYPRESS_DB_PWD }}
RUN_ID: ${{ github.run_id }}
ATTEMPT_NUMBER: ${{ github.run_attempt }}
- uses: actions/github-script@v6
+ uses: actions/github-script@v7
with:
script: |
const { Pool } = require("pg");
@@ -216,7 +216,7 @@ jobs:
# This is done for debugging.
- name: upload combined failed spec
if: needs.ci-test-limited.result != 'success'
- uses: actions/upload-artifact@v3
+ uses: actions/upload-artifact@v4
with:
name: combined_failed_spec_ci
path: ~/combined_failed_spec_ci
@@ -291,7 +291,7 @@ jobs:
DB_PWD: ${{ secrets.CYPRESS_DB_PWD }}
RUN_ID: ${{ github.run_id }}
ATTEMPT_NUMBER: ${{ github.run_attempt }}
- uses: actions/github-script@v6
+ uses: actions/github-script@v7
with:
script: |
const { Pool } = require("pg");
@@ -333,7 +333,7 @@ jobs:
# This is done for debugging.
- name: upload combined failed spec
if: needs.ci-test-limited-existing-docker-image.result != 'success'
- uses: actions/upload-artifact@v3
+ uses: actions/upload-artifact@v4
with:
name: combined_failed_spec_ci
path: ~/combined_failed_spec_ci
diff --git a/.github/workflows/build-docker-image.yml b/.github/workflows/build-docker-image.yml
index e56563dc2198..d55b01a57ab4 100644
--- a/.github/workflows/build-docker-image.yml
+++ b/.github/workflows/build-docker-image.yml
@@ -38,7 +38,7 @@ jobs:
- name: Download the client build artifact
if: steps.run_result.outputs.run_result != 'success'
- uses: actions/download-artifact@v3
+ uses: actions/download-artifact@v4
with:
name: client-build
path: app/client
@@ -51,14 +51,14 @@ jobs:
- name: Download the server build artifact
if: steps.run_result.outputs.run_result != 'success'
- uses: actions/download-artifact@v3
+ uses: actions/download-artifact@v4
with:
name: server-build
path: app/server/dist/
- name: Download the rts build artifact
if: steps.run_result.outputs.run_result != 'success'
- uses: actions/download-artifact@v3
+ uses: actions/download-artifact@v4
with:
name: rts-dist
path: app/client/packages/rts/dist
diff --git a/.github/workflows/ci-test-custom-script.yml b/.github/workflows/ci-test-custom-script.yml
index 229a4b705545..cc0767916f49 100644
--- a/.github/workflows/ci-test-custom-script.yml
+++ b/.github/workflows/ci-test-custom-script.yml
@@ -364,7 +364,7 @@ jobs:
- name: Upload failed test cypress logs artifact
if: failure()
- uses: actions/upload-artifact@v3
+ uses: actions/upload-artifact@v4
with:
name: cypress-console-logs
path: ${{ github.workspace }}/app/client/cypress/cypress-logs
@@ -379,7 +379,7 @@ jobs:
# Upload docker logs
- name: Upload failed test list artifact
if: failure()
- uses: actions/upload-artifact@v3
+ uses: actions/upload-artifact@v4
with:
name: dockerlogs
path: ~/dockerlogs
@@ -392,7 +392,7 @@ jobs:
- name: Upload cypress report
if: failure()
- uses: actions/upload-artifact@v3
+ uses: actions/upload-artifact@v4
with:
name: results-${{github.run_attempt}}
path: ~/results
@@ -415,7 +415,7 @@ jobs:
# Upload the log artifact so that it can be used by the test & deploy job in the workflow
- name: Upload server logs bundle on failure
- uses: actions/upload-artifact@v3
+ uses: actions/upload-artifact@v4
if: failure()
with:
name: server-logs-${{ matrix.job }}
diff --git a/.github/workflows/ci-test-hosted.yml b/.github/workflows/ci-test-hosted.yml
index 5b97f064af5d..0ead26b3fea2 100644
--- a/.github/workflows/ci-test-hosted.yml
+++ b/.github/workflows/ci-test-hosted.yml
@@ -256,14 +256,14 @@ jobs:
- name: Upload cypress report
if: failure()
- uses: actions/upload-artifact@v3
+ uses: actions/upload-artifact@v4
with:
name: results-${{github.run_attempt}}
path: ~/results
- name: Upload cypress snapshots
if: failure()
- uses: actions/upload-artifact@v3
+ uses: actions/upload-artifact@v4
with:
name: snapshots
path: ${{ github.workspace }}/app/client/cypress/snapshots
diff --git a/.github/workflows/ci-test-limited.yml b/.github/workflows/ci-test-limited.yml
index fcdf38a7fc8b..8645cfd0ec10 100644
--- a/.github/workflows/ci-test-limited.yml
+++ b/.github/workflows/ci-test-limited.yml
@@ -367,14 +367,14 @@ jobs:
- name: Upload failed test cypress logs artifact
if: failure()
- uses: actions/upload-artifact@v3
+ uses: actions/upload-artifact@v4
with:
name: cypress-console-logs
path: ${{ github.workspace }}/app/client/cypress/cypress-logs
- name: Upload cypress snapshots
if: always()
- uses: actions/upload-artifact@v3
+ uses: actions/upload-artifact@v4
with:
name: snapshots
path: ${{ github.workspace }}/app/client/cypress/snapshots
@@ -389,7 +389,7 @@ jobs:
# Upload docker logs
- name: Upload failed test list artifact
if: failure()
- uses: actions/upload-artifact@v3
+ uses: actions/upload-artifact@v4
with:
name: dockerlogs
path: ~/dockerlogs
@@ -402,7 +402,7 @@ jobs:
- name: Upload cypress report
if: failure()
- uses: actions/upload-artifact@v3
+ uses: actions/upload-artifact@v4
with:
name: results-${{github.run_attempt}}
path: ~/results
@@ -426,7 +426,7 @@ jobs:
# Upload the log artifact so that it can be used by the test & deploy job in the workflow
- name: Upload server logs bundle on failure
- uses: actions/upload-artifact@v3
+ uses: actions/upload-artifact@v4
if: failure()
with:
name: server-logs-${{ matrix.job }}
diff --git a/.github/workflows/client-build.yml b/.github/workflows/client-build.yml
index 9c29a7fea42b..d71a78aa1e6e 100644
--- a/.github/workflows/client-build.yml
+++ b/.github/workflows/client-build.yml
@@ -290,7 +290,7 @@ jobs:
# Upload the build artifact so that it can be used by the test & deploy job in the workflow
- name: Upload react build bundle
- uses: actions/upload-artifact@v3
+ uses: actions/upload-artifact@v4
with:
name: client-build
path: app/client/build.tar
diff --git a/.github/workflows/close-labeler.yml b/.github/workflows/close-labeler.yml
index 41d68f7178ba..61e4510503bf 100644
--- a/.github/workflows/close-labeler.yml
+++ b/.github/workflows/close-labeler.yml
@@ -12,7 +12,7 @@ jobs:
if: github.event.pull_request.merged == true
runs-on: ubuntu-latest
steps:
- - uses: actions/github-script@v6
+ - uses: actions/github-script@v7
with:
github-token: ${{ secrets.CLOSE_LABELER_GITHUB_TOKEN }}
script: |
diff --git a/.github/workflows/github-release.yml b/.github/workflows/github-release.yml
index fb6e9929397a..9fe4edc313b6 100644
--- a/.github/workflows/github-release.yml
+++ b/.github/workflows/github-release.yml
@@ -89,7 +89,7 @@ jobs:
# Upload the build artifact so that it can be used by the test & deploy job in the workflow
- name: Upload react build bundle
- uses: actions/upload-artifact@v3
+ uses: actions/upload-artifact@v4
with:
name: client-build
path: app/client/build.tar
@@ -136,7 +136,7 @@ jobs:
ls -l dist
- name: Upload server build bundle
- uses: actions/upload-artifact@v3
+ uses: actions/upload-artifact@v4
with:
name: server-build
path: app/server/dist/
@@ -189,7 +189,7 @@ jobs:
# Upload the build artifacts and dependencies so that it can be used by the test & deploy job in other workflows
- name: Upload rts build bundle
- uses: actions/upload-artifact@v3
+ uses: actions/upload-artifact@v4
with:
name: rts-dist
path: app/client/packages/rts/rts-dist.tar
@@ -210,7 +210,7 @@ jobs:
uses: depot/setup-action@v1
- name: Download the client build artifact
- uses: actions/download-artifact@v3
+ uses: actions/download-artifact@v4
with:
name: client-build
path: app/client
@@ -223,13 +223,13 @@ jobs:
rm app/client/build.tar
- name: Download the server build artifact
- uses: actions/download-artifact@v3
+ uses: actions/download-artifact@v4
with:
name: server-build
path: app/server/dist
- name: Download the rts build artifact
- uses: actions/download-artifact@v3
+ uses: actions/download-artifact@v4
with:
name: rts-dist
path: app/client/packages/rts/dist
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 ad5e14d8261d..ec23a20cfccc 100644
--- a/.github/workflows/on-demand-build-docker-image-deploy-preview.yml
+++ b/.github/workflows/on-demand-build-docker-image-deploy-preview.yml
@@ -94,7 +94,7 @@ jobs:
run: |
vercel deploy --prebuilt --token=${{ secrets.VERCEL_TOKEN }} | tee -a ~/run_result.txt
- - uses: actions/github-script@v6
+ - uses: actions/github-script@v7
with:
script: |
const dpUrl = require("fs").readFileSync(process.env.HOME + "/run_result.txt", "utf8")
@@ -134,7 +134,7 @@ jobs:
run: echo "git_hash=$(git rev-parse --short HEAD)" >> $GITHUB_OUTPUT
- name: Download the client build artifact
- uses: actions/download-artifact@v3
+ uses: actions/download-artifact@v4
with:
name: client-build
path: app/client
@@ -146,13 +146,13 @@ jobs:
tar -xvf app/client/build.tar -C app/client/build
- name: Download the server build artifact
- uses: actions/download-artifact@v3
+ uses: actions/download-artifact@v4
with:
name: server-build
path: app/server/dist
- name: Download the rts build artifact
- uses: actions/download-artifact@v3
+ uses: actions/download-artifact@v4
with:
name: rts-dist
path: app/client/packages/rts/dist
diff --git a/.github/workflows/pr-cypress.yml b/.github/workflows/pr-cypress.yml
index 1825181da6e7..f29916920eda 100644
--- a/.github/workflows/pr-cypress.yml
+++ b/.github/workflows/pr-cypress.yml
@@ -104,7 +104,7 @@ jobs:
DB_PWD: ${{ secrets.CYPRESS_DB_PWD }}
RUN_ID: ${{ github.run_id }}
ATTEMPT_NUMBER: ${{ github.run_attempt }}
- uses: actions/github-script@v6
+ uses: actions/github-script@v7
with:
script: |
const { Pool } = require("pg");
@@ -151,7 +151,7 @@ jobs:
# This is done for debugging
- name: Upload combined failed spec
if: needs.ci-test.result != 'success'
- uses: actions/upload-artifact@v3
+ uses: actions/upload-artifact@v4
with:
name: combined_failed_spec_ci
path: ~/combined_failed_spec_ci
diff --git a/.github/workflows/rts-build.yml b/.github/workflows/rts-build.yml
index 62eecccd55f7..5ad6740533a8 100644
--- a/.github/workflows/rts-build.yml
+++ b/.github/workflows/rts-build.yml
@@ -149,7 +149,7 @@ jobs:
# Upload the build artifacts and dependencies so that it can be used by the test & deploy job in other workflows
- name: Upload rts build bundle
- uses: actions/upload-artifact@v3
+ uses: actions/upload-artifact@v4
with:
name: rts-dist
path: app/client/packages/rts/rts-dist.tar
diff --git a/.github/workflows/server-build.yml b/.github/workflows/server-build.yml
index d19e288cda64..9c09c8aca916 100644
--- a/.github/workflows/server-build.yml
+++ b/.github/workflows/server-build.yml
@@ -108,7 +108,7 @@ jobs:
- name: Download the failed test artifact in case of rerun
if: steps.run_result.outputs.run_result == 'failedtest' && (steps.changed-files-specific.outputs.any_changed == 'true' || github.event_name == 'push' || github.event_name == 'workflow_dispatch' || github.event_name == 'schedule')
- uses: actions/download-artifact@v3
+ uses: actions/download-artifact@v4
with:
name: failed-server-tests
path: ~/failed-server-tests
@@ -222,7 +222,7 @@ jobs:
- name: Upload the failed tests report
if: always()
- uses: actions/upload-artifact@v3
+ uses: actions/upload-artifact@v4
with:
name: failed-server-tests
path: app/server/failed-server-tests.txt
@@ -262,7 +262,7 @@ jobs:
# Upload the build artifact so that it can be used by the test & deploy job in the workflow
- name: Upload server build bundle
- uses: actions/upload-artifact@v3
+ uses: actions/upload-artifact@v4
with:
name: server-build
path: app/server/dist/
diff --git a/.github/workflows/test-build-docker-image.yml b/.github/workflows/test-build-docker-image.yml
index 6535a574394a..1b5efeef0d0e 100644
--- a/.github/workflows/test-build-docker-image.yml
+++ b/.github/workflows/test-build-docker-image.yml
@@ -153,7 +153,7 @@ jobs:
rm -f ~/combined_failed_spec_ci
# Download failed_spec_ci list for all CI container jobs
- - uses: actions/download-artifact@v3
+ - uses: actions/download-artifact@v4
if: needs.ci-test.result != 'success'
id: download_ci
with:
@@ -257,7 +257,7 @@ jobs:
# This is done for debugging.
- name: upload combined failed spec
if: needs.ci-test.result != 'success'
- uses: actions/upload-artifact@v3
+ uses: actions/upload-artifact@v4
with:
name: combined_failed_spec_ci
path: ~/combined_failed_spec_ci
@@ -292,7 +292,7 @@ jobs:
uses: actions/checkout@v4
- name: Download the react build artifact
- uses: actions/download-artifact@v3
+ uses: actions/download-artifact@v4
with:
name: client-build
path: app/client
@@ -304,13 +304,13 @@ jobs:
tar -xvf app/client/build.tar -C app/client/build
- name: Download the server build artifact
- uses: actions/download-artifact@v3
+ uses: actions/download-artifact@v4
with:
name: server-build
path: app/server/dist
- name: Download the rts build artifact
- uses: actions/download-artifact@v3
+ uses: actions/download-artifact@v4
with:
name: rts-dist
path: app/client/packages/rts/dist
@@ -367,7 +367,7 @@ jobs:
uses: actions/checkout@v4
- name: Download the react build artifact
- uses: actions/download-artifact@v3
+ uses: actions/download-artifact@v4
with:
name: client-build
path: app/client
@@ -379,13 +379,13 @@ jobs:
tar -xvf app/client/build.tar -C app/client/build
- name: Download the server build artifact
- uses: actions/download-artifact@v3
+ uses: actions/download-artifact@v4
with:
name: server-build
path: app/server/dist
- name: Download the rts build artifact
- uses: actions/download-artifact@v3
+ uses: actions/download-artifact@v4
with:
name: rts-dist
path: app/client/packages/rts/dist
|
4ae0b5b1deec8e1143d5dae520436f5bf7099c9f
|
2022-02-23 21:56:57
|
Nayan
|
fix: Set comment authors email address as reply to field in comment notification email (#11251)
| false
|
Set comment authors email address as reply to field in comment notification email (#11251)
|
fix
|
diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/notifications/EmailSender.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/notifications/EmailSender.java
index 698cbb5cbd1d..996816bbd257 100644
--- a/app/server/appsmith-server/src/main/java/com/appsmith/server/notifications/EmailSender.java
+++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/notifications/EmailSender.java
@@ -7,6 +7,7 @@
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;
+import org.springframework.util.StringUtils;
import reactor.core.Exceptions;
import reactor.core.publisher.Mono;
import reactor.core.scheduler.Schedulers;
@@ -37,11 +38,11 @@ public EmailSender(JavaMailSender javaMailSender, EmailConfig emailConfig) {
REPLY_TO = makeReplyTo();
}
- public Mono<Boolean> sendMail(String to, String subject, String text) {
- return sendMail(to, subject, text, null);
+ public Mono<Boolean> sendMail(String to, String subject, String text, Map<String, ? extends Object> params) {
+ return sendMail(to, subject, text, params, null);
}
- public Mono<Boolean> sendMail(String to, String subject, String text, Map<String, ? extends Object> params) {
+ public Mono<Boolean> sendMail(String to, String subject, String text, Map<String, ? extends Object> params, String replyTo) {
/**
* Creating a publisher which sends email in a blocking fashion, subscribing on the bounded elastic
@@ -58,7 +59,7 @@ public Mono<Boolean> sendMail(String to, String subject, String text, Map<String
}
})
.doOnNext(emailBody -> {
- sendMailSync(to, subject, emailBody);
+ sendMailSync(to, subject, emailBody, replyTo);
})
.subscribeOn(Schedulers.boundedElastic())
.subscribe();
@@ -74,7 +75,7 @@ public Mono<Boolean> sendMail(String to, String subject, String text, Map<String
* @param subject Subject string.
* @param text HTML Body of the message. This method assumes UTF-8.
*/
- private void sendMailSync(String to, String subject, String text) {
+ private void sendMailSync(String to, String subject, String text, String replyTo) {
log.debug("Got request to send email to: {} with subject: {}", to, subject);
// Don't send an email for local, dev or test environments
if (!emailConfig.isEmailEnabled()) {
@@ -96,7 +97,9 @@ private void sendMailSync(String to, String subject, String text) {
if (emailConfig.getMailFrom() != null) {
helper.setFrom(emailConfig.getMailFrom());
}
- if (REPLY_TO != null) {
+ if(StringUtils.hasLength(replyTo)) {
+ helper.setReplyTo(replyTo);
+ } else if (REPLY_TO != null) {
helper.setReplyTo(REPLY_TO);
}
helper.setSubject(subject);
diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ce/EmailEventHandlerCEImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ce/EmailEventHandlerCEImpl.java
index 35015d59805d..03122e5fdddc 100644
--- a/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ce/EmailEventHandlerCEImpl.java
+++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ce/EmailEventHandlerCEImpl.java
@@ -222,7 +222,9 @@ private Mono<Boolean> getAddCommentEmailSenderMono(UserRole receiverUserRole, Co
} else {
templateParams.put("Replied", true);
}
- return emailSender.sendMail(receiverEmail, emailSubject, COMMENT_ADDED_EMAIL_TEMPLATE, templateParams);
+ return emailSender.sendMail(
+ receiverEmail, emailSubject, COMMENT_ADDED_EMAIL_TEMPLATE, templateParams, comment.getAuthorUsername()
+ );
}
private Mono<Boolean> geBotEmailSenderMono(Comment comment, String originHeader, Organization organization, Application application) {
diff --git a/app/server/appsmith-server/src/test/java/com/appsmith/server/solutions/EmailEventHandlerTest.java b/app/server/appsmith-server/src/test/java/com/appsmith/server/solutions/EmailEventHandlerTest.java
index 4dc4db5352c1..f7b2fccaab67 100644
--- a/app/server/appsmith-server/src/test/java/com/appsmith/server/solutions/EmailEventHandlerTest.java
+++ b/app/server/appsmith-server/src/test/java/com/appsmith/server/solutions/EmailEventHandlerTest.java
@@ -182,7 +182,7 @@ public void handle_WhenValidCommentAddedEvent_SendEmailCalled() {
);
// check email sender was called with expected template and subject
Mockito.verify(emailSender, Mockito.times(1)).sendMail(
- eq(emailReceiverUsername), eq(expectedEmailSubject), eq(COMMENT_ADDED_EMAIL_TEMPLATE), Mockito.anyMap()
+ eq(emailReceiverUsername), eq(expectedEmailSubject), eq(COMMENT_ADDED_EMAIL_TEMPLATE), Mockito.anyMap(), eq(authorUserName)
);
}
@@ -254,7 +254,7 @@ public void handle_WhenUserMentionedEvent_ReturnsTrue() {
// check email sender was called with expected template and subject
Mockito.verify(emailSender, Mockito.times(1)).sendMail(
- eq(emailReceiverUsername), eq(expectedEmailSubject), eq(COMMENT_ADDED_EMAIL_TEMPLATE), Mockito.anyMap()
+ eq(emailReceiverUsername), eq(expectedEmailSubject), eq(COMMENT_ADDED_EMAIL_TEMPLATE), Mockito.anyMap(), eq(authorUserName)
);
}
|
26039e9e20cbd64b7543fff14720e98756941b53
|
2023-12-11 11:29:15
|
sneha122
|
feat: release start with data solution (#29480)
| false
|
release start with data solution (#29480)
|
feat
|
diff --git a/app/client/src/ce/pages/Applications/CreateNewAppsOption.tsx b/app/client/src/ce/pages/Applications/CreateNewAppsOption.tsx
index d594937c3002..18e5f80ca515 100644
--- a/app/client/src/ce/pages/Applications/CreateNewAppsOption.tsx
+++ b/app/client/src/ce/pages/Applications/CreateNewAppsOption.tsx
@@ -50,7 +50,6 @@ import styled from "styled-components";
import AnalyticsUtil from "utils/AnalyticsUtil";
import history from "utils/history";
import { builderURL } from "@appsmith/RouteBuilder";
-import localStorage from "utils/localStorage";
import { getDatasource, getPlugin } from "@appsmith/selectors/entitiesSelector";
import type { Plugin } from "api/PluginApi";
import { PluginPackageName, PluginType } from "entities/Action";
@@ -230,32 +229,14 @@ const CreateNewAppsOption = ({
};
const onClickStartWithData = () => {
- const devEnabled = localStorage.getItem(
- "ab_onboarding_flow_start_with_data_dev_only_enabled",
- );
- if (devEnabled) {
- // fetch plugins information to show list of all plugins
- AnalyticsUtil.logEvent("CREATE_APP_FROM_DATA");
- dispatch(fetchPlugins());
- dispatch(fetchMockDatasources());
- if (application?.workspaceId) {
- dispatch(fetchingEnvironmentConfigs(application?.workspaceId, true));
- }
- setUseType(START_WITH_TYPE.DATA);
- } else {
- if (application) {
- AnalyticsUtil.logEvent("CREATE_APP_FROM_DATA", {
- shortcut: "true",
- });
- dispatch(
- firstTimeUserOnboardingInit(
- application.id,
- application.defaultPageId as string,
- "datasources/NEW",
- ),
- );
- }
+ AnalyticsUtil.logEvent("CREATE_APP_FROM_DATA");
+ // fetch plugins information to show list of all plugins
+ dispatch(fetchPlugins());
+ dispatch(fetchMockDatasources());
+ if (application?.workspaceId) {
+ dispatch(fetchingEnvironmentConfigs(application?.workspaceId, true));
}
+ setUseType(START_WITH_TYPE.DATA);
};
const goBackToInitialScreen = () => {
|
337aa412ebed8cc717c1fb6576a9913960ddecfd
|
2023-04-25 05:59:40
|
Aishwarya-U-R
|
test: Cypress tests - Grouping logical it blocks - Part 2 (#22623)
| false
|
Cypress tests - Grouping logical it blocks - Part 2 (#22623)
|
test
|
diff --git a/app/client/cypress/integration/Regression_TestSuite/ClientSideTests/ActionExecution/Error_handling_spec.js b/app/client/cypress/integration/Regression_TestSuite/ClientSideTests/ActionExecution/Error_handling_spec.js
index 679ed049ef97..d1f8f2ad75ae 100644
--- a/app/client/cypress/integration/Regression_TestSuite/ClientSideTests/ActionExecution/Error_handling_spec.js
+++ b/app/client/cypress/integration/Regression_TestSuite/ClientSideTests/ActionExecution/Error_handling_spec.js
@@ -14,7 +14,7 @@ describe("Test Create Api and Bind to Button widget", function () {
});
});
- it("1. Call the api without error handling", () => {
+ it("1. Call the api with & without error handling", () => {
cy.SearchEntityandOpen("Button1");
cy.get(widgetsPage.toggleOnClick)
.invoke("attr", "class")
@@ -45,9 +45,8 @@ describe("Test Create Api and Bind to Button widget", function () {
.should("contain.text", "failed to execute");
cy.get(publishPage.backToEditor).click({ force: true });
- });
- it("2. Call the api with error handling", () => {
+ //With Error handling
cy.SearchEntityandOpen("Button1");
cy.get(".t--property-control-onclick").then(($el) => {
diff --git a/app/client/cypress/integration/Regression_TestSuite/ClientSideTests/ActionExecution/setInterval_spec.js b/app/client/cypress/integration/Regression_TestSuite/ClientSideTests/ActionExecution/setInterval_spec.js
index eeb604f3eaca..74399e3c02d7 100644
--- a/app/client/cypress/integration/Regression_TestSuite/ClientSideTests/ActionExecution/setInterval_spec.js
+++ b/app/client/cypress/integration/Regression_TestSuite/ClientSideTests/ActionExecution/setInterval_spec.js
@@ -29,9 +29,8 @@ describe("Test Create Api and Bind to Button widget", function () {
"onClick",
"{{setInterval(() => { Api1.run();}, 5000, 'myInterval');}}",
);
- });
- it("2. Works in the published version", () => {
+ //Works in the published version"
cy.PublishtheApp();
cy.wait(3000);
cy.get("span:contains('Submit')").closest("div").click();
@@ -50,7 +49,7 @@ describe("Test Create Api and Bind to Button widget", function () {
cy.get(publishPage.backToEditor).click({ force: true });
});
- it("3. Selects clear interval function, Fill clearInterval action creator and test code generated", () => {
+ it("2. Selects clear interval function, Fill clearInterval action creator and test code generated", () => {
cy.SearchEntityandOpen("Button1");
jsEditor.DisableJSContext("onClick");
cy.get(".action-block-tree").click({ force: true });
diff --git a/app/client/cypress/integration/Regression_TestSuite/ClientSideTests/BugTests/ApiBugs_Spec.ts b/app/client/cypress/integration/Regression_TestSuite/ClientSideTests/BugTests/ApiBugs_Spec.ts
new file mode 100644
index 000000000000..2849be9d35f6
--- /dev/null
+++ b/app/client/cypress/integration/Regression_TestSuite/ClientSideTests/BugTests/ApiBugs_Spec.ts
@@ -0,0 +1,60 @@
+import * as _ from "../../../../support/Objects/ObjectsCore";
+import { Widgets } from "../../../../support/Pages/DataSources";
+
+import {
+ ERROR_ACTION_EXECUTE_FAIL,
+ createMessage,
+} from "../../../../support/Objects/CommonErrorMessages";
+
+describe("API Bugs", function () {
+ it("1. Bug 14037: User gets an error even when table widget is added from the API page successfully", function () {
+ _.apiPage.CreateAndFillApi("https://mock-api.appsmith.com/users", "Api1");
+ _.apiPage.RunAPI();
+
+ _.dataSources.AddSuggesstedWidget(Widgets.Table);
+
+ _.debuggerHelper.AssertErrorCount(0);
+ });
+
+ it("2. Bug 16377, When Api url has dynamic binding expressions, ensure the url and path derived is not corrupting Api execution", function () {
+ //Since the specified expression always returns true - it will never run mock-apis - which actually doesn't exist
+ const apiUrl = `http://host.docker.internal:5001/v1/{{true ? 'mock-api' : 'mock-apis'}}?records=10`;
+
+ _.apiPage.CreateAndFillApi(apiUrl, "BindingExpressions");
+ _.apiPage.RunAPI();
+ _.agHelper.AssertElementAbsence(
+ _.locators._specificToast(
+ createMessage(ERROR_ACTION_EXECUTE_FAIL, "BindingExpressions"),
+ ),
+ ); //Assert that an error is not returned.
+ _.apiPage.ResponseStatusCheck("200 OK");
+ _.agHelper.ActionContextMenuWithInPane("Delete");
+ });
+
+ it("3. Bug 18876 Ensures application does not crash when saving datasource", () => {
+ _.apiPage.CreateAndFillApi(
+ "https://www.jsonplaceholder.com",
+ "FirstAPI",
+ 10000,
+ "POST",
+ );
+ _.apiPage.SelectPaneTab("Authentication");
+ cy.get(_.apiPage._saveAsDS).last().click({ force: true });
+ cy.get(".t--close-editor").click({ force: true });
+ cy.get(_.dataSources._datasourceModalSave).click();
+ // ensures app does not crash and datasource is saved.
+ cy.contains("Edit Datasource to access authentication settings").should(
+ "exist",
+ );
+ });
+
+ it("4. Bug 16683, When Api url has dynamic binding expressions, ensures the query params is not truncated", function () {
+ const apiUrl = `https://echo.hoppscotch.io/v6/deployments?limit=4{{Math.random() > 0.5 ? '¶m1=5' : '¶m2=6'}}`;
+
+ _.apiPage.CreateAndFillApi(apiUrl, "BindingExpressions");
+ _.apiPage.ValidateQueryParams({
+ key: "limit",
+ value: "4{{Math.random() > 0.5 ? '¶m1=5' : '¶m2=6'}}",
+ });
+ });
+});
diff --git a/app/client/cypress/integration/Regression_TestSuite/ClientSideTests/BugTests/Bug14037_Spec.ts b/app/client/cypress/integration/Regression_TestSuite/ClientSideTests/BugTests/Bug14037_Spec.ts
deleted file mode 100644
index 4093ebf07dd8..000000000000
--- a/app/client/cypress/integration/Regression_TestSuite/ClientSideTests/BugTests/Bug14037_Spec.ts
+++ /dev/null
@@ -1,13 +0,0 @@
-import * as _ from "../../../../support/Objects/ObjectsCore";
-import { Widgets } from "../../../../support/Pages/DataSources";
-
-describe("Error logged when adding a suggested table widget", function () {
- it("Bug 14037: User gets an error even when table widget is added from the API page successfully", function () {
- cy.fixture("datasources").then((datasourceFormData: any) => {
- _.apiPage.CreateAndFillApi(datasourceFormData["mockApiUrl"], "Api1");
- _.apiPage.RunAPI();
- _.dataSources.AddSuggesstedWidget(Widgets.Table);
- _.debuggerHelper.AssertErrorCount(0);
- });
- });
-});
diff --git a/app/client/cypress/integration/Regression_TestSuite/ClientSideTests/BugTests/Bug15909_Spec.ts b/app/client/cypress/integration/Regression_TestSuite/ClientSideTests/BugTests/Bug15909_Spec.ts
index 92e24d5356aa..1a6a85f1507a 100644
--- a/app/client/cypress/integration/Regression_TestSuite/ClientSideTests/BugTests/Bug15909_Spec.ts
+++ b/app/client/cypress/integration/Regression_TestSuite/ClientSideTests/BugTests/Bug15909_Spec.ts
@@ -4,8 +4,7 @@ import { WIDGET } from "../../../../locators/WidgetLocators";
const jsEditor = ObjectsRegistry.JSEditor,
ee = ObjectsRegistry.EntityExplorer,
agHelper = ObjectsRegistry.AggregateHelper,
- propPane = ObjectsRegistry.PropertyPane,
- CommonLocators = ObjectsRegistry.CommonLocators;
+ propPane = ObjectsRegistry.PropertyPane;
describe("JS Function Execution", function () {
before(() => {
diff --git a/app/client/cypress/integration/Regression_TestSuite/ClientSideTests/BugTests/Bug16377_spec.ts b/app/client/cypress/integration/Regression_TestSuite/ClientSideTests/BugTests/Bug16377_spec.ts
deleted file mode 100644
index 89f6e8a47360..000000000000
--- a/app/client/cypress/integration/Regression_TestSuite/ClientSideTests/BugTests/Bug16377_spec.ts
+++ /dev/null
@@ -1,25 +0,0 @@
-import { ObjectsRegistry } from "../../../../support/Objects/Registry";
-import {
- ERROR_ACTION_EXECUTE_FAIL,
- createMessage,
-} from "../../../../support/Objects/CommonErrorMessages";
-
-const locator = ObjectsRegistry.CommonLocators,
- apiPage = ObjectsRegistry.ApiPage,
- agHelper = ObjectsRegistry.AggregateHelper;
-
-describe("Binding Expressions should not be truncated in Url and path extraction", function () {
- it("Bug 16377, When Api url has dynamic binding expressions, ensure the url and path derived is not corrupting Api execution", function () {
- //Since the specified expression always returns true - it will never run mock-apis - which actually doesn't exist
- const apiUrl = `http://host.docker.internal:5001/v1/{{true ? 'mock-api' : 'mock-apis'}}?records=10`;
-
- apiPage.CreateAndFillApi(apiUrl, "BindingExpressions");
- apiPage.RunAPI();
- agHelper.AssertElementAbsence(
- locator._specificToast(
- createMessage(ERROR_ACTION_EXECUTE_FAIL, "BindingExpressions"),
- ),
- ); //Assert that an error is not returned.
- apiPage.ResponseStatusCheck("200 OK");
- });
-});
diff --git a/app/client/cypress/integration/Regression_TestSuite/ClientSideTests/BugTests/Bug16683_Spec.ts b/app/client/cypress/integration/Regression_TestSuite/ClientSideTests/BugTests/Bug16683_Spec.ts
deleted file mode 100644
index df391d7a184c..000000000000
--- a/app/client/cypress/integration/Regression_TestSuite/ClientSideTests/BugTests/Bug16683_Spec.ts
+++ /dev/null
@@ -1,14 +0,0 @@
-import { ObjectsRegistry } from "../../../../support/Objects/Registry";
-
-const apiPage = ObjectsRegistry.ApiPage;
-describe("Binding Expressions should not be truncated in Url Query Param", function () {
- it("Bug 16683, When Api url has dynamic binding expressions, ensures the query params is not truncated", function () {
- const apiUrl = `https://echo.hoppscotch.io/v6/deployments?limit=4{{Math.random() > 0.5 ? '¶m1=5' : '¶m2=6'}}`;
-
- apiPage.CreateAndFillApi(apiUrl, "BindingExpressions");
- apiPage.ValidateQueryParams({
- key: "limit",
- value: "4{{Math.random() > 0.5 ? '¶m1=5' : '¶m2=6'}}",
- });
- });
-});
diff --git a/app/client/cypress/integration/Regression_TestSuite/ClientSideTests/BugTests/Bug18035_Spec.ts b/app/client/cypress/integration/Regression_TestSuite/ClientSideTests/BugTests/Bug18035_Spec.ts
index 2f703ead36b6..21217a251293 100644
--- a/app/client/cypress/integration/Regression_TestSuite/ClientSideTests/BugTests/Bug18035_Spec.ts
+++ b/app/client/cypress/integration/Regression_TestSuite/ClientSideTests/BugTests/Bug18035_Spec.ts
@@ -23,4 +23,11 @@ describe("Bug 18035: Updates save button text on datasource discard popup", func
agHelper.AssertContains("SAVE", "exist", dataSources._datasourceModalSave);
cy.get(dataSources._datasourceModalDoNotSave).click();
});
+
+ it("3. Bug 19426: Testing empty datasource without saving should not throw 404", function () {
+ dataSources.NavigateToDSCreateNew();
+ dataSources.CreatePlugIn("S3");
+ dataSources.TestDatasource(false);
+ dataSources.SaveDSFromDialog(false);
+ });
});
diff --git a/app/client/cypress/integration/Regression_TestSuite/ClientSideTests/BugTests/Bug18876_Spec.ts b/app/client/cypress/integration/Regression_TestSuite/ClientSideTests/BugTests/Bug18876_Spec.ts
deleted file mode 100644
index 5b8738d9c97b..000000000000
--- a/app/client/cypress/integration/Regression_TestSuite/ClientSideTests/BugTests/Bug18876_Spec.ts
+++ /dev/null
@@ -1,23 +0,0 @@
-import { ObjectsRegistry } from "../../../../support/Objects/Registry";
-
-const apiPage = ObjectsRegistry.ApiPage,
- datasource = ObjectsRegistry.DataSources;
-
-describe("Application crashes when saving datasource", () => {
- it("ensures application does not crash when saving datasource", () => {
- apiPage.CreateAndFillApi(
- "https://www.jsonplaceholder.com",
- "FirstAPI",
- 10000,
- "POST",
- );
- apiPage.SelectPaneTab("Authentication");
- cy.get(apiPage._saveAsDS).last().click({ force: true });
- cy.get(".t--close-editor").click({ force: true });
- cy.get(datasource._datasourceModalSave).click();
- // ensures app does not crash and datasource is saved.
- cy.contains("Edit Datasource to access authentication settings").should(
- "exist",
- );
- });
-});
diff --git a/app/client/cypress/integration/Regression_TestSuite/ClientSideTests/BugTests/Bug19426_spec.ts b/app/client/cypress/integration/Regression_TestSuite/ClientSideTests/BugTests/Bug19426_spec.ts
deleted file mode 100644
index a981012b4ead..000000000000
--- a/app/client/cypress/integration/Regression_TestSuite/ClientSideTests/BugTests/Bug19426_spec.ts
+++ /dev/null
@@ -1,12 +0,0 @@
-import { ObjectsRegistry } from "../../../../support/Objects/Registry";
-
-const dataSources = ObjectsRegistry.DataSources;
-
-describe("Testing empty datasource without saving should not throw 404", function () {
- it("Bug 19426: Create empty S3 datasource, test it", function () {
- dataSources.NavigateToDSCreateNew();
- dataSources.CreatePlugIn("S3");
- dataSources.TestDatasource(false);
- dataSources.SaveDSFromDialog(false);
- });
-});
diff --git a/app/client/cypress/integration/Regression_TestSuite/ClientSideTests/BugTests/Bug9334_Spec.ts b/app/client/cypress/integration/Regression_TestSuite/ClientSideTests/BugTests/Bug9334_Spec.ts
index 3c0c61a18309..84e458ca7d5d 100644
--- a/app/client/cypress/integration/Regression_TestSuite/ClientSideTests/BugTests/Bug9334_Spec.ts
+++ b/app/client/cypress/integration/Regression_TestSuite/ClientSideTests/BugTests/Bug9334_Spec.ts
@@ -9,18 +9,15 @@ const agHelper = ObjectsRegistry.AggregateHelper,
appSettings = ObjectsRegistry.AppSettings;
describe("Bug 9334: The Select widget value is sent as null when user switches between the pages", function () {
- before(() => {
+ before("Change Theme & Create Postgress DS", () => {
appSettings.OpenPaneAndChangeTheme("Pampas");
- });
-
- it("1. Create Postgress DS", function () {
dataSources.CreateDataSource("Postgres");
cy.get("@dsName").then(($dsName) => {
dsName = $dsName;
});
});
- it("2. Create dummy pages for navigating", () => {
+ it("1. Create dummy pages for navigating", () => {
//CRUD page 2
ee.AddNewPage();
ee.AddNewPage("generate-page");
@@ -57,11 +54,8 @@ describe("Bug 9334: The Select widget value is sent as null when user switches b
agHelper.GetNClick(dataSources._visibleTextSpan("GOT IT"));
table.WaitUntilTableLoad();
});
-
- //Since its failing continuously skiping now
- it("3. Navigate & Assert toast", () => {
+ it("2. Navigate & Assert toast", () => {
//Navigating between CRUD (Page3) & EmptyPage (Page2):
-
ee.SelectEntityByName("Page1");
agHelper.Sleep(2000);
ee.SelectEntityByName("Page2");
diff --git a/app/client/cypress/integration/Regression_TestSuite/ClientSideTests/BugTests/MultipleOnPageLoadConfirmation_Spec.ts b/app/client/cypress/integration/Regression_TestSuite/ClientSideTests/BugTests/MultipleOnPageLoadConfirmation_Spec.ts
index 4465e79bb026..4f47bfec9e22 100644
--- a/app/client/cypress/integration/Regression_TestSuite/ClientSideTests/BugTests/MultipleOnPageLoadConfirmation_Spec.ts
+++ b/app/client/cypress/integration/Regression_TestSuite/ClientSideTests/BugTests/MultipleOnPageLoadConfirmation_Spec.ts
@@ -3,14 +3,13 @@ import { ObjectsRegistry } from "../../../../support/Objects/Registry";
const jsEditor = ObjectsRegistry.JSEditor,
agHelper = ObjectsRegistry.AggregateHelper,
ee = ObjectsRegistry.EntityExplorer,
- locator = ObjectsRegistry.CommonLocators,
deployMode = ObjectsRegistry.DeployMode;
describe("Multiple rejection of confirmation for onPageLoad function execution", function () {
before(() => {
ee.DragDropWidgetNVerify("buttonwidget", 300, 300);
});
- it("Works properly", function () {
+ it("1. Works properly", function () {
const FUNCTIONS_SETTINGS_DEFAULT_DATA = [
{
name: "myFun1",
diff --git a/app/client/cypress/integration/Regression_TestSuite/ClientSideTests/OtherUIFeatures/ApplicationURL_spec.js b/app/client/cypress/integration/Regression_TestSuite/ClientSideTests/OtherUIFeatures/ApplicationURL_spec.js
index 022ec9234f6d..5a1a6a6b28e7 100644
--- a/app/client/cypress/integration/Regression_TestSuite/ClientSideTests/OtherUIFeatures/ApplicationURL_spec.js
+++ b/app/client/cypress/integration/Regression_TestSuite/ClientSideTests/OtherUIFeatures/ApplicationURL_spec.js
@@ -3,7 +3,7 @@ const explorer = require("../../../../locators/explorerlocators.json");
describe("Slug URLs", () => {
let applicationName;
let applicationId;
- it("Checks URL redirection from legacy URLs to slug URLs", () => {
+ it("1. Checks URL redirection from legacy URLs to slug URLs", () => {
applicationId = localStorage.getItem("applicationId");
cy.location("pathname").then((pathname) => {
const pageId = pathname.split("/")[3]?.split("-").pop();
@@ -22,7 +22,7 @@ describe("Slug URLs", () => {
});
});
- it("Checks if application slug updates on the URL when application name changes", () => {
+ it("2. Checks if application slug updates on the URL when application name changes", () => {
cy.generateUUID().then((appName) => {
applicationName = appName;
cy.AppSetupForRename();
@@ -39,7 +39,7 @@ describe("Slug URLs", () => {
});
});
- it("Checks if page slug updates on the URL when page name changes", () => {
+ it("3. Checks if page slug updates on the URL when page name changes", () => {
cy.GlobalSearchEntity("Page1");
// cy.RenameEntity("Page renamed");
cy.get(`.t--entity-item:contains(Page1)`).within(() => {
@@ -61,7 +61,7 @@ describe("Slug URLs", () => {
});
});
- it("Check the url of old applications, upgrades version and compares appsmith.URL values", () => {
+ it("4. Check the url of old applications, upgrades version and compares appsmith.URL values", () => {
cy.request("PUT", `/api/v1/applications/${applicationId}`, {
applicationVersion: 1,
}).then((response) => {
@@ -136,7 +136,7 @@ describe("Slug URLs", () => {
});
});
- it("Checks redirect url", () => {
+ it("5. Checks redirect url", () => {
cy.url().then((url) => {
cy.LogOut();
cy.visit(url + "?embed=true&a=b");
diff --git a/app/client/cypress/integration/Regression_TestSuite/ClientSideTests/OtherUIFeatures/DynamicLayout_spec.js b/app/client/cypress/integration/Regression_TestSuite/ClientSideTests/OtherUIFeatures/DynamicLayout_spec.js
index 053ab689fced..eca9d5797786 100644
--- a/app/client/cypress/integration/Regression_TestSuite/ClientSideTests/OtherUIFeatures/DynamicLayout_spec.js
+++ b/app/client/cypress/integration/Regression_TestSuite/ClientSideTests/OtherUIFeatures/DynamicLayout_spec.js
@@ -5,10 +5,9 @@ describe("Dynamic Layout Functionality", function () {
it("Dynamic Layout - Change Layout", function () {
cy.get(commonlocators.layoutControls).last().click();
cy.get(commonlocators.canvas).invoke("width").should("be.eq", 450);
- });
- it("Dynamic Layout - New Page should have selected Layout", function () {
- cy.get(pages.AddPage).first().click();
+ //Dynamic Layout - New Page should have selected Layout
+ cy.get(pages.AddPage).first().click();
cy.get(commonlocators.canvas).invoke("width").should("be.eq", 450);
});
});
diff --git a/app/client/cypress/integration/Regression_TestSuite/ClientSideTests/OtherUIFeatures/EmptyCanvas_spec.ts b/app/client/cypress/integration/Regression_TestSuite/ClientSideTests/OtherUIFeatures/EmptyCanvas_spec.ts
index c3b943882d1f..e9a570440a54 100644
--- a/app/client/cypress/integration/Regression_TestSuite/ClientSideTests/OtherUIFeatures/EmptyCanvas_spec.ts
+++ b/app/client/cypress/integration/Regression_TestSuite/ClientSideTests/OtherUIFeatures/EmptyCanvas_spec.ts
@@ -1,33 +1,22 @@
import { WIDGET } from "../../../../locators/WidgetLocators";
import { ObjectsRegistry } from "../../../../support/Objects/Registry";
-const {
- AggregateHelper: agHelper,
- CommonLocators: locators,
- EntityExplorer: ee,
-} = ObjectsRegistry;
+const { CommonLocators: locators, EntityExplorer: ee } = ObjectsRegistry;
describe("Empty canvas ctas", () => {
- beforeEach(() => {
- agHelper.RestoreLocalStorageCache();
- });
-
- afterEach(() => {
- agHelper.SaveLocalStorageCache();
- });
-
- it("Ctas should not be shown in the second page", () => {
+ it("Ctas validations", () => {
+ //Ctas should not be shown in the second page
cy.get(locators._emptyCanvasCta).should("be.visible");
ee.AddNewPage();
cy.get(locators._emptyCanvasCta).should("not.exist");
ee.SelectEntityByName("Page1", "Pages");
- });
- it("Ctas should continue to show on refresh", () => {
+
+ //Ctas should continue to show on refresh
cy.get(locators._emptyCanvasCta).should("be.visible");
cy.reload();
cy.get(locators._emptyCanvasCta).should("be.visible");
- });
- it("Hide cta on adding a widget", () => {
+
+ //Hide cta on adding a widget
cy.get(locators._emptyCanvasCta).should("be.visible");
ee.DragDropWidgetNVerify(WIDGET.BUTTON, 200, 200);
cy.get(locators._emptyCanvasCta).should("not.exist");
diff --git a/app/client/cypress/integration/Regression_TestSuite/ClientSideTests/OtherUIFeatures/ExportApplication_spec.js b/app/client/cypress/integration/Regression_TestSuite/ClientSideTests/OtherUIFeatures/ExportApplication_spec.js
index d529d61d1d2d..c4c3e31552a3 100644
--- a/app/client/cypress/integration/Regression_TestSuite/ClientSideTests/OtherUIFeatures/ExportApplication_spec.js
+++ b/app/client/cypress/integration/Regression_TestSuite/ClientSideTests/OtherUIFeatures/ExportApplication_spec.js
@@ -16,7 +16,7 @@ describe("Export application as a JSON file", function () {
cy.wait(5000);
});
- it("Check if exporting app flow works as expected", function () {
+ it("1. Check if exporting app flow works as expected", function () {
cy.get(commonlocators.homeIcon).click({ force: true });
appname = localStorage.getItem("AppName");
cy.get(homePage.searchInput).type(appname);
@@ -41,7 +41,7 @@ describe("Export application as a JSON file", function () {
cy.LogOut();
});
- it("User with admin access,should be able to export the app", function () {
+ it("2. User with admin access,should be able to export the app", function () {
if (CURRENT_REPO === REPO.CE) {
cy.LogintoApp(Cypress.env("USERNAME"), Cypress.env("PASSWORD"));
cy.generateUUID().then((uid) => {
@@ -91,7 +91,7 @@ describe("Export application as a JSON file", function () {
}
});
- it("User with developer access,should not be able to export the app", function () {
+ it("3. User with developer access,should not be able to export the app", function () {
cy.LogintoApp(Cypress.env("USERNAME"), Cypress.env("PASSWORD"));
cy.generateUUID().then((uid) => {
workspaceId = uid;
@@ -136,7 +136,7 @@ describe("Export application as a JSON file", function () {
cy.LogOut();
});
- it("User with viewer access,should not be able to export the app", function () {
+ it("4. User with viewer access,should not be able to export the app", function () {
cy.LogintoApp(Cypress.env("USERNAME"), Cypress.env("PASSWORD"));
cy.generateUUID().then((uid) => {
workspaceId = uid;
diff --git a/app/client/cypress/integration/Regression_TestSuite/ClientSideTests/OtherUIFeatures/ForkApplication_spec.js b/app/client/cypress/integration/Regression_TestSuite/ClientSideTests/OtherUIFeatures/ForkApplication_spec.js
index df4936f6813e..c4a8fb93d8ef 100644
--- a/app/client/cypress/integration/Regression_TestSuite/ClientSideTests/OtherUIFeatures/ForkApplication_spec.js
+++ b/app/client/cypress/integration/Regression_TestSuite/ClientSideTests/OtherUIFeatures/ForkApplication_spec.js
@@ -15,7 +15,7 @@ describe("Fork application across workspaces", function () {
cy.addDsl(dsl);
});
- it("Check if the forked application has the same dsl as the original", function () {
+ it("1. Check if the forked application has the same dsl as the original", function () {
const appname = localStorage.getItem("AppName");
cy.SearchEntityandOpen("Input1");
cy.intercept("PUT", "/api/v1/layouts/*/pages/*").as("inputUpdate");
@@ -50,7 +50,7 @@ describe("Fork application across workspaces", function () {
});
});
- it("Non signed user should be able to fork a public forkable app", function () {
+ it("2. Non signed user should be able to fork a public forkable app", function () {
cy.NavigateToHome();
cy.get(homePage.homeIcon).click();
cy.get(homePage.optionsIcon).first().click();
diff --git a/app/client/cypress/integration/Regression_TestSuite/ClientSideTests/OtherUIFeatures/GlobalSearch_spec.js b/app/client/cypress/integration/Regression_TestSuite/ClientSideTests/OtherUIFeatures/GlobalSearch_spec.js
index ef67ff60994a..7a1388be6c5e 100644
--- a/app/client/cypress/integration/Regression_TestSuite/ClientSideTests/OtherUIFeatures/GlobalSearch_spec.js
+++ b/app/client/cypress/integration/Regression_TestSuite/ClientSideTests/OtherUIFeatures/GlobalSearch_spec.js
@@ -14,15 +14,14 @@ describe("GlobalSearch", function () {
cy.startRoutesForDatasource();
});
- it("Clicking on filter should show the filter menu", () => {
+ it("1. Clicking on filter should show the filter menu", () => {
cy.get(commonlocators.globalSearchTrigger).click({ force: true });
cy.contains(globalSearchLocators.docHint, "Snippets").click();
cy.get(globalSearchLocators.filterButton).click();
cy.contains("Reset Filter").should("be.visible");
cy.get("body").type("{esc}");
- });
- it("1. showsAndHidesUsingKeyboardShortcuts", () => {
+ //showsAndHidesUsingKeyboardShortcuts
// wait for the page to load
cy.get(commonlocators.canvas);
const isMac = Cypress.platform === "darwin";
diff --git a/app/client/cypress/integration/Regression_TestSuite/ClientSideTests/OtherUIFeatures/Inspect_Element_spec.js b/app/client/cypress/integration/Regression_TestSuite/ClientSideTests/OtherUIFeatures/Inspect_Element_spec.js
index 29fccb41fb68..b75a466ceabb 100644
--- a/app/client/cypress/integration/Regression_TestSuite/ClientSideTests/OtherUIFeatures/Inspect_Element_spec.js
+++ b/app/client/cypress/integration/Regression_TestSuite/ClientSideTests/OtherUIFeatures/Inspect_Element_spec.js
@@ -4,7 +4,7 @@ describe("Inspect Entity", function () {
before(() => {
cy.addDsl(dsl);
});
- it("Check whether depedencies and references are shown correctly", function () {
+ it("1. Check whether depedencies and references are shown correctly", function () {
cy.openPropertyPane("inputwidgetv2");
cy.testJsontext("defaultvalue", "{{Button1.text}}");
diff --git a/app/client/cypress/integration/Regression_TestSuite/ClientSideTests/OtherUIFeatures/Logs_spec.ts b/app/client/cypress/integration/Regression_TestSuite/ClientSideTests/OtherUIFeatures/Logs_spec.ts
index 5c577f12088d..1e78c0cb5d37 100644
--- a/app/client/cypress/integration/Regression_TestSuite/ClientSideTests/OtherUIFeatures/Logs_spec.ts
+++ b/app/client/cypress/integration/Regression_TestSuite/ClientSideTests/OtherUIFeatures/Logs_spec.ts
@@ -419,7 +419,7 @@ describe("Debugger logs", function () {
debuggerHelper.DoesConsoleLogExist("end: [0,1,2,3,4]");
});
- it("6. Bug #19115 - Objects that start with an underscore `_JSObject1` fail to be navigated from the debugger", function () {
+ it("19. Bug #19115 - Objects that start with an underscore `_JSObject1` fail to be navigated from the debugger", function () {
const JSOBJECT_WITH_UNNECCESARY_SEMICOLON = `export default {
myFun1: () => {
//write code here
diff --git a/app/client/cypress/integration/Regression_TestSuite/ClientSideTests/OtherUIFeatures/PageOnLoad_spec.ts b/app/client/cypress/integration/Regression_TestSuite/ClientSideTests/OtherUIFeatures/PageOnLoad_spec.ts
index 7a5188b3d366..8eae5736182d 100644
--- a/app/client/cypress/integration/Regression_TestSuite/ClientSideTests/OtherUIFeatures/PageOnLoad_spec.ts
+++ b/app/client/cypress/integration/Regression_TestSuite/ClientSideTests/OtherUIFeatures/PageOnLoad_spec.ts
@@ -9,7 +9,7 @@ describe("Check debugger logs state when there are onPageLoad actions", function
before(() => {
cy.addDsl(dsl);
});
- it("Check debugger logs state when there are onPageLoad actions", function () {
+ it("1. Check debugger logs state when there are onPageLoad actions", function () {
cy.openPropertyPane("tablewidget");
cy.testJsontext("tabledata", "{{TestApi.data.users}}");
cy.NavigateToAPI_Panel();
diff --git a/app/client/cypress/integration/Regression_TestSuite/ClientSideTests/OtherUIFeatures/PreviewMode_spec.js b/app/client/cypress/integration/Regression_TestSuite/ClientSideTests/OtherUIFeatures/PreviewMode_spec.js
index fb973b04fdf5..b0a86a37e5e9 100644
--- a/app/client/cypress/integration/Regression_TestSuite/ClientSideTests/OtherUIFeatures/PreviewMode_spec.js
+++ b/app/client/cypress/integration/Regression_TestSuite/ClientSideTests/OtherUIFeatures/PreviewMode_spec.js
@@ -8,14 +8,13 @@ describe("Preview mode functionality", function () {
cy.addDsl(dsl);
});
- it("checks entity explorer and property pane visiblity", function () {
+ it("1. Checks entity explorer and property pane visiblity", function () {
_.agHelper.GetNClick(_.locators._previewModeToggle("edit"));
// in preview mode, entity explorer and property pane are not visible
cy.get(".t--entity-explorer").should("not.be.visible");
cy.get(".t--property-pane-sidebar").should("not.be.visible");
- });
- it("checks if widgets can be selected or not", function () {
+ //checks if widgets can be selected or not
// in preview mode, entity explorer and property pane are not visible
// Also, draggable and resizable components are not available.
const selector = `.t--draggable-buttonwidget`;
@@ -27,7 +26,7 @@ describe("Preview mode functionality", function () {
).should("not.exist");
});
- it("check invisible widget should not show in proview mode and should show in edit mode", function () {
+ it("2. Check invisible widget should not show in proview mode and should show in edit mode", function () {
_.agHelper.GetNClick(_.locators._previewModeToggle("preview"));
cy.openPropertyPane("buttonwidget");
cy.UncheckWidgetProperties(commonlocators.visibleCheckbox);
@@ -43,8 +42,4 @@ describe("Preview mode functionality", function () {
_.agHelper.GetNClick(_.locators._previewModeToggle("preview"));
cy.get(`${publishPage.buttonWidget} button`).should("exist");
});
-
- afterEach(() => {
- // put your clean up code if any
- });
});
diff --git a/app/client/cypress/integration/Regression_TestSuite/ClientSideTests/OtherUIFeatures/ProductUpdates_spec.js b/app/client/cypress/integration/Regression_TestSuite/ClientSideTests/OtherUIFeatures/ProductUpdates_spec.js
index a4e01207d0b8..73f3f842abf8 100644
--- a/app/client/cypress/integration/Regression_TestSuite/ClientSideTests/OtherUIFeatures/ProductUpdates_spec.js
+++ b/app/client/cypress/integration/Regression_TestSuite/ClientSideTests/OtherUIFeatures/ProductUpdates_spec.js
@@ -1,7 +1,7 @@
const commonlocators = require("../../../../locators/commonlocators.json");
describe("Check for product updates button and modal", function () {
- it("Check if we should show the product updates button and it opens the updates modal", function () {
+ it("1. Check if we should show the product updates button and it opens the updates modal", function () {
cy.get(commonlocators.homeIcon).click({ force: true });
//eslint-disable-next-line cypress/no-unnecessary-waiting
cy.wait(2000);
diff --git a/app/client/cypress/integration/Regression_TestSuite/ClientSideTests/OtherUIFeatures/Redirects_spec.js b/app/client/cypress/integration/Regression_TestSuite/ClientSideTests/OtherUIFeatures/Redirects_spec.js
index f216433038e5..99e59bb5e33b 100644
--- a/app/client/cypress/integration/Regression_TestSuite/ClientSideTests/OtherUIFeatures/Redirects_spec.js
+++ b/app/client/cypress/integration/Regression_TestSuite/ClientSideTests/OtherUIFeatures/Redirects_spec.js
@@ -1,5 +1,5 @@
describe("Check for redirects associated with auth pages", function () {
- it("Should redirect away from auth pages if already logged in", function () {
+ it("1. Should redirect away from auth pages if already logged in", function () {
const loginPageRoute = "/user/login";
cy.visit(loginPageRoute);
// eslint-disable-next-line cypress/no-unnecessary-waiting
diff --git a/app/client/cypress/integration/Regression_TestSuite/ClientSideTests/OtherUIFeatures/Replay_spec.js b/app/client/cypress/integration/Regression_TestSuite/ClientSideTests/OtherUIFeatures/Replay_spec.js
index 25c15440a4db..71918a9029d9 100644
--- a/app/client/cypress/integration/Regression_TestSuite/ClientSideTests/OtherUIFeatures/Replay_spec.js
+++ b/app/client/cypress/integration/Regression_TestSuite/ClientSideTests/OtherUIFeatures/Replay_spec.js
@@ -12,7 +12,7 @@ describe("Undo/Redo functionality", function () {
cy.addDsl(dsl);
});
- it("checks undo/redo for new widgets", function () {
+ it("1. checks undo/redo for new widgets", function () {
cy.get(explorer.addWidget).click();
cy.dragAndDropToCanvas("checkboxwidget", { x: 200, y: 200 });
@@ -74,7 +74,7 @@ describe("Undo/Redo functionality", function () {
// });
// });
- it("checks undo/redo for toggle control in property pane", function () {
+ it("2. checks undo/redo for toggle control in property pane", function () {
cy.openPropertyPane("checkboxwidget");
cy.CheckWidgetProperties(commonlocators.disableCheckbox);
@@ -92,7 +92,7 @@ describe("Undo/Redo functionality", function () {
cy.get(widgetLocators.checkboxWidget + " " + "input").should("be.disabled");
});
- it("checks undo/redo for input control in property pane", function () {
+ it("3. checks undo/redo for input control in property pane", function () {
cy.get(widgetsPage.inputLabelControl).type("1");
cy.get(widgetsPage.inputLabelControl).contains("Label1");
@@ -107,7 +107,7 @@ describe("Undo/Redo functionality", function () {
cy.get(`${publish.checkboxWidget} label`).should("have.text", "Label1");
});
- it("checks undo/redo for deletion of widgets", function () {
+ it("4. checks undo/redo for deletion of widgets", function () {
cy.deleteWidget(widgetsPage.checkboxWidget);
cy.get(widgetsPage.checkboxWidget).should("not.exist");
@@ -120,7 +120,7 @@ describe("Undo/Redo functionality", function () {
// cy.get(widgetsPage.checkboxWidget).should("not.exist");
});
- it("checks if property Pane is open on undo/redo property changes", function () {
+ it("5. checks if property Pane is open on undo/redo property changes", function () {
cy.dragAndDropToCanvas("textwidget", { x: 400, y: 400 });
cy.wait(100);
@@ -142,7 +142,7 @@ describe("Undo/Redo functionality", function () {
cy.deleteWidget(widgetsPage.textWidget);
});
- it("checks if toast is shown while undo/redo widget deletion or creation only the first time", function () {
+ it("6. checks if toast is shown while undo/redo widget deletion or creation only the first time", function () {
cy.dragAndDropToCanvas("textwidget", { x: 400, y: 400 });
localStorage.removeItem("undoToastShown");
localStorage.removeItem("redoToastShown");
@@ -160,7 +160,7 @@ describe("Undo/Redo functionality", function () {
cy.deleteWidget(widgetsPage.textWidget);
});
- it("checks undo/redo for color picker", function () {
+ it("7. checks undo/redo for color picker", function () {
cy.dragAndDropToCanvas("textwidget", { x: 100, y: 100 });
cy.moveToStyleTab();
cy.selectColor("textcolor");
@@ -184,7 +184,7 @@ describe("Undo/Redo functionality", function () {
.should("contain", "#7e22ce");
});
- it("checks undo/redo for option control for radio button", function () {
+ it("8. checks undo/redo for option control for radio button", function () {
cy.dragAndDropToCanvas("radiogroupwidget", { x: 200, y: 600 });
cy.get(widgetsPage.RadioInput).first().type("1");
diff --git a/app/client/cypress/integration/Regression_TestSuite/ClientSideTests/OtherUIFeatures/Resize_spec.js b/app/client/cypress/integration/Regression_TestSuite/ClientSideTests/OtherUIFeatures/Resize_spec.js
index 46e21e9ae737..d3f1e8dcc52c 100644
--- a/app/client/cypress/integration/Regression_TestSuite/ClientSideTests/OtherUIFeatures/Resize_spec.js
+++ b/app/client/cypress/integration/Regression_TestSuite/ClientSideTests/OtherUIFeatures/Resize_spec.js
@@ -5,7 +5,7 @@ describe("Canvas Resize", function () {
before(() => {
cy.addDsl(dsl);
});
- it("Deleting bottom widget should resize canvas", function () {
+ it("1. Deleting bottom widget should resize canvas", function () {
const InitHeight = "2950px";
cy.get(commonlocators.dropTarget).should("have.css", "height", InitHeight);
cy.openPropertyPane("textwidget");
diff --git a/app/client/cypress/integration/Regression_TestSuite/ClientSideTests/OtherUIFeatures/TriggerErrors_spec.ts b/app/client/cypress/integration/Regression_TestSuite/ClientSideTests/OtherUIFeatures/TriggerErrors_spec.js
similarity index 92%
rename from app/client/cypress/integration/Regression_TestSuite/ClientSideTests/OtherUIFeatures/TriggerErrors_spec.ts
rename to app/client/cypress/integration/Regression_TestSuite/ClientSideTests/OtherUIFeatures/TriggerErrors_spec.js
index 06dd5e1f3eb2..c961f502ccff 100644
--- a/app/client/cypress/integration/Regression_TestSuite/ClientSideTests/OtherUIFeatures/TriggerErrors_spec.ts
+++ b/app/client/cypress/integration/Regression_TestSuite/ClientSideTests/OtherUIFeatures/TriggerErrors_spec.js
@@ -6,7 +6,7 @@ describe("Trigger errors in the debugger", function () {
before(() => {
cy.addDsl(dsl);
});
- it("Trigger errors need to be shown in the errors tab", function () {
+ it("1. Trigger errors need to be shown in the errors tab", function () {
cy.openPropertyPane("tablewidget");
cy.testJsontext("tabledata", `[{"name": 1}, {"name": 2}]`);
cy.focused().blur();
diff --git a/app/client/cypress/integration/Regression_TestSuite/ClientSideTests/OtherUIFeatures/Unique_key_spec.js b/app/client/cypress/integration/Regression_TestSuite/ClientSideTests/OtherUIFeatures/Unique_key_spec.js
index fd65e68485d4..756a329b2454 100644
--- a/app/client/cypress/integration/Regression_TestSuite/ClientSideTests/OtherUIFeatures/Unique_key_spec.js
+++ b/app/client/cypress/integration/Regression_TestSuite/ClientSideTests/OtherUIFeatures/Unique_key_spec.js
@@ -19,7 +19,7 @@ describe("Unique react keys", function () {
cy.addDsl(dsl);
});
- it("Should not create duplicate versions of widget on drop from explorer", function () {
+ it("1. Should not create duplicate versions of widget on drop from explorer", function () {
cy.get(explorer.addWidget).click();
cy.dragAndDropToCanvas("chartwidget", { x: 200, y: 200 });
cy.dragAndDropToCanvas("selectwidget", { x: 200, y: 600 });
@@ -31,7 +31,7 @@ describe("Unique react keys", function () {
cy.get(widgetsPage.selectwidget).should("have.length", 2);
});
- it("Should not create duplicate versions of widget on widget copy", function () {
+ it("2. Should not create duplicate versions of widget on widget copy", function () {
const modifierKey = Cypress.platform === "darwin" ? "meta" : "ctrl";
cy.get(explorer.addWidget).click();
cy.dragAndDropToCanvas("chartwidget", { x: 200, y: 200 });
diff --git a/app/client/cypress/integration/Regression_TestSuite/ClientSideTests/OtherUIFeatures/UpdateApplication_spec.js b/app/client/cypress/integration/Regression_TestSuite/ClientSideTests/OtherUIFeatures/UpdateApplication_spec.js
index 465f9b5317d8..59ba16af8d1b 100644
--- a/app/client/cypress/integration/Regression_TestSuite/ClientSideTests/OtherUIFeatures/UpdateApplication_spec.js
+++ b/app/client/cypress/integration/Regression_TestSuite/ClientSideTests/OtherUIFeatures/UpdateApplication_spec.js
@@ -10,7 +10,7 @@ describe("Update Application", () => {
.toString(36)
.slice(2, -1)}`;
- it("Open the application menu and update name and then check whether update is reflected in the application card", () => {
+ it("1. Open the application menu and update name and then check whether update is reflected in the application card", () => {
cy.get(commonlocators.homeIcon).click({ force: true });
appname = localStorage.getItem("AppName");
cy.get(homePage.searchInput).clear();
@@ -29,7 +29,7 @@ describe("Update Application", () => {
cy.get(homePage.applicationCardName).should("contain", appname);
});
- it("Open the application menu and update icon and then check whether update is reflected in the application card", () => {
+ it("2. Open the application menu and update icon and then check whether update is reflected in the application card", () => {
cy.get(homePage.applicationIconSelector).first().click();
cy.wait("@updateApplication")
.then((xhr) => {
@@ -43,7 +43,7 @@ describe("Update Application", () => {
});
});
- it("Check for errors in updating application name", () => {
+ it("3. Check for errors in updating application name", () => {
cy.get(commonlocators.homeIcon).click({ force: true });
cy.get(homePage.searchInput).clear();
cy.get(homePage.searchInput).type(appname);
@@ -71,7 +71,7 @@ describe("Update Application", () => {
);
});
- it("Updates the name of first application to very long name and checks whether update is reflected in the application card with no popover", () => {
+ it("4. Updates the name of first application to very long name and checks whether update is reflected in the application card with no popover", () => {
cy.get(commonlocators.homeIcon).click({ force: true });
cy.get(homePage.searchInput).clear();
// eslint-disable-next-line cypress/no-unnecessary-waiting
diff --git a/app/client/cypress/integration/Regression_TestSuite/ClientSideTests/OtherUIFeatures/ViewMode_spec.js b/app/client/cypress/integration/Regression_TestSuite/ClientSideTests/OtherUIFeatures/ViewMode_spec.js
index a37ac5936708..7ad24232b902 100644
--- a/app/client/cypress/integration/Regression_TestSuite/ClientSideTests/OtherUIFeatures/ViewMode_spec.js
+++ b/app/client/cypress/integration/Regression_TestSuite/ClientSideTests/OtherUIFeatures/ViewMode_spec.js
@@ -7,9 +7,8 @@ describe("Preview mode functionality", function () {
cy.addDsl(dsl);
});
- it("on click of apps on header, it should take to application home page", function () {
+ it("1. on click of apps on header, it should take to application home page", function () {
cy.PublishtheApp();
-
cy.get(".t--back-to-home").click();
cy.url().should("eq", BASE_URL + "applications");
});
diff --git a/app/client/cypress/integration/Regression_TestSuite/ClientSideTests/OtherUIFeatures/Widget_Error_spec.js b/app/client/cypress/integration/Regression_TestSuite/ClientSideTests/OtherUIFeatures/Widget_Error_spec.js
index 71207cec2cad..4cba67d5f914 100644
--- a/app/client/cypress/integration/Regression_TestSuite/ClientSideTests/OtherUIFeatures/Widget_Error_spec.js
+++ b/app/client/cypress/integration/Regression_TestSuite/ClientSideTests/OtherUIFeatures/Widget_Error_spec.js
@@ -19,16 +19,16 @@ describe("Widget error state", function () {
cy.testJsontext("visible", "Test");
cy.contains(".t--widget-error-count", 1);
- });
- it("2. Check if the current value is shown in the debugger", function () {
+ //Check if the current value is shown in the debugger
+
_.debuggerHelper.ClickDebuggerIcon();
cy.contains(".react-tabs__tab", "Errors").click();
//This feature is disabled in updated error log - epic 17720
// _.debuggerHelper.LogStateContains("Test");
});
- it("3. Switch to error tab when clicked on the debug button", function () {
+ it("2. Switch to error tab when clicked on the debug button", function () {
cy.get("[data-cy=t--tab-LOGS_TAB]").click();
cy.get(".t--property-control-onclick").find(".t--js-toggle").click();
cy.EnableAllCodeEditors();
@@ -37,14 +37,12 @@ describe("Widget error state", function () {
cy.get(".t--toast-debug-button").click();
cy.contains(".react-tabs__tab--selected", "Errors");
- });
- it("4. All errors should be expanded by default", function () {
+ // All errors should be expanded by default
//Updated count to 1 as the decision not to show triggerexecution/uncaughtpromise error in - epic 17720
_.debuggerHelper.AssertVisibleErrorMessagesCount(1);
- });
- it("5. Recent errors are shown at the top of the list", function () {
+ // Recent errors are shown at the top of the list
cy.testJsontext("label", "{{[]}}");
//This feature is disabled in updated error log - epic 17720
// _.debuggerHelper.LogStateContains("text", 0);
@@ -56,14 +54,13 @@ describe("Widget error state", function () {
// _.debuggerHelper.AssertContextMenuItemVisible();
// });
- it("7. Undoing widget deletion should show errors if present", function () {
+ it("3. Undoing widget deletion should show errors if present + Bug 2760", function () {
cy.deleteWidget();
_.debuggerHelper.AssertVisibleErrorMessagesCount(0);
cy.get("body").type(`{${modifierKey}}z`);
_.debuggerHelper.AssertVisibleErrorMessagesCount(2);
- });
- it("8. Bug-2760: Error log on a widget property not clearing out when the widget property is deleted", function () {
+ //Bug-2760: Error log on a widget property not clearing out when the widget property is deleted
_.entityExplorer.DragDropWidgetNVerify(WIDGET.TABLE, 150, 300);
_.entityExplorer.SelectEntityByName("Table1", "Widgets");
diff --git a/app/client/cypress/integration/Regression_TestSuite/ClientSideTests/OtherUIFeatures/lazyRender_spec.js b/app/client/cypress/integration/Regression_TestSuite/ClientSideTests/OtherUIFeatures/lazyRender_spec.js
index be65e1da3c7c..2667fbe7d6fa 100644
--- a/app/client/cypress/integration/Regression_TestSuite/ClientSideTests/OtherUIFeatures/lazyRender_spec.js
+++ b/app/client/cypress/integration/Regression_TestSuite/ClientSideTests/OtherUIFeatures/lazyRender_spec.js
@@ -5,16 +5,13 @@ describe("lazy widget component render", () => {
cy.addDsl(dsl);
});
- it("should check below the fold widgets are getting rendered", () => {
+ it("1. Should check below the fold widgets are getting rendered", () => {
cy.get(".tableWrap").should("exist");
- });
-
- it("should check that widgets present in the tab other than default tab renders", () => {
+ //should check that widgets present in the tab other than default tab renders
cy.get(".t--tabid-tab2").trigger("click");
cy.get(".t--draggable-ratewidget .bp3-icon-star").should("exist");
- });
- it("should check that widgets in modal are loading properly", () => {
+ //should check that widgets in modal are loading properly
cy.get(".t--draggable-buttonwidget button").trigger("click", {
force: true,
});
diff --git a/app/client/cypress/integration/Regression_TestSuite/ClientSideTests/PeekOverlay/PeekOverlay_Spec.ts b/app/client/cypress/integration/Regression_TestSuite/ClientSideTests/PeekOverlay/PeekOverlay_Spec.ts
index f62faa7dbf4c..17b73d722a60 100644
--- a/app/client/cypress/integration/Regression_TestSuite/ClientSideTests/PeekOverlay/PeekOverlay_Spec.ts
+++ b/app/client/cypress/integration/Regression_TestSuite/ClientSideTests/PeekOverlay/PeekOverlay_Spec.ts
@@ -1,7 +1,7 @@
import * as _ from "../../../../support/Objects/ObjectsCore";
-describe("peek overlay", () => {
- it("main test", () => {
+describe("Peek overlay", () => {
+ it("1. Main test", () => {
cy.fixture("datasources").then((datasourceFormData: any) => {
_.entityExplorer.DragDropWidgetNVerify("tablewidgetv2", 500, 100);
_.apiPage.CreateAndFillApi(datasourceFormData["mockApiUrl"]);
diff --git a/app/client/cypress/integration/Regression_TestSuite/ClientSideTests/PropertyPane/PropertyPaneCTA_spec.js b/app/client/cypress/integration/Regression_TestSuite/ClientSideTests/PropertyPane/PropertyPaneCTA_spec.js
index ce855d824694..e6d6ba779d43 100644
--- a/app/client/cypress/integration/Regression_TestSuite/ClientSideTests/PropertyPane/PropertyPaneCTA_spec.js
+++ b/app/client/cypress/integration/Regression_TestSuite/ClientSideTests/PropertyPane/PropertyPaneCTA_spec.js
@@ -5,15 +5,13 @@ describe("Property pane CTA to add an action", function () {
cy.addDsl(dsl);
});
- it("Check if CTA is shown when there is no action", function () {
+ it("1. Check if CTA is shown when there is no action", function () {
cy.openPropertyPane("tablewidget");
-
cy.get(".t--propertypane-connect-cta")
.scrollIntoView()
.should("be.visible");
- });
- it("Check if CTA does not exist when there is an action", function () {
+ //Check if CTA does not exist when there is an action
cy.NavigateToAPI_Panel();
cy.CreateAPI("FirstAPI");
diff --git a/app/client/cypress/integration/Regression_TestSuite/ClientSideTests/Refactoring/Refactoring_spec.ts b/app/client/cypress/integration/Regression_TestSuite/ClientSideTests/Refactoring/Refactoring_spec.ts
index 7fa9f46c0975..6b97ddb83245 100644
--- a/app/client/cypress/integration/Regression_TestSuite/ClientSideTests/Refactoring/Refactoring_spec.ts
+++ b/app/client/cypress/integration/Regression_TestSuite/ClientSideTests/Refactoring/Refactoring_spec.ts
@@ -34,9 +34,8 @@ describe("Validate JS Object Refactoring does not affect the comments & variable
cy.get("@dsName").then(($dsName) => {
dsName = $dsName;
});
- });
- it("1. Selecting paintings table from MySQL DS", () => {
+ //Selecting paintings table from MySQL DS
cy.fixture("datasources").then((datasourceFormData: any) => {
//Initialize new JSObject with custom code
_.jsEditor.CreateJSObject(jsCode);
@@ -55,7 +54,7 @@ describe("Validate JS Object Refactoring does not affect the comments & variable
});
});
- it("2. Refactor Widget, API, Query and JSObject", () => {
+ it("1. Refactor Widget, API, Query and JSObject", () => {
//Rename all widgets and entities
_.entityExplorer.SelectEntityByName(refactorInput.textWidget.oldName);
_.agHelper.RenameWidget(
@@ -82,8 +81,7 @@ describe("Validate JS Object Refactoring does not affect the comments & variable
);
});
- //Commenting due to failure in RTS start in fat container runs
- it("3. Verify refactoring updates in JS object", () => {
+ it("2. Verify refactoring updates in JS object", () => {
//Verify JSObject refactoring in API pane
_.entityExplorer.SelectEntityByName(refactorInput.api.newName);
_.agHelper.Sleep(1000);
diff --git a/app/client/cypress/integration/Regression_TestSuite/ClientSideTests/SettingsPane/EmbedSettings_spec.ts b/app/client/cypress/integration/Regression_TestSuite/ClientSideTests/SettingsPane/EmbedSettings_spec.ts
index ce9f96945919..100308b780b1 100644
--- a/app/client/cypress/integration/Regression_TestSuite/ClientSideTests/SettingsPane/EmbedSettings_spec.ts
+++ b/app/client/cypress/integration/Regression_TestSuite/ClientSideTests/SettingsPane/EmbedSettings_spec.ts
@@ -69,14 +69,12 @@ describe("In-app embed settings", () => {
"/settings",
);
_.appSettings.ClosePane();
- });
- it("5. Check embed preview show/hides navigation bar according to setting", () => {
+ //Check embed preview show/hides navigation bar according to setting
_.inviteModal.ValidatePreviewEmbed("true");
_.inviteModal.ValidatePreviewEmbed("false");
- });
- it("6. Check Show/Hides Navigation bar syncs between AppSettings Pane Embed tab & Share modal", () => {
+ //Check Show/Hides Navigation bar syncs between AppSettings Pane Embed tab & Share modal
ValidateSyncWithInviteModal("true");
ValidateSyncWithInviteModal("false");
});
diff --git a/app/client/cypress/integration/Regression_TestSuite/ClientSideTests/SettingsPane/GeneralSettings_spec.ts b/app/client/cypress/integration/Regression_TestSuite/ClientSideTests/SettingsPane/GeneralSettings_spec.ts
index e5d6a7632f14..10427aa2d286 100644
--- a/app/client/cypress/integration/Regression_TestSuite/ClientSideTests/SettingsPane/GeneralSettings_spec.ts
+++ b/app/client/cypress/integration/Regression_TestSuite/ClientSideTests/SettingsPane/GeneralSettings_spec.ts
@@ -18,23 +18,20 @@ describe("General Settings", () => {
_.appSettings.CheckUrl(appName as string, "Page1", undefined, false);
_.deployMode.NavigateBacktoEditor();
});
- });
- it("2. Handles app icon change", () => {
+ //Handles app icon change
_.appSettings.OpenAppSettings();
_.appSettings.GoToGeneralSettings();
_.generalSettings.UpdateAppIcon();
_.appSettings.ClosePane();
- });
- it("3. App name allows special and accented character", () => {
+ //App name allows special and accented character
_.appSettings.OpenAppSettings();
_.appSettings.GoToGeneralSettings();
_.generalSettings.UpdateAppNameAndVerifyUrl(true, guid + "!@#œ™¡", guid);
_.appSettings.ClosePane();
- });
- it("4. Veirfy App name doesn't allow empty", () => {
+ //Veirfy App name doesn't allow empty
_.appSettings.OpenAppSettings();
_.appSettings.GoToGeneralSettings();
_.generalSettings.AssertAppErrorMessage("", "App name cannot be empty");
diff --git a/app/client/cypress/integration/Regression_TestSuite/ClientSideTests/SettingsPane/PageSettings_spec.ts b/app/client/cypress/integration/Regression_TestSuite/ClientSideTests/SettingsPane/PageSettings_spec.ts
index 734c8a4abad9..acde3460f831 100644
--- a/app/client/cypress/integration/Regression_TestSuite/ClientSideTests/SettingsPane/PageSettings_spec.ts
+++ b/app/client/cypress/integration/Regression_TestSuite/ClientSideTests/SettingsPane/PageSettings_spec.ts
@@ -23,9 +23,8 @@ describe("Page Settings", () => {
_.deployMode.NavigateBacktoEditor();
});
_.agHelper.Sleep();
- });
- it("3. Check SetAsHome page setting", () => {
+ //Check SetAsHome page setting
_.entityExplorer.AddNewPage();
_.appSettings.OpenAppSettings();
_.appSettings.GoToPageSettings("Page3");
@@ -33,7 +32,7 @@ describe("Page Settings", () => {
_.pageSettings.AssertHomePage("Page3");
});
- it("4. Check SetPageNavigation settings", () => {
+ it("3. Check SetPageNavigation settings", () => {
_.agHelper.GetNClick(_.locators._previewModeToggle("edit"));
_.agHelper.AssertElementExist(_.locators._deployedPage);
_.agHelper.GetNClick(_.locators._previewModeToggle("preview"));
@@ -43,30 +42,26 @@ describe("Page Settings", () => {
_.agHelper.GetNClick(_.locators._previewModeToggle("edit"));
_.agHelper.AssertElementAbsence(_.locators._deployedPage);
_.agHelper.GetNClick(_.locators._previewModeToggle("preview"));
- });
- it("5. Page name allows accented character", () => {
+ // Page name allows accented character
_.appSettings.OpenAppSettings();
_.appSettings.GoToPageSettings("Page3");
_.pageSettings.UpdatePageNameAndVerifyUrl("Page3œßð", "Page3");
_.appSettings.ClosePane();
- });
- it("6. Page name doesn't allow special character", () => {
+ //Page name doesn't allow special character
_.appSettings.OpenAppSettings();
_.appSettings.GoToPageSettings("Page3");
_.pageSettings.UpdatePageNameAndVerifyTextValue("Page3!@#", "Page3 ");
_.appSettings.ClosePane();
- });
- it("7. Page name doesn't allow empty", () => {
+ // Page name doesn't allow empty
_.appSettings.OpenAppSettings();
_.appSettings.GoToPageSettings("Page3");
_.pageSettings.AssertPageErrorMessage("", "Page name cannot be empty");
_.appSettings.ClosePane();
- });
- it("8. Bug #18698 : Page name doesn't allow duplicate name", () => {
+ //Bug #18698 : Page name doesn't allow duplicate name
_.appSettings.OpenAppSettings();
_.appSettings.GoToPageSettings("Page3");
_.pageSettings.AssertPageErrorMessage(
@@ -74,9 +69,8 @@ describe("Page Settings", () => {
"Page2 is already being used.",
);
_.appSettings.ClosePane();
- });
- it("9. Page name doesn't allow keywords", () => {
+ //Page name doesn't allow keywords
_.appSettings.OpenAppSettings();
_.appSettings.GoToPageSettings("Page3");
_.pageSettings.AssertPageErrorMessage(
@@ -84,9 +78,8 @@ describe("Page Settings", () => {
"appsmith is already being used.",
);
_.appSettings.ClosePane();
- });
- it("10. Custom slug doesn't allow special/accented characters", () => {
+ //Custom slug doesn't allow special/accented characters
_.appSettings.OpenAppSettings();
_.appSettings.GoToPageSettings("Page2");
_.pageSettings.UpdateCustomSlugAndVerifyTextValue(
diff --git a/app/client/cypress/integration/Regression_TestSuite/ClientSideTests/Templates/Fork_Template_Existing_app_spec.js b/app/client/cypress/integration/Regression_TestSuite/ClientSideTests/Templates/Fork_Template_Existing_app_spec.js
index c7e55ad57156..b4ad1026cae3 100644
--- a/app/client/cypress/integration/Regression_TestSuite/ClientSideTests/Templates/Fork_Template_Existing_app_spec.js
+++ b/app/client/cypress/integration/Regression_TestSuite/ClientSideTests/Templates/Fork_Template_Existing_app_spec.js
@@ -17,15 +17,13 @@ beforeEach(() => {
});
describe("Fork a template to the current app from new page popover", () => {
- it("Fork template button to be visible always", () => {
+ it("1. Fork template from page section", () => {
+ //Fork template button to be visible always
_.agHelper.RefreshPage();
- cy.AddPageFromTemplate();
- _.agHelper.AssertElementExist(_.templates.locators._forkApp);
- });
- it("Fork template from page section", () => {
cy.wait(5000);
cy.AddPageFromTemplate();
cy.wait(5000);
+ _.agHelper.AssertElementExist(_.templates.locators._forkApp);
cy.get(template.templateDialogBox).should("be.visible");
cy.wait(4000);
cy.xpath(
@@ -51,7 +49,7 @@ describe("Fork a template to the current app from new page popover", () => {
);
});
- it("Add selected page of template from page section", () => {
+ it("2. Add selected page of template from page section", () => {
cy.AddPageFromTemplate();
cy.wait(5000);
cy.get(template.templateDialogBox).should("be.visible");
diff --git a/app/client/cypress/integration/Regression_TestSuite/ClientSideTests/Templates/Fork_Template_To_App_spec.js b/app/client/cypress/integration/Regression_TestSuite/ClientSideTests/Templates/Fork_Template_To_App_spec.js
index dcfcb7cf5a3b..6f8ff2cf858e 100644
--- a/app/client/cypress/integration/Regression_TestSuite/ClientSideTests/Templates/Fork_Template_To_App_spec.js
+++ b/app/client/cypress/integration/Regression_TestSuite/ClientSideTests/Templates/Fork_Template_To_App_spec.js
@@ -25,7 +25,7 @@ describe("Fork a template to the current app", () => {
});
it("1. Fork a template to the current app + Bug 17477", () => {
- cy.wait(5000);
+ cy.wait(3000);
cy.get(template.startFromTemplateCard).click();
// Commented out below code as fetch template call is not going through when template dialog is closed
// cy.wait("@fetchTemplate").should(
@@ -33,7 +33,7 @@ describe("Fork a template to the current app", () => {
// "response.body.responseMeta.status",
// 200,
// );
- cy.wait(5000);
+ cy.wait(4000);
cy.get(template.templateDialogBox).should("be.visible");
cy.xpath(
"//div[text()='Applicant Tracker-test']/parent::div//button[contains(@class, 't--fork-template')]",
diff --git a/app/client/cypress/integration/Regression_TestSuite/ClientSideTests/ThemingTests/Theme_Default_spec.js b/app/client/cypress/integration/Regression_TestSuite/ClientSideTests/ThemingTests/Theme_Default_spec.js
index 6f6a7af86d64..a2ae67e4c404 100644
--- a/app/client/cypress/integration/Regression_TestSuite/ClientSideTests/ThemingTests/Theme_Default_spec.js
+++ b/app/client/cypress/integration/Regression_TestSuite/ClientSideTests/ThemingTests/Theme_Default_spec.js
@@ -11,7 +11,7 @@ const appSettings = ObjectsRegistry.AppSettings;
let themeBackgroudColor;
describe("Theme validation for default data", function () {
- it("Drag and drop form widget and validate Default color/font/shadow/border and list of font validation", function () {
+ it("1. Drag and drop form widget and validate Default color/font/shadow/border and list of font validation", function () {
cy.log("Login Successful");
cy.reload(); // To remove the rename tooltip
cy.get(explorer.addWidget).click();
@@ -68,7 +68,7 @@ describe("Theme validation for default data", function () {
appSettings.ClosePane();
});
- it("Validate Default Theme change across application", function () {
+ it("2. Validate Default Theme change across application", function () {
cy.get(formWidgetsPage.formD).click();
cy.widgetText(
"FormTest",
diff --git a/app/client/cypress/integration/Regression_TestSuite/ClientSideTests/ThemingTests/Theme_FormWidget_spec.js b/app/client/cypress/integration/Regression_TestSuite/ClientSideTests/ThemingTests/Theme_FormWidget_spec.js
index d4861c15a056..a187302f91d6 100644
--- a/app/client/cypress/integration/Regression_TestSuite/ClientSideTests/ThemingTests/Theme_FormWidget_spec.js
+++ b/app/client/cypress/integration/Regression_TestSuite/ClientSideTests/ThemingTests/Theme_FormWidget_spec.js
@@ -83,58 +83,60 @@ describe("Theme validation usecases", function () {
`${$childElem.children().last().text()}, sans-serif`,
);
themeFont = `${$childElem.children().last().text()}, sans-serif`;
- });
- });
- cy.contains("Font").click({ force: true });
- //Color
- //cy.contains("Color").click({ force: true });
- cy.wait(2000);
- cy.colorMouseover(0, "Primary Color");
- cy.validateColor(0, "#553DE9");
- cy.colorMouseover(1, "Background Color");
- cy.validateColor(1, "#F8FAFC");
+ cy.contains("Font").click({ force: true });
- cy.get(themelocator.inputColor).click({ force: true });
- cy.chooseColor(0, themelocator.greenColor);
+ //Color
+ //cy.contains("Color").click({ force: true });
+ cy.wait(2000);
+ cy.colorMouseover(0, "Primary Color");
+ cy.validateColor(0, "#553DE9");
+ cy.colorMouseover(1, "Background Color");
+ cy.validateColor(1, "#F8FAFC");
- cy.get(themelocator.inputColor).should("have.value", "#15803d");
- cy.get(themelocator.inputColor).clear({ force: true });
- cy.wait(2000);
- cy.get(themelocator.inputColor).type("red");
- cy.get(themelocator.inputColor).should("have.value", "red");
- cy.wait(2000);
+ cy.get(themelocator.inputColor).click({ force: true });
+ cy.chooseColor(0, themelocator.greenColor);
- cy.get(themelocator.inputColor).eq(0).click({ force: true });
- cy.get(themelocator.inputColor).click({ force: true });
- cy.get('[data-testid="color-picker"]').first().click({ force: true });
- cy.get("[style='background-color: rgb(21, 128, 61);']").last().click();
- cy.wait(2000);
- cy.get(themelocator.inputColor).should("have.value", "#15803d");
- cy.get(themelocator.inputColor).clear({ force: true });
- cy.wait(2000);
- cy.get(themelocator.inputColor).click().type("Black");
- cy.get(themelocator.inputColor).should("have.value", "Black");
- cy.wait(2000);
- cy.contains("Color").click({ force: true });
- appSettings.ClosePane();
- });
+ cy.get(themelocator.inputColor).should("have.value", "#15803d");
+ cy.get(themelocator.inputColor).clear({ force: true });
+ cy.wait(2000);
+ cy.get(themelocator.inputColor).type("red");
+ cy.get(themelocator.inputColor).should("have.value", "red");
+ cy.wait(2000);
- it("2. Publish the App and validate Font across the app", function () {
- cy.PublishtheApp();
- cy.get(".bp3-button:contains('Sub')").should(
- "have.css",
- "font-family",
- themeFont,
- );
- cy.get(".bp3-button:contains('Reset')").should(
- "have.css",
- "font-family",
- themeFont,
- );
+ cy.get(themelocator.inputColor).eq(0).click({ force: true });
+ cy.get(themelocator.inputColor).click({ force: true });
+ cy.get('[data-testid="color-picker"]').first().click({ force: true });
+ cy.get("[style='background-color: rgb(21, 128, 61);']")
+ .last()
+ .click();
+ cy.wait(2000);
+ cy.get(themelocator.inputColor).should("have.value", "#15803d");
+ cy.get(themelocator.inputColor).clear({ force: true });
+ cy.wait(2000);
+ cy.get(themelocator.inputColor).click().type("Black");
+ cy.get(themelocator.inputColor).should("have.value", "Black");
+ cy.wait(2000);
+ cy.contains("Color").click({ force: true });
+ appSettings.ClosePane();
+
+ //Publish the App and validate Font across the app
+ cy.PublishtheApp();
+ cy.get(".bp3-button:contains('Sub')").should(
+ "have.css",
+ "font-family",
+ themeFont,
+ );
+ cy.get(".bp3-button:contains('Reset')").should(
+ "have.css",
+ "font-family",
+ themeFont,
+ );
+ });
+ });
});
- it("3. Validate Default Theme change across application", function () {
+ it("2. Validate Default Theme change across application", function () {
cy.goToEditFromPublish();
cy.get(formWidgetsPage.formD).click();
cy.widgetText(
@@ -171,7 +173,7 @@ describe("Theme validation usecases", function () {
});
});
- it("4. Validate Theme change across application", function () {
+ it("3. Validate Theme change across application", function () {
cy.goToEditFromPublish();
cy.get(formWidgetsPage.formD).click();
cy.widgetText(
@@ -252,9 +254,8 @@ describe("Theme validation usecases", function () {
cy.get(formWidgetsPage.formD)
.should("have.css", "background-color")
.and("eq", "rgb(126, 34, 206)");
- });
- it("5. Publish the App and validate Theme across the app", function () {
+ //Publish the App and validate Theme across the app
cy.PublishtheApp();
//Bug Form backgroud colour reset in Publish mode
cy.get(formWidgetsPage.formD)
diff --git a/app/client/cypress/integration/Regression_TestSuite/ClientSideTests/ThemingTests/Theme_MultiSelectWidget_spec.js b/app/client/cypress/integration/Regression_TestSuite/ClientSideTests/ThemingTests/Theme_MultiSelectWidget_spec.js
index 78dedb828a96..4f652f1502dd 100644
--- a/app/client/cypress/integration/Regression_TestSuite/ClientSideTests/ThemingTests/Theme_MultiSelectWidget_spec.js
+++ b/app/client/cypress/integration/Regression_TestSuite/ClientSideTests/ThemingTests/Theme_MultiSelectWidget_spec.js
@@ -118,9 +118,8 @@ describe("Theme validation usecase for multi-select widget", function () {
appSettings.ClosePane();
});
});
- });
- it("4. Publish the App and validate change of Theme across the app in publish mode", function () {
+ //Publish the App and validate change of Theme across the app in publish mode
cy.PublishtheApp();
cy.xpath("//div[@id='root']//section/parent::div").should(
"have.css",
diff --git a/app/client/cypress/integration/Regression_TestSuite/ClientSideTests/VisualTests/AppPageLayout_spec.js b/app/client/cypress/integration/Regression_TestSuite/ClientSideTests/VisualTests/AppPageLayout_spec.js
index bc10d3805c3c..75d8841572b9 100644
--- a/app/client/cypress/integration/Regression_TestSuite/ClientSideTests/VisualTests/AppPageLayout_spec.js
+++ b/app/client/cypress/integration/Regression_TestSuite/ClientSideTests/VisualTests/AppPageLayout_spec.js
@@ -7,7 +7,7 @@ describe("Visual regression tests", () => {
// command: "npx cypress run --spec cypress/integration/Regression_TestSuite/ClientSideTests/LayoutValidation/AppPageLayout_spec.js --browser chrome"
// 3. New screenshot will be generated in the snapshot folder.
- it("Layout validation for app page in edit mode", () => {
+ it("1. Layout validation for app page in edit mode", () => {
cy.visit("/applications");
cy.wait(3000);
cy.get(".t--applications-container .createnew").should("be.visible");
@@ -15,38 +15,33 @@ describe("Visual regression tests", () => {
cy.wait(3000);
// taking screenshot of app home page in edit mode
cy.get("#root").matchImageSnapshot("apppage");
- });
- it("Layout validation for Quick page wizard", () => {
+ //Layout validation for Quick page wizard
cy.get("[data-cy='generate-app']").click();
cy.wait(2000);
// taking screenshot of generate crud page
cy.get("#root").matchImageSnapshot("quickPageWizard");
- });
- it("Layout Validation for App builder Page", () => {
+ //Layout Validation for App builder Page
cy.get(".bp3-icon-chevron-left").click();
cy.wait(2000);
// taking screenshot of app builder page
cy.get("#root").matchImageSnapshot("emptyAppBuilder");
- });
- it("Layout Validation for Empty deployed app", () => {
+ //Layout Validation for Empty deployed app
cy.PublishtheApp();
cy.wait(3000);
// taking screenshot of empty deployed app
cy.get("#root").matchImageSnapshot("EmptyApp");
- });
- it("Layout Validation for profile page", () => {
+ //Layout Validation for profile page
cy.get(".t--profile-menu-icon").click();
cy.get(".t--edit-profile").click();
cy.wait(2000);
// taking screenshot of profile page
cy.get("#root").matchImageSnapshot("Profile");
- });
- it("Layout validation for login page", () => {
+ //Layout validation for login page
cy.get(homePage.profileMenu).click();
cy.get(homePage.signOutIcon).click();
cy.wait(500);
diff --git a/app/client/cypress/integration/Regression_TestSuite/ClientSideTests/VisualTests/DatasourcePageLayout_spec.js b/app/client/cypress/integration/Regression_TestSuite/ClientSideTests/VisualTests/DatasourcePageLayout_spec.js
index 8e03f727ac59..ccb3a12b3bc2 100644
--- a/app/client/cypress/integration/Regression_TestSuite/ClientSideTests/VisualTests/DatasourcePageLayout_spec.js
+++ b/app/client/cypress/integration/Regression_TestSuite/ClientSideTests/VisualTests/DatasourcePageLayout_spec.js
@@ -10,7 +10,7 @@ describe("Visual tests for datasources", () => {
// 2. Run test in headless mode with any browser
// command: "npx cypress run --spec cypress/integration/<path> --browser chrome"
// 3. New screenshot will be generated in the snapshot folder.
- it("Layout validation for datasource page", () => {
+ it("1. Layout validation for datasource page", () => {
cy.NavigateToHome();
cy.createWorkspace();
cy.wait("@createWorkspace").then((interception) => {
diff --git a/app/client/cypress/integration/Regression_TestSuite/ClientSideTests/Workspace/LoginFromUIApp_spec.js b/app/client/cypress/integration/Regression_TestSuite/ClientSideTests/Workspace/LoginFromUIApp_spec.js
index 37bbfd50aa17..a232ba1f696e 100644
--- a/app/client/cypress/integration/Regression_TestSuite/ClientSideTests/Workspace/LoginFromUIApp_spec.js
+++ b/app/client/cypress/integration/Regression_TestSuite/ClientSideTests/Workspace/LoginFromUIApp_spec.js
@@ -9,7 +9,7 @@ describe("Login from UI and check the functionality", function () {
cy.LogintoApp(Cypress.env("USERNAME"), Cypress.env("PASSWORD"));
cy.SearchApp(appname);
cy.get("#loading").should("not.exist");
- cy.wait(5000);
+ //cy.wait(5000);
cy.generateUUID().then((uid) => {
pageid = uid;
cy.Createpage(pageid);
diff --git a/app/client/cypress/integration/Regression_TestSuite/ClientSideTests/Workspace/ShareAppTests_spec.js b/app/client/cypress/integration/Regression_TestSuite/ClientSideTests/Workspace/ShareAppTests_spec.js
index 147a13b98677..7f597d441d0a 100644
--- a/app/client/cypress/integration/Regression_TestSuite/ClientSideTests/Workspace/ShareAppTests_spec.js
+++ b/app/client/cypress/integration/Regression_TestSuite/ClientSideTests/Workspace/ShareAppTests_spec.js
@@ -115,7 +115,7 @@ describe("Create new workspace and share with a user", function () {
cy.LogOut();
});
- it("login as Owner and disable public access", function () {
+ it("6. login as Owner and disable public access", function () {
cy.LoginFromAPI(Cypress.env("USERNAME"), Cypress.env("PASSWORD"));
cy.wait("@applications").should(
"have.nested.property",
@@ -134,7 +134,7 @@ describe("Create new workspace and share with a user", function () {
cy.LogOut();
});
- it("6. login as uninvited user, validate public access disable feature ", function () {
+ it("7. login as uninvited user, validate public access disable feature ", function () {
cy.LoginFromAPI(Cypress.env("TESTUSERNAME2"), Cypress.env("TESTPASSWORD2"));
cy.visit(currentUrl);
cy.wait("@getPagesForViewApp").should(
@@ -143,9 +143,8 @@ describe("Create new workspace and share with a user", function () {
404,
);
cy.LogOut();
- });
- it("7. visit the app as anonymous user and validate redirection to login page", function () {
+ // visit the app as anonymous user and validate redirection to login page
cy.visit(currentUrl);
cy.wait("@getPagesForViewApp").should(
"have.nested.property",
|
3756533b3a7b373a087d26f74696554532ce92db
|
2024-05-31 09:57:49
|
Ashwin Solanki
|
fix: Confirmation popup not dismissing after deleting a datasource (#33778)
| false
|
Confirmation popup not dismissing after deleting a datasource (#33778)
|
fix
|
diff --git a/app/client/src/pages/Editor/DataSourceEditor/DSFormHeader.tsx b/app/client/src/pages/Editor/DataSourceEditor/DSFormHeader.tsx
index a0c5f6aa9025..f757fd7e9a9b 100644
--- a/app/client/src/pages/Editor/DataSourceEditor/DSFormHeader.tsx
+++ b/app/client/src/pages/Editor/DataSourceEditor/DSFormHeader.tsx
@@ -183,6 +183,7 @@ export const DSFormHeader = (props: DSFormHeaderProps) => {
{canDeleteDatasource && (
<MenuWrapper
className="t--datasource-menu-option"
+ key={datasourceId}
onClick={(e) => {
e.stopPropagation();
}}
|
0ef0da041b5c230812effa5793d3a6e11112214e
|
2021-09-17 16:32:16
|
Vinod
|
feat: add copy button to evaluated value (#7159)
| false
|
add copy button to evaluated value (#7159)
|
feat
|
diff --git a/app/client/src/components/editorComponents/CodeEditor/EvaluatedValuePopup.tsx b/app/client/src/components/editorComponents/CodeEditor/EvaluatedValuePopup.tsx
index 98168a9a91fc..7ceb78826cf3 100644
--- a/app/client/src/components/editorComponents/CodeEditor/EvaluatedValuePopup.tsx
+++ b/app/client/src/components/editorComponents/CodeEditor/EvaluatedValuePopup.tsx
@@ -10,10 +10,12 @@ import ScrollIndicator from "components/ads/ScrollIndicator";
import { EvaluatedValueDebugButton } from "components/editorComponents/Debugger/DebugCTA";
import { EvaluationSubstitutionType } from "entities/DataTree/dataTreeFactory";
import Tooltip from "components/ads/Tooltip";
+import { Toaster } from "components/ads/Toast";
import { Classes, Collapse, Icon } from "@blueprintjs/core";
import { IconNames } from "@blueprintjs/icons";
import { UNDEFINED_VALIDATION } from "utils/validation/common";
import { IPopoverSharedProps } from "@blueprintjs/core";
+import copy from "copy-to-clipboard";
import {
EvaluationError,
@@ -23,6 +25,7 @@ import * as Sentry from "@sentry/react";
import { Severity } from "@sentry/react";
import { CodeEditorExpected } from "components/editorComponents/CodeEditor/index";
import { Layers } from "constants/Layers";
+import { Variant } from "components/ads/common";
const modifiers: IPopoverSharedProps["modifiers"] = {
offset: {
@@ -81,10 +84,20 @@ const ContentWrapper = styled.div<{ colorTheme: EditorTheme }>`
const CurrentValueWrapper = styled.div<{ colorTheme: EditorTheme }>`
max-height: 300px;
+ min-height: 1rem;
overflow-y: auto;
-ms-overflow-style: none;
padding: ${(props) => props.theme.spaces[3]}px;
background-color: ${(props) => THEMES[props.colorTheme].editorBackground};
+ position: relative;
+`;
+
+const CopyIconWrapper = styled(Icon)<{ colorTheme: EditorTheme }>`
+ color: ${(props) => THEMES[props.colorTheme].textColor};
+ position: absolute;
+ right: ${(props) => props.theme.spaces[2]}px;
+ top: ${(props) => props.theme.spaces[2]}px;
+ cursor: pointer;
`;
const CodeWrapper = styled.pre<{ colorTheme: EditorTheme }>`
@@ -145,6 +158,14 @@ function CollapseToggle(props: { isOpen: boolean }) {
);
}
+function copyContent(content: any) {
+ copy(content);
+ Toaster.show({
+ text: `Evaluated value copied to clipboard`,
+ variant: Variant.success,
+ });
+}
+
interface Props {
theme: EditorTheme;
isOpen: boolean;
@@ -302,6 +323,13 @@ export const CurrentValueViewer = memo(
<Collapse isOpen={openEvaluatedValue}>
<CurrentValueWrapper colorTheme={props.theme}>
{content}
+ {props.evaluatedValue && (
+ <CopyIconWrapper
+ colorTheme={props.theme}
+ icon="duplicate"
+ onClick={() => copyContent(props.evaluatedValue)}
+ />
+ )}
</CurrentValueWrapper>
</Collapse>
</>
|
e73fd0a269270913c4093880ae0ea7482b55c564
|
2022-04-27 08:45:15
|
Nidhi
|
fix: Parse nested structures as tables for action execution results (#13328)
| false
|
Parse nested structures as tables for action execution results (#13328)
|
fix
|
diff --git a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/helpers/DataTypeStringUtils.java b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/helpers/DataTypeStringUtils.java
index 17dab5ec6e93..64b61cc1faba 100644
--- a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/helpers/DataTypeStringUtils.java
+++ b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/helpers/DataTypeStringUtils.java
@@ -310,27 +310,25 @@ private static boolean isBinary(String input) {
private static boolean isDisplayTypeTable(Object data) {
if (data instanceof List) {
- // Check if the data is a list of simple json objects i.e. all values in the key value pairs are simple
- // objects or their wrappers.
- return ((List)data).stream()
- .allMatch(item -> item instanceof Map
- && ((Map)item).entrySet().stream()
- .allMatch(e -> ((Map.Entry)e).getValue() == null ||
- isPrimitiveOrWrapper(((Map.Entry)e).getValue().getClass())));
+ // Check if the data is a list of json objects
+ return ((List) data).stream()
+ .allMatch(item -> item instanceof Map);
}
else if (data instanceof JsonNode) {
- // Check if the data is an array of simple json objects
+ // Check if the data is an array of json objects
try {
- objectMapper.convertValue(data, new TypeReference<List<Map<String, String>>>() {});
+ objectMapper.convertValue(data, new TypeReference<List<Map<String, Object>>>() {
+ });
return true;
} catch (IllegalArgumentException e) {
return false;
}
}
else if (data instanceof String) {
- // Check if the data is an array of simple json objects
+ // Check if the data is an array of json objects
try {
- objectMapper.readValue((String)data, new TypeReference<List<Map<String, String>>>() {});
+ objectMapper.readValue((String) data, new TypeReference<List<Map<String, Object>>>() {
+ });
return true;
} catch (IOException e) {
return false;
diff --git a/app/server/appsmith-interfaces/src/test/java/com/appsmith/external/helpers/DataTypeStringUtilsTest.java b/app/server/appsmith-interfaces/src/test/java/com/appsmith/external/helpers/DataTypeStringUtilsTest.java
index a916cad59450..23a7a4dc3de1 100644
--- a/app/server/appsmith-interfaces/src/test/java/com/appsmith/external/helpers/DataTypeStringUtilsTest.java
+++ b/app/server/appsmith-interfaces/src/test/java/com/appsmith/external/helpers/DataTypeStringUtilsTest.java
@@ -1,8 +1,19 @@
package com.appsmith.external.helpers;
import com.appsmith.external.constants.DataType;
+import com.appsmith.external.constants.DisplayDataType;
+import com.appsmith.external.models.ParsedDataType;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.fasterxml.jackson.databind.node.ArrayNode;
+import com.fasterxml.jackson.databind.node.ObjectNode;
import org.junit.Test;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import static com.appsmith.external.helpers.DataTypeStringUtils.getDisplayDataTypes;
import static com.appsmith.external.helpers.DataTypeStringUtils.stringToKnownDataTypeConverter;
import static org.assertj.core.api.Assertions.assertThat;
@@ -176,4 +187,49 @@ public void testJsonStrictParsing() {
assertThat(DataType.JSON_OBJECT).isEqualByComparingTo(stringToKnownDataTypeConverter("{\"a\": \"\"}"));
assertThat(DataType.JSON_OBJECT).isEqualByComparingTo(stringToKnownDataTypeConverter("{\"a\": []}"));
}
+
+ @Test
+ public void testGetDisplayDataTypes_withNestedObjectsInList_returnsWithTable() {
+
+ final List<Object> data = new ArrayList<>();
+ final Map<String, Object> objectMap = new HashMap<>();
+ final Map<String, Object> nestedObjectMap = new HashMap<>();
+ nestedObjectMap.put("k2", "v2");
+ objectMap.put("k", nestedObjectMap);
+
+ data.add(objectMap);
+ final List<ParsedDataType> displayDataTypes = getDisplayDataTypes(data);
+
+ assertThat(displayDataTypes).anyMatch(parsedDataType -> parsedDataType.getDataType().equals(DisplayDataType.TABLE));
+ }
+
+ @Test
+ public void testGetDisplayDataTypes_withNestedObjectsInArrayNode_returnsWithTable() {
+ final ObjectMapper objectMapper = new ObjectMapper();
+ final ArrayNode data = objectMapper.createArrayNode();
+ final ObjectNode objectNode = objectMapper.createObjectNode();
+ final ObjectNode nestedObjectNode = objectMapper.createObjectNode();
+ nestedObjectNode.put("k2", "v2");
+ objectNode.set("k", nestedObjectNode);
+
+ data.add(objectNode);
+ final List<ParsedDataType> displayDataTypes = getDisplayDataTypes(data);
+
+ assertThat(displayDataTypes).anyMatch(parsedDataType -> parsedDataType.getDataType().equals(DisplayDataType.TABLE));
+ }
+
+ @Test
+ public void testGetDisplayDataTypes_withNestedObjectsInString_returnsWithTable() {
+ final ObjectMapper objectMapper = new ObjectMapper();
+ final ArrayNode data = objectMapper.createArrayNode();
+ final ObjectNode objectNode = objectMapper.createObjectNode();
+ final ObjectNode nestedObjectNode = objectMapper.createObjectNode();
+ nestedObjectNode.put("k2", "v2");
+ objectNode.set("k", nestedObjectNode);
+
+ data.add(objectNode);
+ final List<ParsedDataType> displayDataTypes = getDisplayDataTypes(data.toString());
+
+ assertThat(displayDataTypes).anyMatch(parsedDataType -> parsedDataType.getDataType().equals(DisplayDataType.TABLE));
+ }
}
|
ebc4090b53408eb103e374c58ea9674664b69a55
|
2022-06-17 10:09:28
|
Abhijeet
|
chore: Enable serialisation for `JsonIgnore` fields during export flow to avoid adding intermediate fields in DTO (#14120)
| false
|
Enable serialisation for `JsonIgnore` fields during export flow to avoid adding intermediate fields in DTO (#14120)
|
chore
|
diff --git a/app/server/appsmith-git/src/main/java/com/appsmith/git/helpers/FileUtilsImpl.java b/app/server/appsmith-git/src/main/java/com/appsmith/git/helpers/FileUtilsImpl.java
index 26614f072003..88a6d9f845e4 100644
--- a/app/server/appsmith-git/src/main/java/com/appsmith/git/helpers/FileUtilsImpl.java
+++ b/app/server/appsmith-git/src/main/java/com/appsmith/git/helpers/FileUtilsImpl.java
@@ -1,5 +1,6 @@
package com.appsmith.git.helpers;
+import com.appsmith.external.converters.GsonISOStringToInstantConverter;
import com.appsmith.external.exceptions.pluginExceptions.AppsmithPluginError;
import com.appsmith.external.exceptions.pluginExceptions.AppsmithPluginException;
import com.appsmith.external.git.FileInterface;
@@ -42,6 +43,7 @@
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
+import java.time.Instant;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
@@ -149,6 +151,7 @@ public Mono<Path> saveApplicationToGitRepo(Path baseRepoSuffix,
.registerTypeAdapter(Double.class, new GsonDoubleToLongConverter())
.registerTypeAdapter(Set.class, new GsonUnorderedToOrderedConverter())
.registerTypeAdapter(Map.class, new GsonUnorderedToOrderedConverter())
+ .registerTypeAdapter(Instant.class, new GsonISOStringToInstantConverter())
.disableHtmlEscaping()
.setPrettyPrinting()
.create();
@@ -229,7 +232,7 @@ public Mono<Path> saveApplicationToGitRepo(Path baseRepoSuffix,
}
}
// Save JSObjects
- for (Map.Entry<String, Object> resource : applicationGitReference.getActionsCollections().entrySet()) {
+ for (Map.Entry<String, Object> resource : applicationGitReference.getActionCollections().entrySet()) {
// JSObjectName_pageName => nomenclature for the keys
// TODO
// JSObjectName => for app level JSObjects, this is not implemented yet
@@ -466,7 +469,7 @@ private ApplicationGitReference fetchApplicationReference(Path baseRepoPath, Gso
// Extract actions
applicationGitReference.setActions(readFiles(baseRepoPath.resolve(ACTION_DIRECTORY), gson, ""));
// Extract actionCollections
- applicationGitReference.setActionsCollections(readFiles(baseRepoPath.resolve(ACTION_COLLECTION_DIRECTORY), gson, ""));
+ applicationGitReference.setActionCollections(readFiles(baseRepoPath.resolve(ACTION_COLLECTION_DIRECTORY), gson, ""));
// Extract pages
applicationGitReference.setPages(readFiles(pageDirectory, gson, ""));
// Extract datasources
@@ -490,7 +493,7 @@ private ApplicationGitReference fetchApplicationReference(Path baseRepoPath, Gso
}
}
applicationGitReference.setActions(actionMap);
- applicationGitReference.setActionsCollections(actionCollectionMap);
+ applicationGitReference.setActionCollections(actionCollectionMap);
applicationGitReference.setPages(pageMap);
// Extract datasources
applicationGitReference.setDatasources(readFiles(baseRepoPath.resolve(DATASOURCE_DIRECTORY), gson, ""));
diff --git a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/converters/GsonISOStringToInstantConverter.java b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/converters/GsonISOStringToInstantConverter.java
new file mode 100644
index 000000000000..a3768eb119d1
--- /dev/null
+++ b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/converters/GsonISOStringToInstantConverter.java
@@ -0,0 +1,43 @@
+package com.appsmith.external.converters;
+
+import com.google.gson.JsonDeserializationContext;
+import com.google.gson.JsonDeserializer;
+import com.google.gson.JsonElement;
+import com.google.gson.JsonParseException;
+import com.google.gson.JsonPrimitive;
+import com.google.gson.JsonSerializationContext;
+import com.google.gson.JsonSerializer;
+
+import java.lang.reflect.Type;
+import java.time.Instant;
+import java.time.ZoneOffset;
+import java.time.format.DateTimeFormatter;
+
+public class GsonISOStringToInstantConverter implements JsonSerializer<Instant>, JsonDeserializer<Instant> {
+ private DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ssX").withZone(ZoneOffset.UTC);
+
+ @Override
+ public Instant deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext jsonDeserializationContext) throws JsonParseException {
+ if(jsonElement.isJsonNull()) {
+ return null;
+ }
+ if (jsonElement.isJsonPrimitive()) {
+ String jsonString = jsonElement.getAsJsonPrimitive().getAsString();
+ if (jsonString.length() == 0) {
+ return null;
+ }
+ try {
+ Double aDouble = Double.parseDouble(jsonString);
+ return Instant.ofEpochSecond(aDouble.longValue());
+ } catch (NumberFormatException e) {
+ // do nothing, let's try to parse with Instant.parse assuming it's in ISO format
+ }
+ }
+ return Instant.parse(jsonElement.getAsString());
+ }
+
+ @Override
+ public JsonElement serialize(Instant src, Type typeOfSrc, JsonSerializationContext context) {
+ return new JsonPrimitive(formatter.format(src));
+ }
+}
diff --git a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/ApplicationGitReference.java b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/ApplicationGitReference.java
index 95f150f32acd..6b6f02204082 100644
--- a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/ApplicationGitReference.java
+++ b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/ApplicationGitReference.java
@@ -17,7 +17,7 @@ public class ApplicationGitReference {
Object metadata;
Object theme;
Map<String, Object> actions;
- Map<String, Object> actionsCollections;
+ Map<String, Object> actionCollections;
Map<String, Object> pages;
Map<String, Object> datasources;
diff --git a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/BaseDomain.java b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/BaseDomain.java
index 5f2d37f2c17b..e00edc1c438c 100644
--- a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/BaseDomain.java
+++ b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/BaseDomain.java
@@ -79,4 +79,14 @@ public boolean isDeleted() {
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
@JsonIgnore
String gitSyncId;
+
+ public void sanitiseToExportBaseObject() {
+ this.setDefaultResources(null);
+ this.setCreatedAt(null);
+ this.setUpdatedAt(null);
+ this.setUserPermissions(null);
+ this.setPolicies(null);
+ this.setCreatedBy(null);
+ this.setModifiedBy(null);
+ }
}
diff --git a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/Datasource.java b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/Datasource.java
index b963ab6e21d9..18850f6bd2e4 100644
--- a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/Datasource.java
+++ b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/Datasource.java
@@ -12,6 +12,7 @@
import org.springframework.util.CollectionUtils;
import java.util.HashSet;
+import java.util.Map;
import java.util.Set;
@Getter
@@ -107,4 +108,18 @@ public boolean softEquals(Datasource other) {
.isEquals();
}
+ public void sanitiseToExportResource(Map<String, String> pluginMap) {
+ this.setPolicies(null);
+ this.setStructure(null);
+ this.setUpdatedAt(null);
+ this.setCreatedAt(null);
+ this.setUserPermissions(null);
+ this.setIsConfigured(null);
+ this.setInvalids(null);
+ this.setId(null);
+ this.setWorkspaceId(null);
+ this.setOrganizationId(null);
+ this.setPluginId(pluginMap.get(this.getPluginId()));
+ }
+
}
diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/constants/ResourceModes.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/constants/ResourceModes.java
new file mode 100644
index 000000000000..384c5f593432
--- /dev/null
+++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/constants/ResourceModes.java
@@ -0,0 +1,5 @@
+package com.appsmith.server.constants;
+
+public enum ResourceModes {
+ EDIT, VIEW
+}
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 fd8835b8631c..cf1af1dd6e45 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
@@ -4,7 +4,6 @@
import com.appsmith.server.constants.FieldName;
import com.appsmith.server.constants.Url;
import com.appsmith.server.domains.Application;
-import com.appsmith.server.domains.ApplicationJson;
import com.appsmith.server.domains.GitAuth;
import com.appsmith.server.domains.Theme;
import com.appsmith.server.dtos.ApplicationAccessDTO;
@@ -23,7 +22,6 @@
import com.appsmith.server.solutions.ImportExportApplicationService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.http.ContentDisposition;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
@@ -45,7 +43,6 @@
import reactor.core.publisher.Mono;
import javax.validation.Valid;
-import java.nio.charset.StandardCharsets;
import java.util.List;
@Slf4j
@@ -160,22 +157,15 @@ public Mono<ResponseDTO<Application>> forkApplication(
}
@GetMapping("/export/{id}")
- public Mono<ResponseEntity<ApplicationJson>> getApplicationFile(@PathVariable String id,
- @RequestHeader(name = FieldName.BRANCH_NAME, required = false) String branchName) {
+ public Mono<ResponseEntity<Object>> getApplicationFile(@PathVariable String id,
+ @RequestHeader(name = FieldName.BRANCH_NAME, required = false) String branchName) {
log.debug("Going to export application with id: {}, branch: {}", id, branchName);
- return importExportApplicationService.exportApplicationById(id, branchName)
+ return importExportApplicationService.getApplicationFile(id, branchName)
.map(fetchedResource -> {
- String applicationName = fetchedResource.getExportedApplication().getName();
- HttpHeaders responseHeaders = new HttpHeaders();
- ContentDisposition contentDisposition = ContentDisposition
- .builder("attachment")
- .filename(applicationName + ".json", StandardCharsets.UTF_8)
- .build();
- responseHeaders.setContentDisposition(contentDisposition);
- responseHeaders.setContentType(MediaType.APPLICATION_JSON);
-
- return new ResponseEntity<>(fetchedResource, responseHeaders, HttpStatus.OK);
+ HttpHeaders responseHeaders = fetchedResource.getHttpHeaders();
+ Object applicationResource = fetchedResource.getApplicationResource();
+ return new ResponseEntity<>(applicationResource, responseHeaders, HttpStatus.OK);
});
}
diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/converters/GsonISOStringToInstantConverter.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/converters/GsonISOStringToInstantConverter.java
deleted file mode 100644
index f8fe47ff4bb3..000000000000
--- a/app/server/appsmith-server/src/main/java/com/appsmith/server/converters/GsonISOStringToInstantConverter.java
+++ /dev/null
@@ -1,29 +0,0 @@
-package com.appsmith.server.converters;
-
-import com.google.gson.JsonDeserializationContext;
-import com.google.gson.JsonDeserializer;
-import com.google.gson.JsonElement;
-import com.google.gson.JsonParseException;
-
-import java.lang.reflect.Type;
-import java.time.Instant;
-
-public class GsonISOStringToInstantConverter implements JsonDeserializer<Instant> {
- @Override
- public Instant deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext jsonDeserializationContext) throws JsonParseException {
- if(jsonElement.isJsonNull()) {
- return null;
- }
- String jsonString = jsonElement.getAsJsonPrimitive().getAsString();
- if(jsonString.length() == 0) {
- return null;
- }
- try {
- Double aDouble = Double.parseDouble(jsonString);
- return Instant.ofEpochSecond(aDouble.longValue());
- } catch (NumberFormatException e) {
- // do nothing, let's try to parse with Instant.parse assuming it's in ISO format
- }
- return Instant.parse(jsonString);
- }
-}
diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/domains/ActionCollection.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/domains/ActionCollection.java
index a195c77d4ae1..ebc2f761415d 100644
--- a/app/server/appsmith-server/src/main/java/com/appsmith/server/domains/ActionCollection.java
+++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/domains/ActionCollection.java
@@ -32,4 +32,18 @@ public class ActionCollection extends BaseDomain {
ActionCollectionDTO unpublishedCollection;
ActionCollectionDTO publishedCollection;
+
+ public void sanitiseToExportDBObject() {
+ this.setDefaultResources(null);
+ ActionCollectionDTO unpublishedCollection = this.getUnpublishedCollection();
+ if (unpublishedCollection != null) {
+ unpublishedCollection.sanitiseForExport();
+ }
+ ActionCollectionDTO publishedCollection = this.getPublishedCollection();
+ if (publishedCollection != null) {
+ publishedCollection.sanitiseForExport();
+ }
+ this.sanitiseToExportBaseObject();
+ this.setOrganizationId(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 f6c456220051..2519f6fb73a6 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
@@ -18,7 +18,10 @@
import java.time.Instant;
import java.util.ArrayList;
import java.util.List;
+import java.util.Map;
+import static com.appsmith.server.constants.ResourceModes.EDIT;
+import static com.appsmith.server.constants.ResourceModes.VIEW;
import static com.appsmith.server.helpers.DateUtils.ISO_FORMATTER;
@Getter
@@ -161,6 +164,33 @@ public Application(Application application) {
this.publishedAppLayout = application.getPublishedAppLayout() == null ? null : new AppLayout(application.getPublishedAppLayout().type);
}
+ public void exportApplicationPages(final Map<String, String> pageIdToNameMap) {
+ for (ApplicationPage applicationPage : this.getPages()) {
+ applicationPage.setId(pageIdToNameMap.get(applicationPage.getId() + EDIT));
+ applicationPage.setDefaultPageId(null);
+ }
+ for (ApplicationPage applicationPage : this.getPublishedPages()) {
+ applicationPage.setId(pageIdToNameMap.get(applicationPage.getId() + VIEW));
+ applicationPage.setDefaultPageId(null);
+ }
+ }
+
+ public void sanitiseToExportDBObject() {
+ this.setWorkspaceId(null);
+ this.setOrganizationId(null);
+ this.setModifiedBy(null);
+ this.setCreatedBy(null);
+ this.setLastDeployedAt(null);
+ this.setLastEditedAt(null);
+ this.setGitApplicationMetadata(null);
+ this.setEditModeThemeId(null);
+ this.setPublishedModeThemeId(null);
+ this.setClientSchemaVersion(null);
+ this.setServerSchemaVersion(null);
+ this.setIsManualUpdate(false);
+ this.sanitiseToExportBaseObject();
+ }
+
public List<ApplicationPage> getPages() {
return Boolean.TRUE.equals(viewMode) ? publishedPages : pages;
}
diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/domains/Layout.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/domains/Layout.java
index fc1338a7acaa..a23b636c3519 100644
--- a/app/server/appsmith-server/src/main/java/com/appsmith/server/domains/Layout.java
+++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/domains/Layout.java
@@ -2,6 +2,8 @@
import com.appsmith.external.models.BaseDomain;
import com.appsmith.server.dtos.DslActionDTO;
+import com.appsmith.server.helpers.CollectionUtils;
+import com.appsmith.server.helpers.CompareDslActionDTO;
import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.Getter;
import lombok.NoArgsConstructor;
@@ -11,6 +13,7 @@
import java.util.List;
import java.util.Set;
+import java.util.TreeSet;
import static java.lang.Boolean.TRUE;
@@ -76,4 +79,23 @@ public Set<DslActionDTO> getLayoutActions() {
public List<Set<DslActionDTO>> getLayoutOnLoadActions() {
return viewMode ? publishedLayoutOnLoadActions : layoutOnLoadActions;
}
+
+ public void sanitiseToExportDBObject() {
+ this.setAllOnPageLoadActionNames(null);
+ this.setCreatedAt(null);
+ this.setUpdatedAt(null);
+ this.setAllOnPageLoadActionEdges(null);
+ this.setActionsUsedInDynamicBindings(null);
+ this.setWidgetNames(null);
+ List<Set<DslActionDTO>> layoutOnLoadActions = this.getLayoutOnLoadActions();
+ if (!CollectionUtils.isNullOrEmpty(layoutOnLoadActions)) {
+ // Sort actions based on id to commit to git in ordered manner
+ for (int dslActionIndex = 0; dslActionIndex < layoutOnLoadActions.size(); dslActionIndex++) {
+ TreeSet<DslActionDTO> sortedActions = new TreeSet<>(new CompareDslActionDTO());
+ sortedActions.addAll(layoutOnLoadActions.get(dslActionIndex));
+ sortedActions.forEach(DslActionDTO::sanitiseForExport);
+ layoutOnLoadActions.set(dslActionIndex, sortedActions);
+ }
+ }
+ }
}
diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/domains/NewAction.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/domains/NewAction.java
index 707292280951..eaa93ebacc5f 100644
--- a/app/server/appsmith-server/src/main/java/com/appsmith/server/domains/NewAction.java
+++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/domains/NewAction.java
@@ -39,4 +39,22 @@ public class NewAction extends BaseDomain {
ActionDTO publishedAction;
+ public void sanitiseToExportDBObject() {
+ this.setTemplateId(null);
+ this.setApplicationId(null);
+ this.setOrganizationId(null);
+ this.setWorkspaceId(null);
+ this.setProviderId(null);
+ this.setDocumentation(null);
+ ActionDTO unpublishedAction = this.getUnpublishedAction();
+ if (unpublishedAction != null) {
+ unpublishedAction.sanitiseToExportDBObject();
+ }
+ ActionDTO publishedAction = this.getPublishedAction();
+ if (publishedAction != null) {
+ publishedAction.sanitiseToExportDBObject();
+ }
+ this.sanitiseToExportBaseObject();
+ }
+
}
diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/domains/NewPage.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/domains/NewPage.java
index 7091919805ab..6dbef3f5e7a8 100644
--- a/app/server/appsmith-server/src/main/java/com/appsmith/server/domains/NewPage.java
+++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/domains/NewPage.java
@@ -18,4 +18,16 @@ public class NewPage extends BaseDomain {
PageDTO unpublishedPage;
PageDTO publishedPage;
+
+ public void sanitiseToExportDBObject() {
+ this.setApplicationId(null);
+ this.setId(null);
+ if (this.getUnpublishedPage() != null) {
+ this.getUnpublishedPage().sanitiseToExportDBObject();
+ }
+ if (this.getPublishedPage() != null) {
+ this.getPublishedPage().sanitiseToExportDBObject();
+ }
+ this.sanitiseToExportBaseObject();
+ }
}
diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/domains/Theme.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/domains/Theme.java
index 413b72c09bd9..838301ed82ee 100644
--- a/app/server/appsmith-server/src/main/java/com/appsmith/server/domains/Theme.java
+++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/domains/Theme.java
@@ -47,4 +47,16 @@ public static class Colors {
private String primaryColor;
private String backgroundColor;
}
+
+ public void sanitiseToExportDBObject() {
+ this.setId(null);
+ if(this.isSystemTheme()) {
+ // for system theme, we only need theme name and isSystemTheme properties so set null to others
+ this.setProperties(null);
+ this.setConfig(null);
+ this.setStylesheet(null);
+ }
+ // set null to base domain properties also
+ this.sanitiseToExportBaseObject();
+ }
}
diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/dtos/ActionCollectionDTO.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/dtos/ActionCollectionDTO.java
index d33e7bfeba9b..77e3d8c6e8ff 100644
--- a/app/server/appsmith-server/src/main/java/com/appsmith/server/dtos/ActionCollectionDTO.java
+++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/dtos/ActionCollectionDTO.java
@@ -115,4 +115,12 @@ public void populateTransientFields(ActionCollection actionCollection) {
this.setWorkspaceId(actionCollection.getWorkspaceId());
copyNewFieldValuesIntoOldObject(actionCollection.getDefaultResources(), this.getDefaultResources());
}
+
+ public void sanitiseForExport() {
+ this.setDefaultResources(null);
+ this.setDefaultToBranchedActionIdsMap(null);
+ this.setDefaultToBranchedArchivedActionIdsMap(null);
+ this.setActionIds(null);
+ this.setArchivedActionIds(null);
+ }
}
diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/dtos/ActionDTO.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/dtos/ActionDTO.java
index d39691ddee15..12ab3a43d320 100644
--- a/app/server/appsmith-server/src/main/java/com/appsmith/server/dtos/ActionDTO.java
+++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/dtos/ActionDTO.java
@@ -2,10 +2,10 @@
import com.appsmith.external.models.ActionConfiguration;
import com.appsmith.external.models.Datasource;
+import com.appsmith.external.models.DefaultResources;
import com.appsmith.external.models.Policy;
import com.appsmith.external.models.Property;
import com.appsmith.server.domains.ActionProvider;
-import com.appsmith.external.models.DefaultResources;
import com.appsmith.server.domains.Documentation;
import com.appsmith.server.domains.PluginType;
import com.fasterxml.jackson.annotation.JsonFormat;
@@ -148,4 +148,17 @@ public String getValidName() {
return this.fullyQualifiedName;
}
}
+ public void sanitiseToExportDBObject() {
+ this.setDefaultResources(null);
+ this.setCacheResponse(null);
+ if (this.getDatasource() != null) {
+ this.getDatasource().setCreatedAt(null);
+ }
+ if (this.getUserPermissions() != null) {
+ this.getUserPermissions().clear();
+ }
+ if (this.getPolicies() != null) {
+ this.getPolicies().clear();
+ }
+ }
}
diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/domains/ApplicationJson.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/dtos/ApplicationJson.java
similarity index 73%
rename from app/server/appsmith-server/src/main/java/com/appsmith/server/domains/ApplicationJson.java
rename to app/server/appsmith-server/src/main/java/com/appsmith/server/dtos/ApplicationJson.java
index 2f6e8bd9f79d..371f3477ce62 100644
--- a/app/server/appsmith-server/src/main/java/com/appsmith/server/domains/ApplicationJson.java
+++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/dtos/ApplicationJson.java
@@ -1,13 +1,17 @@
-package com.appsmith.server.domains;
+package com.appsmith.server.dtos;
import com.appsmith.external.models.Datasource;
-import com.appsmith.external.models.InvisibleActionFields;
import com.appsmith.external.models.DecryptedSensitiveFields;
+import com.appsmith.external.models.InvisibleActionFields;
+import com.appsmith.server.domains.ActionCollection;
+import com.appsmith.server.domains.Application;
+import com.appsmith.server.domains.NewAction;
+import com.appsmith.server.domains.NewPage;
+import com.appsmith.server.domains.Theme;
import lombok.Getter;
import lombok.Setter;
import org.springframework.data.annotation.Transient;
-import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
@@ -36,20 +40,26 @@ public class ApplicationJson {
List<NewPage> pageList;
- List<String> pageOrder = new ArrayList<>();
+ @Deprecated
+ List<String> pageOrder;
- List<String> publishedPageOrder = new ArrayList<>();
+ @Deprecated
+ List<String> publishedPageOrder;
+ @Deprecated
String publishedDefaultPageName;
-
+
+ @Deprecated
String unpublishedDefaultPageName;
List<NewAction> actionList;
List<ActionCollection> actionCollectionList;
+ // TODO remove the plain text fields during the export once we have a way to address sample apps DB authentication
Map<String, DecryptedSensitiveFields> decryptedFields;
+ @Deprecated
Map<String, InvisibleActionFields> invisibleActionFields;
Theme editModeTheme;
@@ -58,6 +68,9 @@ public class ApplicationJson {
/**
* Mapping mongoEscapedWidgets with layoutId
*/
+ @Deprecated
Map<String, Set<String>> publishedLayoutmongoEscapedWidgets;
+
+ @Deprecated
Map<String, Set<String>> unpublishedLayoutmongoEscapedWidgets;
}
diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/dtos/DslActionDTO.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/dtos/DslActionDTO.java
index dd42ee027fa4..07402c803b14 100644
--- a/app/server/appsmith-server/src/main/java/com/appsmith/server/dtos/DslActionDTO.java
+++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/dtos/DslActionDTO.java
@@ -28,4 +28,9 @@ public class DslActionDTO {
PluginType pluginType;
Set<String> jsonPathKeys;
Integer timeoutInMillisecond = DEFAULT_ACTION_EXECUTION_TIMEOUT_MS;
+
+ public void sanitiseForExport() {
+ this.setDefaultActionId(null);
+ this.setDefaultCollectionId(null);
+ }
}
diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/dtos/ExportFileDTO.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/dtos/ExportFileDTO.java
new file mode 100644
index 000000000000..a5ae30e6ae90
--- /dev/null
+++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/dtos/ExportFileDTO.java
@@ -0,0 +1,11 @@
+package com.appsmith.server.dtos;
+
+import lombok.Data;
+import org.springframework.http.HttpHeaders;
+
+
+@Data
+public class ExportFileDTO {
+ HttpHeaders httpHeaders;
+ Object applicationResource;
+}
diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/dtos/PageDTO.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/dtos/PageDTO.java
index 180d6bac25c5..0c26b15045a2 100644
--- a/app/server/appsmith-server/src/main/java/com/appsmith/server/dtos/PageDTO.java
+++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/dtos/PageDTO.java
@@ -55,4 +55,8 @@ public class PageDTO {
// connected applications and will be used to connect actions across the branches
@Transient
DefaultResources defaultResources;
+
+ public void sanitiseToExportDBObject() {
+ this.getLayouts().forEach(Layout::sanitiseToExportDBObject);
+ }
}
diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/helpers/CompareDslActionDTO.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/helpers/CompareDslActionDTO.java
index 6afe8b58c045..b3592481f3d3 100644
--- a/app/server/appsmith-server/src/main/java/com/appsmith/server/helpers/CompareDslActionDTO.java
+++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/helpers/CompareDslActionDTO.java
@@ -10,9 +10,9 @@ public class CompareDslActionDTO implements Comparator<DslActionDTO>, Serializab
// Method to compare DslActionDTO based on id
@Override
public int compare(DslActionDTO action1, DslActionDTO action2) {
- if (action1 != null && !StringUtils.isEmpty(action1.getId())
- && action2 != null && !StringUtils.isEmpty(action2.getId())) {
- return action1.getId().compareTo(action2.getId());
+ if (action1 != null && !StringUtils.isEmpty(action1.getName())
+ && action2 != null && !StringUtils.isEmpty(action2.getName())) {
+ return action1.getName().compareTo(action2.getName());
}
return 1;
}
diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/helpers/GitFileUtils.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/helpers/GitFileUtils.java
index 519cefbb21f3..d20ef0dbad12 100644
--- a/app/server/appsmith-server/src/main/java/com/appsmith/server/helpers/GitFileUtils.java
+++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/helpers/GitFileUtils.java
@@ -1,22 +1,21 @@
package com.appsmith.server.helpers;
+import com.appsmith.external.constants.AnalyticsEvents;
import com.appsmith.external.git.FileInterface;
import com.appsmith.external.helpers.Stopwatch;
import com.appsmith.external.models.ApplicationGitReference;
import com.appsmith.external.models.Datasource;
import com.appsmith.git.helpers.FileUtilsImpl;
-import com.appsmith.external.constants.AnalyticsEvents;
import com.appsmith.server.constants.FieldName;
import com.appsmith.server.domains.ActionCollection;
import com.appsmith.server.domains.Application;
-import com.appsmith.server.domains.ApplicationJson;
-import com.appsmith.server.domains.Layout;
+import com.appsmith.server.domains.ApplicationPage;
import com.appsmith.server.domains.NewAction;
import com.appsmith.server.domains.NewPage;
import com.appsmith.server.domains.Theme;
import com.appsmith.server.dtos.ActionCollectionDTO;
import com.appsmith.server.dtos.ActionDTO;
-import com.appsmith.server.dtos.DslActionDTO;
+import com.appsmith.server.dtos.ApplicationJson;
import com.appsmith.server.dtos.PageDTO;
import com.appsmith.server.exceptions.AppsmithError;
import com.appsmith.server.exceptions.AppsmithException;
@@ -39,11 +38,9 @@
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
-import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
-import java.util.TreeSet;
import java.util.stream.Collectors;
import static com.appsmith.external.constants.GitConstants.NAME_SEPARATOR;
@@ -205,14 +202,13 @@ public ApplicationGitReference createApplicationReference(ApplicationJson applic
resourceMap.put(prefix, actionCollection);
});
- applicationReference.setActionsCollections(new HashMap<>(resourceMap));
+ applicationReference.setActionCollections(new HashMap<>(resourceMap));
resourceMap.clear();
// Send datasources
applicationJson
.getDatasourceList()
.forEach(datasource -> {
- removeUnwantedFieldsFromDatasource(datasource);
resourceMap.put(datasource.getName(), datasource);
});
applicationReference.setDatasources(new HashMap<>(resourceMap));
@@ -308,19 +304,9 @@ public Mono<Boolean> checkIfDirectoryIsEmpty(Path baseRepoSuffix) throws IOExcep
}
private void removeUnwantedFieldsFromPage(NewPage page) {
- page.setDefaultResources(null);
- page.setCreatedAt(null);
- page.setUpdatedAt(null);
// As we are publishing the app and then committing to git we expect the published and unpublished PageDTO will
// be same, so we only commit unpublished PageDTO.
page.setPublishedPage(null);
- page.setUserPermissions(null);
- PageDTO unpublishedPage = page.getUnpublishedPage();
- if (unpublishedPage != null) {
- unpublishedPage
- .getLayouts()
- .forEach(this::removeUnwantedFieldsFromLayout);
- }
}
private void removeUnwantedFieldsFromApplication(Application application) {
@@ -331,83 +317,40 @@ private void removeUnwantedFieldsFromApplication(Application application) {
application.setSlug(null);
}
- private void removeUnwantedFieldsFromDatasource(Datasource datasource) {
- datasource.setPolicies(new HashSet<>());
- datasource.setStructure(null);
- datasource.setUpdatedAt(null);
- datasource.setCreatedAt(null);
- datasource.setUserPermissions(null);
- datasource.setIsConfigured(null);
- datasource.setInvalids(null);
- }
-
private void removeUnwantedFieldFromAction(NewAction action) {
- action.setDefaultResources(null);
- action.setCreatedAt(null);
- action.setUpdatedAt(null);
// As we are publishing the app and then committing to git we expect the published and unpublished ActionDTO will
// be same, so we only commit unpublished ActionDTO.
action.setPublishedAction(null);
- action.setUserPermissions(null);
- ActionDTO unpublishedAction = action.getUnpublishedAction();
- if (unpublishedAction != null) {
- unpublishedAction.setDefaultResources(null);
- if (unpublishedAction.getDatasource() != null) {
- unpublishedAction.getDatasource().setCreatedAt(null);
- }
- }
}
private void removeUnwantedFieldFromActionCollection(ActionCollection actionCollection) {
- actionCollection.setDefaultResources(null);
- actionCollection.setCreatedAt(null);
- actionCollection.setUpdatedAt(null);
// As we are publishing the app and then committing to git we expect the published and unpublished
// ActionCollectionDTO will be same, so we only commit unpublished ActionCollectionDTO.
actionCollection.setPublishedCollection(null);
- actionCollection.setUserPermissions(null);
- ActionCollectionDTO unpublishedCollection = actionCollection.getUnpublishedCollection();
- if (unpublishedCollection != null) {
- unpublishedCollection.setDefaultResources(null);
- unpublishedCollection.setDefaultToBranchedActionIdsMap(null);
- unpublishedCollection.setDefaultToBranchedArchivedActionIdsMap(null);
- unpublishedCollection.setActionIds(null);
- unpublishedCollection.setArchivedActionIds(null);
- }
- }
-
- private void removeUnwantedFieldsFromLayout(Layout layout) {
- layout.setAllOnPageLoadActionNames(null);
- layout.setCreatedAt(null);
- layout.setUpdatedAt(null);
- layout.setAllOnPageLoadActionEdges(null);
- layout.setActionsUsedInDynamicBindings(null);
- layout.setMongoEscapedWidgetNames(null);
- List<Set<DslActionDTO>> layoutOnLoadActions = layout.getLayoutOnLoadActions();
- if (!CollectionUtils.isNullOrEmpty(layout.getLayoutOnLoadActions())) {
- // Sort actions based on id to commit to git in ordered manner
- for (int dslActionIndex = 0; dslActionIndex < layoutOnLoadActions.size(); dslActionIndex++) {
- TreeSet<DslActionDTO> sortedActions = new TreeSet<>(new CompareDslActionDTO());
- sortedActions.addAll(layoutOnLoadActions.get(dslActionIndex));
- sortedActions
- .forEach(actionDTO -> {
- actionDTO.setDefaultActionId(null);
- actionDTO.setDefaultCollectionId(null);
- });
- layoutOnLoadActions.set(dslActionIndex, sortedActions);
- }
- }
}
private ApplicationJson getApplicationJsonFromGitReference(ApplicationGitReference applicationReference) {
ApplicationJson applicationJson = new ApplicationJson();
// Extract application data from the json
- applicationJson.setExportedApplication(getApplicationResource(applicationReference.getApplication(), Application.class));
+ Application application = getApplicationResource(applicationReference.getApplication(), Application.class);
+ applicationJson.setExportedApplication(application);
applicationJson.setEditModeTheme(getApplicationResource(applicationReference.getTheme(), Theme.class));
// Clone the edit mode theme to published theme as both should be same for git connected application because we
// do deploy and push as a single operation
applicationJson.setPublishedTheme(applicationJson.getEditModeTheme());
Gson gson = new Gson();
+
+ if (application != null && !CollectionUtils.isNullOrEmpty(application.getPages())) {
+ // Remove null values
+ org.apache.commons.collections.CollectionUtils.filter(application.getPages(), PredicateUtils.notNullPredicate());
+ // Create a deep clone of application pages to update independently
+ application.setViewMode(false);
+ final List<ApplicationPage> applicationPages = new ArrayList<>(application.getPages().size());
+ application.getPages()
+ .forEach(applicationPage -> applicationPages.add(gson.fromJson(gson.toJson(applicationPage), ApplicationPage.class)));
+ application.setPublishedPages(applicationPages);
+ }
+
// Extract pages
List<NewPage> pages = getApplicationResource(applicationReference.getPages(), NewPage.class);
// Remove null values
@@ -436,10 +379,10 @@ private ApplicationJson getApplicationJsonFromGitReference(ApplicationGitReferen
}
// Extract actionCollection
- if (CollectionUtils.isNullOrEmpty(applicationReference.getActionsCollections())) {
+ if (CollectionUtils.isNullOrEmpty(applicationReference.getActionCollections())) {
applicationJson.setActionCollectionList(new ArrayList<>());
} else {
- List<ActionCollection> actionCollections = getApplicationResource(applicationReference.getActionsCollections(), ActionCollection.class);
+ List<ActionCollection> actionCollections = getApplicationResource(applicationReference.getActionCollections(), ActionCollection.class);
// Remove null values if present
org.apache.commons.collections.CollectionUtils.filter(actionCollections, PredicateUtils.notNullPredicate());
actionCollections.forEach(actionCollection -> {
diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/migrations/HelperMethods.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/migrations/HelperMethods.java
deleted file mode 100644
index 56026ced3390..000000000000
--- a/app/server/appsmith-server/src/main/java/com/appsmith/server/migrations/HelperMethods.java
+++ /dev/null
@@ -1,42 +0,0 @@
-package com.appsmith.server.migrations;
-
-import com.appsmith.server.domains.ApplicationJson;
-import com.appsmith.server.domains.NewAction;
-import com.appsmith.server.dtos.ActionDTO;
-import com.appsmith.server.helpers.CollectionUtils;
-
-import java.time.Instant;
-import java.util.List;
-
-public class HelperMethods {
- // Migration for deprecating archivedAt field in ActionDTO
- public static void updateArchivedAtByDeletedATForActions(List<NewAction> actionList) {
- for (NewAction newAction : actionList) {
- ActionDTO unpublishedAction = newAction.getUnpublishedAction();
- if (unpublishedAction != null) {
- final Instant archivedAt = unpublishedAction.getArchivedAt();
- unpublishedAction.setDeletedAt(archivedAt);
- unpublishedAction.setArchivedAt(null);
- }
- }
- }
-
- public static void migrateActionFormDataToObject(ApplicationJson applicationJson) {
- final List<NewAction> actionList = applicationJson.getActionList();
-
- if (!CollectionUtils.isNullOrEmpty(actionList)) {
- actionList.parallelStream()
- .forEach(newAction -> {
- // determine plugin
- final String pluginName = newAction.getPluginId();
- if ("mongo-plugin".equals(pluginName)) {
- DatabaseChangelog2.migrateMongoActionsFormData(newAction);
- } else if ("amazons3-plugin".equals(pluginName)) {
- DatabaseChangelog2.migrateAmazonS3ActionsFormData(newAction);
- } else if ("firestore-plugin".equals(pluginName)) {
- DatabaseChangelog2.migrateFirestoreActionsFormData(newAction);
- }
- });
- }
- }
-}
diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/migrations/JsonSchemaMigration.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/migrations/JsonSchemaMigration.java
index 77d7da6aa0ed..3a1a820ca06b 100644
--- a/app/server/appsmith-server/src/main/java/com/appsmith/server/migrations/JsonSchemaMigration.java
+++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/migrations/JsonSchemaMigration.java
@@ -1,6 +1,6 @@
package com.appsmith.server.migrations;
-import com.appsmith.server.domains.ApplicationJson;
+import com.appsmith.server.dtos.ApplicationJson;
import com.appsmith.server.exceptions.AppsmithError;
import com.appsmith.server.exceptions.AppsmithException;
import com.appsmith.server.helpers.CollectionUtils;
@@ -40,16 +40,26 @@ private static ApplicationJson migrateServerSchema(ApplicationJson applicationJs
case 1:
// Migration for deprecating archivedAt field in ActionDTO
if (!CollectionUtils.isNullOrEmpty(applicationJson.getActionList())) {
- HelperMethods.updateArchivedAtByDeletedATForActions(applicationJson.getActionList());
+ MigrationHelperMethods.updateArchivedAtByDeletedATForActions(applicationJson.getActionList());
}
applicationJson.setServerSchemaVersion(2);
case 2:
// Migration for converting formData elements to one that supports viewType
- HelperMethods.migrateActionFormDataToObject(applicationJson);
+ MigrationHelperMethods.migrateActionFormDataToObject(applicationJson);
applicationJson.setServerSchemaVersion(3);
case 3:
// File structure migration to update git directory structure
applicationJson.setServerSchemaVersion(4);
+ case 4:
+ // Remove unwanted fields from DTO and allow serialization for JsonIgnore fields
+ if (!CollectionUtils.isNullOrEmpty(applicationJson.getPageList()) && applicationJson.getExportedApplication() != null) {
+ MigrationHelperMethods.arrangeApplicationPagesAsPerImportedPageOrder(applicationJson);
+ MigrationHelperMethods.updateMongoEscapedWidget(applicationJson);
+ }
+ if (!CollectionUtils.isNullOrEmpty(applicationJson.getActionList())) {
+ MigrationHelperMethods.updateUserSetOnLoadAction(applicationJson);
+ }
+ applicationJson.setServerSchemaVersion(5);
default:
// Unable to detect the serverSchema
}
diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/migrations/JsonSchemaVersions.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/migrations/JsonSchemaVersions.java
index ba1c5de95062..c11d224271ed 100644
--- a/app/server/appsmith-server/src/main/java/com/appsmith/server/migrations/JsonSchemaVersions.java
+++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/migrations/JsonSchemaVersions.java
@@ -12,6 +12,6 @@
*/
@Getter
public class JsonSchemaVersions {
- public final static Integer serverVersion = 4;
+ public final static Integer serverVersion = 5;
public final static Integer clientVersion = 1;
}
diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/migrations/MigrationHelperMethods.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/migrations/MigrationHelperMethods.java
new file mode 100644
index 000000000000..3a63721738d3
--- /dev/null
+++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/migrations/MigrationHelperMethods.java
@@ -0,0 +1,153 @@
+package com.appsmith.server.migrations;
+
+import com.appsmith.external.models.InvisibleActionFields;
+import com.appsmith.server.constants.ResourceModes;
+import com.appsmith.server.domains.ApplicationPage;
+import com.appsmith.server.domains.NewAction;
+import com.appsmith.server.dtos.ActionDTO;
+import com.appsmith.server.dtos.ApplicationJson;
+import com.appsmith.server.helpers.CollectionUtils;
+import org.apache.commons.lang.StringUtils;
+
+import java.time.Instant;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.stream.Collectors;
+
+import static com.appsmith.server.constants.ResourceModes.EDIT;
+import static com.appsmith.server.constants.ResourceModes.VIEW;
+
+public class MigrationHelperMethods {
+ // Migration for deprecating archivedAt field in ActionDTO
+ public static void updateArchivedAtByDeletedATForActions(List<NewAction> actionList) {
+ for (NewAction newAction : actionList) {
+ ActionDTO unpublishedAction = newAction.getUnpublishedAction();
+ if (unpublishedAction != null) {
+ final Instant archivedAt = unpublishedAction.getArchivedAt();
+ unpublishedAction.setDeletedAt(archivedAt);
+ unpublishedAction.setArchivedAt(null);
+ }
+ }
+ }
+
+ public static void migrateActionFormDataToObject(ApplicationJson applicationJson) {
+ final List<NewAction> actionList = applicationJson.getActionList();
+
+ if (!CollectionUtils.isNullOrEmpty(actionList)) {
+ actionList.parallelStream()
+ .forEach(newAction -> {
+ // determine plugin
+ final String pluginName = newAction.getPluginId();
+ if ("mongo-plugin".equals(pluginName)) {
+ DatabaseChangelog2.migrateMongoActionsFormData(newAction);
+ } else if ("amazons3-plugin".equals(pluginName)) {
+ DatabaseChangelog2.migrateAmazonS3ActionsFormData(newAction);
+ } else if ("firestore-plugin".equals(pluginName)) {
+ DatabaseChangelog2.migrateFirestoreActionsFormData(newAction);
+ }
+ });
+ }
+ }
+
+ // Method to embed application pages in imported application object as per modified serialization format where we
+ // are serialising JsonIgnored fields to keep the relevant data with domain objects only
+ public static void arrangeApplicationPagesAsPerImportedPageOrder(ApplicationJson applicationJson) {
+
+ Map<ResourceModes, List<ApplicationPage>> applicationPages = Map.of(
+ EDIT, new ArrayList<>(),
+ VIEW, new ArrayList<>()
+ );
+ // Reorder the pages based on edit mode page sequence
+ List<String> pageOrderList;
+ if(!CollectionUtils.isNullOrEmpty(applicationJson.getPageOrder())) {
+ pageOrderList = applicationJson.getPageOrder();
+ } else {
+ pageOrderList = applicationJson.getPageList()
+ .parallelStream()
+ .filter(newPage -> newPage.getUnpublishedPage() != null && newPage.getUnpublishedPage().getDeletedAt() == null)
+ .map(newPage -> newPage.getUnpublishedPage().getName())
+ .collect(Collectors.toList());
+ }
+ for(String pageName : pageOrderList) {
+ ApplicationPage unpublishedAppPage = new ApplicationPage();
+ unpublishedAppPage.setId(pageName);
+ unpublishedAppPage.setIsDefault(StringUtils.equals(pageName, applicationJson.getUnpublishedDefaultPageName()));
+ applicationPages.get(EDIT).add(unpublishedAppPage);
+ }
+
+ // Reorder the pages based on view mode page sequence
+ pageOrderList.clear();
+ if(!CollectionUtils.isNullOrEmpty(applicationJson.getPublishedPageOrder())) {
+ pageOrderList = applicationJson.getPublishedPageOrder();
+ } else {
+ pageOrderList = applicationJson.getPageList()
+ .parallelStream()
+ .filter(newPage -> newPage.getPublishedPage() != null && !StringUtils.isEmpty(newPage.getPublishedPage().getName()))
+ .map(newPage -> newPage.getPublishedPage().getName())
+ .collect(Collectors.toList());
+ }
+ for(String pageName : pageOrderList) {
+ ApplicationPage publishedAppPage = new ApplicationPage();
+ publishedAppPage.setId(pageName);
+ publishedAppPage.setIsDefault(StringUtils.equals(pageName, applicationJson.getPublishedDefaultPageName()));
+ applicationPages.get(VIEW).add(publishedAppPage);
+ }
+ applicationJson.getExportedApplication().setPages(applicationPages.get(EDIT));
+ applicationJson.getExportedApplication().setPublishedPages(applicationPages.get(VIEW));
+ }
+
+ // Method to embed mongo escaped widgets in imported layouts as per modified serialization format where we are
+ // serialising JsonIgnored fields to keep the relevant data with domain objects only
+ public static void updateMongoEscapedWidget(ApplicationJson applicationJson) {
+ Map<String, Set<String>> unpublishedMongoEscapedWidget
+ = CollectionUtils.isNullOrEmpty(applicationJson.getUnpublishedLayoutmongoEscapedWidgets())
+ ? new HashMap<>()
+ : applicationJson.getUnpublishedLayoutmongoEscapedWidgets();
+
+ Map<String, Set<String>> publishedMongoEscapedWidget
+ = CollectionUtils.isNullOrEmpty(applicationJson.getPublishedLayoutmongoEscapedWidgets())
+ ? new HashMap<>()
+ : applicationJson.getPublishedLayoutmongoEscapedWidgets();
+
+ applicationJson.getPageList().parallelStream().forEach(newPage -> {
+ if (newPage.getUnpublishedPage() != null
+ && unpublishedMongoEscapedWidget.containsKey(newPage.getUnpublishedPage().getName())
+ && !CollectionUtils.isNullOrEmpty(newPage.getUnpublishedPage().getLayouts())) {
+
+ newPage.getUnpublishedPage().getLayouts().forEach(layout -> {
+ layout.setMongoEscapedWidgetNames(unpublishedMongoEscapedWidget.get(layout.getId()));
+ });
+ }
+
+ if (newPage.getPublishedPage() != null
+ && publishedMongoEscapedWidget.containsKey(newPage.getPublishedPage().getName())
+ && !CollectionUtils.isNullOrEmpty(newPage.getPublishedPage().getLayouts())) {
+
+ newPage.getPublishedPage().getLayouts().forEach(layout -> {
+ layout.setMongoEscapedWidgetNames(publishedMongoEscapedWidget.get(layout.getId()));
+ });
+ }
+ });
+ }
+
+ // Method to embed userSetOnLoad in imported actions as per modified serialization format where we are serialising
+ // JsonIgnored fields to keep the relevant data with domain objects only
+ public static void updateUserSetOnLoadAction(ApplicationJson applicationJson) {
+ Map<String, InvisibleActionFields> invisibleActionFieldsMap = applicationJson.getInvisibleActionFields() ;
+ if (invisibleActionFieldsMap != null) {
+ applicationJson.getActionList().parallelStream().forEach(newAction -> {
+ if (newAction.getUnpublishedAction() != null) {
+ newAction.getUnpublishedAction()
+ .setUserSetOnLoad(invisibleActionFieldsMap.get(newAction.getId()).getUnpublishedUserSetOnLoad());
+ }
+ if (newAction.getPublishedAction() != null) {
+ newAction.getPublishedAction()
+ .setUserSetOnLoad(invisibleActionFieldsMap.get(newAction.getId()).getPublishedUserSetOnLoad());
+ }
+ });
+ }
+ }
+}
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 df12eb9972b1..c2dd15680611 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
@@ -2,9 +2,9 @@
import com.appsmith.external.constants.AnalyticsEvents;
import com.appsmith.server.configurations.CloudServicesConfig;
-import com.appsmith.server.converters.GsonISOStringToInstantConverter;
+import com.appsmith.external.converters.GsonISOStringToInstantConverter;
import com.appsmith.server.domains.Application;
-import com.appsmith.server.domains.ApplicationJson;
+import com.appsmith.server.dtos.ApplicationJson;
import com.appsmith.server.domains.UserData;
import com.appsmith.server.dtos.ApplicationTemplate;
import com.appsmith.server.exceptions.AppsmithError;
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 81fb0c48aeb0..69456d322e12 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
@@ -16,7 +16,7 @@
import com.appsmith.server.constants.FieldName;
import com.appsmith.server.constants.SerialiseApplicationObjective;
import com.appsmith.server.domains.Application;
-import com.appsmith.server.domains.ApplicationJson;
+import com.appsmith.server.dtos.ApplicationJson;
import com.appsmith.server.domains.GitApplicationMetadata;
import com.appsmith.server.domains.GitAuth;
import com.appsmith.server.domains.GitDeployKeys;
diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/ThemeServiceCE.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/ThemeServiceCE.java
index c54c61765fc5..53e4e29c4296 100644
--- a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/ThemeServiceCE.java
+++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/ThemeServiceCE.java
@@ -2,9 +2,9 @@
import com.appsmith.server.acl.AclPermission;
import com.appsmith.server.domains.Application;
-import com.appsmith.server.domains.ApplicationJson;
import com.appsmith.server.domains.ApplicationMode;
import com.appsmith.server.domains.Theme;
+import com.appsmith.server.dtos.ApplicationJson;
import com.appsmith.server.services.CrudService;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/ThemeServiceCEImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/ThemeServiceCEImpl.java
index 951df25ce08c..f8df32c52173 100644
--- a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/ThemeServiceCEImpl.java
+++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/ThemeServiceCEImpl.java
@@ -5,9 +5,9 @@
import com.appsmith.server.acl.PolicyGenerator;
import com.appsmith.server.constants.FieldName;
import com.appsmith.server.domains.Application;
-import com.appsmith.server.domains.ApplicationJson;
import com.appsmith.server.domains.ApplicationMode;
import com.appsmith.server.domains.Theme;
+import com.appsmith.server.dtos.ApplicationJson;
import com.appsmith.server.exceptions.AppsmithError;
import com.appsmith.server.exceptions.AppsmithException;
import com.appsmith.server.repositories.ApplicationRepository;
diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ImportExportApplicationServiceImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ImportExportApplicationServiceImpl.java
index 9fe923ff9f74..824f20c82e59 100644
--- a/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ImportExportApplicationServiceImpl.java
+++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ImportExportApplicationServiceImpl.java
@@ -1,10 +1,6 @@
package com.appsmith.server.solutions;
import com.appsmith.server.helpers.PolicyUtils;
-import com.appsmith.server.domains.Application;
-import com.appsmith.server.domains.ApplicationJson;
-import com.appsmith.server.exceptions.AppsmithError;
-import com.appsmith.server.exceptions.AppsmithException;
import com.appsmith.server.repositories.ActionCollectionRepository;
import com.appsmith.server.repositories.DatasourceRepository;
import com.appsmith.server.repositories.NewActionRepository;
@@ -17,17 +13,13 @@
import com.appsmith.server.services.DatasourceService;
import com.appsmith.server.services.NewActionService;
import com.appsmith.server.services.NewPageService;
-import com.appsmith.server.services.WorkspaceService;
import com.appsmith.server.services.SequenceService;
import com.appsmith.server.services.SessionUserService;
import com.appsmith.server.services.ThemeService;
+import com.appsmith.server.services.WorkspaceService;
import com.appsmith.server.solutions.ce.ImportExportApplicationServiceCEImpl;
import lombok.extern.slf4j.Slf4j;
-import org.springframework.core.io.buffer.DataBufferUtils;
-import org.springframework.http.MediaType;
-import org.springframework.http.codec.multipart.Part;
import org.springframework.stereotype.Component;
-import reactor.core.publisher.Mono;
@Slf4j
@Component
diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ce/CreateDBTablePageSolutionCEImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ce/CreateDBTablePageSolutionCEImpl.java
index eb304ccc67cd..b8bfe0af09c2 100644
--- a/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ce/CreateDBTablePageSolutionCEImpl.java
+++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ce/CreateDBTablePageSolutionCEImpl.java
@@ -1,5 +1,7 @@
package com.appsmith.server.solutions.ce;
+import com.appsmith.external.constants.AnalyticsEvents;
+import com.appsmith.external.converters.GsonISOStringToInstantConverter;
import com.appsmith.external.helpers.AppsmithBeanUtils;
import com.appsmith.external.models.ActionConfiguration;
import com.appsmith.external.models.Datasource;
@@ -10,17 +12,15 @@
import com.appsmith.external.models.DefaultResources;
import com.appsmith.external.models.Property;
import com.appsmith.server.acl.AclPermission;
-import com.appsmith.external.constants.AnalyticsEvents;
import com.appsmith.server.constants.Assets;
import com.appsmith.server.constants.Entity;
import com.appsmith.server.constants.FieldName;
-import com.appsmith.server.converters.GsonISOStringToInstantConverter;
-import com.appsmith.server.domains.ApplicationJson;
import com.appsmith.server.domains.Layout;
import com.appsmith.server.domains.NewAction;
import com.appsmith.server.domains.NewPage;
import com.appsmith.server.domains.Plugin;
import com.appsmith.server.dtos.ActionDTO;
+import com.appsmith.server.dtos.ApplicationJson;
import com.appsmith.server.dtos.CRUDPageResourceDTO;
import com.appsmith.server.dtos.CRUDPageResponseDTO;
import com.appsmith.server.dtos.PageDTO;
diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ce/ImportExportApplicationServiceCE.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ce/ImportExportApplicationServiceCE.java
index 811c5b6a4bc8..e3b044ef6233 100644
--- a/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ce/ImportExportApplicationServiceCE.java
+++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ce/ImportExportApplicationServiceCE.java
@@ -3,8 +3,9 @@
import com.appsmith.external.models.Datasource;
import com.appsmith.server.constants.SerialiseApplicationObjective;
import com.appsmith.server.domains.Application;
-import com.appsmith.server.domains.ApplicationJson;
import com.appsmith.server.dtos.ApplicationImportDTO;
+import com.appsmith.server.dtos.ApplicationJson;
+import com.appsmith.server.dtos.ExportFileDTO;
import org.springframework.http.codec.multipart.Part;
import reactor.core.publisher.Mono;
@@ -23,6 +24,8 @@ public interface ImportExportApplicationServiceCE {
Mono<ApplicationJson> exportApplicationById(String applicationId, String branchName);
+ Mono<ExportFileDTO> getApplicationFile(String applicationId, String branchName);
+
/**
* This function will take the Json filepart and saves the application in workspace
*
diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ce/ImportExportApplicationServiceCEImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ce/ImportExportApplicationServiceCEImpl.java
index 0b6310cea424..95e9f01e4d10 100644
--- a/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ce/ImportExportApplicationServiceCEImpl.java
+++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ce/ImportExportApplicationServiceCEImpl.java
@@ -1,6 +1,7 @@
package com.appsmith.server.solutions.ce;
-import com.appsmith.external.helpers.AppsmithBeanUtils;
+import com.appsmith.external.constants.AnalyticsEvents;
+import com.appsmith.external.converters.GsonISOStringToInstantConverter;
import com.appsmith.external.helpers.Stopwatch;
import com.appsmith.external.models.AuthenticationDTO;
import com.appsmith.external.models.AuthenticationResponse;
@@ -11,17 +12,15 @@
import com.appsmith.external.models.DatasourceConfiguration;
import com.appsmith.external.models.DecryptedSensitiveFields;
import com.appsmith.external.models.DefaultResources;
-import com.appsmith.external.models.InvisibleActionFields;
import com.appsmith.external.models.OAuth2;
import com.appsmith.server.acl.AclPermission;
-import com.appsmith.external.constants.AnalyticsEvents;
import com.appsmith.server.constants.FieldName;
+import com.appsmith.server.constants.ResourceModes;
import com.appsmith.server.constants.SerialiseApplicationObjective;
-import com.appsmith.server.converters.GsonISOStringToInstantConverter;
import com.appsmith.server.domains.ActionCollection;
import com.appsmith.server.domains.Application;
-import com.appsmith.server.domains.ApplicationJson;
import com.appsmith.server.domains.ApplicationPage;
+import com.appsmith.server.domains.Layout;
import com.appsmith.server.domains.NewAction;
import com.appsmith.server.domains.NewPage;
import com.appsmith.server.domains.Theme;
@@ -29,6 +28,8 @@
import com.appsmith.server.dtos.ActionCollectionDTO;
import com.appsmith.server.dtos.ActionDTO;
import com.appsmith.server.dtos.ApplicationImportDTO;
+import com.appsmith.server.dtos.ApplicationJson;
+import com.appsmith.server.dtos.ExportFileDTO;
import com.appsmith.server.dtos.PageDTO;
import com.appsmith.server.exceptions.AppsmithError;
import com.appsmith.server.exceptions.AppsmithException;
@@ -50,10 +51,10 @@
import com.appsmith.server.services.DatasourceService;
import com.appsmith.server.services.NewActionService;
import com.appsmith.server.services.NewPageService;
-import com.appsmith.server.services.WorkspaceService;
import com.appsmith.server.services.SequenceService;
import com.appsmith.server.services.SessionUserService;
import com.appsmith.server.services.ThemeService;
+import com.appsmith.server.services.WorkspaceService;
import com.appsmith.server.solutions.ExamplesWorkspaceCloner;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
@@ -65,6 +66,8 @@
import org.bson.types.ObjectId;
import org.springframework.core.io.buffer.DataBufferUtils;
import org.springframework.dao.DuplicateKeyException;
+import org.springframework.http.ContentDisposition;
+import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.codec.multipart.Part;
import reactor.core.publisher.Flux;
@@ -72,16 +75,17 @@
import reactor.util.function.Tuple2;
import java.lang.reflect.Type;
+import java.nio.charset.StandardCharsets;
import java.time.Instant;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
-import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
+import static com.appsmith.external.helpers.AppsmithBeanUtils.copyNestedNonNullProperties;
import static com.appsmith.server.acl.AclPermission.EXPORT_APPLICATIONS;
import static com.appsmith.server.acl.AclPermission.MANAGE_ACTIONS;
import static com.appsmith.server.acl.AclPermission.MANAGE_APPLICATIONS;
@@ -91,6 +95,8 @@
import static com.appsmith.server.acl.AclPermission.READ_APPLICATIONS;
import static com.appsmith.server.acl.AclPermission.READ_PAGES;
import static com.appsmith.server.acl.AclPermission.READ_THEMES;
+import static com.appsmith.server.constants.ResourceModes.EDIT;
+import static com.appsmith.server.constants.ResourceModes.VIEW;
@Slf4j
@RequiredArgsConstructor
@@ -118,10 +124,6 @@ public class ImportExportApplicationServiceCEImpl implements ImportExportApplica
private static final Set<MediaType> ALLOWED_CONTENT_TYPES = Set.of(MediaType.APPLICATION_JSON);
private static final String INVALID_JSON_FILE = "invalid json file";
- private enum PublishType {
- UNPUBLISHED, PUBLISHED
- }
-
/**
* This function will give the application resource to rebuild the application in import application flow
*
@@ -205,43 +207,20 @@ public Mono<ApplicationJson> exportApplicationById(String applicationId, Seriali
.switchIfEmpty(defaultThemeMono)// setting default theme if theme is missing
)
.map(themesTuple -> {
- Theme editModeTheme = exportTheme(themesTuple.getT1());
- Theme publishedModeTheme = exportTheme(themesTuple.getT2());
+ Theme editModeTheme = themesTuple.getT1();
+ Theme publishedModeTheme = themesTuple.getT2();
+ editModeTheme.sanitiseToExportDBObject();
+ publishedModeTheme.sanitiseToExportDBObject();
applicationJson.setEditModeTheme(editModeTheme);
applicationJson.setPublishedTheme(publishedModeTheme);
return themesTuple;
}).thenReturn(application))
.flatMap(application -> {
- // Assign the default page names for published and unpublished field in applicationJson object
- ApplicationPage unpublishedDefaultPage = application.getPages()
- .stream()
- .filter(ApplicationPage::getIsDefault)
- .findFirst()
- .orElse(null);
-
- if (unpublishedDefaultPage == null) {
- return Mono.error(new AppsmithException(AppsmithError.NO_RESOURCE_FOUND, FieldName.DEFAULT_PAGE_NAME));
- } else {
- applicationJson.setUnpublishedDefaultPageName(unpublishedDefaultPage.getId());
- }
-
- if (application.getPublishedPages() != null) {
- application.getPublishedPages()
- .stream()
- .filter(ApplicationPage::getIsDefault)
- .findFirst()
- .ifPresent(
- publishedDefaultPage -> applicationJson.setPublishedDefaultPageName(publishedDefaultPage.getId())
- );
- }
-
// Refactor application to remove the ids
final String workspaceId = application.getWorkspaceId();
- List<String> pageOrderList = application.getPages().stream().map(applicationPage -> applicationPage.getId()).collect(Collectors.toList());
- List<String> publishedPageOrderList = application.getPublishedPages().stream().map(applicationPage -> applicationPage.getId()).collect(Collectors.toList());
- removeUnwantedFieldsFromApplicationDuringExport(application);
examplesWorkspaceCloner.makePristine(application);
+ application.sanitiseToExportDBObject();
applicationJson.setExportedApplication(application);
Set<String> dbNamesUsedInActions = new HashSet<>();
@@ -255,75 +234,33 @@ public Mono<ApplicationJson> exportApplicationById(String applicationId, Seriali
// Extract mongoEscapedWidgets from pages and save it to applicationJson object as this
// field is JsonIgnored. Also remove any ids those are present in the page objects
- Map<String, Set<String>> publishedMongoEscapedWidgetsNames = new HashMap<>();
- Map<String, Set<String>> unpublishedMongoEscapedWidgetsNames = new HashMap<>();
newPageList.forEach(newPage -> {
if (newPage.getUnpublishedPage() != null) {
pageIdToNameMap.put(
- newPage.getId() + PublishType.UNPUBLISHED, newPage.getUnpublishedPage().getName()
+ newPage.getId() + EDIT, newPage.getUnpublishedPage().getName()
);
PageDTO unpublishedPageDTO = newPage.getUnpublishedPage();
- if (StringUtils.equals(
- applicationJson.getUnpublishedDefaultPageName(), newPage.getId())
- ) {
- applicationJson.setUnpublishedDefaultPageName(unpublishedPageDTO.getName());
- }
- if (unpublishedPageDTO.getLayouts() != null) {
-
+ if (!CollectionUtils.isEmpty(unpublishedPageDTO.getLayouts())) {
unpublishedPageDTO.getLayouts().forEach(layout -> {
layout.setId(unpublishedPageDTO.getName());
- unpublishedMongoEscapedWidgetsNames
- .put(layout.getId(), layout.getMongoEscapedWidgetNames());
-
});
}
}
if (newPage.getPublishedPage() != null) {
pageIdToNameMap.put(
- newPage.getId() + PublishType.PUBLISHED, newPage.getPublishedPage().getName()
+ newPage.getId() + VIEW, newPage.getPublishedPage().getName()
);
PageDTO publishedPageDTO = newPage.getPublishedPage();
- if (applicationJson.getPublishedDefaultPageName() != null &&
- StringUtils.equals(
- applicationJson.getPublishedDefaultPageName(), newPage.getId()
- )
- ) {
- applicationJson.setPublishedDefaultPageName(publishedPageDTO.getName());
- }
-
- if (publishedPageDTO.getLayouts() != null) {
+ if (!CollectionUtils.isEmpty(publishedPageDTO.getLayouts())) {
publishedPageDTO.getLayouts().forEach(layout -> {
layout.setId(publishedPageDTO.getName());
- publishedMongoEscapedWidgetsNames.put(layout.getId(), layout.getMongoEscapedWidgetNames());
});
}
}
- newPage.setApplicationId(null);
- examplesWorkspaceCloner.makePristine(newPage);
+ newPage.sanitiseToExportDBObject();
});
applicationJson.setPageList(newPageList);
- applicationJson.setPublishedLayoutmongoEscapedWidgets(publishedMongoEscapedWidgetsNames);
- applicationJson.setUnpublishedLayoutmongoEscapedWidgets(unpublishedMongoEscapedWidgetsNames);
-
- // Save the page order to json while exporting the application
- for (String pageId : pageOrderList) {
- String pageName = pageIdToNameMap.get(pageId + PublishType.UNPUBLISHED);
- if (!StringUtils.isEmpty(pageName)) {
- applicationJson.getPageOrder().add(pageName);
- } else {
- log.debug("Unable to find page {} during export", pageId);
- }
- }
-
- for (String pageId : publishedPageOrderList) {
- String pageName = pageIdToNameMap.get(pageId + PublishType.PUBLISHED);
- if (!StringUtils.isEmpty(pageName)) {
- applicationJson.getPublishedPageOrder().add(pageName);
- } else {
- log.debug("Unable to find page {} during export", pageId);
- }
- }
Flux<Datasource> datasourceFlux = Boolean.TRUE.equals(application.getExportWithConfiguration())
? datasourceRepository.findAllByWorkspaceId(workspaceId, AclPermission.READ_DATASOURCES)
@@ -352,7 +289,7 @@ public Mono<ApplicationJson> exportApplicationById(String applicationId, Seriali
// be used to replace collectionIds in action
if (actionCollection.getUnpublishedCollection() != null) {
ActionCollectionDTO actionCollectionDTO = actionCollection.getUnpublishedCollection();
- actionCollectionDTO.setPageId(pageIdToNameMap.get(actionCollectionDTO.getPageId() + PublishType.UNPUBLISHED));
+ actionCollectionDTO.setPageId(pageIdToNameMap.get(actionCollectionDTO.getPageId() + EDIT));
actionCollectionDTO.setPluginId(pluginMap.get(actionCollectionDTO.getPluginId()));
final String updatedCollectionId = actionCollectionDTO.getPageId() + "_" + actionCollectionDTO.getName();
@@ -361,7 +298,7 @@ public Mono<ApplicationJson> exportApplicationById(String applicationId, Seriali
}
if (actionCollection.getPublishedCollection() != null) {
ActionCollectionDTO actionCollectionDTO = actionCollection.getPublishedCollection();
- actionCollectionDTO.setPageId(pageIdToNameMap.get(actionCollectionDTO.getPageId() + PublishType.PUBLISHED));
+ actionCollectionDTO.setPageId(pageIdToNameMap.get(actionCollectionDTO.getPageId() + VIEW));
actionCollectionDTO.setPluginId(pluginMap.get(actionCollectionDTO.getPluginId()));
if (!collectionIdToNameMap.containsValue(actionCollection.getId())) {
@@ -370,7 +307,7 @@ public Mono<ApplicationJson> exportApplicationById(String applicationId, Seriali
actionCollection.setId(updatedCollectionId);
}
}
-
+ actionCollection.sanitiseToExportDBObject();
return actionCollection;
})
.collectList()
@@ -401,7 +338,7 @@ public Mono<ApplicationJson> exportApplicationById(String applicationId, Seriali
// Set unique id for action
if (newAction.getUnpublishedAction() != null) {
ActionDTO actionDTO = newAction.getUnpublishedAction();
- actionDTO.setPageId(pageIdToNameMap.get(actionDTO.getPageId() + PublishType.UNPUBLISHED));
+ actionDTO.setPageId(pageIdToNameMap.get(actionDTO.getPageId() + EDIT));
if (!StringUtils.isEmpty(actionDTO.getCollectionId())
&& collectionIdToNameMap.containsKey(actionDTO.getCollectionId())) {
@@ -414,7 +351,7 @@ public Mono<ApplicationJson> exportApplicationById(String applicationId, Seriali
}
if (newAction.getPublishedAction() != null) {
ActionDTO actionDTO = newAction.getPublishedAction();
- actionDTO.setPageId(pageIdToNameMap.get(actionDTO.getPageId() + PublishType.PUBLISHED));
+ actionDTO.setPageId(pageIdToNameMap.get(actionDTO.getPageId() + VIEW));
if (!StringUtils.isEmpty(actionDTO.getCollectionId())
&& collectionIdToNameMap.containsKey(actionDTO.getCollectionId())) {
@@ -427,96 +364,43 @@ public Mono<ApplicationJson> exportApplicationById(String applicationId, Seriali
newAction.setId(updatedActionId);
}
}
+ newAction.sanitiseToExportDBObject();
return newAction;
})
.collectList()
.map(actionList -> {
applicationJson.setActionList(actionList);
- Map<String, InvisibleActionFields> invisibleActionFieldsMap = new HashMap<>();
- applicationJson.setInvisibleActionFields(invisibleActionFieldsMap);
- actionList.forEach(newAction -> {
- final InvisibleActionFields invisibleActionFields = new InvisibleActionFields();
-
- if (newAction.getUnpublishedAction() != null) {
- invisibleActionFields.setUnpublishedUserSetOnLoad(newAction.getUnpublishedAction().getUserSetOnLoad());
- }
- if (newAction.getPublishedAction() != null) {
- invisibleActionFields.setPublishedUserSetOnLoad(newAction.getPublishedAction().getUserSetOnLoad());
- }
-
- if (invisibleActionFields.getPublishedUserSetOnLoad() != null || invisibleActionFields.getUnpublishedUserSetOnLoad() != null) {
- invisibleActionFieldsMap.put(newAction.getId(), invisibleActionFields);
- }
- });
-
// This is where we're removing global datasources that are unused in this application
applicationJson
.getDatasourceList()
.removeIf(datasource -> !dbNamesUsedInActions.contains(datasource.getName()));
// Save decrypted fields for datasources for internally used sample apps and templates only
- if(Boolean.TRUE.equals(application.getExportWithConfiguration())) {
+ // when serialising for file sharing
+ if(Boolean.TRUE.equals(application.getExportWithConfiguration()) && SerialiseApplicationObjective.SHARE.equals(serialiseFor)) {
// Save decrypted fields for datasources
Map<String, DecryptedSensitiveFields> decryptedFields = new HashMap<>();
applicationJson.getDatasourceList().forEach(datasource -> {
decryptedFields.put(datasource.getName(), getDecryptedFields(datasource));
- datasource.setId(null);
- datasource.setWorkspaceId(null);
- datasource.setPluginId(pluginMap.get(datasource.getPluginId()));
- datasource.setStructure(null);
+ datasource.sanitiseToExportResource(pluginMap);
});
applicationJson.setDecryptedFields(decryptedFields);
} else {
applicationJson.getDatasourceList().forEach(datasource -> {
- datasource.setId(null);
- datasource.setWorkspaceId(null);
- datasource.setPluginId(pluginMap.get(datasource.getPluginId()));
- datasource.setStructure(null);
// Remove the datasourceConfiguration object as user will configure it once imported to other instance
datasource.setDatasourceConfiguration(null);
+ datasource.sanitiseToExportResource(pluginMap);
});
}
// Update ids for layoutOnLoadAction
for (NewPage newPage : applicationJson.getPageList()) {
- if (!CollectionUtils.isEmpty(newPage.getUnpublishedPage().getLayouts())) {
-
- newPage.getUnpublishedPage().getLayouts().forEach(layout -> {
- if (layout.getLayoutOnLoadActions() != null) {
- layout.getLayoutOnLoadActions().forEach(onLoadAction -> onLoadAction
- .forEach(actionDTO -> {
- if (actionIdToNameMap.containsKey(actionDTO.getId())) {
- actionDTO.setId(actionIdToNameMap.get(actionDTO.getId()));
- }
- if (collectionIdToNameMap.containsKey(actionDTO.getCollectionId())) {
- actionDTO.setCollectionId(collectionIdToNameMap.get(actionDTO.getCollectionId()));
- }
- })
- );
- }
- });
- }
-
- if (newPage.getPublishedPage() != null
- && !CollectionUtils.isEmpty(newPage.getPublishedPage().getLayouts())) {
-
- newPage.getPublishedPage().getLayouts().forEach(layout -> {
- if (layout.getLayoutOnLoadActions() != null) {
- layout.getLayoutOnLoadActions().forEach(onLoadAction -> onLoadAction
- .forEach(actionDTO -> {
- if (actionIdToNameMap.containsKey(actionDTO.getId())) {
- actionDTO.setId(actionIdToNameMap.get(actionDTO.getId()));
- }
- if (collectionIdToNameMap.containsKey(actionDTO.getCollectionId())) {
- actionDTO.setCollectionId(collectionIdToNameMap.get(actionDTO.getCollectionId()));
- }
- })
- );
- }
- });
- }
+ updateIdsForLayoutOnLoadAction(newPage.getUnpublishedPage(), actionIdToNameMap, collectionIdToNameMap);
+ updateIdsForLayoutOnLoadAction(newPage.getPublishedPage(), actionIdToNameMap, collectionIdToNameMap);
}
+
+ application.exportApplicationPages(pageIdToNameMap);
// Disable exporting the application with datasource config once imported in destination instance
application.setExportWithConfiguration(null);
return applicationJson;
@@ -543,6 +427,53 @@ public Mono<ApplicationJson> exportApplicationById(String applicationId, String
.flatMap(branchedAppId -> exportApplicationById(branchedAppId, SerialiseApplicationObjective.SHARE));
}
+ private void updateIdsForLayoutOnLoadAction(PageDTO page,
+ Map<String, String> actionIdToNameMap,
+ Map<String, String> collectionIdToNameMap) {
+
+ if (page != null && !CollectionUtils.isEmpty(page.getLayouts())) {
+ for (Layout layout : page.getLayouts()) {
+ if (!CollectionUtils.isEmpty(layout.getLayoutOnLoadActions())) {
+ layout.getLayoutOnLoadActions().forEach(onLoadAction -> onLoadAction
+ .forEach(actionDTO -> {
+ if (actionIdToNameMap.containsKey(actionDTO.getId())) {
+ actionDTO.setId(actionIdToNameMap.get(actionDTO.getId()));
+ }
+ if (collectionIdToNameMap.containsKey(actionDTO.getCollectionId())) {
+ actionDTO.setCollectionId(collectionIdToNameMap.get(actionDTO.getCollectionId()));
+ }
+ })
+ );
+ }
+ }
+ }
+ }
+
+ public Mono<ExportFileDTO> getApplicationFile(String applicationId, String branchName) {
+ return this.exportApplicationById(applicationId, branchName)
+ .map(applicationJson -> {
+ Gson gson = new GsonBuilder()
+ .registerTypeAdapter(Instant.class, new GsonISOStringToInstantConverter())
+ .create();
+
+ String stringifiedFile = gson.toJson(applicationJson);
+ String applicationName = applicationJson.getExportedApplication().getName();
+ Object jsonObject = gson.fromJson(stringifiedFile, Object.class);
+ HttpHeaders responseHeaders = new HttpHeaders();
+ ContentDisposition contentDisposition = ContentDisposition
+ .builder("attachment")
+ .filename(applicationName + ".json", StandardCharsets.UTF_8)
+ .build();
+ responseHeaders.setContentDisposition(contentDisposition);
+ responseHeaders.setContentType(MediaType.APPLICATION_JSON);
+
+ ExportFileDTO exportFileDTO = new ExportFileDTO();
+ exportFileDTO.setApplicationResource(jsonObject);
+ exportFileDTO.setHttpHeaders(responseHeaders);
+ return exportFileDTO;
+ });
+ }
+
/**
* This function will take the Json filepart and saves the application in workspace
*
@@ -670,10 +601,10 @@ private String validateApplicationJson(ApplicationJson importedDoc) {
* @return Updated application
*/
private Mono<Application> importApplicationInWorkspace(String workspaceId,
- ApplicationJson applicationJson,
- String applicationId,
- String branchName,
- boolean appendToApp) {
+ ApplicationJson applicationJson,
+ String applicationId,
+ String branchName,
+ boolean appendToApp) {
/*
1. Migrate resource to latest schema
2. Fetch workspace by id
@@ -683,9 +614,6 @@ private Mono<Application> importApplicationInWorkspace(String workspaceId,
6. Extract and save pages in the application
7. Extract and save actions in the application
*/
- // Start the stopwatch to log the execution time
- Stopwatch processStopwatch = new Stopwatch("Import application");
-
ApplicationJson importedDoc = JsonSchemaMigration.migrateApplicationToLatestSchema(applicationJson);
@@ -724,6 +652,12 @@ private Mono<Application> importApplicationInWorkspace(String workspaceId,
importedApplication.setApplicationVersion(ApplicationVersion.EARLIEST_VERSION);
}
+ final List<ApplicationPage> publishedPages = importedApplication.getPublishedPages();
+ importedApplication.setViewMode(false);
+ final List<ApplicationPage> unpublishedPages = importedApplication.getPages();
+
+ importedApplication.setPages(null);
+ importedApplication.setPublishedPages(null);
// Start the stopwatch to log the execution time
Stopwatch stopwatch = new Stopwatch(AnalyticsEvents.IMPORT_APPLICATION.getEventName());
Mono<Application> importedApplicationMono = pluginRepository.findAll()
@@ -777,7 +711,7 @@ private Mono<Application> importApplicationInWorkspace(String workspaceId,
// for this instance
datasource.setDatasourceConfiguration(null);
datasource.setPluginId(null);
- AppsmithBeanUtils.copyNestedNonNullProperties(datasource, existingDatasource);
+ copyNestedNonNullProperties(datasource, existingDatasource);
existingDatasource.setStructure(null);
// Don't update the datasource configuration for already available datasources
existingDatasource.setDatasourceConfiguration(null);
@@ -833,7 +767,11 @@ private Mono<Application> importApplicationInWorkspace(String workspaceId,
applicationId))
)
.flatMap(existingApplication -> {
- if(StringUtils.isEmpty(branchName)) {
+ if(appendToApp) {
+ // When we are appending the pages to the existing application
+ // e.g. import template we are only importing this in unpublished
+ // version. At the same time we want to keep the existing page ref
+ unpublishedPages.addAll(existingApplication.getPages());
return Mono.just(existingApplication);
}
importedApplication.setId(existingApplication.getId());
@@ -841,7 +779,7 @@ private Mono<Application> importApplicationInWorkspace(String workspaceId,
// The isPublic flag has a default value as false and this would be confusing to user
// when it is reset to false during importing where the application already is present in DB
importedApplication.setIsPublic(null);
- AppsmithBeanUtils.copyNestedNonNullProperties(importedApplication, existingApplication);
+ copyNestedNonNullProperties(importedApplication, existingApplication);
// We are expecting the changes present in DB are committed to git directory
// so that these won't be lost when we are pulling changes from remote and
// rehydrate the application. We are now rehydrating the application with/without
@@ -896,8 +834,6 @@ private Mono<Application> importApplicationInWorkspace(String workspaceId,
Flux<NewPage> importNewPageFlux = importAndSavePages(
importedNewPageList,
savedApp,
- importedDoc.getPublishedLayoutmongoEscapedWidgets(),
- importedDoc.getUnpublishedLayoutmongoEscapedWidgets(),
branchName,
existingPagesMono
);
@@ -916,6 +852,10 @@ private Mono<Application> importApplicationInWorkspace(String workspaceId,
if(!newPageName.equals(oldPageName)) {
renamePageInActions(importedNewActionList, oldPageName, newPageName);
renamePageInActionCollections(importedActionCollectionList, oldPageName, newPageName);
+ unpublishedPages.stream()
+ .filter(applicationPage -> oldPageName.equals(applicationPage.getId()))
+ .findAny()
+ .ifPresent(applicationPage -> applicationPage.setId(newPageName));
}
return newPage;
})
@@ -938,15 +878,59 @@ private Mono<Application> importApplicationInWorkspace(String workspaceId,
return importedNewPagesMono
.collectList()
.map(newPageList -> {
- return reorderPages(applicationJson, importedDoc, pageNameMap);
+ Map<ResourceModes, List<ApplicationPage>> applicationPages = Map.of(
+ EDIT, unpublishedPages,
+ VIEW, publishedPages
+ );
+ for(ApplicationPage applicationPage : unpublishedPages) {
+ NewPage newPage = pageNameMap.get(applicationPage.getId());
+ if (newPage == null) {
+ if (appendToApp) {
+ // Don't remove the page reference if doing the partial import and appending
+ // to the existing application
+ continue;
+ }
+ log.debug("Unable to find the page during import for appId {}, with name {}", applicationId, applicationPage.getId());
+ unpublishedPages.remove(applicationPage);
+ } else {
+ applicationPage.setId(newPage.getId());
+ applicationPage.setDefaultPageId(newPage.getDefaultResources().getPageId());
+ // Keep the existing page as the default one
+ if (appendToApp) {
+ applicationPage.setIsDefault(false);
+ }
+ }
+ }
+
+ for(ApplicationPage applicationPage : publishedPages) {
+ NewPage newPage = pageNameMap.get(applicationPage.getId());
+ if (newPage == null) {
+ log.debug("Unable to find the page during import for appId {}, with name {}", applicationId, applicationPage.getId());
+ if (!appendToApp) {
+ publishedPages.remove(applicationPage);
+ }
+ } else {
+ applicationPage.setId(newPage.getId());
+ applicationPage.setDefaultPageId(newPage.getDefaultResources().getPageId());
+ if (appendToApp) {
+ applicationPage.setIsDefault(false);
+ }
+ }
+ }
+
+ return applicationPages;
})
.flatMap(applicationPages -> {
+ // During partial import/appending to the existing application keep the resources
+ // attached to the application:
+ // Delete the invalid resources (which are not the part of applicationJsonDTO) in
+ // the git flow only
if (!StringUtils.isEmpty(applicationId) && !appendToApp) {
- Set<String> validPageIds = applicationPages.get(PublishType.UNPUBLISHED).stream()
+ Set<String> validPageIds = applicationPages.get(EDIT).stream()
.map(ApplicationPage::getId)
.collect(Collectors.toSet());
- validPageIds.addAll(applicationPages.get(PublishType.PUBLISHED)
+ validPageIds.addAll(applicationPages.get(VIEW)
.stream()
.map(ApplicationPage::getId)
.collect(Collectors.toSet()));
@@ -978,20 +962,10 @@ private Mono<Application> importApplicationInWorkspace(String workspaceId,
});
})
.flatMap(applicationPageMap -> {
- // set it based on the order for published and unublished pages
- if(appendToApp) {
- if(importedApplication.getPages() == null) {
- importedApplication.setPages(new ArrayList<>());
- }
- // new pages should not be a default one, existing default page should not change
- applicationPageMap.get(PublishType.UNPUBLISHED)
- .forEach(applicationPage -> applicationPage.setIsDefault(false));
- // append the new pages so that existing pages not lost when we update later
- importedApplication.getPages().addAll(applicationPageMap.get(PublishType.UNPUBLISHED));
- } else {
- importedApplication.setPages(applicationPageMap.get(PublishType.UNPUBLISHED));
- importedApplication.setPublishedPages(applicationPageMap.get(PublishType.PUBLISHED));
- }
+
+ // Set page sequence based on the order for published and unpublished pages
+ importedApplication.setPages(applicationPageMap.get(EDIT));
+ importedApplication.setPublishedPages(applicationPageMap.get(VIEW));
// This will be non-empty for GIT sync
return newActionRepository.findByApplicationId(importedApplication.getId())
.collectList();
@@ -1007,13 +981,16 @@ private Mono<Application> importApplicationInWorkspace(String workspaceId,
pluginMap,
datasourceMap,
unpublishedCollectionIdToActionIdsMap,
- publishedCollectionIdToActionIdsMap,
- applicationJson.getInvisibleActionFields()
+ publishedCollectionIdToActionIdsMap
)
.map(NewAction::getId)
.collectList()
.flatMap(savedActionIds -> {
// Updating the existing application for git-sync
+ // During partial import/appending to the existing application keep the resources
+ // attached to the application:
+ // Delete the invalid resources (which are not the part of applicationJsonDTO) in
+ // the git flow only
if (!StringUtils.isEmpty(applicationId) && !appendToApp) {
// Remove unwanted actions
Set<String> invalidActionIds = new HashSet<>();
@@ -1069,6 +1046,10 @@ private Mono<Application> importApplicationInWorkspace(String workspaceId,
.collectList()
.flatMap(ignore -> {
// Updating the existing application for git-sync
+ // During partial import/appending to the existing application keep the resources
+ // attached to the application:
+ // Delete the invalid resources (which are not the part of applicationJsonDTO) in
+ // the git flow only
if (!StringUtils.isEmpty(applicationId) && !appendToApp) {
// Remove unwanted action collections
Set<String> invalidCollectionIds = new HashSet<>();
@@ -1156,72 +1137,6 @@ private void renamePageInActionCollections(List<ActionCollection> actionCollecti
}
}
- private Map<PublishType, List<ApplicationPage>> reorderPages(ApplicationJson applicationJson, ApplicationJson importedDoc, Map<String, NewPage> pageNameMap) {
- Map<PublishType, List<ApplicationPage>> applicationPages = Map.of(
- PublishType.UNPUBLISHED, new ArrayList<>(),
- PublishType.PUBLISHED, new ArrayList<>()
- );
- // Reorder the pages based on edit mode page sequence
- List<String> pageOrderList;
- if(!CollectionUtils.isEmpty(applicationJson.getPageOrder())) {
- pageOrderList = applicationJson.getPageOrder();
- } else {
- pageOrderList = pageNameMap.values()
- .stream()
- .map(newPage -> newPage.getUnpublishedPage().getName())
- .collect(Collectors.toList());
- }
- for(String pageName : pageOrderList) {
- NewPage newPage = pageNameMap.get(pageName);
- ApplicationPage unpublishedAppPage = new ApplicationPage();
- if (newPage.getUnpublishedPage() != null && newPage.getUnpublishedPage().getName() != null) {
- unpublishedAppPage.setIsDefault(
- StringUtils.equals(
- newPage.getUnpublishedPage().getName(), importedDoc.getUnpublishedDefaultPageName()
- )
- );
- unpublishedAppPage.setId(newPage.getId());
- if (newPage.getDefaultResources() != null) {
- unpublishedAppPage.setDefaultPageId(newPage.getDefaultResources().getPageId());
- }
- }
- if (unpublishedAppPage.getId() != null && newPage.getUnpublishedPage().getDeletedAt() == null) {
- applicationPages.get(PublishType.UNPUBLISHED).add(unpublishedAppPage);
- }
- }
-
- // Reorder the pages based on view mode page sequence
- List<String> publishedPageOrderList;
- if(!CollectionUtils.isEmpty(applicationJson.getPublishedPageOrder())) {
- publishedPageOrderList = applicationJson.getPublishedPageOrder();
- } else {
- publishedPageOrderList = pageNameMap.values()
- .stream()
- .filter(newPage -> Optional.ofNullable(newPage.getPublishedPage()).isPresent())
- .map(newPage -> newPage.getPublishedPage().getName()).collect(Collectors.toList());
- }
- for(String pageName : publishedPageOrderList) {
- NewPage newPage = pageNameMap.get(pageName);
- ApplicationPage publishedAppPage = new ApplicationPage();
- if (newPage.getPublishedPage() != null && newPage.getPublishedPage().getName() != null) {
- publishedAppPage.setIsDefault(
- StringUtils.equals(
- newPage.getPublishedPage().getName(), importedDoc.getPublishedDefaultPageName()
- )
- );
- publishedAppPage.setId(newPage.getId());
- if (newPage.getDefaultResources() != null) {
- publishedAppPage.setDefaultPageId(newPage.getDefaultResources().getPageId());
- }
- }
-
- if (publishedAppPage.getId() != null && newPage.getPublishedPage().getDeletedAt() == null) {
- applicationPages.get(PublishType.PUBLISHED).add(publishedAppPage);
- }
- }
- return applicationPages;
- }
-
/**
* This function will respond with unique suffixed number for the entity to avoid duplicate names
*
@@ -1250,48 +1165,35 @@ private Mono<String> getUniqueSuffixForDuplicateNameEntity(BaseDomain sourceEnti
*
* @param pages pagelist extracted from the imported JSON file
* @param application saved application where pages needs to be added
- * @param publishedMongoEscapedWidget widget list those needs to be escaped for published layout
- * @param unpublishedMongoEscapedWidget widget list those needs to be escaped for unpublished layout
* @param branchName to which branch pages should be imported if application is connected to git
* @param existingPages existing pages in DB if the application is connected to git
* @return flux of saved pages in DB
*/
private Flux<NewPage> importAndSavePages(List<NewPage> pages,
Application application,
- Map<String, Set<String>> publishedMongoEscapedWidget,
- Map<String, Set<String>> unpublishedMongoEscapedWidget,
String branchName,
Mono<List<NewPage>> existingPages) {
Map<String, String> oldToNewLayoutIds = new HashMap<>();
pages.forEach(newPage -> {
- if (newPage.getDefaultResources() != null) {
- newPage.getDefaultResources().setBranchName(branchName);
- }
newPage.setApplicationId(application.getId());
if (newPage.getUnpublishedPage() != null) {
applicationPageService.generateAndSetPagePolicies(application, newPage.getUnpublishedPage());
newPage.setPolicies(newPage.getUnpublishedPage().getPolicies());
- if (unpublishedMongoEscapedWidget != null) {
- newPage.getUnpublishedPage().getLayouts().forEach(layout -> {
- String layoutId = new ObjectId().toString();
- oldToNewLayoutIds.put(layout.getId(), layoutId);
- layout.setMongoEscapedWidgetNames(unpublishedMongoEscapedWidget.get(layout.getId()));
- layout.setId(layoutId);
- });
- }
+ newPage.getUnpublishedPage().getLayouts().forEach(layout -> {
+ String layoutId = new ObjectId().toString();
+ oldToNewLayoutIds.put(layout.getId(), layoutId);
+ layout.setId(layoutId);
+ });
}
if (newPage.getPublishedPage() != null) {
applicationPageService.generateAndSetPagePolicies(application, newPage.getPublishedPage());
- if (publishedMongoEscapedWidget != null) {
- newPage.getPublishedPage().getLayouts().forEach(layout -> {
- String layoutId = oldToNewLayoutIds.containsKey(layout.getId())
- ? oldToNewLayoutIds.get(layout.getId()) : new ObjectId().toString();
- layout.setMongoEscapedWidgetNames(publishedMongoEscapedWidget.get(layout.getId()));
- layout.setId(layoutId);
- });
- }
+ newPage.getPublishedPage().getLayouts().forEach(layout -> {
+ String layoutId = oldToNewLayoutIds.containsKey(layout.getId())
+ ? oldToNewLayoutIds.get(layout.getId()) : new ObjectId().toString();
+ layout.setId(layoutId);
+ });
}
});
@@ -1309,7 +1211,9 @@ private Flux<NewPage> importAndSavePages(List<NewPage> pages,
if (newPage.getGitSyncId() != null && savedPagesGitIdToPageMap.containsKey(newPage.getGitSyncId())) {
//Since the resource is already present in DB, just update resource
NewPage existingPage = savedPagesGitIdToPageMap.get(newPage.getGitSyncId());
- AppsmithBeanUtils.copyNestedNonNullProperties(newPage, existingPage);
+ copyNestedNonNullProperties(newPage, existingPage);
+ // Update branchName
+ existingPage.getDefaultResources().setBranchName(branchName);
// Recover the deleted state present in DB from imported page
existingPage.getUnpublishedPage().setDeletedAt(newPage.getUnpublishedPage().getDeletedAt());
existingPage.setDeletedAt(newPage.getDeletedAt());
@@ -1376,8 +1280,7 @@ private Flux<NewAction> importAndSaveAction(List<NewAction> importedNewActionLis
Map<String, String> pluginMap,
Map<String, String> datasourceMap,
Map<String, Map<String, String>> unpublishedCollectionIdToActionIdsMap,
- Map<String, Map<String, String>> publishedCollectionIdToActionIdsMap,
- Map<String, InvisibleActionFields> invisibleActionFieldsMap) {
+ Map<String, Map<String, String>> publishedCollectionIdToActionIdsMap) {
Map<String, NewAction> savedActionsGitIdToActionsMap = new HashMap<>();
final String workspaceId = importedApplication.getWorkspaceId();
@@ -1397,26 +1300,16 @@ private Flux<NewAction> importAndSaveAction(List<NewAction> importedNewActionLis
ActionDTO unpublishedAction = newAction.getUnpublishedAction();
ActionDTO publishedAction = newAction.getPublishedAction();
- if (newAction.getDefaultResources() != null) {
- newAction.getDefaultResources().setBranchName(branchName);
- }
-
// If pageId is missing in the actionDTO create a fallback pageId
final String fallbackParentPageId = unpublishedAction.getPageId();
if (unpublishedAction.getValidName() != null) {
- if (invisibleActionFieldsMap != null) {
- unpublishedAction.setUserSetOnLoad(invisibleActionFieldsMap.get(newAction.getId()).getUnpublishedUserSetOnLoad());
- }
unpublishedAction.setId(newAction.getId());
parentPage = updatePageInAction(unpublishedAction, pageNameMap, actionIdMap);
sanitizeDatasourceInActionDTO(unpublishedAction, datasourceMap, pluginMap, workspaceId, false);
}
if (publishedAction != null && publishedAction.getValidName() != null) {
- if (invisibleActionFieldsMap != null) {
- publishedAction.setUserSetOnLoad(invisibleActionFieldsMap.get(newAction.getId()).getPublishedUserSetOnLoad());
- }
publishedAction.setId(newAction.getId());
if (StringUtils.isEmpty(publishedAction.getPageId())) {
publishedAction.setPageId(fallbackParentPageId);
@@ -1438,7 +1331,9 @@ private Flux<NewAction> importAndSaveAction(List<NewAction> importedNewActionLis
//Since the resource is already present in DB, just update resource
NewAction existingAction = savedActionsGitIdToActionsMap.get(newAction.getGitSyncId());
- AppsmithBeanUtils.copyNestedNonNullProperties(newAction, existingAction);
+ copyNestedNonNullProperties(newAction, existingAction);
+ // Update branchName
+ existingAction.getDefaultResources().setBranchName(branchName);
// Recover the deleted state present in DB from imported action
existingAction.getUnpublishedAction().setDeletedAt(newAction.getUnpublishedAction().getDeletedAt());
existingAction.setDeletedAt(newAction.getDeletedAt());
@@ -1547,9 +1442,6 @@ private Flux<Tuple2<String, ActionCollection>> importAndSaveActionCollection(
.filter(actionCollection -> actionCollection.getUnpublishedCollection() != null
&& !StringUtils.isEmpty(actionCollection.getUnpublishedCollection().getPageId()))
.flatMap(actionCollection -> {
- if (actionCollection.getDefaultResources() != null) {
- actionCollection.getDefaultResources().setBranchName(branchName);
- }
final String importedActionCollectionId = actionCollection.getId();
NewPage parentPage = new NewPage();
final ActionCollectionDTO unpublishedCollection = actionCollection.getUnpublishedCollection();
@@ -1590,7 +1482,9 @@ private Flux<Tuple2<String, ActionCollection>> importAndSaveActionCollection(
//Since the resource is already present in DB, just update resource
ActionCollection existingActionCollection = savedActionCollectionGitIdToCollectionsMap.get(actionCollection.getGitSyncId());
- AppsmithBeanUtils.copyNestedNonNullProperties(actionCollection, existingActionCollection);
+ copyNestedNonNullProperties(actionCollection, existingActionCollection);
+ // Update branchName
+ existingActionCollection.getDefaultResources().setBranchName(branchName);
// Recover the deleted state present in DB from imported actionCollection
existingActionCollection.getUnpublishedCollection().setDeletedAt(actionCollection.getUnpublishedCollection().getDeletedAt());
existingActionCollection.setDeletedAt(actionCollection.getDeletedAt());
@@ -1924,7 +1818,7 @@ private Mono<Datasource> createUniqueDatasourceIfNotPresent(Flux<Datasource> exi
final DatasourceConfiguration datasourceConfig = datasource.getDatasourceConfiguration();
AuthenticationResponse authResponse = new AuthenticationResponse();
if (datasourceConfig != null && datasourceConfig.getAuthentication() != null) {
- AppsmithBeanUtils.copyNestedNonNullProperties(
+ copyNestedNonNullProperties(
datasourceConfig.getAuthentication().getAuthenticationResponse(), authResponse);
datasourceConfig.getAuthentication().setAuthenticationResponse(null);
datasourceConfig.getAuthentication().setAuthenticationType(null);
@@ -1990,30 +1884,9 @@ private Datasource updateAuthenticationDTO(Datasource datasource, DecryptedSensi
return datasource;
}
- /**
- * Removes internal fields e.g. database ID from the provided Theme object.
- * @param srcTheme Theme object from DB that'll be exported
- * @return Theme DTO with null or empty value in internal fields
- */
- private Theme exportTheme(Theme srcTheme) {
- srcTheme.setId(null);
- if(srcTheme.isSystemTheme()) {
- // for system theme, we only need theme name and isSystemTheme properties so set null to others
- srcTheme.setProperties(null);
- srcTheme.setConfig(null);
- srcTheme.setStylesheet(null);
- }
- // set null to base domain properties also
- srcTheme.setCreatedAt(null);
- srcTheme.setCreatedBy(null);
- srcTheme.setUpdatedAt(null);
- srcTheme.setModifiedBy(null);
- srcTheme.setUserPermissions(null);
- return srcTheme;
- }
-
private Mono<Application> importThemes(Application application, ApplicationJson importedApplicationJson, boolean appendToApp) {
- if(appendToApp) { // appending to existing app, theme should not change
+ if(appendToApp) {
+ // appending to existing app, theme should not change
return Mono.just(application);
}
return themeService.importThemesToApplication(application, importedApplicationJson);
@@ -2072,25 +1945,6 @@ public Mono<List<Datasource>> findDatasourceByApplicationId(String applicationId
});
}
- private void removeUnwantedFieldsFromApplicationDuringExport(Application application) {
- application.setWorkspaceId(null);
- application.setPages(null);
- application.setPublishedPages(null);
- application.setModifiedBy(null);
- application.setUpdatedAt(null);
- application.setLastDeployedAt(null);
- application.setLastEditedAt(null);
- application.setUpdatedAt(null);
- application.setGitApplicationMetadata(null);
- application.setPolicies(null);
- application.setUserPermissions(null);
- application.setEditModeThemeId(null);
- application.setPublishedModeThemeId(null);
- application.setClientSchemaVersion(null);
- application.setServerSchemaVersion(null);
- application.setIsManualUpdate(false);
- }
-
/**
*
* @param applicationId default ID of the application where this ApplicationJSON is going to get merged with
@@ -2101,7 +1955,11 @@ private void removeUnwantedFieldsFromApplicationDuringExport(Application applica
* @return Merged Application
*/
@Override
- public Mono<Application> mergeApplicationJsonWithApplication(String workspaceId, String applicationId, String branchName, ApplicationJson applicationJson, List<String> pagesToImport) {
+ public Mono<Application> mergeApplicationJsonWithApplication(String workspaceId,
+ String applicationId,
+ String branchName,
+ ApplicationJson applicationJson,
+ List<String> pagesToImport) {
// Update the application JSON to prepare it for merging inside an existing application
if(applicationJson.getExportedApplication() != null) {
// setting some properties to null so that target application is not updated by these properties
@@ -2114,12 +1972,30 @@ public Mono<Application> mergeApplicationJsonWithApplication(String workspaceId,
// need to remove git sync id. Also filter pages if pageToImport is not empty
if(applicationJson.getPageList() != null) {
+ List<ApplicationPage> applicationPageList = new ArrayList<>(applicationJson.getPageList().size());
+ List<String> pageNames = new ArrayList<>(applicationJson.getPageList().size());
List<NewPage> importedNewPageList = applicationJson.getPageList().stream()
.filter(newPage -> newPage.getUnpublishedPage() != null &&
(CollectionUtils.isEmpty(pagesToImport) ||
pagesToImport.contains(newPage.getUnpublishedPage().getName()))
- ).collect(Collectors.toList());
+ )
+ .peek(newPage -> {
+ ApplicationPage applicationPage = new ApplicationPage();
+ applicationPage.setId(newPage.getUnpublishedPage().getName());
+ applicationPage.setIsDefault(false);
+ applicationPageList.add(applicationPage);
+ pageNames.add(applicationPage.getId());
+ })
+ .peek(newPage -> newPage.setGitSyncId(null))
+ .collect(Collectors.toList());
applicationJson.setPageList(importedNewPageList);
+// if (!CollectionUtils.isEmpty(applicationJson.getExportedApplication().getPages())) {
+// applicationJson.getExportedApplication().getPages().addAll(applicationPageList);
+// } else {
+// // If the pages are not emebedded inside the application object we have to add these to pageOrder as
+// // JSONSchema migration only works with pageOrder
+// applicationJson.getPageOrder().addAll(pageNames);
+// }
}
if(applicationJson.getActionList() != null) {
List<NewAction> importedNewActionList = applicationJson.getActionList().stream()
@@ -2157,11 +2033,6 @@ private Mono<Map<String, String>> updateNewPagesBeforeMerge(Mono<List<NewPage>>
// modify each new page
for (NewPage newPage : newPagesList) {
newPage.setPublishedPage(null); // we'll not merge published pages so removing this
- /* Need to remove gitSyncId from imported new pages.
- * Same template or page can be merged with same application multiple times.
- * As gitSyncId will be same for each import, new page will not be created
- */
- newPage.setGitSyncId(null);
// let's check if page name conflicts, rename in that case
String oldPageName = newPage.getUnpublishedPage().getName(),
diff --git a/app/server/appsmith-server/src/test/java/com/appsmith/server/converters/GsonISOStringToInstantConverterTest.java b/app/server/appsmith-server/src/test/java/com/appsmith/server/converters/GsonISOStringToInstantConverterTest.java
index 051335f097a6..b23ec091454e 100644
--- a/app/server/appsmith-server/src/test/java/com/appsmith/server/converters/GsonISOStringToInstantConverterTest.java
+++ b/app/server/appsmith-server/src/test/java/com/appsmith/server/converters/GsonISOStringToInstantConverterTest.java
@@ -1,6 +1,7 @@
package com.appsmith.server.converters;
+import com.appsmith.external.converters.GsonISOStringToInstantConverter;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
diff --git a/app/server/appsmith-server/src/test/java/com/appsmith/server/git/FileFormatMigrationTests.java b/app/server/appsmith-server/src/test/java/com/appsmith/server/git/FileFormatMigrationTests.java
index ae1152918e87..eefd775e00b0 100644
--- a/app/server/appsmith-server/src/test/java/com/appsmith/server/git/FileFormatMigrationTests.java
+++ b/app/server/appsmith-server/src/test/java/com/appsmith/server/git/FileFormatMigrationTests.java
@@ -72,7 +72,7 @@ public void extractFiles_whenFilesInRepoWithFormatVersion1_success() {
assertThat(actions.size()).isEqualTo(1);
assertThat(actions.get("Query1_Page1.json").getAsJsonObject().get("queryKey").getAsString()).isEqualTo("queryValue");
- JsonObject actionCollections = gson.fromJson(gson.toJson(applicationGitReference.getActionsCollections()), JsonObject.class);
+ JsonObject actionCollections = gson.fromJson(gson.toJson(applicationGitReference.getActionCollections()), JsonObject.class);
assertThat(actionCollections.size()).isEqualTo(1);
assertThat(actionCollections.get("JSObject1_Page1.json").getAsJsonObject().get("jsobjectKey").getAsString()).isEqualTo("jsobjectValue");
@@ -108,7 +108,7 @@ public void extractFiles_whenFilesInRepoWithFormatVersion2_success() {
assertThat(actions.size()).isEqualTo(1);
assertThat(actions.get("Query1.jsonPage1").getAsJsonObject().get("queryKey").getAsString()).isEqualTo("queryValue");
- JsonObject actionCollections = gson.fromJson(gson.toJson(applicationGitReference.getActionsCollections()), JsonObject.class);
+ JsonObject actionCollections = gson.fromJson(gson.toJson(applicationGitReference.getActionCollections()), JsonObject.class);
assertThat(actionCollections.size()).isEqualTo(1);
assertThat(actionCollections.get("JSObject1.jsonPage1").getAsJsonObject().get("jsobjectKey").getAsString()).isEqualTo("jsobjectValue");
diff --git a/app/server/appsmith-server/src/test/java/com/appsmith/server/helpers/CompareDslActionDTOTest.java b/app/server/appsmith-server/src/test/java/com/appsmith/server/helpers/CompareDslActionDTOTest.java
index 38bd381f048b..ae11a7c9170c 100644
--- a/app/server/appsmith-server/src/test/java/com/appsmith/server/helpers/CompareDslActionDTOTest.java
+++ b/app/server/appsmith-server/src/test/java/com/appsmith/server/helpers/CompareDslActionDTOTest.java
@@ -12,65 +12,44 @@
public class CompareDslActionDTOTest {
- List<String> sortedActionIds = new LinkedList<>();
- TreeSet<DslActionDTO> orderedActionSet = new TreeSet<>(new CompareDslActionDTO());
@Test
- public void convert_whenNullActionIds_returnsSetInInputOrder() {
- DslActionDTO action1 = new DslActionDTO();
- DslActionDTO action2 = new DslActionDTO();
- action1.setName("testName");
- action2.setName("testName2");
- Set<DslActionDTO> unorderedSet = Set.of(action1, action2);
- orderedActionSet.addAll(unorderedSet);
+ public void convert_whenEmptyActionIdSet_elementsDoesNotMaintainOrder() {
+ TreeSet<DslActionDTO> orderedActionSet = new TreeSet<>(new CompareDslActionDTO());
List<String> sortedActionNames = new LinkedList<>();
- for (DslActionDTO dslActionDTO : orderedActionSet) {
- sortedActionNames.add(dslActionDTO.getName());
- }
- List<String> actionNames = new LinkedList<>();
- for (DslActionDTO dslActionDTO : unorderedSet) {
- actionNames.add(dslActionDTO.getName());
- }
- assertThat(sortedActionNames).isEqualTo(actionNames);
- }
-
- @Test
- public void convert_whenEmptyActionIdSet_returnsSetInInputOrder() {
DslActionDTO action1 = new DslActionDTO();
DslActionDTO action2 = new DslActionDTO();
- action1.setId("");
- action2.setId("abcd");
+ action1.setName("");
+ action2.setName("abcd");
Set<DslActionDTO> actionSet = Set.of(action1, action2);
orderedActionSet.addAll(actionSet);
for (DslActionDTO dslActionDTO : orderedActionSet) {
- sortedActionIds.add(dslActionDTO.getId());
- }
- List<String> actionIds = new LinkedList<>();
- for (DslActionDTO dslActionDTO : actionSet) {
- actionIds.add(dslActionDTO.getId());
+ sortedActionNames.add(dslActionDTO.getName());
}
// Two lists are defined to be equal if they contain the same elements in the same order.
- assertThat(sortedActionIds).isEqualTo(actionIds);
+ assertThat(sortedActionNames).contains("abcd", "");
}
@Test
public void convert_whenNonEmptySet_returnsOrderedResult() {
+ TreeSet<DslActionDTO> orderedActionSet = new TreeSet<>(new CompareDslActionDTO());
+ List<String> sortedActionIds = new LinkedList<>();
DslActionDTO action1 = new DslActionDTO();
DslActionDTO action2 = new DslActionDTO();
DslActionDTO action3 = new DslActionDTO();
DslActionDTO action4 = new DslActionDTO();
DslActionDTO action5 = new DslActionDTO();
DslActionDTO action6 = new DslActionDTO();
- action1.setId("abc");
- action2.setId("0abc");
- action3.setId("1abc");
- action4.setId("abc0");
- action5.setId("abc1");
- action6.setId("abcd");
+ action1.setName("abc");
+ action2.setName("0abc");
+ action3.setName("1abc");
+ action4.setName("abc0");
+ action5.setName("abc1");
+ action6.setName("abcd");
Set<DslActionDTO> actionSet = Set.of(action1, action2, action3, action4, action5, action6);
orderedActionSet.addAll(actionSet);
for (DslActionDTO dslActionDTO : orderedActionSet) {
- sortedActionIds.add(dslActionDTO.getId());
+ sortedActionIds.add(dslActionDTO.getName());
}
// Two lists are defined to be equal if they contain the same elements in the same order.
assertThat(sortedActionIds).isEqualTo(List.of("0abc", "1abc", "abc", "abc0", "abc1", "abcd"));
diff --git a/app/server/appsmith-server/src/test/java/com/appsmith/server/helpers/GitFileUtilsTest.java b/app/server/appsmith-server/src/test/java/com/appsmith/server/helpers/GitFileUtilsTest.java
index 9833a5fd06ff..f0e229efb816 100644
--- a/app/server/appsmith-server/src/test/java/com/appsmith/server/helpers/GitFileUtilsTest.java
+++ b/app/server/appsmith-server/src/test/java/com/appsmith/server/helpers/GitFileUtilsTest.java
@@ -2,17 +2,17 @@
import com.appsmith.external.git.FileInterface;
import com.appsmith.external.models.ApplicationGitReference;
-import com.appsmith.git.helpers.FileUtilsImpl;
import com.appsmith.server.domains.ActionCollection;
-import com.appsmith.server.domains.ApplicationJson;
import com.appsmith.server.domains.NewAction;
import com.appsmith.server.domains.NewPage;
+import com.appsmith.server.dtos.ApplicationJson;
+import com.appsmith.server.migrations.JsonSchemaMigration;
import com.appsmith.server.services.AnalyticsService;
import com.appsmith.server.services.SessionUserService;
import com.google.gson.Gson;
-import com.google.gson.reflect.TypeToken;
import lombok.SneakyThrows;
-import org.junit.jupiter.api.Test;
+import org.junit.Test;
+import org.junit.runner.RunWith;
import org.mockito.Mockito;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
@@ -25,11 +25,11 @@
import org.springframework.http.codec.multipart.FilePart;
import org.springframework.security.test.context.support.WithUserDetails;
import org.springframework.test.annotation.DirtiesContext;
+import org.springframework.test.context.junit4.SpringRunner;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import reactor.test.StepVerifier;
-import java.lang.reflect.Type;
import java.nio.file.Path;
import java.time.Instant;
import java.util.HashMap;
@@ -40,6 +40,7 @@
import static com.appsmith.external.constants.GitConstants.NAME_SEPARATOR;
import static org.assertj.core.api.Assertions.assertThat;
+@RunWith(SpringRunner.class)
@SpringBootTest
@DirtiesContext
public class GitFileUtilsTest {
@@ -82,10 +83,9 @@ private Mono<ApplicationJson> createAppJson(String filePath) {
return stringifiedFile
.map(data -> {
Gson gson = new Gson();
- Type fileType = new TypeToken<ApplicationJson>() {
- }.getType();
- return gson.fromJson(data, fileType);
- });
+ return gson.fromJson(data, ApplicationJson.class);
+ })
+ .map(JsonSchemaMigration::migrateApplicationToLatestSchema);
}
@Test
@@ -118,7 +118,7 @@ public void getSerializableResource_allEntitiesArePresentForApplication_keysIncl
assertThat(pageNames).contains(pageName);
}
- Map<String, Object> actionsCollections = applicationGitReference.getActionsCollections();
+ Map<String, Object> actionsCollections = applicationGitReference.getActionCollections();
for (Map.Entry<String, Object> entry : actionsCollections.entrySet()) {
assertThat(entry.getKey()).contains(NAME_SEPARATOR);
String[] names = entry.getKey().split(NAME_SEPARATOR);
@@ -163,7 +163,7 @@ public void getSerializableResource_withDeletedEntities_excludeDeletedEntities()
assertThat(deletedAction.getUnpublishedAction().getValidName().replace(".", "-")).isNotEqualTo(queryName);
}
- Map<String, Object> actionsCollections = applicationGitReference.getActionsCollections();
+ Map<String, Object> actionsCollections = applicationGitReference.getActionCollections();
for (Map.Entry<String, Object> entry : actionsCollections.entrySet()) {
String[] names = entry.getKey().split(NAME_SEPARATOR);
final String collectionName = names[0].replace(".", "-");
@@ -233,9 +233,10 @@ public void reconstructApplicationFromLocalRepo_allResourcesArePresent_getCloned
});
ApplicationGitReference applicationReference = new ApplicationGitReference();
+ applicationReference.setApplication(applicationJson.getExportedApplication());
applicationReference.setPages(pageRef);
applicationReference.setActions(actionRef);
- applicationReference.setActionsCollections(actionCollectionRef);
+ applicationReference.setActionCollections(actionCollectionRef);
Mockito.when(fileInterface.reconstructApplicationReferenceFromGitRepo(Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString()))
.thenReturn(Mono.just(applicationReference));
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 e6fbe9ac941e..bae5504c7346 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
@@ -13,7 +13,6 @@
import com.appsmith.server.constants.FieldName;
import com.appsmith.server.domains.ActionCollection;
import com.appsmith.server.domains.Application;
-import com.appsmith.server.domains.ApplicationJson;
import com.appsmith.server.domains.GitApplicationMetadata;
import com.appsmith.server.domains.GitAuth;
import com.appsmith.server.domains.GitProfile;
@@ -25,6 +24,7 @@
import com.appsmith.server.dtos.ActionCollectionDTO;
import com.appsmith.server.dtos.ActionDTO;
import com.appsmith.server.dtos.ApplicationImportDTO;
+import com.appsmith.server.dtos.ApplicationJson;
import com.appsmith.server.dtos.GitCommitDTO;
import com.appsmith.server.dtos.GitConnectDTO;
import com.appsmith.server.dtos.GitMergeDTO;
@@ -37,6 +37,7 @@
import com.appsmith.server.helpers.GitFileUtils;
import com.appsmith.server.helpers.MockPluginExecutor;
import com.appsmith.server.helpers.PluginExecutorHelper;
+import com.appsmith.server.migrations.JsonSchemaMigration;
import com.appsmith.server.migrations.JsonSchemaVersions;
import com.appsmith.server.repositories.PluginRepository;
import com.appsmith.server.repositories.WorkspaceRepository;
@@ -44,7 +45,6 @@
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.gson.Gson;
-import com.google.gson.reflect.TypeToken;
import lombok.extern.slf4j.Slf4j;
import net.minidev.json.JSONArray;
import net.minidev.json.JSONObject;
@@ -75,7 +75,6 @@
import reactor.test.StepVerifier;
import java.io.IOException;
-import java.lang.reflect.Type;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.Duration;
@@ -211,10 +210,9 @@ private Mono<ApplicationJson> createAppJson(String filePath) {
return stringifiedFile
.map(data -> {
Gson gson = new Gson();
- Type fileType = new TypeToken<ApplicationJson>() {
- }.getType();
- return gson.fromJson(data, fileType);
- });
+ return gson.fromJson(data, ApplicationJson.class);
+ })
+ .map(JsonSchemaMigration::migrateApplicationToLatestSchema);
}
private GitConnectDTO getConnectRequest(String remoteUrl, GitProfile gitProfile) {
diff --git a/app/server/appsmith-server/src/test/java/com/appsmith/server/services/ThemeServiceTest.java b/app/server/appsmith-server/src/test/java/com/appsmith/server/services/ThemeServiceTest.java
index 697ef32a5be3..ebac4b473d4d 100644
--- a/app/server/appsmith-server/src/test/java/com/appsmith/server/services/ThemeServiceTest.java
+++ b/app/server/appsmith-server/src/test/java/com/appsmith/server/services/ThemeServiceTest.java
@@ -4,10 +4,10 @@
import com.appsmith.server.acl.AclPermission;
import com.appsmith.server.constants.FieldName;
import com.appsmith.server.domains.Application;
-import com.appsmith.server.domains.ApplicationJson;
import com.appsmith.server.domains.ApplicationMode;
import com.appsmith.server.domains.Theme;
import com.appsmith.server.dtos.ApplicationAccessDTO;
+import com.appsmith.server.dtos.ApplicationJson;
import com.appsmith.server.exceptions.AppsmithError;
import com.appsmith.server.exceptions.AppsmithException;
import com.appsmith.server.helpers.PolicyUtils;
diff --git a/app/server/appsmith-server/src/test/java/com/appsmith/server/solutions/ImportExportApplicationServiceTests.java b/app/server/appsmith-server/src/test/java/com/appsmith/server/solutions/ImportExportApplicationServiceTests.java
index 1380cbb20ec6..79317d62ac9a 100644
--- a/app/server/appsmith-server/src/test/java/com/appsmith/server/solutions/ImportExportApplicationServiceTests.java
+++ b/app/server/appsmith-server/src/test/java/com/appsmith/server/solutions/ImportExportApplicationServiceTests.java
@@ -12,7 +12,6 @@
import com.appsmith.server.constants.SerialiseApplicationObjective;
import com.appsmith.server.domains.ActionCollection;
import com.appsmith.server.domains.Application;
-import com.appsmith.server.domains.ApplicationJson;
import com.appsmith.server.domains.ApplicationMode;
import com.appsmith.server.domains.ApplicationPage;
import com.appsmith.server.domains.GitApplicationMetadata;
@@ -27,6 +26,7 @@
import com.appsmith.server.dtos.ActionDTO;
import com.appsmith.server.dtos.ApplicationAccessDTO;
import com.appsmith.server.dtos.ApplicationImportDTO;
+import com.appsmith.server.dtos.ApplicationJson;
import com.appsmith.server.dtos.ApplicationPagesDTO;
import com.appsmith.server.dtos.PageDTO;
import com.appsmith.server.dtos.PageNameIdDTO;
@@ -53,7 +53,6 @@
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.gson.Gson;
-import com.google.gson.reflect.TypeToken;
import lombok.extern.slf4j.Slf4j;
import net.minidev.json.JSONArray;
import net.minidev.json.JSONObject;
@@ -84,7 +83,6 @@
import reactor.test.StepVerifier;
import reactor.util.function.Tuple3;
-import java.lang.reflect.Type;
import java.time.Duration;
import java.time.Instant;
import java.util.ArrayList;
@@ -265,10 +263,9 @@ private Mono<ApplicationJson> createAppJson(String filePath) {
return stringifiedFile
.map(data -> {
Gson gson = new Gson();
- Type fileType = new TypeToken<ApplicationJson>() {
- }.getType();
- return gson.fromJson(data, fileType);
- });
+ return gson.fromJson(data, ApplicationJson.class);
+ })
+ .map(JsonSchemaMigration::migrateApplicationToLatestSchema);
}
private Workspace createTemplateWorkspace() {
@@ -391,6 +388,20 @@ public void createExportAppJsonWithActionAndActionCollectionTest() {
testWidget.put("testField", "{{ validAction.data }}");
children.add(testWidget);
+ JSONObject tableWidget = new JSONObject();
+ tableWidget.put("widgetName", "Table1");
+ tableWidget.put("type", "TABLE_WIDGET");
+ Map<String, Object> primaryColumns = new HashMap<>();
+ JSONObject jsonObject = new JSONObject(Map.of("key", "value"));
+ primaryColumns.put("_id", "{{ PageAction.data }}");
+ primaryColumns.put("_class", jsonObject);
+ tableWidget.put("primaryColumns", primaryColumns);
+ final ArrayList<Object> objects = new ArrayList<>();
+ JSONArray temp2 = new JSONArray();
+ temp2.addAll(List.of(new JSONObject(Map.of("key", "primaryColumns._id"))));
+ tableWidget.put("dynamicBindingPathList", temp2);
+ children.add(tableWidget);
+
layout.setDsl(dsl);
layout.setPublishedDsl(dsl);
@@ -468,6 +479,7 @@ public void createExportAppJsonWithActionAndActionCollectionTest() {
List<String> DBOnLayoutLoadActionIds = new ArrayList<>();
List<String> exportedOnLayoutLoadActionIds = new ArrayList<>();
+ assertThat(DBPages).hasSize(1);
DBPages.forEach(newPage ->
newPage.getUnpublishedPage().getLayouts().forEach(layout -> {
if (layout.getLayoutOnLoadActions() != null) {
@@ -477,7 +489,6 @@ public void createExportAppJsonWithActionAndActionCollectionTest() {
}
})
);
-
pageList.forEach(newPage ->
newPage.getUnpublishedPage().getLayouts().forEach(layout -> {
if (layout.getLayoutOnLoadActions() != null) {
@@ -490,9 +501,21 @@ public void createExportAppJsonWithActionAndActionCollectionTest() {
NewPage defaultPage = pageList.get(0);
+ // Check if the mongo escaped widget names are carried to exported file from DB
+ Layout pageLayout = DBPages.get(0).getUnpublishedPage().getLayouts().get(0);
+ Set<String> mongoEscapedWidgets = pageLayout.getMongoEscapedWidgetNames();
+ Set<String> expectedMongoEscapedWidgets = Set.of("Table1");
+ assertThat(mongoEscapedWidgets).isEqualTo(expectedMongoEscapedWidgets);
+
+ pageLayout = pageList.get(0).getUnpublishedPage().getLayouts().get(0);
+ Set<String> exportedMongoEscapedWidgets = pageLayout.getMongoEscapedWidgetNames();
+ assertThat(exportedMongoEscapedWidgets).isEqualTo(expectedMongoEscapedWidgets);
+
+
assertThat(exportedApp.getName()).isEqualTo(appName);
assertThat(exportedApp.getWorkspaceId()).isNull();
- assertThat(exportedApp.getPages()).isNull();
+ assertThat(exportedApp.getPages()).hasSize(1);
+ assertThat(exportedApp.getPages().get(0).getId()).isEqualTo(defaultPage.getUnpublishedPage().getName());
assertThat(exportedApp.getPolicies()).isNull();
@@ -500,7 +523,7 @@ public void createExportAppJsonWithActionAndActionCollectionTest() {
assertThat(defaultPage.getApplicationId()).isNull();
assertThat(defaultPage.getUnpublishedPage().getLayouts().get(0).getDsl()).isNotNull();
assertThat(defaultPage.getId()).isNull();
- assertThat(defaultPage.getPolicies()).isEmpty();
+ assertThat(defaultPage.getPolicies()).isNull();
assertThat(actionList.isEmpty()).isFalse();
assertThat(actionList).hasSize(3);
@@ -537,14 +560,12 @@ public void createExportAppJsonWithActionAndActionCollectionTest() {
assertThat(datasource.getPluginId()).isEqualTo(installedPlugin.getPackageName());
assertThat(datasource.getDatasourceConfiguration()).isNull();
- final Map<String, InvisibleActionFields> invisibleActionFields = applicationJson.getInvisibleActionFields();
-
- Assert.assertEquals(3, invisibleActionFields.size());
+ assertThat(applicationJson.getInvisibleActionFields()).isNull();
NewAction validAction2 = actionList.stream().filter(action -> action.getId().equals("Page1_validAction2")).findFirst().get();
- Assert.assertEquals(true, invisibleActionFields.get(validAction2.getId()).getUnpublishedUserSetOnLoad());
+ Assert.assertEquals(true, validAction2.getUnpublishedAction().getUserSetOnLoad());
- assertThat(applicationJson.getUnpublishedLayoutmongoEscapedWidgets()).isNotEmpty();
- assertThat(applicationJson.getPublishedLayoutmongoEscapedWidgets()).isNotEmpty();
+ assertThat(applicationJson.getUnpublishedLayoutmongoEscapedWidgets()).isNull();
+ assertThat(applicationJson.getPublishedLayoutmongoEscapedWidgets()).isNull();
assertThat(applicationJson.getEditModeTheme()).isNotNull();
assertThat(applicationJson.getEditModeTheme().isSystemTheme()).isTrue();
assertThat(applicationJson.getEditModeTheme().getName()).isEqualToIgnoringCase(Theme.DEFAULT_THEME_NAME);
@@ -569,45 +590,39 @@ public void createExportAppJsonWithActionAndActionCollectionTest() {
@WithUserDetails(value = "api_user")
public void createExportAppJsonForGitTest() {
- final Mono<ApplicationJson> resultMono = Mono.zip(
- workspaceService.getById(workspaceId),
- applicationRepository.findById(testAppId)
- )
- .flatMap(tuple -> {
+ StringBuilder pageName = new StringBuilder();
+ final Mono<ApplicationJson> resultMono = applicationRepository.findById(testAppId)
+ .flatMap(testApp -> {
+ final String pageId = testApp.getPages().get(0).getId();
+ return Mono.zip(
+ Mono.just(testApp),
+ newPageService.findPageById(pageId, READ_PAGES, false)
+ );
+ })
+ .flatMap(tuple -> {
+ Datasource ds1 = datasourceMap.get("DS1");
+ Application testApp = tuple.getT1();
+ PageDTO testPage = tuple.getT2();
+ pageName.append(testPage.getName());
- Workspace workspace = tuple.getT1();
- Application testApp = tuple.getT2();
+ Layout layout = testPage.getLayouts().get(0);
+ JSONObject dsl = new JSONObject(Map.of("text", "{{ query1.data }}"));
- final String pageId = testApp.getPages().get(0).getId();
+ layout.setDsl(dsl);
+ layout.setPublishedDsl(dsl);
- return Mono.zip(
- Mono.just(testApp),
- newPageService.findPageById(pageId, READ_PAGES, false)
- );
- })
- .flatMap(tuple -> {
- Datasource ds1 = datasourceMap.get("DS1");
- Application testApp = tuple.getT1();
- PageDTO testPage = tuple.getT2();
-
- Layout layout = testPage.getLayouts().get(0);
- JSONObject dsl = new JSONObject(Map.of("text", "{{ query1.data }}"));
-
- layout.setDsl(dsl);
- layout.setPublishedDsl(dsl);
-
- ActionDTO action = new ActionDTO();
- action.setName("validAction");
- action.setPageId(testPage.getId());
- action.setExecuteOnLoad(true);
- ActionConfiguration actionConfiguration = new ActionConfiguration();
- actionConfiguration.setHttpMethod(HttpMethod.GET);
- action.setActionConfiguration(actionConfiguration);
- action.setDatasource(ds1);
-
- return layoutActionService.createAction(action)
- .then(importExportApplicationService.exportApplicationById(testApp.getId(), SerialiseApplicationObjective.VERSION_CONTROL));
- });
+ ActionDTO action = new ActionDTO();
+ action.setName("validAction");
+ action.setPageId(testPage.getId());
+ action.setExecuteOnLoad(true);
+ ActionConfiguration actionConfiguration = new ActionConfiguration();
+ actionConfiguration.setHttpMethod(HttpMethod.GET);
+ action.setActionConfiguration(actionConfiguration);
+ action.setDatasource(ds1);
+
+ return layoutActionService.createAction(action)
+ .then(importExportApplicationService.exportApplicationById(testApp.getId(), SerialiseApplicationObjective.VERSION_CONTROL));
+ });
StepVerifier
.create(resultMono)
@@ -625,16 +640,18 @@ public void createExportAppJsonForGitTest() {
assertThat(exportedApp.getName()).isNotNull();
assertThat(exportedApp.getWorkspaceId()).isNull();
- assertThat(exportedApp.getPages()).isNull();
+ assertThat(exportedApp.getPages()).hasSize(1);
+ assertThat(exportedApp.getPages().get(0).getId()).isEqualTo(pageName.toString());
assertThat(exportedApp.getGitApplicationMetadata()).isNull();
assertThat(exportedApp.getPolicies()).isNull();
+ assertThat(exportedApp.getUserPermissions()).isNull();
assertThat(pageList).hasSize(1);
assertThat(newPage.getApplicationId()).isNull();
assertThat(newPage.getUnpublishedPage().getLayouts().get(0).getDsl()).isNotNull();
assertThat(newPage.getId()).isNull();
- assertThat(newPage.getPolicies()).isEmpty();
+ assertThat(newPage.getPolicies()).isNull();
assertThat(actionList.isEmpty()).isFalse();
NewAction validAction = actionList.get(0);
@@ -654,8 +671,8 @@ public void createExportAppJsonForGitTest() {
assertThat(datasource.getPluginId()).isEqualTo(installedPlugin.getPackageName());
assertThat(datasource.getDatasourceConfiguration()).isNull();
- assertThat(applicationJson.getUnpublishedLayoutmongoEscapedWidgets()).isNotEmpty();
- assertThat(applicationJson.getPublishedLayoutmongoEscapedWidgets()).isNotEmpty();
+ assertThat(applicationJson.getUnpublishedLayoutmongoEscapedWidgets()).isNull();
+ assertThat(applicationJson.getPublishedLayoutmongoEscapedWidgets()).isNull();
})
.verifyComplete();
}
@@ -1953,7 +1970,21 @@ public void discardChange_removeNewActionCollection_removedActionCollectionResto
@Test
@WithUserDetails(value = "api_user")
public void applySchemaMigration_jsonFileWithFirstVersion_migratedToLatestVersionSuccess() {
- Mono<ApplicationJson> v1ApplicationMono = createAppJson("test_assets/ImportExportServiceTest/file-with-v1.json").cache();
+ FilePart filePart = createFilePart("test_assets/ImportExportServiceTest/file-with-v1.json");
+
+ Mono<String> stringifiedFile = DataBufferUtils.join(filePart.content())
+ .map(dataBuffer -> {
+ byte[] data = new byte[dataBuffer.readableByteCount()];
+ dataBuffer.read(data);
+ DataBufferUtils.release(dataBuffer);
+ return new String(data);
+ });
+ Mono<ApplicationJson> v1ApplicationMono = stringifiedFile
+ .map(data -> {
+ Gson gson = new Gson();
+ return gson.fromJson(data, ApplicationJson.class);
+ }).cache();
+
Mono<ApplicationJson> migratedApplicationMono = v1ApplicationMono
.map(applicationJson -> {
ApplicationJson applicationJson1 = new ApplicationJson();
@@ -2125,7 +2156,12 @@ public void exportApplication_withDatasourceConfig_exportedWithDecryptedFields()
assertThat(exportedApp.getName()).isEqualTo(appName);
assertThat(exportedApp.getWorkspaceId()).isNull();
- assertThat(exportedApp.getPages()).isNull();
+ assertThat(exportedApp.getPages()).hasSize(1);
+ ApplicationPage page = exportedApp.getPages().get(0);
+
+ assertThat(page.getId()).isEqualTo(defaultPage.getUnpublishedPage().getName());
+ assertThat(page.getIsDefault()).isTrue();
+ assertThat(page.getDefaultPageId()).isNull();
assertThat(exportedApp.getPolicies()).isNull();
@@ -2133,7 +2169,7 @@ public void exportApplication_withDatasourceConfig_exportedWithDecryptedFields()
assertThat(defaultPage.getApplicationId()).isNull();
assertThat(defaultPage.getUnpublishedPage().getLayouts().get(0).getDsl()).isNotNull();
assertThat(defaultPage.getId()).isNull();
- assertThat(defaultPage.getPolicies()).isEmpty();
+ assertThat(defaultPage.getPolicies()).isNull();
assertThat(actionList.isEmpty()).isFalse();
assertThat(actionList).hasSize(3);
@@ -2172,12 +2208,17 @@ public void exportApplication_withDatasourceConfig_exportedWithDecryptedFields()
final Map<String, InvisibleActionFields> invisibleActionFields = applicationJson.getInvisibleActionFields();
- Assert.assertEquals(3, invisibleActionFields.size());
- NewAction validAction2 = actionList.stream().filter(action -> action.getId().equals("Page1_validAction2")).findFirst().get();
- Assert.assertEquals(true, invisibleActionFields.get(validAction2.getId()).getUnpublishedUserSetOnLoad());
+ assertThat(invisibleActionFields).isNull();
+ for (NewAction newAction : actionList) {
+ if (newAction.getId().equals("Page1_validAction2")) {
+ Assert.assertEquals(true, newAction.getUnpublishedAction().getUserSetOnLoad());
+ } else {
+ Assert.assertEquals(false, newAction.getUnpublishedAction().getUserSetOnLoad());
+ }
+ }
- assertThat(applicationJson.getUnpublishedLayoutmongoEscapedWidgets()).isNotEmpty();
- assertThat(applicationJson.getPublishedLayoutmongoEscapedWidgets()).isNotEmpty();
+ assertThat(applicationJson.getUnpublishedLayoutmongoEscapedWidgets()).isNull();
+ assertThat(applicationJson.getPublishedLayoutmongoEscapedWidgets()).isNull();
assertThat(applicationJson.getEditModeTheme()).isNotNull();
assertThat(applicationJson.getEditModeTheme().isSystemTheme()).isTrue();
assertThat(applicationJson.getEditModeTheme().getName()).isEqualToIgnoringCase(Theme.DEFAULT_THEME_NAME);
@@ -2336,40 +2377,50 @@ public void exportAndImportApplication_withMultiplePagesOrderSameInDeployAndEdit
testApplication = applicationPageService.createApplication(testApplication, workspaceId).block();
assert testApplication != null;
- PageDTO testPage = new PageDTO();
- testPage.setName("123");
- testPage.setApplicationId(testApplication.getId());
- PageDTO page1 = applicationPageService.createPage(testPage).block();
+ PageDTO testPage1 = new PageDTO();
+ testPage1.setName("testPage1");
+ testPage1.setApplicationId(testApplication.getId());
+ testPage1 = applicationPageService.createPage(testPage1).block();
- testPage = new PageDTO();
- testPage.setName("abc");
- testPage.setApplicationId(testApplication.getId());
- PageDTO page2 = applicationPageService.createPage(testPage).block();
+ PageDTO testPage2 = new PageDTO();
+ testPage2.setName("testPage2");
+ testPage2.setApplicationId(testApplication.getId());
+ testPage2 = applicationPageService.createPage(testPage2).block();
// Set order for the newly created pages
- applicationPageService.reorderPage(testApplication.getId(), page1.getId(), 0, null).block();
- applicationPageService.reorderPage(testApplication.getId(), page2.getId(), 1, null).block();
+ applicationPageService.reorderPage(testApplication.getId(), testPage1.getId(), 0, null).block();
+ applicationPageService.reorderPage(testApplication.getId(), testPage2.getId(), 1, null).block();
// Deploy the current application
applicationPageService.publish(testApplication.getId(), true).block();
- Mono<ApplicationJson> applicationJsonMono = importExportApplicationService.exportApplicationById(testApplication.getId(), "");
+ Mono<ApplicationJson> applicationJsonMono = importExportApplicationService.exportApplicationById(testApplication.getId(), "").cache();
StepVerifier
.create(applicationJsonMono)
.assertNext(applicationJson -> {
- List<String> pageList = applicationJson.getPageOrder();
- assertThat(pageList.get(0)).isEqualTo("123");
- assertThat(pageList.get(1)).isEqualTo("abc");
+ assertThat(applicationJson.getPageOrder()).isNull();
+ assertThat(applicationJson.getPublishedPageOrder()).isNull();
+ List<String> pageList = applicationJson.getExportedApplication().getPages()
+ .stream()
+ .map(ApplicationPage::getId)
+ .collect(Collectors.toList());
+
+ assertThat(pageList.get(0)).isEqualTo("testPage1");
+ assertThat(pageList.get(1)).isEqualTo("testPage2");
assertThat(pageList.get(2)).isEqualTo("Page1");
- List<String> publishedPageList = applicationJson.getPublishedPageOrder();
- assertThat(publishedPageList.get(0)).isEqualTo("123");
- assertThat(publishedPageList.get(1)).isEqualTo("abc");
+ List<String> publishedPageList = applicationJson.getExportedApplication().getPublishedPages()
+ .stream()
+ .map(ApplicationPage::getId)
+ .collect(Collectors.toList());
+
+ assertThat(publishedPageList.get(0)).isEqualTo("testPage1");
+ assertThat(publishedPageList.get(1)).isEqualTo("testPage2");
assertThat(publishedPageList.get(2)).isEqualTo("Page1");
})
.verifyComplete();
- ApplicationJson applicationJson = importExportApplicationService.exportApplicationById(testApplication.getId(), "").block();
+ ApplicationJson applicationJson = applicationJsonMono.block();
Application application = importExportApplicationService.importApplicationInWorkspace(workspaceId, applicationJson).block();
// Get the unpublished pages and verify the order
@@ -2384,8 +2435,8 @@ public void exportAndImportApplication_withMultiplePagesOrderSameInDeployAndEdit
NewPage newPage1 = objects.getT1();
NewPage newPage2 = objects.getT2();
NewPage newPage3 = objects.getT3();
- assertThat(newPage1.getUnpublishedPage().getName()).isEqualTo("123");
- assertThat(newPage2.getUnpublishedPage().getName()).isEqualTo("abc");
+ assertThat(newPage1.getUnpublishedPage().getName()).isEqualTo("testPage1");
+ assertThat(newPage2.getUnpublishedPage().getName()).isEqualTo("testPage2");
assertThat(newPage3.getUnpublishedPage().getName()).isEqualTo("Page1");
assertThat(newPage1.getId()).isEqualTo(pageDTOS.get(0).getId());
@@ -2406,8 +2457,8 @@ public void exportAndImportApplication_withMultiplePagesOrderSameInDeployAndEdit
NewPage newPage1 = objects.getT1();
NewPage newPage2 = objects.getT2();
NewPage newPage3 = objects.getT3();
- assertThat(newPage1.getPublishedPage().getName()).isEqualTo("123");
- assertThat(newPage2.getPublishedPage().getName()).isEqualTo("abc");
+ assertThat(newPage1.getPublishedPage().getName()).isEqualTo("testPage1");
+ assertThat(newPage2.getPublishedPage().getName()).isEqualTo("testPage2");
assertThat(newPage3.getPublishedPage().getName()).isEqualTo("Page1");
assertThat(newPage1.getId()).isEqualTo(publishedPageDTOs.get(0).getId());
@@ -2431,44 +2482,54 @@ public void exportAndImportApplication_withMultiplePagesOrderDifferentInDeployAn
testApplication = applicationPageService.createApplication(testApplication, workspaceId).block();
assert testApplication != null;
- PageDTO testPage = new PageDTO();
- testPage.setName("123");
- testPage.setApplicationId(testApplication.getId());
- PageDTO page1 = applicationPageService.createPage(testPage).block();
+ PageDTO testPage1 = new PageDTO();
+ testPage1.setName("testPage1");
+ testPage1.setApplicationId(testApplication.getId());
+ testPage1 = applicationPageService.createPage(testPage1).block();
- testPage = new PageDTO();
- testPage.setName("abc");
- testPage.setApplicationId(testApplication.getId());
- PageDTO page2 = applicationPageService.createPage(testPage).block();
+ PageDTO testPage2 = new PageDTO();
+ testPage2.setName("testPage2");
+ testPage2.setApplicationId(testApplication.getId());
+ testPage2 = applicationPageService.createPage(testPage2).block();
// Deploy the current application so that edit and view mode will have different page order
applicationPageService.publish(testApplication.getId(), true).block();
// Set order for the newly created pages
- applicationPageService.reorderPage(testApplication.getId(), page1.getId(), 0, null).block();
- applicationPageService.reorderPage(testApplication.getId(), page2.getId(), 1, null).block();
+ applicationPageService.reorderPage(testApplication.getId(), testPage1.getId(), 0, null).block();
+ applicationPageService.reorderPage(testApplication.getId(), testPage2.getId(), 1, null).block();
- Mono<ApplicationJson> applicationJsonMono = importExportApplicationService.exportApplicationById(testApplication.getId(), "");
+ Mono<ApplicationJson> applicationJsonMono = importExportApplicationService.exportApplicationById(testApplication.getId(), "").cache();
StepVerifier
.create(applicationJsonMono)
.assertNext(applicationJson -> {
- List<String> pageList = applicationJson.getPageOrder();
- assertThat(pageList.get(0)).isEqualTo("123");
- assertThat(pageList.get(1)).isEqualTo("abc");
- assertThat(pageList.get(2)).isEqualTo("Page1");
-
- List<String> publishedPageOrder = applicationJson.getPageOrder();
- assertThat(publishedPageOrder.get(0)).isEqualTo("123");
- assertThat(publishedPageOrder.get(1)).isEqualTo("abc");
- assertThat(publishedPageOrder.get(2)).isEqualTo("Page1");
+ Application exportedApplication = applicationJson.getExportedApplication();
+ exportedApplication.setViewMode(false);
+ List<String> pageOrder = exportedApplication.getPages()
+ .stream()
+ .map(ApplicationPage::getId)
+ .collect(Collectors.toList());
+ assertThat(pageOrder.get(0)).isEqualTo("testPage1");
+ assertThat(pageOrder.get(1)).isEqualTo("testPage2");
+ assertThat(pageOrder.get(2)).isEqualTo("Page1");
+
+ pageOrder.clear();
+ pageOrder = exportedApplication.getPublishedPages()
+ .stream()
+ .map(ApplicationPage::getId)
+ .collect(Collectors.toList());
+ assertThat(pageOrder.get(0)).isEqualTo("Page1");
+ assertThat(pageOrder.get(1)).isEqualTo("testPage1");
+ assertThat(pageOrder.get(2)).isEqualTo("testPage2");
})
.verifyComplete();
- ApplicationJson applicationJson = importExportApplicationService.exportApplicationById(testApplication.getId(), "").block();
+ ApplicationJson applicationJson = applicationJsonMono.block();
Application application = importExportApplicationService.importApplicationInWorkspace(workspaceId, applicationJson).block();
// Get the unpublished pages and verify the order
+ application.setViewMode(false);
List<ApplicationPage> pageDTOS = application.getPages();
Mono<NewPage> newPageMono1 = newPageService.findById(pageDTOS.get(0).getId(), MANAGE_PAGES);
Mono<NewPage> newPageMono2 = newPageService.findById(pageDTOS.get(1).getId(), MANAGE_PAGES);
@@ -2480,8 +2541,8 @@ public void exportAndImportApplication_withMultiplePagesOrderDifferentInDeployAn
NewPage newPage1 = objects.getT1();
NewPage newPage2 = objects.getT2();
NewPage newPage3 = objects.getT3();
- assertThat(newPage1.getUnpublishedPage().getName()).isEqualTo("123");
- assertThat(newPage2.getUnpublishedPage().getName()).isEqualTo("abc");
+ assertThat(newPage1.getUnpublishedPage().getName()).isEqualTo("testPage1");
+ assertThat(newPage2.getUnpublishedPage().getName()).isEqualTo("testPage2");
assertThat(newPage3.getUnpublishedPage().getName()).isEqualTo("Page1");
assertThat(newPage1.getId()).isEqualTo(pageDTOS.get(0).getId());
@@ -2503,8 +2564,8 @@ public void exportAndImportApplication_withMultiplePagesOrderDifferentInDeployAn
NewPage newPage2 = objects.getT2();
NewPage newPage3 = objects.getT3();
assertThat(newPage1.getPublishedPage().getName()).isEqualTo("Page1");
- assertThat(newPage2.getPublishedPage().getName()).isEqualTo("123");
- assertThat(newPage3.getPublishedPage().getName()).isEqualTo("abc");
+ assertThat(newPage2.getPublishedPage().getName()).isEqualTo("testPage1");
+ assertThat(newPage3.getPublishedPage().getName()).isEqualTo("testPage2");
assertThat(newPage1.getId()).isEqualTo(publishedPageDTOs.get(0).getId());
assertThat(newPage2.getId()).isEqualTo(publishedPageDTOs.get(1).getId());
diff --git a/app/server/appsmith-server/src/test/resources/test_assets/ImportExportServiceTest/valid-application-with-custom-themes.json b/app/server/appsmith-server/src/test/resources/test_assets/ImportExportServiceTest/valid-application-with-custom-themes.json
index 82793f2fcb1e..595d66fe845f 100644
--- a/app/server/appsmith-server/src/test/resources/test_assets/ImportExportServiceTest/valid-application-with-custom-themes.json
+++ b/app/server/appsmith-server/src/test/resources/test_assets/ImportExportServiceTest/valid-application-with-custom-themes.json
@@ -90,7 +90,7 @@
"name": "Page1",
"layouts": [
{
- "id": "60aca056136c4b7178f67906",
+ "id": "Page1",
"userPermissions": [],
"dsl": {
"widgetName": "MainContainer",
@@ -345,7 +345,7 @@
"name": "Page1",
"layouts": [
{
- "id": "60aca056136c4b7178f67906",
+ "id": "Page1",
"userPermissions": [],
"dsl": {
"widgetName": "MainContainer",
@@ -622,12 +622,12 @@
"publishedDefaultPageName": "Page1",
"unpublishedDefaultPageName": "Page1",
"publishedLayoutmongoEscapedWidgets": {
- "60aca056136c4b7178f67906": [
+ "Page1": [
"Table1"
]
},
"unpublishedLayoutmongoEscapedWidgets": {
- "60aca056136c4b7178f67906": [
+ "Page1": [
"Table1"
]
},
diff --git a/app/server/appsmith-server/src/test/resources/test_assets/ImportExportServiceTest/valid-application-without-action-collection.json b/app/server/appsmith-server/src/test/resources/test_assets/ImportExportServiceTest/valid-application-without-action-collection.json
index df53c8f2ba7d..170583631b5f 100644
--- a/app/server/appsmith-server/src/test/resources/test_assets/ImportExportServiceTest/valid-application-without-action-collection.json
+++ b/app/server/appsmith-server/src/test/resources/test_assets/ImportExportServiceTest/valid-application-without-action-collection.json
@@ -90,7 +90,7 @@
"name": "Page1",
"layouts": [
{
- "id": "60aca056136c4b7178f67906",
+ "id": "Page1",
"userPermissions": [],
"dsl": {
"widgetName": "MainContainer",
@@ -345,7 +345,7 @@
"name": "Page1",
"layouts": [
{
- "id": "60aca056136c4b7178f67906",
+ "id": "Page1",
"userPermissions": [],
"dsl": {
"widgetName": "MainContainer",
@@ -546,12 +546,12 @@
"publishedDefaultPageName": "Page1",
"unpublishedDefaultPageName": "Page1",
"publishedLayoutmongoEscapedWidgets": {
- "60aca056136c4b7178f67906": [
+ "Page1": [
"Table1"
]
},
"unpublishedLayoutmongoEscapedWidgets": {
- "60aca056136c4b7178f67906": [
+ "Page1": [
"Table1"
]
}
diff --git a/app/server/appsmith-server/src/test/resources/test_assets/ImportExportServiceTest/valid-application-without-theme.json b/app/server/appsmith-server/src/test/resources/test_assets/ImportExportServiceTest/valid-application-without-theme.json
index d36510772b7e..2895626de347 100644
--- a/app/server/appsmith-server/src/test/resources/test_assets/ImportExportServiceTest/valid-application-without-theme.json
+++ b/app/server/appsmith-server/src/test/resources/test_assets/ImportExportServiceTest/valid-application-without-theme.json
@@ -90,7 +90,7 @@
"name": "Page1",
"layouts": [
{
- "id": "60aca056136c4b7178f67906",
+ "id": "Page1",
"userPermissions": [],
"dsl": {
"widgetName": "MainContainer",
@@ -345,7 +345,7 @@
"name": "Page1",
"layouts": [
{
- "id": "60aca056136c4b7178f67906",
+ "id": "Page1",
"userPermissions": [],
"dsl": {
"widgetName": "MainContainer",
@@ -622,12 +622,12 @@
"publishedDefaultPageName": "Page1",
"unpublishedDefaultPageName": "Page1",
"publishedLayoutmongoEscapedWidgets": {
- "60aca056136c4b7178f67906": [
+ "Page1": [
"Table1"
]
},
"unpublishedLayoutmongoEscapedWidgets": {
- "60aca056136c4b7178f67906": [
+ "Page1": [
"Table1"
]
}
diff --git a/app/server/appsmith-server/src/test/resources/test_assets/ImportExportServiceTest/valid-application.json b/app/server/appsmith-server/src/test/resources/test_assets/ImportExportServiceTest/valid-application.json
index 92bb277ccaee..3e3ef4fe22c4 100644
--- a/app/server/appsmith-server/src/test/resources/test_assets/ImportExportServiceTest/valid-application.json
+++ b/app/server/appsmith-server/src/test/resources/test_assets/ImportExportServiceTest/valid-application.json
@@ -90,7 +90,7 @@
"name": "Page1",
"layouts": [
{
- "id": "60aca056136c4b7178f67906",
+ "id": "Page1",
"userPermissions": [],
"dsl": {
"widgetName": "MainContainer",
@@ -345,7 +345,7 @@
"name": "Page1",
"layouts": [
{
- "id": "60aca056136c4b7178f67906",
+ "id": "Page1",
"userPermissions": [],
"dsl": {
"widgetName": "MainContainer",
@@ -692,12 +692,12 @@
"publishedDefaultPageName": "Page1",
"unpublishedDefaultPageName": "Page1",
"publishedLayoutmongoEscapedWidgets": {
- "60aca056136c4b7178f67906": [
+ "Page1": [
"Table1"
]
},
"unpublishedLayoutmongoEscapedWidgets": {
- "60aca056136c4b7178f67906": [
+ "Page1": [
"Table1"
]
},
|
b5af1a936f3adf27d3cb9c9738bd8526b4bc514c
|
2023-08-04 09:16:59
|
Aishwarya-U-R
|
test: Cypress | CI Stabilize (#26000)
| false
|
Cypress | CI Stabilize (#26000)
|
test
|
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 8693f1437d7d..f43787fca4b5 100644
--- a/app/client/cypress/e2e/Regression/ClientSide/BugTests/DatasourceSchema_spec.ts
+++ b/app/client/cypress/e2e/Regression/ClientSide/BugTests/DatasourceSchema_spec.ts
@@ -72,11 +72,7 @@ describe("Datasource form related tests", function () {
dataSources.VerifyTableSchemaOnQueryEditor("public.users");
entityExplorer.ExpandCollapseEntity("public.users");
dataSources.VerifyColumnSchemaOnQueryEditor("id");
- dataSources.FilterAndVerifyDatasourceSchemaBySearch(
- "gender",
- true,
- "column",
- );
+ dataSources.FilterAndVerifyDatasourceSchemaBySearch("gender", "column");
},
);
@@ -126,10 +122,8 @@ describe("Datasource form related tests", function () {
agHelper.RefreshPage();
dataSources.CreateDataSource("S3", true, false);
dataSources.CreateQueryAfterDSSaved();
- dataSources.VerifyTableSchemaOnQueryEditor("appsmith-hris");
dataSources.FilterAndVerifyDatasourceSchemaBySearch(
"appsmith-hris",
- true,
"table",
);
});
diff --git a/app/client/cypress/e2e/Regression/ClientSide/Widgets/ListV2/Event_Bindings_spec.ts b/app/client/cypress/e2e/Regression/ClientSide/Widgets/ListV2/Event_Bindings_spec.ts
index ff3f3dc9db17..d7c8922273b7 100644
--- a/app/client/cypress/e2e/Regression/ClientSide/Widgets/ListV2/Event_Bindings_spec.ts
+++ b/app/client/cypress/e2e/Regression/ClientSide/Widgets/ListV2/Event_Bindings_spec.ts
@@ -41,7 +41,9 @@ describe("Listv2 - Event bindings spec", () => {
// click the button on inner list 1st row.
agHelper.ClickButton("Submit");
- agHelper.ValidateToastMessage("Blue _ 001 _ 0 _ outer input _ inner input");
+ agHelper.WaitUntilToastDisappear(
+ "Blue _ 001 _ 0 _ outer input _ inner input",
+ );
});
it("2. nested list - inner widget should get updated values of currentView and level_1", () => {
diff --git a/app/client/cypress/support/Pages/DataSources.ts b/app/client/cypress/support/Pages/DataSources.ts
index 87b874a6ff85..e6a16677c2c7 100644
--- a/app/client/cypress/support/Pages/DataSources.ts
+++ b/app/client/cypress/support/Pages/DataSources.ts
@@ -32,7 +32,7 @@ interface RunQueryParams {
export class DataSources {
private agHelper = ObjectsRegistry.AggregateHelper;
private table = ObjectsRegistry.Table;
- private ee = ObjectsRegistry.EntityExplorer;
+ private entityExplorer = ObjectsRegistry.EntityExplorer;
private locator = ObjectsRegistry.CommonLocators;
private apiPage = ObjectsRegistry.ApiPage;
private tedTestConfig = ObjectsRegistry.TEDTestConfigs;
@@ -238,8 +238,8 @@ export class DataSources {
"//p[contains(text(),'" +
ddName +
"')]/ancestor::div[@class='form-config-top']/following-sibling::div//div[contains(@class, 'rc-select-multiple')]";
- private _datasourceTableSchemaInQueryEditor =
- ".datasourceStructure-query-editor";
+ private _datasourceTableSchemaInQueryEditor = (schemaName: string) =>
+ `//div[contains(@class, 'datasourceStructure-query-editor')]//div[contains(@class, 't--entity-name')][text()='${schemaName}']`;
private _datasourceSchemaRefreshBtn = ".datasourceStructure-refresh";
private _datasourceStructureHeader = ".datasourceStructure-header";
private _datasourceColumnSchemaInQueryEditor = ".t--datasource-column";
@@ -255,7 +255,7 @@ export class DataSources {
}
public GeneratePageWithDB(datasourceName: any, tableName: string) {
- this.ee.AddNewPage("Generate page with data");
+ this.entityExplorer.AddNewPage("Generate page with data");
this.agHelper.GetNClick(this._selectDatasourceDropdown);
this.agHelper.GetNClickByContains(
this.locator._dropdownText,
@@ -271,7 +271,7 @@ export class DataSources {
}
public GeneratePageWithMockDB() {
- this.ee.AddNewPage("Generate page with data");
+ this.entityExplorer.AddNewPage("Generate page with data");
this.agHelper.GetNClick(this._selectDatasourceDropdown);
this.agHelper.GetNClickByContains(
this._dropdownOption,
@@ -394,7 +394,7 @@ export class DataSources {
}
public NavigateToDSCreateNew() {
- this.ee.HoverOnEntityItem("Datasources");
+ this.entityExplorer.HoverOnEntityItem("Datasources");
Cypress._.times(2, () => {
this.agHelper.GetNClick(this._addNewDataSource, 0, true);
this.agHelper.Sleep();
@@ -816,8 +816,8 @@ export class DataSources {
dsName: string,
expectedRes: number | number[] = 200,
) {
- this.ee.SelectEntityByName(dsName, "Datasources");
- this.ee.ActionContextMenuByEntityName({
+ this.entityExplorer.SelectEntityByName(dsName, "Datasources");
+ this.entityExplorer.ActionContextMenuByEntityName({
entityNameinLeftSidebar: dsName,
action: "Delete",
entityType: EntityItems.Datasource,
@@ -884,10 +884,10 @@ export class DataSources {
}
public AssertDSActive(dsName: string | RegExp) {
- this.ee.NavigateToSwitcher("Explorer", 0, true);
- this.ee.ExpandCollapseEntity("Datasources", false);
- //this.ee.SelectEntityByName(datasourceName, "Datasources");
- //this.ee.ExpandCollapseEntity(datasourceName, false);
+ this.entityExplorer.NavigateToSwitcher("Explorer", 0, true);
+ this.entityExplorer.ExpandCollapseEntity("Datasources", false);
+ //this.entityExplorer.SelectEntityByName(datasourceName, "Datasources");
+ //this.entityExplorer.ExpandCollapseEntity(datasourceName, false);
this.NavigateToActiveTab();
return this.agHelper.GetNAssertContains(this._datasourceCard, dsName);
}
@@ -951,8 +951,8 @@ export class DataSources {
}
DeleteQuery(queryName: string) {
- this.ee.ExpandCollapseEntity("Queries/JS");
- this.ee.ActionContextMenuByEntityName({
+ this.entityExplorer.ExpandCollapseEntity("Queries/JS");
+ this.entityExplorer.ActionContextMenuByEntityName({
entityNameinLeftSidebar: queryName,
action: "Delete",
entityType: EntityItems.Query,
@@ -1245,7 +1245,7 @@ export class DataSources {
sleep = 500,
) {
this.agHelper.RemoveEvaluatedPopUp(); //to close the evaluated pop-up
- this.ee.CreateNewDsQuery(dsName);
+ this.entityExplorer.CreateNewDsQuery(dsName);
if (query) {
this.EnterQuery(query, sleep);
}
@@ -1341,7 +1341,7 @@ export class DataSources {
} else {
this.SaveDatasource();
}
- this.ee.ActionContextMenuByEntityName({
+ this.entityExplorer.ActionContextMenuByEntityName({
entityNameinLeftSidebar: dataSourceName,
action: "Refresh",
});
@@ -1351,9 +1351,9 @@ export class DataSources {
}
public VerifyTableSchemaOnQueryEditor(schema: string) {
- this.agHelper
- .GetElement(this._datasourceTableSchemaInQueryEditor)
- .contains(schema);
+ this.agHelper.AssertElementVisible(
+ this._datasourceTableSchemaInQueryEditor(schema),
+ );
}
public VerifySchemaAbsenceInQueryEditor() {
@@ -1381,17 +1381,15 @@ export class DataSources {
public FilterAndVerifyDatasourceSchemaBySearch(
search: string,
- verifySearch = false,
- filterBy: "table" | "column" = "column",
+ filterBy?: "table" | "column",
) {
+ this.agHelper.Sleep(2500); //for query editor to load
this.agHelper.TypeText(this._datasourceStructureSearchInput, search);
-
- if (verifySearch) {
- if (filterBy === "column") {
- this.VerifyColumnSchemaOnQueryEditor(search);
- } else {
- this.VerifyTableSchemaOnQueryEditor(search);
- }
+ this.agHelper.Sleep(); //for search result to load
+ if (filterBy === "column") {
+ this.VerifyColumnSchemaOnQueryEditor(search);
+ } else if (filterBy === "table") {
+ this.VerifyTableSchemaOnQueryEditor(search);
}
}
|
5c879230fc8b60f92903d843e9ad998cf65bc1da
|
2024-02-15 10:25:24
|
Shrikant Sharat Kandula
|
chore: Fluent API for update methods (#31104)
| false
|
Fluent API for update methods (#31104)
|
chore
|
diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/BaseAppsmithRepositoryCEImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/BaseAppsmithRepositoryCEImpl.java
index 5af505996667..b0c3881e19c7 100644
--- a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/BaseAppsmithRepositoryCEImpl.java
+++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/BaseAppsmithRepositoryCEImpl.java
@@ -17,6 +17,7 @@
import com.mongodb.client.result.UpdateResult;
import com.querydsl.core.types.Path;
import jakarta.validation.constraints.NotNull;
+import lombok.NonNull;
import org.bson.Document;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
@@ -39,6 +40,7 @@
import java.util.HashSet;
import java.util.List;
import java.util.Map;
+import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
@@ -236,46 +238,6 @@ public Mono<UpdateResult> updateFieldByDefaultIdAndBranchName(
});
}
- public Mono<UpdateResult> updateById(String id, Update updateObj, AclPermission permission) {
- if (id == null) {
- return Mono.error(new AppsmithException(AppsmithError.INVALID_PARAMETER, FieldName.ID));
- }
- if (updateObj == null) {
- return Mono.error(new AppsmithException(AppsmithError.INVALID_PARAMETER, FieldName.ID));
- }
- return updateById(id, updateObj, Optional.ofNullable(permission));
- }
-
- public Mono<UpdateResult> updateById(String id, Update updateObj, Optional<AclPermission> permission) {
- Query query = new Query(Criteria.where("id").is(id));
-
- if (permission.isEmpty()) {
- return mongoOperations.updateFirst(query, updateObj, this.genericDomain);
- }
-
- return getCurrentUserPermissionGroupsIfRequired(permission, true).flatMap(permissionGroups -> {
- query.addCriteria(new Criteria().andOperator(notDeleted(), userAcl(permissionGroups, permission.get())));
- return mongoOperations.updateFirst(query, updateObj, this.genericDomain);
- });
- }
-
- public Mono<UpdateResult> updateByCriteria(
- List<Criteria> criteriaList, UpdateDefinition updateObj, AclPermission permission) {
- if (criteriaList == null) {
- return Mono.error(new AppsmithException(AppsmithError.INVALID_PARAMETER, "criteriaList"));
- }
- if (updateObj == null) {
- return Mono.error(new AppsmithException(AppsmithError.INVALID_PARAMETER, "updateObj"));
- }
- Mono<Set<String>> permissionGroupsMono =
- getCurrentUserPermissionGroupsIfRequired(Optional.ofNullable(permission), true);
-
- return permissionGroupsMono.flatMap(permissionGroups -> {
- Query queryWithPermission = createQueryWithPermission(criteriaList, permissionGroups, permission);
- return mongoOperations.updateMulti(queryWithPermission, updateObj, this.genericDomain);
- });
- }
-
protected Mono<Set<String>> getCurrentUserPermissionGroupsIfRequired(Optional<AclPermission> permission) {
return getCurrentUserPermissionGroupsIfRequired(permission, true);
}
@@ -382,6 +344,27 @@ public Mono<Long> countExecute(QueryAllParams<T> params) {
this.genericDomain));
}
+ public Mono<UpdateResult> updateAllExecute(@NonNull QueryAllParams<T> params, @NonNull UpdateDefinition update) {
+ Objects.requireNonNull(params.getCriteria());
+
+ if (!isEmpty(params.getFields())) {
+ // Specifying fields to update doesn't make any sense, so explicitly disallow it.
+ return Mono.error(new AppsmithException(AppsmithError.INVALID_PARAMETER, "fields"));
+ }
+
+ return tryGetPermissionGroups(params).flatMap(permissionGroups -> {
+ final Query query =
+ createQueryWithPermission(params.getCriteria(), null, permissionGroups, params.getPermission());
+ if (QueryAllParams.Scope.ALL.equals(params.getScope())) {
+ return mongoOperations.updateMulti(query, update, genericDomain);
+ } else if (QueryAllParams.Scope.FIRST.equals(params.getScope())) {
+ return mongoOperations.updateFirst(query, update, genericDomain);
+ } else {
+ return Mono.error(new AppsmithException(AppsmithError.INVALID_PARAMETER, "scope"));
+ }
+ });
+ }
+
private Mono<Set<String>> tryGetPermissionGroups(QueryAllParams<T> params) {
return Mono.justOrEmpty(params.getPermissionGroups())
.switchIfEmpty(Mono.defer(() -> getCurrentUserPermissionGroupsIfRequired(
diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/CustomActionCollectionRepositoryCEImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/CustomActionCollectionRepositoryCEImpl.java
index 249705a3de7b..9879191d39af 100644
--- a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/CustomActionCollectionRepositoryCEImpl.java
+++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/CustomActionCollectionRepositoryCEImpl.java
@@ -272,7 +272,7 @@ public Flux<ActionCollection> findAllUnpublishedActionCollectionsByContextIdAndC
where(contextIdPath).is(contextId).and(contextTypePath).is(contextType);
return queryBuilder()
.criteria(contextIdAndContextTypeCriteria)
- .permission(Optional.ofNullable(permission).orElse(null))
+ .permission(permission)
.all();
}
@@ -287,7 +287,7 @@ public Flux<ActionCollection> findAllPublishedActionCollectionsByContextIdAndCon
where(contextIdPath).is(contextId).and(contextTypePath).is(contextType);
return queryBuilder()
.criteria(contextIdAndContextTypeCriteria)
- .permission(Optional.ofNullable(permission).orElse(null))
+ .permission(permission)
.all();
}
diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/CustomApplicationRepositoryCEImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/CustomApplicationRepositoryCEImpl.java
index 03e68eb6280a..999bf9f31159 100644
--- a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/CustomApplicationRepositoryCEImpl.java
+++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/CustomApplicationRepositoryCEImpl.java
@@ -179,7 +179,7 @@ public Mono<UpdateResult> setGitAuth(String applicationId, GitAuth gitAuth, AclP
fieldName(QApplication.application.gitApplicationMetadata.gitAuth));
updateObj.set(path, gitAuth);
- return this.updateById(applicationId, updateObj, aclPermission);
+ return queryBuilder().byId(applicationId).permission(aclPermission).updateFirst(updateObj);
}
@Override
@@ -304,7 +304,7 @@ public Mono<UpdateResult> setAppTheme(
updateObj = updateObj.set(fieldName(QApplication.application.publishedModeThemeId), publishedModeThemeId);
}
- return this.updateById(applicationId, updateObj, aclPermission);
+ return queryBuilder().byId(applicationId).permission(aclPermission).updateFirst(updateObj);
}
@Override
@@ -379,7 +379,10 @@ public Mono<UpdateResult> unprotectAllBranches(String applicationId, AclPermissi
Update unsetProtected = new Update().set(isProtectedFieldPath, false);
- return updateByCriteria(List.of(defaultApplicationIdCriteria), unsetProtected, permission);
+ return queryBuilder()
+ .criteria(defaultApplicationIdCriteria)
+ .permission(permission)
+ .updateAll(unsetProtected);
}
/**
@@ -404,6 +407,9 @@ public Mono<UpdateResult> protectBranchedApplications(
Criteria branchMatchCriteria = Criteria.where(branchNameFieldPath).in(branchNames);
Update setProtected = new Update().set(isProtectedFieldPath, true);
- return updateByCriteria(List.of(defaultApplicationIdCriteria, branchMatchCriteria), setProtected, permission);
+ return queryBuilder()
+ .criteria(defaultApplicationIdCriteria, branchMatchCriteria)
+ .permission(permission)
+ .updateAll(setProtected);
}
}
diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/CustomNewActionRepositoryCEImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/CustomNewActionRepositoryCEImpl.java
index 20947d4b65ad..3ebbb685cb6f 100644
--- a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/CustomNewActionRepositoryCEImpl.java
+++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/CustomNewActionRepositoryCEImpl.java
@@ -624,7 +624,10 @@ public Mono<UpdateResult> archiveDeletedUnpublishedActions(String applicationId,
Update update = new Update();
update.set(FieldName.DELETED, true);
update.set(FieldName.DELETED_AT, Instant.now());
- return updateByCriteria(List.of(applicationIdCriteria, deletedFromUnpublishedCriteria), update, permission);
+ return queryBuilder()
+ .criteria(applicationIdCriteria, deletedFromUnpublishedCriteria)
+ .permission(permission)
+ .updateAll(update);
}
@Override
@@ -672,10 +675,7 @@ public Flux<NewAction> findAllUnpublishedActionsByContextIdAndContextType(
criteriaList.add(jsInclusionOrExclusionCriteria);
}
- return queryBuilder()
- .criteria(criteriaList)
- .permission(Optional.ofNullable(permission).orElse(null))
- .all();
+ return queryBuilder().criteria(criteriaList).permission(permission).all();
}
@Override
@@ -700,9 +700,6 @@ public Flux<NewAction> findAllPublishedActionsByContextIdAndContextType(
criteriaList.add(jsInclusionOrExclusionCriteria);
- return queryBuilder()
- .criteria(criteriaList)
- .permission(Optional.ofNullable(permission).orElse(null))
- .all();
+ return queryBuilder().criteria(criteriaList).permission(permission).all();
}
}
diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/CustomThemeRepositoryCEImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/CustomThemeRepositoryCEImpl.java
index 3173f012870f..4dadb94d2c75 100644
--- a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/CustomThemeRepositoryCEImpl.java
+++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/CustomThemeRepositoryCEImpl.java
@@ -17,7 +17,6 @@
import reactor.core.publisher.Mono;
import java.time.Instant;
-import java.util.List;
import java.util.regex.Pattern;
import static org.springframework.data.mongodb.core.query.Criteria.where;
@@ -75,7 +74,7 @@ private Mono<Boolean> archiveThemeByCriteria(Criteria criteria) {
Update update = new Update();
update.set(fieldName(QTheme.theme.deletedAt), Instant.now());
- return updateByCriteria(List.of(criteria, permissionCriteria), update, null);
+ return queryBuilder().criteria(criteria, permissionCriteria).updateAll(update);
})
.map(updateResult -> updateResult.getModifiedCount() > 0);
}
diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/params/QueryAllParams.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/params/QueryAllParams.java
index 3706c2abd260..f22c27a88644 100644
--- a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/params/QueryAllParams.java
+++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/params/QueryAllParams.java
@@ -4,9 +4,12 @@
import com.appsmith.server.acl.AclPermission;
import com.appsmith.server.constants.FieldName;
import com.appsmith.server.repositories.ce.BaseAppsmithRepositoryCEImpl;
+import com.mongodb.client.result.UpdateResult;
import lombok.Getter;
+import lombok.NonNull;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.query.Criteria;
+import org.springframework.data.mongodb.core.query.UpdateDefinition;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
@@ -36,6 +39,8 @@ public class QueryAllParams<T extends BaseDomain> {
*/
private boolean includeAnonymousUserPermissions = true;
+ private Scope scope;
+
public QueryAllParams(BaseAppsmithRepositoryCEImpl<T> repo) {
this.repo = repo;
}
@@ -56,6 +61,16 @@ public Mono<Long> count() {
return repo.countExecute(this);
}
+ public Mono<UpdateResult> updateAll(@NonNull UpdateDefinition update) {
+ scope = Scope.ALL;
+ return repo.updateAllExecute(this, update);
+ }
+
+ public Mono<UpdateResult> updateFirst(@NonNull UpdateDefinition update) {
+ scope = Scope.FIRST;
+ return repo.updateAllExecute(this, update);
+ }
+
public QueryAllParams<T> criteria(Criteria... criteria) {
if (criteria == null) {
return this;
@@ -117,4 +132,10 @@ public QueryAllParams<T> includeAnonymousUserPermissions(boolean value) {
includeAnonymousUserPermissions = value;
return this;
}
+
+ public enum Scope {
+ ALL,
+ FIRST,
+ ONE,
+ }
}
|
7443c16e59ae424677be7e738362feb0be0adefa
|
2022-03-24 16:50:43
|
akash-codemonk
|
fix: show the error message received from the server when sending test email fails (#11972)
| false
|
show the error message received from the server when sending test email fails (#11972)
|
fix
|
diff --git a/app/client/src/sagas/SuperUserSagas.tsx b/app/client/src/sagas/SuperUserSagas.tsx
index 1cc67b68691f..f633b22208f4 100644
--- a/app/client/src/sagas/SuperUserSagas.tsx
+++ b/app/client/src/sagas/SuperUserSagas.tsx
@@ -110,34 +110,32 @@ function* SendTestEmail(action: ReduxAction<SendTestEmailPayload>) {
try {
const response = yield call(UserApi.sendTestEmail, action.payload);
const currentUser = yield select(getCurrentUser);
- let actionElement;
- if (response.data) {
- actionElement = (
- <>
- <br />
- <span onClick={() => window.open(EMAIL_SETUP_DOC, "blank")}>
- {createMessage(TEST_EMAIL_SUCCESS_TROUBLESHOOT)}
- </span>
- </>
- );
+ const isValidResponse = yield validateResponse(response);
+
+ if (isValidResponse) {
+ let actionElement;
+ if (response.data) {
+ actionElement = (
+ <>
+ <br />
+ <span onClick={() => window.open(EMAIL_SETUP_DOC, "blank")}>
+ {createMessage(TEST_EMAIL_SUCCESS_TROUBLESHOOT)}
+ </span>
+ </>
+ );
+ }
+ Toaster.show({
+ actionElement,
+ text: createMessage(
+ response.data
+ ? TEST_EMAIL_SUCCESS(currentUser?.email)
+ : TEST_EMAIL_FAILURE,
+ ),
+ hideProgressBar: true,
+ variant: response.data ? Variant.info : Variant.danger,
+ });
}
- Toaster.show({
- actionElement,
- text: createMessage(
- response.data
- ? TEST_EMAIL_SUCCESS(currentUser?.email)
- : TEST_EMAIL_FAILURE,
- ),
- hideProgressBar: true,
- variant: response.data ? Variant.info : Variant.danger,
- });
- } catch (e) {
- Toaster.show({
- text: e?.message || createMessage(TEST_EMAIL_FAILURE),
- hideProgressBar: true,
- variant: Variant.danger,
- });
- }
+ } catch (e) {}
}
function* InitSuperUserSaga(action: ReduxAction<User>) {
|
59f91b618c79e3fb8931f9a4565215a72ae3f3e6
|
2022-07-13 19:24:05
|
Anand Srinivasan
|
fix: curl import error (#15178)
| false
|
curl import error (#15178)
|
fix
|
diff --git a/app/client/src/components/editorComponents/GlobalSearch/GlobalSearchHooks.tsx b/app/client/src/components/editorComponents/GlobalSearch/GlobalSearchHooks.tsx
index db7fd883a886..f0591ed4d955 100644
--- a/app/client/src/components/editorComponents/GlobalSearch/GlobalSearchHooks.tsx
+++ b/app/client/src/components/editorComponents/GlobalSearch/GlobalSearchHooks.tsx
@@ -136,11 +136,7 @@ export const useFilteredFileOperations = (query = "") => {
</EntityIcon>
),
kind: SEARCH_ITEM_TYPES.actionOperation,
- redirect: (
- applicationSlug: string,
- pageSlug: string,
- pageId: string,
- ) => {
+ redirect: (pageId: string) => {
history.push(
integrationEditorURL({
pageId,
diff --git a/app/client/src/pages/Editor/Explorer/Files/Submenu.tsx b/app/client/src/pages/Editor/Explorer/Files/Submenu.tsx
index 10e79924f099..65622f75cb39 100644
--- a/app/client/src/pages/Editor/Explorer/Files/Submenu.tsx
+++ b/app/client/src/pages/Editor/Explorer/Files/Submenu.tsx
@@ -8,11 +8,7 @@ import {
import styled from "constants/DefaultTheme";
import React, { useCallback, useEffect, useMemo, useState } from "react";
import { useDispatch, useSelector } from "react-redux";
-import {
- getCurrentPageId,
- selectCurrentApplicationSlug,
- selectPageSlugToIdMap,
-} from "selectors/editorSelectors";
+import { getCurrentPageId } from "selectors/editorSelectors";
import EntityAddButton from "../Entity/AddButton";
import { ReactComponent as SearchIcon } from "assets/icons/ads/search.svg";
import { ReactComponent as CrossIcon } from "assets/icons/ads/cross.svg";
@@ -66,8 +62,6 @@ export default function ExplorerSubMenu({
const [show, setShow] = useState(openMenu);
const fileOperations = useFilteredFileOperations(query);
const pageId = useSelector(getCurrentPageId);
- const applicationSlug = useSelector(selectCurrentApplicationSlug);
- const pageIdToSlugMap = useSelector(selectPageSlugToIdMap);
const dispatch = useDispatch();
const plugins = useSelector((state: AppState) => {
return state.entities.plugins.list;
@@ -128,12 +122,7 @@ export default function ExplorerSubMenu({
if (item.action) {
dispatch(item.action(pageId, "SUBMENU"));
} else if (item.redirect) {
- item.redirect(
- applicationSlug,
- pageIdToSlugMap[pageId],
- pageId,
- "SUBMENU",
- );
+ item.redirect(pageId, "SUBMENU");
}
setShow(false);
},
diff --git a/app/client/src/utils/AnalyticsUtil.tsx b/app/client/src/utils/AnalyticsUtil.tsx
index e0e16ea85722..903d95afd461 100644
--- a/app/client/src/utils/AnalyticsUtil.tsx
+++ b/app/client/src/utils/AnalyticsUtil.tsx
@@ -22,7 +22,8 @@ export type EventLocation =
| "QUERY_PANE"
| "QUERY_TEMPLATE"
| "QUICK_COMMANDS"
- | "OMNIBAR";
+ | "OMNIBAR"
+ | "SUBMENU";
export type EventName =
| "APP_CRASH"
|
4d74ed7a11ac44fa1152e52317e112efa821f09e
|
2023-11-24 18:14:22
|
Valera Melnikov
|
chore: remove redundant package (#29084)
| false
|
remove redundant package (#29084)
|
chore
|
diff --git a/app/client/packages/design-system/widgets-old/package.json b/app/client/packages/design-system/widgets-old/package.json
index 910f308dd0cf..90d7c6dbf8a4 100644
--- a/app/client/packages/design-system/widgets-old/package.json
+++ b/app/client/packages/design-system/widgets-old/package.json
@@ -16,7 +16,6 @@
"@types/react-form": "^4.0.2",
"@types/react-table": "*",
"@types/react-tabs": "*",
- "@types/wait-on": "^5.2.0",
"concurrently": "^7.3.0",
"eslint-config-react": "^1.1.7",
"eslint-plugin-storybook": "^0.6.8",
@@ -24,8 +23,7 @@
"playwright": "^1.25.1",
"postcss": "^8.4.31",
"postcss-import": "^14.1.0",
- "tsconfig-paths-webpack-plugin": "^3.5.2",
- "wait-on": "^5.3.0"
+ "tsconfig-paths-webpack-plugin": "^3.5.2"
},
"peerDependencies": {
"@blueprintjs/core": "3.33.0",
diff --git a/app/client/yarn.lock b/app/client/yarn.lock
index 4a8d2fc426b1..f6959fa3cfd1 100644
--- a/app/client/yarn.lock
+++ b/app/client/yarn.lock
@@ -3040,7 +3040,6 @@ __metadata:
"@types/react-form": ^4.0.2
"@types/react-table": "*"
"@types/react-tabs": "*"
- "@types/wait-on": ^5.2.0
concurrently: ^7.3.0
emoji-mart: 3.0.1
eslint-config-react: ^1.1.7
@@ -3050,7 +3049,6 @@ __metadata:
postcss: ^8.4.31
postcss-import: ^14.1.0
tsconfig-paths-webpack-plugin: ^3.5.2
- wait-on: ^5.3.0
peerDependencies:
"@blueprintjs/core": 3.33.0
"@blueprintjs/datetime": 3.23.6
@@ -3966,22 +3964,6 @@ __metadata:
languageName: node
linkType: hard
-"@hapi/hoek@npm:^9.0.0":
- version: 9.3.0
- resolution: "@hapi/hoek@npm:9.3.0"
- checksum: 4771c7a776242c3c022b168046af4e324d116a9d2e1d60631ee64f474c6e38d1bb07092d898bf95c7bc5d334c5582798a1456321b2e53ca817d4e7c88bc25b43
- languageName: node
- linkType: hard
-
-"@hapi/topo@npm:^5.0.0":
- version: 5.1.0
- resolution: "@hapi/topo@npm:5.1.0"
- dependencies:
- "@hapi/hoek": ^9.0.0
- checksum: 604dfd5dde76d5c334bd03f9001fce69c7ce529883acf92da96f4fe7e51221bf5e5110e964caca287a6a616ba027c071748ab636ff178ad750547fba611d6014
- languageName: node
- linkType: hard
-
"@humanwhocodes/config-array@npm:^0.11.11":
version: 0.11.11
resolution: "@humanwhocodes/config-array@npm:0.11.11"
@@ -7568,29 +7550,6 @@ __metadata:
languageName: unknown
linkType: soft
-"@sideway/address@npm:^4.1.3":
- version: 4.1.4
- resolution: "@sideway/address@npm:4.1.4"
- dependencies:
- "@hapi/hoek": ^9.0.0
- checksum: b9fca2a93ac2c975ba12e0a6d97853832fb1f4fb02393015e012b47fa916a75ca95102d77214b2a29a2784740df2407951af8c5dde054824c65577fd293c4cdb
- languageName: node
- linkType: hard
-
-"@sideway/formula@npm:^3.0.1":
- version: 3.0.1
- resolution: "@sideway/formula@npm:3.0.1"
- checksum: e4beeebc9dbe2ff4ef0def15cec0165e00d1612e3d7cea0bc9ce5175c3263fc2c818b679bd558957f49400ee7be9d4e5ac90487e1625b4932e15c4aa7919c57a
- languageName: node
- linkType: hard
-
-"@sideway/pinpoint@npm:^2.0.0":
- version: 2.0.0
- resolution: "@sideway/pinpoint@npm:2.0.0"
- checksum: 0f4491e5897fcf5bf02c46f5c359c56a314e90ba243f42f0c100437935daa2488f20482f0f77186bd6bf43345095a95d8143ecf8b1f4d876a7bc0806aba9c3d2
- languageName: node
- linkType: hard
-
"@sinclair/typebox@npm:^0.23.3":
version: 0.23.5
resolution: "@sinclair/typebox@npm:0.23.5"
@@ -10814,15 +10773,6 @@ __metadata:
languageName: node
linkType: hard
-"@types/wait-on@npm:^5.2.0":
- version: 5.3.1
- resolution: "@types/wait-on@npm:5.3.1"
- dependencies:
- "@types/node": "*"
- checksum: 2a6e88a107930963ceea016dc733dc259dc52faf864933cd4d6f7fc6db7165254c10f8bfcb3b803237b2869674d988319ea4f958c0b6fd3763c5fcb9e489565a
- languageName: node
- linkType: hard
-
"@types/web@npm:^0.0.99":
version: 0.0.99
resolution: "@types/web@npm:0.0.99"
@@ -13016,15 +12966,6 @@ __metadata:
languageName: node
linkType: hard
-"axios@npm:^0.21.1":
- version: 0.21.4
- resolution: "axios@npm:0.21.4"
- dependencies:
- follow-redirects: ^1.14.0
- checksum: 44245f24ac971e7458f3120c92f9d66d1fc695e8b97019139de5b0cc65d9b8104647db01e5f46917728edfc0cfd88eb30fc4c55e6053eef4ace76768ce95ff3c
- languageName: node
- linkType: hard
-
"axios@npm:^1.6.0":
version: 1.6.1
resolution: "axios@npm:1.6.1"
@@ -18927,7 +18868,7 @@ __metadata:
languageName: node
linkType: hard
-"follow-redirects@npm:^1.0.0, follow-redirects@npm:^1.14.0, follow-redirects@npm:^1.15.0":
+"follow-redirects@npm:^1.0.0, follow-redirects@npm:^1.15.0":
version: 1.15.2
resolution: "follow-redirects@npm:1.15.2"
peerDependenciesMeta:
@@ -22575,19 +22516,6 @@ __metadata:
languageName: node
linkType: hard
-"joi@npm:^17.3.0":
- version: 17.9.2
- resolution: "joi@npm:17.9.2"
- dependencies:
- "@hapi/hoek": ^9.0.0
- "@hapi/topo": ^5.0.0
- "@sideway/address": ^4.1.3
- "@sideway/formula": ^3.0.1
- "@sideway/pinpoint": ^2.0.0
- checksum: 8c3709849293411c524e5a679dba7b42598a29a663478941767b8d5b06288611dece58803c468a2c7320cc2429a3e71e3d94337fe47aefcf6c22174dbd90b601
- languageName: node
- linkType: hard
-
"js-beautify@npm:^1.14.0":
version: 1.14.0
resolution: "js-beautify@npm:1.14.0"
@@ -29839,7 +29767,7 @@ __metadata:
languageName: node
linkType: hard
-"rxjs@npm:^6.4.0, rxjs@npm:^6.6.0, rxjs@npm:^6.6.3, rxjs@npm:^6.6.7":
+"rxjs@npm:^6.4.0, rxjs@npm:^6.6.0, rxjs@npm:^6.6.7":
version: 6.6.7
resolution: "rxjs@npm:6.6.7"
dependencies:
@@ -33274,21 +33202,6 @@ __metadata:
languageName: node
linkType: hard
-"wait-on@npm:^5.3.0":
- version: 5.3.0
- resolution: "wait-on@npm:5.3.0"
- dependencies:
- axios: ^0.21.1
- joi: ^17.3.0
- lodash: ^4.17.21
- minimist: ^1.2.5
- rxjs: ^6.6.3
- bin:
- wait-on: bin/wait-on
- checksum: b7099104b7900ff6349f1196edff759076ab557a2053c017a587819f7a59f146ec9e35c99579acd31dcda371bfa72241ef28b8ccda902f0bf3fbf2d780a00ebf
- languageName: node
- linkType: hard
-
"walker@npm:^1.0.7, walker@npm:^1.0.8":
version: 1.0.8
resolution: "walker@npm:1.0.8"
|
645d38bdaa2b4e80b5b3812fadb75105931afd99
|
2023-12-28 15:37:24
|
Aman Agarwal
|
feat: added onboarding flow for admin users (#29872)
| false
|
added onboarding flow for admin users (#29872)
|
feat
|
diff --git a/app/client/src/pages/setup/SignupSuccess.tsx b/app/client/src/pages/setup/SignupSuccess.tsx
index 8c4d69653c58..9ebd5e8af42e 100644
--- a/app/client/src/pages/setup/SignupSuccess.tsx
+++ b/app/client/src/pages/setup/SignupSuccess.tsx
@@ -39,8 +39,7 @@ export function SignupSuccess() {
user?.email && setUserSignedUpFlag(user?.email);
}, []);
- const isNonInvitedAndNonAdminUser =
- !user?.isSuperUser && shouldEnableFirstTimeUserOnboarding === "true";
+ const isNonInvitedUser = shouldEnableFirstTimeUserOnboarding === "true";
const redirectUsingQueryParam = useCallback(
() =>
@@ -50,7 +49,7 @@ export function SignupSuccess() {
validLicense,
dispatch,
showStarterTemplatesInsteadofBlankCanvas,
- isNonInvitedAndNonAdminUser && isEnabledForCreateNew,
+ isNonInvitedUser && isEnabledForCreateNew,
),
[],
);
|
82c5c0b58027f3b15a69809701abc7fac88570d7
|
2023-07-07 10:01:43
|
Goutham Pratapa
|
chore: update init-container images and update probes (#23401)
| false
|
update init-container images and update probes (#23401)
|
chore
|
diff --git a/deploy/helm/Chart.yaml b/deploy/helm/Chart.yaml
index 9e9eeacb0a59..e3c4ea2a9446 100644
--- a/deploy/helm/Chart.yaml
+++ b/deploy/helm/Chart.yaml
@@ -11,7 +11,7 @@ sources:
- https://github.com/appsmithorg/appsmith
home: https://www.appsmith.com/
icon: https://assets.appsmith.com/appsmith-icon.png
-version: 2.0.2
+version: 2.0.3
dependencies:
- condition: redis.enabled
name: redis
diff --git a/deploy/helm/templates/NOTES.txt b/deploy/helm/templates/NOTES.txt
index 17f6147c106e..61e648b7e248 100644
--- a/deploy/helm/templates/NOTES.txt
+++ b/deploy/helm/templates/NOTES.txt
@@ -26,5 +26,5 @@ Please update your DNS records with your domain by the address. You can use foll
echo "Visit http://127.0.0.1:8080 to use your application"
kubectl --namespace {{ .Release.Namespace }} port-forward $POD_NAME 8080:$CONTAINER_PORT
-To expose your Appsmith service to be accessible from the Internet, please refer to our docs here https://docs.appsmith.com/setup/kubernetes#expose-appsmith.
+To expose your Appsmith service to be accessible from the Internet, please refer to our docs here https://docs.appsmith.com/getting-started/setup/installation-guides/kubernetes/publish-appsmith-online.
{{- end }}
diff --git a/deploy/helm/templates/statefulset.yaml b/deploy/helm/templates/statefulset.yaml
index 17d89639b4fb..9e6ad7f0d650 100644
--- a/deploy/helm/templates/statefulset.yaml
+++ b/deploy/helm/templates/statefulset.yaml
@@ -49,16 +49,16 @@ spec:
{{- if ((.Values.initContainer.redis).image) }}
image: {{ .Values.initContainer.redis.image }}
{{- else }}
- image: "alpine"
+ image: "docker.io/library/redis:6.2-alpine"
{{- end }}
- command: ['sh', '-c', "apk add redis; until redis-cli -h {{ include "appsmith.fullname" . }}-redis-master.{{.Release.Namespace}}.svc.cluster.local ping; do echo waiting for redis; sleep 2; done"]
+ command: ['sh', '-c', "until redis-cli -h {{ include "appsmith.fullname" . }}-redis-master.{{.Release.Namespace}}.svc.cluster.local ping ; do echo waiting for redis; sleep 2; done"]
{{- end }}
{{- if .Values.mongodb.enabled }}
- name: mongo-init-container
{{- if ((.Values.initContainer.mongodb).image) }}
image: {{ .Values.initContainer.mongodb.image }}
{{- else }}
- image: "docker.io/bitnami/mongodb:4.4.11-debian-10-r12"
+ image: "docker.io/bitnami/mongodb:5.0.17-debian-11-r5"
{{- end }}
command: ['sh', '-c', "until mongo --host appsmith-mongodb.{{.Release.Namespace}}.svc.cluster.local --eval 'db.runCommand({ping:1})' ; do echo waiting for mongo; sleep 2; done"]
{{- end }}
@@ -78,19 +78,26 @@ spec:
- name: supervisord
containerPort: 9001
protocol: TCP
+ {{- $probes := .Values.probes | default dict }}
startupProbe:
# The `livenessProbe` and `readinessProbe` will be disabled until the `startupProbe` is successful.
httpGet:
- path: /
port: http
+ path: {{ dig "startupProbe" "api" "/api/v1/health" $probes }}
+ failureThreshold: {{ dig "startupProbe" "failureThreshold" 3 $probes }}
+ periodSeconds: {{ dig "startupProbe" "periodSeconds" 60 $probes }}
livenessProbe:
httpGet:
- path: /
port: http
+ path: {{ dig "livenessProbe" "api" "/api/v1/health" $probes }}
+ failureThreshold: {{ dig "livenessProbe" "failureThreshold" 3 $probes }}
+ periodSeconds: {{ dig "livenessProbe" "periodSeconds" 60 $probes }}
readinessProbe:
httpGet:
- path: /api/v1/users/me
port: http
+ path: {{ dig "readinessProbe" "api" "/api/v1/health" $probes }}
+ failureThreshold: {{ dig "readinessProbe" "failureThreshold" 3 $probes }}
+ periodSeconds: {{ dig "readinessProbe" "periodSeconds" 60 $probes }}
resources:
{{- toYaml .Values.resources | nindent 12 }}
volumeMounts:
|
8724f1c4fa17745b7fe6463b2d3cdebacc2504fa
|
2022-07-20 11:35:44
|
Aswath K
|
fix: Unwanted width calculation in Dropdown (#15239)
| false
|
Unwanted width calculation in Dropdown (#15239)
|
fix
|
diff --git a/app/client/src/components/ads/Dropdown.tsx b/app/client/src/components/ads/Dropdown.tsx
index a48a4f5b976f..b8456d5dfe83 100644
--- a/app/client/src/components/ads/Dropdown.tsx
+++ b/app/client/src/components/ads/Dropdown.tsx
@@ -21,7 +21,7 @@ import { TooltipComponent as Tooltip } from "design-system";
import { isEllipsisActive } from "utils/helpers";
import SegmentHeader from "components/ads/ListSegmentHeader";
import { useTheme } from "styled-components";
-import { findIndex, isArray } from "lodash";
+import { debounce, findIndex, isArray } from "lodash";
import { TooltipComponent } from "design-system";
import { SubTextPosition } from "components/constants";
import { DSEventTypes, emitDSEvent } from "utils/AppsmithUtils";
@@ -1149,12 +1149,36 @@ export default function Dropdown(props: DropdownProps) {
[isOpen, props.options, props.selected, selected, highlight],
);
- let dropdownWrapperWidth = "100%";
+ const [dropdownWrapperWidth, setDropdownWrapperWidth] = useState<string>(
+ "100%",
+ );
- if (dropdownWrapperRef.current) {
- const { width } = dropdownWrapperRef.current.getBoundingClientRect();
- dropdownWrapperWidth = `${width}px`;
- }
+ 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) {
diff --git a/app/client/test/setup.ts b/app/client/test/setup.ts
index ceac3d56d573..731fd9bbb1b2 100644
--- a/app/client/test/setup.ts
+++ b/app/client/test/setup.ts
@@ -14,6 +14,7 @@ const mockObserveFn = () => {
};
window.IntersectionObserver = jest.fn().mockImplementation(mockObserveFn);
+window.ResizeObserver = jest.fn().mockImplementation(mockObserveFn);
// establish API mocking before all tests
beforeAll(() => server.listen());
|
58a2632f75da211778ae1ae4f926cc5ed197f593
|
2022-10-24 11:04:55
|
Rimil Dey
|
chore: move render field to component (#17084)
| false
|
move render field to component (#17084)
|
chore
|
diff --git a/app/client/src/components/editorComponents/ActionCreator/Field/Field.test.tsx b/app/client/src/components/editorComponents/ActionCreator/Field/Field.test.tsx
new file mode 100644
index 000000000000..a16bb44ce7ad
--- /dev/null
+++ b/app/client/src/components/editorComponents/ActionCreator/Field/Field.test.tsx
@@ -0,0 +1,200 @@
+import { render, screen } from "@testing-library/react";
+import "@testing-library/jest-dom";
+import React from "react";
+import { Field } from "./index";
+import { ThemeProvider } from "constants/DefaultTheme";
+import { lightTheme } from "selectors/themeSelectors";
+import { FieldType } from "../constants";
+import { FIELD_CONFIG } from "../FieldConfig";
+
+describe("Field component", () => {
+ const commonProps = {
+ activeNavigateToTab: {
+ action: () => {
+ return null;
+ },
+ id: "page-name",
+ text: "Page Name",
+ },
+ depth: 1,
+ integrationOptionTree: [],
+ maxDepth: 0,
+ modalDropdownList: [],
+ navigateToSwitches: [
+ {
+ id: "page-name",
+ text: "Page Name",
+ action: () => {
+ return null;
+ },
+ },
+ {
+ id: "url",
+ text: "URL",
+ action: () => {
+ return null;
+ },
+ },
+ ],
+ onValueChange: () => {
+ return null;
+ },
+ pageDropdownOptions: [
+ { id: "62d8f2ed3e80f46c3ac16df6", label: "Page1", value: "'Page1'" },
+ ],
+ widgetOptionTree: [],
+ };
+ const tests = [
+ {
+ field: FieldType.ACTION_SELECTOR_FIELD,
+ value: "",
+ testId: null,
+ },
+ {
+ field: FieldType.ALERT_TEXT_FIELD,
+ value: "{{showAlert()}}",
+ testId: "text-view-label",
+ },
+ {
+ field: FieldType.ALERT_TYPE_SELECTOR_FIELD,
+ value: "{{showAlert()}}",
+ testId: "selector-view-label",
+ },
+ {
+ field: FieldType.KEY_TEXT_FIELD,
+ value: "{{storeValue()}}",
+ testId: "text-view-label",
+ },
+ {
+ field: FieldType.VALUE_TEXT_FIELD,
+ value: "{{storeValue()}}",
+ testId: "text-view-label",
+ },
+ {
+ field: FieldType.QUERY_PARAMS_FIELD,
+ value: "{{navigateTo('', {}, 'SAME_WINDOW')}}",
+ testId: "text-view-label",
+ },
+ {
+ field: FieldType.DOWNLOAD_DATA_FIELD,
+ value: "{{download()}}",
+ testId: "text-view-label",
+ },
+ {
+ field: FieldType.DOWNLOAD_FILE_NAME_FIELD,
+ value: "{{download()}}",
+ testId: "text-view-label",
+ },
+ {
+ field: FieldType.COPY_TEXT_FIELD,
+ value: "{{copyToClipboard()}}",
+ testId: "text-view-label",
+ },
+ {
+ field: FieldType.NAVIGATION_TARGET_FIELD,
+ value: "{{navigateTo('', {}, 'SAME_WINDOW')}}",
+ testId: "selector-view-label",
+ },
+ {
+ field: FieldType.WIDGET_NAME_FIELD,
+ value: "{{resetWidget()}}",
+ testId: "selector-view-label",
+ },
+ {
+ field: FieldType.RESET_CHILDREN_FIELD,
+ value: "{{resetWidget()}}",
+ testId: "selector-view-label",
+ },
+ {
+ field: FieldType.CALLBACK_FUNCTION_FIELD,
+ value: "{{setInterval()}}",
+ testId: "text-view-label",
+ },
+ {
+ field: FieldType.DELAY_FIELD,
+ value: "{{setInterval()}}",
+ testId: "text-view-label",
+ },
+ {
+ field: FieldType.ID_FIELD,
+ value: "{{setInterval()}}",
+ testId: "text-view-label",
+ },
+ {
+ field: FieldType.CLEAR_INTERVAL_ID_FIELD,
+ value: "{{clearInterval()}}",
+ testId: "text-view-label",
+ },
+ {
+ field: FieldType.PAGE_NAME_AND_URL_TAB_SELECTOR_FIELD,
+ value: "{{navigateTo('', {}, 'SAME_WINDOW')}}",
+ testId: "tabs-label",
+ },
+ {
+ field: FieldType.URL_FIELD,
+ value: "{{navigateTo('', {}, 'SAME_WINDOW')}}",
+ testId: "text-view-label",
+ },
+ {
+ field: FieldType.DOWNLOAD_FILE_TYPE_FIELD,
+ value: "{{download()}}",
+ testId: "selector-view-label",
+ },
+ {
+ field: FieldType.PAGE_SELECTOR_FIELD,
+ value: "{{navigateTo('', {}, 'SAME_WINDOW')}}",
+ testId: "selector-view-label",
+ },
+ {
+ field: FieldType.CLOSE_MODAL_FIELD,
+ value: "{{closeModal()}}",
+ testId: "selector-view-label",
+ },
+ {
+ field: FieldType.SHOW_MODAL_FIELD,
+ value: "{{showModal()}}",
+ testId: "selector-view-label",
+ },
+ ];
+
+ it("renders the component", () => {
+ const props = {
+ value: "{{download()}}",
+ ...commonProps,
+ field: {
+ field: FieldType.DOWNLOAD_FILE_TYPE_FIELD,
+ },
+ };
+ render(
+ <ThemeProvider theme={lightTheme}>
+ <Field {...props} />
+ </ThemeProvider>,
+ );
+ });
+
+ test.each(tests.map((x, index) => [index, x.field, x.value, x.testId]))(
+ "test case %d",
+ (index, field, value, testId) => {
+ const props = {
+ ...commonProps,
+ field: {
+ field: field as FieldType,
+ },
+ value: value as string,
+ };
+ const expectedLabel = FIELD_CONFIG[field as FieldType].label(props);
+ const expectedDefaultText = FIELD_CONFIG[field as FieldType].defaultText;
+ render(
+ <ThemeProvider theme={lightTheme}>
+ <Field {...props} />
+ </ThemeProvider>,
+ );
+ if (testId && expectedLabel) {
+ expect(screen.getByTestId(testId)).toHaveTextContent(expectedLabel);
+ }
+ if (expectedDefaultText) {
+ expect(screen.getByText(expectedDefaultText)).toBeInTheDocument();
+ }
+ },
+ );
+});
diff --git a/app/client/src/components/editorComponents/ActionCreator/Field/index.tsx b/app/client/src/components/editorComponents/ActionCreator/Field/index.tsx
new file mode 100644
index 000000000000..8411ce4d7699
--- /dev/null
+++ b/app/client/src/components/editorComponents/ActionCreator/Field/index.tsx
@@ -0,0 +1,198 @@
+import { AppsmithFunction, FieldType, ViewTypes } from "../constants";
+import { TreeDropdownOption } from "design-system";
+import {
+ FieldProps,
+ KeyValueViewProps,
+ SelectorViewProps,
+ TabViewProps,
+ TextViewProps,
+} from "../types";
+import HightlightedCode from "../../HighlightedCode";
+import { Skin } from "../../../../constants/DefaultTheme";
+import { DropdownOption } from "../../../constants";
+import React from "react";
+import { SelectorView } from "../viewComponents/SelectorView";
+import { KeyValueView } from "../viewComponents/KeyValueView";
+import { TextView } from "../viewComponents/TextView";
+import { TabView } from "../viewComponents/TabView";
+import { FIELD_CONFIG } from "../FieldConfig";
+
+const views = {
+ [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} />,
+ // eslint-disable-next-line react/jsx-no-useless-fragment
+ [ViewTypes.NO_VIEW]: () => <></>,
+};
+
+export function Field(props: FieldProps) {
+ const { field } = props;
+ const fieldType = field.field;
+ const fieldConfig = FIELD_CONFIG[fieldType];
+ // eslint-disable-next-line react/jsx-no-useless-fragment
+ if (!fieldConfig) return <></>;
+ let viewElement: JSX.Element | null = null;
+ const view = fieldConfig.view && views[fieldConfig.view];
+ const label = FIELD_CONFIG[fieldType].label(props);
+ const getterFunction = fieldConfig.getter;
+ const value = props.value;
+ const defaultText = FIELD_CONFIG[fieldType].defaultText;
+ const options = FIELD_CONFIG[fieldType].options(props);
+ const toolTip = FIELD_CONFIG[fieldType].toolTip;
+
+ switch (fieldType) {
+ case FieldType.ACTION_SELECTOR_FIELD:
+ viewElement = (view as (props: SelectorViewProps) => JSX.Element)({
+ options: options as TreeDropdownOption[],
+ label: label,
+ get: getterFunction,
+ set: (
+ value: TreeDropdownOption,
+ defaultValue?: string,
+ isUpdatedViaKeyboard = false,
+ ) => {
+ const finalValueToSet = fieldConfig.setter(value, "");
+ props.onValueChange(finalValueToSet, isUpdatedViaKeyboard);
+ },
+ value: value,
+ defaultText: defaultText,
+ getDefaults: (value: string) => {
+ return {
+ [AppsmithFunction.navigateTo]: `'${props.pageDropdownOptions[0].label}'`,
+ }[value];
+ },
+ selectedLabelModifier: (
+ option: TreeDropdownOption,
+ displayValue?: string,
+ ) => {
+ if (option.type === AppsmithFunction.integration) {
+ return (
+ <HightlightedCode
+ codeText={`{{${option.label}.run()}}`}
+ skin={Skin.LIGHT}
+ />
+ );
+ } else if (displayValue) {
+ return (
+ <HightlightedCode codeText={displayValue} skin={Skin.LIGHT} />
+ );
+ }
+ return <span>{option.label}</span>;
+ },
+ displayValue:
+ field.value !== "{{undefined}}" &&
+ field.value !== "{{()}}" &&
+ field.value !== "{{{}, ()}}"
+ ? field.value
+ : undefined,
+ });
+ break;
+ case FieldType.ON_SUCCESS_FIELD:
+ case FieldType.ON_ERROR_FIELD:
+ case FieldType.SHOW_MODAL_FIELD:
+ case FieldType.CLOSE_MODAL_FIELD:
+ case FieldType.PAGE_SELECTOR_FIELD:
+ case FieldType.ALERT_TYPE_SELECTOR_FIELD:
+ case FieldType.DOWNLOAD_FILE_TYPE_FIELD:
+ case FieldType.NAVIGATION_TARGET_FIELD:
+ case FieldType.RESET_CHILDREN_FIELD:
+ case FieldType.WIDGET_NAME_FIELD:
+ viewElement = (view as (props: SelectorViewProps) => JSX.Element)({
+ options: options as TreeDropdownOption[],
+ label: label,
+ get: getterFunction,
+ set: (
+ value: TreeDropdownOption,
+ defaultValue?: string,
+ isUpdatedViaKeyboard = false,
+ ) => {
+ const finalValueToSet = fieldConfig.setter(
+ value,
+ props.value,
+ isUpdatedViaKeyboard,
+ );
+ props.onValueChange(finalValueToSet, isUpdatedViaKeyboard);
+ },
+ value: value,
+ defaultText: defaultText,
+ });
+ break;
+ case FieldType.PAGE_NAME_AND_URL_TAB_SELECTOR_FIELD:
+ viewElement = (view as (props: TabViewProps) => JSX.Element)({
+ activeObj: props.activeNavigateToTab,
+ switches: props.navigateToSwitches,
+ label: label,
+ value: value,
+ });
+ break;
+ case FieldType.ARGUMENT_KEY_VALUE_FIELD:
+ viewElement = (view as (props: TextViewProps) => JSX.Element)({
+ label: label,
+ get: getterFunction,
+ set: (value: string) => {
+ const finalValueToSet = fieldConfig.setter(
+ value,
+ props.value,
+ props.field.index,
+ );
+ props.onValueChange(finalValueToSet, false);
+ },
+ index: props.field.index,
+ value: value || "",
+ });
+ break;
+ case FieldType.KEY_VALUE_FIELD:
+ viewElement = (view as (props: SelectorViewProps) => JSX.Element)({
+ options: options as TreeDropdownOption[],
+ label: label,
+ get: getterFunction,
+ set: (value: string | DropdownOption) => {
+ const finalValueToSet = fieldConfig.setter(value, props.value);
+ props.onValueChange(finalValueToSet, false);
+ },
+ value: value,
+ defaultText: defaultText,
+ });
+ break;
+ case FieldType.ALERT_TEXT_FIELD:
+ case FieldType.URL_FIELD:
+ case FieldType.KEY_TEXT_FIELD:
+ case FieldType.VALUE_TEXT_FIELD:
+ case FieldType.QUERY_PARAMS_FIELD:
+ case FieldType.DOWNLOAD_DATA_FIELD:
+ case FieldType.DOWNLOAD_FILE_NAME_FIELD:
+ case FieldType.COPY_TEXT_FIELD:
+ case FieldType.CALLBACK_FUNCTION_FIELD:
+ case FieldType.DELAY_FIELD:
+ case FieldType.ID_FIELD:
+ case FieldType.CLEAR_INTERVAL_ID_FIELD:
+ case FieldType.MESSAGE_FIELD:
+ case FieldType.TARGET_ORIGIN_FIELD:
+ case FieldType.SOURCE_FIELD:
+ viewElement = (view as (props: TextViewProps) => JSX.Element)({
+ label: label,
+ toolTip: toolTip,
+ get: getterFunction,
+ set: (value: string | DropdownOption, isUpdatedViaKeyboard = false) => {
+ const finalValueToSet = fieldConfig.setter(value, props.value);
+ props.onValueChange(finalValueToSet, isUpdatedViaKeyboard);
+ },
+ value: value,
+ additionalAutoComplete: props.additionalAutoComplete,
+ });
+ break;
+ default:
+ break;
+ }
+
+ return (
+ <div data-guided-tour-iid={field.label} key={fieldType}>
+ {viewElement}
+ </div>
+ );
+}
diff --git a/app/client/src/components/editorComponents/ActionCreator/FieldConfig.ts b/app/client/src/components/editorComponents/ActionCreator/FieldConfig.ts
new file mode 100644
index 000000000000..405eecf1f2b3
--- /dev/null
+++ b/app/client/src/components/editorComponents/ActionCreator/FieldConfig.ts
@@ -0,0 +1,424 @@
+import {
+ AppsmithFunction,
+ FieldType,
+ FILE_TYPE_OPTIONS,
+ NAVIGATION_TARGET_FIELD_OPTIONS,
+ RESET_CHILDREN_OPTIONS,
+ ViewTypes,
+} from "./constants";
+import { ALERT_STYLE_OPTIONS } from "../../../ce/constants/messages";
+import { ActionType, AppsmithFunctionConfigType, FieldProps } from "./types";
+import {
+ enumTypeGetter,
+ enumTypeSetter,
+ modalGetter,
+ modalSetter,
+ textGetter,
+ textSetter,
+} from "./utils";
+import store from "../../../store";
+import { getPageList } from "../../../selectors/entitiesSelector";
+import { ACTION_TRIGGER_REGEX } from "./regex";
+import { TreeDropdownOption } from "design-system";
+
+export const FIELD_CONFIG: AppsmithFunctionConfigType = {
+ [FieldType.ACTION_SELECTOR_FIELD]: {
+ label: (props: FieldProps) => props.label || "",
+ options: (props: FieldProps) => props.integrationOptionTree,
+ defaultText: "Select Action",
+ getter: (storedValue: string) => {
+ let matches: any[] = [];
+ if (storedValue) {
+ matches = storedValue
+ ? [...storedValue.matchAll(ACTION_TRIGGER_REGEX)]
+ : [];
+ }
+ let mainFuncSelectedValue = AppsmithFunction.none;
+ if (matches.length) {
+ mainFuncSelectedValue = matches[0][1] || AppsmithFunction.none;
+ }
+ const mainFuncSelectedValueSplit = mainFuncSelectedValue.split(".");
+ if (mainFuncSelectedValueSplit[1] === "run") {
+ return mainFuncSelectedValueSplit[0];
+ }
+ return mainFuncSelectedValue;
+ },
+ setter: (option) => {
+ const dropdownOption = option as TreeDropdownOption;
+ const type: ActionType = dropdownOption.type || dropdownOption.value;
+ let value = dropdownOption.value;
+ let defaultParams = "";
+ let defaultArgs: Array<any> = [];
+ switch (type) {
+ case AppsmithFunction.integration:
+ value = `${value}.run`;
+ break;
+ case AppsmithFunction.navigateTo:
+ defaultParams = `'', {}, 'SAME_WINDOW'`;
+ break;
+ case AppsmithFunction.jsFunction:
+ defaultArgs = dropdownOption.args ? dropdownOption.args : [];
+ break;
+ case AppsmithFunction.setInterval:
+ defaultParams = "() => { \n\t // add code here \n}, 5000";
+ break;
+ case AppsmithFunction.getGeolocation:
+ defaultParams = "(location) => { \n\t // add code here \n }";
+ break;
+ case AppsmithFunction.resetWidget:
+ defaultParams = `"",true`;
+ break;
+ case AppsmithFunction.postMessage:
+ defaultParams = `'', 'window', '*'`;
+ break;
+ default:
+ break;
+ }
+ return value === "none"
+ ? ""
+ : defaultArgs && defaultArgs.length
+ ? `{{${value}(${defaultArgs})}}`
+ : `{{${value}(${defaultParams})}}`;
+ },
+ view: ViewTypes.SELECTOR_VIEW,
+ },
+ [FieldType.ALERT_TEXT_FIELD]: {
+ label: () => "Message",
+ defaultText: "",
+ options: () => null,
+ getter: (value: string) => {
+ return textGetter(value, 0);
+ },
+ setter: (value, currentValue) => {
+ return textSetter(value, currentValue, 0);
+ },
+ view: ViewTypes.TEXT_VIEW,
+ },
+ [FieldType.URL_FIELD]: {
+ label: () => "Enter URL",
+ defaultText: "",
+ options: () => null,
+ getter: (value: string) => {
+ const appState = store.getState();
+ const pageList = getPageList(appState).map((page) => page.pageName);
+ const urlFieldValue = textGetter(value, 0);
+ return pageList.includes(urlFieldValue) ? "" : urlFieldValue;
+ },
+ setter: (value, currentValue) => {
+ return textSetter(value, currentValue, 0);
+ },
+ view: ViewTypes.TEXT_VIEW,
+ },
+ [FieldType.QUERY_PARAMS_FIELD]: {
+ label: () => "Query Params",
+ defaultText: "",
+ options: () => null,
+ getter: (value: any) => {
+ return textGetter(value, 1);
+ },
+ setter: (value: any, currentValue: string) => {
+ if (value === "") {
+ value = undefined;
+ }
+ return textSetter(value, currentValue, 1);
+ },
+ view: ViewTypes.TEXT_VIEW,
+ },
+ [FieldType.KEY_TEXT_FIELD]: {
+ label: () => "Key",
+ defaultText: "",
+ options: () => null,
+ getter: (value: any) => {
+ return textGetter(value, 0);
+ },
+ setter: (option: any, currentValue: string) => {
+ return textSetter(option, currentValue, 0);
+ },
+ view: ViewTypes.TEXT_VIEW,
+ },
+ [FieldType.VALUE_TEXT_FIELD]: {
+ label: () => "Value",
+ defaultText: "",
+ options: () => null,
+ getter: (value: any) => {
+ return textGetter(value, 1);
+ },
+ setter: (option: any, currentValue: string) => {
+ return textSetter(option, currentValue, 1);
+ },
+ view: ViewTypes.TEXT_VIEW,
+ },
+ [FieldType.DOWNLOAD_DATA_FIELD]: {
+ label: () => "Data to download",
+ defaultText: "",
+ options: () => null,
+ getter: (value: any) => {
+ return textGetter(value, 0);
+ },
+ setter: (option: any, currentValue: string) => {
+ return textSetter(option, currentValue, 0);
+ },
+ view: ViewTypes.TEXT_VIEW,
+ },
+ [FieldType.DOWNLOAD_FILE_NAME_FIELD]: {
+ label: () => "File name with extension",
+ defaultText: "",
+ options: () => null,
+ getter: (value: any) => {
+ return textGetter(value, 1);
+ },
+ setter: (option: any, currentValue: string) => {
+ return textSetter(option, currentValue, 1);
+ },
+ view: ViewTypes.TEXT_VIEW,
+ },
+ [FieldType.COPY_TEXT_FIELD]: {
+ label: () => "Text to be copied to clipboard",
+ defaultText: "",
+ options: () => null,
+ getter: (value: any) => {
+ return textGetter(value, 0);
+ },
+ setter: (option: any, currentValue: string) => {
+ return textSetter(option, currentValue, 0);
+ },
+ view: ViewTypes.TEXT_VIEW,
+ },
+ [FieldType.CALLBACK_FUNCTION_FIELD]: {
+ label: () => "Callback function",
+ defaultText: "",
+ options: () => null,
+ getter: (value: string) => {
+ return textGetter(value, 0);
+ },
+ setter: (value, currentValue) => {
+ return textSetter(value, currentValue, 0);
+ },
+ view: ViewTypes.TEXT_VIEW,
+ },
+ [FieldType.DELAY_FIELD]: {
+ label: () => "Delay (ms)",
+ defaultText: "",
+ options: () => null,
+ getter: (value: string) => {
+ return textGetter(value, 1);
+ },
+ setter: (value, currentValue) => {
+ return textSetter(value, currentValue, 1);
+ },
+ view: ViewTypes.TEXT_VIEW,
+ },
+ [FieldType.ID_FIELD]: {
+ label: () => "Id",
+ defaultText: "",
+ options: () => null,
+ getter: (value: string) => {
+ return textGetter(value, 2);
+ },
+ setter: (value, currentValue) => {
+ return textSetter(value, currentValue, 2);
+ },
+ view: ViewTypes.TEXT_VIEW,
+ },
+ [FieldType.CLEAR_INTERVAL_ID_FIELD]: {
+ label: () => "Id",
+ defaultText: "",
+ options: () => null,
+ getter: (value: string) => {
+ return textGetter(value, 0);
+ },
+ setter: (value, currentValue) => {
+ return textSetter(value, currentValue, 0);
+ },
+ view: ViewTypes.TEXT_VIEW,
+ },
+ [FieldType.SHOW_MODAL_FIELD]: {
+ label: () => "Modal Name",
+ options: (props: FieldProps) => props.modalDropdownList,
+ defaultText: "Select Modal",
+ getter: (value: any) => {
+ return modalGetter(value);
+ },
+ setter: (option: any, currentValue: string) => {
+ return modalSetter(option.value, currentValue);
+ },
+ view: ViewTypes.SELECTOR_VIEW,
+ },
+ [FieldType.CLOSE_MODAL_FIELD]: {
+ label: () => "Modal Name",
+ options: (props: FieldProps) => props.modalDropdownList,
+ defaultText: "Select Modal",
+ getter: (value: any) => {
+ return modalGetter(value);
+ },
+ setter: (option: any, currentValue: string) => {
+ return modalSetter(option.value, currentValue);
+ },
+ view: ViewTypes.SELECTOR_VIEW,
+ },
+ [FieldType.RESET_CHILDREN_FIELD]: {
+ label: () => "Reset Children",
+ options: () => RESET_CHILDREN_OPTIONS,
+ defaultText: "true",
+ getter: (value: any) => {
+ return enumTypeGetter(value, 1);
+ },
+ setter: (option: any, currentValue: string) => {
+ return enumTypeSetter(option.value, currentValue, 1);
+ },
+ view: ViewTypes.SELECTOR_VIEW,
+ },
+ [FieldType.WIDGET_NAME_FIELD]: {
+ label: () => "Widget",
+ options: (props: FieldProps) => props.widgetOptionTree,
+ defaultText: "Select Widget",
+ getter: (value: any) => {
+ return enumTypeGetter(value, 0);
+ },
+ setter: (option: any, currentValue: string) => {
+ return enumTypeSetter(option.value, currentValue, 0);
+ },
+ view: ViewTypes.SELECTOR_VIEW,
+ },
+ [FieldType.PAGE_SELECTOR_FIELD]: {
+ label: () => "Choose Page",
+ options: (props: FieldProps) => props.pageDropdownOptions,
+ defaultText: "Select Page",
+ getter: (value: any) => {
+ return enumTypeGetter(value, 0, "");
+ },
+ setter: (option: any, currentValue: string) => {
+ return enumTypeSetter(option.value, currentValue, 0);
+ },
+ view: ViewTypes.SELECTOR_VIEW,
+ },
+ [FieldType.ALERT_TYPE_SELECTOR_FIELD]: {
+ label: () => "Type",
+ options: () => ALERT_STYLE_OPTIONS,
+ defaultText: "Select type",
+ getter: (value: any) => {
+ return enumTypeGetter(value, 1, "success");
+ },
+ setter: (option: any, currentValue: string) => {
+ return enumTypeSetter(option.value, currentValue, 1);
+ },
+ view: ViewTypes.SELECTOR_VIEW,
+ },
+ [FieldType.DOWNLOAD_FILE_TYPE_FIELD]: {
+ label: () => "Type",
+ options: () => FILE_TYPE_OPTIONS,
+ defaultText: "Select file type (optional)",
+ getter: (value: any) => {
+ return enumTypeGetter(value, 2);
+ },
+ setter: (option: any, currentValue: string) =>
+ enumTypeSetter(option.value, currentValue, 2),
+ view: ViewTypes.SELECTOR_VIEW,
+ },
+ [FieldType.NAVIGATION_TARGET_FIELD]: {
+ label: () => "Target",
+ options: () => NAVIGATION_TARGET_FIELD_OPTIONS,
+ defaultText: NAVIGATION_TARGET_FIELD_OPTIONS[0].label,
+ getter: (value: any) => {
+ return enumTypeGetter(value, 2, "SAME_WINDOW");
+ },
+ setter: (option: any, currentValue: string) => {
+ return enumTypeSetter(option.value, currentValue, 2);
+ },
+ view: ViewTypes.SELECTOR_VIEW,
+ },
+ [FieldType.ON_SUCCESS_FIELD]: {
+ label: () => "",
+ options: (props: FieldProps) => props.integrationOptionTree,
+ defaultText: "Select Action",
+ view: ViewTypes.NO_VIEW,
+ getter: () => "",
+ setter: () => "",
+ },
+ [FieldType.ON_ERROR_FIELD]: {
+ label: () => "",
+ options: (props: FieldProps) => props.integrationOptionTree,
+ defaultText: "Select Action",
+ view: ViewTypes.NO_VIEW,
+ getter: () => "",
+ setter: () => "",
+ },
+ [FieldType.PAGE_NAME_AND_URL_TAB_SELECTOR_FIELD]: {
+ label: () => "Type",
+ defaultText: "",
+ options: () => null,
+ getter: (value: any) => {
+ return enumTypeGetter(value, 0);
+ },
+ setter: (option: any, currentValue: string) => {
+ return enumTypeSetter(option.value, currentValue, 0);
+ },
+ view: ViewTypes.TAB_VIEW,
+ },
+ [FieldType.KEY_VALUE_FIELD]: {
+ label: () => "",
+ defaultText: "Select Action",
+ options: (props: FieldProps) => props.integrationOptionTree,
+ getter: (value: any) => {
+ return value;
+ },
+ setter: (value: any) => {
+ return value;
+ },
+ view: ViewTypes.KEY_VALUE_VIEW,
+ },
+ [FieldType.ARGUMENT_KEY_VALUE_FIELD]: {
+ label: (props: FieldProps) => props.field.label || "",
+ defaultText: "",
+ options: () => null,
+ getter: (value: any, index: number) => {
+ return textGetter(value, index);
+ },
+ setter: (value: any, currentValue: string, index) => {
+ if (value === "") {
+ value = undefined;
+ }
+ return textSetter(value, currentValue, index as number);
+ },
+ view: ViewTypes.TEXT_VIEW,
+ },
+ [FieldType.MESSAGE_FIELD]: {
+ label: () => "Message",
+ defaultText: "",
+ options: () => null,
+ toolTip: "Data to be sent to the target iframe",
+ getter: (value: string) => {
+ return textGetter(value, 0);
+ },
+ setter: (value, currentValue) => {
+ return textSetter(value, currentValue, 0);
+ },
+ view: ViewTypes.TEXT_VIEW,
+ },
+ [FieldType.TARGET_ORIGIN_FIELD]: {
+ label: () => "Allowed origins",
+ defaultText: "",
+ options: () => null,
+ toolTip: "Restricts domains to which the message can be sent",
+ getter: (value: string) => {
+ return textGetter(value, 2);
+ },
+ setter: (value, currentValue) => {
+ return textSetter(value, currentValue, 2);
+ },
+ view: ViewTypes.TEXT_VIEW,
+ },
+ [FieldType.SOURCE_FIELD]: {
+ label: () => "Target iframe",
+ defaultText: "",
+ options: () => null,
+ toolTip: "Specifies the target iframe widget name or parent window",
+ getter: (value: string) => {
+ return textGetter(value, 1);
+ },
+ setter: (value, currentValue) => {
+ return textSetter(value, currentValue, 1);
+ },
+ view: ViewTypes.TEXT_VIEW,
+ },
+};
diff --git a/app/client/src/components/editorComponents/ActionCreator/Fields.tsx b/app/client/src/components/editorComponents/ActionCreator/Fields.tsx
index 5079ac7ef509..dcf899a827db 100644
--- a/app/client/src/components/editorComponents/ActionCreator/Fields.tsx
+++ b/app/client/src/components/editorComponents/ActionCreator/Fields.tsx
@@ -1,47 +1,13 @@
import React from "react";
-import { TreeDropdownOption } from "design-system";
import {
StyledDividerContainer,
StyledNavigateToFieldsContainer,
StyledNavigateToFieldWrapper,
} from "components/propertyControls/StyledControls";
-import HightlightedCode from "components/editorComponents/HighlightedCode";
-import { Skin } from "constants/DefaultTheme";
-import { DropdownOption } from "components/constants";
import DividerComponent from "widgets/DividerWidget/component";
-import store from "store";
-import { getPageList } from "selectors/entitiesSelector";
-import {
- RESET_CHILDREN_OPTIONS,
- FILE_TYPE_OPTIONS,
- NAVIGATION_TARGET_FIELD_OPTIONS,
- ViewTypes,
- AppsmithFunction,
- FieldType,
-} from "./constants";
-import { ACTION_TRIGGER_REGEX } from "./regex";
-import {
- SwitchType,
- ActionType,
- SelectorViewProps,
- KeyValueViewProps,
- TextViewProps,
- TabViewProps,
- FieldConfigs,
-} from "./types";
-import {
- modalSetter,
- modalGetter,
- textSetter,
- textGetter,
- enumTypeSetter,
- enumTypeGetter,
-} from "./utils";
-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";
+import { FieldType } from "./constants";
+import { FieldsProps } from "./types";
+import { Field } from "./Field";
/**
******** Steps to add a new function *******
@@ -63,578 +29,7 @@ import { TabView } from "./viewComponents/TabView";
* 2. Attach fields to the new action in the getFieldFromValue function
**/
-const views = {
- [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 = {
- [FieldType.ACTION_SELECTOR_FIELD]: {
- getter: (storedValue: string) => {
- let matches: any[] = [];
- if (storedValue) {
- matches = storedValue
- ? [...storedValue.matchAll(ACTION_TRIGGER_REGEX)]
- : [];
- }
- let mainFuncSelectedValue = AppsmithFunction.none;
- if (matches.length) {
- mainFuncSelectedValue = matches[0][1] || AppsmithFunction.none;
- }
- const mainFuncSelectedValueSplit = mainFuncSelectedValue.split(".");
- if (mainFuncSelectedValueSplit[1] === "run") {
- return mainFuncSelectedValueSplit[0];
- }
- return mainFuncSelectedValue;
- },
- setter: (option: TreeDropdownOption) => {
- const type: ActionType = option.type || option.value;
- let value = option.value;
- let defaultParams = "";
- let defaultArgs: Array<any> = [];
- switch (type) {
- case AppsmithFunction.integration:
- value = `${value}.run`;
- break;
- case AppsmithFunction.navigateTo:
- defaultParams = `'', {}, 'SAME_WINDOW'`;
- break;
- case AppsmithFunction.jsFunction:
- defaultArgs = option.args ? option.args : [];
- break;
- case AppsmithFunction.setInterval:
- defaultParams = "() => { \n\t // add code here \n}, 5000";
- break;
- case AppsmithFunction.getGeolocation:
- defaultParams = "(location) => { \n\t // add code here \n }";
- break;
- case AppsmithFunction.resetWidget:
- defaultParams = `"",true`;
- break;
- case AppsmithFunction.postMessage:
- defaultParams = `'', 'window', '*'`;
- break;
- default:
- break;
- }
- return value === "none"
- ? ""
- : defaultArgs && defaultArgs.length
- ? `{{${value}(${defaultArgs})}}`
- : `{{${value}(${defaultParams})}}`;
- },
- view: ViewTypes.SELECTOR_VIEW,
- },
- [FieldType.SHOW_MODAL_FIELD]: {
- getter: (value: any) => {
- return modalGetter(value);
- },
- setter: (option: any, currentValue: string) => {
- return modalSetter(option.value, currentValue);
- },
- view: ViewTypes.SELECTOR_VIEW,
- },
- [FieldType.CLOSE_MODAL_FIELD]: {
- getter: (value: any) => {
- return modalGetter(value);
- },
- setter: (option: any, currentValue: string) => {
- return modalSetter(option.value, currentValue);
- },
- view: ViewTypes.SELECTOR_VIEW,
- },
- [FieldType.PAGE_SELECTOR_FIELD]: {
- getter: (value: any) => {
- return enumTypeGetter(value, 0, "");
- },
- setter: (option: any, currentValue: string) => {
- return enumTypeSetter(option.value, currentValue, 0);
- },
- view: ViewTypes.SELECTOR_VIEW,
- },
- [FieldType.KEY_VALUE_FIELD]: {
- getter: (value: any) => {
- return value;
- },
- setter: (value: any) => {
- return value;
- },
- view: ViewTypes.KEY_VALUE_VIEW,
- },
- [FieldType.ARGUMENT_KEY_VALUE_FIELD]: {
- getter: (value: any, index: number) => {
- return textGetter(value, index);
- },
- setter: (value: any, currentValue: string, index: number) => {
- if (value === "") {
- value = undefined;
- }
- return textSetter(value, currentValue, index);
- },
- view: ViewTypes.TEXT_VIEW,
- },
- [FieldType.URL_FIELD]: {
- getter: (value: string) => {
- const appState = store.getState();
- const pageList = getPageList(appState).map((page) => page.pageName);
- const urlFieldValue = textGetter(value, 0);
- return pageList.includes(urlFieldValue) ? "" : urlFieldValue;
- },
- setter: (value: string, currentValue: string) => {
- return textSetter(value, currentValue, 0);
- },
- view: ViewTypes.TEXT_VIEW,
- },
- [FieldType.NAVIGATION_TARGET_FIELD]: {
- getter: (value: any) => {
- return enumTypeGetter(value, 2, NAVIGATION_TARGET_FIELD_OPTIONS[0].value);
- },
- setter: (option: any, currentValue: string) => {
- return enumTypeSetter(option.value, currentValue, 2);
- },
- view: ViewTypes.SELECTOR_VIEW,
- },
- [FieldType.ALERT_TEXT_FIELD]: {
- getter: (value: string) => {
- return textGetter(value, 0);
- },
- setter: (value: string, currentValue: string) => {
- return textSetter(value, currentValue, 0);
- },
- view: ViewTypes.TEXT_VIEW,
- },
- [FieldType.ALERT_TYPE_SELECTOR_FIELD]: {
- getter: (value: any) => {
- return enumTypeGetter(value, 1, "success");
- },
- setter: (option: any, currentValue: string) => {
- return enumTypeSetter(option.value, currentValue, 1);
- },
- view: ViewTypes.SELECTOR_VIEW,
- },
- [FieldType.KEY_TEXT_FIELD]: {
- getter: (value: any) => {
- return textGetter(value, 0);
- },
- setter: (option: any, currentValue: string) => {
- return textSetter(option, currentValue, 0);
- },
- view: ViewTypes.TEXT_VIEW,
- },
- [FieldType.VALUE_TEXT_FIELD]: {
- getter: (value: any) => {
- return textGetter(value, 1);
- },
- setter: (option: any, currentValue: string) => {
- return textSetter(option, currentValue, 1);
- },
- view: ViewTypes.TEXT_VIEW,
- },
- [FieldType.QUERY_PARAMS_FIELD]: {
- getter: (value: any) => {
- return textGetter(value, 1);
- },
- setter: (value: any, currentValue: string) => {
- if (value === "") {
- value = undefined;
- }
- return textSetter(value, currentValue, 1);
- },
- view: ViewTypes.TEXT_VIEW,
- },
- [FieldType.DOWNLOAD_DATA_FIELD]: {
- getter: (value: any) => {
- return textGetter(value, 0);
- },
- setter: (option: any, currentValue: string) => {
- return textSetter(option, currentValue, 0);
- },
- view: ViewTypes.TEXT_VIEW,
- },
- [FieldType.DOWNLOAD_FILE_NAME_FIELD]: {
- getter: (value: any) => {
- return textGetter(value, 1);
- },
- setter: (option: any, currentValue: string) => {
- return textSetter(option, currentValue, 1);
- },
- view: ViewTypes.TEXT_VIEW,
- },
- [FieldType.DOWNLOAD_FILE_TYPE_FIELD]: {
- getter: (value: any) => {
- return enumTypeGetter(value, 2);
- },
- setter: (option: any, currentValue: string) =>
- enumTypeSetter(option.value, currentValue, 2),
- view: ViewTypes.SELECTOR_VIEW,
- },
- [FieldType.COPY_TEXT_FIELD]: {
- getter: (value: any) => {
- return textGetter(value, 0);
- },
- setter: (option: any, currentValue: string) => {
- return textSetter(option, currentValue, 0);
- },
- view: ViewTypes.TEXT_VIEW,
- },
- [FieldType.WIDGET_NAME_FIELD]: {
- getter: (value: any) => {
- return enumTypeGetter(value, 0);
- },
- setter: (option: any, currentValue: string) => {
- return enumTypeSetter(option.value, currentValue, 0);
- },
- view: ViewTypes.SELECTOR_VIEW,
- },
- [FieldType.RESET_CHILDREN_FIELD]: {
- getter: (value: any) => {
- return enumTypeGetter(value, 1);
- },
- setter: (option: any, currentValue: string) => {
- return enumTypeSetter(option.value, currentValue, 1);
- },
- view: ViewTypes.SELECTOR_VIEW,
- },
- [FieldType.CALLBACK_FUNCTION_FIELD]: {
- getter: (value: string) => {
- return textGetter(value, 0);
- },
- setter: (value: string, currentValue: string) => {
- return textSetter(value, currentValue, 0);
- },
- view: ViewTypes.TEXT_VIEW,
- },
- [FieldType.DELAY_FIELD]: {
- getter: (value: string) => {
- return textGetter(value, 1);
- },
- setter: (value: string, currentValue: string) => {
- return textSetter(value, currentValue, 1);
- },
- view: ViewTypes.TEXT_VIEW,
- },
- [FieldType.ID_FIELD]: {
- getter: (value: string) => {
- return textGetter(value, 2);
- },
- setter: (value: string, currentValue: string) => {
- return textSetter(value, currentValue, 2);
- },
- view: ViewTypes.TEXT_VIEW,
- },
- [FieldType.CLEAR_INTERVAL_ID_FIELD]: {
- getter: (value: string) => {
- return textGetter(value, 0);
- },
- setter: (value: string, currentValue: string) => {
- return textSetter(value, currentValue, 0);
- },
- view: ViewTypes.TEXT_VIEW,
- },
- [FieldType.MESSAGE_FIELD]: {
- getter: (value: string) => {
- return textGetter(value, 0);
- },
- setter: (value: string, currentValue: string) => {
- return textSetter(value, currentValue, 0);
- },
- view: ViewTypes.TEXT_VIEW,
- },
- [FieldType.SOURCE_FIELD]: {
- getter: (value: string) => {
- return textGetter(value, 1);
- },
- setter: (value: string, currentValue: string) => {
- return textSetter(value, currentValue, 1);
- },
- view: ViewTypes.TEXT_VIEW,
- },
- [FieldType.TARGET_ORIGIN_FIELD]: {
- getter: (value: string) => {
- return textGetter(value, 2);
- },
- setter: (value: string, currentValue: string) => {
- return textSetter(value, currentValue, 2);
- },
- view: ViewTypes.TEXT_VIEW,
- },
- [FieldType.PAGE_NAME_AND_URL_TAB_SELECTOR_FIELD]: {
- getter: (value: any) => {
- return enumTypeGetter(value, 0);
- },
- setter: (option: any, currentValue: string) => {
- return enumTypeSetter(option.value, currentValue, 0);
- },
- view: ViewTypes.TAB_VIEW,
- },
-};
-
-function renderField(props: {
- onValueChange: (newValue: string, isUpdatedViaKeyboard: boolean) => void;
- value: string;
- field: { field: FieldType; value: string; label: string; index: number };
- label?: string;
- widgetOptionTree: TreeDropdownOption[];
- modalDropdownList: TreeDropdownOption[];
- pageDropdownOptions: TreeDropdownOption[];
- integrationOptionTree: TreeDropdownOption[];
- depth: number;
- maxDepth: number;
- additionalAutoComplete?: Record<string, Record<string, unknown>>;
- activeNavigateToTab: SwitchType;
- navigateToSwitches: Array<SwitchType>;
-}) {
- const { field } = props;
- const fieldType = field.field;
- const fieldConfig = fieldConfigs[fieldType];
- if (!fieldConfig) return;
- const view = views[fieldConfig.view];
- let viewElement: JSX.Element | null = null;
-
- switch (fieldType) {
- case FieldType.ACTION_SELECTOR_FIELD:
- case FieldType.ON_SUCCESS_FIELD:
- case FieldType.ON_ERROR_FIELD:
- case FieldType.SHOW_MODAL_FIELD:
- case FieldType.CLOSE_MODAL_FIELD:
- case FieldType.PAGE_SELECTOR_FIELD:
- case FieldType.ALERT_TYPE_SELECTOR_FIELD:
- case FieldType.DOWNLOAD_FILE_TYPE_FIELD:
- case FieldType.NAVIGATION_TARGET_FIELD:
- case FieldType.RESET_CHILDREN_FIELD:
- case FieldType.WIDGET_NAME_FIELD:
- let label = "";
- let defaultText = "Select Action";
- let options = props.integrationOptionTree;
- let selectedLabelModifier = undefined;
- let displayValue = undefined;
- let getDefaults = undefined;
- if (fieldType === FieldType.ACTION_SELECTOR_FIELD) {
- label = props.label || "";
- displayValue =
- field.value !== "{{undefined}}" &&
- field.value !== "{{()}}" &&
- field.value !== "{{{}, ()}}"
- ? field.value
- : undefined;
- // eslint-disable-next-line react/display-name
- selectedLabelModifier = function(
- option: TreeDropdownOption,
- displayValue?: string,
- ) {
- if (option.type === AppsmithFunction.integration) {
- return (
- <HightlightedCode
- codeText={`{{${option.label}.run()}}`}
- skin={Skin.LIGHT}
- />
- );
- } else if (displayValue) {
- return (
- <HightlightedCode codeText={displayValue} skin={Skin.LIGHT} />
- );
- }
- return <span>{option.label}</span>;
- };
- getDefaults = (value: string) => {
- return {
- [AppsmithFunction.navigateTo]: `'${props.pageDropdownOptions[0].label}'`,
- }[value];
- };
- }
- if (
- fieldType === FieldType.SHOW_MODAL_FIELD ||
- fieldType === FieldType.CLOSE_MODAL_FIELD
- ) {
- label = "Modal Name";
- options = props.modalDropdownList;
- defaultText = "Select Modal";
- }
- if (fieldType === FieldType.RESET_CHILDREN_FIELD) {
- label = "Reset Children";
- options = RESET_CHILDREN_OPTIONS;
- defaultText = "true";
- }
- if (fieldType === FieldType.WIDGET_NAME_FIELD) {
- label = "Widget";
- options = props.widgetOptionTree;
- defaultText = "Select Widget";
- }
- if (fieldType === FieldType.PAGE_SELECTOR_FIELD) {
- label = "Choose Page";
- options = props.pageDropdownOptions;
- defaultText = "Select Page";
- }
- if (fieldType === FieldType.ALERT_TYPE_SELECTOR_FIELD) {
- label = "Type";
- options = ALERT_STYLE_OPTIONS;
- defaultText = "Select type";
- }
- if (fieldType === FieldType.DOWNLOAD_FILE_TYPE_FIELD) {
- label = "Type";
- options = FILE_TYPE_OPTIONS;
- defaultText = "Select file type (optional)";
- }
- if (fieldType === FieldType.NAVIGATION_TARGET_FIELD) {
- label = "Target";
- options = NAVIGATION_TARGET_FIELD_OPTIONS;
- defaultText = NAVIGATION_TARGET_FIELD_OPTIONS[0].label;
- }
- viewElement = (view as (props: SelectorViewProps) => JSX.Element)({
- options: options,
- label: label,
- get: fieldConfig.getter,
- set: (
- value: string | DropdownOption,
- defaultValue?: string,
- isUpdatedViaKeyboard = false,
- ) => {
- const finalValueToSet = fieldConfig.setter(
- value,
- props.value,
- defaultValue,
- );
- props.onValueChange(finalValueToSet, isUpdatedViaKeyboard);
- },
- value: props.value,
- defaultText: defaultText,
- getDefaults: getDefaults,
- selectedLabelModifier: selectedLabelModifier,
- displayValue: displayValue ? displayValue : "",
- });
- break;
- case FieldType.PAGE_NAME_AND_URL_TAB_SELECTOR_FIELD:
- viewElement = (view as (props: TabViewProps) => JSX.Element)({
- activeObj: props.activeNavigateToTab,
- switches: props.navigateToSwitches,
- label: "Type",
- value: props.value,
- });
- break;
- case FieldType.ARGUMENT_KEY_VALUE_FIELD:
- viewElement = (view as (props: TextViewProps) => JSX.Element)({
- label: props.field.label || "",
- get: fieldConfig.getter,
- set: (value: string) => {
- const finalValueToSet = fieldConfig.setter(
- value,
- props.value,
- props.field.index,
- );
- props.onValueChange(finalValueToSet, false);
- },
- index: props.field.index,
- value: props.value || "",
- });
- break;
- case FieldType.KEY_VALUE_FIELD:
- viewElement = (view as (props: SelectorViewProps) => JSX.Element)({
- options: props.integrationOptionTree,
- label: "",
- get: fieldConfig.getter,
- set: (value: string | DropdownOption) => {
- const finalValueToSet = fieldConfig.setter(value, props.value);
- props.onValueChange(finalValueToSet, false);
- },
- value: props.value,
- defaultText: "Select Action",
- });
- break;
- case FieldType.ALERT_TEXT_FIELD:
- case FieldType.URL_FIELD:
- case FieldType.KEY_TEXT_FIELD:
- case FieldType.VALUE_TEXT_FIELD:
- case FieldType.QUERY_PARAMS_FIELD:
- case FieldType.DOWNLOAD_DATA_FIELD:
- case FieldType.DOWNLOAD_FILE_NAME_FIELD:
- case FieldType.COPY_TEXT_FIELD:
- case FieldType.CALLBACK_FUNCTION_FIELD:
- case FieldType.DELAY_FIELD:
- case FieldType.ID_FIELD:
- case FieldType.CLEAR_INTERVAL_ID_FIELD:
- case FieldType.MESSAGE_FIELD:
- case FieldType.TARGET_ORIGIN_FIELD:
- case FieldType.SOURCE_FIELD:
- let fieldLabel = "";
- let toolTip = "";
- if (fieldType === FieldType.ALERT_TEXT_FIELD) {
- fieldLabel = "Message";
- } else if (fieldType === FieldType.URL_FIELD) {
- fieldLabel = "Enter URL";
- } else if (fieldType === FieldType.KEY_TEXT_FIELD) {
- fieldLabel = "Key";
- } else if (fieldType === FieldType.VALUE_TEXT_FIELD) {
- fieldLabel = "Value";
- } else if (fieldType === FieldType.QUERY_PARAMS_FIELD) {
- fieldLabel = "Query Params";
- } else if (fieldType === FieldType.DOWNLOAD_DATA_FIELD) {
- fieldLabel = "Data to download";
- } else if (fieldType === FieldType.DOWNLOAD_FILE_NAME_FIELD) {
- fieldLabel = "File name with extension";
- } else if (fieldType === FieldType.COPY_TEXT_FIELD) {
- fieldLabel = "Text to be copied to clipboard";
- } else if (fieldType === FieldType.CALLBACK_FUNCTION_FIELD) {
- fieldLabel = "Callback function";
- } else if (fieldType === FieldType.DELAY_FIELD) {
- fieldLabel = "Delay (ms)";
- } else if (fieldType === FieldType.ID_FIELD) {
- fieldLabel = "Id";
- } else if (fieldType === FieldType.CLEAR_INTERVAL_ID_FIELD) {
- fieldLabel = "Id";
- } else if (fieldType === FieldType.MESSAGE_FIELD) {
- fieldLabel = "Message";
- toolTip = "Data to be sent to the target iframe";
- } else if (fieldType === FieldType.TARGET_ORIGIN_FIELD) {
- fieldLabel = "Allowed Origins";
- toolTip = "Restricts domains to which the message can be sent";
- } else if (fieldType === FieldType.SOURCE_FIELD) {
- fieldLabel = "Target iframe";
- toolTip = "Specifies the target iframe widget name or parent window";
- }
- viewElement = (view as (props: TextViewProps) => JSX.Element)({
- label: fieldLabel,
- toolTip: toolTip,
- get: fieldConfig.getter,
- set: (value: string | DropdownOption, isUpdatedViaKeyboard = false) => {
- const finalValueToSet = fieldConfig.setter(value, props.value);
- props.onValueChange(finalValueToSet, isUpdatedViaKeyboard);
- },
- value: props.value,
- additionalAutoComplete: props.additionalAutoComplete,
- });
- break;
- default:
- break;
- }
-
- return (
- <div data-guided-tour-iid={field.label} key={fieldType}>
- {viewElement}
- </div>
- );
-}
-
-function Fields(props: {
- onValueChange: (newValue: string, isUpdatedViaKeyboard: boolean) => void;
- value: string;
- fields: any;
- label?: string;
- integrationOptionTree: TreeDropdownOption[];
- widgetOptionTree: TreeDropdownOption[];
- modalDropdownList: TreeDropdownOption[];
- pageDropdownOptions: TreeDropdownOption[];
- depth: number;
- maxDepth: number;
- additionalAutoComplete?: Record<string, Record<string, unknown>>;
- navigateToSwitches: Array<SwitchType>;
- activeNavigateToTab: SwitchType;
-}) {
+function Fields(props: FieldsProps) {
const { fields, ...otherProps } = props;
if (fields[0].field === FieldType.ACTION_SELECTOR_FIELD) {
@@ -648,9 +43,9 @@ function Fields(props: {
* This if condition achieves that design */
return (
<>
- {renderField({
- field: fields[0],
+ {Field({
...otherProps,
+ field: fields[0],
})}
<StyledNavigateToFieldWrapper>
@@ -664,7 +59,7 @@ function Fields(props: {
</StyledDividerContainer>
<StyledNavigateToFieldsContainer>
{remainingFields.map((paramField: any) => {
- return renderField({ field: paramField, ...otherProps });
+ return Field({ ...otherProps, field: paramField });
})}
</StyledNavigateToFieldsContainer>
</StyledNavigateToFieldWrapper>
@@ -673,16 +68,17 @@ function Fields(props: {
}
return (
<>
- {renderField({
- field: fields[0],
+ {Field({
...otherProps,
+ field: fields[0],
})}
<ul className={props.depth === 1 ? "tree" : ""}>
{remainingFields.map((field: any, index: number) => {
if (Array.isArray(field)) {
if (props.depth > props.maxDepth) {
- return null;
+ // eslint-disable-next-line react/jsx-no-useless-fragment
+ return <></>;
}
const selectorField = field[0];
return (
@@ -721,7 +117,7 @@ function Fields(props: {
} else {
return (
<li key={field.field + index}>
- {renderField({
+ {Field({
field: field,
...otherProps,
})}
@@ -736,7 +132,8 @@ function Fields(props: {
const ui = fields.map((field: any, index: number) => {
if (Array.isArray(field)) {
if (props.depth > props.maxDepth) {
- return null;
+ // eslint-disable-next-line react/jsx-no-useless-fragment
+ return <></>;
}
const selectorField = field[0];
return (
@@ -762,13 +159,14 @@ function Fields(props: {
/>
);
} else {
- return renderField({
+ return Field({
field: field,
...otherProps,
});
}
});
- return ui;
+ // eslint-disable-next-line react/jsx-no-useless-fragment
+ return <>{ui}</>;
}
}
diff --git a/app/client/src/components/editorComponents/ActionCreator/constants.ts b/app/client/src/components/editorComponents/ActionCreator/constants.ts
index 391cca2b6b71..773c3d320b51 100644
--- a/app/client/src/components/editorComponents/ActionCreator/constants.ts
+++ b/app/client/src/components/editorComponents/ActionCreator/constants.ts
@@ -61,6 +61,7 @@ export const ViewTypes = {
TEXT_VIEW: "TEXT_VIEW",
BOOL_VIEW: "BOOL_VIEW",
TAB_VIEW: "TAB_VIEW",
+ NO_VIEW: "NO_VIEW",
};
export const NAVIGATE_TO_TAB_OPTIONS = {
@@ -70,7 +71,6 @@ export const NAVIGATE_TO_TAB_OPTIONS = {
export enum FieldType {
ACTION_SELECTOR_FIELD = "ACTION_SELECTOR_FIELD",
- JS_ACTION_SELECTOR_FIELD = "JS_ACTION_SELECTOR_FIELD",
ON_SUCCESS_FIELD = "ON_SUCCESS_FIELD",
ON_ERROR_FIELD = "ON_ERROR_FIELD",
SHOW_MODAL_FIELD = "SHOW_MODAL_FIELD",
diff --git a/app/client/src/components/editorComponents/ActionCreator/types.ts b/app/client/src/components/editorComponents/ActionCreator/types.ts
index 746c5efee6f3..08707111a2d3 100644
--- a/app/client/src/components/editorComponents/ActionCreator/types.ts
+++ b/app/client/src/components/editorComponents/ActionCreator/types.ts
@@ -57,3 +57,50 @@ export type ActionCreatorProps = {
additionalAutoComplete?: Record<string, Record<string, unknown>>;
pageDropdownOptions: TreeDropdownOption[];
};
+
+export type Field = {
+ field: FieldType;
+ value?: string;
+ label?: string;
+ index?: number;
+};
+
+export type FieldProps = {
+ onValueChange: (newValue: string, isUpdatedViaKeyboard: boolean) => void;
+ value: string;
+ field: Field;
+ label?: string;
+ widgetOptionTree: TreeDropdownOption[];
+ modalDropdownList: TreeDropdownOption[];
+ pageDropdownOptions: TreeDropdownOption[];
+ integrationOptionTree: TreeDropdownOption[];
+ depth: number;
+ maxDepth: number;
+ additionalAutoComplete?: Record<string, Record<string, unknown>>;
+ activeNavigateToTab: SwitchType;
+ navigateToSwitches: Array<SwitchType>;
+};
+
+export type FieldsProps = Omit<FieldProps, "field"> & {
+ fields: Array<Field>;
+};
+
+export type OptionListType = { label: string; value: string; id: string };
+
+export type AppsmithFunctionConfigValues = {
+ label: (args: FieldProps) => string;
+ defaultText: string;
+ options: (args: FieldProps) => null | TreeDropdownOption[] | OptionListType;
+ getter: (arg1: string, arg2: number) => string;
+ setter: (
+ arg1: string | TreeDropdownOption,
+ arg2: string,
+ arg3?: number,
+ ) => string;
+ view: ViewType;
+ toolTip?: string;
+};
+
+export type AppsmithFunctionConfigType = {
+ [key: string]: AppsmithFunctionConfigValues;
+};
|
7053632d746d066f841d02122bd779b3f89d8dff
|
2024-08-27 16:05:12
|
Anagh Hegde
|
ci: merge release to pg (#35905)
| false
|
merge release to pg (#35905)
|
ci
|
diff --git a/.github/workflows/sync-release-to-pg.yml b/.github/workflows/sync-release-to-pg.yml
index 0748ef9a40c6..b3a9c6ab3991 100644
--- a/.github/workflows/sync-release-to-pg.yml
+++ b/.github/workflows/sync-release-to-pg.yml
@@ -16,7 +16,7 @@ jobs:
ref: release # Checkout the release branch
- name: Fetch all branches
- run: git fetch pg
+ run: git fetch origin pg
- name: Checkout pg branch
run: git checkout pg
|
c346af60c343f99e164f24150e0c59aa900a7138
|
2022-03-05 18:50:33
|
f0c1s
|
chore: update icons in org menu (#11548)
| false
|
update icons in org menu (#11548)
|
chore
|
diff --git a/app/client/src/components/ads/Icon.tsx b/app/client/src/components/ads/Icon.tsx
index f2dcb8769ccc..41118749de16 100644
--- a/app/client/src/components/ads/Icon.tsx
+++ b/app/client/src/components/ads/Icon.tsx
@@ -147,6 +147,7 @@ import Settings2LineIcon from "remixicon-react/Settings2LineIcon";
import FileListLineIcon from "remixicon-react/FileListLineIcon";
import HamburgerIcon from "remixicon-react/MenuLineIcon";
import MagicLineIcon from "remixicon-react/MagicLineIcon";
+import UserHeartLineIcon from "remixicon-react/UserHeartLineIcon";
export enum IconSize {
XXS = "extraExtraSmall",
@@ -294,6 +295,7 @@ const ICON_LOOKUP = {
"trending-flat": <TrendingFlat />,
"unread-pin": <UnreadPin />,
"user-2": <UserV2Icon />,
+ "user-heart-line": <UserHeartLineIcon />,
"view-all": <RightArrowIcon />,
"view-less": <LeftArrowIcon />,
"warning-line": <WarningLineIcon />,
@@ -333,6 +335,7 @@ const ICON_LOOKUP = {
loader: <LoaderLineIcon />,
logout: <LogoutIcon />,
manage: <ManageIcon />,
+ member: <UserHeartLineIcon />,
mobile: <MobileIcon />,
open: <OpenIcon />,
pin: <Pin />,
diff --git a/app/client/src/pages/Applications/index.tsx b/app/client/src/pages/Applications/index.tsx
index b0ceaec1e5cf..9d4fffbbdb8a 100644
--- a/app/client/src/pages/Applications/index.tsx
+++ b/app/client/src/pages/Applications/index.tsx
@@ -774,7 +774,7 @@ function ApplicationsSection(props: any) {
</div>
<MenuItem
cypressSelector="t--org-setting"
- icon="general"
+ icon="settings-2-line"
onSelect={() =>
getOnSelectAction(
DropdownOnSelectActions.REDIRECT,
@@ -783,7 +783,7 @@ function ApplicationsSection(props: any) {
},
)
}
- text="Organization Settings"
+ text="Settings"
/>
{enableImportExport && (
<MenuItem
@@ -816,12 +816,12 @@ function ApplicationsSection(props: any) {
/>
)}
<MenuItem
- icon="share"
+ icon="share-line"
onSelect={() => setSelectedOrgId(organization.id)}
text="Share"
/>
<MenuItem
- icon="user"
+ icon="member"
onSelect={() =>
getOnSelectAction(
DropdownOnSelectActions.REDIRECT,
|
078ad256138294b08ee81ceebc293bfccf6b570f
|
2021-08-27 14:17:35
|
Anagh Hegde
|
feat: Create interface for git service and add all the required classes (#6903)
| false
|
Create interface for git service and add all the required classes (#6903)
|
feat
|
diff --git a/app/server/appsmith-git/pom.xml b/app/server/appsmith-git/pom.xml
index c940f6729724..aa9782993cee 100644
--- a/app/server/appsmith-git/pom.xml
+++ b/app/server/appsmith-git/pom.xml
@@ -63,6 +63,12 @@
<version>3.1.0</version>
<scope>test</scope>
</dependency>
+ <dependency>
+ <groupId>com.appsmith</groupId>
+ <artifactId>interfaces</artifactId>
+ <version>1.0-SNAPSHOT</version>
+ <scope>compile</scope>
+ </dependency>
</dependencies>
<build>
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
new file mode 100644
index 000000000000..1dcbfaa8b853
--- /dev/null
+++ b/app/server/appsmith-git/src/main/java/com/appsmith/git/service/GitExecutorImpl.java
@@ -0,0 +1,6 @@
+package com.appsmith.git.service;
+
+import com.appsmith.external.git.GitExecutor;
+
+public class GitExecutorImpl implements GitExecutor {
+}
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
new file mode 100644
index 000000000000..6a7b7747af94
--- /dev/null
+++ b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/git/GitExecutor.java
@@ -0,0 +1,4 @@
+package com.appsmith.external.git;
+
+public interface GitExecutor {
+}
diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/constants/Url.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/constants/Url.java
index 9e3e5d8120ba..fc2662ed495d 100644
--- a/app/server/appsmith-server/src/main/java/com/appsmith/server/constants/Url.java
+++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/constants/Url.java
@@ -31,4 +31,5 @@ public interface Url {
String COMMENT_URL = BASE_URL + VERSION + "/comments";
String NOTIFICATION_URL = BASE_URL + VERSION + "/notifications";
String INSTANCE_ADMIN_URL = BASE_URL + VERSION + "/admin";
+ String GIT_URL = BASE_URL + VERSION + "/git";
}
diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/controllers/GitController.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/controllers/GitController.java
new file mode 100644
index 000000000000..26dbb9240961
--- /dev/null
+++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/controllers/GitController.java
@@ -0,0 +1,20 @@
+package com.appsmith.server.controllers;
+
+import com.appsmith.server.constants.Url;
+import com.appsmith.server.domains.UserData;
+import com.appsmith.server.services.GitService;
+import lombok.extern.slf4j.Slf4j;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RestController;
+
+@Slf4j
+@RestController
+@RequestMapping(Url.GIT_URL)
+public class GitController extends BaseController<GitService, UserData, String> {
+
+ @Autowired
+ public GitController(GitService service) {
+ super(service);
+ }
+}
diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/GitService.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/GitService.java
new file mode 100644
index 000000000000..1f33bb197d44
--- /dev/null
+++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/GitService.java
@@ -0,0 +1,7 @@
+package com.appsmith.server.services;
+
+import com.appsmith.server.domains.UserData;
+
+public interface GitService extends CrudService<UserData, String> {
+
+}
diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/GitServiceImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/GitServiceImpl.java
new file mode 100644
index 000000000000..ab5059d53477
--- /dev/null
+++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/GitServiceImpl.java
@@ -0,0 +1,25 @@
+package com.appsmith.server.services;
+
+import com.appsmith.server.domains.UserData;
+import com.appsmith.server.repositories.UserDataRepository;
+import lombok.extern.slf4j.Slf4j;
+import org.springframework.data.mongodb.core.ReactiveMongoTemplate;
+import org.springframework.data.mongodb.core.convert.MongoConverter;
+import org.springframework.stereotype.Service;
+import reactor.core.scheduler.Scheduler;
+
+import javax.validation.Validator;
+
+@Slf4j
+@Service
+public class GitServiceImpl extends BaseService<UserDataRepository, UserData, String> implements GitService {
+
+ public GitServiceImpl(Scheduler scheduler,
+ Validator validator,
+ MongoConverter mongoConverter,
+ ReactiveMongoTemplate reactiveMongoTemplate,
+ UserDataRepository repository,
+ AnalyticsService analyticsService) {
+ super(scheduler, validator, mongoConverter, reactiveMongoTemplate, repository, analyticsService);
+ }
+}
|
1c14d698f1449e930ca70cfd78039a458b9235af
|
2024-09-05 17:19:57
|
Nilansh Bansal
|
chore: added thread logging info for plugins (#36077)
| false
|
added thread logging info for plugins (#36077)
|
chore
|
diff --git a/app/client/packages/eslint-plugin/package.json b/app/client/packages/eslint-plugin/package.json
index 46f1726ebec2..389406b120b1 100644
--- a/app/client/packages/eslint-plugin/package.json
+++ b/app/client/packages/eslint-plugin/package.json
@@ -11,4 +11,4 @@
"postinstall": "yarn build",
"test:unit": "yarn g:jest"
}
-}
\ No newline at end of file
+}
diff --git a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/helpers/Stopwatch.java b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/helpers/Stopwatch.java
index 1fc597c01f82..9d6fdb3eba6a 100644
--- a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/helpers/Stopwatch.java
+++ b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/helpers/Stopwatch.java
@@ -25,6 +25,18 @@ public void stopAndLogTimeInMillis() {
log.debug("Execute time: {}, Time elapsed: {}ms", this.flow, this.watch.getTime(TimeUnit.MILLISECONDS));
}
+ /**
+ * This is a temporary function created to log stopwatch timer within the plugin package
+ * Due to this bug https://github.com/appsmithorg/appsmith/issues/36073 logging is not working in the plugin package
+ */
+ public void stopAndLogTimeInMillisWithSysOut() {
+ if (!this.watch.isStopped()) {
+ this.watch.stop();
+ }
+ System.out.println(String.format(
+ "Execute time: %s, Time elapsed: %dms", this.flow, this.watch.getTime(TimeUnit.MILLISECONDS)));
+ }
+
public void stopTimer() {
if (!this.watch.isStopped()) {
this.watch.stop();
diff --git a/app/server/appsmith-plugins/amazons3Plugin/src/main/java/com/external/plugins/AmazonS3Plugin.java b/app/server/appsmith-plugins/amazons3Plugin/src/main/java/com/external/plugins/AmazonS3Plugin.java
index b4166191fe8c..d14626056018 100644
--- a/app/server/appsmith-plugins/amazons3Plugin/src/main/java/com/external/plugins/AmazonS3Plugin.java
+++ b/app/server/appsmith-plugins/amazons3Plugin/src/main/java/com/external/plugins/AmazonS3Plugin.java
@@ -416,6 +416,9 @@ public Mono<ActionExecutionResult> executeParameterized(
DatasourceConfiguration datasourceConfiguration,
ActionConfiguration actionConfiguration) {
+ String printMessage =
+ Thread.currentThread().getName() + ": executeParameterized() called for AmazonS3 plugin.";
+ System.out.println(printMessage);
final Map<String, Object> formData = actionConfiguration.getFormData();
List<Map.Entry<String, String>> parameters = new ArrayList<>();
@@ -464,6 +467,8 @@ private Mono<ActionExecutionResult> executeCommon(
DatasourceConfiguration datasourceConfiguration,
ActionConfiguration actionConfiguration) {
+ String printMessage = Thread.currentThread().getName() + ": executeCommon() called for AmazonS3 plugin.";
+ System.out.println(printMessage);
final String[] query = new String[1];
Map<String, Object> requestProperties = new HashMap<>();
List<RequestParamDTO> requestParams = new ArrayList<>();
@@ -539,6 +544,8 @@ private Mono<ActionExecutionResult> executeCommon(
Object actionResult;
switch (s3Action) {
case LIST:
+ System.out.println(
+ Thread.currentThread().getName() + ": LIST action called for AmazonS3 plugin.");
String prefix = getDataValueSafelyFromFormData(formData, LIST_PREFIX, STRING_TYPE, "");
requestParams.add(new RequestParamDTO(LIST_PREFIX, prefix, null, null, null));
@@ -637,6 +644,8 @@ private Mono<ActionExecutionResult> executeCommon(
break;
case UPLOAD_FILE_FROM_BODY: {
+ System.out.println(Thread.currentThread().getName()
+ + ": UPLOAD_FILE_FROM_BODY action called for AmazonS3 plugin.");
requestParams.add(
new RequestParamDTO(ACTION_CONFIGURATION_PATH, path, null, null, null));
@@ -688,6 +697,8 @@ private Mono<ActionExecutionResult> executeCommon(
break;
}
case UPLOAD_MULTIPLE_FILES_FROM_BODY: {
+ System.out.println(Thread.currentThread().getName()
+ + ": UPLOAD_MULTIPLE_FILES_FROM_BODY action called for AmazonS3 plugin.");
requestParams.add(
new RequestParamDTO(ACTION_CONFIGURATION_PATH, path, null, null, null));
@@ -740,6 +751,8 @@ private Mono<ActionExecutionResult> executeCommon(
break;
}
case READ_FILE:
+ System.out.println(Thread.currentThread().getName()
+ + ": READ_FILE action called for AmazonS3 plugin.");
requestParams.add(
new RequestParamDTO(ACTION_CONFIGURATION_PATH, path, null, null, null));
@@ -757,6 +770,8 @@ private Mono<ActionExecutionResult> executeCommon(
actionResult = Map.of("fileData", result);
break;
case DELETE_FILE:
+ System.out.println(Thread.currentThread().getName()
+ + ": DELETE_FILE action called for AmazonS3 plugin.");
requestParams.add(
new RequestParamDTO(ACTION_CONFIGURATION_PATH, path, null, null, null));
@@ -768,6 +783,8 @@ private Mono<ActionExecutionResult> executeCommon(
actionResult = Map.of("status", "File deleted successfully");
break;
case DELETE_MULTIPLE_FILES:
+ System.out.println(Thread.currentThread().getName()
+ + ": DELETE_MULTIPLE_FILES action called for AmazonS3 plugin.");
requestParams.add(
new RequestParamDTO(ACTION_CONFIGURATION_PATH, path, null, null, null));
@@ -806,7 +823,7 @@ private Mono<ActionExecutionResult> executeCommon(
ActionExecutionResult actionExecutionResult = new ActionExecutionResult();
actionExecutionResult.setBody(result);
actionExecutionResult.setIsExecutionSuccess(true);
- log.debug("In the S3 Plugin, got action execution result");
+ System.out.println("In the S3 Plugin, got action execution result");
return Mono.just(actionExecutionResult);
})
.onErrorResume(e -> {
@@ -825,6 +842,8 @@ private Mono<ActionExecutionResult> executeCommon(
})
// Now set the request in the result to be returned to the server
.map(actionExecutionResult -> {
+ System.out.println(Thread.currentThread().getName()
+ + ": Setting the actionExecutionResult for AmazonS3 plugin.");
ActionExecutionRequest actionExecutionRequest = new ActionExecutionRequest();
actionExecutionRequest.setQuery(query[0]);
actionExecutionRequest.setProperties(requestProperties);
@@ -873,7 +892,8 @@ private DeleteObjectsRequest getDeleteObjectsRequest(String bucketName, List<Str
@Override
public Mono<AmazonS3> datasourceCreate(DatasourceConfiguration datasourceConfiguration) {
-
+ String printMessage = Thread.currentThread().getName() + ": datasourceCreate() called for AmazonS3 plugin.";
+ System.out.println(printMessage);
try {
Class.forName(S3_DRIVER);
} catch (ClassNotFoundException e) {
@@ -901,13 +921,17 @@ public Mono<AmazonS3> datasourceCreate(DatasourceConfiguration datasourceConfigu
@Override
public void datasourceDestroy(AmazonS3 connection) {
+ String printMessage =
+ Thread.currentThread().getName() + ": datasourceDestroy() called for AmazonS3 plugin.";
+ System.out.println(printMessage);
if (connection != null) {
Mono.fromCallable(() -> {
connection.shutdown();
return connection;
})
.onErrorResume(exception -> {
- log.debug("Error closing S3 connection.", exception);
+ System.out.println("Error closing S3 connection.");
+ exception.printStackTrace();
return Mono.empty();
})
.subscribeOn(scheduler)
@@ -917,6 +941,9 @@ public void datasourceDestroy(AmazonS3 connection) {
@Override
public Set<String> validateDatasource(DatasourceConfiguration datasourceConfiguration) {
+ String printMessage =
+ Thread.currentThread().getName() + ": validateDatasource() called for AmazonS3 plugin.";
+ System.out.println(printMessage);
Set<String> invalids = new HashSet<>();
if (datasourceConfiguration == null || datasourceConfiguration.getAuthentication() == null) {
@@ -978,6 +1005,8 @@ public Set<String> validateDatasource(DatasourceConfiguration datasourceConfigur
@Override
public Mono<DatasourceTestResult> testDatasource(DatasourceConfiguration datasourceConfiguration) {
+ String printMessage = Thread.currentThread().getName() + ": testDatasource() called for AmazonS3 plugin.";
+ System.out.println(printMessage);
if (datasourceConfiguration == null) {
return Mono.just(new DatasourceTestResult(
S3ErrorMessages.DS_AT_LEAST_ONE_MANDATORY_PARAMETER_MISSING_ERROR_MSG));
@@ -1000,6 +1029,8 @@ public Mono<DatasourceTestResult> testDatasource(DatasourceConfiguration datasou
* object with wrong credentials does not throw any exception.
* - Hence, adding a listBuckets() method call to test the connection.
*/
+ System.out.println(Thread.currentThread().getName()
+ + ": listBuckets() called for AmazonS3 plugin.");
connection.listBuckets();
return new DatasourceTestResult();
})
@@ -1037,6 +1068,8 @@ private Mono<DatasourceTestResult> testGoogleCloudStorage(DatasourceConfiguratio
return datasourceCreate(datasourceConfiguration)
.flatMap(connection -> Mono.fromCallable(() -> {
connection.listObjects(defaultBucket);
+ System.out.println(Thread.currentThread().getName()
+ + ": connection.listObjects() called for AmazonS3 plugin.");
return new DatasourceTestResult();
})
.onErrorResume(error -> {
@@ -1062,9 +1095,13 @@ private Mono<DatasourceTestResult> testGoogleCloudStorage(DatasourceConfiguratio
public Mono<DatasourceStructure> getStructure(
AmazonS3 connection, DatasourceConfiguration datasourceConfiguration) {
+ String printMessage = Thread.currentThread().getName() + ": getStructure() called for AmazonS3 plugin.";
+ System.out.println(printMessage);
return Mono.fromSupplier(() -> {
List<DatasourceStructure.Table> tableList;
try {
+ System.out.println(Thread.currentThread().getName()
+ + ": connection.listBuckets() called for AmazonS3 plugin.");
tableList = connection.listBuckets().stream()
/* Get name of each bucket */
.map(Bucket::getName)
@@ -1113,6 +1150,9 @@ public Object substituteValueInInput(
Object... args) {
String jsonBody = (String) input;
Param param = (Param) args[0];
+ String printMessage =
+ Thread.currentThread().getName() + ": substituteValueInInput() called for AmazonS3 plugin.";
+ System.out.println(printMessage);
return DataTypeStringUtils.jsonSmartReplacementPlaceholderWithValue(
jsonBody, value, null, insertedParams, null, param);
}
@@ -1158,6 +1198,9 @@ void uploadFileInS3(
@Override
public Mono<Void> sanitizeGenerateCRUDPageTemplateInfo(
List<ActionConfiguration> actionConfigurationList, Object... args) {
+ String printMessage = Thread.currentThread().getName()
+ + ": sanitizeGenerateCRUDPageTemplateInfo() called for AmazonS3 plugin.";
+ System.out.println(printMessage);
if (isEmpty(actionConfigurationList)) {
return Mono.empty();
}
diff --git a/app/server/appsmith-plugins/amazons3Plugin/src/main/java/com/external/utils/DatasourceUtils.java b/app/server/appsmith-plugins/amazons3Plugin/src/main/java/com/external/utils/DatasourceUtils.java
index 96b5a3b5f500..8a20d55b6993 100644
--- a/app/server/appsmith-plugins/amazons3Plugin/src/main/java/com/external/utils/DatasourceUtils.java
+++ b/app/server/appsmith-plugins/amazons3Plugin/src/main/java/com/external/utils/DatasourceUtils.java
@@ -101,7 +101,7 @@ public static S3ServiceProvider fromString(String name) throws AppsmithPluginExc
*/
public static AmazonS3ClientBuilder getS3ClientBuilder(DatasourceConfiguration datasourceConfiguration)
throws AppsmithPluginException {
-
+ System.out.println(Thread.currentThread().getName() + ": getS3ClientBuilder action called.");
DBAuth authentication = (DBAuth) datasourceConfiguration.getAuthentication();
String accessKey = authentication.getUsername();
String secretKey = authentication.getPassword();
diff --git a/app/server/appsmith-plugins/anthropicPlugin/src/main/java/com/external/plugins/AnthropicPlugin.java b/app/server/appsmith-plugins/anthropicPlugin/src/main/java/com/external/plugins/AnthropicPlugin.java
index 7d8559d93180..a91fc0ee11ce 100644
--- a/app/server/appsmith-plugins/anthropicPlugin/src/main/java/com/external/plugins/AnthropicPlugin.java
+++ b/app/server/appsmith-plugins/anthropicPlugin/src/main/java/com/external/plugins/AnthropicPlugin.java
@@ -74,6 +74,8 @@ protected AnthropicPluginExecutor(SharedConfig sharedConfig) {
@Override
public Mono<DatasourceTestResult> testDatasource(DatasourceConfiguration datasourceConfiguration) {
+ String printMessage = Thread.currentThread().getName() + ": testDatasource() called for Anthropic plugin.";
+ System.out.println(printMessage);
final ApiKeyAuth apiKeyAuth = (ApiKeyAuth) datasourceConfiguration.getAuthentication();
if (!StringUtils.hasText(apiKeyAuth.getValue())) {
return Mono.error(new AppsmithPluginException(
@@ -110,6 +112,10 @@ public Mono<ActionExecutionResult> executeParameterized(
ExecuteActionDTO executeActionDTO,
DatasourceConfiguration datasourceConfiguration,
ActionConfiguration actionConfiguration) {
+
+ String printMessage =
+ Thread.currentThread().getName() + ": executeParameterized() called for Anthropic plugin.";
+ System.out.println(printMessage);
// Get prompt from action configuration
List<Map.Entry<String, String>> parameters = new ArrayList<>();
@@ -248,6 +254,8 @@ private Object formatResponseBodyAsCompletionAPI(String model, byte[] response)
@Override
public Mono<TriggerResultDTO> trigger(
APIConnection connection, DatasourceConfiguration datasourceConfiguration, TriggerRequestDTO request) {
+ String printMessage = Thread.currentThread().getName() + ": trigger() called for Anthropic plugin.";
+ System.out.println(printMessage);
final ApiKeyAuth apiKeyAuth = (ApiKeyAuth) datasourceConfiguration.getAuthentication();
if (!StringUtils.hasText(apiKeyAuth.getValue())) {
return Mono.error(new AppsmithPluginException(
@@ -309,6 +317,9 @@ public Mono<TriggerResultDTO> trigger(
@Override
public Set<String> validateDatasource(DatasourceConfiguration datasourceConfiguration) {
+ String printMessage =
+ Thread.currentThread().getName() + ": validateDatasource() called for Anthropic plugin.";
+ System.out.println(printMessage);
return RequestUtils.validateApiKeyAuthDatasource(datasourceConfiguration);
}
diff --git a/app/server/appsmith-plugins/appsmithAiPlugin/src/main/java/com/external/plugins/AppsmithAiPlugin.java b/app/server/appsmith-plugins/appsmithAiPlugin/src/main/java/com/external/plugins/AppsmithAiPlugin.java
index 5d44245d8fa6..ff2335daff21 100644
--- a/app/server/appsmith-plugins/appsmithAiPlugin/src/main/java/com/external/plugins/AppsmithAiPlugin.java
+++ b/app/server/appsmith-plugins/appsmithAiPlugin/src/main/java/com/external/plugins/AppsmithAiPlugin.java
@@ -65,6 +65,9 @@ public AppsmithAiPluginExecutor(SharedConfig config) {
@Override
public Mono<APIConnection> datasourceCreate(DatasourceConfiguration datasourceConfiguration) {
+ String printMessage =
+ Thread.currentThread().getName() + ": datasourceCreate() called for AppsmithAI plugin.";
+ System.out.println(printMessage);
ApiKeyAuth apiKeyAuth = new ApiKeyAuth();
apiKeyAuth.setValue("test-key");
return ApiKeyAuthentication.create(apiKeyAuth)
@@ -78,6 +81,8 @@ public Mono<APIConnection> datasourceCreate(DatasourceConfiguration datasourceCo
@Override
public Mono<TriggerResultDTO> trigger(
APIConnection connection, DatasourceConfiguration datasourceConfiguration, TriggerRequestDTO request) {
+ String printMessage = Thread.currentThread().getName() + ": trigger() called for AppsmithAI plugin.";
+ System.out.println(printMessage);
SourceDetails sourceDetails = SourceDetails.createSourceDetails(request);
String requestType = request.getRequestType();
if (UPLOAD_FILES.equals(requestType)) {
@@ -143,6 +148,9 @@ public Mono<ActionExecutionResult> executeParameterized(
DatasourceConfiguration datasourceConfiguration,
ActionConfiguration actionConfiguration) {
+ String printMessage =
+ Thread.currentThread().getName() + ": executeParameterized() called for AppsmithAI plugin.";
+ System.out.println(printMessage);
// Get input from action configuration
List<Map.Entry<String, String>> parameters = new ArrayList<>();
@@ -162,6 +170,8 @@ public Mono<ActionExecutionResult> executeCommon(
List<Map.Entry<String, String>> insertedParams,
ExecuteActionDTO executeActionDTO) {
+ String printMessage = Thread.currentThread().getName() + ": executeCommon() called for AppsmithAI plugin.";
+ System.out.println(printMessage);
// Initializing object for error condition
ActionExecutionResult errorResult = new ActionExecutionResult();
initUtils.initializeResponseWithError(errorResult);
@@ -199,11 +209,16 @@ public Mono<ActionExecutionResult> executeCommon(
@Override
public Set<String> validateDatasource(DatasourceConfiguration datasourceConfiguration, boolean isEmbedded) {
+ String printMessage =
+ Thread.currentThread().getName() + ": validateDatasource() called for AppsmithAI plugin.";
+ System.out.println(printMessage);
return Set.of();
}
@Override
public Mono<DatasourceStorage> preSaveHook(DatasourceStorage datasourceStorage) {
+ String printMessage = Thread.currentThread().getName() + ": preSaveHook() called for AppsmithAI plugin.";
+ System.out.println(printMessage);
return aiServerService
.associateDatasource(createAssociateDTO(datasourceStorage))
.thenReturn(datasourceStorage);
@@ -211,6 +226,8 @@ public Mono<DatasourceStorage> preSaveHook(DatasourceStorage datasourceStorage)
@Override
public Mono<DatasourceStorage> preDeleteHook(DatasourceStorage datasourceStorage) {
+ String printMessage = Thread.currentThread().getName() + ": preDeleteHook() called for AppsmithAI plugin.";
+ System.out.println(printMessage);
DatasourceConfiguration datasourceConfiguration = datasourceStorage.getDatasourceConfiguration();
if (hasFiles(datasourceConfiguration)) {
return aiServerService
diff --git a/app/server/appsmith-plugins/arangoDBPlugin/src/main/java/com/external/plugins/ArangoDBPlugin.java b/app/server/appsmith-plugins/arangoDBPlugin/src/main/java/com/external/plugins/ArangoDBPlugin.java
index 2b25c529e51c..8c750a5e9e57 100644
--- a/app/server/appsmith-plugins/arangoDBPlugin/src/main/java/com/external/plugins/ArangoDBPlugin.java
+++ b/app/server/appsmith-plugins/arangoDBPlugin/src/main/java/com/external/plugins/ArangoDBPlugin.java
@@ -85,6 +85,8 @@ public Mono<ActionExecutionResult> execute(
DatasourceConfiguration datasourceConfiguration,
ActionConfiguration actionConfiguration) {
+ String printMessage = Thread.currentThread().getName() + ": execute() called for ArangoDB plugin.";
+ System.out.println(printMessage);
if (!isConnectionValid(db)) {
return Mono.error(new StaleConnectionException(CONNECTION_INVALID_ERROR_MSG));
}
@@ -99,7 +101,8 @@ public Mono<ActionExecutionResult> execute(
}
return Mono.fromCallable(() -> {
- log.debug("In the ArangoDBPlugin, got action execution result");
+ System.out.println(Thread.currentThread().getName()
+ + ": got action execution result from ArangoDB plugin.");
ArangoCursor<Map> cursor = db.query(query, null, null, Map.class);
ActionExecutionResult result = new ActionExecutionResult();
result.setIsExecutionSuccess(true);
@@ -176,7 +179,11 @@ private boolean isConnectionValid(ArangoDatabase db) {
@Override
public Mono<ArangoDatabase> datasourceCreate(DatasourceConfiguration datasourceConfiguration) {
+ String printMessage = Thread.currentThread().getName() + ": datasourceCreate() called for ArangoDB plugin.";
+ System.out.println(printMessage);
return (Mono<ArangoDatabase>) Mono.fromCallable(() -> {
+ System.out.println(
+ Thread.currentThread().getName() + ": inside schdeuled thread from ArangoDB plugin.");
List<Endpoint> nonEmptyEndpoints = datasourceConfiguration.getEndpoints().stream()
.filter(endpoint -> isNonEmptyEndpoint(endpoint))
.collect(Collectors.toList());
@@ -256,11 +263,17 @@ private boolean isAuthenticationMissing(DBAuth auth) {
@Override
public void datasourceDestroy(ArangoDatabase db) {
+ String printMessage =
+ Thread.currentThread().getName() + ": datasourceDestroy() called for ArangoDB plugin.";
+ System.out.println(printMessage);
db.arango().shutdown();
}
@Override
public Set<String> validateDatasource(DatasourceConfiguration datasourceConfiguration) {
+ String printMessage =
+ Thread.currentThread().getName() + ": validateDatasource() called for ArangoDB plugin.";
+ System.out.println(printMessage);
Set<String> invalids = new HashSet<>();
DBAuth auth = (DBAuth) datasourceConfiguration.getAuthentication();
@@ -305,12 +318,15 @@ private boolean isEndpointAvailable(List<Endpoint> endpoints) {
@Override
public Mono<DatasourceTestResult> testDatasource(ArangoDatabase connection) {
+ String printMessage = Thread.currentThread().getName() + ": testDatasource() called for ArangoDB plugin.";
+ System.out.println(printMessage);
return Mono.fromCallable(() -> {
connection.getVersion();
return new DatasourceTestResult();
})
.onErrorResume(error -> {
- log.error("Error when testing ArangoDB datasource.", error);
+ System.out.println("Error when testing ArangoDB datasource.");
+ error.printStackTrace();
return Mono.just(new DatasourceTestResult(arangoDBErrorUtils.getReadableError(error)));
})
.timeout(
@@ -321,6 +337,8 @@ public Mono<DatasourceTestResult> testDatasource(ArangoDatabase connection) {
@Override
public Mono<DatasourceStructure> getStructure(
ArangoDatabase db, DatasourceConfiguration datasourceConfiguration) {
+ String printMessage = Thread.currentThread().getName() + ": getStructure() called for ArangoDB plugin.";
+ System.out.println(printMessage);
final DatasourceStructure structure = new DatasourceStructure();
List<DatasourceStructure.Table> tables = new ArrayList<>();
structure.setTables(tables);
@@ -340,6 +358,8 @@ public Mono<DatasourceStructure> getStructure(
return Flux.fromIterable(collections)
.filter(collectionEntity -> !collectionEntity.getIsSystem())
.flatMap(collectionEntity -> {
+ System.out.println(Thread.currentThread().getName()
+ + ": got collectionEntity result from ArangoDB plugin.");
final ArrayList<DatasourceStructure.Column> columns = new ArrayList<>();
final ArrayList<DatasourceStructure.Template> templates = new ArrayList<>();
final String collectionName = collectionEntity.getName();
@@ -365,6 +385,8 @@ public Mono<DatasourceStructure> getStructure(
Mono.just(document));
})
.flatMap(tuple -> {
+ System.out.println(Thread.currentThread().getName()
+ + ": generating templates and structure in ArangoDB plugin.");
final ArrayList<DatasourceStructure.Column> columns = tuple.getT1();
final ArrayList<DatasourceStructure.Template> templates = tuple.getT2();
String collectionName = tuple.getT3();
@@ -381,6 +403,9 @@ public Mono<DatasourceStructure> getStructure(
@Override
public Mono<String> getEndpointIdentifierForRateLimit(DatasourceConfiguration datasourceConfiguration) {
+ String printMessage = Thread.currentThread().getName()
+ + ": getEndpointIdentifierForRateLimit() called for ArangoDB plugin.";
+ System.out.println(printMessage);
List<Endpoint> endpoints = datasourceConfiguration.getEndpoints();
String identifier = "";
// When hostname and port both are available, both will be used as identifier
diff --git a/app/server/appsmith-plugins/awsLambdaPlugin/src/main/java/com/external/plugins/AwsLambdaPlugin.java b/app/server/appsmith-plugins/awsLambdaPlugin/src/main/java/com/external/plugins/AwsLambdaPlugin.java
index 8a4757400ced..f9fe1e083178 100644
--- a/app/server/appsmith-plugins/awsLambdaPlugin/src/main/java/com/external/plugins/AwsLambdaPlugin.java
+++ b/app/server/appsmith-plugins/awsLambdaPlugin/src/main/java/com/external/plugins/AwsLambdaPlugin.java
@@ -60,10 +60,14 @@ public Mono<ActionExecutionResult> execute(
DatasourceConfiguration datasourceConfiguration,
ActionConfiguration actionConfiguration) {
+ String printMessage = Thread.currentThread().getName() + ": execute() called for AWS Lambda plugin.";
+ System.out.println(printMessage);
Map<String, Object> formData = actionConfiguration.getFormData();
String command = getDataValueSafelyFromFormData(formData, "command", STRING_TYPE);
return Mono.fromCallable(() -> {
+ System.out.println(Thread.currentThread().getName()
+ + ": creating action execution result for AWS Lambda plugin.");
ActionExecutionResult result;
switch (Objects.requireNonNull(command)) {
case "LIST_FUNCTIONS" -> result = listFunctions(actionConfiguration, connection);
@@ -90,6 +94,8 @@ public Mono<ActionExecutionResult> execute(
@Override
public Mono<TriggerResultDTO> trigger(
AWSLambda connection, DatasourceConfiguration datasourceConfiguration, TriggerRequestDTO request) {
+ String printMessage = Thread.currentThread().getName() + ": trigger() called for AWS Lambda plugin.";
+ System.out.println(printMessage);
if (!StringUtils.hasText(request.getRequestType())) {
throw new AppsmithPluginException(
AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, "request type is missing");
@@ -143,6 +149,9 @@ ActionExecutionResult listFunctions(ActionConfiguration actionConfiguration, AWS
@Override
public Mono<AWSLambda> datasourceCreate(DatasourceConfiguration datasourceConfiguration) {
+ String printMessage =
+ Thread.currentThread().getName() + ": datasourceCreate() called for AWS Lambda plugin.";
+ System.out.println(printMessage);
DBAuth authentication = (DBAuth) datasourceConfiguration.getAuthentication();
String accessKey = authentication.getUsername();
String secretKey = authentication.getPassword();
@@ -178,6 +187,8 @@ public void datasourceDestroy(AWSLambda connection) {
@Override
public Mono<DatasourceTestResult> testDatasource(AWSLambda connection) {
+ String printMessage = Thread.currentThread().getName() + ": testDatasource() called for AWS Lambda plugin.";
+ System.out.println(printMessage);
return Mono.fromCallable(() -> {
/*
* - Please note that as of 28 Jan 2021, the way Amazon client SDK works, creating a connection
@@ -207,6 +218,9 @@ public Mono<DatasourceTestResult> testDatasource(AWSLambda connection) {
@Override
public Set<String> validateDatasource(DatasourceConfiguration datasourceConfiguration) {
+ String printMessage =
+ Thread.currentThread().getName() + ": validateDatasource() called for AWS Lambda plugin.";
+ System.out.println(printMessage);
Set<String> invalids = new HashSet<>();
if (datasourceConfiguration == null
|| datasourceConfiguration.getAuthentication() == null
diff --git a/app/server/appsmith-plugins/databricksPlugin/src/main/java/com/external/plugins/DatabricksPlugin.java b/app/server/appsmith-plugins/databricksPlugin/src/main/java/com/external/plugins/DatabricksPlugin.java
index 3b40911be6a6..c25c9b5a77db 100644
--- a/app/server/appsmith-plugins/databricksPlugin/src/main/java/com/external/plugins/DatabricksPlugin.java
+++ b/app/server/appsmith-plugins/databricksPlugin/src/main/java/com/external/plugins/DatabricksPlugin.java
@@ -79,12 +79,16 @@ public Mono<ActionExecutionResult> execute(
DatasourceConfiguration datasourceConfiguration,
ActionConfiguration actionConfiguration) {
+ String printMessage = Thread.currentThread().getName() + ": execute() called for Databricks plugin.";
+ System.out.println(printMessage);
String query = actionConfiguration.getBody();
List<Map<String, Object>> rowsList = new ArrayList<>(INITIAL_ROWLIST_CAPACITY);
final List<String> columnsList = new ArrayList<>();
return (Mono<ActionExecutionResult>) Mono.fromCallable(() -> {
+ System.out.println(Thread.currentThread().getName()
+ + ": creating action execution result from Databricks plugin.");
try {
// Check for connection validity :
@@ -179,6 +183,9 @@ public Mono<ActionExecutionResult> execute(
@Override
public Mono<Connection> datasourceCreate(DatasourceConfiguration datasourceConfiguration) {
+ String printMessage =
+ Thread.currentThread().getName() + ": datasourceCreate() called for Databricks plugin.";
+ System.out.println(printMessage);
// Ensure the databricks JDBC driver is loaded.
try {
Class.forName(JDBC_DRIVER);
@@ -242,6 +249,8 @@ public Mono<Connection> datasourceCreate(DatasourceConfiguration datasourceConfi
}
return (Mono<Connection>) Mono.fromCallable(() -> {
+ System.out.println(
+ Thread.currentThread().getName() + ": creating connection from Databricks plugin.");
Connection connection = DriverManager.getConnection(url, p);
// Execute statements to default catalog and schema for all queries on this datasource.
@@ -292,6 +301,9 @@ public Mono<Connection> datasourceCreate(DatasourceConfiguration datasourceConfi
@Override
public void datasourceDestroy(Connection connection) {
+ String printMessage =
+ Thread.currentThread().getName() + ": datasourceDestroy() called for Databricks plugin.";
+ System.out.println(printMessage);
try {
if (connection != null) {
connection.close();
@@ -310,7 +322,11 @@ public Set<String> validateDatasource(DatasourceConfiguration datasourceConfigur
@Override
public Mono<DatasourceStructure> getStructure(
Connection connection, DatasourceConfiguration datasourceConfiguration) {
+ String printMessage = Thread.currentThread().getName() + ": getStructure() called for Databricks plugin.";
+ System.out.println(printMessage);
return Mono.fromSupplier(() -> {
+ System.out.println(Thread.currentThread().getName()
+ + ": fetching datasource structure from Databricks plugin.");
final DatasourceStructure structure = new DatasourceStructure();
final Map<String, DatasourceStructure.Table> tablesByName =
new TreeMap<>(String.CASE_INSENSITIVE_ORDER);
@@ -347,7 +363,6 @@ public Mono<DatasourceStructure> getStructure(
for (DatasourceStructure.Table table : structure.getTables()) {
table.getKeys().sort(Comparator.naturalOrder());
}
- log.debug("Got the structure of Databricks DB");
return structure;
} catch (SQLException e) {
return Mono.error(new AppsmithPluginException(
diff --git a/app/server/appsmith-plugins/dynamoPlugin/src/main/java/com/external/plugins/DynamoPlugin.java b/app/server/appsmith-plugins/dynamoPlugin/src/main/java/com/external/plugins/DynamoPlugin.java
index 964e9a993f6e..18a8219cc383 100644
--- a/app/server/appsmith-plugins/dynamoPlugin/src/main/java/com/external/plugins/DynamoPlugin.java
+++ b/app/server/appsmith-plugins/dynamoPlugin/src/main/java/com/external/plugins/DynamoPlugin.java
@@ -91,6 +91,8 @@ public static class DynamoPluginExecutor implements PluginExecutor<DynamoDbClien
private final Scheduler scheduler = Schedulers.boundedElastic();
public Object extractValue(Object rawItem) {
+ String printMessage = Thread.currentThread().getName() + ": extractValue() called for Dynamo plugin.";
+ System.out.println(printMessage);
if (!(rawItem instanceof List) && !(rawItem instanceof Map)) {
return rawItem;
@@ -162,7 +164,9 @@ public Object extractValue(Object rawItem) {
*/
public Object getTransformedResponse(Map<String, Object> rawResponse, String action)
throws AppsmithPluginException {
-
+ String printMessage =
+ Thread.currentThread().getName() + ": getTransformedResponse() called for Dynamo plugin.";
+ System.out.println(printMessage);
Map<String, Object> transformedResponse = new HashMap<>();
for (Map.Entry<String, Object> responseEntry : rawResponse.entrySet()) {
Object rawItems = responseEntry.getValue();
@@ -184,12 +188,15 @@ public Mono<ActionExecutionResult> execute(
DynamoDbClient ddb,
DatasourceConfiguration datasourceConfiguration,
ActionConfiguration actionConfiguration) {
-
+ String printMessage = Thread.currentThread().getName() + ": execute() called for Dynamo plugin.";
+ System.out.println(printMessage);
final Map<String, Object> requestData = new HashMap<>();
final String body = actionConfiguration.getBody();
List<RequestParamDTO> requestParams = new ArrayList<>();
return Mono.fromCallable(() -> {
+ System.out.println(Thread.currentThread().getName()
+ + ": creating action execution result from DynamoDB plugin.");
ActionExecutionResult result = new ActionExecutionResult();
final String action = actionConfiguration.getPath();
@@ -251,7 +258,6 @@ public Mono<ActionExecutionResult> execute(
}
result.setIsExecutionSuccess(true);
- log.debug("In the DynamoPlugin, got action execution result");
return result;
})
.onErrorResume(error -> {
@@ -280,8 +286,11 @@ public Mono<ActionExecutionResult> execute(
@Override
public Mono<DynamoDbClient> datasourceCreate(DatasourceConfiguration datasourceConfiguration) {
-
+ String printMessage = Thread.currentThread().getName() + ": datasourceCreate() called for Dynamo plugin.";
+ System.out.println(printMessage);
return Mono.fromCallable(() -> {
+ System.out.println(
+ Thread.currentThread().getName() + ": creating dynamodbclient from DynamoDB plugin.");
final DynamoDbClientBuilder builder = DynamoDbClient.builder();
if (!CollectionUtils.isEmpty(datasourceConfiguration.getEndpoints())) {
@@ -317,6 +326,8 @@ public void datasourceDestroy(DynamoDbClient client) {
@Override
public Set<String> validateDatasource(@NonNull DatasourceConfiguration datasourceConfiguration) {
+ String printMessage = Thread.currentThread().getName() + ": validateDatasource() called for Dynamo plugin.";
+ System.out.println(printMessage);
Set<String> invalids = new HashSet<>();
final DBAuth authentication = (DBAuth) datasourceConfiguration.getAuthentication();
@@ -341,6 +352,8 @@ public Set<String> validateDatasource(@NonNull DatasourceConfiguration datasourc
@Override
public Mono<DatasourceTestResult> testDatasource(DynamoDbClient connection) {
+ String printMessage = Thread.currentThread().getName() + ": testDatasource() called for Dynamo plugin.";
+ System.out.println(printMessage);
return Mono.fromCallable(() -> {
/*
* - Creating a connection with false credentials does not throw an error. Hence,
@@ -354,7 +367,11 @@ public Mono<DatasourceTestResult> testDatasource(DynamoDbClient connection) {
@Override
public Mono<DatasourceStructure> getStructure(
DynamoDbClient ddb, DatasourceConfiguration datasourceConfiguration) {
+ String printMessage = Thread.currentThread().getName() + ": getStructure() called for Dynamo plugin.";
+ System.out.println(printMessage);
return Mono.fromCallable(() -> {
+ System.out.println(Thread.currentThread().getName()
+ + ": creating datasourceStructure from DynamoDB plugin.");
final ListTablesResponse listTablesResponse = ddb.listTables();
List<DatasourceStructure.Table> tables = new ArrayList<>();
diff --git a/app/server/appsmith-plugins/elasticSearchPlugin/src/main/java/com/external/plugins/ElasticSearchPlugin.java b/app/server/appsmith-plugins/elasticSearchPlugin/src/main/java/com/external/plugins/ElasticSearchPlugin.java
index b1ed9a985e83..ffdfa491863a 100644
--- a/app/server/appsmith-plugins/elasticSearchPlugin/src/main/java/com/external/plugins/ElasticSearchPlugin.java
+++ b/app/server/appsmith-plugins/elasticSearchPlugin/src/main/java/com/external/plugins/ElasticSearchPlugin.java
@@ -80,12 +80,16 @@ public Mono<ActionExecutionResult> execute(
DatasourceConfiguration datasourceConfiguration,
ActionConfiguration actionConfiguration) {
+ String printMessage = Thread.currentThread().getName() + ": execute() called for ElasticSearch plugin.";
+ System.out.println(printMessage);
final Map<String, Object> requestData = new HashMap<>();
String query = actionConfiguration.getBody();
List<RequestParamDTO> requestParams = new ArrayList<>();
return Mono.fromCallable(() -> {
+ System.out.println(Thread.currentThread().getName()
+ + ": creating action execution result from ElasticSearch plugin.");
final ActionExecutionResult result = new ActionExecutionResult();
String body = query;
@@ -148,7 +152,7 @@ public Mono<ActionExecutionResult> execute(
}
result.setIsExecutionSuccess(true);
- log.debug("In the Elastic Search Plugin, got action execution result");
+ System.out.println("In the Elastic Search Plugin, got action execution result");
return Mono.just(result);
})
.flatMap(obj -> obj)
@@ -167,6 +171,8 @@ public Mono<ActionExecutionResult> execute(
})
// Now set the request in the result to be returned to the server
.map(result -> {
+ System.out.println(Thread.currentThread().getName()
+ + ": setting the request in the result to be returned from ElasticSearch plugin.");
ActionExecutionRequest request = new ActionExecutionRequest();
request.setProperties(requestData);
request.setQuery(query);
@@ -192,7 +198,9 @@ public Long getPort(Endpoint endpoint) {
@Override
public Mono<RestClient> datasourceCreate(DatasourceConfiguration datasourceConfiguration) {
-
+ String printMessage =
+ Thread.currentThread().getName() + ": datasourceCreate() called for ElasticSearch plugin.";
+ System.out.println(printMessage);
final List<HttpHost> hosts = new ArrayList<>();
for (Endpoint endpoint : datasourceConfiguration.getEndpoints()) {
@@ -247,6 +255,9 @@ public void datasourceDestroy(RestClient client) {
@Override
public Set<String> validateDatasource(DatasourceConfiguration datasourceConfiguration) {
+ String printMessage =
+ Thread.currentThread().getName() + ": validateDatasource() called for ElasticSearch plugin.";
+ System.out.println(printMessage);
Set<String> invalids = new HashSet<>();
if (CollectionUtils.isEmpty(datasourceConfiguration.getEndpoints())) {
@@ -271,6 +282,9 @@ public Set<String> validateDatasource(DatasourceConfiguration datasourceConfigur
@Override
public Mono<DatasourceTestResult> testDatasource(RestClient connection) {
+ String printMessage =
+ Thread.currentThread().getName() + ": testDatasource() called for ElasticSearch plugin.";
+ System.out.println(printMessage);
return Mono.fromCallable(() -> {
if (connection == null) {
return new DatasourceTestResult("Null client object to ElasticSearch.");
@@ -320,6 +334,9 @@ public Mono<DatasourceTestResult> testDatasource(RestClient connection) {
@Override
public Mono<String> getEndpointIdentifierForRateLimit(DatasourceConfiguration datasourceConfiguration) {
+ String printMessage = Thread.currentThread().getName()
+ + ": getEndpointIdentifierForRateLimit() called for ElasticSearch plugin.";
+ System.out.println(printMessage);
List<Endpoint> endpoints = datasourceConfiguration.getEndpoints();
String identifier = "";
// When hostname and port both are available, both will be used as identifier
diff --git a/app/server/appsmith-plugins/firestorePlugin/src/main/java/com/external/plugins/FirestorePlugin.java b/app/server/appsmith-plugins/firestorePlugin/src/main/java/com/external/plugins/FirestorePlugin.java
index fe20eb013935..e839027abe98 100644
--- a/app/server/appsmith-plugins/firestorePlugin/src/main/java/com/external/plugins/FirestorePlugin.java
+++ b/app/server/appsmith-plugins/firestorePlugin/src/main/java/com/external/plugins/FirestorePlugin.java
@@ -138,6 +138,9 @@ public Mono<ActionExecutionResult> executeParameterized(
DatasourceConfiguration datasourceConfiguration,
ActionConfiguration actionConfiguration) {
+ String printMessage =
+ Thread.currentThread().getName() + ": executeParameterized() called for Firestore plugin.";
+ System.out.println(printMessage);
Object smartSubstitutionObject = actionConfiguration.getFormData().getOrDefault(SMART_SUBSTITUTION, TRUE);
Boolean smartJsonSubstitution = TRUE;
if (smartSubstitutionObject instanceof Boolean) {
@@ -244,6 +247,8 @@ public Mono<ActionExecutionResult> executeParameterized(
}
try {
+ System.out.println(Thread.currentThread().getName()
+ + ": objectMapper.readValue invoked from Firestore plugin.");
return Mono.just(objectMapper.readValue(strBody, HashMap.class));
} catch (IOException e) {
return Mono.error(new AppsmithPluginException(
@@ -315,6 +320,8 @@ && isTimestampAndDeleteFieldValuePathEmpty(formData)) {
})
// Now set the request in the result to be returned to the server
.map(result -> {
+ System.out.println(Thread.currentThread().getName()
+ + ": setting the request in action execution result from Firestore plugin.");
ActionExecutionRequest request = new ActionExecutionRequest();
request.setProperties(requestData);
request.setQuery(query);
@@ -501,6 +508,9 @@ public Mono<ActionExecutionResult> handleDocumentLevelMethod(
Map<String, Object> mapBody,
String query,
List<RequestParamDTO> requestParams) {
+ String printMessage =
+ Thread.currentThread().getName() + ": handleDocumentLevelMethod() called for Firestore plugin.";
+ System.out.println(printMessage);
return Mono.just(method)
// Get the actual Java method to be called.
.flatMap(method1 -> {
@@ -578,7 +588,6 @@ public Mono<ActionExecutionResult> handleDocumentLevelMethod(
return Mono.error(e);
}
result.setIsExecutionSuccess(true);
- log.debug("In the Firestore Plugin, got action execution result");
return Mono.just(result);
});
}
@@ -594,7 +603,9 @@ public Mono<ActionExecutionResult> handleCollectionLevelMethod(
List<RequestParamDTO> requestParams,
Set<String> hintMessages,
ActionConfiguration actionConfiguration) {
-
+ String printMessage =
+ Thread.currentThread().getName() + ": handleCollectionLevelMethod() called for Firestore plugin.";
+ System.out.println(printMessage);
final CollectionReference collection = connection.collection(path);
if (method == Method.GET_COLLECTION) {
@@ -773,7 +784,6 @@ private Mono<ActionExecutionResult> methodGetCollection(
return Mono.error(e);
}
result.setIsExecutionSuccess(true);
- log.debug("In the Firestore Plugin, got action execution result for get collection");
return Mono.just(result);
});
}
@@ -824,7 +834,6 @@ private Mono<ActionExecutionResult> methodAddToCollection(
return Mono.error(e);
}
result.setIsExecutionSuccess(true);
- log.debug("In the Firestore Plugin, got action execution result for add to collection");
return Mono.just(result);
});
}
@@ -892,6 +901,9 @@ private Object resultToMap(Object objResult, boolean isRoot) throws AppsmithPlug
@Override
public Mono<Firestore> datasourceCreate(DatasourceConfiguration datasourceConfiguration) {
+ String printMessage =
+ Thread.currentThread().getName() + ": datasourceCreate() called for Firestore plugin.";
+ System.out.println(printMessage);
final DBAuth authentication = (DBAuth) datasourceConfiguration.getAuthentication();
final Set<String> errors = validateDatasource(datasourceConfiguration);
@@ -907,6 +919,8 @@ public Mono<Firestore> datasourceCreate(DatasourceConfiguration datasourceConfig
InputStream serviceAccount = new ByteArrayInputStream(clientJson.getBytes());
return Mono.fromSupplier(() -> {
+ System.out.println(Thread.currentThread().getName()
+ + ": instantiating googlecredentials object from Firestore plugin.");
GoogleCredentials credentials;
try {
credentials = GoogleCredentials.fromStream(serviceAccount);
@@ -937,12 +951,13 @@ public Mono<Firestore> datasourceCreate(DatasourceConfiguration datasourceConfig
@Override
public Mono<DatasourceTestResult> testDatasource(DatasourceConfiguration datasourceConfiguration) {
-
+ String printMessage = Thread.currentThread().getName() + ": testDatasource() called for Firestore plugin.";
+ System.out.println(printMessage);
return datasourceCreate(datasourceConfiguration).flatMap(connection -> {
try {
connection.listCollections();
} catch (FirestoreException e) {
- log.debug("Invalid datasource configuration : {}", e.getMessage());
+ System.out.println("Invalid datasource configuration: " + e.getMessage());
if (e.getMessage().contains("Metadata operations require admin authentication")) {
DatasourceTestResult datasourceTestResult = new DatasourceTestResult();
datasourceTestResult.setMessages(new HashSet<>(
@@ -964,6 +979,9 @@ public void datasourceDestroy(Firestore connection) {
@Override
public Set<String> validateDatasource(DatasourceConfiguration datasourceConfiguration) {
+ String printMessage =
+ Thread.currentThread().getName() + ": validateDatasource() called for Firestore plugin.";
+ System.out.println(printMessage);
final DBAuth authentication = (DBAuth) datasourceConfiguration.getAuthentication();
Set<String> invalids = new HashSet<>();
@@ -991,7 +1009,11 @@ public Set<String> validateDatasource(DatasourceConfiguration datasourceConfigur
@Override
public Mono<DatasourceStructure> getStructure(
Firestore connection, DatasourceConfiguration datasourceConfiguration) {
+ String printMessage = Thread.currentThread().getName() + ": getStructure() called for Firestore plugin.";
+ System.out.println(printMessage);
return Mono.fromSupplier(() -> {
+ System.out.println(Thread.currentThread().getName()
+ + ": invoking connection.listCollections() from Firestore plugin.");
Iterable<CollectionReference> collectionReferences = connection.listCollections();
List<DatasourceStructure.Table> tables = StreamSupport.stream(
diff --git a/app/server/appsmith-plugins/googleAiPlugin/src/main/java/com/external/plugins/GoogleAiPlugin.java b/app/server/appsmith-plugins/googleAiPlugin/src/main/java/com/external/plugins/GoogleAiPlugin.java
index 534fce99f754..1736acd1b38c 100644
--- a/app/server/appsmith-plugins/googleAiPlugin/src/main/java/com/external/plugins/GoogleAiPlugin.java
+++ b/app/server/appsmith-plugins/googleAiPlugin/src/main/java/com/external/plugins/GoogleAiPlugin.java
@@ -66,6 +66,8 @@ protected GoogleAiPluginExecutor(SharedConfig sharedConfig) {
*/
@Override
public Mono<DatasourceTestResult> testDatasource(DatasourceConfiguration datasourceConfiguration) {
+ String printMessage = Thread.currentThread().getName() + ": testDatasource() called for GoogleAI plugin.";
+ System.out.println(printMessage);
final ApiKeyAuth apiKeyAuth = (ApiKeyAuth) datasourceConfiguration.getAuthentication();
if (!StringUtils.hasText(apiKeyAuth.getValue())) {
return Mono.error(new AppsmithPluginException(
@@ -96,6 +98,9 @@ public Mono<ActionExecutionResult> executeParameterized(
ExecuteActionDTO executeActionDTO,
DatasourceConfiguration datasourceConfiguration,
ActionConfiguration actionConfiguration) {
+ String printMessage =
+ Thread.currentThread().getName() + ": executeParameterized() called for GoogleAI plugin.";
+ System.out.println(printMessage);
// Get prompt from action configuration
List<Map.Entry<String, String>> parameters = new ArrayList<>();
@@ -194,11 +199,16 @@ public Mono<ActionExecutionResult> executeParameterized(
@Override
public Mono<TriggerResultDTO> trigger(
APIConnection connection, DatasourceConfiguration datasourceConfiguration, TriggerRequestDTO request) {
+ String printMessage = Thread.currentThread().getName() + ": trigger() called for GoogleAI plugin.";
+ System.out.println(printMessage);
return Mono.just(new TriggerResultDTO(getDataToMap(GoogleAIConstants.GOOGLE_AI_MODELS)));
}
@Override
public Set<String> validateDatasource(DatasourceConfiguration datasourceConfiguration) {
+ String printMessage =
+ Thread.currentThread().getName() + ": validateDatasource() called for GoogleAI plugin.";
+ System.out.println(printMessage);
return RequestUtils.validateApiKeyAuthDatasource(datasourceConfiguration);
}
diff --git a/app/server/appsmith-plugins/googleSheetsPlugin/src/main/java/com/external/plugins/GoogleSheetsPlugin.java b/app/server/appsmith-plugins/googleSheetsPlugin/src/main/java/com/external/plugins/GoogleSheetsPlugin.java
index 5f6cd38dec88..95bc2d4c4325 100644
--- a/app/server/appsmith-plugins/googleSheetsPlugin/src/main/java/com/external/plugins/GoogleSheetsPlugin.java
+++ b/app/server/appsmith-plugins/googleSheetsPlugin/src/main/java/com/external/plugins/GoogleSheetsPlugin.java
@@ -82,6 +82,9 @@ public Mono<ActionExecutionResult> executeParameterized(
DatasourceConfiguration datasourceConfiguration,
ActionConfiguration actionConfiguration) {
+ String printMessage =
+ Thread.currentThread().getName() + ": executeParameterized() called for GoogleSheets plugin.";
+ System.out.println(printMessage);
boolean smartJsonSubstitution;
final Map<String, Object> formData = actionConfiguration.getFormData();
List<Map.Entry<String, String>> parameters = new ArrayList<>();
@@ -140,6 +143,9 @@ public Mono<ActionExecutionResult> executeCommon(
DatasourceConfiguration datasourceConfiguration,
ActionConfiguration actionConfiguration) {
+ String printMessage =
+ Thread.currentThread().getName() + ": executeCommon() called for GoogleSheets plugin.";
+ System.out.println(printMessage);
// Initializing object for error condition
ActionExecutionResult errorResult = new ActionExecutionResult();
errorResult.setStatusCode(GSheetsPluginError.QUERY_EXECUTION_FAILED.getAppErrorCode());
@@ -249,7 +255,8 @@ public Mono<ActionExecutionResult> executeCommon(
})
.onErrorResume(e -> {
errorResult.setBody(Exceptions.unwrap(e).getMessage());
- log.debug("Received error on Google Sheets action execution", e);
+ System.out.println("Received error on Google Sheets action execution");
+ e.printStackTrace();
if (!(e instanceof AppsmithPluginException)) {
e = new AppsmithPluginException(
GSheetsPluginError.QUERY_EXECUTION_FAILED,
@@ -317,6 +324,8 @@ public Object substituteValueInInput(
@Override
public Mono<TriggerResultDTO> trigger(
Void connection, DatasourceConfiguration datasourceConfiguration, TriggerRequestDTO request) {
+ String printMessage = Thread.currentThread().getName() + ": trigger() called for GoogleSheets plugin.";
+ System.out.println(printMessage);
final TriggerMethod triggerMethod = GoogleSheetsMethodStrategy.getTriggerMethod(request, objectMapper);
MethodConfig methodConfig = new MethodConfig(request);
@@ -387,6 +396,9 @@ public void updateCrudTemplateFormData(
Map<String, Object> formData,
Map<String, String> mappedColumns,
Map<String, String> pluginSpecificTemplateParams) {
+ String printMessage =
+ Thread.currentThread().getName() + ": updateCrudTemplateFormData() called for GoogleSheets plugin.";
+ System.out.println(printMessage);
pluginSpecificTemplateParams.forEach((k, v) -> {
if (formData.containsKey(k)) {
setDataValueSafelyInFormData(formData, k, v);
@@ -400,6 +412,9 @@ public void updateCrudTemplateFormData(
@Override
public Mono<DatasourceConfiguration> getDatasourceMetadata(DatasourceConfiguration datasourceConfiguration) {
+ String printMessage =
+ Thread.currentThread().getName() + ": getDatasourceMetadata() called for GoogleSheets plugin.";
+ System.out.println(printMessage);
return GetDatasourceMetadataMethod.getDatasourceMetadata(datasourceConfiguration);
}
}
diff --git a/app/server/appsmith-plugins/graphqlPlugin/src/main/java/com/external/plugins/GraphQLPlugin.java b/app/server/appsmith-plugins/graphqlPlugin/src/main/java/com/external/plugins/GraphQLPlugin.java
index 14b61d10a76f..68c057bfa3c8 100644
--- a/app/server/appsmith-plugins/graphqlPlugin/src/main/java/com/external/plugins/GraphQLPlugin.java
+++ b/app/server/appsmith-plugins/graphqlPlugin/src/main/java/com/external/plugins/GraphQLPlugin.java
@@ -85,6 +85,9 @@ public Mono<ActionExecutionResult> executeParameterized(
DatasourceConfiguration datasourceConfiguration,
ActionConfiguration actionConfiguration) {
+ String printMessage =
+ Thread.currentThread().getName() + ": executeParameterized() called for GraphQL plugin.";
+ System.out.println(printMessage);
final List<Property> properties = actionConfiguration.getPluginSpecifiedTemplates();
List<Map.Entry<String, String>> parameters = new ArrayList<>();
@@ -161,6 +164,8 @@ public Mono<ActionExecutionResult> executeCommon(
ActionConfiguration actionConfiguration,
List<Map.Entry<String, String>> insertedParams) {
+ String printMessage = Thread.currentThread().getName() + ": executeCommon() called for GraphQL plugin.";
+ System.out.println(printMessage);
// Initializing object for error condition
ActionExecutionResult errorResult = new ActionExecutionResult();
initUtils.initializeResponseWithError(errorResult);
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 8d451d2ca959..f097f99bd7d0 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
@@ -12,6 +12,7 @@
import com.appsmith.external.helpers.DataTypeStringUtils;
import com.appsmith.external.helpers.MustacheHelper;
import com.appsmith.external.helpers.PluginUtils;
+import com.appsmith.external.helpers.Stopwatch;
import com.appsmith.external.models.ActionConfiguration;
import com.appsmith.external.models.ActionExecutionRequest;
import com.appsmith.external.models.ActionExecutionResult;
@@ -243,6 +244,9 @@ public Mono<ActionExecutionResult> executeParameterized(
DatasourceConfiguration datasourceConfiguration,
ActionConfiguration actionConfiguration) {
+ String printMessage =
+ Thread.currentThread().getName() + ": executeParameterized() called for Mongo plugin.";
+ System.out.println(printMessage);
final Map<String, Object> formData = actionConfiguration.getFormData();
List<Map.Entry<String, String>> parameters = new ArrayList<>();
@@ -304,8 +308,10 @@ public Mono<ActionExecutionResult> executeCommon(
ActionConfiguration actionConfiguration,
List<Map.Entry<String, String>> parameters) {
+ String printMessage = Thread.currentThread().getName() + ": executeCommon() called for Mongo plugin.";
+ System.out.println(printMessage);
if (mongoClient == null) {
- log.info("Encountered null connection in MongoDB plugin. Reporting back.");
+ System.out.println("Encountered null connection in MongoDB plugin. Reporting back.");
throw new StaleConnectionException(MONGO_CLIENT_NULL_ERROR_MSG);
}
Mono<Document> mongoOutputMono;
@@ -313,6 +319,7 @@ public Mono<ActionExecutionResult> executeCommon(
String query;
List<RequestParamDTO> requestParams;
try {
+ System.out.println(Thread.currentThread().getName() + ": mongoClient.getDatabase from Mongo plugin.");
MongoDatabase database = mongoClient.getDatabase(getDatabaseName(datasourceConfiguration));
final Map<String, Object> formData = actionConfiguration.getFormData();
@@ -379,9 +386,14 @@ public Mono<ActionExecutionResult> executeCommon(
`new` field in the command. Let's return that value to the user.
*/
if (outputJson.has(VALUE)) {
+ System.out.println(Thread.currentThread().getName()
+ + ": objectMapper.readTree.VALUE from Mongo plugin.");
+ Stopwatch processStopwatch =
+ new Stopwatch("Mongo Plugin objectMapper readTree.VALUE");
result.setBody(objectMapper.readTree(
cleanUp(new JSONObject().put(VALUE, outputJson.get(VALUE)))
.toString()));
+ processStopwatch.stopAndLogTimeInMillisWithSysOut();
}
/*
@@ -389,9 +401,14 @@ public Mono<ActionExecutionResult> executeCommon(
results. In case there are no results for find, this key is not present in the result json.
*/
if (outputJson.has("cursor")) {
+ System.out.println(Thread.currentThread().getName()
+ + ": objectMapper.readTree.CURSOR from Mongo plugin.");
+ Stopwatch processStopwatch =
+ new Stopwatch("Mongo Plugin objectMapper readTree.CURSOR");
JSONArray outputResult = (JSONArray) cleanUp(
outputJson.getJSONObject("cursor").getJSONArray("firstBatch"));
result.setBody(objectMapper.readTree(outputResult.toString()));
+ processStopwatch.stopAndLogTimeInMillisWithSysOut();
}
/*
@@ -400,8 +417,12 @@ public Mono<ActionExecutionResult> executeCommon(
number of documents inserted.
*/
if (outputJson.has("n")) {
+ System.out.println(Thread.currentThread().getName()
+ + ": objectMapper.readTree.N from Mongo plugin.");
+ Stopwatch processStopwatch = new Stopwatch("Mongo Plugin objectMapper readTree.N");
JSONObject body = new JSONObject().put("n", outputJson.getBigInteger("n"));
result.setBody(objectMapper.readTree(body.toString()));
+ processStopwatch.stopAndLogTimeInMillisWithSysOut();
headerArray.put(body);
}
@@ -410,9 +431,14 @@ public Mono<ActionExecutionResult> executeCommon(
documents updated.
*/
if (outputJson.has(N_MODIFIED)) {
+ System.out.println(Thread.currentThread().getName()
+ + ": objectMapper.readTree.N_MODIFIED from Mongo plugin.");
+ Stopwatch processStopwatch =
+ new Stopwatch("Mongo Plugin objectMapper readTree.N_MODIFIED");
JSONObject body =
new JSONObject().put(N_MODIFIED, outputJson.getBigInteger(N_MODIFIED));
result.setBody(objectMapper.readTree(body.toString()));
+ processStopwatch.stopAndLogTimeInMillisWithSysOut();
headerArray.put(body);
}
@@ -422,14 +448,25 @@ public Mono<ActionExecutionResult> executeCommon(
if (outputJson.has(VALUES)) {
JSONArray outputResult = (JSONArray) cleanUp(outputJson.getJSONArray(VALUES));
+ System.out.println(Thread.currentThread().getName()
+ + ": objectMapper.createObjectNode from Mongo plugin.");
+ Stopwatch processStopwatch =
+ new Stopwatch("Mongo Plugin objectMapper createObjectNode");
ObjectNode resultNode = objectMapper.createObjectNode();
+ processStopwatch.stopAndLogTimeInMillisWithSysOut();
// Create a JSON structure with the results stored with a key to abide by the
// Server-Client contract of only sending array of objects in result.
+ Stopwatch processStopwatch1 =
+ new Stopwatch("Mongo Plugin objectMapper readTree outputResult");
resultNode.putArray(VALUES).addAll((ArrayNode)
objectMapper.readTree(outputResult.toString()));
+ processStopwatch1.stopAndLogTimeInMillisWithSysOut();
+ Stopwatch processStopwatch2 =
+ new Stopwatch("Mongo Plugin objectMapper readTree resultNode");
result.setBody(objectMapper.readTree(resultNode.toString()));
+ processStopwatch2.stopAndLogTimeInMillisWithSysOut();
}
/*
@@ -440,7 +477,11 @@ public Mono<ActionExecutionResult> executeCommon(
JSONObject statusJson = new JSONObject().put("ok", status);
headerArray.put(statusJson);
+ System.out.println(
+ Thread.currentThread().getName() + ": objectMapper readTree for Mongo plugin.");
+ Stopwatch processStopwatch = new Stopwatch("Mongo Plugin objectMapper readTree");
result.setHeaders(objectMapper.readTree(headerArray.toString()));
+ processStopwatch.stopAndLogTimeInMillisWithSysOut();
} catch (JsonProcessingException e) {
return Mono.error(new AppsmithPluginException(
MongoPluginError.QUERY_EXECUTION_FAILED,
@@ -452,7 +493,8 @@ public Mono<ActionExecutionResult> executeCommon(
})
.onErrorResume(error -> {
if (error instanceof StaleConnectionException) {
- log.debug("The mongo connection seems to have been invalidated or doesn't exist anymore");
+ System.out.println(
+ "The mongo connection seems to have been invalidated or doesn't exist anymore");
return Mono.error(error);
} else if (!(error instanceof AppsmithPluginException)) {
error = new AppsmithPluginException(
@@ -467,6 +509,8 @@ public Mono<ActionExecutionResult> executeCommon(
})
// Now set the request in the result to be returned to the server
.map(actionExecutionResult -> {
+ System.out.println(Thread.currentThread().getName()
+ + ": building actionExecutionResult from Mongo plugin.");
ActionExecutionRequest request = new ActionExecutionRequest();
request.setQuery(query);
if (!parameters.isEmpty()) {
@@ -494,6 +538,8 @@ public Mono<ActionExecutionResult> executeCommon(
*/
@Override
public String sanitizeReplacement(String replacementValue, DataType dataType) {
+ String printMessage = Thread.currentThread().getName() + ": sanitizeReplacement() called for Mongo plugin.";
+ System.out.println(printMessage);
replacementValue = removeOrAddQuotesAroundMongoDBSpecialTypes(replacementValue);
if (DataType.BSON_SPECIAL_DATA_TYPES.equals(dataType)) {
@@ -521,6 +567,10 @@ For all other data types the replacementValue is prepared for replacement (by us
*/
@Override
public ActionConfiguration getSchemaPreviewActionConfig(Template queryTemplate, Boolean isMock) {
+
+ String printMessage =
+ Thread.currentThread().getName() + ": getSchemaPreviewActionConfig() called for Mongo plugin.";
+ System.out.println(printMessage);
// For mongo, currently this experiment will only exist for mock DB movies
// Later on we can extend it for all mongo datasources
if (isMock) {
@@ -581,7 +631,12 @@ private String removeOrAddQuotesAroundMongoDBSpecialTypes(String query) {
try {
argWithoutQuotes = matcher.group(4);
if (specialType.isQuotesRequiredAroundParameter()) {
+ System.out.println(Thread.currentThread().getName()
+ + ": objectMapper writeValueAsString for Mongo plugin.");
+ Stopwatch processStopwatch =
+ new Stopwatch("Mongo Plugin objectMapper writeValueAsString");
argWithoutQuotes = objectMapper.writeValueAsString(argWithoutQuotes);
+ processStopwatch.stopAndLogTimeInMillisWithSysOut();
}
} catch (JsonProcessingException e) {
throw new AppsmithPluginException(
@@ -703,9 +758,12 @@ public Mono<MongoClient> datasourceCreate(DatasourceConfiguration datasourceConf
a user that doesn't have write permissions on the database.
Ref: https://api.mongodb.com/java/2.13/com/mongodb/DB.html#setReadOnly-java.lang.Boolean-
*/
-
+ String printMessage = Thread.currentThread().getName() + ": datasourceCreate() called for Mongo plugin.";
+ System.out.println(printMessage);
return Mono.just(datasourceConfiguration)
.flatMap(dsConfig -> {
+ System.out.println(
+ Thread.currentThread().getName() + ": buildClientURI called from Mongo plugin.");
try {
return Mono.just(buildClientURI(dsConfig));
} catch (AppsmithPluginException e) {
@@ -745,6 +803,8 @@ public void datasourceDestroy(MongoClient mongoClient) {
@Override
public Set<String> validateDatasource(DatasourceConfiguration datasourceConfiguration) {
+ String printMessage = Thread.currentThread().getName() + ": validateDatasource() called for Mongo plugin.";
+ System.out.println(printMessage);
Set<String> invalids = new HashSet<>();
List<Property> properties = datasourceConfiguration.getProperties();
DBAuth authentication = (DBAuth) datasourceConfiguration.getAuthentication();
@@ -833,6 +893,8 @@ public Set<String> validateDatasource(DatasourceConfiguration datasourceConfigur
@Override
public Mono<DatasourceTestResult> testDatasource(DatasourceConfiguration datasourceConfiguration) {
+ String printMessage = Thread.currentThread().getName() + ": testDatasource() called for Mongo plugin.";
+ System.out.println(printMessage);
Function<TimeoutException, Throwable> timeoutExceptionThrowableFunction =
error -> new AppsmithPluginException(
AppsmithPluginError.PLUGIN_DATASOURCE_TIMEOUT_ERROR,
@@ -840,6 +902,8 @@ public Mono<DatasourceTestResult> testDatasource(DatasourceConfiguration datasou
return datasourceCreate(datasourceConfiguration)
.flatMap(mongoClient -> {
+ System.out.println(
+ Thread.currentThread().getName() + ":Finding list of databases for Mongo plugin.");
final Publisher<String> result = mongoClient.listDatabaseNames();
final Mono<List<String>> documentMono =
Flux.from(result).collectList().cache();
@@ -899,6 +963,8 @@ public Mono<DatasourceTestResult> testDatasource(DatasourceConfiguration datasou
@Override
public Mono<DatasourceStructure> getStructure(
MongoClient mongoClient, DatasourceConfiguration datasourceConfiguration, Boolean isMock) {
+ String printMessage = Thread.currentThread().getName() + ": getStructure() called for Mongo plugin.";
+ System.out.println(printMessage);
final DatasourceStructure structure = new DatasourceStructure();
List<DatasourceStructure.Table> tables = new ArrayList<>();
structure.setTables(tables);
@@ -1030,6 +1096,9 @@ public Mono<ActionExecutionResult> execute(
*/
@Override
public void extractAndSetNativeQueryFromFormData(ActionConfiguration actionConfiguration) {
+ String printMessage = Thread.currentThread().getName()
+ + ": extractAndSetNativeQueryFromFormData() called for Mongo plugin.";
+ System.out.println(printMessage);
Map<String, Object> formData = actionConfiguration.getFormData();
if (formData != null && !formData.isEmpty()) {
/* If it is not raw command, then it must be one of the mongo form commands */
diff --git a/app/server/appsmith-plugins/mssqlPlugin/src/main/java/com/external/plugins/MssqlPlugin.java b/app/server/appsmith-plugins/mssqlPlugin/src/main/java/com/external/plugins/MssqlPlugin.java
index 130b67dce889..36e0c57c1022 100644
--- a/app/server/appsmith-plugins/mssqlPlugin/src/main/java/com/external/plugins/MssqlPlugin.java
+++ b/app/server/appsmith-plugins/mssqlPlugin/src/main/java/com/external/plugins/MssqlPlugin.java
@@ -8,6 +8,7 @@
import com.appsmith.external.exceptions.pluginExceptions.StaleConnectionException;
import com.appsmith.external.helpers.DataTypeServiceUtils;
import com.appsmith.external.helpers.MustacheHelper;
+import com.appsmith.external.helpers.Stopwatch;
import com.appsmith.external.models.ActionConfiguration;
import com.appsmith.external.models.ActionExecutionRequest;
import com.appsmith.external.models.ActionExecutionResult;
@@ -134,6 +135,9 @@ public Mono<ActionExecutionResult> executeParameterized(
DatasourceConfiguration datasourceConfiguration,
ActionConfiguration actionConfiguration) {
+ String printMessage =
+ Thread.currentThread().getName() + ": executeParameterized() called for MSSQL plugin.";
+ System.out.println(printMessage);
String query = actionConfiguration.getBody();
// Check for query parameter before performing the probably expensive fetch connection from the pool op.
if (!StringUtils.hasLength(query)) {
@@ -182,6 +186,8 @@ public Mono<ActionExecutionResult> executeCommon(
List<MustacheBindingToken> mustacheValuesInOrder,
ExecuteActionDTO executeActionDTO) {
+ String printMessage = Thread.currentThread().getName() + ": executeCommon() called for MSSQL plugin.";
+ System.out.println(printMessage);
final Map<String, Object> requestData = new HashMap<>();
requestData.put("preparedStatement", TRUE.equals(preparedStatement) ? true : false);
@@ -192,6 +198,8 @@ public Mono<ActionExecutionResult> executeCommon(
List.of(new RequestParamDTO(ACTION_CONFIGURATION_BODY, transformedQuery, null, null, psParams));
return Mono.fromCallable(() -> {
+ System.out.println(
+ Thread.currentThread().getName() + ": within mono callable from MSSQL plugin.");
boolean isResultSet;
Connection sqlConnectionFromPool;
Statement statement = null;
@@ -219,7 +227,7 @@ public Mono<ActionExecutionResult> executeCommon(
if (sqlConnectionFromPool == null
|| sqlConnectionFromPool.isClosed()
|| !sqlConnectionFromPool.isValid(VALIDITY_CHECK_TIMEOUT)) {
- log.info("Encountered stale connection in MsSQL plugin. Reporting back.");
+ System.out.println("Encountered stale connection in MsSQL plugin. Reporting back.");
if (sqlConnectionFromPool == null) {
return Mono.error(new StaleConnectionException(CONNECTION_NULL_ERROR_MSG));
@@ -238,7 +246,8 @@ public Mono<ActionExecutionResult> executeCommon(
// This exception is thrown only when the timeout to `isValid` is negative. Since, that's
// not the case,
// here, this should never happen.
- log.error("Error checking validity of MsSQL connection.", error);
+ System.out.println("Error checking validity of MsSQL connection.");
+ error.printStackTrace();
}
// Log HikariCP status
@@ -297,10 +306,13 @@ public Mono<ActionExecutionResult> executeCommon(
}
ActionExecutionResult result = new ActionExecutionResult();
+ System.out.println(Thread.currentThread().getName()
+ + ": objectMapper.valueToTree invoked from MSSQL plugin.");
+ Stopwatch processStopwatch = new Stopwatch("MSSQL Plugin objectMapper valueToTree");
result.setBody(objectMapper.valueToTree(rowsList));
+ processStopwatch.stopAndLogTimeInMillisWithSysOut();
result.setMessages(populateHintMessages(columnsList));
result.setIsExecutionSuccess(true);
- log.debug("In the MssqlPlugin, got action execution result");
return Mono.just(result);
})
.flatMap(obj -> obj)
@@ -316,6 +328,8 @@ public Mono<ActionExecutionResult> executeCommon(
})
// Now set the request in the result to be returned back to the server
.map(actionExecutionResult -> {
+ System.out.println(Thread.currentThread().getName()
+ + ": setting request in the actionExecutionResult from MSSQL plugin.");
ActionExecutionRequest request = new ActionExecutionRequest();
request.setQuery(query);
request.setProperties(requestData);
@@ -345,8 +359,10 @@ private Set<String> populateHintMessages(List<String> columnNames) {
@Override
public Mono<HikariDataSource> datasourceCreate(DatasourceConfiguration datasourceConfiguration) {
+ String printMessage = Thread.currentThread().getName() + ": datasourceCreate() called for MSSQL plugin.";
+ System.out.println(printMessage);
return Mono.fromCallable(() -> {
- log.debug("Connecting to SQL Server db");
+ System.out.println(Thread.currentThread().getName() + ": Connecting to SQL Server db");
return createConnectionPool(datasourceConfiguration);
})
.subscribeOn(scheduler);
@@ -361,6 +377,8 @@ public void datasourceDestroy(HikariDataSource connection) {
@Override
public Set<String> validateDatasource(@NonNull DatasourceConfiguration datasourceConfiguration) {
+ String printMessage = Thread.currentThread().getName() + ": validateDatasource() called for MSSQL plugin.";
+ System.out.println(printMessage);
Set<String> invalids = new HashSet<>();
if (isEmpty(datasourceConfiguration.getEndpoints())) {
@@ -404,6 +422,8 @@ public Mono<ActionExecutionResult> execute(
@Override
public Mono<DatasourceStructure> getStructure(
HikariDataSource connection, DatasourceConfiguration datasourceConfiguration) {
+ String printMessage = Thread.currentThread().getName() + ": getStructure() called for MSSQL plugin.";
+ System.out.println(printMessage);
return MssqlDatasourceUtils.getStructure(connection, datasourceConfiguration);
}
diff --git a/app/server/appsmith-plugins/mysqlPlugin/src/main/java/com/external/plugins/MySqlPlugin.java b/app/server/appsmith-plugins/mysqlPlugin/src/main/java/com/external/plugins/MySqlPlugin.java
index 58833ea9e1d8..68a9921add6b 100644
--- a/app/server/appsmith-plugins/mysqlPlugin/src/main/java/com/external/plugins/MySqlPlugin.java
+++ b/app/server/appsmith-plugins/mysqlPlugin/src/main/java/com/external/plugins/MySqlPlugin.java
@@ -9,6 +9,7 @@
import com.appsmith.external.helpers.MustacheHelper;
import com.appsmith.external.helpers.SSHTunnelContext;
import com.appsmith.external.helpers.SSHUtils;
+import com.appsmith.external.helpers.Stopwatch;
import com.appsmith.external.models.ActionConfiguration;
import com.appsmith.external.models.ActionExecutionRequest;
import com.appsmith.external.models.ActionExecutionResult;
@@ -182,6 +183,9 @@ public Mono<ActionExecutionResult> executeParameterized(
DatasourceConfiguration datasourceConfiguration,
ActionConfiguration actionConfiguration) {
+ String printMessage =
+ Thread.currentThread().getName() + ": executeParameterized() called for MySQL plugin.";
+ System.out.println(printMessage);
final Map<String, Object> requestData = new HashMap<>();
Boolean isPreparedStatement;
@@ -240,6 +244,9 @@ public Mono<ActionExecutionResult> executeParameterized(
@Override
public ActionConfiguration getSchemaPreviewActionConfig(Template queryTemplate, Boolean isMock) {
+ String printMessage =
+ Thread.currentThread().getName() + ": getSchemaPreviewActionConfig() called for MySQL plugin.";
+ System.out.println(printMessage);
ActionConfiguration actionConfig = new ActionConfiguration();
// Sets query body
actionConfig.setBody(queryTemplate.getBody());
@@ -255,6 +262,9 @@ public ActionConfiguration getSchemaPreviewActionConfig(Template queryTemplate,
@Override
public Mono<String> getEndpointIdentifierForRateLimit(DatasourceConfiguration datasourceConfiguration) {
+ String printMessage =
+ Thread.currentThread().getName() + ": getEndpointIdentifierForRateLimit() called for MySQL plugin.";
+ System.out.println(printMessage);
List<Endpoint> endpoints = datasourceConfiguration.getEndpoints();
SSHConnection sshProxy = datasourceConfiguration.getSshProxy();
String identifier = "";
@@ -285,6 +295,8 @@ public Mono<ActionExecutionResult> executeCommon(
List<MustacheBindingToken> mustacheValuesInOrder,
ExecuteActionDTO executeActionDTO,
Map<String, Object> requestData) {
+ String printMessage = Thread.currentThread().getName() + ": executeCommon() called for MySQL plugin.";
+ System.out.println(printMessage);
ConnectionPool connectionPool = connectionContext.getConnection();
SSHTunnelContext sshTunnelContext = connectionContext.getSshTunnelContext();
String query = actionConfiguration.getBody();
@@ -385,10 +397,16 @@ isConnectionValid && isSSHTunnelConnected(sshTunnelContext))
return resultMono
.map(res -> {
ActionExecutionResult result = new ActionExecutionResult();
+ System.out.println(
+ Thread.currentThread().getName()
+ + ": objectMapper.valueToTree from MySQL plugin.");
+ Stopwatch processStopwatch =
+ new Stopwatch("MySQL Plugin objectMapper valueToTree");
result.setBody(objectMapper.valueToTree(rowsList));
+ processStopwatch.stopAndLogTimeInMillisWithSysOut();
result.setMessages(populateHintMessages(columnsList));
result.setIsExecutionSuccess(true);
- log.debug("In the MySqlPlugin, got action execution result");
+ System.out.println("In the MySqlPlugin, got action execution result");
return result;
})
.onErrorResume(error -> {
@@ -428,6 +446,9 @@ isConnectionValid && isSSHTunnelConnected(sshTunnelContext))
})
// Now set the request in the result to be returned to the server
.map(actionExecutionResult -> {
+ System.out.println(
+ Thread.currentThread().getName()
+ + ": setting the request in actionExecutionResult from MySQL plugin.");
ActionExecutionRequest request = new ActionExecutionRequest();
request.setQuery(finalQuery);
request.setProperties(requestData);
@@ -470,7 +491,7 @@ private Flux<Result> createAndExecuteQueryFromConnection(
return Flux.from(connectionStatement.execute());
}
- log.debug("Query : {}", query);
+ System.out.println("Query : " + query);
List<Map.Entry<String, String>> parameters = new ArrayList<>();
try {
@@ -495,6 +516,8 @@ private Flux<Result> createAndExecuteQueryFromConnection(
@Override
public Mono<DatasourceTestResult> testDatasource(ConnectionContext<ConnectionPool> connectionContext) {
+ String printMessage = Thread.currentThread().getName() + ": testDatasource() called for MySQL plugin.";
+ System.out.println(printMessage);
ConnectionPool pool = connectionContext.getConnection();
return Mono.just(pool)
.flatMap(p -> p.create())
@@ -647,6 +670,8 @@ public Mono<ActionExecutionResult> execute(
@Override
public Mono<ConnectionContext<ConnectionPool>> datasourceCreate(
DatasourceConfiguration datasourceConfiguration) {
+ String printMessage = Thread.currentThread().getName() + ": datasourceCreate() called for MySQL plugin.";
+ System.out.println(printMessage);
return Mono.just(datasourceConfiguration).flatMap(ignore -> {
ConnectionContext<ConnectionPool> connectionContext;
try {
@@ -663,6 +688,8 @@ public Mono<ConnectionContext<ConnectionPool>> datasourceCreate(
@Override
public void datasourceDestroy(ConnectionContext<ConnectionPool> connectionContext) {
+ String printMessage = Thread.currentThread().getName() + ": datasourceDestroy() called for MySQL plugin.";
+ System.out.println(printMessage);
Mono.just(connectionContext)
.flatMap(ignore -> {
SSHTunnelContext sshTunnelContext = connectionContext.getSshTunnelContext();
@@ -677,7 +704,7 @@ public void datasourceDestroy(ConnectionContext<ConnectionPool> connectionContex
sshTunnelContext.getSshClient().disconnect();
sshTunnelContext.getThread().stop();
} catch (IOException e) {
- log.debug("Failed to destroy SSH tunnel context: {}", e.getMessage());
+ System.out.println("Failed to destroy SSH tunnel context: " + e.getMessage());
}
}
@@ -695,7 +722,8 @@ public void datasourceDestroy(ConnectionContext<ConnectionPool> connectionContex
connectionPool
.disposeLater()
.onErrorResume(exception -> {
- log.debug("Could not destroy MySQL connection pool", exception);
+ System.out.println("Could not destroy MySQL connection pool");
+ exception.printStackTrace();
return Mono.empty();
})
.subscribeOn(scheduler)
@@ -705,12 +733,16 @@ public void datasourceDestroy(ConnectionContext<ConnectionPool> connectionContex
@Override
public Set<String> validateDatasource(DatasourceConfiguration datasourceConfiguration) {
+ String printMessage = Thread.currentThread().getName() + ": validateDatasource() called for MySQL plugin.";
+ System.out.println(printMessage);
return MySqlDatasourceUtils.validateDatasource(datasourceConfiguration);
}
@Override
public Mono<DatasourceStructure> getStructure(
ConnectionContext<ConnectionPool> connectionContext, DatasourceConfiguration datasourceConfiguration) {
+ String printMessage = Thread.currentThread().getName() + ": getStructure() called for MySQL plugin.";
+ System.out.println(printMessage);
final DatasourceStructure structure = new DatasourceStructure();
final Map<String, DatasourceStructure.Table> tablesByName = new TreeMap<>(String.CASE_INSENSITIVE_ORDER);
final Map<String, DatasourceStructure.Key> keyRegistry = new HashMap<>();
@@ -769,6 +801,8 @@ isConnectionValid && isSSHTunnelConnected(sshTunnelContext))
})
.collectList()
.map(list -> {
+ System.out.println(
+ Thread.currentThread().getName() + ": getTemplates from MySQL plugin.");
/* Get templates for each table and put those in. */
getTemplates(tablesByName);
structure.setTables(new ArrayList<>(tablesByName.values()));
diff --git a/app/server/appsmith-plugins/openAiPlugin/src/main/java/com/external/plugins/OpenAiPlugin.java b/app/server/appsmith-plugins/openAiPlugin/src/main/java/com/external/plugins/OpenAiPlugin.java
index 967b6d1a3631..a4561b6fb4cd 100644
--- a/app/server/appsmith-plugins/openAiPlugin/src/main/java/com/external/plugins/OpenAiPlugin.java
+++ b/app/server/appsmith-plugins/openAiPlugin/src/main/java/com/external/plugins/OpenAiPlugin.java
@@ -75,6 +75,9 @@ public Mono<ActionExecutionResult> executeParameterized(
DatasourceConfiguration datasourceConfiguration,
ActionConfiguration actionConfiguration) {
+ String printMessage =
+ Thread.currentThread().getName() + ": executeParameterized() called for OpenAI plugin.";
+ System.out.println(printMessage);
// Get prompt from action configuration
List<Map.Entry<String, String>> parameters = new ArrayList<>();
@@ -92,6 +95,8 @@ public Mono<ActionExecutionResult> executeCommon(
ActionConfiguration actionConfiguration,
List<Map.Entry<String, String>> insertedParams) {
+ String printMessage = Thread.currentThread().getName() + ": executeCommon() called for OpenAI plugin.";
+ System.out.println(printMessage);
// Initializing object for error condition
ActionExecutionResult errorResult = new ActionExecutionResult();
initUtils.initializeResponseWithError(errorResult);
@@ -200,6 +205,8 @@ private String sha256(String base) {
@Override
public Set<String> validateDatasource(DatasourceConfiguration datasourceConfiguration) {
+ String printMessage = Thread.currentThread().getName() + ": validateDatasource() called for OpenAI plugin.";
+ System.out.println(printMessage);
return RequestUtils.validateBearerTokenDatasource(datasourceConfiguration);
}
@@ -207,6 +214,8 @@ public Set<String> validateDatasource(DatasourceConfiguration datasourceConfigur
public Mono<TriggerResultDTO> trigger(
APIConnection connection, DatasourceConfiguration datasourceConfiguration, TriggerRequestDTO request) {
+ String printMessage = Thread.currentThread().getName() + ": trigger() called for OpenAI plugin.";
+ System.out.println(printMessage);
// Authentication will already be valid at this point
final BearerTokenAuth bearerTokenAuth = (BearerTokenAuth) datasourceConfiguration.getAuthentication();
assert (bearerTokenAuth.getBearerToken() != null);
@@ -276,6 +285,8 @@ public Mono<TriggerResultDTO> trigger(
@Override
public Mono<DatasourceTestResult> testDatasource(DatasourceConfiguration datasourceConfiguration) {
+ String printMessage = Thread.currentThread().getName() + ": testDatasource() called for OpenAI plugin.";
+ System.out.println(printMessage);
final BearerTokenAuth bearerTokenAuth = (BearerTokenAuth) datasourceConfiguration.getAuthentication();
HttpMethod httpMethod = HttpMethod.GET;
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 3555dcdf9629..b6ff9f9cfbea 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
@@ -94,6 +94,8 @@ public static class OraclePluginExecutor implements SmartSubstitutionInterface,
@Override
public Mono<HikariDataSource> datasourceCreate(DatasourceConfiguration datasourceConfiguration) {
+ String printMessage = Thread.currentThread().getName() + ": datasourceCreate() called for Oracle plugin.";
+ System.out.println(printMessage);
try {
Class.forName(JDBC_DRIVER);
} catch (ClassNotFoundException e) {
@@ -104,7 +106,7 @@ public Mono<HikariDataSource> datasourceCreate(DatasourceConfiguration datasourc
}
return Mono.fromCallable(() -> {
- log.debug(Thread.currentThread().getName() + ": Connecting to Oracle db");
+ System.out.println(Thread.currentThread().getName() + ": Connecting to Oracle db");
return createConnectionPool(datasourceConfiguration);
})
.subscribeOn(scheduler);
@@ -117,6 +119,8 @@ public void datasourceDestroy(HikariDataSource connection) {
@Override
public Set<String> validateDatasource(DatasourceConfiguration datasourceConfiguration) {
+ String printMessage = Thread.currentThread().getName() + ": validateDatasource() called for Oracle plugin.";
+ System.out.println(printMessage);
return OracleDatasourceUtils.validateDatasource(datasourceConfiguration);
}
@@ -135,6 +139,10 @@ public Mono<ActionExecutionResult> executeParameterized(
ExecuteActionDTO executeActionDTO,
DatasourceConfiguration datasourceConfiguration,
ActionConfiguration actionConfiguration) {
+
+ String printMessage =
+ Thread.currentThread().getName() + ": executeParameterized() called for Oracle plugin.";
+ System.out.println(printMessage);
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.
@@ -193,6 +201,8 @@ private Mono<ActionExecutionResult> executeCommon(
List<MustacheBindingToken> mustacheValuesInOrder,
ExecuteActionDTO executeActionDTO) {
+ String printMessage = Thread.currentThread().getName() + ": executeCommon() called for Oracle plugin.";
+ System.out.println(printMessage);
final Map<String, Object> requestData = new HashMap<>();
requestData.put("preparedStatement", TRUE.equals(preparedStatement) ? true : false);
@@ -221,7 +231,8 @@ private Mono<ActionExecutionResult> executeCommon(
// 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.
- log.debug("Exception Occurred while getting connection from pool" + e.getMessage());
+ System.out.println(
+ "Exception Occurred while getting connection from pool" + e.getMessage());
e.printStackTrace(System.out);
return Mono.error(
e instanceof StaleConnectionException
@@ -274,9 +285,9 @@ private Mono<ActionExecutionResult> executeCommon(
statement,
preparedQuery);
} catch (SQLException e) {
- log.debug(Thread.currentThread().getName()
+ System.out.println(Thread.currentThread().getName()
+ ": In the OraclePlugin, got action execution error");
- log.debug(e.getMessage());
+ System.out.println(e.getMessage());
return Mono.error(new AppsmithPluginException(
OraclePluginError.QUERY_EXECUTION_FAILED,
OracleErrorMessages.QUERY_EXECUTION_FAILED_ERROR_MSG,
@@ -294,7 +305,7 @@ private Mono<ActionExecutionResult> executeCommon(
result.setBody(objectMapper.valueToTree(rowsList));
result.setMessages(populateHintMessages(columnsList));
result.setIsExecutionSuccess(true);
- log.debug(Thread.currentThread().getName()
+ System.out.println(Thread.currentThread().getName()
+ ": In the OraclePlugin, got action execution result");
return Mono.just(result);
})
@@ -325,6 +336,8 @@ private Mono<ActionExecutionResult> executeCommon(
@Override
public Mono<DatasourceStructure> getStructure(
HikariDataSource connectionPool, DatasourceConfiguration datasourceConfiguration) {
+ String printMessage = Thread.currentThread().getName() + ": getStructure() called for Oracle plugin.";
+ System.out.println(printMessage);
return OracleDatasourceUtils.getStructure(connectionPool, datasourceConfiguration);
}
@@ -433,6 +446,9 @@ public Object substituteValueInInput(
@Override
public Mono<String> getEndpointIdentifierForRateLimit(DatasourceConfiguration datasourceConfiguration) {
+ String printMessage = Thread.currentThread().getName()
+ + ": getEndpointIdentifierForRateLimit() called for Oracle plugin.";
+ System.out.println(printMessage);
List<Endpoint> endpoints = datasourceConfiguration.getEndpoints();
String identifier = "";
// When hostname and port both are available, both will be used as identifier
diff --git a/app/server/appsmith-plugins/postgresPlugin/src/main/java/com/external/plugins/PostgresPlugin.java b/app/server/appsmith-plugins/postgresPlugin/src/main/java/com/external/plugins/PostgresPlugin.java
index e037faa31016..8a6db99d5a6d 100644
--- a/app/server/appsmith-plugins/postgresPlugin/src/main/java/com/external/plugins/PostgresPlugin.java
+++ b/app/server/appsmith-plugins/postgresPlugin/src/main/java/com/external/plugins/PostgresPlugin.java
@@ -10,6 +10,7 @@
import com.appsmith.external.helpers.DataTypeServiceUtils;
import com.appsmith.external.helpers.MustacheHelper;
import com.appsmith.external.helpers.SSHUtils;
+import com.appsmith.external.helpers.Stopwatch;
import com.appsmith.external.models.ActionConfiguration;
import com.appsmith.external.models.ActionExecutionRequest;
import com.appsmith.external.models.ActionExecutionResult;
@@ -239,6 +240,9 @@ public Mono<ActionExecutionResult> executeParameterized(
DatasourceConfiguration datasourceConfiguration,
ActionConfiguration actionConfiguration) {
+ String printMessage =
+ Thread.currentThread().getName() + ": executeParameterized() called for Postgres plugin.";
+ System.out.println(printMessage);
String query = actionConfiguration.getBody();
// Check for query parameter before performing the probably expensive fetch
// connection from the pool op.
@@ -293,6 +297,9 @@ public Mono<ActionExecutionResult> executeParameterized(
@Override
public ActionConfiguration getSchemaPreviewActionConfig(Template queryTemplate, Boolean isMock) {
+ String printMessage =
+ Thread.currentThread().getName() + ": getSchemaPreviewActionConfig() called for Postgres plugin.";
+ System.out.println(printMessage);
ActionConfiguration actionConfig = new ActionConfiguration();
// Sets query body
actionConfig.setBody(queryTemplate.getBody());
@@ -308,6 +315,9 @@ public ActionConfiguration getSchemaPreviewActionConfig(Template queryTemplate,
@Override
public Mono<String> getEndpointIdentifierForRateLimit(DatasourceConfiguration datasourceConfiguration) {
+ String printMessage = Thread.currentThread().getName()
+ + ": getEndpointIdentifierForRateLimit() called for Postgres plugin.";
+ System.out.println(printMessage);
List<Endpoint> endpoints = datasourceConfiguration.getEndpoints();
SSHConnection sshProxy = datasourceConfiguration.getSshProxy();
String identifier = "";
@@ -350,6 +360,8 @@ private Mono<ActionExecutionResult> executeCommon(
Instant requestedAt = Instant.now();
return Mono.fromCallable(() -> {
+ System.out.println(Thread.currentThread().getName()
+ + ": Within the executeCommon method of PostgresPluginExecutor.");
Connection connectionFromPool;
try {
@@ -383,13 +395,13 @@ private Mono<ActionExecutionResult> executeCommon(
int activeConnections = poolProxy.getActiveConnections();
int totalConnections = poolProxy.getTotalConnections();
int threadsAwaitingConnection = poolProxy.getThreadsAwaitingConnection();
- log.debug(
- "Before executing postgres query [{}] Hikari Pool stats : active - {} , idle - {} , awaiting - {} , total - {}",
+ System.out.println(String.format(
+ "Before executing postgres query [%s] Hikari Pool stats: active - %d, idle - %d, awaiting - %d, total - %d",
query,
activeConnections,
idleConnections,
threadsAwaitingConnection,
- totalConnections);
+ totalConnections));
try {
if (FALSE.equals(preparedStatement)) {
statement = connectionFromPool.createStatement();
@@ -442,10 +454,9 @@ private Mono<ActionExecutionResult> executeCommon(
int objectSize = sizeof(rowsList);
if (objectSize > MAX_SIZE_SUPPORTED) {
- log.debug(
- "[PostgresPlugin] Result size greater than maximum supported size of {} bytes. Current size : {}",
- MAX_SIZE_SUPPORTED,
- objectSize);
+ System.out.println(String.format(
+ "[PostgresPlugin] Result size greater than maximum supported size of %d bytes. Current size: %d",
+ MAX_SIZE_SUPPORTED, objectSize));
return Mono.error(new AppsmithPluginException(
PostgresPluginError.RESPONSE_SIZE_TOO_LARGE,
(float) (MAX_SIZE_SUPPORTED / (1024 * 1024))));
@@ -489,7 +500,13 @@ private Mono<ActionExecutionResult> executeCommon(
} else if (JSON_TYPE_NAME.equalsIgnoreCase(typeName)
|| JSONB_TYPE_NAME.equalsIgnoreCase(typeName)) {
+ System.out.println(
+ Thread.currentThread().getName()
+ + ": objectMapper readTree for Postgres plugin.");
+ Stopwatch processStopwatch =
+ new Stopwatch("Postgres Plugin objectMapper readTree");
value = objectMapper.readTree(resultSet.getString(i));
+ processStopwatch.stopAndLogTimeInMillisWithSysOut();
} else {
value = resultSet.getObject(i);
@@ -518,7 +535,7 @@ private Mono<ActionExecutionResult> executeCommon(
}
} catch (SQLException e) {
- log.debug("In the PostgresPlugin, got action execution error");
+ System.out.println("In the PostgresPlugin, got action execution error");
return Mono.error(new AppsmithPluginException(
PostgresPluginError.QUERY_EXECUTION_FAILED,
PostgresErrorMessages.QUERY_EXECUTION_FAILED_ERROR_MSG,
@@ -528,7 +545,7 @@ private Mono<ActionExecutionResult> executeCommon(
// Since postgres json type field can only hold valid json data, this exception
// is not expected
// to occur.
- log.debug("In the PostgresPlugin, got action execution error");
+ System.out.println("In the PostgresPlugin, got action execution error");
return Mono.error(new AppsmithPluginException(
PostgresPluginError.QUERY_EXECUTION_FAILED,
PostgresErrorMessages.QUERY_EXECUTION_FAILED_ERROR_MSG,
@@ -538,17 +555,15 @@ private Mono<ActionExecutionResult> executeCommon(
activeConnections = poolProxy.getActiveConnections();
totalConnections = poolProxy.getTotalConnections();
threadsAwaitingConnection = poolProxy.getThreadsAwaitingConnection();
- log.debug(
- "After executing postgres query, Hikari Pool stats active - {} , idle - {} , awaiting - {} , total - {} ",
- activeConnections,
- idleConnections,
- threadsAwaitingConnection,
- totalConnections);
+ System.out.println(String.format(
+ "After executing postgres query, Hikari Pool stats active - %d, idle - %d, awaiting - %d, total - %d",
+ activeConnections, idleConnections, threadsAwaitingConnection, totalConnections));
if (resultSet != null) {
try {
resultSet.close();
} catch (SQLException e) {
- log.debug("Execute Error closing Postgres ResultSet", e);
+ System.out.println("Execute Error closing Postgres ResultSet");
+ e.printStackTrace();
}
}
@@ -556,7 +571,8 @@ private Mono<ActionExecutionResult> executeCommon(
try {
statement.close();
} catch (SQLException e) {
- log.debug("Execute Error closing Postgres Statement", e);
+ System.out.println("Execute Error closing Postgres Statement");
+ e.printStackTrace();
}
}
@@ -564,7 +580,8 @@ private Mono<ActionExecutionResult> executeCommon(
try {
preparedQuery.close();
} catch (SQLException e) {
- log.debug("Execute Error closing Postgres Statement", e);
+ System.out.println("Execute Error closing Postgres Statement");
+ e.printStackTrace();
}
}
@@ -573,16 +590,22 @@ private Mono<ActionExecutionResult> executeCommon(
// Return the connection back to the pool
connectionFromPool.close();
} catch (SQLException e) {
- log.debug("Execute Error returning Postgres connection to pool", e);
+ System.out.println("Execute Error returning Postgres connection to pool");
+ e.printStackTrace();
}
}
}
ActionExecutionResult result = new ActionExecutionResult();
+ System.out.println(
+ Thread.currentThread().getName() + ": objectMapper valueToTree for Postgres plugin.");
+ Stopwatch processStopwatch = new Stopwatch("Postgres Plugin objectMapper valueToTree");
result.setBody(objectMapper.valueToTree(rowsList));
+ processStopwatch.stopAndLogTimeInMillisWithSysOut();
result.setMessages(populateHintMessages(columnsList));
result.setIsExecutionSuccess(true);
- log.debug("In the PostgresPlugin, got action execution result");
+ System.out.println(Thread.currentThread().getName()
+ + ": In the PostgresPlugin, got action execution result");
return Mono.just(result);
})
.flatMap(obj -> obj)
@@ -645,6 +668,8 @@ public Mono<ActionExecutionResult> execute(
@Override
public Mono<HikariDataSource> datasourceCreate(DatasourceConfiguration datasourceConfiguration) {
+ String printMessage = Thread.currentThread().getName() + ": datasourceCreate() called for Postgres plugin.";
+ System.out.println(printMessage);
try {
Class.forName(JDBC_DRIVER);
} catch (ClassNotFoundException e) {
@@ -655,7 +680,7 @@ public Mono<HikariDataSource> datasourceCreate(DatasourceConfiguration datasourc
}
return connectionPoolConfig.getMaxConnectionPoolSize().flatMap(maxPoolSize -> Mono.fromCallable(() -> {
- log.info("Connecting to Postgres db");
+ System.out.println(Thread.currentThread().getName() + ": Connecting to Postgres db");
return createConnectionPool(datasourceConfiguration, maxPoolSize);
})
.subscribeOn(scheduler));
@@ -670,6 +695,9 @@ public void datasourceDestroy(HikariDataSource connection) {
@Override
public Set<String> validateDatasource(DatasourceConfiguration datasourceConfiguration) {
+ String printMessage =
+ Thread.currentThread().getName() + ": validateDatasource() called for Postgres plugin.";
+ System.out.println(printMessage);
Set<String> invalids = new HashSet<>();
if (CollectionUtils.isEmpty(datasourceConfiguration.getEndpoints())) {
@@ -752,6 +780,8 @@ public Set<String> validateDatasource(DatasourceConfiguration datasourceConfigur
public Mono<DatasourceStructure> getStructure(
HikariDataSource connection, DatasourceConfiguration datasourceConfiguration) {
+ String printMessage = Thread.currentThread().getName() + ": getStructure() called for Postgres plugin.";
+ System.out.println(printMessage);
final DatasourceStructure structure = new DatasourceStructure();
final Map<String, DatasourceStructure.Table> tablesByName = new TreeMap<>(String.CASE_INSENSITIVE_ORDER);
@@ -780,12 +810,9 @@ public Mono<DatasourceStructure> getStructure(
int activeConnections = poolProxy.getActiveConnections();
int totalConnections = poolProxy.getTotalConnections();
int threadsAwaitingConnection = poolProxy.getThreadsAwaitingConnection();
- log.debug(
- "Before getting postgres db structure Hikari Pool stats active - {} , idle - {} , awaiting - {} , total - {} ",
- activeConnections,
- idleConnections,
- threadsAwaitingConnection,
- totalConnections);
+ System.out.println(String.format(
+ "Before getting postgres db structure Hikari Pool stats active - %d, idle - %d, awaiting - %d, total - %d",
+ activeConnections, idleConnections, threadsAwaitingConnection, totalConnections));
// Ref:
// <https://docs.oracle.com/en/java/javase/11/docs/api/java.sql/java/sql/DatabaseMetaData.html>.
@@ -967,19 +994,18 @@ public Mono<DatasourceStructure> getStructure(
activeConnections = poolProxy.getActiveConnections();
totalConnections = poolProxy.getTotalConnections();
threadsAwaitingConnection = poolProxy.getThreadsAwaitingConnection();
- log.debug(
- "After postgres db structure, Hikari Pool stats active - {} , idle - {} , awaiting - {} , total - {} ",
- activeConnections,
- idleConnections,
- threadsAwaitingConnection,
- totalConnections);
+ System.out.println(String.format(
+ "After postgres db structure, Hikari Pool stats active - %d, idle - %d, awaiting - %d, total - %d",
+ activeConnections, idleConnections, threadsAwaitingConnection, totalConnections));
if (connectionFromPool != null) {
try {
// Return the connection back to the pool
connectionFromPool.close();
} catch (SQLException e) {
- log.debug("Error returning Postgres connection to pool during get structure", e);
+ System.out.println(
+ "Error returning Postgres connection to pool during get structure");
+ e.printStackTrace();
}
}
}
@@ -988,7 +1014,7 @@ public Mono<DatasourceStructure> getStructure(
for (DatasourceStructure.Table table : structure.getTables()) {
table.getKeys().sort(Comparator.naturalOrder());
}
- log.debug("Got the structure of postgres db");
+ System.out.println(Thread.currentThread().getName() + ": Got the structure of postgres db");
return structure;
})
.map(resultStructure -> (DatasourceStructure) resultStructure)
@@ -1069,7 +1095,12 @@ public Object substituteValueInInput(
preparedStatement.setArray(index, null);
break;
case ARRAY: {
+ System.out.println(Thread.currentThread().getName()
+ + ": objectMapper readValue for Postgres plugin ARRAY class");
+ Stopwatch processStopwatch =
+ new Stopwatch("Postgres Plugin objectMapper readValue for ARRAY class");
List arrayListFromInput = objectMapper.readValue(value, List.class);
+ processStopwatch.stopAndLogTimeInMillisWithSysOut();
if (arrayListFromInput.isEmpty()) {
break;
}
diff --git a/app/server/appsmith-plugins/redisPlugin/src/main/java/com/external/plugins/RedisPlugin.java b/app/server/appsmith-plugins/redisPlugin/src/main/java/com/external/plugins/RedisPlugin.java
index cf6d4c8645e9..50520412df62 100644
--- a/app/server/appsmith-plugins/redisPlugin/src/main/java/com/external/plugins/RedisPlugin.java
+++ b/app/server/appsmith-plugins/redisPlugin/src/main/java/com/external/plugins/RedisPlugin.java
@@ -68,6 +68,8 @@ public Mono<ActionExecutionResult> execute(
DatasourceConfiguration datasourceConfiguration,
ActionConfiguration actionConfiguration) {
+ String printMessage = Thread.currentThread().getName() + ": execute() called for Redis plugin.";
+ System.out.println(printMessage);
String query = actionConfiguration.getBody();
List<RequestParamDTO> requestParams =
List.of(new RequestParamDTO(ACTION_CONFIGURATION_BODY, query, null, null, null));
@@ -119,7 +121,9 @@ public Mono<ActionExecutionResult> execute(
objectMapper.valueToTree(removeQuotes(processCommandOutput(commandOutput))));
actionExecutionResult.setIsExecutionSuccess(true);
- log.debug("In the RedisPlugin, got action execution result");
+ System.out.println(
+ Thread.currentThread().getName() + ": In the RedisPlugin, got action execution result");
+
return Mono.just(actionExecutionResult);
})
.flatMap(obj -> obj)
@@ -252,12 +256,15 @@ private JedisPoolConfig buildPoolConfig() {
@Override
public Mono<JedisPool> datasourceCreate(DatasourceConfiguration datasourceConfiguration) {
+ String printMessage = Thread.currentThread().getName() + ": datasourceCreate() called for Redis plugin.";
+ System.out.println(printMessage);
return Mono.fromCallable(() -> {
final JedisPoolConfig poolConfig = buildPoolConfig();
int timeout =
(int) Duration.ofSeconds(CONNECTION_TIMEOUT).toMillis();
URI uri = RedisURIUtils.getURI(datasourceConfiguration);
JedisPool jedisPool = new JedisPool(poolConfig, uri, timeout);
+ System.out.println(Thread.currentThread().getName() + ": Created Jedis pool.");
return jedisPool;
})
.subscribeOn(scheduler);
@@ -265,6 +272,8 @@ public Mono<JedisPool> datasourceCreate(DatasourceConfiguration datasourceConfig
@Override
public void datasourceDestroy(JedisPool jedisPool) {
+ String printMessage = Thread.currentThread().getName() + ": datasourceDestroy() called for Redis plugin.";
+ System.out.println(printMessage);
// Schedule on elastic thread pool and subscribe immediately.
Mono.fromSupplier(() -> {
try {
@@ -272,7 +281,7 @@ public void datasourceDestroy(JedisPool jedisPool) {
jedisPool.destroy();
}
} catch (JedisException e) {
- log.debug("Error destroying Jedis pool.");
+ System.out.println("Error destroying Jedis pool.");
}
return Mono.empty();
@@ -283,6 +292,8 @@ public void datasourceDestroy(JedisPool jedisPool) {
@Override
public Set<String> validateDatasource(DatasourceConfiguration datasourceConfiguration) {
+ String printMessage = Thread.currentThread().getName() + ": validateDatasource() called for Redis plugin.";
+ System.out.println(printMessage);
Set<String> invalids = new HashSet<>();
if (isEndpointMissing(datasourceConfiguration.getEndpoints())) {
@@ -299,6 +310,9 @@ public Set<String> validateDatasource(DatasourceConfiguration datasourceConfigur
@Override
public Mono<String> getEndpointIdentifierForRateLimit(DatasourceConfiguration datasourceConfiguration) {
+ String printMessage =
+ Thread.currentThread().getName() + ": getEndpointIdentifierForRateLimit() called for Redis plugin.";
+ System.out.println(printMessage);
List<Endpoint> endpoints = datasourceConfiguration.getEndpoints();
String identifier = "";
// When hostname and port both are available, both will be used as identifier
@@ -364,6 +378,8 @@ private Mono<Void> verifyPing(JedisPool connectionPool) {
@Override
public Mono<DatasourceTestResult> testDatasource(JedisPool connectionPool) {
+ String printMessage = Thread.currentThread().getName() + ": testDatasource() called for Redis plugin.";
+ System.out.println(printMessage);
return Mono.just(connectionPool)
.flatMap(c -> verifyPing(connectionPool))
diff --git a/app/server/appsmith-plugins/redshiftPlugin/src/main/java/com/external/plugins/RedshiftPlugin.java b/app/server/appsmith-plugins/redshiftPlugin/src/main/java/com/external/plugins/RedshiftPlugin.java
index c16154e0de0f..812d51ccf0a9 100644
--- a/app/server/appsmith-plugins/redshiftPlugin/src/main/java/com/external/plugins/RedshiftPlugin.java
+++ b/app/server/appsmith-plugins/redshiftPlugin/src/main/java/com/external/plugins/RedshiftPlugin.java
@@ -131,7 +131,7 @@ public static class RedshiftPluginExecutor implements PluginExecutor<HikariDataS
private void checkResultSetValidity(ResultSet resultSet) throws AppsmithPluginException {
if (resultSet == null) {
- log.debug("Redshift plugin: getRow: driver failed to fetch result: resultSet is null.");
+ System.out.println("Redshift plugin: getRow: driver failed to fetch result: resultSet is null.");
throw new AppsmithPluginException(
RedshiftPluginError.QUERY_EXECUTION_FAILED, RedshiftErrorMessages.NULL_RESULTSET_ERROR_MSG);
}
@@ -147,7 +147,7 @@ private Map<String, Object> getRow(ResultSet resultSet) throws SQLException, App
* ResultSetMetaData.
*/
if (metaData == null) {
- log.debug("Redshift plugin: getRow: metaData is null. Ideally this is never supposed to "
+ System.out.println("Redshift plugin: getRow: metaData is null. Ideally this is never supposed to "
+ "happen as the Redshift JDBC driver does a null check before passing this object. This means "
+ "that something has gone wrong while processing the query result.");
throw new AppsmithPluginException(
@@ -195,6 +195,8 @@ public Mono<ActionExecutionResult> execute(
DatasourceConfiguration datasourceConfiguration,
ActionConfiguration actionConfiguration) {
+ String printMessage = Thread.currentThread().getName() + ": execute() called for Redshift plugin.";
+ System.out.println(printMessage);
String query = actionConfiguration.getBody();
List<RequestParamDTO> requestParams =
List.of(new RequestParamDTO(ACTION_CONFIGURATION_BODY, query, null, null, null));
@@ -271,7 +273,8 @@ public Mono<ActionExecutionResult> execute(
try {
resultSet.close();
} catch (SQLException e) {
- log.error("Error closing Redshift ResultSet", e);
+ System.out.println("Error closing Redshift ResultSet");
+ e.printStackTrace();
}
}
@@ -279,14 +282,16 @@ public Mono<ActionExecutionResult> execute(
try {
statement.close();
} catch (SQLException e) {
- log.error("Error closing Redshift Statement", e);
+ System.out.println("Error closing Redshift Statement");
+ e.printStackTrace();
}
}
try {
connection.close();
} catch (SQLException e) {
- log.error("Error closing Redshift Connection", e);
+ System.out.println("Error closing Redshift Connection");
+ e.printStackTrace();
}
}
@@ -294,7 +299,8 @@ public Mono<ActionExecutionResult> execute(
result.setBody(objectMapper.valueToTree(rowsList));
result.setMessages(populateHintMessages(columnsList));
result.setIsExecutionSuccess(true);
- log.debug("In RedshiftPlugin, got action execution result");
+ System.out.println(Thread.currentThread().getName()
+ + ": In the RedshiftPlugin, got action execution result");
return Mono.just(result);
})
.flatMap(obj -> obj)
@@ -327,19 +333,25 @@ public Mono<ActionExecutionResult> execute(
}
public void printConnectionPoolStatus(HikariDataSource connectionPool, boolean isFetchingStructure) {
+ String printMessage =
+ Thread.currentThread().getName() + ": printConnectionPoolStatus() called for Redshift plugin.";
+ System.out.println(printMessage);
HikariPoolMXBean poolProxy = connectionPool.getHikariPoolMXBean();
int idleConnections = poolProxy.getIdleConnections();
int activeConnections = poolProxy.getActiveConnections();
int totalConnections = poolProxy.getTotalConnections();
int threadsAwaitingConnection = poolProxy.getThreadsAwaitingConnection();
- log.debug(Thread.currentThread().getName()
+ System.out.println(Thread.currentThread().getName()
+ (isFetchingStructure
- ? "Before fetching Redshift db" + " structure."
- : "Before executing Redshift query.")
- + " Hikari Pool stats : " + " active - "
- + activeConnections + ", idle - "
- + idleConnections + ", awaiting - "
- + threadsAwaitingConnection + ", total - "
+ ? " Before fetching Redshift db structure."
+ : " Before executing Redshift query.")
+ + " Hikari Pool stats: active - "
+ + activeConnections
+ + ", idle - "
+ + idleConnections
+ + ", awaiting - "
+ + threadsAwaitingConnection
+ + ", total - "
+ totalConnections);
}
@@ -360,6 +372,8 @@ private Set<String> populateHintMessages(List<String> columnNames) {
@Override
public Mono<HikariDataSource> datasourceCreate(DatasourceConfiguration datasourceConfiguration) {
+ String printMessage = Thread.currentThread().getName() + ": datasourceCreate() called for Redshift plugin.";
+ System.out.println(printMessage);
try {
Class.forName(JDBC_DRIVER);
} catch (ClassNotFoundException e) {
@@ -370,7 +384,7 @@ public Mono<HikariDataSource> datasourceCreate(DatasourceConfiguration datasourc
}
return Mono.fromCallable(() -> {
- log.debug(Thread.currentThread().getName() + ": Connecting to Redshift db");
+ System.out.println(Thread.currentThread().getName() + ": Connecting to Redshift db");
return createConnectionPool(datasourceConfiguration);
})
.subscribeOn(scheduler);
@@ -378,6 +392,9 @@ public Mono<HikariDataSource> datasourceCreate(DatasourceConfiguration datasourc
@Override
public void datasourceDestroy(HikariDataSource connectionPool) {
+ String printMessage =
+ Thread.currentThread().getName() + ": datasourceDestroy() called for Redshift plugin.";
+ System.out.println(printMessage);
if (connectionPool != null) {
connectionPool.close();
}
@@ -385,6 +402,9 @@ public void datasourceDestroy(HikariDataSource connectionPool) {
@Override
public Set<String> validateDatasource(@NonNull DatasourceConfiguration datasourceConfiguration) {
+ String printMessage =
+ Thread.currentThread().getName() + ": validateDatasource() called for Redshift plugin.";
+ System.out.println(printMessage);
Set<String> invalids = new HashSet<>();
if (CollectionUtils.isEmpty(datasourceConfiguration.getEndpoints())) {
@@ -429,6 +449,9 @@ public Set<String> validateDatasource(@NonNull DatasourceConfiguration datasourc
@Override
public Mono<String> getEndpointIdentifierForRateLimit(DatasourceConfiguration datasourceConfiguration) {
+ String printMessage = Thread.currentThread().getName()
+ + ": getEndpointIdentifierForRateLimit() called for Redshift plugin.";
+ System.out.println(printMessage);
List<Endpoint> endpoints = datasourceConfiguration.getEndpoints();
String identifier = "";
// When hostname and port both are available, both will be used as identifier
@@ -602,6 +625,8 @@ private void getTemplates(Map<String, DatasourceStructure.Table> tablesByName) {
@Override
public Mono<DatasourceStructure> getStructure(
HikariDataSource connectionPool, DatasourceConfiguration datasourceConfiguration) {
+ String printMessage = Thread.currentThread().getName() + ": getStructure() called for Redshift plugin.";
+ System.out.println(printMessage);
final DatasourceStructure structure = new DatasourceStructure();
final Map<String, DatasourceStructure.Table> tablesByName = new LinkedHashMap<>();
final Map<String, DatasourceStructure.Key> keyRegistry = new HashMap<>();
@@ -640,7 +665,7 @@ public Mono<DatasourceStructure> getStructure(
// Ref:
// <https://docs.oracle.com/en/java/javase/11/docs/api/java.sql/java/sql/DatabaseMetaData.html>.
- log.debug(Thread.currentThread().getName() + ": Getting Redshift Db structure");
+ System.out.println(Thread.currentThread().getName() + ": Getting Redshift Db structure");
try (Statement statement = connection.createStatement()) {
// Get tables' schema and fill up their columns.
@@ -672,7 +697,8 @@ public Mono<DatasourceStructure> getStructure(
try {
connection.close();
} catch (SQLException e) {
- log.error("Error closing Redshift Connection", e);
+ System.out.println("Error closing Redshift Connection");
+ e.printStackTrace();
}
}
diff --git a/app/server/appsmith-plugins/restApiPlugin/src/main/java/com/external/plugins/RestApiPlugin.java b/app/server/appsmith-plugins/restApiPlugin/src/main/java/com/external/plugins/RestApiPlugin.java
index 9fe83b18905f..97b2e5b08b09 100644
--- a/app/server/appsmith-plugins/restApiPlugin/src/main/java/com/external/plugins/RestApiPlugin.java
+++ b/app/server/appsmith-plugins/restApiPlugin/src/main/java/com/external/plugins/RestApiPlugin.java
@@ -72,6 +72,9 @@ public Mono<ActionExecutionResult> executeParameterized(
DatasourceConfiguration datasourceConfiguration,
ActionConfiguration actionConfiguration) {
+ String printMessage = Thread.currentThread().getName()
+ + ": executeParameterized() called for RestAPI plugin. Executing the API call.";
+ System.out.println(printMessage);
final List<Property> properties = actionConfiguration.getPluginSpecifiedTemplates();
List<Map.Entry<String, String>> parameters = new ArrayList<>();
@@ -131,6 +134,9 @@ public Mono<ActionExecutionResult> executeCommon(
ActionConfiguration actionConfiguration,
List<Map.Entry<String, String>> insertedParams) {
+ String printMessage = Thread.currentThread().getName()
+ + ": executeCommon() called for RestAPI plugin. Executing the API call.";
+ System.out.println(printMessage);
// Initializing object for error condition
ActionExecutionResult errorResult = new ActionExecutionResult();
initUtils.initializeResponseWithError(errorResult);
@@ -209,10 +215,9 @@ public Mono<ActionExecutionResult> executeCommon(
errorResult.setRequest(requestCaptureFilter.populateRequestFields(
actionExecutionRequest, isBodySentWithApiRequest, datasourceConfiguration));
errorResult.setIsExecutionSuccess(false);
- log.debug(
- "An error has occurred while trying to run the API query for url: {}, path : {}",
- datasourceConfiguration.getUrl(),
- actionConfiguration.getPath());
+ System.out.println(String.format(
+ "An error has occurred while trying to run the API query for url: %s, path: %s",
+ datasourceConfiguration.getUrl(), actionConfiguration.getPath()));
error.printStackTrace();
if (!(error instanceof AppsmithPluginException)) {
error = new AppsmithPluginException(
diff --git a/app/server/appsmith-plugins/saasPlugin/src/main/java/com/external/plugins/SaasPlugin.java b/app/server/appsmith-plugins/saasPlugin/src/main/java/com/external/plugins/SaasPlugin.java
index f1b153530588..da4c99e70ec6 100644
--- a/app/server/appsmith-plugins/saasPlugin/src/main/java/com/external/plugins/SaasPlugin.java
+++ b/app/server/appsmith-plugins/saasPlugin/src/main/java/com/external/plugins/SaasPlugin.java
@@ -3,6 +3,7 @@
import com.appsmith.external.dtos.ExecutePluginDTO;
import com.appsmith.external.exceptions.pluginExceptions.AppsmithPluginError;
import com.appsmith.external.exceptions.pluginExceptions.AppsmithPluginException;
+import com.appsmith.external.helpers.Stopwatch;
import com.appsmith.external.models.ActionConfiguration;
import com.appsmith.external.models.ActionExecutionRequest;
import com.appsmith.external.models.ActionExecutionResult;
@@ -84,6 +85,8 @@ public Mono<ActionExecutionResult> execute(
ExecutePluginDTO connection,
DatasourceConfiguration datasourceConfiguration,
ActionConfiguration actionConfiguration) {
+ String printMessage = Thread.currentThread().getName() + ": execute() called for Saas plugin.";
+ System.out.println(printMessage);
// Initializing object for error condition
ActionExecutionResult errorResult = new ActionExecutionResult();
@@ -132,7 +135,12 @@ public Mono<ActionExecutionResult> execute(
String valueAsString = "";
try {
+ System.out.println(
+ Thread.currentThread().getName() + ": objectMapper writing value as string for Saas plugin.");
+ Stopwatch processStopwatch =
+ new Stopwatch("SaaS Plugin objectMapper writing value as string for connection");
valueAsString = saasObjectMapper.writeValueAsString(connection);
+ processStopwatch.stopAndLogTimeInMillisWithSysOut();
} catch (JsonProcessingException e) {
e.printStackTrace();
}
@@ -145,7 +153,14 @@ public Mono<ActionExecutionResult> execute(
byte[] body = stringResponseEntity.getBody();
if (statusCode.is2xxSuccessful()) {
try {
- return saasObjectMapper.readValue(body, ActionExecutionResult.class);
+ System.out.println(Thread.currentThread().getName()
+ + ": objectMapper reading value as string for Saas plugin.");
+ Stopwatch processStopwatch =
+ new Stopwatch("SaaS Plugin objectMapper reading value as string for body");
+ ActionExecutionResult result =
+ saasObjectMapper.readValue(body, ActionExecutionResult.class);
+ processStopwatch.stopAndLogTimeInMillisWithSysOut();
+ return result;
} catch (IOException e) {
throw Exceptions.propagate(new AppsmithPluginException(
AppsmithPluginError.PLUGIN_JSON_PARSE_ERROR, body, e.getMessage()));
diff --git a/app/server/appsmith-plugins/smtpPlugin/src/main/java/com/external/plugins/SmtpPlugin.java b/app/server/appsmith-plugins/smtpPlugin/src/main/java/com/external/plugins/SmtpPlugin.java
index b7a0804fb39d..952a34df655d 100644
--- a/app/server/appsmith-plugins/smtpPlugin/src/main/java/com/external/plugins/SmtpPlugin.java
+++ b/app/server/appsmith-plugins/smtpPlugin/src/main/java/com/external/plugins/SmtpPlugin.java
@@ -71,6 +71,8 @@ public Mono<ActionExecutionResult> execute(
DatasourceConfiguration datasourceConfiguration,
ActionConfiguration actionConfiguration) {
+ String printMessage = Thread.currentThread().getName() + ": execute() called for SMTP plugin.";
+ System.out.println(printMessage);
MimeMessage message = getMimeMessage(connection);
ActionExecutionResult result = new ActionExecutionResult();
try {
@@ -164,7 +166,7 @@ public Mono<ActionExecutionResult> execute(
}
// Send the email now
- log.debug("Going to send the email");
+ System.out.println("Going to send the email");
Transport.send(message);
result.setIsExecutionSuccess(true);
@@ -172,7 +174,7 @@ public Mono<ActionExecutionResult> execute(
responseBody.put("message", "Sent the email successfully");
result.setBody(objectMapper.valueToTree(responseBody));
- log.debug("Sent the email successfully");
+ System.out.println("Sent the email successfully");
} catch (MessagingException e) {
return Mono.error(new AppsmithPluginException(
SMTPPluginError.MAIL_SENDING_FAILED,
@@ -198,7 +200,8 @@ MimeMessage getMimeMessage(Session connection) {
@Override
public Mono<Session> datasourceCreate(DatasourceConfiguration datasourceConfiguration) {
-
+ String printMessage = Thread.currentThread().getName() + ": datasourceCreate() called for SMTP plugin.";
+ System.out.println(printMessage);
Endpoint endpoint = datasourceConfiguration.getEndpoints().get(0);
DBAuth authentication = (DBAuth) datasourceConfiguration.getAuthentication();
@@ -225,7 +228,8 @@ protected PasswordAuthentication getPasswordAuthentication() {
@Override
public void datasourceDestroy(Session session) {
- log.debug("Going to destroy email datasource");
+ String printMessage = Thread.currentThread().getName() + ": datasourceDestroy() called for SMTP plugin.";
+ System.out.println(printMessage);
try {
if (session != null && session.getTransport() != null) {
session.getTransport().close();
@@ -237,7 +241,8 @@ public void datasourceDestroy(Session session) {
@Override
public Set<String> validateDatasource(DatasourceConfiguration datasourceConfiguration) {
- log.debug("Going to validate email datasource");
+ String printMessage = Thread.currentThread().getName() + ": validateDatasource() called for SMTP plugin.";
+ System.out.println(printMessage);
Set<String> invalids = new HashSet<>();
if (CollectionUtils.isEmpty(datasourceConfiguration.getEndpoints())) {
invalids.add(SMTPErrorMessages.DS_MISSING_HOST_ADDRESS_ERROR_MSG);
@@ -260,7 +265,8 @@ public Set<String> validateDatasource(DatasourceConfiguration datasourceConfigur
@Override
public Mono<DatasourceTestResult> testDatasource(Session connection) {
- log.debug("Going to test email datasource");
+ String printMessage = Thread.currentThread().getName() + ": testDatasource() called for SMTP plugin.";
+ System.out.println(printMessage);
return Mono.fromCallable(() -> {
Set<String> invalids = new HashSet<>();
try {
@@ -274,7 +280,7 @@ public Mono<DatasourceTestResult> testDatasource(Session connection) {
} catch (AuthenticationFailedException e) {
invalids.add(SMTPErrorMessages.DS_AUTHENTICATION_FAILED_ERROR_MSG);
} catch (MessagingException e) {
- log.debug(e.getMessage());
+ System.out.println(e.getMessage());
invalids.add(SMTPErrorMessages.DS_CONNECTION_FAILED_TO_SMTP_SERVER_ERROR_MSG);
}
return invalids;
@@ -284,6 +290,9 @@ public Mono<DatasourceTestResult> testDatasource(Session connection) {
@Override
public Mono<String> getEndpointIdentifierForRateLimit(DatasourceConfiguration datasourceConfiguration) {
+ String printMessage =
+ Thread.currentThread().getName() + ": getEndpointIdentifierForRateLimit() called for SMTP plugin.";
+ System.out.println(printMessage);
List<Endpoint> endpoints = datasourceConfiguration.getEndpoints();
String identifier = "";
// When hostname and port both are available, both will be used as identifier
diff --git a/app/server/appsmith-plugins/snowflakePlugin/src/main/java/com/external/plugins/SnowflakePlugin.java b/app/server/appsmith-plugins/snowflakePlugin/src/main/java/com/external/plugins/SnowflakePlugin.java
index e178c61df48e..04cc9c2b499e 100644
--- a/app/server/appsmith-plugins/snowflakePlugin/src/main/java/com/external/plugins/SnowflakePlugin.java
+++ b/app/server/appsmith-plugins/snowflakePlugin/src/main/java/com/external/plugins/SnowflakePlugin.java
@@ -71,6 +71,8 @@ public Mono<ActionExecutionResult> execute(
DatasourceConfiguration datasourceConfiguration,
ActionConfiguration actionConfiguration) {
+ String printMessage = Thread.currentThread().getName() + ": execute() called for Snowflake plugin.";
+ System.out.println(printMessage);
String query = actionConfiguration.getBody();
if (!StringUtils.hasLength(query)) {
@@ -80,6 +82,7 @@ public Mono<ActionExecutionResult> execute(
}
return Mono.fromCallable(() -> {
+ System.out.println(Thread.currentThread().getName() + ": Execute Snowflake Query");
Connection connectionFromPool;
try {
@@ -104,13 +107,13 @@ public Mono<ActionExecutionResult> execute(
int activeConnections = poolProxy.getActiveConnections();
int totalConnections = poolProxy.getTotalConnections();
int threadsAwaitingConnection = poolProxy.getThreadsAwaitingConnection();
- log.debug(
- "Before executing snowflake query [{}] Hikari Pool stats : active - {} , idle - {} , awaiting - {} , total - {}",
+ System.out.println(String.format(
+ "Before executing snowflake query [%s] Hikari Pool stats: active - %d, idle - %d, awaiting - %d, total - %d",
query,
activeConnections,
idleConnections,
threadsAwaitingConnection,
- totalConnections);
+ totalConnections));
try {
// Connection staleness is checked as part of this method call.
@@ -123,19 +126,17 @@ public Mono<ActionExecutionResult> execute(
activeConnections = poolProxy.getActiveConnections();
totalConnections = poolProxy.getTotalConnections();
threadsAwaitingConnection = poolProxy.getThreadsAwaitingConnection();
- log.debug(
- "After executing snowflake query, Hikari Pool stats active - {} , idle - {} , awaiting - {} , total - {} ",
- activeConnections,
- idleConnections,
- threadsAwaitingConnection,
- totalConnections);
+ System.out.println(String.format(
+ "After executing snowflake query, Hikari Pool stats active - %d, idle - %d, awaiting - %d, total - %d",
+ activeConnections, idleConnections, threadsAwaitingConnection, totalConnections));
if (connectionFromPool != null) {
try {
// Return the connection back to the pool
connectionFromPool.close();
} catch (SQLException e) {
- log.debug("Execute Error returning Snowflake connection to pool", e);
+ System.out.println("Execute Error returning Snowflake connection to pool");
+ e.printStackTrace();
}
}
}
@@ -155,8 +156,13 @@ public Mono<ActionExecutionResult> execute(
@Override
public Mono<HikariDataSource> createConnectionClient(
DatasourceConfiguration datasourceConfiguration, Properties properties) {
+ String printMessage =
+ Thread.currentThread().getName() + ": createConnectionClient() called for Snowflake plugin.";
+ System.out.println(printMessage);
return getHikariConfig(datasourceConfiguration, properties)
.flatMap(config -> Mono.fromCallable(() -> {
+ System.out.println(
+ Thread.currentThread().getName() + ": creating Snowflake connection client");
// Set up the connection URL
String jdbcUrl = getJDBCUrl(datasourceConfiguration);
config.setJdbcUrl(jdbcUrl);
@@ -196,6 +202,9 @@ public Properties addPluginSpecificProperties(
@Override
public Properties addAuthParamsToConnectionConfig(
DatasourceConfiguration datasourceConfiguration, Properties properties) {
+ String printMessage = Thread.currentThread().getName()
+ + ": addAuthParamsToConnectionConfig() called for Snowflake plugin.";
+ System.out.println(printMessage);
// Only for username password auth, we need to set these properties, for others
// like key-pair auth, authentication specific properties need to be set on config itself
AuthenticationDTO authentication = datasourceConfiguration.getAuthentication();
@@ -235,6 +244,9 @@ public void datasourceDestroy(HikariDataSource connection) {
@Override
public Set<String> validateDatasource(DatasourceConfiguration datasourceConfiguration) {
+ String printMessage =
+ Thread.currentThread().getName() + ": validateDatasource() called for Snowflake plugin.";
+ System.out.println(printMessage);
Set<String> invalids = new HashSet<>();
if (StringUtils.isEmpty(datasourceConfiguration.getUrl())) {
@@ -303,9 +315,11 @@ public Set<String> validateDatasource(DatasourceConfiguration datasourceConfigur
@Override
public Mono<DatasourceTestResult> testDatasource(HikariDataSource connection) {
-
+ String printMessage = Thread.currentThread().getName() + ": testDatasource() called for Snowflake plugin.";
+ System.out.println(printMessage);
return Mono.just(connection)
.flatMap(connectionPool -> {
+ System.out.println(Thread.currentThread().getName() + ": Testing Snowflake Datasource");
Connection connectionFromPool;
try {
/**
@@ -345,6 +359,8 @@ public Mono<DatasourceTestResult> testDatasource(HikariDataSource connection) {
@Override
public Mono<DatasourceStructure> getStructure(
HikariDataSource connection, DatasourceConfiguration datasourceConfiguration) {
+ String printMessage = Thread.currentThread().getName() + ": getStructure() called for Snowflake plugin.";
+ System.out.println(printMessage);
final DatasourceStructure structure = new DatasourceStructure();
final Map<String, DatasourceStructure.Table> tablesByName = new LinkedHashMap<>();
final Map<String, DatasourceStructure.Key> keyRegistry = new HashMap<>();
@@ -374,12 +390,9 @@ public Mono<DatasourceStructure> getStructure(
int activeConnections = poolProxy.getActiveConnections();
int totalConnections = poolProxy.getTotalConnections();
int threadsAwaitingConnection = poolProxy.getThreadsAwaitingConnection();
- log.debug(
- "Before getting snowflake structure Hikari Pool stats active - {} , idle - {} , awaiting - {} , total - {} ",
- activeConnections,
- idleConnections,
- threadsAwaitingConnection,
- totalConnections);
+ System.out.println(String.format(
+ "Before getting snowflake structure Hikari Pool stats active - %d, idle - %d, awaiting - %d, total - %d",
+ activeConnections, idleConnections, threadsAwaitingConnection, totalConnections));
try {
// Connection staleness is checked as part of this method call.
@@ -417,33 +430,32 @@ public Mono<DatasourceStructure> getStructure(
table.getKeys().sort(Comparator.naturalOrder());
}
} catch (SQLException throwable) {
- log.error(
- "Exception caught while fetching structure of Snowflake datasource. Cause: ",
- throwable);
+ System.out.println(
+ "Exception caught while fetching structure of Snowflake datasource. Cause:");
+ throwable.printStackTrace();
throw new AppsmithPluginException(
AppsmithPluginError.PLUGIN_GET_STRUCTURE_ERROR,
SnowflakeErrorMessages.GET_STRUCTURE_ERROR_MSG,
throwable.getMessage(),
"SQLSTATE: " + throwable.getSQLState());
} finally {
-
+ System.out.println(Thread.currentThread().getName() + ": Get Structure Snowflake");
idleConnections = poolProxy.getIdleConnections();
activeConnections = poolProxy.getActiveConnections();
totalConnections = poolProxy.getTotalConnections();
threadsAwaitingConnection = poolProxy.getThreadsAwaitingConnection();
- log.debug(
- "After snowflake structure, Hikari Pool stats active - {} , idle - {} , awaiting - {} , total - {} ",
- activeConnections,
- idleConnections,
- threadsAwaitingConnection,
- totalConnections);
+ System.out.println(String.format(
+ "After snowflake structure, Hikari Pool stats active - %d, idle - %d, awaiting - %d, total - %d",
+ activeConnections, idleConnections, threadsAwaitingConnection, totalConnections));
if (connectionFromPool != null) {
try {
// Return the connection back to the pool
connectionFromPool.close();
} catch (SQLException e) {
- log.debug("Error returning snowflake connection to pool during get structure", e);
+ System.out.println(
+ "Error returning snowflake connection to pool during get structure");
+ e.printStackTrace();
}
}
}
|
a6e0c54d7248d0888c1d6dab96acc09272eaa273
|
2023-11-15 18:01:54
|
Ashok Kumar M
|
fix: Anvil fixes and enhancements post R0 (#28711)
| false
|
Anvil fixes and enhancements post R0 (#28711)
|
fix
|
diff --git a/app/client/src/components/editorComponents/ActionRightPane/SuggestedWidgets.tsx b/app/client/src/components/editorComponents/ActionRightPane/SuggestedWidgets.tsx
index 9cec447ae4c2..f92254ad8934 100644
--- a/app/client/src/components/editorComponents/ActionRightPane/SuggestedWidgets.tsx
+++ b/app/client/src/components/editorComponents/ActionRightPane/SuggestedWidgets.tsx
@@ -49,6 +49,8 @@ import localStorage from "utils/localStorage";
import { WIDGET_ID_SHOW_WALKTHROUGH } from "constants/WidgetConstants";
import { FEATURE_WALKTHROUGH_KEYS } from "constants/WalkthroughConstants";
import type { WidgetType } from "constants/WidgetConstants";
+import { useFeatureFlag } from "utils/hooks/useFeatureFlag";
+import { WDS_V2_WIDGET_MAP } from "components/wds/constants";
import Collapsible from "components/common/Collapsible";
const BINDING_GUIDE_GIF = `${ASSETS_CDN_URL}/binding.gif`;
@@ -498,6 +500,12 @@ function SuggestedWidgets(props: SuggestedWidgetProps) {
useEffect(() => {
checkAndShowWalkthrough();
}, []);
+ const isWDSEnabled = useFeatureFlag("ab_wds_enabled");
+ const filteredSuggestedWidgets = isWDSEnabled
+ ? props.suggestedWidgets.filter(
+ (each) => !!Object.keys(WDS_V2_WIDGET_MAP).includes(each.type),
+ )
+ : props.suggestedWidgets;
return (
<SuggestedWidgetContainer id={BINDING_SECTION_ID}>
@@ -559,7 +567,7 @@ function SuggestedWidgets(props: SuggestedWidgetProps) {
<SubSection className="t--suggested-widget-add-new">
{renderHeading(addNewWidgetLabel, addNewWidgetSubLabel)}
<WidgetList className="spacing">
- {props.suggestedWidgets.map((suggestedWidget) => {
+ {filteredSuggestedWidgets.map((suggestedWidget) => {
const widgetInfo: WidgetBindingInfo | undefined =
WIDGET_DATA_FIELD_MAP[suggestedWidget.type];
diff --git a/app/client/src/layoutSystems/anvil/canvasArenas/hooks/useCanvasActivation.ts b/app/client/src/layoutSystems/anvil/canvasArenas/hooks/useCanvasActivation.ts
index f005b35f0220..f0ad8ddd77cc 100644
--- a/app/client/src/layoutSystems/anvil/canvasArenas/hooks/useCanvasActivation.ts
+++ b/app/client/src/layoutSystems/anvil/canvasArenas/hooks/useCanvasActivation.ts
@@ -4,6 +4,7 @@ import { MAIN_CONTAINER_WIDGET_ID } from "constants/WidgetConstants";
import type { LayoutElementPosition } from "layoutSystems/common/types";
import { positionObserver } from "layoutSystems/common/utils/LayoutElementPositionsObserver";
import { getAnvilLayoutDOMId } from "layoutSystems/common/utils/LayoutElementPositionsObserver/utils";
+import { debounce } from "lodash";
import { useEffect, useRef } from "react";
import { useWidgetDragResize } from "utils/hooks/dragResizeHooks";
import type { AnvilDnDStates } from "./useAnvilDnDStates";
@@ -28,6 +29,8 @@ const checkIfMousePositionIsInsideBlock = (
);
};
+const MAIN_CANVAS_BUFFER = 20;
+
export const useCanvasActivation = (
anvilDragStates: AnvilDnDStates,
layoutId: string,
@@ -46,6 +49,7 @@ export const useCanvasActivation = (
const draggedWidgetPositions = anvilDragStates.selectedWidgets.map((each) => {
return layoutElementPositions[each];
});
+ const debouncedSetDraggingCanvas = debounce(setDraggingCanvas);
/**
* 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.
@@ -55,6 +59,7 @@ export const useCanvasActivation = (
isMouseOutOfMainCanvas.current = true;
setDraggingCanvas();
};
+ const debouncedMouseOutOfCanvasArtBoard = debounce(mouseOutOfCanvasArtBoard);
/**
* all layouts registered on the position observer.
@@ -79,7 +84,7 @@ export const useCanvasActivation = (
* layoutIds that are supported to drop while dragging.
* when dragging an AnvilOverlayWidgetTypes widget only the main canvas is supported for dropping.
*/
- const filteredLayoutIds = activateOverlayWidgetDrop
+ const filteredLayoutIds: string[] = activateOverlayWidgetDrop
? allLayoutIds.filter((each) => each === mainCanvasLayoutDomId)
: allLayoutIds;
/**
@@ -130,7 +135,13 @@ export const useCanvasActivation = (
const hoveredCanvas = isMousePositionOutsideOfDraggingWidgets
? dragDetails.dragGroupActualParent
: smallToLargeSortedDroppableLayoutIds.find((each) => {
- const currentCanvasPositions = layoutElementPositions[each];
+ const currentCanvasPositions = { ...layoutElementPositions[each] };
+ if (each === mainCanvasLayoutId) {
+ currentCanvasPositions.left -= MAIN_CANVAS_BUFFER;
+ currentCanvasPositions.top -= MAIN_CANVAS_BUFFER;
+ currentCanvasPositions.width += 2 * MAIN_CANVAS_BUFFER;
+ currentCanvasPositions.height += 2 * MAIN_CANVAS_BUFFER;
+ }
if (currentCanvasPositions) {
return checkIfMousePositionIsInsideBlock(
e,
@@ -142,9 +153,9 @@ export const useCanvasActivation = (
if (dragDetails.draggedOn !== hoveredCanvas) {
if (hoveredCanvas) {
isMouseOutOfMainCanvas.current = false;
- setDraggingCanvas(hoveredCanvas);
+ debouncedSetDraggingCanvas(hoveredCanvas);
} else {
- mouseOutOfCanvasArtBoard();
+ debouncedMouseOutOfCanvasArtBoard();
}
}
}
@@ -179,6 +190,6 @@ export const useCanvasActivation = (
isDragging,
onMouseMoveWhileDragging,
onMouseUp,
- mouseOutOfCanvasArtBoard,
+ debouncedMouseOutOfCanvasArtBoard,
]);
};
diff --git a/app/client/src/layoutSystems/anvil/canvasArenas/hooks/useCanvasDragging.ts b/app/client/src/layoutSystems/anvil/canvasArenas/hooks/useCanvasDragging.ts
index eeb0bb740130..cb1fc02ea83f 100644
--- a/app/client/src/layoutSystems/anvil/canvasArenas/hooks/useCanvasDragging.ts
+++ b/app/client/src/layoutSystems/anvil/canvasArenas/hooks/useCanvasDragging.ts
@@ -323,6 +323,8 @@ export const useCanvasDragging = (
onMouseUp,
false,
);
+ // to make sure drops on the main canvas boundary buffer are processed
+ document.addEventListener("mouseup", onMouseUp);
scrollParent?.addEventListener("scroll", onScroll, false);
}
@@ -332,6 +334,7 @@ export const useCanvasDragging = (
onMouseMove,
);
slidingArenaRef.current?.removeEventListener("mouseup", onMouseUp);
+ document.removeEventListener("mouseup", onMouseUp);
scrollParent?.removeEventListener("scroll", onScroll);
};
} else {
diff --git a/app/client/src/layoutSystems/anvil/common/AnvilFlexComponent.tsx b/app/client/src/layoutSystems/anvil/common/AnvilFlexComponent.tsx
index 0c6520fd8dee..e4a8e157a490 100644
--- a/app/client/src/layoutSystems/anvil/common/AnvilFlexComponent.tsx
+++ b/app/client/src/layoutSystems/anvil/common/AnvilFlexComponent.tsx
@@ -159,7 +159,7 @@ export function AnvilFlexComponent(props: AnvilFlexComponentProps) {
position: "relative",
// overflow is set to make sure widgets internal components/divs don't overflow this boundary causing scrolls
overflow: "hidden",
- opacity: isDragging && isSelected ? 0.5 : 1,
+ opacity: (isDragging && isSelected) || !props.isVisible ? 0.5 : 1,
"&:hover": {
zIndex: onHoverZIndex,
},
diff --git a/app/client/src/layoutSystems/anvil/common/widgetComponent/AnvilWidgetComponent.tsx b/app/client/src/layoutSystems/anvil/common/widgetComponent/AnvilWidgetComponent.tsx
index f603055c4837..79176cc842ab 100644
--- a/app/client/src/layoutSystems/anvil/common/widgetComponent/AnvilWidgetComponent.tsx
+++ b/app/client/src/layoutSystems/anvil/common/widgetComponent/AnvilWidgetComponent.tsx
@@ -19,7 +19,7 @@ export const AnvilWidgetComponent = (props: BaseWidgetProps) => {
return <Skeleton />;
}
- if (!detachFromLayout) return <div>{props.children}</div>;
+ if (!detachFromLayout) return props.children;
return (
<ErrorBoundary>
diff --git a/app/client/src/layoutSystems/anvil/editor/AnvilEditorWidgetOnion.tsx b/app/client/src/layoutSystems/anvil/editor/AnvilEditorWidgetOnion.tsx
index c93d04220626..507db5342fa9 100644
--- a/app/client/src/layoutSystems/anvil/editor/AnvilEditorWidgetOnion.tsx
+++ b/app/client/src/layoutSystems/anvil/editor/AnvilEditorWidgetOnion.tsx
@@ -2,7 +2,6 @@ import React, { useCallback } from "react";
import { useMemo } from "react";
import type { BaseWidgetProps } from "widgets/BaseWidgetHOC/withBaseWidgetHOC";
import { AnvilFlexComponent } from "../common/AnvilFlexComponent";
-import SnipeableComponent from "layoutSystems/common/snipeable/SnipeableComponent";
import { AnvilWidgetComponent } from "../common/widgetComponent/AnvilWidgetComponent";
import DraggableComponent from "layoutSystems/common/draggable/DraggableComponent";
import { AnvilResizableLayer } from "../common/resizer/AnvilResizableLayer";
@@ -42,6 +41,7 @@ export const AnvilEditorWidgetOnion = (props: BaseWidgetProps) => {
return (
<AnvilFlexComponent
isResizeDisabled={props.resizeDisabled}
+ isVisible={!!props.isVisible}
layoutId={props.layoutId}
parentId={props.parentId}
rowIndex={props.rowIndex}
@@ -50,23 +50,21 @@ export const AnvilEditorWidgetOnion = (props: BaseWidgetProps) => {
widgetSize={widgetSize}
widgetType={props.type}
>
- <SnipeableComponent type={props.type} widgetId={props.widgetId}>
- <DraggableComponent
- dragDisabled={!!props.dragDisabled}
- generateDragState={generateDragState}
- isFlexChild
- parentId={props.parentId}
- resizeDisabled={props.resizeDisabled}
- type={props.type}
- widgetId={props.widgetId}
- >
- <AnvilResizableLayer {...props}>
- <AnvilWidgetComponent {...props}>
- {props.children}
- </AnvilWidgetComponent>
- </AnvilResizableLayer>
- </DraggableComponent>
- </SnipeableComponent>
+ <DraggableComponent
+ dragDisabled={!!props.dragDisabled}
+ generateDragState={generateDragState}
+ isFlexChild
+ parentId={props.parentId}
+ resizeDisabled={props.resizeDisabled}
+ type={props.type}
+ widgetId={props.widgetId}
+ >
+ <AnvilResizableLayer {...props}>
+ <AnvilWidgetComponent {...props}>
+ {props.children}
+ </AnvilWidgetComponent>
+ </AnvilResizableLayer>
+ </DraggableComponent>
</AnvilFlexComponent>
);
};
diff --git a/app/client/src/layoutSystems/anvil/integrations/actions/actionTypes.ts b/app/client/src/layoutSystems/anvil/integrations/actions/actionTypes.ts
index b6219c26c89f..6b863523fcc7 100644
--- a/app/client/src/layoutSystems/anvil/integrations/actions/actionTypes.ts
+++ b/app/client/src/layoutSystems/anvil/integrations/actions/actionTypes.ts
@@ -9,4 +9,5 @@ export enum AnvilReduxActionTypes {
REMOVE_LAYOUT_ELEMENT_POSITIONS = "REMOVE_LAYOUT_ELEMENT_POSITIONS",
ANVIL_ADD_NEW_WIDGET = "ANVIL_ADD_NEW_WIDGET",
ANVIL_MOVE_WIDGET = "ANVIL_MOVE_WIDGET",
+ ANVIL_ADD_SUGGESTED_WIDGET = "ANVIL_ADD_SUGGESTED_WIDGET",
}
diff --git a/app/client/src/layoutSystems/anvil/integrations/actions/draggingActions.ts b/app/client/src/layoutSystems/anvil/integrations/actions/draggingActions.ts
index cd2bfdf85fc9..67b13d57aa70 100644
--- a/app/client/src/layoutSystems/anvil/integrations/actions/draggingActions.ts
+++ b/app/client/src/layoutSystems/anvil/integrations/actions/draggingActions.ts
@@ -1,3 +1,4 @@
+import type { WidgetProps } from "widgets/BaseWidget";
import type { AnvilHighlightInfo } from "../../utils/anvilTypes";
import { AnvilReduxActionTypes } from "./actionTypes";
@@ -37,3 +38,21 @@ export const moveAnvilWidgets = (
},
};
};
+
+/**
+ * Add suggested widget to Anvil canvas.
+ */
+export const addSuggestedWidgetAnvilAction = (newWidget: {
+ newWidgetId: string;
+ type?: string;
+ rows?: number;
+ columns?: number;
+ props?: WidgetProps;
+}) => {
+ return {
+ type: AnvilReduxActionTypes.ANVIL_ADD_SUGGESTED_WIDGET,
+ payload: {
+ newWidget,
+ },
+ };
+};
diff --git a/app/client/src/layoutSystems/anvil/integrations/sagas/draggingSagas.ts b/app/client/src/layoutSystems/anvil/integrations/sagas/draggingSagas.ts
index fd62abae6611..1cf880220ca4 100644
--- a/app/client/src/layoutSystems/anvil/integrations/sagas/draggingSagas.ts
+++ b/app/client/src/layoutSystems/anvil/integrations/sagas/draggingSagas.ts
@@ -9,7 +9,7 @@ import type { CanvasWidgetsReduxState } from "reducers/entityReducers/canvasWidg
import { all, call, put, select, takeLatest } from "redux-saga/effects";
import { getUpdateDslAfterCreatingChild } from "sagas/WidgetAdditionSagas";
import { executeWidgetBlueprintBeforeOperations } from "sagas/WidgetBlueprintSagas";
-import { getWidgets } from "sagas/selectors";
+import { getWidget, getWidgets } from "sagas/selectors";
import type { AnvilHighlightInfo } from "../../utils/anvilTypes";
import { addWidgetsToPreset } from "../../utils/layouts/update/additionUtils";
import { moveWidgets } from "../../utils/layouts/update/moveUtils";
@@ -17,6 +17,143 @@ import { AnvilReduxActionTypes } from "../actions/actionTypes";
import { generateDefaultLayoutPreset } from "layoutSystems/anvil/layoutComponents/presets/DefaultLayoutPreset";
import { selectWidgetInitAction } from "actions/widgetSelectionActions";
import { SelectionRequestType } from "sagas/WidgetSelectUtils";
+import {
+ GridDefaults,
+ MAIN_CONTAINER_WIDGET_ID,
+} from "constants/WidgetConstants";
+import type { WidgetProps } from "widgets/BaseWidget";
+import { FlexLayerAlignment } from "layoutSystems/common/utils/constants";
+import { WDS_V2_WIDGET_MAP } from "components/wds/constants";
+
+export function* getMainCanvasLastRowHighlight() {
+ const mainCanvas: WidgetProps = yield select(
+ getWidget,
+ MAIN_CONTAINER_WIDGET_ID,
+ );
+ const layoutId: string = mainCanvas.layout[0].layoutId;
+ const layoutOrder = [layoutId];
+ const rowIndex = mainCanvas.layout[0].layout.length;
+ return {
+ canvasId: MAIN_CONTAINER_WIDGET_ID,
+ layoutOrder,
+ rowIndex,
+ posX: 0,
+ posY: 0,
+ alignment: FlexLayerAlignment.Start,
+ dropZone: {},
+ height: 0,
+ width: 0,
+ isVertical: false,
+ };
+}
+
+function* addSuggestedWidgetsAnvilSaga(
+ actionPayload: ReduxAction<{
+ newWidget: {
+ newWidgetId: string;
+ type: string;
+ rows?: number;
+ columns?: number;
+ props: WidgetProps;
+ };
+ }>,
+) {
+ const { newWidget } = actionPayload.payload;
+ const wdsEntry = Object.entries(WDS_V2_WIDGET_MAP).find(
+ ([legacyType]) => legacyType === newWidget.type,
+ );
+ if (wdsEntry) {
+ const [, wdsType] = wdsEntry;
+ const newWidgetParams = {
+ width: (newWidget.rows || 0 / GridDefaults.DEFAULT_GRID_COLUMNS) * 100,
+ height: newWidget.columns || 0 * GridDefaults.DEFAULT_GRID_ROW_HEIGHT,
+ newWidgetId: newWidget.newWidgetId,
+ parentId: MAIN_CONTAINER_WIDGET_ID,
+ type: wdsType,
+ };
+ const mainCanvasHighLight: AnvilHighlightInfo = yield call(
+ getMainCanvasLastRowHighlight,
+ );
+ const updatedWidgets: CanvasWidgetsReduxState = yield call(
+ addNewChildToDSL,
+ mainCanvasHighLight,
+ newWidgetParams,
+ );
+ updatedWidgets[newWidgetParams.newWidgetId] = {
+ ...updatedWidgets[newWidgetParams.newWidgetId],
+ ...newWidget.props,
+ };
+ yield put(updateAndSaveLayout(updatedWidgets));
+ yield put(
+ selectWidgetInitAction(SelectionRequestType.One, [
+ newWidgetParams.newWidgetId,
+ ]),
+ );
+ }
+}
+
+function* addNewChildToDSL(
+ highlight: AnvilHighlightInfo,
+ newWidget: {
+ width: number;
+ height: number;
+ newWidgetId: string;
+ type: string;
+ },
+) {
+ const { alignment, canvasId } = highlight;
+ const allWidgets: CanvasWidgetsReduxState = yield select(getWidgets);
+
+ // Execute Blueprint operation to update widget props before creation.
+ const newParams: { [key: string]: any } = yield call(
+ executeWidgetBlueprintBeforeOperations,
+ BlueprintOperationTypes.UPDATE_CREATE_PARAMS_BEFORE_ADD,
+ {
+ parentId: canvasId,
+ widgetId: newWidget.newWidgetId,
+ widgets: allWidgets,
+ widgetType: newWidget.type,
+ },
+ );
+ const updatedParams: any = { ...newWidget, ...newParams };
+
+ // Create and add widget.
+ const updatedWidgetsOnAddition: CanvasWidgetsReduxState = yield call(
+ getUpdateDslAfterCreatingChild,
+ {
+ ...updatedParams,
+ widgetId: canvasId,
+ },
+ );
+
+ const canvasWidget = updatedWidgetsOnAddition[canvasId];
+ const canvasLayout = canvasWidget.layout
+ ? canvasWidget.layout
+ : generateDefaultLayoutPreset();
+ /**
+ * Add new widget to the children of parent canvas.
+ * Also add it to parent canvas' layout.
+ */
+ const updatedWidgets = {
+ ...updatedWidgetsOnAddition,
+ [canvasWidget.widgetId]: {
+ ...canvasWidget,
+ layout: addWidgetsToPreset(canvasLayout, highlight, [
+ {
+ widgetId: newWidget.newWidgetId,
+ alignment,
+ },
+ ]),
+ },
+ [newWidget.newWidgetId]: {
+ ...updatedWidgetsOnAddition[newWidget.newWidgetId],
+ // This is a temp fix, widget dimensions will be self computed by widgets
+ height: newWidget.height,
+ width: newWidget.width,
+ },
+ };
+ return updatedWidgets;
+}
function* addWidgetsSaga(
actionPayload: ReduxAction<{
@@ -32,57 +169,12 @@ function* addWidgetsSaga(
try {
const start = performance.now();
const { highlight, newWidget } = actionPayload.payload;
- const { alignment, canvasId } = highlight;
- const allWidgets: CanvasWidgetsReduxState = yield select(getWidgets);
- // Execute Blueprint operation to update widget props before creation.
- const newParams: { [key: string]: any } = yield call(
- executeWidgetBlueprintBeforeOperations,
- BlueprintOperationTypes.UPDATE_CREATE_PARAMS_BEFORE_ADD,
- {
- parentId: canvasId,
- widgetId: newWidget.newWidgetId,
- widgets: allWidgets,
- widgetType: newWidget.type,
- },
- );
- const updatedParams: any = { ...newWidget, ...newParams };
-
- // Create and add widget.
- const updatedWidgetsOnAddition: CanvasWidgetsReduxState = yield call(
- getUpdateDslAfterCreatingChild,
- {
- ...updatedParams,
- widgetId: canvasId,
- },
+ const updatedWidgets: CanvasWidgetsReduxState = yield call(
+ addNewChildToDSL,
+ highlight,
+ newWidget,
);
-
- const canvasWidget = updatedWidgetsOnAddition[canvasId];
- const canvasLayout = canvasWidget.layout
- ? canvasWidget.layout
- : generateDefaultLayoutPreset();
- /**
- * Add new widget to the children of parent canvas.
- * Also add it to parent canvas' layout.
- */
- const updatedWidgets = {
- ...updatedWidgetsOnAddition,
- [canvasWidget.widgetId]: {
- ...canvasWidget,
- layout: addWidgetsToPreset(canvasLayout, highlight, [
- {
- widgetId: newWidget.newWidgetId,
- alignment,
- },
- ]),
- },
- [newWidget.newWidgetId]: {
- ...updatedWidgetsOnAddition[newWidget.newWidgetId],
- // This is a temp fix, widget dimensions will be self computed by widgets
- height: newWidget.height,
- width: newWidget.width,
- },
- };
yield put(updateAndSaveLayout(updatedWidgets));
yield put(
selectWidgetInitAction(SelectionRequestType.One, [newWidget.newWidgetId]),
@@ -134,5 +226,9 @@ export default function* anvilDraggingSagas() {
yield all([
takeLatest(AnvilReduxActionTypes.ANVIL_ADD_NEW_WIDGET, addWidgetsSaga),
takeLatest(AnvilReduxActionTypes.ANVIL_MOVE_WIDGET, moveWidgetsSaga),
+ takeLatest(
+ AnvilReduxActionTypes.ANVIL_ADD_SUGGESTED_WIDGET,
+ addSuggestedWidgetsAnvilSaga,
+ ),
]);
}
diff --git a/app/client/src/layoutSystems/anvil/utils/types.ts b/app/client/src/layoutSystems/anvil/utils/types.ts
index 784685c2d9e8..26a621b7ca1c 100644
--- a/app/client/src/layoutSystems/anvil/utils/types.ts
+++ b/app/client/src/layoutSystems/anvil/utils/types.ts
@@ -10,6 +10,7 @@ export interface AnvilFlexComponentProps {
parentId?: string;
rowIndex: number;
selected?: boolean;
+ isVisible: boolean;
widgetId: string;
widgetName: string;
widgetSize?: SizeConfig;
diff --git a/app/client/src/layoutSystems/anvil/viewer/AnvilViewerWidgetOnion.tsx b/app/client/src/layoutSystems/anvil/viewer/AnvilViewerWidgetOnion.tsx
index eb8d1fcbe117..df5200c293c2 100644
--- a/app/client/src/layoutSystems/anvil/viewer/AnvilViewerWidgetOnion.tsx
+++ b/app/client/src/layoutSystems/anvil/viewer/AnvilViewerWidgetOnion.tsx
@@ -25,6 +25,7 @@ export const AnvilViewerWidgetOnion = (props: BaseWidgetProps) => {
return (
<AnvilFlexComponent
isResizeDisabled={props.resizeDisabled}
+ isVisible={!!props.isVisible}
layoutId={props.layoutId}
parentId={props.parentId}
rowIndex={props.rowIndex}
diff --git a/app/client/src/layoutSystems/common/canvasArenas/StickyCanvasArena.tsx b/app/client/src/layoutSystems/common/canvasArenas/StickyCanvasArena.tsx
index 7d073aae19b8..57507117c979 100644
--- a/app/client/src/layoutSystems/common/canvasArenas/StickyCanvasArena.tsx
+++ b/app/client/src/layoutSystems/common/canvasArenas/StickyCanvasArena.tsx
@@ -24,6 +24,61 @@ interface StickyCanvasArenaRef {
slidingArenaRef: RefObject<HTMLDivElement>;
}
+/**
+ * we use IntersectionObserver to detect the amount of canvas(stickyCanvasRef) that is interactable at any point of time
+ * and resize and reposition it wrt to the slider(slidingArenaRef).
+ * downside to this is it fires events everytime the widget is interactable which is a lot.
+ * in this function we process events to check for changes on which updating of the canvas styles is based upon in
+ * repositionSliderCanvas and rescaleSliderCanvas functions.
+ *
+ * if no changes are required then we could safely skip calling the repositionSliderCanvas and rescaleSliderCanvas.
+ * Why is it important to limit calling repositionSliderCanvas and rescaleSliderCanvas
+ * every time a canvas style is updated(even with the same values) or the canvas is scaled,
+ * the canvas loses context and has to be redrawn which is a costly operation if done very frequent.
+ */
+const shouldUpdateCanvas = (
+ currentEntry: IntersectionObserverEntry,
+ previousEntry?: IntersectionObserverEntry,
+) => {
+ if (previousEntry) {
+ const {
+ boundingClientRect: {
+ left: previousBoundingLeft,
+ top: previousBoundingTop,
+ },
+ intersectionRect: {
+ height: previousIntersectHeight,
+ left: previousIntersectLeft,
+ top: previousIntersectTop,
+ width: previousIntersectWidth,
+ },
+ } = previousEntry;
+ const {
+ boundingClientRect: {
+ left: currentBoundingLeft,
+ top: currentBoundingTop,
+ },
+ intersectionRect: {
+ height: currentIntersectHeight,
+ left: currentIntersectLeft,
+ top: currentIntersectTop,
+ width: currentIntersectWidth,
+ },
+ } = currentEntry;
+ if (
+ previousIntersectHeight === currentIntersectHeight &&
+ previousIntersectWidth === currentIntersectWidth &&
+ previousIntersectLeft === currentIntersectLeft &&
+ previousIntersectTop === currentIntersectTop &&
+ previousBoundingTop === currentBoundingTop &&
+ previousBoundingLeft === currentBoundingLeft
+ ) {
+ return false;
+ }
+ }
+ return true;
+};
+
const StyledCanvasSlider = styled.div<{ paddingBottom: number }>`
position: absolute;
top: 0px;
@@ -49,7 +104,7 @@ export const StickyCanvasArena = forwardRef(
sliderId,
} = props;
const { slidingArenaRef, stickyCanvasRef } = ref.current;
-
+ const previousIntersectionEntry = useRef<IntersectionObserverEntry>();
const interSectionObserver = useRef(
new IntersectionObserver((entries) => {
entries.forEach(updateCanvasStylesIntersection);
@@ -94,9 +149,14 @@ export const StickyCanvasArena = forwardRef(
slidingArenaRef.current,
);
- if (parentCanvas && stickyCanvasRef.current) {
+ if (
+ parentCanvas &&
+ stickyCanvasRef.current &&
+ shouldUpdateCanvas(entry, previousIntersectionEntry.current)
+ ) {
repositionSliderCanvas(entry);
rescaleSliderCanvas(entry);
+ previousIntersectionEntry.current = entry;
}
});
}
diff --git a/app/client/src/layoutSystems/common/mainContainerResizer/useMainContainerResizer.ts b/app/client/src/layoutSystems/common/mainContainerResizer/useMainContainerResizer.ts
new file mode 100644
index 000000000000..e30ba3f823d7
--- /dev/null
+++ b/app/client/src/layoutSystems/common/mainContainerResizer/useMainContainerResizer.ts
@@ -0,0 +1,20 @@
+import { LayoutSystemTypes } from "layoutSystems/types";
+import { useSelector } from "react-redux";
+import { previewModeSelector } from "selectors/editorSelectors";
+import { getLayoutSystemType } from "selectors/layoutSystemSelectors";
+import {
+ LayoutSystemFeatures,
+ useLayoutSystemFeatures,
+} from "../useLayoutSystemFeatures";
+
+export const useMainContainerResizer = () => {
+ const checkLayoutSystemFeatures = useLayoutSystemFeatures();
+ const [enableMainContainerResizer] = checkLayoutSystemFeatures([
+ LayoutSystemFeatures.ENABLE_MAIN_CONTAINER_RESIZER,
+ ]);
+ const layoutSystemType = useSelector(getLayoutSystemType);
+ const isPreviewMode = useSelector(previewModeSelector);
+ const canShowResizer =
+ layoutSystemType === LayoutSystemTypes.ANVIL ? isPreviewMode : true;
+ return { enableMainContainerResizer, canShowResizer };
+};
diff --git a/app/client/src/pages/Editor/WidgetsEditor/MainContainerWrapper.tsx b/app/client/src/pages/Editor/WidgetsEditor/MainContainerWrapper.tsx
index 4a424ea0989b..9cdb3b5a01aa 100644
--- a/app/client/src/pages/Editor/WidgetsEditor/MainContainerWrapper.tsx
+++ b/app/client/src/pages/Editor/WidgetsEditor/MainContainerWrapper.tsx
@@ -32,12 +32,9 @@ import Canvas from "../Canvas";
import type { AppState } from "@appsmith/reducers";
import { useFeatureFlag } from "utils/hooks/useFeatureFlag";
import { getIsAnonymousDataPopupVisible } from "selectors/onboardingSelectors";
-import {
- LayoutSystemFeatures,
- useLayoutSystemFeatures,
-} from "../../../layoutSystems/common/useLayoutSystemFeatures";
import { CANVAS_VIEWPORT } from "constants/componentClassNameConstants";
import { MainContainerResizer } from "layoutSystems/common/mainContainerResizer/MainContainerResizer";
+import { useMainContainerResizer } from "layoutSystems/common/mainContainerResizer/useMainContainerResizer";
interface MainCanvasWrapperProps {
isPreviewMode: boolean;
@@ -145,11 +142,8 @@ function MainContainerWrapper(props: MainCanvasWrapperProps) {
const isLayoutingInitialized = useDynamicAppLayout();
const isPageInitializing = isFetchingPage || !isLayoutingInitialized;
const isWDSV2Enabled = useFeatureFlag("ab_wds_enabled");
-
- const checkLayoutSystemFeatures = useLayoutSystemFeatures();
- const [enableMainContainerResizer] = checkLayoutSystemFeatures([
- LayoutSystemFeatures.ENABLE_MAIN_CONTAINER_RESIZER,
- ]);
+ const { canShowResizer, enableMainContainerResizer } =
+ useMainContainerResizer();
useEffect(() => {
return () => {
@@ -262,7 +256,7 @@ function MainContainerWrapper(props: MainCanvasWrapperProps) {
</Wrapper>
<MainContainerResizer
currentPageId={currentPageId}
- enableMainCanvasResizer={enableMainContainerResizer}
+ enableMainCanvasResizer={enableMainContainerResizer && canShowResizer}
heightWithTopMargin={heightWithTopMargin}
isPageInitiated={!isPageInitializing && !!widgetsStructure}
isPreview={isPreviewMode || isProtectedMode}
diff --git a/app/client/src/sagas/WidgetOperationSagas.tsx b/app/client/src/sagas/WidgetOperationSagas.tsx
index a03ed4dbd1cd..e839d144fa0c 100644
--- a/app/client/src/sagas/WidgetOperationSagas.tsx
+++ b/app/client/src/sagas/WidgetOperationSagas.tsx
@@ -181,6 +181,7 @@ import localStorage from "utils/localStorage";
import type { FlexLayer } from "layoutSystems/autolayout/utils/types";
import { EMPTY_BINDING } from "components/editorComponents/ActionCreator/constants";
import { getLayoutSystemType } from "selectors/layoutSystemSelectors";
+import { addSuggestedWidgetAnvilAction } from "layoutSystems/anvil/integrations/actions/draggingActions";
export function* resizeSaga(resizeAction: ReduxAction<WidgetResize>) {
try {
@@ -2041,7 +2042,7 @@ function* addSuggestedWidget(action: ReduxAction<Partial<WidgetProps>>) {
const widgets: CanvasWidgetsReduxState = yield select(getWidgets);
const widgetName = getNextWidgetName(widgets, widgetConfig.type, evalTree);
- const isAutoLayout: boolean = yield select(getIsAutoLayout);
+ const layoutSystemType: LayoutSystemTypes = yield select(getLayoutSystemType);
try {
let newWidget = {
newWidgetId: generateReactKey(),
@@ -2069,26 +2070,39 @@ function* addSuggestedWidget(action: ReduxAction<Partial<WidgetProps>>) {
bottomRow,
parentRowSpace: GridDefaults.DEFAULT_GRID_ROW_HEIGHT,
};
-
- if (isAutoLayout) {
- yield put({
- type: ReduxActionTypes.AUTOLAYOUT_ADD_NEW_WIDGETS,
- payload: {
- dropPayload: {
- isNewLayer: true,
- alignment: FlexLayerAlignment.Start,
+ switch (layoutSystemType) {
+ case LayoutSystemTypes.AUTO:
+ yield put({
+ type: ReduxActionTypes.AUTOLAYOUT_ADD_NEW_WIDGETS,
+ payload: {
+ dropPayload: {
+ isNewLayer: true,
+ alignment: FlexLayerAlignment.Start,
+ },
+ newWidget,
+ parentId: MAIN_CONTAINER_WIDGET_ID,
+ direction: LayoutDirection.Vertical,
+ addToBottom: true,
},
- newWidget,
- parentId: MAIN_CONTAINER_WIDGET_ID,
- direction: LayoutDirection.Vertical,
- addToBottom: true,
- },
- });
- } else {
- yield put({
- type: WidgetReduxActionTypes.WIDGET_ADD_CHILD,
- payload: newWidget,
- });
+ });
+ break;
+ case LayoutSystemTypes.ANVIL:
+ yield put(
+ addSuggestedWidgetAnvilAction({
+ newWidgetId: newWidget.newWidgetId,
+ rows: newWidget.rows,
+ columns: newWidget.columns,
+ type: newWidget.type,
+ ...widgetConfig,
+ }),
+ );
+ break;
+ default:
+ yield put({
+ type: WidgetReduxActionTypes.WIDGET_ADD_CHILD,
+ payload: newWidget,
+ });
+ break;
}
yield take(ReduxActionTypes.UPDATE_LAYOUT);
diff --git a/app/client/src/widgets/withWidgetProps.tsx b/app/client/src/widgets/withWidgetProps.tsx
index c421a9782d54..bebb1792dca7 100644
--- a/app/client/src/widgets/withWidgetProps.tsx
+++ b/app/client/src/widgets/withWidgetProps.tsx
@@ -242,7 +242,11 @@ function withWidgetProps(WrappedWidget: typeof BaseWidget) {
!isPreviewMode;
widgetProps.mainCanvasWidth = mainCanvasWidth;
- if (layoutSystemType !== LayoutSystemTypes.ANVIL) {
+ if (layoutSystemType === LayoutSystemTypes.ANVIL) {
+ if (shouldCollapseWidgetInViewOrPreviewMode) {
+ return null;
+ }
+ } else {
// We don't render invisible widgets in view mode
if (shouldCollapseWidgetInViewOrPreviewMode) {
// This flag (isMetaWidget) is used to prevent the Auto height saga from updating
|
af9e89d2a1b103bbcfb4bde6ed6cccc23eb0f714
|
2023-10-20 11:08:47
|
arunvjn
|
chore: remove xml parser v3 as a default library (#28012)
| false
|
remove xml parser v3 as a default library (#28012)
|
chore
|
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 3fc3d6ef511d..caee6aa86de4 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
@@ -86,15 +86,6 @@ describe("Autocomplete bug fixes", function () {
);
});
- it("6. feat #16426 Autocomplete for fast-xml-parser", function () {
- entityExplorer.SelectEntityByName("Text1");
- propPane.TypeTextIntoField("Text", "{{xmlParser.j");
- agHelper.GetNAssertElementText(locators._hints, "j2xParser");
-
- propPane.TypeTextIntoField("Text", "{{new xmlParser.j2xParser().p");
- agHelper.GetNAssertElementText(locators._hints, "parse");
- });
-
it(
"excludeForAirgap",
"7. Installed library should show up in autocomplete",
diff --git a/app/client/cypress/e2e/Regression/ClientSide/Binding/xmlParser_spec.js b/app/client/cypress/e2e/Regression/ClientSide/Binding/xmlParser_spec.js
index 5cd7b98d3fce..6adf665579dd 100644
--- a/app/client/cypress/e2e/Regression/ClientSide/Binding/xmlParser_spec.js
+++ b/app/client/cypress/e2e/Regression/ClientSide/Binding/xmlParser_spec.js
@@ -3,9 +3,21 @@ import * as _ from "../../../../support/Objects/ObjectsCore";
describe("xml2json text", function () {
before(() => {
- _.agHelper.AddDsl("xmlParser");
+ _.homePage.NavigateToHome();
+ _.homePage.ImportApp("xmlParser.json");
+ _.homePage.AssertImportToast();
});
- it("1. Publish widget and validate the data displayed in text widget from xmlParser function", function () {
+
+ it("1. Check if XMLparser v3 autocomplete works", function () {
+ _.entityExplorer.SelectEntityByName("Text2", "Widgets");
+ _.propPane.TypeTextIntoField("Text", "{{xmlParser.j", true);
+ _.agHelper.GetNAssertElementText(_.locators._hints, "j2xParser");
+
+ _.propPane.TypeTextIntoField("Text", "{{new xmlParser.j2xParser().p", true);
+ _.agHelper.GetNAssertElementText(_.locators._hints, "parse");
+ });
+
+ it("2. Publish widget and validate the data displayed in text widget from xmlParser function", function () {
_.deployMode.DeployApp();
cy.get(publish.textWidget)
.first()
diff --git a/app/client/cypress/e2e/Regression/ClientSide/Git/ExistingApps/v1.9.24/DSCrudAndBindings_Spec.ts b/app/client/cypress/e2e/Regression/ClientSide/Git/ExistingApps/v1.9.24/DSCrudAndBindings_Spec.ts
index 0504dea35dea..a24ac844b60d 100644
--- a/app/client/cypress/e2e/Regression/ClientSide/Git/ExistingApps/v1.9.24/DSCrudAndBindings_Spec.ts
+++ b/app/client/cypress/e2e/Regression/ClientSide/Git/ExistingApps/v1.9.24/DSCrudAndBindings_Spec.ts
@@ -53,11 +53,13 @@ describe("Import and validate older app (app created in older versions of Appsmi
gitSync._gitStatusChanges,
/[0-9] page(|s) modified/,
);
- agHelper.GetNAssertElementText(
- gitSync._gitStatusChanges,
- "Application settings modified",
- "not.contain.text",
- );
+
+ // Commenting it as part of #28012 - to be added back later
+ // agHelper.GetNAssertElementText(
+ // gitSync._gitStatusChanges,
+ // "Application settings modified",
+ // "not.contain.text",
+ // );
agHelper.GetNAssertElementText(
gitSync._gitStatusChanges,
"Theme modified",
@@ -73,7 +75,10 @@ describe("Import and validate older app (app created in older versions of Appsmi
// );
agHelper.AssertContains(/[0-9] JS Object(|s) modified/, "not.exist");
- agHelper.AssertContains(/[0-9] librar(y|ies) modified/, "not.exist");
+
+ // Commenting it as part of #28012 - to be added back later
+ // agHelper.AssertContains(/[0-9] librar(y|ies) modified/, "not.exist");
+
agHelper.GetNAssertElementText(
gitSync._gitStatusChanges,
"Some of the changes above are due to an improved file structure designed to reduce merge conflicts. You can safely commit them to your repository.",
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 4c77d0fabfb8..e7282223c1b9 100644
--- a/app/client/cypress/e2e/Regression/ClientSide/JSLibrary/Library_spec.ts
+++ b/app/client/cypress/e2e/Regression/ClientSide/JSLibrary/Library_spec.ts
@@ -10,14 +10,13 @@ describe("excludeForAirgap", "Tests JS Libraries", () => {
_.installer.assertUnInstall("uuidjs");
});
- it("2. Checks for naming collision", () => {
+ it("2. Installs the library against a unique namespace when there is a collision with the existing entity", () => {
_.entityExplorer.DragDropWidgetNVerify(_.draggableWidgets.TABLE, 200, 200);
_.entityExplorer.NavigateToSwitcher("Explorer");
_.entityExplorer.RenameEntityFromExplorer("Table1", "jsonwebtoken");
_.entityExplorer.ExpandCollapseEntity("Libraries");
_.installer.OpenInstaller();
- _.installer.installLibrary("jsonwebtoken", "jsonwebtoken", false);
- _.agHelper.AssertContains("Name collision detected: jsonwebtoken");
+ _.installer.installLibrary("jsonwebtoken", "jsonwebtoken_1", true);
});
it("3. Checks jspdf library", () => {
diff --git a/app/client/cypress/fixtures/xmlParser.json b/app/client/cypress/fixtures/xmlParser.json
index ed63586a5c86..65573652b83e 100644
--- a/app/client/cypress/fixtures/xmlParser.json
+++ b/app/client/cypress/fixtures/xmlParser.json
@@ -1,64 +1,342 @@
{
- "dsl": {
- "widgetName": "MainContainer",
- "backgroundColor": "none",
- "rightColumn": 1224,
- "snapColumns": 16,
- "detachFromLayout": true,
- "widgetId": "0",
- "topRow": 0,
- "bottomRow": 1280,
- "containerStyle": "none",
- "snapRows": 33,
- "parentRowSpace": 1,
- "type": "CANVAS_WIDGET",
- "canExtend": true,
- "version": 7,
- "minHeight": 1292,
- "parentColumnSpace": 1,
- "leftColumn": 0,
- "dynamicBindingPathList": [],
- "children": [
+ "clientSchemaVersion": 1.0,
+ "serverSchemaVersion": 6.0,
+ "exportedApplication": {
+ "name": "xml_paser_test",
+ "isPublic": false,
+ "pages": [
{
- "isVisible": true,
- "text": "{{xmlParser.parse(Input1.text) }}",
- "textStyle": "LABEL",
- "textAlign": "LEFT",
- "widgetName": "Text1",
- "type": "TEXT_WIDGET",
- "isLoading": false,
- "parentColumnSpace": 74,
- "parentRowSpace": 40,
- "leftColumn": 3,
- "rightColumn": 8,
- "topRow": 3,
- "bottomRow": 10,
- "parentId": "0",
- "widgetId": "axlcnmjk4t",
- "dynamicBindingPathList": [
+ "id": "Page1",
+ "isDefault": true
+ }
+ ],
+ "publishedPages": [
+ {
+ "id": "Page1",
+ "isDefault": true
+ }
+ ],
+ "viewMode": false,
+ "appIsExample": false,
+ "unreadCommentThreads": 0.0,
+ "color": "#EAEDFB",
+ "icon": "yen",
+ "slug": "xml-paser-test",
+ "unpublishedCustomJSLibs": [],
+ "publishedCustomJSLibs": [],
+ "evaluationVersion": 2.0,
+ "applicationVersion": 2.0,
+ "collapseInvisibleWidgets": true,
+ "isManualUpdate": false,
+ "deleted": false
+ },
+ "datasourceList": [],
+ "customJSLibList": [],
+ "pageList": [
+ {
+ "unpublishedPage": {
+ "name": "Page1",
+ "slug": "page1",
+ "layouts": [
{
- "key": "text"
+ "viewMode": false,
+ "dsl": {
+ "widgetName": "MainContainer",
+ "backgroundColor": "none",
+ "rightColumn": 4896.0,
+ "snapColumns": 64.0,
+ "detachFromLayout": true,
+ "widgetId": "0",
+ "topRow": 0.0,
+ "bottomRow": 380.0,
+ "containerStyle": "none",
+ "snapRows": 124.0,
+ "parentRowSpace": 1.0,
+ "type": "CANVAS_WIDGET",
+ "canExtend": true,
+ "version": 87.0,
+ "minHeight": 1292.0,
+ "dynamicTriggerPathList": [],
+ "parentColumnSpace": 1.0,
+ "dynamicBindingPathList": [],
+ "leftColumn": 0.0,
+ "children": [
+ {
+ "mobileBottomRow": 14.0,
+ "widgetName": "Text1",
+ "displayName": "Text",
+ "iconSVG": "https://release-appcdn.appsmith.com/static/media/icon.a47d6d5dbbb718c4dc4b2eb4f218c1b7.svg",
+ "searchTags": [
+ "typography",
+ "paragraph",
+ "label"
+ ],
+ "topRow": 0.0,
+ "bottomRow": 16.0,
+ "parentRowSpace": 10.0,
+ "type": "TEXT_WIDGET",
+ "hideCard": false,
+ "mobileRightColumn": 23.0,
+ "animateLoading": true,
+ "overflow": "NONE",
+ "fontFamily": "{{appsmith.theme.fontFamily.appFont}}",
+ "parentColumnSpace": 14.953125,
+ "dynamicTriggerPathList": [],
+ "leftColumn": 0.0,
+ "dynamicBindingPathList": [
+ {
+ "key": "truncateButtonColor"
+ },
+ {
+ "key": "fontFamily"
+ },
+ {
+ "key": "borderRadius"
+ },
+ {
+ "key": "text"
+ }
+ ],
+ "shouldTruncate": false,
+ "truncateButtonColor": "{{appsmith.theme.colors.primaryColor}}",
+ "text": "{{xmlParser.parse(Input1.text)}}",
+ "key": "bdg0tfrf6x",
+ "isDeprecated": false,
+ "rightColumn": 13.0,
+ "textAlign": "LEFT",
+ "dynamicHeight": "AUTO_HEIGHT",
+ "widgetId": "b8blvt9b2z",
+ "minWidth": 450.0,
+ "isVisible": true,
+ "fontStyle": "BOLD",
+ "textColor": "#231F20",
+ "version": 1.0,
+ "parentId": "0",
+ "tags": [
+ "Suggested",
+ "Content"
+ ],
+ "renderMode": "CANVAS",
+ "isLoading": false,
+ "mobileTopRow": 10.0,
+ "responsiveBehavior": "fill",
+ "originalTopRow": 0.0,
+ "borderRadius": "{{appsmith.theme.borderRadius.appBorderRadius}}",
+ "mobileLeftColumn": 7.0,
+ "maxDynamicHeight": 9000.0,
+ "originalBottomRow": 4.0,
+ "fontSize": "1rem",
+ "minDynamicHeight": 4.0
+ },
+ {
+ "boxShadow": "none",
+ "iconSVG": "https://release-appcdn.appsmith.com/static/media/icon.f2c34197dbcf03595098986de898928f.svg",
+ "topRow": 17.0,
+ "labelWidth": 5.0,
+ "type": "INPUT_WIDGET_V2",
+ "animateLoading": true,
+ "resetOnSubmit": true,
+ "leftColumn": 0.0,
+ "dynamicBindingPathList": [
+ {
+ "key": "accentColor"
+ },
+ {
+ "key": "borderRadius"
+ }
+ ],
+ "labelStyle": "",
+ "inputType": "TEXT",
+ "isDisabled": false,
+ "isRequired": false,
+ "dynamicHeight": "FIXED",
+ "accentColor": "{{appsmith.theme.colors.primaryColor}}",
+ "showStepArrows": false,
+ "isVisible": true,
+ "version": 2.0,
+ "tags": [
+ "Suggested",
+ "Inputs"
+ ],
+ "isLoading": false,
+ "borderRadius": "{{appsmith.theme.borderRadius.appBorderRadius}}",
+ "originalBottomRow": 21.0,
+ "mobileBottomRow": 21.0,
+ "widgetName": "Input1",
+ "displayName": "Input",
+ "searchTags": [
+ "form",
+ "text input",
+ "number",
+ "textarea"
+ ],
+ "bottomRow": 24.0,
+ "parentRowSpace": 10.0,
+ "autoFocus": false,
+ "hideCard": false,
+ "mobileRightColumn": 19.0,
+ "parentColumnSpace": 14.34375,
+ "dynamicTriggerPathList": [],
+ "labelPosition": "Top",
+ "key": "mx0emg6xlv",
+ "labelTextSize": "0.875rem",
+ "isDeprecated": false,
+ "rightColumn": 19.0,
+ "widgetId": "ni16fc0xys",
+ "minWidth": 450.0,
+ "label": "Label",
+ "parentId": "0",
+ "labelAlignment": "left",
+ "renderMode": "CANVAS",
+ "mobileTopRow": 14.0,
+ "responsiveBehavior": "fill",
+ "originalTopRow": 14.0,
+ "mobileLeftColumn": 0.0,
+ "maxDynamicHeight": 9000.0,
+ "iconAlign": "left",
+ "defaultText": "<note> <to>Tove</to> <from>Jani</from> <heading>Reminder</heading> <body>Don't forget me this weekend!</body> </note>",
+ "minDynamicHeight": 4.0
+ },
+ {
+ "mobileBottomRow": 35.0,
+ "widgetName": "Text2",
+ "displayName": "Text",
+ "iconSVG": "https://release-appcdn.appsmith.com/static/media/icon.a47d6d5dbbb718c4dc4b2eb4f218c1b7.svg",
+ "searchTags": [
+ "typography",
+ "paragraph",
+ "label"
+ ],
+ "topRow": 31.0,
+ "bottomRow": 35.0,
+ "parentRowSpace": 10.0,
+ "type": "TEXT_WIDGET",
+ "hideCard": false,
+ "mobileRightColumn": 16.0,
+ "animateLoading": true,
+ "overflow": "NONE",
+ "fontFamily": "{{appsmith.theme.fontFamily.appFont}}",
+ "parentColumnSpace": 14.34375,
+ "leftColumn": 0.0,
+ "dynamicBindingPathList": [
+ {
+ "key": "truncateButtonColor"
+ },
+ {
+ "key": "fontFamily"
+ },
+ {
+ "key": "borderRadius"
+ },
+ {
+ "key": "text"
+ }
+ ],
+ "shouldTruncate": false,
+ "truncateButtonColor": "{{appsmith.theme.colors.primaryColor}}",
+ "text": "Hello {{appsmith.user.name || appsmith.user.email}}",
+ "key": "bdg0tfrf6x",
+ "isDeprecated": false,
+ "rightColumn": 20.0,
+ "textAlign": "LEFT",
+ "dynamicHeight": "AUTO_HEIGHT",
+ "widgetId": "3m7c3st35v",
+ "minWidth": 450.0,
+ "isVisible": true,
+ "fontStyle": "BOLD",
+ "textColor": "#231F20",
+ "version": 1.0,
+ "parentId": "0",
+ "tags": [
+ "Suggested",
+ "Content"
+ ],
+ "renderMode": "CANVAS",
+ "isLoading": false,
+ "mobileTopRow": 31.0,
+ "responsiveBehavior": "fill",
+ "borderRadius": "{{appsmith.theme.borderRadius.appBorderRadius}}",
+ "mobileLeftColumn": 0.0,
+ "maxDynamicHeight": 9000.0,
+ "fontSize": "1rem",
+ "minDynamicHeight": 4.0
+ }
+ ]
+ },
+ "layoutOnLoadActions": [],
+ "layoutOnLoadActionErrors": [],
+ "validOnPageLoadActions": true,
+ "id": "Page1",
+ "deleted": false,
+ "policies": [],
+ "userPermissions": []
}
- ]
+ ],
+ "userPermissions": [],
+ "policies": []
},
- {
- "isVisible": true,
- "inputType": "TEXT",
- "label": "",
- "widgetName": "Input1",
- "type": "INPUT_WIDGET_V2",
- "isLoading": false,
- "parentColumnSpace": 74,
- "parentRowSpace": 40,
- "leftColumn": 3,
- "rightColumn": 8,
- "topRow": 2,
- "bottomRow": 3,
- "parentId": "0",
- "widgetId": "8n5urob9mz",
- "dynamicBindingPathList": [],
- "defaultText": "<note> <to>Tove</to> <from>Jani</from> <heading>Reminder</heading> <body>Don't forget me this weekend!</body> </note>"
- }
- ]
+ "publishedPage": {
+ "name": "Page1",
+ "slug": "page1",
+ "layouts": [
+ {
+ "viewMode": false,
+ "dsl": {
+ "widgetName": "MainContainer",
+ "backgroundColor": "none",
+ "rightColumn": 1224.0,
+ "snapColumns": 16.0,
+ "detachFromLayout": true,
+ "widgetId": "0",
+ "topRow": 0.0,
+ "bottomRow": 1250.0,
+ "containerStyle": "none",
+ "snapRows": 33.0,
+ "parentRowSpace": 1.0,
+ "type": "CANVAS_WIDGET",
+ "canExtend": true,
+ "version": 4.0,
+ "minHeight": 1292.0,
+ "dynamicTriggerPathList": [],
+ "parentColumnSpace": 1.0,
+ "dynamicBindingPathList": [],
+ "leftColumn": 0.0,
+ "children": []
+ },
+ "validOnPageLoadActions": true,
+ "id": "Page1",
+ "deleted": false,
+ "policies": [],
+ "userPermissions": []
+ }
+ ],
+ "userPermissions": [],
+ "policies": []
+ },
+ "deleted": false,
+ "gitSyncId": "6529174c97a7581320fb6a4f_6529174c97a7581320fb6a51"
+ }
+ ],
+ "actionList": [],
+ "actionCollectionList": [],
+ "updatedResources": {
+ "customJSLibList": [],
+ "actionList": [],
+ "pageList": [
+ "Page1"
+ ],
+ "actionCollectionList": []
+ },
+ "editModeTheme": {
+ "name": "Default-New",
+ "displayName": "Modern",
+ "isSystemTheme": true,
+ "deleted": false
+ },
+ "publishedTheme": {
+ "name": "Default-New",
+ "displayName": "Modern",
+ "isSystemTheme": true,
+ "deleted": false
}
-}
+}
\ No newline at end of file
diff --git a/app/client/package.json b/app/client/package.json
index 2079505bdcd1..de934e1b83cc 100644
--- a/app/client/package.json
+++ b/app/client/package.json
@@ -104,7 +104,6 @@
"echarts-gl": "^2.0.9",
"fast-deep-equal": "^3.1.3",
"fast-sort": "^3.4.0",
- "fast-xml-parser": "^3.17.5",
"fastdom": "^1.0.11",
"focus-trap-react": "^8.9.2",
"fuse.js": "^3.4.5",
diff --git a/app/client/src/actions/JSLibraryActions.ts b/app/client/src/actions/JSLibraryActions.ts
index 9076263d3f56..6ab4709057c2 100644
--- a/app/client/src/actions/JSLibraryActions.ts
+++ b/app/client/src/actions/JSLibraryActions.ts
@@ -1,5 +1,5 @@
import { ReduxActionTypes } from "@appsmith/constants/ReduxActionConstants";
-import type { TJSLibrary } from "workers/common/JSLibrary";
+import type { JSLibrary } from "workers/common/JSLibrary";
export function fetchJSLibraries(applicationId: string) {
return {
@@ -8,7 +8,7 @@ export function fetchJSLibraries(applicationId: string) {
};
}
-export function installLibraryInit(payload: Partial<TJSLibrary>) {
+export function installLibraryInit(payload: Partial<JSLibrary>) {
return {
type: ReduxActionTypes.INSTALL_LIBRARY_INIT,
payload,
@@ -22,7 +22,7 @@ export function toggleInstaller(payload: boolean) {
};
}
-export function uninstallLibraryInit(payload: TJSLibrary) {
+export function uninstallLibraryInit(payload: JSLibrary) {
return {
type: ReduxActionTypes.UNINSTALL_LIBRARY_INIT,
payload,
diff --git a/app/client/src/api/LibraryAPI.tsx b/app/client/src/api/LibraryAPI.tsx
index 123d4801e1eb..73b5c0d879c7 100644
--- a/app/client/src/api/LibraryAPI.tsx
+++ b/app/client/src/api/LibraryAPI.tsx
@@ -1,5 +1,5 @@
import { APP_MODE } from "entities/App";
-import type { TJSLibrary } from "workers/common/JSLibrary";
+import type { JSLibrary } from "workers/common/JSLibrary";
import Api from "./Api";
export default class LibraryApi extends Api {
@@ -10,7 +10,7 @@ export default class LibraryApi extends Api {
static async addLibrary(
applicationId: string,
- library: Partial<TJSLibrary> & { defs: string },
+ library: Partial<JSLibrary> & { defs: string },
) {
const url = LibraryApi.getUpdateLibraryBaseURL(applicationId) + "/add";
return Api.patch(url, library);
@@ -18,7 +18,7 @@ export default class LibraryApi extends Api {
static async removeLibrary(
applicationId: string,
- library: Partial<TJSLibrary>,
+ library: Partial<JSLibrary>,
) {
const url = LibraryApi.getUpdateLibraryBaseURL(applicationId) + "/remove";
return Api.patch(url, library);
diff --git a/app/client/src/ce/selectors/entitiesSelector.ts b/app/client/src/ce/selectors/entitiesSelector.ts
index 35aa61a050d3..484070825b1a 100644
--- a/app/client/src/ce/selectors/entitiesSelector.ts
+++ b/app/client/src/ce/selectors/entitiesSelector.ts
@@ -39,7 +39,7 @@ import {
import { InstallState } from "reducers/uiReducers/libraryReducer";
import recommendedLibraries from "pages/Editor/Explorer/Libraries/recommendedLibraries";
-import type { TJSLibrary } from "workers/common/JSLibrary";
+import type { JSLibrary } from "workers/common/JSLibrary";
import { getEntityNameAndPropertyPath } from "@appsmith/workers/Evaluation/evaluationUtils";
import { getFormValues } from "redux-form";
import { TEMP_DATASOURCE_ID } from "constants/Datasource";
@@ -1099,7 +1099,7 @@ export const selectLibrariesForExplorer = createSelector(
version: recommendedLibrary?.version || "",
url: recommendedLibrary?.url || url,
accessor: [],
- } as TJSLibrary;
+ } as JSLibrary;
});
return [...queuedInstalls, ...libs];
},
diff --git a/app/client/src/constants/defs/xmlParser.json b/app/client/src/constants/defs/xmlParser.json
deleted file mode 100644
index 83f55cbe1326..000000000000
--- a/app/client/src/constants/defs/xmlParser.json
+++ /dev/null
@@ -1,39 +0,0 @@
-{
- "!name": "LIB/xmlParser",
- "xmlParser": {
- "parse": {
- "!doc": "converts xml string to json object",
- "!type": "fn(xml: string, options?: object, validationOption?: object) -> object"
- },
- "validate": {
- "!doc": "validate xml data",
- "!type": "fn(xml: string) -> bool"
- },
- "convertToJson": {
- "!type": "fn(node: ?, options: object) -> ?"
- },
- "convertToJsonString": {
- "!type": "fn(node: ?, options: object) -> string"
- },
- "convertTonimn": {
- "!type": "fn(node: ?, e_schema: ?, options: object) -> ?"
- },
- "getTraversalObj": {
- "!type": "fn(xmlData: ?, options: object) -> ?"
- },
- "j2xParser": {
- "!type": "fn(options: object) -> object",
- "prototype": {
- "parse": {
- "!type": "fn(jObj: ?)"
- },
- "j2x": {
- "!type": "fn(jObj: ?, level: ?)"
- }
- }
- },
- "parseToNimn": {
- "!type": "fn(xmlData: ?, schema: ?, options: ?) -> ?"
- }
- }
-}
diff --git a/app/client/src/pages/Editor/Explorer/Libraries/Installer.tsx b/app/client/src/pages/Editor/Explorer/Libraries/Installer.tsx
index 0451226a3f65..1d04e4aa939c 100644
--- a/app/client/src/pages/Editor/Explorer/Libraries/Installer.tsx
+++ b/app/client/src/pages/Editor/Explorer/Libraries/Installer.tsx
@@ -36,7 +36,7 @@ import recommendedLibraries from "pages/Editor/Explorer/Libraries/recommendedLib
import type { AppState } from "@appsmith/reducers";
import { installLibraryInit } from "actions/JSLibraryActions";
import classNames from "classnames";
-import type { TJSLibrary } from "workers/common/JSLibrary";
+import type { JSLibrary } from "workers/common/JSLibrary";
import AnalyticsUtil from "utils/AnalyticsUtil";
import { EntityClassNames } from "pages/Editor/Explorer/Entity";
@@ -317,7 +317,7 @@ export function Installer() {
}, [URL, isValid]);
const installLibrary = useCallback(
- (lib?: Partial<TJSLibrary>) => {
+ (lib?: Partial<JSLibrary>) => {
const url = lib?.url || URL;
const isQueued = queuedLibraries.find((libURL) => libURL === url);
if (isQueued) return;
diff --git a/app/client/src/pages/Editor/Explorer/Libraries/index.tsx b/app/client/src/pages/Editor/Explorer/Libraries/index.tsx
index 7e502331be23..848dd8116a66 100644
--- a/app/client/src/pages/Editor/Explorer/Libraries/index.tsx
+++ b/app/client/src/pages/Editor/Explorer/Libraries/index.tsx
@@ -33,7 +33,7 @@ import {
uninstallLibraryInit,
} from "actions/JSLibraryActions";
import EntityAddButton from "../Entity/AddButton";
-import type { TJSLibrary } from "workers/common/JSLibrary";
+import type { JSLibrary } from "workers/common/JSLibrary";
import {
getCurrentPageId,
getPagePermissions,
@@ -177,7 +177,7 @@ const Version = styled.div<{ version?: string }>`
margin: ${(props) => (props.version ? "0 8px" : "0")};
`;
-const PrimaryCTA = function ({ lib }: { lib: TJSLibrary }) {
+const PrimaryCTA = function ({ lib }: { lib: JSLibrary }) {
const installationStatus = useSelector(selectInstallationStatus);
const dispatch = useDispatch();
@@ -215,7 +215,7 @@ const PrimaryCTA = function ({ lib }: { lib: TJSLibrary }) {
return null;
};
-function LibraryEntity({ lib }: { lib: TJSLibrary }) {
+function LibraryEntity({ lib }: { lib: JSLibrary }) {
const openDocs = useCallback(
(url?: string) => (e: React.MouseEvent) => {
e?.stopPropagation();
diff --git a/app/client/src/pages/Editor/Explorer/Libraries/recommendedLibraries.ts b/app/client/src/pages/Editor/Explorer/Libraries/recommendedLibraries.ts
index db64c2d001b0..2c7acb74db45 100644
--- a/app/client/src/pages/Editor/Explorer/Libraries/recommendedLibraries.ts
+++ b/app/client/src/pages/Editor/Explorer/Libraries/recommendedLibraries.ts
@@ -5,9 +5,19 @@ export default [
author: "auth0",
docsURL: "https://github.com/auth0/node-jsonwebtoken#readme",
version: "8.5.1",
- url: `/libraries/[email protected]`,
+ url: "/libraries/[email protected]",
icon: "https://github.com/auth0.png?s=20",
},
+ {
+ name: "fast-xml-parser",
+ description:
+ "Validate XML, Parse XML to JS Object, or Build XML from JS Object without C/C++ based libraries and no callback.",
+ author: "NaturalIntelligence",
+ docsURL: "https://github.com/NaturalIntelligence/fast-xml-parser",
+ url: "https://cdnjs.cloudflare.com/ajax/libs/fast-xml-parser/4.3.2/fxparser.min.js",
+ version: "4.3.2",
+ icon: "https://img.jsdelivr.com/github.com/NaturalIntelligence.png",
+ },
{
name: "jspdf",
description: "PDF Document creation from JavaScript",
diff --git a/app/client/src/plugins/Linting/types.ts b/app/client/src/plugins/Linting/types.ts
index b3cfa00d0b39..17cb175e4ac8 100644
--- a/app/client/src/plugins/Linting/types.ts
+++ b/app/client/src/plugins/Linting/types.ts
@@ -10,7 +10,7 @@ import type {
} from "workers/Evaluation/evaluate";
import type { DependencyMap } from "utils/DynamicBindingUtils";
import type { TJSPropertiesState } from "workers/Evaluation/JSObject/jsPropertiesState";
-import type { TJSLibrary } from "workers/common/JSLibrary";
+import type { JSLibrary } from "workers/common/JSLibrary";
export enum LINT_WORKER_ACTIONS {
LINT_TREE = "LINT_TREE",
@@ -78,5 +78,5 @@ export interface getLintErrorsFromTreeResponse {
export interface updateJSLibraryProps {
add?: boolean;
- libs: TJSLibrary[];
+ libs: JSLibrary[];
}
diff --git a/app/client/src/reducers/uiReducers/libraryReducer.ts b/app/client/src/reducers/uiReducers/libraryReducer.ts
index a9ade8c1c6b6..5cda44347aee 100644
--- a/app/client/src/reducers/uiReducers/libraryReducer.ts
+++ b/app/client/src/reducers/uiReducers/libraryReducer.ts
@@ -5,7 +5,7 @@ import {
ReduxActionTypes,
} from "@appsmith/constants/ReduxActionConstants";
import recommendedLibraries from "pages/Editor/Explorer/Libraries/recommendedLibraries";
-import type { TJSLibrary } from "workers/common/JSLibrary";
+import type { JSLibrary } from "workers/common/JSLibrary";
import { defaultLibraries } from "workers/common/JSLibrary";
export enum InstallState {
@@ -17,14 +17,14 @@ export enum InstallState {
export interface LibraryState {
installationStatus: Record<string, InstallState>;
- installedLibraries: TJSLibrary[];
+ installedLibraries: JSLibrary[];
isInstallerOpen: boolean;
}
const initialState = {
isInstallerOpen: false,
installationStatus: {},
- installedLibraries: defaultLibraries.map((lib: TJSLibrary) => {
+ installedLibraries: defaultLibraries.map((lib: JSLibrary) => {
return {
name: lib.name,
docsURL: lib.docsURL,
@@ -38,7 +38,7 @@ const initialState = {
const jsLibraryReducer = createImmerReducer(initialState, {
[ReduxActionTypes.INSTALL_LIBRARY_INIT]: (
state: LibraryState,
- action: ReduxAction<Partial<TJSLibrary>>,
+ action: ReduxAction<Partial<JSLibrary>>,
) => {
const { url } = action.payload;
state.installationStatus[url as string] =
@@ -91,7 +91,7 @@ const jsLibraryReducer = createImmerReducer(initialState, {
},
[ReduxActionTypes.FETCH_JS_LIBRARIES_SUCCESS]: (
state: LibraryState,
- action: ReduxAction<TJSLibrary[]>,
+ action: ReduxAction<JSLibrary[]>,
) => {
state.installedLibraries = action.payload.concat(
initialState.installedLibraries,
@@ -99,7 +99,7 @@ const jsLibraryReducer = createImmerReducer(initialState, {
},
[ReduxActionTypes.UNINSTALL_LIBRARY_SUCCESS]: (
state: LibraryState,
- action: ReduxAction<TJSLibrary>,
+ action: ReduxAction<JSLibrary>,
) => {
const uLib = action.payload;
state.installedLibraries = state.installedLibraries.filter(
diff --git a/app/client/src/sagas/JSLibrarySaga.ts b/app/client/src/sagas/JSLibrarySaga.ts
index 17d57a71018c..aa9237418cbe 100644
--- a/app/client/src/sagas/JSLibrarySaga.ts
+++ b/app/client/src/sagas/JSLibrarySaga.ts
@@ -29,7 +29,7 @@ import log from "loglevel";
import { APP_MODE } from "entities/App";
import { getAppMode } from "@appsmith/selectors/applicationSelectors";
import AnalyticsUtil from "utils/AnalyticsUtil";
-import type { TJSLibrary } from "workers/common/JSLibrary";
+import type { JSLibrary } from "workers/common/JSLibrary";
import { getUsedActionNames } from "selectors/actionSelectors";
import AppsmithConsole from "utils/AppsmithConsole";
import { selectInstalledLibraries } from "@appsmith/selectors/entitiesSelector";
@@ -73,7 +73,7 @@ function* handleInstallationFailure(
log.error(message);
}
-export function* installLibrarySaga(lib: Partial<TJSLibrary>) {
+export function* installLibrarySaga(lib: Partial<JSLibrary>) {
const { url } = lib;
const takenNamesMap: Record<string, true> = yield select(
@@ -81,7 +81,7 @@ export function* installLibrarySaga(lib: Partial<TJSLibrary>) {
"",
);
- const installedLibraries: TJSLibrary[] = yield select(
+ const installedLibraries: JSLibrary[] = yield select(
selectInstalledLibraries,
);
@@ -232,7 +232,7 @@ export function* installLibrarySaga(lib: Partial<TJSLibrary>) {
});
}
-function* uninstallLibrarySaga(action: ReduxAction<TJSLibrary>) {
+function* uninstallLibrarySaga(action: ReduxAction<JSLibrary>) {
const { accessor, name } = action.payload;
const applicationId: string = yield select(getCurrentApplicationId);
@@ -320,7 +320,7 @@ function* fetchJSLibraries(action: ReduxAction<string>) {
const isValidResponse: boolean = yield validateResponse(response);
if (!isValidResponse) return;
- const libraries = response.data as Array<TJSLibrary & { defs: string }>;
+ const libraries = response.data as Array<JSLibrary & { defs: string }>;
const { message, success }: { success: boolean; message: string } =
yield call(
@@ -404,7 +404,7 @@ function* startInstallationRequestChannel() {
ReduxActionTypes.INSTALL_LIBRARY_INIT,
]);
while (true) {
- const action: ReduxAction<Partial<TJSLibrary>> =
+ const action: ReduxAction<Partial<JSLibrary>> =
yield take(queueInstallChannel);
yield put({
type: ReduxActionTypes.INSTALL_LIBRARY_START,
diff --git a/app/client/src/sagas/LintingSagas.ts b/app/client/src/sagas/LintingSagas.ts
index ea0c96edbd77..b2a44292ecef 100644
--- a/app/client/src/sagas/LintingSagas.ts
+++ b/app/client/src/sagas/LintingSagas.ts
@@ -4,7 +4,7 @@ import { ReduxActionTypes } from "@appsmith/constants/ReduxActionConstants";
import { APP_MODE } from "entities/App";
import { call, put, select, takeEvery } from "redux-saga/effects";
import { getAppMode } from "@appsmith/selectors/entitiesSelector";
-import type { TJSLibrary } from "workers/common/JSLibrary";
+import type { JSLibrary } from "workers/common/JSLibrary";
import { logLatestLintPropertyErrors } from "./PostLintingSagas";
import { getAppsmithConfigs } from "@appsmith/configs";
import type { AppState } from "@appsmith/reducers";
@@ -29,7 +29,7 @@ const APPSMITH_CONFIGS = getAppsmithConfigs();
export const lintWorker = new Linter();
function* updateLintGlobals(
- action: ReduxAction<{ add?: boolean; libs: TJSLibrary[] }>,
+ action: ReduxAction<{ add?: boolean; libs: JSLibrary[] }>,
) {
const appMode: APP_MODE = yield select(getAppMode);
const isEditorMode = appMode === APP_MODE.EDIT;
diff --git a/app/client/src/selectors/actionSelectors.tsx b/app/client/src/selectors/actionSelectors.tsx
index 47f3d97b49fd..4318ac8fd20c 100644
--- a/app/client/src/selectors/actionSelectors.tsx
+++ b/app/client/src/selectors/actionSelectors.tsx
@@ -2,7 +2,7 @@ import type { DataTree } from "entities/DataTree/dataTreeTypes";
import { createSelector } from "reselect";
import WidgetFactory from "WidgetProvider/factory";
import type { FlattenedWidgetProps } from "WidgetProvider/constants";
-import type { TJSLibrary } from "workers/common/JSLibrary";
+import type { JSLibrary } from "workers/common/JSLibrary";
import { getDataTree } from "./dataTreeSelectors";
import {
getExistingPageNames,
@@ -28,7 +28,7 @@ export const getUsedActionNames = createSelector(
pageNames: Record<string, any>,
dataTree: DataTree,
parentWidget: FlattenedWidgetProps | undefined,
- installedLibraries: TJSLibrary[],
+ installedLibraries: JSLibrary[],
) => {
const map: Record<string, boolean> = {};
// The logic has been copied from Explorer/Entity/Name.tsx Component.
diff --git a/app/client/src/workers/Evaluation/handlers/__tests__/jsLibrary.test.ts b/app/client/src/workers/Evaluation/handlers/__tests__/jsLibrary.test.ts
index 8ee15ccfb7d1..7f193a721543 100644
--- a/app/client/src/workers/Evaluation/handlers/__tests__/jsLibrary.test.ts
+++ b/app/client/src/workers/Evaluation/handlers/__tests__/jsLibrary.test.ts
@@ -7,14 +7,14 @@ import * as mod from "../../../common/JSLibrary/ternDefinitionGenerator";
jest.mock("../../../common/JSLibrary/ternDefinitionGenerator");
+declare const self: WorkerGlobalScope;
+
describe("Tests to assert install/uninstall flows", function () {
beforeAll(() => {
self.importScripts = jest.fn(() => {
- //@ts-expect-error importScripts is not defined in the test environment
self.lodash = {};
});
- //@ts-expect-error importScripts is not defined in the test environment
self.import = jest.fn();
const mockTernDefsGenerator = jest.fn(() => ({}));
@@ -49,7 +49,7 @@ describe("Tests to assert install/uninstall flows", function () {
});
});
- it("Reinstalling a different version of the same installed library should fail", async function () {
+ it("Reinstalling a different version of the same installed library should create a new accessor", async function () {
const res = await installLibrary({
data: {
url: "https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.16.0/lodash.min.js",
@@ -59,39 +59,43 @@ describe("Tests to assert install/uninstall flows", function () {
method: EVAL_WORKER_ASYNC_ACTION.INSTALL_LIBRARY,
});
expect(res).toEqual({
- success: false,
- defs: {},
- error: expect.any(Error),
+ success: true,
+ defs: {
+ "!name": "LIB/lodash_1",
+ lodash_1: undefined,
+ },
+ accessor: ["lodash_1"],
});
});
- it("Detects name space collision where there is another entity(api, widget or query) with the same name", async function () {
- //@ts-expect-error ignore
- delete self.lodash;
+ it("Detects name space collision where there is another entity(api, widget or query) with the same name and creates a unique accessor", async function () {
+ delete self["lodash"];
const res = await installLibrary({
data: {
url: "https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.16.0/lodash.min.js",
- takenAccessors: [],
+ takenAccessors: ["lodash_1"],
takenNamesMap: { lodash: true },
},
method: EVAL_WORKER_ASYNC_ACTION.INSTALL_LIBRARY,
});
expect(res).toEqual({
- success: false,
- defs: {},
- error: expect.any(Error),
+ success: true,
+ defs: {
+ "!name": "LIB/lodash_2",
+ lodash_2: undefined,
+ },
+ accessor: ["lodash_2"],
});
+ delete self["lodash_2"];
});
- it("Removes or set the accessors to undefined on the global object on uninstallation", async function () {
- //@ts-expect-error ignore
+ it("Removes or set the accessors to undefined on the global object on un-installation", async function () {
self.lodash = {};
const res = await uninstallLibrary({
data: ["lodash"],
method: EVAL_WORKER_SYNC_ACTION.UNINSTALL_LIBRARY,
});
expect(res).toEqual({ success: true });
- //@ts-expect-error ignore
expect(self.lodash).toBeUndefined();
});
});
diff --git a/app/client/src/workers/Evaluation/handlers/jsLibrary.ts b/app/client/src/workers/Evaluation/handlers/jsLibrary.ts
index f45992d91896..9e20f4ceea6d 100644
--- a/app/client/src/workers/Evaluation/handlers/jsLibrary.ts
+++ b/app/client/src/workers/Evaluation/handlers/jsLibrary.ts
@@ -9,10 +9,20 @@ import {
JSLibraries,
libraryReservedIdentifiers,
} from "../../common/JSLibrary";
+import type { JSLibrary } from "../../common/JSLibrary";
import { resetJSLibraries } from "../../common/JSLibrary/resetJSLibraries";
import { makeTernDefs } from "../../common/JSLibrary/ternDefinitionGenerator";
import type { EvalWorkerASyncRequest, EvalWorkerSyncRequest } from "../types";
import { dataTreeEvaluator } from "./evalTree";
+import log from "loglevel";
+
+declare global {
+ interface WorkerGlobalScope {
+ [x: string]: any;
+ }
+}
+
+declare const self: WorkerGlobalScope;
enum LibraryInstallError {
NameCollisionError,
@@ -21,16 +31,6 @@ enum LibraryInstallError {
LibraryOverrideError,
}
-class NameCollisionError extends Error {
- code = LibraryInstallError.NameCollisionError;
- constructor(accessors: string) {
- super(
- createMessage(customJSLibraryMessages.NAME_COLLISION_ERROR, accessors),
- );
- this.name = "NameCollisionError";
- }
-}
-
class ImportError extends Error {
code = LibraryInstallError.ImportError;
constructor(url: string) {
@@ -47,25 +47,13 @@ class TernDefinitionError extends Error {
}
}
-class LibraryOverrideError extends Error {
- code = LibraryInstallError.LibraryOverrideError;
- data: any;
- constructor(name: string, data: any) {
- super(createMessage(customJSLibraryMessages.LIB_OVERRIDE_ERROR, name));
- this.name = "LibraryOverrideError";
- this.data = data;
- }
-}
-
const removeDataTreeFromContext = () => {
if (!dataTreeEvaluator) return {};
const evalTree = dataTreeEvaluator?.getEvalTree();
const dataTreeEntityNames = Object.keys(evalTree);
const tempDataTreeStore: Record<string, any> = {};
for (const entityName of dataTreeEntityNames) {
- // @ts-expect-error: self is a global variable
tempDataTreeStore[entityName] = self[entityName];
- // @ts-expect-error: self is a global variable
delete self[entityName];
}
return tempDataTreeStore;
@@ -76,12 +64,17 @@ function addTempStoredDataTreeToContext(
) {
const dataTreeEntityNames = Object.keys(tempDataTreeStore);
for (const entityName of dataTreeEntityNames) {
- // @ts-expect-error: self is a global variable
self[entityName] = tempDataTreeStore[entityName];
}
}
-export async function installLibrary(request: EvalWorkerASyncRequest) {
+export async function installLibrary(
+ request: EvalWorkerASyncRequest<{
+ url: string;
+ takenNamesMap: Record<string, true>;
+ takenAccessors: Array<string>;
+ }>,
+) {
const { data } = request;
const { takenAccessors, takenNamesMap, url } = data;
const defs: Def = {};
@@ -91,73 +84,105 @@ export async function installLibrary(request: EvalWorkerASyncRequest) {
* We store the data tree in a temporary variable and add it back to the global scope after the library is imported.
*/
const tempDataTreeStore = removeDataTreeFromContext();
+
+ // Map of all the currently installed libraries
+ const libStore = takenAccessors.reduce(
+ (acc: Record<string, unknown>, a: string) => {
+ acc[a] = self[a];
+ return acc;
+ },
+ {},
+ );
+
try {
- const currentEnvKeys = Object.keys(self);
+ const envKeysBeforeInstallation = Object.keys(self);
- //@ts-expect-error Find libraries that were uninstalled.
- const unsetKeys = currentEnvKeys.filter((key) => self[key] === undefined);
+ /** Holds keys of uninstalled libraries that cannot be removed from worker global.
+ * Certain libraries are added to the global scope with { configurable: false }
+ */
+ const unsetLibraryKeys = envKeysBeforeInstallation.filter(
+ (k) => self[k] === undefined,
+ );
+
+ const accessors: string[] = [];
- const existingLibraries: Record<string, any> = {};
- for (const acc of takenAccessors) {
- existingLibraries[acc] = self[acc];
- }
let module = null;
try {
self.importScripts(url);
+ // Find keys add that were installed to the global scope.
+ const keysAfterInstallation = Object.keys(self);
+ accessors.push(
+ ...difference(keysAfterInstallation, envKeysBeforeInstallation),
+ );
+
+ // Check the list of installed library to see if their values have changed.
+ // This is to check if the newly installed library overwrites an already existing
+ accessors.push(
+ ...Object.keys(libStore).filter((k) => {
+ return libStore[k] !== self[k];
+ }),
+ );
+
+ accessors.push(...unsetLibraryKeys.filter((k) => self[k] !== undefined));
+
+ for (let i = 0; i < accessors.length; i++) {
+ if (
+ takenNamesMap.hasOwnProperty(accessors[i]) ||
+ takenAccessors.includes(accessors[i])
+ ) {
+ const uniqueName = generateUniqueAccessor(
+ accessors[i],
+ takenAccessors,
+ takenNamesMap,
+ );
+ self[uniqueName] = self[accessors[i]];
+ accessors[i] = uniqueName;
+ }
+ }
} catch (e) {
+ log.debug(e, `importScripts failed for ${url}`);
try {
module = await import(/* webpackIgnore: true */ url);
+ if (module && typeof module === "object") {
+ const uniqAccessor = generateUniqueAccessor(
+ url,
+ takenAccessors,
+ takenNamesMap,
+ );
+ self[uniqAccessor] = flattenModule(module);
+ accessors.push(uniqAccessor);
+ }
} catch (e) {
+ log.debug(e, `dynamic import failed for ${url}`);
throw new ImportError(url);
}
}
- // Find keys add that were installed to the global scope.
- const accessors = difference(
- Object.keys(self),
- currentEnvKeys,
- ) as Array<string>;
-
- // If no keys were added to the global scope, check if the module is a ESM module.
+ // If no accessors at this point, installation likely failed.
if (accessors.length === 0) {
- if (module && typeof module === "object") {
- const uniqAccessor = generateUniqueAccessor(
- url,
- takenAccessors,
- takenNamesMap,
- );
- // @ts-expect-error no types
- self[uniqAccessor] = flattenModule(module);
- accessors.push(uniqAccessor);
- }
+ throw new Error("Unable to determine a unique accessor");
}
- addTempStoredDataTreeToContext(tempDataTreeStore);
- checkForNameCollision(accessors, takenNamesMap);
- checkIfUninstalledEarlier(accessors, unsetKeys);
- checkForOverrides(url, accessors, takenAccessors, existingLibraries);
- if (accessors.length === 0)
- return { status: false, defs, accessor: accessors };
-
- //Reserves accessor names.
const name = accessors[accessors.length - 1];
defs["!name"] = `LIB/${name}`;
try {
for (const key of accessors) {
- //@ts-expect-error no types
defs[key] = makeTernDefs(self[key]);
}
} catch (e) {
for (const acc of accessors) {
- //@ts-expect-error no types
self[acc] = undefined;
}
+ log.debug(e, `ternDefinitions failed for ${url}`);
throw new TernDefinitionError(
`Failed to generate autocomplete definitions: ${name}`,
);
}
+ // All the existing library and the newly installed one is added to global.
+ Object.keys(libStore).forEach((k) => (self[k] = libStore[k]));
+
//Reserve accessor names.
for (const acc of accessors) {
//we have to update invalidEntityIdentifiers as well
@@ -167,21 +192,20 @@ export async function installLibrary(request: EvalWorkerASyncRequest) {
return { success: true, defs, accessor: accessors };
} catch (error) {
+ addTempStoredDataTreeToContext(tempDataTreeStore);
+ takenAccessors.forEach((k) => (self[k] = libStore[k]));
return { success: false, defs, error };
}
}
-export function uninstallLibrary(request: EvalWorkerSyncRequest) {
+export function uninstallLibrary(
+ request: EvalWorkerSyncRequest<Array<string>>,
+) {
const { data } = request;
const accessor = data;
try {
for (const key of accessor) {
- try {
- delete self[key];
- } catch (e) {
- //@ts-expect-error ignore
- self[key] = undefined;
- }
+ self[key] = undefined;
//we have to update invalidEntityIdentifiers as well
delete libraryReservedIdentifiers[key];
delete invalidEntityIdentifiers[key];
@@ -192,39 +216,60 @@ export function uninstallLibrary(request: EvalWorkerSyncRequest) {
}
}
-export async function loadLibraries(request: EvalWorkerASyncRequest) {
+export async function loadLibraries(
+ request: EvalWorkerASyncRequest<JSLibrary[]>,
+) {
resetJSLibraries();
- //Add types
const { data: libs } = request;
let message = "";
+ const libStore: Record<string, unknown> = {};
try {
for (const lib of libs) {
- const url = lib.url;
- const accessor = lib.accessor;
+ const url = lib.url as string;
+ const accessors = lib.accessor;
const keysBefore = Object.keys(self);
let module = null;
try {
self.importScripts(url);
+ const keysAfter = Object.keys(self);
+ const defaultAccessors = difference(keysAfter, keysBefore);
+
+ /**
+ * Installing 2 different version of lodash tries to add the same accessor on the self object. Let take version a & b for example.
+ * Installation of version a, will add _ to the self object and can be detected by looking at the differences in the previous step.
+ * Now when version b is installed, differences will be [], since _ already exists in the self object.
+ * We add all the installations to the libStore and see if the reference it points to in the self object changes.
+ * If the references changes it means that it a valid accessor.
+ */
+ defaultAccessors.push(
+ ...Object.keys(libStore).filter((k) => libStore[k] !== self[k]),
+ );
+
+ /** Sort the accessor list from backend and installed accessor list using the same rule to apply all modifications.
+ * This is required only for UMD builds, since we always generate unique names for ESM.
+ */
+ accessors.sort();
+ defaultAccessors.sort();
+
+ for (let i = 0; i < defaultAccessors.length; i++) {
+ self[accessors[i]] = self[defaultAccessors[i]];
+ libStore[defaultAccessors[i]] = self[defaultAccessors[i]];
+ libraryReservedIdentifiers[accessors[i]] = true;
+ invalidEntityIdentifiers[accessors[i]] = true;
+ }
} catch (e) {
- message = (e as Error).message;
try {
module = await import(/* webpackIgnore: true */ url);
+ if (!module || typeof module !== "object") throw "Not an ESM module";
+ const key = accessors[0];
+ libStore[key] = module;
+ libraryReservedIdentifiers[key] = true;
+ invalidEntityIdentifiers[key] = true;
} catch (e) {
- message = (e as Error).message;
+ throw new ImportError(url);
}
}
- const keysAfter = Object.keys(self);
- const newKeys = difference(keysAfter, keysBefore);
- if (newKeys.length === 0 && module && typeof module === "object") {
- self[accessor[0]] = flattenModule(module);
- newKeys.push(accessor[0]);
- }
- for (const key of newKeys) {
- //we have to update invalidEntityIdentifiers as well
- libraryReservedIdentifiers[key] = true;
- invalidEntityIdentifiers[key] = true;
- }
}
JSLibraries.push(...libs);
return { success: true, message };
@@ -234,48 +279,6 @@ export async function loadLibraries(request: EvalWorkerASyncRequest) {
}
}
-function checkForNameCollision(
- accessor: string[],
- takenNamesMap: Record<string, any>,
-) {
- const collidingNames = accessor.filter((key: string) => takenNamesMap[key]);
- if (collidingNames.length) {
- for (const acc of accessor) {
- //@ts-expect-error no types
- self[acc] = undefined;
- }
- throw new NameCollisionError(collidingNames.join(", "));
- }
-}
-
-function checkIfUninstalledEarlier(accessor: string[], unsetKeys: string[]) {
- if (accessor.length > 0) return;
- for (const key of unsetKeys) {
- //@ts-expect-error no types
- if (!self[key]) continue;
- accessor.push(key);
- }
-}
-
-function checkForOverrides(
- url: string,
- accessor: string[],
- takenAccessors: string[],
- existingLibraries: Record<string, any>,
-) {
- if (accessor.length > 0) return;
- const overriddenAccessors: Array<string> = [];
- for (const acc of takenAccessors) {
- //@ts-expect-error no types
- if (existingLibraries[acc] === self[acc]) continue;
- //@ts-expect-error no types
- self[acc] = existingLibraries[acc];
- overriddenAccessors.push(acc);
- }
- if (overriddenAccessors.length === 0) return;
- throw new LibraryOverrideError(url, overriddenAccessors);
-}
-
/**
* This function is called only for ESM modules and generates a unique namespace for the module.
* @param url
@@ -284,22 +287,24 @@ function checkForOverrides(
* @returns
*/
function generateUniqueAccessor(
- url: string,
+ urlOrName: string,
takenAccessors: Array<string>,
takenNamesMap: Record<string, true>,
) {
+ let name = urlOrName;
// extract file name from url
- const urlObject = new URL(url);
- // URL pattern for ESM modules from jsDelivr - https://cdn.jsdelivr.net/npm/[email protected]/+esm
- // Assuming the file name is the last part of the path
- const urlPathParts = urlObject.pathname.split("/");
- let fileName = urlPathParts.pop();
- fileName = fileName?.includes("esm") ? urlPathParts.pop() : fileName;
+ try {
+ // Checks to see if a URL was passed
+ const urlObject = new URL(urlOrName);
+ // URL pattern for ESM modules from jsDelivr - https://cdn.jsdelivr.net/npm/[email protected]/+esm
+ // Assuming the file name is the last part of the path
+ const urlPathParts = urlObject.pathname.split("/");
+ name = urlPathParts.pop() as string;
+ name = name?.includes("+esm") ? (urlPathParts.pop() as string) : name;
+ } catch (e) {}
- // This should never happen. This is just to avoid the typescript error.
- if (!fileName) throw new Error("Unable to generate a unique accessor");
// Replace all non-alphabetic characters with underscores and remove trailing underscores
- const validVar = fileName.replace(/[^a-zA-Z]/g, "_").replace(/_+$/, "");
+ const validVar = name.replace(/[^a-zA-Z]/g, "_").replace(/_+$/, "");
if (
!takenAccessors.includes(validVar) &&
!takenNamesMap.hasOwnProperty(validVar)
@@ -308,7 +313,7 @@ function generateUniqueAccessor(
}
let index = 0;
while (index++ < 100) {
- const name = `Library_${index}`;
+ const name = `${validVar}_${index}`;
if (!takenAccessors.includes(name) && !takenNamesMap.hasOwnProperty(name)) {
return name;
}
diff --git a/app/client/src/workers/Evaluation/types.ts b/app/client/src/workers/Evaluation/types.ts
index ee5f1f7f8231..d416e8735b02 100644
--- a/app/client/src/workers/Evaluation/types.ts
+++ b/app/client/src/workers/Evaluation/types.ts
@@ -19,9 +19,12 @@ import type { WorkerRequest } from "@appsmith/workers/common/types";
import type { DataTreeDiff } from "@appsmith/workers/Evaluation/evaluationUtils";
import type { APP_MODE } from "entities/App";
-export type EvalWorkerSyncRequest = WorkerRequest<any, EVAL_WORKER_SYNC_ACTION>;
-export type EvalWorkerASyncRequest = WorkerRequest<
- any,
+export type EvalWorkerSyncRequest<T = any> = WorkerRequest<
+ T,
+ EVAL_WORKER_SYNC_ACTION
+>;
+export type EvalWorkerASyncRequest<T = any> = WorkerRequest<
+ T,
EVAL_WORKER_ASYNC_ACTION
>;
export type EvalWorkerResponse = EvalTreeResponseData | boolean | unknown;
diff --git a/app/client/src/workers/Tern/tern.worker.ts b/app/client/src/workers/Tern/tern.worker.ts
index 7c3d77c923b1..97b3f2bcc496 100644
--- a/app/client/src/workers/Tern/tern.worker.ts
+++ b/app/client/src/workers/Tern/tern.worker.ts
@@ -6,7 +6,6 @@ import ecma from "constants/defs/ecmascript.json";
import lodash from "constants/defs/lodash.json";
import base64 from "constants/defs/base64-js.json";
import moment from "constants/defs/moment.json";
-import xmlJs from "constants/defs/xmlParser.json";
import forge from "constants/defs/forge.json";
import browser from "constants/defs/browser.json";
import {
@@ -64,7 +63,6 @@ function startServer(plugins = {}, scripts?: string[]) {
lodash,
base64,
moment,
- xmlJs,
forge,
] as Def[],
plugins: plugins,
diff --git a/app/client/src/workers/common/JSLibrary/index.ts b/app/client/src/workers/common/JSLibrary/index.ts
index 05d772d52e2a..9f23b48d7176 100644
--- a/app/client/src/workers/common/JSLibrary/index.ts
+++ b/app/client/src/workers/common/JSLibrary/index.ts
@@ -1,7 +1,7 @@
import lodashPackageJson from "lodash/package.json";
import momentPackageJson from "moment-timezone/package.json";
-export interface TJSLibrary {
+export interface JSLibrary {
version?: string;
docsURL: string;
name: string;
@@ -9,7 +9,7 @@ export interface TJSLibrary {
url?: string;
}
-export const defaultLibraries: TJSLibrary[] = [
+export const defaultLibraries: JSLibrary[] = [
{
accessor: ["_"],
version: lodashPackageJson.version,
@@ -22,12 +22,6 @@ export const defaultLibraries: TJSLibrary[] = [
docsURL: `https://momentjs.com/docs/`,
name: "moment",
},
- {
- accessor: ["xmlParser"],
- version: "3.17.5",
- docsURL: "https://github.com/NaturalIntelligence/fast-xml-parser",
- name: "xmlParser",
- },
{
accessor: ["forge"],
version: "1.3.0",
diff --git a/app/client/src/workers/common/JSLibrary/resetJSLibraries.ts b/app/client/src/workers/common/JSLibrary/resetJSLibraries.ts
index 49e45ca18c99..250c6c6132c7 100644
--- a/app/client/src/workers/common/JSLibrary/resetJSLibraries.ts
+++ b/app/client/src/workers/common/JSLibrary/resetJSLibraries.ts
@@ -1,6 +1,5 @@
import _ from "./lodash-wrapper";
import moment from "moment-timezone";
-import parser from "fast-xml-parser";
import forge from "node-forge";
import { defaultLibraries } from "./index";
import { JSLibraries, libraryReservedIdentifiers } from "./index";
@@ -8,7 +7,6 @@ import { invalidEntityIdentifiers } from "../DependencyMap/utils";
const defaultLibImplementations = {
lodash: _,
moment: moment,
- xmlParser: parser,
// We are removing some functionalities of node-forge because they wont
// work in the worker thread
forge: /*#__PURE*/ _.omit(forge, ["tls", "http", "xhr", "socket", "task"]),
diff --git a/app/client/yarn.lock b/app/client/yarn.lock
index 6706b5b8aea2..dcb96e034d37 100644
--- a/app/client/yarn.lock
+++ b/app/client/yarn.lock
@@ -10511,7 +10511,6 @@ __metadata:
factory.ts: ^0.5.1
fast-deep-equal: ^3.1.3
fast-sort: ^3.4.0
- fast-xml-parser: ^3.17.5
fastdom: ^1.0.11
focus-trap-react: ^8.9.2
fuse.js: ^3.4.5
@@ -16679,15 +16678,6 @@ __metadata:
languageName: node
linkType: hard
-"fast-xml-parser@npm:^3.17.5":
- version: 3.17.5
- resolution: "fast-xml-parser@npm:3.17.5"
- bin:
- xml2js: cli.js
- checksum: 6c436f540a4dcab67d395c0f6e8dc70090e6ced2ff73ed5fec181c1b25df755ed9fd9ba8271d6f70096fbe3add8b4eac130a5f4daeb12970427f72403a56934e
- languageName: node
- linkType: hard
-
"fastdom@npm:^1.0.11":
version: 1.0.11
resolution: "fastdom@npm:1.0.11"
diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/constants/ApplicationConstants.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/constants/ApplicationConstants.java
index 0a7b2d2a0aed..e79e33547aa1 100644
--- a/app/server/appsmith-server/src/main/java/com/appsmith/server/constants/ApplicationConstants.java
+++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/constants/ApplicationConstants.java
@@ -1,8 +1,34 @@
package com.appsmith.server.constants;
+import com.appsmith.server.domains.CustomJSLib;
+
+import java.util.Set;
+
public class ApplicationConstants {
public static final String[] APP_CARD_COLORS = {
"#FFDEDE", "#FFEFDB", "#F3F1C7", "#F4FFDE", "#C7F3F0", "#D9E7FF", "#E3DEFF", "#F1DEFF", "#C7F3E3", "#F5D1D1",
"#ECECEC", "#FBF4ED", "#D6D1F2", "#FFEBFB", "#EAEDFB"
};
+
+ public static CustomJSLib getDefaultParserCustomJsLibCompatibilityDTO() {
+ CustomJSLib customJSLib = new CustomJSLib();
+ customJSLib.setName("xmlParser");
+ customJSLib.setVersion("3.17.5");
+ customJSLib.setAccessor(Set.of("xmlParser"));
+ customJSLib.setUrl("https://cdnjs.cloudflare.com/ajax/libs/fast-xml-parser/3.17.5/parser.min.js");
+ customJSLib.setDefs(
+ "{\"!name\":\"LIB/xmlParser\",\"xmlParser\":{\"parse\":{\"!type\":\"fn()\",\"prototype\":{}},\"convertTonimn\":{\"!type\":\"fn()\",\"prototype\":{}},\"getTraversalObj\":{\"!type\":\"fn()\",\"prototype\":{}},\"convertToJson\":{\"!type\":\"fn()\",\"prototype\":{}},\"convertToJsonString\":{\"!type\":\"fn()\",\"prototype\":{}},\"validate\":{\"!type\":\"fn()\",\"prototype\":{}},\"j2xParser\":{\"!type\":\"fn()\",\"prototype\":{\"parse\":{\"!type\":\"fn()\",\"prototype\":{}},\"j2x\":{\"!type\":\"fn()\",\"prototype\":{}}}},\"parseToNimn\":{\"!type\":\"fn()\",\"prototype\":{}}}}");
+ customJSLib.setUidString(XML_PARSER_LIBRARY_UID);
+ return customJSLib;
+ }
+
+ /**
+ * Appsmith provides xmlParser v 3.17.5 and few other customJSLibraries by default, xmlParser has been
+ * flagged because it has some vulnerabilities. Appsmith is stopping natively providing support for xmlParser.
+ * This however, would break existing applications which are using xmlParser. In order to prevent this,
+ * we are adding xmlParser as an add-onn to all existing applications and applications which will be imported
+ * This CustomJSLib UID needs to be added to all the imported applications where we don't have any later versions of xmlParser present.
+ */
+ public static final String XML_PARSER_LIBRARY_UID =
+ "xmlParser_https://cdnjs.cloudflare.com/ajax/libs/fast-xml-parser/3.17.5/parser.min.js";
}
diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/imports/internal/ImportApplicationServiceCEImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/imports/internal/ImportApplicationServiceCEImpl.java
index 0f45d9f0b4ee..1de6ffcb7b2e 100644
--- a/app/server/appsmith-server/src/main/java/com/appsmith/server/imports/internal/ImportApplicationServiceCEImpl.java
+++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/imports/internal/ImportApplicationServiceCEImpl.java
@@ -16,6 +16,7 @@
import com.appsmith.external.models.OAuth2;
import com.appsmith.external.models.Policy;
import com.appsmith.server.actioncollections.base.ActionCollectionService;
+import com.appsmith.server.constants.ApplicationConstants;
import com.appsmith.server.constants.FieldName;
import com.appsmith.server.constants.ResourceModes;
import com.appsmith.server.datasources.base.DatasourceService;
@@ -1135,6 +1136,8 @@ private Mono<List<CustomJSLibApplicationDTO>> getCustomJslibImportMono(List<Cust
customJSLibs = new ArrayList<>();
}
+ ensureXmlParserPresenceInCustomJsLibList(customJSLibs);
+
return Flux.fromIterable(customJSLibs)
.flatMap(customJSLib -> {
customJSLib.setId(null);
@@ -1154,6 +1157,32 @@ private Mono<List<CustomJSLibApplicationDTO>> getCustomJslibImportMono(List<Cust
});
}
+ /**
+ * This method takes customJSLibList from application JSON, checks if an entry for XML parser exists,
+ * otherwise adds the entry.
+ * This has been done to add the xmlParser entry in imported application as appsmith is stopping native support
+ * for xml parser.
+ * Read More: https://github.com/appsmithorg/appsmith/pull/28012
+ *
+ * @param customJSLibList
+ */
+ public void ensureXmlParserPresenceInCustomJsLibList(List<CustomJSLib> customJSLibList) {
+ boolean isXmlParserLibFound = false;
+ for (CustomJSLib customJSLib : customJSLibList) {
+ if (!customJSLib.getUidString().equals(ApplicationConstants.XML_PARSER_LIBRARY_UID)) {
+ continue;
+ }
+
+ isXmlParserLibFound = true;
+ break;
+ }
+
+ if (!isXmlParserLibFound) {
+ CustomJSLib xmlParserJsLib = ApplicationConstants.getDefaultParserCustomJsLibCompatibilityDTO();
+ customJSLibList.add(xmlParserJsLib);
+ }
+ }
+
private Mono<List<Datasource>> getExistingDatasourceMono(String applicationId, Flux<Datasource> datasourceFlux) {
Mono<List<Datasource>> existingDatasourceMono;
// Check if the request is to hydrate the application to DB for particular branch
diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/migrations/MigrationHelperMethods.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/migrations/MigrationHelperMethods.java
index 6b14b9b64d90..a361eb3965d2 100644
--- a/app/server/appsmith-server/src/main/java/com/appsmith/server/migrations/MigrationHelperMethods.java
+++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/migrations/MigrationHelperMethods.java
@@ -3,6 +3,7 @@
import com.appsmith.external.models.ActionDTO;
import com.appsmith.external.models.BaseDomain;
import com.appsmith.external.models.InvisibleActionFields;
+import com.appsmith.server.constants.FieldName;
import com.appsmith.server.constants.ResourceModes;
import com.appsmith.server.domains.ApplicationPage;
import com.appsmith.server.domains.NewAction;
@@ -236,4 +237,23 @@ public static <T extends BaseDomain> List<T> fetchAllDomainObjectsUsingId(
mongoTemplate.find(query(where(fieldName(path)).is(id)), type);
return domainObject;
}
+
+ /**
+ * The method provides the criteria for any document to qualify as not deleted
+ * @return Criteria
+ */
+ public static Criteria notDeleted() {
+ return new Criteria()
+ .andOperator(
+ // Older check for deleted
+ new Criteria()
+ .orOperator(
+ where(FieldName.DELETED).exists(false),
+ where(FieldName.DELETED).is(false)),
+ // New check for deleted
+ new Criteria()
+ .orOperator(
+ where(FieldName.DELETED_AT).exists(false),
+ where(FieldName.DELETED_AT).is(null)));
+ }
}
diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/migrations/db/ce/Migration032AddingXmlParserToApplicationLibraries.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/migrations/db/ce/Migration032AddingXmlParserToApplicationLibraries.java
new file mode 100644
index 000000000000..4cccb969ac2c
--- /dev/null
+++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/migrations/db/ce/Migration032AddingXmlParserToApplicationLibraries.java
@@ -0,0 +1,90 @@
+package com.appsmith.server.migrations.db.ce;
+
+import com.appsmith.server.constants.ApplicationConstants;
+import com.appsmith.server.domains.Application;
+import com.appsmith.server.domains.CustomJSLib;
+import com.appsmith.server.domains.QApplication;
+import com.appsmith.server.dtos.CustomJSLibApplicationDTO;
+import com.appsmith.server.exceptions.AppsmithError;
+import com.appsmith.server.exceptions.AppsmithException;
+import io.mongock.api.annotations.ChangeUnit;
+import io.mongock.api.annotations.Execution;
+import io.mongock.api.annotations.RollbackExecution;
+import lombok.extern.slf4j.Slf4j;
+import org.springframework.dao.DuplicateKeyException;
+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 static com.appsmith.server.constants.ApplicationConstants.XML_PARSER_LIBRARY_UID;
+import static com.appsmith.server.migrations.MigrationHelperMethods.notDeleted;
+import static com.appsmith.server.repositories.ce.BaseAppsmithRepositoryCEImpl.fieldName;
+
+/**
+ * Appsmith provides xmlParser v 3.17.5 and few other customJSLibraries by default, xmlParser has been
+ * flagged because it has some vulnerabilities. Appsmith is stopping natively providing support for xmlParser.
+ * This however, would break existing applications which are using xmlParser. In order to prevent this,
+ * applications require to have xmlParser as added library.
+ *
+ * This migration takes care of adding a document in customJsLib for xml-parser and adding corresponding entry
+ * in application collection
+ *
+ */
+@Slf4j
+@ChangeUnit(order = "032", id = "add-xml-parser-to-application-jslibs", author = " ")
+public class Migration032AddingXmlParserToApplicationLibraries {
+
+ private final MongoTemplate mongoTemplate;
+ private static final String UNPUBLISHED_CUSTOM_JS_LIBS =
+ fieldName(QApplication.application.unpublishedCustomJSLibs);
+ private static final String PUBLISHED_CUSTOM_JS_LIBS = fieldName(QApplication.application.publishedCustomJSLibs);
+
+ public Migration032AddingXmlParserToApplicationLibraries(MongoTemplate mongoTemplate) {
+ this.mongoTemplate = mongoTemplate;
+ }
+
+ @RollbackExecution
+ public void rollbackExecution() {}
+
+ @Execution
+ public void addXmlParserEntryToEachApplication() {
+ // add the xml-parser to customJSLib if it's not already present
+ CustomJSLib customJSLib = generateXmlParserJSLibObject();
+ try {
+ mongoTemplate.save(customJSLib);
+ } catch (DuplicateKeyException duplicateKeyException) {
+ log.debug(
+ "Addition of xmlParser object in customJSLib failed, because object with similar UID already exists");
+ } catch (Exception exception) {
+ throw new AppsmithException(
+ AppsmithError.MIGRATION_FAILED,
+ "Migration032AddingXmlParserToApplicationLibraries",
+ exception.getMessage(),
+ "Unable to insert xml parser library in CustomJSLib collection");
+ }
+
+ // add uid entry in all these custom js libs
+ Update pushXmlParserUpdate = new Update()
+ .addToSet(PUBLISHED_CUSTOM_JS_LIBS, getXmlParserCustomJSLibApplicationDTO())
+ .addToSet(UNPUBLISHED_CUSTOM_JS_LIBS, getXmlParserCustomJSLibApplicationDTO());
+
+ log.debug("Going to add Xml Parser uid in all application DTOs");
+ mongoTemplate.updateMulti(
+ new Query().addCriteria(getMigrationCriteria()), pushXmlParserUpdate, Application.class);
+ }
+
+ private CustomJSLibApplicationDTO getXmlParserCustomJSLibApplicationDTO() {
+ CustomJSLibApplicationDTO xmlParserApplicationDTO = new CustomJSLibApplicationDTO();
+ xmlParserApplicationDTO.setUidString(XML_PARSER_LIBRARY_UID);
+ return xmlParserApplicationDTO;
+ }
+
+ private static CustomJSLib generateXmlParserJSLibObject() {
+ return ApplicationConstants.getDefaultParserCustomJsLibCompatibilityDTO();
+ }
+
+ private static Criteria getMigrationCriteria() {
+ return notDeleted();
+ }
+}
diff --git a/app/server/appsmith-server/src/test/java/com/appsmith/server/solutions/ImportApplicationServiceTests.java b/app/server/appsmith-server/src/test/java/com/appsmith/server/solutions/ImportApplicationServiceTests.java
index 56cc8fe2e98f..e799141df377 100644
--- a/app/server/appsmith-server/src/test/java/com/appsmith/server/solutions/ImportApplicationServiceTests.java
+++ b/app/server/appsmith-server/src/test/java/com/appsmith/server/solutions/ImportApplicationServiceTests.java
@@ -968,7 +968,10 @@ public void importApplicationFromValidJsonFileTest() {
final List<ActionCollection> actionCollectionList = tuple.getT5();
final List<CustomJSLib> importedJSLibList = tuple.getT6();
- assertEquals(1, importedJSLibList.size());
+ // although the imported list had only one jsLib entry, the other entry comes from ensuring an xml
+ // parser entry
+ // for backward compatibility
+ assertEquals(2, importedJSLibList.size());
CustomJSLib importedJSLib = (CustomJSLib) importedJSLibList.toArray()[0];
CustomJSLib expectedJSLib = new CustomJSLib(
"TestLib", Set.of("accessor1"), "url", "docsUrl", "1" + ".0", "defs_string");
@@ -978,10 +981,10 @@ public void importApplicationFromValidJsonFileTest() {
assertEquals(expectedJSLib.getDocsUrl(), importedJSLib.getDocsUrl());
assertEquals(expectedJSLib.getVersion(), importedJSLib.getVersion());
assertEquals(expectedJSLib.getDefs(), importedJSLib.getDefs());
- assertEquals(1, application.getUnpublishedCustomJSLibs().size());
- assertEquals(
- getDTOFromCustomJSLib(expectedJSLib),
- application.getUnpublishedCustomJSLibs().toArray()[0]);
+ // although the imported list had only one jsLib entry, the other entry comes from ensuring an xml
+ // parser entry
+ // for backward compatibility
+ assertEquals(2, application.getUnpublishedCustomJSLibs().size());
assertThat(application.getName()).isEqualTo("valid_application");
assertThat(application.getWorkspaceId()).isNotNull();
|
fbfdfc060f22d9253876da45c11ea4cef9ee5fb2
|
2024-01-04 14:32:40
|
sneha122
|
fix: Auth API send refresh token issue fixed (#30012)
| false
|
Auth API send refresh token issue fixed (#30012)
|
fix
|
diff --git a/app/client/src/pages/Editor/DataSourceEditor/RestAPIDatasourceForm.tsx b/app/client/src/pages/Editor/DataSourceEditor/RestAPIDatasourceForm.tsx
index 03f197237f09..30cea60ff978 100644
--- a/app/client/src/pages/Editor/DataSourceEditor/RestAPIDatasourceForm.tsx
+++ b/app/client/src/pages/Editor/DataSourceEditor/RestAPIDatasourceForm.tsx
@@ -595,7 +595,7 @@ class DatasourceRestAPIEditor extends React.Component<Props> {
"",
false,
"",
- true,
+ !!_.get(formData.authentication, "isTokenHeader"),
)}
</FormInputContainer>
{_.get(formData.authentication, "isTokenHeader") && (
@@ -679,7 +679,7 @@ class DatasourceRestAPIEditor extends React.Component<Props> {
"",
false,
"",
- false,
+ !!_.get(formData.authentication, "isAuthorizationHeader"),
)}
</FormInputContainer>
</>
@@ -721,7 +721,7 @@ class DatasourceRestAPIEditor extends React.Component<Props> {
"",
false,
"",
- false,
+ !!_.get(authentication, "sendScopeWithRefreshToken"),
)}
</FormInputContainer>
)}
|
1529225aefada6d9d963a1c78c7fbc99d59820b0
|
2024-11-20 10:33:01
|
Shrikant Sharat Kandula
|
chore: Rename app-viewers to widgets-blocks (#37553)
| false
|
Rename app-viewers to widgets-blocks (#37553)
|
chore
|
diff --git a/CODEOWNERS b/CODEOWNERS
index 6f6f143cc2f3..a617c2070c11 100644
--- a/CODEOWNERS
+++ b/CODEOWNERS
@@ -27,12 +27,12 @@ app/client/src/widgets/wds/* @appsmithorg/wds-team @appsmithorg/anvil-team
app/client/src/layoutSystems/anvil/* @appsmithorg/anvil-team
# App viewers pod
-app/client/src/widgets/* @appsmithorg/app-viewers
-app/client/src/components/propertyControls/* @appsmithorg/app-viewers
-app/client/src/sagas/OneClickBindingSaga.ts @appsmithorg/app-viewers
-app/client/src/WidgetQueryGenerators/* @appsmithorg/app-viewers
-app/client/src/components/editorComponents/WidgetQueryGeneratorForm/* @appsmithorg/app-viewers
-app/client/src/pages/AppViewer/* @appsmithorg/app-viewers
+app/client/src/widgets/* @appsmithorg/widgets-blocks
+app/client/src/components/propertyControls/* @appsmithorg/widgets-blocks
+app/client/src/sagas/OneClickBindingSaga.ts @appsmithorg/widgets-blocks
+app/client/src/WidgetQueryGenerators/* @appsmithorg/widgets-blocks
+app/client/src/components/editorComponents/WidgetQueryGeneratorForm/* @appsmithorg/widgets-blocks
+app/client/src/pages/AppViewer/* @appsmithorg/widgets-blocks
# New Developers Pod
app/server/appsmith-server/src/main/java/com/appsmith/server/featureflags/* @nilanshbansal
|
6c19af7c2433f092408d096af477fa9101908863
|
2020-12-02 16:14:56
|
vicky-primathon
|
fix: Columns flicker when columns are resized or reordered (#1940)
| false
|
Columns flicker when columns are resized or reordered (#1940)
|
fix
|
diff --git a/app/client/src/components/designSystems/appsmith/ReactTableComponent.tsx b/app/client/src/components/designSystems/appsmith/ReactTableComponent.tsx
index 8e854b45a409..af5a35e2e7b9 100644
--- a/app/client/src/components/designSystems/appsmith/ReactTableComponent.tsx
+++ b/app/client/src/components/designSystems/appsmith/ReactTableComponent.tsx
@@ -12,6 +12,7 @@ import {
ReactTableFilter,
} from "widgets/TableWidget";
import { EventType } from "constants/ActionConstants";
+import produce from "immer";
export interface ColumnMenuOptionProps {
content: string | JSX.Element;
@@ -146,10 +147,9 @@ const ReactTableComponent = (props: ReactTableComponentProps) => {
header.parentElement.className = "th header-reorder";
if (i !== dragged && dragged !== -1) {
e.preventDefault();
- let columnOrder = props.columnOrder;
- if (columnOrder === undefined) {
- columnOrder = props.columns.map(item => item.accessor);
- }
+ const columnOrder = props.columnOrder
+ ? [...props.columnOrder]
+ : props.columns.map(item => item.accessor);
const draggedColumn = props.columns[dragged].accessor;
columnOrder.splice(dragged, 1);
columnOrder.splice(i, 0, draggedColumn);
@@ -275,9 +275,15 @@ const ReactTableComponent = (props: ReactTableComponentProps) => {
const handleResizeColumn = (columnIndex: number, columnWidth: string) => {
const column = props.columns[columnIndex];
- const columnSizeMap = props.columnSizeMap || {};
const width = Number(columnWidth.split("px")[0]);
- columnSizeMap[column.accessor] = width;
+ const columnSizeMap = props.columnSizeMap
+ ? {
+ ...props.columnSizeMap,
+ [column.accessor]: width,
+ }
+ : {
+ [column.accessor]: width,
+ };
props.handleResizeColumn(columnSizeMap);
};
diff --git a/app/client/src/components/designSystems/appsmith/TableUtilities.tsx b/app/client/src/components/designSystems/appsmith/TableUtilities.tsx
index efe2f6a6b633..cb4038070d50 100644
--- a/app/client/src/components/designSystems/appsmith/TableUtilities.tsx
+++ b/app/client/src/components/designSystems/appsmith/TableUtilities.tsx
@@ -698,6 +698,7 @@ export const TableHeaderCell = (props: {
toggleRenameColumn(false);
};
const handleSortColumn = () => {
+ if (column.isResizing) return;
let columnIndex = props.columnIndex;
if (props.isAscOrder === true) {
columnIndex = -1;
@@ -760,6 +761,10 @@ export const TableHeaderCell = (props: {
<div
{...column.getResizerProps()}
className={`resizer ${column.isResizing ? "isResizing" : ""}`}
+ onClick={(e: React.MouseEvent<HTMLElement>) => {
+ e.preventDefault();
+ e.stopPropagation();
+ }}
/>
</div>
);
|
d4cc110cd128c2a788ec3026d47321a4e2213f68
|
2021-10-27 17:04:54
|
Rishabh Saxena
|
fix: dont validate the email during comments onboarding if the email exists on the user object (#8851)
| false
|
dont validate the email during comments onboarding if the email exists on the user object (#8851)
|
fix
|
diff --git a/app/client/src/comments/CommentsShowcaseCarousel/ProfileForm.tsx b/app/client/src/comments/CommentsShowcaseCarousel/ProfileForm.tsx
index bec31d2233de..46246101d982 100644
--- a/app/client/src/comments/CommentsShowcaseCarousel/ProfileForm.tsx
+++ b/app/client/src/comments/CommentsShowcaseCarousel/ProfileForm.tsx
@@ -24,7 +24,7 @@ const Container = styled.div`
export const PROFILE_FORM = "PROFILE_FORM";
-const fieldNames = {
+export const fieldNames = {
displayName: "displayName",
emailAddress: "emailAddress",
};
diff --git a/app/client/src/comments/CommentsShowcaseCarousel/index.tsx b/app/client/src/comments/CommentsShowcaseCarousel/index.tsx
index 370ec0073623..6d0763cdc054 100644
--- a/app/client/src/comments/CommentsShowcaseCarousel/index.tsx
+++ b/app/client/src/comments/CommentsShowcaseCarousel/index.tsx
@@ -2,7 +2,7 @@ import React, { useState } from "react";
import Text, { TextType } from "components/ads/Text";
import ShowcaseCarousel, { Steps } from "components/ads/ShowcaseCarousel";
-import ProfileForm, { PROFILE_FORM } from "./ProfileForm";
+import ProfileForm, { PROFILE_FORM, fieldNames } from "./ProfileForm";
import CommentsCarouselModal from "./CommentsCarouselModal";
import ProgressiveImage, {
Container as ProgressiveImageContainer,
@@ -204,13 +204,23 @@ export default function CommentsShowcaseCarousel() {
const dispatch = useDispatch();
const isIntroCarouselVisible = useSelector(isIntroCarouselVisibleSelector);
const profileFormValues = useSelector(getFormValues(PROFILE_FORM));
- const profileFormErrors = useSelector(getFormSyncErrors("PROFILE_FORM"));
- const isSubmitDisabled = Object.keys(profileFormErrors).length !== 0;
+ const profileFormErrors = useSelector(
+ getFormSyncErrors("PROFILE_FORM"),
+ ) as Partial<typeof fieldNames>;
const [isSkipped, setIsSkipped] = useState(false);
const currentUser = useSelector(getCurrentUser);
const { email, name } = currentUser || {};
+ const emailDisabled = !!email;
+
+ // don't validate email address if it already exists on the user object
+ // this is to unblock the comments feature for github users where email is
+ // actually the github username
+ const isSubmitDisabled = !!(
+ profileFormErrors.displayName ||
+ (profileFormErrors.emailAddress && !emailDisabled)
+ );
const initialProfileFormValues = { emailAddress: email, displayName: name };
const onSubmitProfileForm = () => {
@@ -265,7 +275,7 @@ export default function CommentsShowcaseCarousel() {
isSubmitDisabled,
finalSubmit,
initialProfileFormValues,
- !!email,
+ emailDisabled,
canManage,
onSkip,
isSkipped,
|
eab29f5cdbc99c610114aa62b4a9375c5d2dd08f
|
2023-09-15 20:21:17
|
Pawan Kumar
|
chore: add fg + bd tokens tests for color algo (#27291)
| false
|
add fg + bd tokens tests for color algo (#27291)
|
chore
|
diff --git a/app/client/packages/design-system/theming/src/color/tests/DarkModeTheme.test.ts b/app/client/packages/design-system/theming/src/color/tests/DarkModeTheme.test.ts
index 7da566634412..7361926b6544 100644
--- a/app/client/packages/design-system/theming/src/color/tests/DarkModeTheme.test.ts
+++ b/app/client/packages/design-system/theming/src/color/tests/DarkModeTheme.test.ts
@@ -1,26 +1,26 @@
import { DarkModeTheme } from "../src/DarkModeTheme";
describe("bg color", () => {
- it("should return correct color when chroma is less than 0.04", () => {
+ it("should return correct color when chroma < 0.04", () => {
const { bg } = new DarkModeTheme("oklch(0.92 0.02 110)").getColors();
expect(bg).toBe("rgb(4.3484% 4.3484% 4.3484%)");
});
- it("should return correct color when chroma is greater than 0.04", () => {
+ it("should return correct color when chroma > 0.04", () => {
const { bg } = new DarkModeTheme("oklch(0.92 0.05 110)").getColors();
expect(bg).toBe("rgb(5.3377% 4.7804% 0%)");
});
});
describe("bgAccent color", () => {
- it("should return correct color when lightness is less than 0.3", () => {
+ it("should return correct color when lightness < 0.3", () => {
const { bgAccent } = new DarkModeTheme("oklch(0.2 0.09 231)").getColors();
expect(bgAccent).toBe("rgb(0% 19.987% 30.122%)");
});
});
describe("bgAccentHover color", () => {
- it("should return correct color when lightness is less than 0.3", () => {
+ it("should return correct color when lightness < 0.3", () => {
const { bgAccentHover } = new DarkModeTheme(
"oklch(0.2 0.09 231)",
).getColors();
@@ -41,28 +41,28 @@ describe("bgAccentHover color", () => {
expect(bgAccentHover).toBe("rgb(15.696% 45.773% 58.926%)");
});
- it("should return correct color when lightness is between 0.77 and 0.85, hue is outside 120-300, and chroma is greater than 0.04", () => {
+ it("should return correct color when lightness is between 0.77 and 0.85, hue is outside 120-300, and chroma > 0.04", () => {
const { bgAccentHover } = new DarkModeTheme(
"oklch(0.80 0.09 150)",
).getColors();
expect(bgAccentHover).toBe("rgb(51.184% 89.442% 60.062%)");
});
- it("should return correct color when lightness is between 0.77 and 0.85, hue is inside 120-300, and chroma is greater than 0.04", () => {
+ it("should return correct color when lightness is between 0.77 and 0.85, hue is inside 120-300, and chroma > 0.04", () => {
const { bgAccentHover } = new DarkModeTheme(
"oklch(0.80 0.09 110)",
).getColors();
expect(bgAccentHover).toBe("rgb(85.364% 85.594% 0%)");
});
- it("should return correct color when lightness is between 0.77 and 0.85, and chroma is less than 0.04", () => {
+ it("should return correct color when lightness is between 0.77 and 0.85, and chroma < 0.04", () => {
const { bgAccentHover } = new DarkModeTheme(
"oklch(0.80 0.03 110)",
).getColors();
expect(bgAccentHover).toBe("rgb(79.687% 80.239% 71.58%)");
});
- it("should return correct color when lightness is greater than 0.85", () => {
+ it("should return correct color when lightness > 0.85", () => {
const { bgAccentHover } = new DarkModeTheme(
"oklch(0.90 0.03 110)",
).getColors();
@@ -71,7 +71,7 @@ describe("bgAccentHover color", () => {
});
describe("bgAccentActive color", () => {
- it("should return correct color when seedLightness is less than 0.4", () => {
+ it("should return correct color when seedLightness < 0.4", () => {
const { bgAccentActive } = new DarkModeTheme(
"oklch(0.2 0.09 231)",
).getColors();
@@ -92,7 +92,7 @@ describe("bgAccentActive color", () => {
expect(bgAccentActive).toBe("rgb(37.393% 66.165% 80.119%)");
});
- it("should return correct color when seedLightness is greater than or equal to 0.85", () => {
+ it("should return correct color when seedLightness > or equal to 0.85", () => {
const { bgAccentActive } = new DarkModeTheme(
"oklch(0.90 0.09 231)",
).getColors();
@@ -101,28 +101,28 @@ describe("bgAccentActive color", () => {
});
describe("bgAccentSubtle color", () => {
- it("should return correct color when seedLightness is greater than 0.25", () => {
+ it("should return correct color when seedLightness > 0.25", () => {
const { bgAccentSubtle } = new DarkModeTheme(
"oklch(0.30 0.09 231)",
).getColors();
expect(bgAccentSubtle).toBe("rgb(0% 14.671% 23.499%)");
});
- it("should return correct color when seedLightness is less than 0.2", () => {
+ it("should return correct color when seedLightness < 0.2", () => {
const { bgAccentSubtle } = new DarkModeTheme(
"oklch(0.15 0.09 231)",
).getColors();
expect(bgAccentSubtle).toBe("rgb(0% 9.5878% 17.677%)");
});
- it("should return correct color when seedChroma is greater than 0.1", () => {
+ it("should return correct color when seedChroma > 0.1", () => {
const { bgAccentSubtle } = new DarkModeTheme(
"oklch(0.30 0.15 231)",
).getColors();
expect(bgAccentSubtle).toBe("rgb(0% 14.556% 23.9%)");
});
- it("should return correct color when seedChroma is less than 0.04", () => {
+ it("should return correct color when seedChroma < 0.04", () => {
const { bgAccentSubtle } = new DarkModeTheme(
"oklch(0.30 0.03 231)",
).getColors();
@@ -131,28 +131,28 @@ describe("bgAccentSubtle color", () => {
});
describe("bgAccentSubtle color", () => {
- it("should return correct color when seedLightness is greater than 0.25", () => {
+ it("should return correct color when seedLightness > 0.25", () => {
const { bgAccentSubtle } = new DarkModeTheme(
"oklch(0.30 0.09 231)",
).getColors();
expect(bgAccentSubtle).toBe("rgb(0% 14.671% 23.499%)");
});
- it("should return correct color when seedLightness is less than 0.2", () => {
+ it("should return correct color when seedLightness < 0.2", () => {
const { bgAccentSubtle } = new DarkModeTheme(
"oklch(0.15 0.09 231)",
).getColors();
expect(bgAccentSubtle).toBe("rgb(0% 9.5878% 17.677%)");
});
- it("should return correct color when seedChroma is greater than 0.1", () => {
+ it("should return correct color when seedChroma > 0.1", () => {
const { bgAccentSubtle } = new DarkModeTheme(
"oklch(0.30 0.15 231)",
).getColors();
expect(bgAccentSubtle).toBe("rgb(0% 14.556% 23.9%)");
});
- it("should return correct color when seedChroma is less than 0.04", () => {
+ it("should return correct color when seedChroma < 0.04", () => {
const { bgAccentSubtle } = new DarkModeTheme(
"oklch(0.30 0.03 231)",
).getColors();
@@ -188,12 +188,12 @@ describe("bgAssistive color", () => {
});
describe("bgNeutral color", () => {
- it("should return correct color when lightness is less than 0.5", () => {
+ it("should return correct color when lightness < 0.5", () => {
const { bgNeutral } = new DarkModeTheme("oklch(0.3 0.09 231)").getColors();
expect(bgNeutral).toEqual("rgb(18.887% 23.77% 26.341%)");
});
- it("should return correct color when chroma is less than 0.04", () => {
+ it("should return correct color when chroma < 0.04", () => {
const { bgNeutral } = new DarkModeTheme("oklch(0.95 0.02 170)").getColors();
expect(bgNeutral).toEqual("rgb(93.448% 93.448% 93.448%)");
});
@@ -210,7 +210,7 @@ describe("bgNeutral color", () => {
});
describe("bgNeutralHover color", () => {
- it("should return correct color when lightness is greater than or equal to 0.85", () => {
+ it("should return correct color when lightness > or equal to 0.85", () => {
const { bgNeutralHover } = new DarkModeTheme(
"oklch(0.86 0.03 170)",
).getColors();
@@ -240,7 +240,7 @@ describe("bgNeutralHover color", () => {
});
describe("bgNeutralActive color", () => {
- it("should return correct color when lightness is less than 0.4", () => {
+ it("should return correct color when lightness < 0.4", () => {
const { bgNeutralActive } = new DarkModeTheme(
"oklch(0.39 0.03 170)",
).getColors();
@@ -261,7 +261,7 @@ describe("bgNeutralActive color", () => {
expect(bgNeutralActive).toEqual("rgb(68.134% 68.134% 68.134%)");
});
- it("should return correct color when lightness is greater than or equal to 0.85", () => {
+ it("should return correct color when lightness > or equal to 0.85", () => {
const { bgNeutralActive } = new DarkModeTheme(
"oklch(0.9 0.03 170)",
).getColors();
@@ -270,28 +270,28 @@ describe("bgNeutralActive color", () => {
});
describe("bgNeutralSubtle color", () => {
- it("should return correct color when lightness is greater than 0.25", () => {
+ it("should return correct color when lightness > 0.25", () => {
const { bgNeutralSubtle } = new DarkModeTheme(
"oklch(0.3 0.03 170)",
).getColors();
expect(bgNeutralSubtle).toEqual("rgb(13.15% 13.15% 13.15%)");
});
- it("should return correct color when lightness is less than 0.2", () => {
+ it("should return correct color when lightness < 0.2", () => {
const { bgNeutralSubtle } = new DarkModeTheme(
"oklch(0.15 0.03 170)",
).getColors();
expect(bgNeutralSubtle).toEqual("rgb(8.6104% 8.6104% 8.6104%)");
});
- it("should return correct color when chroma is greater than 0.025", () => {
+ it("should return correct color when chroma > 0.025", () => {
const { bgNeutralSubtle } = new DarkModeTheme(
"oklch(0.3 0.03 170)",
).getColors();
expect(bgNeutralSubtle).toEqual("rgb(13.15% 13.15% 13.15%)");
});
- it("should return correct color when chroma is less than 0.025 (achromatic)", () => {
+ it("should return correct color when chroma < 0.025 (achromatic)", () => {
const { bgNeutralSubtle } = new DarkModeTheme(
"oklch(0.3 0.01 170)",
).getColors();
@@ -525,3 +525,328 @@ describe("bgWarningSubtleActive color", () => {
expect(bgWarningSubtleActive).toEqual("rgb(14.696% 10.673% 1.7722%)");
});
});
+
+describe("fg color", () => {
+ it("should return correct color when chroma < 0.04", () => {
+ const { fg } = new DarkModeTheme("oklch(0.45 0.03 60)").getColors();
+
+ expect(fg).toEqual("rgb(95.405% 95.405% 95.405%)");
+ });
+
+ it("should return correct color when chroma > 0.04", () => {
+ const { fg } = new DarkModeTheme("oklch(0.45 0.1 60)").getColors();
+
+ expect(fg).toEqual("rgb(100% 94.175% 89.331%)");
+ });
+});
+
+describe("fgAccent color", () => {
+ it("should return correct color when chroma < 0.04", () => {
+ const { fgAccent } = new DarkModeTheme("oklch(0.45 0.03 60)").getColors();
+
+ expect(fgAccent).toEqual("rgb(73.075% 73.075% 73.075%)");
+ });
+
+ it("should return correct color when chroma > 0.04", () => {
+ const { fgAccent } = new DarkModeTheme("oklch(0.45 0.1 60)").getColors();
+
+ expect(fgAccent).toEqual("rgb(97.93% 64.37% 34.977%)");
+ });
+});
+
+describe("fgNeutral color", () => {
+ it("should return correct color when chroma < 0.04", () => {
+ const { fgNeutral } = new DarkModeTheme("oklch(0.45 0.03 60)").getColors();
+
+ expect(fgNeutral).toEqual("rgb(78.08% 78.08% 78.08%)");
+ });
+
+ it("should return correct color when chroma > 0.04 and hue is between 120 and 300", () => {
+ const { fgNeutral } = new DarkModeTheme("oklch(0.45 0.1 150)").getColors();
+
+ expect(fgNeutral).toEqual("rgb(73.047% 80.455% 74.211%)");
+ });
+
+ it("should return correct color when chroma > 0.04 and hue is not between 120 and 300", () => {
+ const { fgNeutral } = new DarkModeTheme("oklch(0.45 0.1 110)").getColors();
+
+ expect(fgNeutral).toEqual("rgb(78.185% 78.394% 75.54%)");
+ });
+});
+
+describe("fgPositive color", () => {
+ it("should return correct color when chroma < 0.04", () => {
+ const { fgPositive } = new DarkModeTheme("oklch(0.45 0.03 60)").getColors();
+
+ expect(fgPositive).toEqual("rgb(30.123% 72.521% 33.746%)");
+ });
+
+ it("should return correct color when chroma > 0.04", () => {
+ const { fgPositive } = new DarkModeTheme("oklch(0.45 0.1 60)").getColors();
+
+ expect(fgPositive).toEqual("rgb(30.123% 72.521% 33.746%)");
+ });
+
+ it("should return correct color hue is between 116 and 165", () => {
+ const { fgPositive } = new DarkModeTheme("oklch(0.45 0.1 120)").getColors();
+
+ expect(fgPositive).toEqual("rgb(21.601% 73.197% 38.419%)");
+ });
+
+ it("should return correct color hue is not between 116 and 165", () => {
+ const { fgPositive } = new DarkModeTheme("oklch(0.45 0.1 30)").getColors();
+
+ expect(fgPositive).toEqual("rgb(30.123% 72.521% 33.746%)");
+ });
+});
+
+describe("fgNegative color", () => {
+ it("should return correct color when chroma < 0.04", () => {
+ const { fgNegative } = new DarkModeTheme("oklch(0.45 0.03 60)").getColors();
+
+ expect(fgNegative).toEqual("rgb(93.903% 0% 24.24%)");
+ });
+
+ it("should return correct color when chroma > 0.04", () => {
+ const { fgNegative } = new DarkModeTheme("oklch(0.45 0.1 60)").getColors();
+
+ expect(fgNegative).toEqual("rgb(93.903% 0% 24.24%)");
+ });
+
+ it("should return correct color hue is between 5 and 49", () => {
+ const { fgNegative } = new DarkModeTheme("oklch(0.45 0.1 30)").getColors();
+
+ expect(fgNegative).toEqual("rgb(93.292% 0% 32.205%)");
+ });
+
+ it("should return correct color hue is not between 5 and 49", () => {
+ const { fgNegative } = new DarkModeTheme("oklch(0.45 0.1 120)").getColors();
+
+ expect(fgNegative).toEqual("rgb(93.903% 0% 24.24%)");
+ });
+});
+
+describe("fgWarning color", () => {
+ it("should return correct color", () => {
+ const { fgWarning } = new DarkModeTheme("oklch(0.45 0.03 60)").getColors();
+
+ expect(fgWarning).toEqual("rgb(100% 78.06% 1.4578%)");
+ });
+});
+
+describe("fgOnAccent color ", () => {
+ it("should return correct color when chroma < 0.04", () => {
+ const { fgOnAccent } = new DarkModeTheme("oklch(0.45 0.03 60)").getColors();
+
+ expect(fgOnAccent).toEqual("rgb(92.148% 92.148% 92.148%)");
+ });
+
+ it("should return correct color when chroma > 0.04", () => {
+ const { fgOnAccent } = new DarkModeTheme("oklch(0.45 0.1 60)").getColors();
+
+ expect(fgOnAccent).toEqual("rgb(100% 89.256% 79.443%)");
+ });
+});
+
+describe("fgOnAssistive color ", () => {
+ it("should return correct color", () => {
+ const { fgOnAssistive } = new DarkModeTheme(
+ "oklch(0.45 0.03 110)",
+ ).getColors();
+
+ expect(fgOnAssistive).toEqual("rgb(15.033% 15.033% 15.033%)");
+ });
+});
+
+describe("fgOnNeutral color ", () => {
+ it("should return correct color", () => {
+ const { fgOnNeutral } = new DarkModeTheme(
+ "oklch(0.45 0.03 110)",
+ ).getColors();
+
+ expect(fgOnNeutral).toEqual("rgb(92.148% 92.148% 92.148%)");
+ });
+});
+
+describe("fgOnPositive color ", () => {
+ it("should return correct color", () => {
+ const { fgOnPositive } = new DarkModeTheme(
+ "oklch(0.45 0.03 110)",
+ ).getColors();
+
+ expect(fgOnPositive).toEqual("rgb(80.46% 100% 80.049%)");
+ });
+});
+
+describe("fgOnNegative color ", () => {
+ it("should return correct color", () => {
+ const { fgOnNegative } = new DarkModeTheme(
+ "oklch(0.45 0.03 110)",
+ ).getColors();
+
+ expect(fgOnNegative).toEqual("rgb(100% 85.802% 83.139%)");
+ });
+});
+
+describe("fgOnWarning color ", () => {
+ it("should return correct color", () => {
+ const { fgOnWarning } = new DarkModeTheme(
+ "oklch(0.45 0.03 110)",
+ ).getColors();
+
+ expect(fgOnWarning).toEqual("rgb(23.887% 11.273% 0%)");
+ });
+});
+
+describe("bd color", () => {
+ it("should return correct color", () => {
+ const { bd } = new DarkModeTheme("oklch(0.45 0.5 60)").getColors();
+ expect(bd).toEqual("rgb(32.033% 27.005% 23.081%)");
+ });
+});
+
+describe("bdAccent color", () => {
+ it("should return correct color when chroma < 0.04", () => {
+ const { bd } = new DarkModeTheme("oklch(0.45 0.03 60)").getColors();
+ expect(bd).toEqual("rgb(28.06% 28.06% 28.06%)");
+ });
+
+ it("should return correct color when chroma > 0.04", () => {
+ const { bd } = new DarkModeTheme("oklch(0.45 0.1 60)").getColors();
+ expect(bd).toEqual("rgb(32.033% 27.005% 23.081%)");
+ });
+});
+
+describe("bdFocus color", () => {
+ it("should return correct color when lightness < 0.4", () => {
+ const { bd } = new DarkModeTheme("oklch(0.3 0.4 60)").getColors();
+ expect(bd).toEqual("rgb(32.033% 27.005% 23.081%)");
+ });
+
+ it("should return correct color when lightness > 0.65", () => {
+ const { bd } = new DarkModeTheme("oklch(0.85 0.03 60)").getColors();
+ expect(bd).toEqual("rgb(28.06% 28.06% 28.06%)");
+ });
+
+ it("should return correct color when chroma < 0.12", () => {
+ const { bd } = new DarkModeTheme("oklch(0.85 0.1 60)").getColors();
+ expect(bd).toEqual("rgb(32.033% 27.005% 23.081%)");
+ });
+
+ it("should return correct color when hue is between 0 and 55", () => {
+ const { bd } = new DarkModeTheme("oklch(0.85 0.1 30)").getColors();
+ expect(bd).toEqual("rgb(32.929% 26.308% 25.118%)");
+ });
+
+ it("should return correct color when hue > 340", () => {
+ const { bd } = new DarkModeTheme("oklch(0.85 0.1 350)").getColors();
+ expect(bd).toEqual("rgb(32.237% 26.106% 28.799%)");
+ });
+});
+
+describe("bdNeutral color", () => {
+ it("should return correct color when chroma < 0.04", () => {
+ const { bd } = new DarkModeTheme("oklch(0.45 0.03 60)").getColors();
+ expect(bd).toEqual("rgb(28.06% 28.06% 28.06%)");
+ });
+});
+
+describe("bdNeutralHover", () => {
+ it("should return correct color", () => {
+ const { bdNeutralHover } = new DarkModeTheme(
+ "oklch(0.45 0.03 60)",
+ ).getColors();
+ expect(bdNeutralHover).toEqual("rgb(89.558% 89.558% 89.558%)");
+ });
+});
+
+describe("bdPositive", () => {
+ it("should return correct color", () => {
+ const { bdPositive } = new DarkModeTheme("oklch(0.45 0.03 60)").getColors();
+ expect(bdPositive).toEqual("rgb(0% 71.137% 15.743%)");
+ });
+});
+
+describe("bdPositiveHover", () => {
+ it("should return correct color", () => {
+ const { bdPositiveHover } = new DarkModeTheme(
+ "oklch(0.45 0.03 60)",
+ ).getColors();
+ expect(bdPositiveHover).toEqual("rgb(25.51% 86.719% 33.38%)");
+ });
+});
+
+describe("bdNegative", () => {
+ it("should return correct color", () => {
+ const { bdNegative } = new DarkModeTheme("oklch(0.45 0.03 60)").getColors();
+ expect(bdNegative).toEqual("rgb(83.108% 4.6651% 10.252%)");
+ });
+});
+
+describe("bdNegativeHover", () => {
+ it("should return correct color", () => {
+ const { bdNegativeHover } = new DarkModeTheme(
+ "oklch(0.45 0.03 60)",
+ ).getColors();
+ expect(bdNegativeHover).toEqual("rgb(100% 33.485% 30.164%)");
+ });
+});
+
+describe("bdWarning", () => {
+ it("should return correct color", () => {
+ const { bdWarning } = new DarkModeTheme("oklch(0.45 0.03 60)").getColors();
+ expect(bdWarning).toEqual("rgb(85.145% 64.66% 8.0286%)");
+ });
+});
+
+describe("bdWarningHover", () => {
+ it("should return correct color", () => {
+ const { bdWarningHover } = new DarkModeTheme(
+ "oklch(0.45 0.03 60)",
+ ).getColors();
+ expect(bdWarningHover).toEqual("rgb(100% 77.286% 0%)");
+ });
+});
+
+describe("bdOnAccent", () => {
+ it("should return correct color", () => {
+ const { bdOnAccent } = new DarkModeTheme("oklch(0.45 0.03 60)").getColors();
+ expect(bdOnAccent).toEqual("rgb(8.8239% 3.8507% 0.7917%)");
+ });
+});
+
+describe("bdOnNeutral", () => {
+ it("should return correct color", () => {
+ const { bdOnNeutral } = new DarkModeTheme(
+ "oklch(0.45 0.03 60)",
+ ).getColors();
+ expect(bdOnNeutral).toEqual("rgb(9.4978% 9.4978% 9.4978%)");
+ });
+});
+
+describe("bdOnPositive", () => {
+ it("should return correct color", () => {
+ const { bdOnPositive } = new DarkModeTheme(
+ "oklch(0.45 0.03 60)",
+ ).getColors();
+ expect(bdOnPositive).toEqual("rgb(0% 38.175% 0%)");
+ });
+});
+
+describe("bdOnNegative", () => {
+ it("should return correct color", () => {
+ const { bdOnNegative } = new DarkModeTheme(
+ "oklch(0.45 0.03 60)",
+ ).getColors();
+ expect(bdOnNegative).toEqual("rgb(36.138% 0% 2.5021%)");
+ });
+});
+
+describe("bdOnWarning", () => {
+ it("should return correct color", () => {
+ const { bdOnWarning } = new DarkModeTheme(
+ "oklch(0.45 0.03 60)",
+ ).getColors();
+ expect(bdOnWarning).toEqual("rgb(49.811% 36.357% 0%)");
+ });
+});
diff --git a/app/client/packages/design-system/theming/src/color/tests/LightModeTheme.test.ts b/app/client/packages/design-system/theming/src/color/tests/LightModeTheme.test.ts
index e1f17868bb0b..35cd52404f12 100644
--- a/app/client/packages/design-system/theming/src/color/tests/LightModeTheme.test.ts
+++ b/app/client/packages/design-system/theming/src/color/tests/LightModeTheme.test.ts
@@ -35,7 +35,7 @@ describe("bgAccent color", () => {
});
describe("bgAccentHover color", () => {
- it("should return correct color when lightness is less than 0.06", () => {
+ it("should return correct color when lightness < 0.06", () => {
const { bgAccentHover } = new LightModeTheme(
"oklch(0.05 0.09 231)",
).getColors();
@@ -77,21 +77,21 @@ describe("bgAccentHover color", () => {
expect(bgAccentHover).toBe("rgb(45.795% 46.287% 19.839%)");
});
- it("should return correct color when lightness is greater than 0.7", () => {
+ it("should return correct color when lightness > 0.7", () => {
const { bgAccentHover } = new LightModeTheme(
"oklch(0.9 0.09 110)",
).getColors();
expect(bgAccentHover).toBe("rgb(92.14% 93.271% 65.642%)");
});
- it("should return correct color when lightness is greater than 0.93 and hue is between 60 and 115", () => {
+ it("should return correct color when lightness > 0.93 and hue is between 60 and 115", () => {
const { bgAccentHover } = new LightModeTheme(
"oklch(0.95 0.09 70)",
).getColors();
expect(bgAccentHover).toBe("rgb(100% 90.701% 78.457%)");
});
- it("should return correct color when lightness is greater than 0.93 and hue is not between 116 and 165", () => {
+ it("should return correct color when lightness > 0.93 and hue is not between 116 and 165", () => {
const { bgAccentHover } = new LightModeTheme(
"oklch(0.95 0.09 120)",
).getColors();
@@ -100,7 +100,7 @@ describe("bgAccentHover color", () => {
});
describe("bgAccentActive color", () => {
- it("should return correct color when lightness is less than 0.4", () => {
+ it("should return correct color when lightness < 0.4", () => {
const { bgAccentActive } = new LightModeTheme(
"oklch(0.35 0.09 70)",
).getColors();
@@ -114,14 +114,14 @@ describe("bgAccentActive color", () => {
expect(bgAccentActive).toBe("rgb(49.27% 32.745% 10.549%)");
});
- it("should return correct color when lightness is greater than or equal to 0.7", () => {
+ it("should return correct color when lightness > or equal to 0.7", () => {
const { bgAccentActive } = new LightModeTheme(
"oklch(0.75 0.09 70)",
).getColors();
expect(bgAccentActive).toBe("rgb(81.395% 63.124% 41.808%)");
});
- it("should return correct color when lightness is greater than 0.93", () => {
+ it("should return correct color when lightness > 0.93", () => {
const { bgAccentActive } = new LightModeTheme(
"oklch(0.95 0.09 70)",
).getColors();
@@ -130,35 +130,35 @@ describe("bgAccentActive color", () => {
});
describe("bgAccentSubtle color", () => {
- it("should return correct color when seedLightness is greater than 0.93", () => {
+ it("should return correct color when seedLightness > 0.93", () => {
const { bgAccentSubtle } = new LightModeTheme(
"oklch(0.95 0.09 231)",
).getColors();
expect(bgAccentSubtle).toBe("rgb(85.876% 96.17% 100%)");
});
- it("should return correct color when seedLightness is less than 0.93", () => {
+ it("should return correct color when seedLightness < 0.93", () => {
const { bgAccentSubtle } = new LightModeTheme(
"oklch(0.92 0.09 231)",
).getColors();
expect(bgAccentSubtle).toBe("rgb(78.235% 93.705% 100%)");
});
- it("should return correct color when seedChroma is greater than 0.09 and hue is between 116 and 165", () => {
+ it("should return correct color when seedChroma > 0.09 and hue is between 116 and 165", () => {
const { bgAccentSubtle } = new LightModeTheme(
"oklch(0.95 0.10 120)",
).getColors();
expect(bgAccentSubtle).toBe("rgb(90.964% 97.964% 71.119%)");
});
- it("should return correct color when seedChroma is greater than 0.06 and hue is not between 116 and 165", () => {
+ it("should return correct color when seedChroma > 0.06 and hue is not between 116 and 165", () => {
const { bgAccentSubtle } = new LightModeTheme(
"oklch(0.95 0.07 170)",
).getColors();
expect(bgAccentSubtle).toBe("rgb(75.944% 100% 91.359%)");
});
- it("should return correct color when seedChroma is less than 0.04", () => {
+ it("should return correct color when seedChroma < 0.04", () => {
const { bgAccentSubtle } = new LightModeTheme(
"oklch(0.95 0.03 170)",
).getColors();
@@ -194,7 +194,7 @@ describe("bgAssistive color", () => {
});
describe("bgNeutral color", () => {
- it("should return correct color when lightness is greater than 0.85", () => {
+ it("should return correct color when lightness > 0.85", () => {
const { bgNeutral } = new LightModeTheme(
"oklch(0.95 0.03 170)",
).getColors();
@@ -206,7 +206,7 @@ describe("bgNeutral color", () => {
expect(bgNeutral).toEqual("rgb(21.658% 29.368% 33.367%)");
});
- it("should return correct color when chroma is less than 0.04", () => {
+ it("should return correct color when chroma < 0.04", () => {
const { bgNeutral } = new LightModeTheme(
"oklch(0.95 0.02 170)",
).getColors();
@@ -227,7 +227,7 @@ describe("bgNeutral color", () => {
});
describe("bgNeutralHover color", () => {
- it("should return correct color when lightness is less than 0.06", () => {
+ it("should return correct color when lightness < 0.06", () => {
const { bgNeutralHover } = new LightModeTheme(
"oklch(0.05 0.03 170)",
).getColors();
@@ -262,7 +262,7 @@ describe("bgNeutralHover color", () => {
expect(bgNeutralHover).toEqual("rgb(62.05% 62.05% 62.05%)");
});
- it("should return correct color when lightness is greater than or equal to 0.955", () => {
+ it("should return correct color when lightness > or equal to 0.955", () => {
const { bgNeutralHover } = new LightModeTheme(
"oklch(0.96 0.03 170)",
).getColors();
@@ -271,7 +271,7 @@ describe("bgNeutralHover color", () => {
});
describe("bgNeutralActive color", () => {
- it("should return correct color when lightness is less than 0.4", () => {
+ it("should return correct color when lightness < 0.4", () => {
const { bgNeutralActive } = new LightModeTheme(
"oklch(0.35 0.03 170)",
).getColors();
@@ -285,7 +285,7 @@ describe("bgNeutralActive color", () => {
expect(bgNeutralActive).toEqual("rgb(60.846% 60.846% 60.846%)");
});
- it("should return correct color when lightness is greater than or equal to 0.955", () => {
+ it("should return correct color when lightness > or equal to 0.955", () => {
const { bgNeutralActive } = new LightModeTheme(
"oklch(0.96 0.03 170)",
).getColors();
@@ -294,28 +294,28 @@ describe("bgNeutralActive color", () => {
});
describe("bgNeutralSubtle color", () => {
- it("should return correct color when lightness is greater than 0.93", () => {
+ it("should return correct color when lightness > 0.93", () => {
const { bgNeutralSubtle } = new LightModeTheme(
"oklch(0.95 0.03 170)",
).getColors();
expect(bgNeutralSubtle).toEqual("rgb(94.099% 94.099% 94.099%)");
});
- it("should return correct color when lightness is less than or equal to 0.93", () => {
+ it("should return correct color when lightness < or equal to 0.93", () => {
const { bgNeutralSubtle } = new LightModeTheme(
"oklch(0.92 0.03 170)",
).getColors();
expect(bgNeutralSubtle).toEqual("rgb(90.851% 90.851% 90.851%)");
});
- it("should return correct color when seedChroma is greater than 0.01", () => {
+ it("should return correct color when seedChroma > 0.01", () => {
const { bgNeutralSubtle } = new LightModeTheme(
"oklch(0.92 0.1 170)",
).getColors();
expect(bgNeutralSubtle).toEqual("rgb(88.517% 91.796% 90.467%)");
});
- it("should return correct color when chroma is less than 0.04", () => {
+ it("should return correct color when chroma < 0.04", () => {
const { bgNeutralSubtle } = new LightModeTheme(
"oklch(0.92 0.03 170)",
).getColors();
@@ -555,3 +555,344 @@ describe("bgWarningSubtleActive color", () => {
expect(bgWarningSubtleActive).toEqual("rgb(100% 91.621% 80.174%)");
});
});
+
+describe("fg color", () => {
+ it("should return correct color when chroma < 0.04", () => {
+ const { fg } = new LightModeTheme("oklch(0.45 0.03 60)").getColors();
+
+ expect(fg).toEqual("rgb(2.2326% 2.2326% 2.2326%)");
+ });
+
+ it("should return correct color when chroma > 0.04", () => {
+ const { fg } = new LightModeTheme("oklch(0.45 0.1 60)").getColors();
+
+ expect(fg).toEqual("rgb(5.4369% 1.2901% 0%)");
+ });
+});
+
+describe("fgAccent color", () => {
+ it("should return correct color when chroma < 0.04", () => {
+ const { fgAccent } = new LightModeTheme("oklch(0.45 0.03 60)").getColors();
+
+ expect(fgAccent).toEqual("rgb(38.473% 32.008% 26.943%)");
+ });
+
+ it("should return correct color when chroma > 0.04", () => {
+ const { fgAccent } = new LightModeTheme("oklch(0.45 0.1 60)").getColors();
+
+ expect(fgAccent).toEqual("rgb(48.857% 27.291% 4.3335%)");
+ });
+});
+
+describe("fgNeutral color", () => {
+ it("should return correct color when chroma < 0.04", () => {
+ const { fgNeutral } = new LightModeTheme("oklch(0.45 0.03 60)").getColors();
+
+ expect(fgNeutral).toEqual("rgb(33.384% 33.384% 33.384%)");
+ });
+
+ it("should return correct color when chroma > 0.04 and hue is between 120 and 300", () => {
+ const { fgNeutral } = new LightModeTheme("oklch(0.45 0.1 150)").getColors();
+
+ expect(fgNeutral).toEqual("rgb(25.52% 36.593% 27.669%)");
+ });
+
+ it("should return correct color when chroma > 0.04 and hue is not between 120 and 300", () => {
+ const { fgNeutral } = new LightModeTheme("oklch(0.45 0.1 110)").getColors();
+
+ expect(fgNeutral).toEqual("rgb(33.531% 33.77% 30.07%)");
+ });
+});
+
+describe("fgPositive color", () => {
+ it("should return correct color when chroma < 0.04", () => {
+ const { fgPositive } = new LightModeTheme(
+ "oklch(0.45 0.03 60)",
+ ).getColors();
+
+ expect(fgPositive).toEqual("rgb(6.7435% 63.436% 18.481%)");
+ });
+
+ it("should return correct color when lightness > 0.04", () => {
+ const { fgPositive } = new LightModeTheme("oklch(0.45 0.1 60)").getColors();
+
+ expect(fgPositive).toEqual("rgb(6.7435% 63.436% 18.481%)");
+ });
+
+ it("should return correct color hue is between 116 and 165", () => {
+ const { fgPositive } = new LightModeTheme(
+ "oklch(0.45 0.1 120)",
+ ).getColors();
+
+ expect(fgPositive).toEqual("rgb(6.7435% 63.436% 18.481%)");
+ });
+
+ it("should return correct color hue is not between 116 and 165", () => {
+ const { fgPositive } = new LightModeTheme("oklch(0.45 0.1 30)").getColors();
+
+ expect(fgPositive).toEqual("rgb(6.7435% 63.436% 18.481%)");
+ });
+});
+
+describe("fgNegative color", () => {
+ it("should return correct color when chroma < 0.04", () => {
+ const { fgNegative } = new LightModeTheme(
+ "oklch(0.45 0.03 60)",
+ ).getColors();
+
+ expect(fgNegative).toEqual("rgb(100% 0% 28.453%)");
+ });
+
+ it("should return correct color when chroma > 0.04", () => {
+ const { fgNegative } = new LightModeTheme("oklch(0.45 0.1 60)").getColors();
+
+ expect(fgNegative).toEqual("rgb(100% 0% 28.453%)");
+ });
+
+ it("should return correct color hue is between 5 and 49", () => {
+ const { fgNegative } = new LightModeTheme("oklch(0.45 0.1 30)").getColors();
+
+ expect(fgNegative).toEqual("rgb(100% 0% 28.453%)");
+ });
+
+ it("should return correct color hue is not between 5 and 49", () => {
+ const { fgNegative } = new LightModeTheme(
+ "oklch(0.45 0.1 120)",
+ ).getColors();
+
+ expect(fgNegative).toEqual("rgb(100% 0% 28.453%)");
+ });
+});
+
+describe("fgWarning color", () => {
+ it("should return correct color", () => {
+ const { fgWarning } = new LightModeTheme("oklch(0.45 0.03 60)").getColors();
+
+ expect(fgWarning).toEqual("rgb(71.79% 51.231% 0%)");
+ });
+});
+
+describe("fgOnAccent color ", () => {
+ it("should return correct color when chroma < 0.04", () => {
+ const { fgOnAccent } = new LightModeTheme(
+ "oklch(0.45 0.03 60)",
+ ).getColors();
+
+ expect(fgOnAccent).toEqual("rgb(94.752% 94.752% 94.752%)");
+ });
+
+ it("should return correct color when chroma > 0.04", () => {
+ const { fgOnAccent } = new LightModeTheme("oklch(0.45 0.1 60)").getColors();
+
+ expect(fgOnAccent).toEqual("rgb(100% 92.634% 85.713%)");
+ });
+});
+
+describe("fgOnAssistive color ", () => {
+ it("should return correct color", () => {
+ const { fgOnAssistive } = new LightModeTheme(
+ "oklch(0.45 0.03 110)",
+ ).getColors();
+
+ expect(fgOnAssistive).toEqual("rgb(96.059% 96.059% 96.059%)");
+ });
+});
+
+describe("fgOnNeutral color ", () => {
+ it("should return correct color", () => {
+ const { fgOnNeutral } = new LightModeTheme(
+ "oklch(0.45 0.03 110)",
+ ).getColors();
+
+ expect(fgOnNeutral).toEqual("rgb(94.752% 94.752% 94.752%)");
+ });
+});
+
+describe("fgOnPositive color ", () => {
+ it("should return correct color", () => {
+ const { fgOnPositive } = new LightModeTheme(
+ "oklch(0.45 0.03 110)",
+ ).getColors();
+
+ expect(fgOnPositive).toEqual("rgb(89.702% 100% 89.053%)");
+ });
+});
+
+describe("fgOnNegative color ", () => {
+ it("should return correct color", () => {
+ const { fgOnNegative } = new LightModeTheme(
+ "oklch(0.45 0.03 110)",
+ ).getColors();
+
+ expect(fgOnNegative).toEqual("rgb(100% 87.612% 85.249%)");
+ });
+});
+
+describe("fgOnWarning color ", () => {
+ it("should return correct color", () => {
+ const { fgOnWarning } = new LightModeTheme(
+ "oklch(0.45 0.03 110)",
+ ).getColors();
+
+ expect(fgOnWarning).toEqual("rgb(21.953% 9.0775% 0%)");
+ });
+});
+
+describe("bd color", () => {
+ it("should return correct color", () => {
+ const { bd } = new LightModeTheme("oklch(0.45 0.5 60)").getColors();
+ expect(bd).toEqual("rgb(80.718% 72.709% 66.526%)");
+ });
+});
+
+describe("bdAccent color", () => {
+ it("should return correct color when chroma < 0.04", () => {
+ const { bd } = new LightModeTheme("oklch(0.45 0.03 60)").getColors();
+ expect(bd).toEqual("rgb(74.321% 74.321% 74.321%)");
+ });
+
+ it("should return correct color when chroma > 0.04", () => {
+ const { bd } = new LightModeTheme("oklch(0.45 0.1 60)").getColors();
+ expect(bd).toEqual("rgb(80.718% 72.709% 66.526%)");
+ });
+});
+
+describe("bdFocus color", () => {
+ it("should return correct color when lightness < 0.6", () => {
+ const { bd } = new LightModeTheme("oklch(0.45 0.4 60)").getColors();
+ expect(bd).toEqual("rgb(80.718% 72.709% 66.526%)");
+ });
+
+ it("should return correct color when lightness > 0.8", () => {
+ const { bd } = new LightModeTheme("oklch(0.85 0.03 60)").getColors();
+ expect(bd).toEqual("rgb(74.321% 74.321% 74.321%)");
+ });
+
+ it("should return correct color when chroma < 0.15", () => {
+ const { bd } = new LightModeTheme("oklch(0.85 0.1 60)").getColors();
+ expect(bd).toEqual("rgb(80.718% 72.709% 66.526%)");
+ });
+
+ it("should return correct color when hue is between 0 and 55", () => {
+ const { bd } = new LightModeTheme("oklch(0.85 0.1 30)").getColors();
+ expect(bd).toEqual("rgb(82.213% 71.61% 69.683%)");
+ });
+
+ it("should return correct color when hue > 340", () => {
+ const { bd } = new LightModeTheme("oklch(0.85 0.1 350)").getColors();
+ expect(bd).toEqual("rgb(81.085% 71.278% 75.495%)");
+ });
+});
+
+describe("bdNeutral color", () => {
+ it("should return correct color when chroma < 0.04", () => {
+ const { bd } = new LightModeTheme("oklch(0.45 0.03 60)").getColors();
+ expect(bd).toEqual("rgb(74.321% 74.321% 74.321%)");
+ });
+});
+
+describe("bdNeutralHover", () => {
+ it("should return correct color", () => {
+ const { bdNeutralHover } = new LightModeTheme(
+ "oklch(0.45 0.03 60)",
+ ).getColors();
+ expect(bdNeutralHover).toEqual("rgb(62.05% 62.05% 62.05%)");
+ });
+});
+
+describe("bdPositive", () => {
+ it("should return correct color", () => {
+ const { bdPositive } = new LightModeTheme(
+ "oklch(0.45 0.03 60)",
+ ).getColors();
+ expect(bdPositive).toEqual("rgb(6.7435% 63.436% 18.481%)");
+ });
+});
+
+describe("bdPositiveHover", () => {
+ it("should return correct color", () => {
+ const { bdPositiveHover } = new LightModeTheme(
+ "oklch(0.45 0.03 60)",
+ ).getColors();
+ expect(bdPositiveHover).toEqual("rgb(26.362% 76.094% 31.718%)");
+ });
+});
+
+describe("bdNegative", () => {
+ it("should return correct color", () => {
+ const { bdNegative } = new LightModeTheme(
+ "oklch(0.45 0.03 60)",
+ ).getColors();
+ expect(bdNegative).toEqual("rgb(83.108% 4.6651% 10.252%)");
+ });
+});
+
+describe("bdNegativeHover", () => {
+ it("should return correct color", () => {
+ const { bdNegativeHover } = new LightModeTheme(
+ "oklch(0.45 0.03 60)",
+ ).getColors();
+ expect(bdNegativeHover).toEqual("rgb(97.525% 25.712% 23.78%)");
+ });
+});
+
+describe("bdWarning", () => {
+ it("should return correct color", () => {
+ const { bdWarning } = new LightModeTheme("oklch(0.45 0.03 60)").getColors();
+ expect(bdWarning).toEqual("rgb(85.145% 64.66% 8.0286%)");
+ });
+});
+
+describe("bdWarningHover", () => {
+ it("should return correct color", () => {
+ const { bdWarningHover } = new LightModeTheme(
+ "oklch(0.45 0.03 60)",
+ ).getColors();
+ expect(bdWarningHover).toEqual("rgb(98.232% 77.293% 27.893%)");
+ });
+});
+
+describe("bdOnAccent", () => {
+ it("should return correct color", () => {
+ const { bdOnAccent } = new LightModeTheme(
+ "oklch(0.45 0.03 60)",
+ ).getColors();
+ expect(bdOnAccent).toEqual("rgb(5.2437% 1.364% 0%)");
+ });
+});
+
+describe("bdOnNeutral", () => {
+ it("should return correct color", () => {
+ const { bdOnNeutral } = new LightModeTheme(
+ "oklch(0.45 0.03 60)",
+ ).getColors();
+ expect(bdOnNeutral).toEqual("rgb(46.751% 46.751% 46.751%)");
+ });
+});
+
+describe("bdOnPositive", () => {
+ it("should return correct color", () => {
+ const { bdOnPositive } = new LightModeTheme(
+ "oklch(0.45 0.03 60)",
+ ).getColors();
+ expect(bdOnPositive).toEqual("rgb(0% 22.552% 3.6201%)");
+ });
+});
+
+describe("bdOnNegative", () => {
+ it("should return correct color", () => {
+ const { bdOnNegative } = new LightModeTheme(
+ "oklch(0.45 0.03 60)",
+ ).getColors();
+ expect(bdOnNegative).toEqual("rgb(21.923% 0% 2.8118%)");
+ });
+});
+
+describe("bdOnWarning", () => {
+ it("should return correct color", () => {
+ const { bdOnWarning } = new LightModeTheme(
+ "oklch(0.45 0.03 60)",
+ ).getColors();
+ expect(bdOnWarning).toEqual("rgb(39.972% 27.552% 0%)");
+ });
+});
|
dc1e2e124fe0b1c39026c71a2f4a13a5f99e90d6
|
2020-09-28 10:36:06
|
devrk96
|
fix: Light mode bugs (#724)
| false
|
Light mode bugs (#724)
|
fix
|
diff --git a/app/client/src/components/ads/Button.tsx b/app/client/src/components/ads/Button.tsx
index 94b41d35393d..3131abcf1181 100644
--- a/app/client/src/components/ads/Button.tsx
+++ b/app/client/src/components/ads/Button.tsx
@@ -221,7 +221,7 @@ const btnFontStyles = (props: ThemeProp & ButtonProps): BtnFontType => {
padding =
!props.text && props.icon
? `0px ${props.theme.spaces[1]}px`
- : `0px ${props.theme.spaces[6]}px`;
+ : `0px ${props.theme.spaces[3]}px`;
break;
case Size.medium:
buttonFont = mediumButton;
@@ -258,7 +258,7 @@ const StyledButton = styled("a")<ThemeProp & ButtonProps>`
padding: ${props => btnFontStyles(props).padding};
.${Classes.ICON} {
margin-right: ${props =>
- props.text && props.icon ? `${props.theme.spaces[4]}px` : `0`};
+ props.text && props.icon ? `${props.theme.spaces[2] - 1}px` : `0`};
path {
fill: ${props => btnColorStyles(props, "main").txtColor};
}
@@ -272,7 +272,7 @@ const StyledButton = styled("a")<ThemeProp & ButtonProps>`
props.isLoading || props.disabled ? `not-allowed` : `pointer`};
.${Classes.ICON} {
margin-right: ${props =>
- props.text && props.icon ? `${props.theme.spaces[4]}px` : `0`};
+ props.text && props.icon ? `${props.theme.spaces[2] - 1}px` : `0`};
path {
fill: ${props => btnColorStyles(props, "hover").txtColor};
}
diff --git a/app/client/src/components/ads/EditableText.tsx b/app/client/src/components/ads/EditableText.tsx
index 4a6c8426bb5e..4eabe3af465c 100644
--- a/app/client/src/components/ads/EditableText.tsx
+++ b/app/client/src/components/ads/EditableText.tsx
@@ -136,11 +136,18 @@ export const EditableText = (props: EditableTextProps) => {
const [savingState, setSavingState] = useState<SavingState>(
SavingState.NOT_STARTED,
);
+ const valueRef = React.useRef(props.defaultValue);
useEffect(() => {
setSavingState(props.savingState);
}, [props.savingState]);
+ useEffect(() => {
+ return () => {
+ props.onBlur(valueRef.current);
+ };
+ }, []);
+
useEffect(() => {
setValue(props.defaultValue);
setIsEditing(!!props.isEditingDefault);
@@ -169,18 +176,21 @@ export const EditableText = (props: EditableTextProps) => {
[props],
);
- const onConfirm = (_value: string) => {
- if (savingState === SavingState.ERROR || isInvalid) {
- setValue(lastValidValue);
- props.onBlur(lastValidValue);
- setSavingState(SavingState.NOT_STARTED);
- } else if (changeStarted) {
- props.onTextChanged(_value);
- props.onBlur(_value);
- }
- setIsEditing(false);
- setChangeStarted(false);
- };
+ const onConfirm = useCallback(
+ (_value: string) => {
+ if (savingState === SavingState.ERROR || isInvalid) {
+ setValue(lastValidValue);
+ props.onBlur(lastValidValue);
+ setSavingState(SavingState.NOT_STARTED);
+ } else if (changeStarted) {
+ props.onTextChanged(_value);
+ props.onBlur(_value);
+ }
+ setIsEditing(false);
+ setChangeStarted(false);
+ },
+ [changeStarted, lastValidValue, props.onBlur, props.onTextChanged],
+ );
const onInputchange = useCallback(
(_value: string) => {
@@ -189,12 +199,13 @@ export const EditableText = (props: EditableTextProps) => {
const error = errorMessage ? errorMessage : false;
if (!error) {
setLastValidValue(finalVal);
+ valueRef.current = finalVal;
}
setValue(finalVal);
setIsInvalid(error);
setChangeStarted(true);
},
- [props],
+ [props.isInvalid],
);
const iconName =
diff --git a/app/client/src/components/ads/RectangularSwitcher.tsx b/app/client/src/components/ads/RectangularSwitcher.tsx
index 506a0f0dca6c..b3349a05aebb 100644
--- a/app/client/src/components/ads/RectangularSwitcher.tsx
+++ b/app/client/src/components/ads/RectangularSwitcher.tsx
@@ -56,10 +56,6 @@ const StyledSwitch = styled.label<{
input:checked + .slider:before {
background-color: ${props => props.theme.colors.switch.hover.bg};
}
-
- input:hover + .slider {
- border: 1px solid ${props => props.theme.colors.switch.hover.border};
- }
`;
const Light = styled.div<{ value: boolean }>`
diff --git a/app/client/src/constants/DefaultTheme.tsx b/app/client/src/constants/DefaultTheme.tsx
index 8786f1fd7b8b..11997ab4ba46 100644
--- a/app/client/src/constants/DefaultTheme.tsx
+++ b/app/client/src/constants/DefaultTheme.tsx
@@ -457,7 +457,7 @@ const lightShades = [
"#FFFFFF",
] as const;
-type ColorPalette = typeof darkShades[number] | typeof lightShades[number];
+type ShadeColor = typeof darkShades[number] | typeof lightShades[number];
type buttonVariant = {
main: string;
@@ -469,7 +469,7 @@ type buttonVariant = {
type ColorType = {
button: {
- disabledText: ColorPalette;
+ disabledText: ShadeColor;
};
tertiary: buttonVariant;
info: buttonVariant;
@@ -480,162 +480,161 @@ type ColorType = {
card: {
hoverBG: Color;
hoverBGOpacity: number;
- hoverBorder: ColorPalette;
+ hoverBorder: ShadeColor;
targetBg: string;
- iconColor: ColorPalette;
+ iconColor: ShadeColor;
};
appCardColors: string[];
text: {
- normal: ColorPalette;
- heading: ColorPalette;
- hightlight: ColorPalette;
+ normal: ShadeColor;
+ heading: ShadeColor;
+ hightlight: ShadeColor;
};
icon: {
- normal: ColorPalette;
- hover: ColorPalette;
- active: ColorPalette;
+ normal: ShadeColor;
+ hover: ShadeColor;
+ active: ShadeColor;
};
appIcon: {
- normal: ColorPalette;
- background: ColorPalette;
+ normal: ShadeColor;
+ background: ShadeColor;
};
menu: {
- background: ColorPalette;
+ background: ShadeColor;
shadow: string;
};
menuItem: {
- normalText: ColorPalette;
- normalIcon: ColorPalette;
- hoverIcon: ColorPalette;
- hoverText: ColorPalette;
- hoverBg: ColorPalette;
+ normalText: ShadeColor;
+ normalIcon: ShadeColor;
+ hoverIcon: ShadeColor;
+ hoverText: ShadeColor;
+ hoverBg: ShadeColor;
};
colorSelector: {
- shadow: string;
- checkmark: ColorPalette;
+ shadow: ShadeColor;
+ checkmark: ShadeColor;
};
checkbox: {
- disabled: ColorPalette;
- unchecked: ColorPalette;
- disabledCheck: string;
- normalCheck: ColorPalette;
- labelColor: ColorPalette;
+ disabled: ShadeColor;
+ unchecked: ShadeColor;
+ disabledCheck: ShadeColor;
+ normalCheck: ShadeColor;
+ labelColor: ShadeColor;
};
dropdown: {
header: {
- text: ColorPalette;
- disabled: ColorPalette;
- bg: ColorPalette;
- disabledBg: ColorPalette;
+ text: ShadeColor;
+ disabled: ShadeColor;
+ bg: ShadeColor;
+ disabledBg: ShadeColor;
};
- menuBg: ColorPalette;
+ menuBg: ShadeColor;
menuShadow: string;
selected: {
- text: ColorPalette;
- bg: ColorPalette;
- icon: ColorPalette;
+ text: ShadeColor;
+ bg: ShadeColor;
+ icon: ShadeColor;
};
- icon: ColorPalette;
+ icon: ShadeColor;
};
toggle: {
- bg: ColorPalette;
+ bg: ShadeColor;
hover: {
on: string;
off: string;
};
disable: {
on: string;
- off: ColorPalette;
+ off: ShadeColor;
};
disabledSlider: {
- on: ColorPalette;
- off: string;
+ on: ShadeColor;
+ off: ShadeColor;
};
- spinner: ColorPalette;
+ spinner: ShadeColor;
};
textInput: {
disable: {
- bg: ColorPalette;
- text: ColorPalette;
- border: ColorPalette;
+ bg: ShadeColor;
+ text: ShadeColor;
+ border: ShadeColor;
};
normal: {
- bg: ColorPalette;
- text: ColorPalette;
- border: ColorPalette;
+ bg: ShadeColor;
+ text: ShadeColor;
+ border: ShadeColor;
};
- placeholder: ColorPalette;
+ placeholder: ShadeColor;
};
- menuBorder: ColorPalette;
+ menuBorder: ShadeColor;
editableText: {
- color: ColorPalette;
- bg: string;
+ color: ShadeColor;
+ bg: ShadeColor;
dangerBg: string;
};
radio: {
- disable: string;
- border: ColorPalette;
+ disable: ShadeColor;
+ border: ShadeColor;
};
searchInput: {
- placeholder: ColorPalette;
- text: ColorPalette;
- border: ColorPalette;
- bg: ColorPalette;
+ placeholder: ShadeColor;
+ text: ShadeColor;
+ border: ShadeColor;
+ bg: ShadeColor;
icon: {
- focused: ColorPalette;
- normal: ColorPalette;
+ focused: ShadeColor;
+ normal: ShadeColor;
};
};
- spinner: ColorPalette;
+ spinner: ShadeColor;
tableDropdown: {
- bg: ColorPalette;
- selectedBg: ColorPalette;
- selectedText: ColorPalette;
+ bg: ShadeColor;
+ selectedBg: ShadeColor;
+ selectedText: ShadeColor;
shadow: string;
};
tabs: {
- normal: ColorPalette;
- hover: ColorPalette;
- border: ColorPalette;
+ normal: ShadeColor;
+ hover: ShadeColor;
+ border: ShadeColor;
};
- settingHeading: ColorPalette;
+ settingHeading: ShadeColor;
table: {
- headerBg: ColorPalette;
- headerText: ColorPalette;
- rowData: ColorPalette;
- rowTitle: ColorPalette;
- border: ColorPalette;
+ headerBg: ShadeColor;
+ headerText: ShadeColor;
+ rowData: ShadeColor;
+ rowTitle: ShadeColor;
+ border: ShadeColor;
hover: {
- headerColor: ColorPalette;
- rowBg: ColorPalette;
- rowTitle: ColorPalette;
- rowData: ColorPalette;
+ headerColor: ShadeColor;
+ rowBg: ShadeColor;
+ rowTitle: ShadeColor;
+ rowData: ShadeColor;
};
};
applications: {
- bg: ColorPalette;
- textColor: ColorPalette;
- orgColor: ColorPalette;
- iconColor: ColorPalette;
+ bg: ShadeColor;
+ textColor: ShadeColor;
+ orgColor: ShadeColor;
+ iconColor: ShadeColor;
hover: {
- bg: ColorPalette;
- textColor: ColorPalette;
- orgColor: ColorPalette;
+ bg: ShadeColor;
+ textColor: ShadeColor;
+ orgColor: ShadeColor;
};
};
switch: {
- border: ColorPalette;
- bg: ColorPalette;
+ border: ShadeColor;
+ bg: ShadeColor;
hover: {
- border: ColorPalette;
- bg: ColorPalette;
+ bg: ShadeColor;
};
- lightText: ColorPalette;
- darkText: ColorPalette;
+ lightText: ShadeColor;
+ darkText: ShadeColor;
};
queryTemplate: {
- bg: ColorPalette;
- color: ColorPalette;
+ bg: ShadeColor;
+ color: ShadeColor;
};
profileDropdown: {
userName: ColorPalette;
@@ -726,13 +725,13 @@ export const dark: ColorType = {
hoverBg: darkShades[4],
},
colorSelector: {
- shadow: "#353535",
+ shadow: darkShades[4],
checkmark: darkShades[9],
},
checkbox: {
disabled: darkShades[3],
unchecked: darkShades[4],
- disabledCheck: "#565656",
+ disabledCheck: darkShades[5],
normalCheck: darkShades[9],
labelColor: darkShades[7],
},
@@ -764,7 +763,7 @@ export const dark: ColorType = {
},
disabledSlider: {
on: darkShades[9],
- off: "#565656",
+ off: darkShades[5],
},
spinner: darkShades[6],
},
@@ -788,7 +787,7 @@ export const dark: ColorType = {
dangerBg: "rgba(226, 44, 44, 0.08)",
},
radio: {
- disable: "#565656",
+ disable: darkShades[5],
border: darkShades[4],
},
searchInput: {
@@ -842,7 +841,6 @@ export const dark: ColorType = {
border: darkShades[5],
bg: darkShades[0],
hover: {
- border: darkShades[7],
bg: darkShades[0],
},
lightText: darkShades[9],
@@ -999,7 +997,7 @@ export const light: ColorType = {
menuBorder: lightShades[3],
editableText: {
color: lightShades[10],
- bg: "rgba(247, 247, 247, 0.8)",
+ bg: lightShades[2],
dangerBg: "rgba(242, 43, 43, 0.06)",
},
radio: {
@@ -1057,7 +1055,6 @@ export const light: ColorType = {
border: lightShades[5],
bg: lightShades[11],
hover: {
- border: lightShades[7],
bg: lightShades[11],
},
lightText: lightShades[11],
diff --git a/app/client/src/pages/Applications/ApplicationCard.tsx b/app/client/src/pages/Applications/ApplicationCard.tsx
index 10247c950f9e..6f736c899579 100644
--- a/app/client/src/pages/Applications/ApplicationCard.tsx
+++ b/app/client/src/pages/Applications/ApplicationCard.tsx
@@ -45,10 +45,11 @@ import { Classes as CsClasses } from "components/ads/common";
type NameWrapperProps = {
hasReadPermission: boolean;
showOverlay: boolean;
+ isMenuOpen: boolean;
};
const NameWrapper = styled((props: HTMLDivProps & NameWrapperProps) => (
- <div {...omit(props, ["hasReadPermission", "showOverlay"])} />
+ <div {...omit(props, ["hasReadPermission", "showOverlay", "isMenuOpen"])} />
))`
.bp3-card {
border-radius: 0;
@@ -80,7 +81,7 @@ const NameWrapper = styled((props: HTMLDivProps & NameWrapperProps) => (
& div.image-container {
background: ${
- props.hasReadPermission
+ props.hasReadPermission && !props.isMenuOpen
? getColorWithOpacity(
props.theme.colors.card.hoverBG,
props.theme.colors.card.hoverBGOpacity,
@@ -384,6 +385,7 @@ export const ApplicationCard = (props: ApplicationCardProps) => {
!isMenuOpen && setShowOverlay(false);
}}
hasReadPermission={hasReadPermission}
+ isMenuOpen={isMenuOpen}
className="t--application-card"
>
<Wrapper
@@ -412,7 +414,7 @@ export const ApplicationCard = (props: ApplicationCardProps) => {
/>
)} */}
- {hasEditPermission && (
+ {hasEditPermission && !isMenuOpen && (
<EditButton
text="Edit"
size={Size.medium}
@@ -422,15 +424,17 @@ export const ApplicationCard = (props: ApplicationCardProps) => {
href={editApplicationURL}
/>
)}
- <Button
- text="LAUNCH"
- size={Size.medium}
- category={Category.tertiary}
- className="t--application-view-link"
- icon={"rocket"}
- href={viewApplicationURL}
- fill
- />
+ {!isMenuOpen && (
+ <Button
+ text="LAUNCH"
+ size={Size.medium}
+ category={Category.tertiary}
+ className="t--application-view-link"
+ icon={"rocket"}
+ href={viewApplicationURL}
+ fill
+ />
+ )}
</Control>
</ApplicationImage>
</div>
diff --git a/app/client/src/pages/Applications/index.tsx b/app/client/src/pages/Applications/index.tsx
index 24ec19411a80..8b071eb0ca86 100644
--- a/app/client/src/pages/Applications/index.tsx
+++ b/app/client/src/pages/Applications/index.tsx
@@ -53,6 +53,7 @@ const OrgDropDown = styled.div`
${props => props.theme.spaces[4]}px;
font-size: ${props => props.theme.fontSizes[1]}px;
justify-content: space-between;
+ align-items: center;
`;
const ApplicationCardsWrapper = styled.div`
@@ -183,7 +184,7 @@ const NewWorkspaceWrapper = styled.div`
const ApplicationAddCardWrapper = styled(Card)`
display: flex;
flex-direction: column;
- // justify-content: center;
+ justify-content: center;
background: ${props => props.theme.colors.applications.bg};
align-items: center;
width: ${props => props.theme.card.minWidth}px;
@@ -192,8 +193,7 @@ const ApplicationAddCardWrapper = styled(Card)`
box-shadow: none;
border-radius: 0;
padding: 0;
- padding-top: 52px;
- margin: ${props => props.theme.spaces[11]}px
+ margin: ${props => props.theme.spaces[11] - 2}px
${props => props.theme.spaces[5]}px;
a {
display: block;
|
64ffb6ee7fc4abdbd36867584135474415a6193f
|
2023-06-02 16:38:30
|
Dipyaman Biswas
|
fix: add additional checks for super user form not not be submitted more than once (#23981)
| false
|
add additional checks for super user form not not be submitted more than once (#23981)
|
fix
|
diff --git a/app/client/src/pages/setup/SetupForm.tsx b/app/client/src/pages/setup/SetupForm.tsx
index 4c6e87fe7b6f..317104240363 100644
--- a/app/client/src/pages/setup/SetupForm.tsx
+++ b/app/client/src/pages/setup/SetupForm.tsx
@@ -117,6 +117,7 @@ function SetupForm(props: SetupFormProps) {
const [isFirstPage, setIsFirstPage] = useState(true);
const formRef = useRef<HTMLFormElement>(null);
const isAirgappedFlag = isAirgapped();
+ const [isSubmitted, setIsSubmitted] = useState(false);
const onSubmit = () => {
const form: HTMLFormElement = formRef.current as HTMLFormElement;
@@ -184,7 +185,7 @@ function SetupForm(props: SetupFormProps) {
return () => {
document.removeEventListener("keydown", onKeyDown);
};
- }, [props]);
+ }, [props, isSubmitted]);
const toggleFormPage = () => {
setIsFirstPage(!isFirstPage);
@@ -198,8 +199,10 @@ function SetupForm(props: SetupFormProps) {
// instead we move the user to the next page
toggleFormPage();
} else {
- // If we are on the second page we submit the form
- onSubmit();
+ // If we are on the second page we submit the form if not submitted already
+ if (!isSubmitted) onSubmit();
+ //if form is already submitted once do not submit it again
+ setIsSubmitted(true);
}
} else {
// The fields to be marked as touched so that we can display the errors
|
3209ad8cdf8da79268e7cd580c3c0f688e4f4dd7
|
2021-10-04 09:56:52
|
akash-codemonk
|
chore: Do not show initialLocation of map widget in an error state when field is blank (#7931)
| false
|
Do not show initialLocation of map widget in an error state when field is blank (#7931)
|
chore
|
diff --git a/app/client/src/widgets/MapWidget/widget/index.tsx b/app/client/src/widgets/MapWidget/widget/index.tsx
index d14a72c4d3f3..f6fe0efce41f 100644
--- a/app/client/src/widgets/MapWidget/widget/index.tsx
+++ b/app/client/src/widgets/MapWidget/widget/index.tsx
@@ -56,7 +56,6 @@ class MapWidget extends BaseWidget<MapWidgetProps, WidgetState> {
validation: {
type: ValidationTypes.OBJECT,
params: {
- required: true,
allowedKeys: [
{
name: "lat",
|
878d0178ca2ae5decd402ccef9ac8bd6cbb2d7cf
|
2023-10-17 17:32:05
|
akash-codemonk
|
chore: skip signposting discovery test (#27892)
| false
|
skip signposting discovery test (#27892)
|
chore
|
diff --git a/app/client/cypress/e2e/Regression/ClientSide/Onboarding/SignpostingDiscovery_spec.ts b/app/client/cypress/e2e/Regression/ClientSide/Onboarding/SignpostingDiscovery_spec.ts
deleted file mode 100644
index 386bdb92ec0c..000000000000
--- a/app/client/cypress/e2e/Regression/ClientSide/Onboarding/SignpostingDiscovery_spec.ts
+++ /dev/null
@@ -1,73 +0,0 @@
-import {
- agHelper,
- locators,
- entityExplorer,
- onboarding,
- draggableWidgets,
- dataSources,
- debuggerHelper,
-} from "../../../../support/Objects/ObjectsCore";
-import OneClickBindingLocator from "../../../../locators/OneClickBindingLocator";
-const OnboardingLocator = require("../../../../locators/FirstTimeUserOnboarding.json");
-import { featureFlagIntercept } from "../../../../support/Objects/FeatureFlags";
-
-describe("Signposting discovery", function () {
- beforeEach(() => {
- featureFlagIntercept(
- {
- ab_gif_signposting_enabled: true,
- },
- false,
- );
- cy.generateUUID().then((uid) => {
- cy.Signup(`${uid}@appsmithtest.com`, uid);
- });
- });
- it("1. Add datasource popup should be visible", function () {
- cy.get(OnboardingLocator.introModal).should("be.visible");
-
- // Create datasource
- cy.get(OnboardingLocator.checklistDatasourceBtn).click();
- agHelper.AssertElementVisibility(onboarding.locators.add_datasources);
- agHelper.AssertElementVisibility(locators._walkthrough_overlay);
- agHelper.GetNClick(onboarding.locators.add_datasources);
-
- // Create query
- dataSources.CreateDataSource("Postgres", true, false);
- agHelper.AssertElementVisibility(onboarding.locators.create_query);
- agHelper.AssertElementVisibility(locators._walkthrough_overlay);
- agHelper.GetNClick(onboarding.locators.create_query);
- agHelper.AssertElementVisibility(dataSources._runQueryBtn, true, 0, 20000);
-
- // Switch to widget pane
- agHelper.AssertElementVisibility(onboarding.locators.explorer_widget_tab);
- agHelper.Sleep();
- agHelper.AssertElementVisibility(locators._walkthrough_overlay);
- agHelper.GetNClick(onboarding.locators.explorer_widget_tab);
- agHelper.Sleep();
-
- // Drag and drop table widget
- agHelper.AssertElementVisibility(onboarding.locators.table_widget_card);
- agHelper.Sleep();
- agHelper.AssertElementVisibility(locators._walkthrough_overlay);
- entityExplorer.DragDropWidgetNVerify(
- draggableWidgets.TABLE,
- 500,
- 700,
- "",
- "",
- true,
- );
-
- // Connect data popup
- agHelper.AssertElementVisibility(onboarding.locators.connect_data_overlay);
- agHelper.AssertElementVisibility(locators._walkthrough_overlay);
- agHelper.GetNClick(onboarding.locators.connect_data_overlay, 0, true);
- agHelper.GetNClick(OneClickBindingLocator.datasourceQuerySelector());
-
- // Deploy button popup
- agHelper.AssertElementVisibility(onboarding.locators.deploy);
- agHelper.AssertElementVisibility(locators._walkthrough_overlay);
- agHelper.GetNClick(onboarding.locators.deploy);
- });
-});
diff --git a/app/client/src/ce/entities/FeatureFlag.ts b/app/client/src/ce/entities/FeatureFlag.ts
index 97070a73f04e..6e0670540a4e 100644
--- a/app/client/src/ce/entities/FeatureFlag.ts
+++ b/app/client/src/ce/entities/FeatureFlag.ts
@@ -13,7 +13,6 @@ export const FEATURE_FLAG = {
"release_table_serverside_filtering_enabled",
release_custom_echarts_enabled: "release_custom_echarts_enabled",
license_branding_enabled: "license_branding_enabled",
- ab_gif_signposting_enabled: "ab_gif_signposting_enabled",
release_git_status_lite_enabled: "release_git_status_lite_enabled",
license_sso_saml_enabled: "license_sso_saml_enabled",
license_sso_oidc_enabled: "license_sso_oidc_enabled",
@@ -42,7 +41,6 @@ export const DEFAULT_FEATURE_FLAG_VALUE: FeatureFlags = {
release_table_serverside_filtering_enabled: false,
release_custom_echarts_enabled: false,
license_branding_enabled: false,
- ab_gif_signposting_enabled: false,
release_git_status_lite_enabled: false,
license_sso_saml_enabled: false,
license_sso_oidc_enabled: false,
diff --git a/app/client/src/ce/selectors/featureFlagsSelectors.ts b/app/client/src/ce/selectors/featureFlagsSelectors.ts
index c45010bce7ae..004a15a8c005 100644
--- a/app/client/src/ce/selectors/featureFlagsSelectors.ts
+++ b/app/client/src/ce/selectors/featureFlagsSelectors.ts
@@ -1,4 +1,3 @@
-import { createSelector } from "reselect";
import type { AppState } from "@appsmith/reducers";
import type { FeatureFlag } from "@appsmith/entities/FeatureFlag";
@@ -16,10 +15,3 @@ export const selectFeatureFlagCheck = (
}
return false;
};
-
-export const adaptiveSignpostingEnabled = createSelector(
- selectFeatureFlags,
- (flags) => {
- return !!flags.ab_gif_signposting_enabled;
- },
-);
diff --git a/app/client/src/components/editorComponents/ActionRightPane/index.tsx b/app/client/src/components/editorComponents/ActionRightPane/index.tsx
index 4bdcfda2acb8..10a97933aea3 100644
--- a/app/client/src/components/editorComponents/ActionRightPane/index.tsx
+++ b/app/client/src/components/editorComponents/ActionRightPane/index.tsx
@@ -29,7 +29,6 @@ import {
SCHEMALESS_PLUGINS,
} from "pages/Editor/Explorer/Datasources/DatasourceStructureContainer";
import { DatasourceStructureContext } from "pages/Editor/Explorer/Datasources/DatasourceStructure";
-import { adaptiveSignpostingEnabled } from "@appsmith/selectors/featureFlagsSelectors";
import {
getDatasourceStructureById,
getIsFetchingDatasourceStructure,
@@ -49,8 +48,6 @@ import { getCurrentUser } from "selectors/usersSelectors";
import { Tooltip } from "design-system";
import { ASSETS_CDN_URL } from "constants/ThirdPartyConstants";
import { FEATURE_WALKTHROUGH_KEYS } from "constants/WalkthroughConstants";
-import { getIsFirstTimeUserOnboardingEnabled } from "selectors/onboardingSelectors";
-import { SignpostingWalkthroughConfig } from "pages/Editor/FirstTimeUserOnboarding/Utils";
import { getAssetUrl } from "@appsmith/utils/airgapHelpers";
import { useFeatureFlag } from "utils/hooks/useFeatureFlag";
import { FEATURE_FLAG } from "@appsmith/entities/FeatureFlag";
@@ -380,22 +377,6 @@ function ActionSidebar({
});
};
- const signpostingEnabled = useSelector(getIsFirstTimeUserOnboardingEnabled);
- const adaptiveSignposting = useSelector(adaptiveSignpostingEnabled);
- const checkAndShowBackToCanvasWalkthrough = async () => {
- const isFeatureWalkthroughShown = await getFeatureWalkthroughShown(
- FEATURE_WALKTHROUGH_KEYS.back_to_canvas,
- );
- !isFeatureWalkthroughShown &&
- pushFeature &&
- pushFeature(SignpostingWalkthroughConfig.BACK_TO_CANVAS);
- };
- useEffect(() => {
- if (!hasWidgets && adaptiveSignposting && signpostingEnabled) {
- checkAndShowBackToCanvasWalkthrough();
- }
- }, [hasWidgets, adaptiveSignposting, signpostingEnabled]);
-
const showSchema =
pluginDatasourceForm !== DatasourceComponentTypes.RestAPIDatasourceForm &&
!SCHEMALESS_PLUGINS.includes(pluginName);
diff --git a/app/client/src/pages/Editor/DataSourceEditor/NewActionButton.tsx b/app/client/src/pages/Editor/DataSourceEditor/NewActionButton.tsx
index e68bc46afd7b..193cf66fb9ed 100644
--- a/app/client/src/pages/Editor/DataSourceEditor/NewActionButton.tsx
+++ b/app/client/src/pages/Editor/DataSourceEditor/NewActionButton.tsx
@@ -1,4 +1,4 @@
-import React, { useCallback, useContext, useEffect, useState } from "react";
+import React, { useCallback, useState } from "react";
import { PluginType } from "entities/Action";
import { Button, toast } from "design-system";
import {
@@ -14,13 +14,6 @@ import type { Datasource } from "entities/Datasource";
import type { EventLocation } from "@appsmith/utils/analyticsUtilTypes";
import { noop } from "utils/AppsmithUtils";
import { getCurrentEnvironmentId } from "@appsmith/selectors/environmentSelectors";
-import WalkthroughContext from "components/featureWalkthrough/walkthroughContext";
-import { getIsFirstTimeUserOnboardingEnabled } from "selectors/onboardingSelectors";
-import { getFeatureWalkthroughShown } from "utils/storage";
-import { FEATURE_WALKTHROUGH_KEYS } from "constants/WalkthroughConstants";
-import { adaptiveSignpostingEnabled } from "@appsmith/selectors/featureFlagsSelectors";
-import { actionsExistInCurrentPage } from "@appsmith/selectors/entitiesSelector";
-import { SignpostingWalkthroughConfig } from "../FirstTimeUserOnboarding/Utils";
interface NewActionButtonProps {
datasource?: Datasource;
@@ -37,36 +30,9 @@ function NewActionButton(props: NewActionButtonProps) {
const [isSelected, setIsSelected] = useState(false);
const dispatch = useDispatch();
- const actionExist = useSelector(actionsExistInCurrentPage);
const currentPageId = useSelector(getCurrentPageId);
const currentEnvironment = useSelector(getCurrentEnvironmentId);
- const signpostingEnabled = useSelector(getIsFirstTimeUserOnboardingEnabled);
- const adapativeSignposting = useSelector(adaptiveSignpostingEnabled);
- const {
- isOpened: isWalkthroughOpened,
- popFeature,
- pushFeature,
- } = useContext(WalkthroughContext) || {};
- const closeWalkthrough = () => {
- if (isWalkthroughOpened && popFeature) {
- popFeature();
- }
- };
- useEffect(() => {
- if (adapativeSignposting && signpostingEnabled && !actionExist) {
- checkAndShowWalkthrough();
- }
- }, [actionExist, signpostingEnabled]);
- const checkAndShowWalkthrough = async () => {
- const isFeatureWalkthroughShown = await getFeatureWalkthroughShown(
- FEATURE_WALKTHROUGH_KEYS.create_query,
- );
- !isFeatureWalkthroughShown &&
- pushFeature &&
- pushFeature(SignpostingWalkthroughConfig.CREATE_A_QUERY);
- };
-
const createQueryAction = useCallback(
(e) => {
e?.stopPropagation();
@@ -84,9 +50,6 @@ function NewActionButton(props: NewActionButtonProps) {
return;
}
- // Close signposting walkthrough on click of create query button
- closeWalkthrough();
-
if (currentPageId) {
setIsSelected(true);
if (datasource) {
@@ -100,7 +63,7 @@ function NewActionButton(props: NewActionButtonProps) {
}
}
},
- [dispatch, currentPageId, datasource, pluginType, closeWalkthrough],
+ [dispatch, currentPageId, datasource, pluginType],
);
return (
diff --git a/app/client/src/pages/Editor/EditorHeader.tsx b/app/client/src/pages/Editor/EditorHeader.tsx
index c9933e3c666e..accb5fd1d0d2 100644
--- a/app/client/src/pages/Editor/EditorHeader.tsx
+++ b/app/client/src/pages/Editor/EditorHeader.tsx
@@ -1,9 +1,8 @@
-import React, { useCallback, useEffect, useState, useContext } from "react";
+import React, { useCallback, useEffect, useState } from "react";
import { ThemeProvider } from "styled-components";
import AppInviteUsersForm from "pages/workspace/AppInviteUsersForm";
import AnalyticsUtil from "utils/AnalyticsUtil";
import {
- getApplicationLastDeployedAt,
getCurrentApplicationId,
getCurrentPageId,
getIsPageSaving,
@@ -46,10 +45,7 @@ import ToggleModeButton from "pages/Editor/ToggleModeButton";
import { showConnectGitModal } from "actions/gitSyncActions";
import RealtimeAppEditors from "./RealtimeAppEditors";
import { EditorSaveIndicator } from "./EditorSaveIndicator";
-import {
- adaptiveSignpostingEnabled,
- selectFeatureFlags,
-} from "@appsmith/selectors/featureFlagsSelectors";
+import { selectFeatureFlags } from "@appsmith/selectors/featureFlagsSelectors";
import { fetchUsersForWorkspace } from "@appsmith/actions/workspaceActions";
import { getIsGitConnected } from "selectors/gitSyncSelectors";
@@ -73,14 +69,6 @@ import { getIsAppSettingsPaneWithNavigationTabOpen } from "selectors/appSettings
import type { NavigationSetting } from "constants/AppConstants";
import { getUserPreferenceFromStorage } from "@appsmith/utils/Environments";
import { showEnvironmentDeployInfoModal } from "@appsmith/actions/environmentAction";
-import {
- getIsFirstTimeUserOnboardingEnabled,
- isWidgetActionConnectionPresent,
-} from "selectors/onboardingSelectors";
-import WalkthroughContext from "components/featureWalkthrough/walkthroughContext";
-import { getFeatureWalkthroughShown } from "utils/storage";
-import { FEATURE_WALKTHROUGH_KEYS } from "constants/WalkthroughConstants";
-import { SignpostingWalkthroughConfig } from "./FirstTimeUserOnboarding/Utils";
import CommunityTemplatesPublishInfo from "./CommunityTemplates/Modals/CommunityTemplatesPublishInfo";
import PublishCommunityTemplateModal from "./CommunityTemplates/Modals/PublishCommunityTemplate";
import { useFeatureFlag } from "utils/hooks/useFeatureFlag";
@@ -92,6 +80,7 @@ import { Omnibar } from "./commons/Omnibar";
import { EditorShareButton } from "./EditorShareButton";
import { HelperBarInHeader } from "./HelpBarInHeader";
import { AppsmithLink } from "./AppsmithLink";
+import { getIsFirstTimeUserOnboardingEnabled } from "selectors/onboardingSelectors";
import { GetNavigationMenuData } from "./EditorName/NavigationMenuData";
const { cloudHosting } = getAppsmithConfigs();
@@ -196,8 +185,6 @@ export function EditorHeader() {
dispatch(showEnvironmentDeployInfoModal());
}
}
-
- closeWalkthrough();
},
[dispatch, handlePublish],
);
@@ -209,45 +196,9 @@ export function EditorHeader() {
}
}, [workspaceId]);
- const {
- isOpened: isWalkthroughOpened,
- popFeature,
- pushFeature,
- } = useContext(WalkthroughContext) || {};
- const adaptiveSignposting = useSelector(adaptiveSignpostingEnabled);
- const isConnectionPresent = useSelector(isWidgetActionConnectionPresent);
- const isDeployed = !!useSelector(getApplicationLastDeployedAt);
const isPrivateEmbedEnabled = useFeatureFlag(
FEATURE_FLAG.license_private_embeds_enabled,
);
- useEffect(() => {
- if (
- signpostingEnabled &&
- isConnectionPresent &&
- adaptiveSignposting &&
- !isDeployed
- ) {
- checkAndShowWalkthrough();
- }
- }, [
- signpostingEnabled,
- isConnectionPresent,
- adaptiveSignposting,
- isDeployed,
- ]);
- const closeWalkthrough = () => {
- if (popFeature && isWalkthroughOpened) {
- popFeature();
- }
- };
- const checkAndShowWalkthrough = async () => {
- const isFeatureWalkthroughShown = await getFeatureWalkthroughShown(
- FEATURE_WALKTHROUGH_KEYS.deploy,
- );
- !isFeatureWalkthroughShown &&
- pushFeature &&
- pushFeature(SignpostingWalkthroughConfig.DEPLOY_APP, true);
- };
const isGACEnabled = useFeatureFlag(FEATURE_FLAG.license_gac_enabled);
diff --git a/app/client/src/pages/Editor/Explorer/EntityExplorer.tsx b/app/client/src/pages/Editor/Explorer/EntityExplorer.tsx
index c6063b928b85..58c93c572ae9 100644
--- a/app/client/src/pages/Editor/Explorer/EntityExplorer.tsx
+++ b/app/client/src/pages/Editor/Explorer/EntityExplorer.tsx
@@ -1,4 +1,4 @@
-import React, { useRef, useCallback, useEffect, useContext } from "react";
+import React, { useRef, useCallback, useEffect } from "react";
import styled from "styled-components";
import { NonIdealState, Classes } from "@blueprintjs/core";
import JSDependencies from "./Libraries";
@@ -31,7 +31,6 @@ import {
saveExplorerStatus,
} from "@appsmith/pages/Editor/Explorer/helpers";
import { integrationEditorURL } from "@appsmith/RouteBuilder";
-import WalkthroughContext from "components/featureWalkthrough/walkthroughContext";
const NoEntityFoundSvg = importSvg(
async () => import("assets/svg/no_entities_found.svg"),
@@ -90,17 +89,9 @@ function EntityExplorer({ isActive }: { isActive: boolean }) {
dispatch(fetchWorkspace(currentWorkspaceId));
}, [currentWorkspaceId]);
- const { isOpened: isWalkthroughOpened, popFeature } =
- useContext(WalkthroughContext) || {};
const applicationId = useSelector(getCurrentApplicationId);
const isDatasourcesOpen = getExplorerStatus(applicationId, "datasource");
- const closeWalkthrough = useCallback(() => {
- if (isWalkthroughOpened && popFeature) {
- popFeature("EXPLORER_DATASOURCE_ADD");
- }
- }, [isWalkthroughOpened, popFeature]);
-
const addDatasource = useCallback(
(entryPoint: string) => {
history.push(
@@ -113,9 +104,8 @@ function EntityExplorer({ isActive }: { isActive: boolean }) {
AnalyticsUtil.logEvent("NAVIGATE_TO_CREATE_NEW_DATASOURCE_PAGE", {
entryPoint,
});
- closeWalkthrough();
},
- [pageId, closeWalkthrough],
+ [pageId],
);
const listDatasource = useCallback(() => {
diff --git a/app/client/src/pages/Editor/Explorer/index.tsx b/app/client/src/pages/Editor/Explorer/index.tsx
index 716f6ef1663d..25addf45528f 100644
--- a/app/client/src/pages/Editor/Explorer/index.tsx
+++ b/app/client/src/pages/Editor/Explorer/index.tsx
@@ -1,4 +1,4 @@
-import React, { useContext, useEffect } from "react";
+import React, { useEffect } from "react";
import { toggleInOnboardingWidgetSelection } from "actions/onboardingActions";
import { forceOpenWidgetPanel } from "actions/widgetSidebarActions";
import { SegmentedControl } from "design-system";
@@ -14,16 +14,7 @@ import history from "utils/history";
import EntityExplorer from "./EntityExplorer";
import { getExplorerSwitchIndex } from "selectors/editorContextSelectors";
import { setExplorerSwitchIndex } from "actions/editorContextActions";
-import { adaptiveSignpostingEnabled } from "@appsmith/selectors/featureFlagsSelectors";
import WidgetSidebarWithTags from "../WidgetSidebarWithTags";
-import WalkthroughContext from "components/featureWalkthrough/walkthroughContext";
-import { getFeatureWalkthroughShown } from "utils/storage";
-import { FEATURE_WALKTHROUGH_KEYS } from "constants/WalkthroughConstants";
-import {
- actionsExistInCurrentPage,
- widgetsExistCurrentPage,
-} from "@appsmith/selectors/entitiesSelector";
-import { SignpostingWalkthroughConfig } from "../FirstTimeUserOnboarding/Utils";
import { ExplorerWrapper } from "./Common/ExplorerWrapper";
const selectForceOpenWidgetPanel = (state: AppState) =>
@@ -81,53 +72,9 @@ function ExplorerContent() {
dispatch(toggleInOnboardingWidgetSelection(true));
}
}
-
- handleCloseWalkthrough();
};
const { value: activeOption } = options[activeSwitchIndex];
- const {
- isOpened: isWalkthroughOpened,
- popFeature,
- pushFeature,
- } = useContext(WalkthroughContext) || {};
-
- const handleCloseWalkthrough = () => {
- if (isWalkthroughOpened && popFeature) {
- popFeature();
- }
- };
- const signpostingEnabled = useSelector(getIsFirstTimeUserOnboardingEnabled);
- const adaptiveSignposting = useSelector(adaptiveSignpostingEnabled);
- const hasWidgets = useSelector(widgetsExistCurrentPage);
- const actionsExist = useSelector(actionsExistInCurrentPage);
- const checkAndShowSwitchWidgetWalkthrough = async () => {
- const isFeatureWalkthroughShown = await getFeatureWalkthroughShown(
- FEATURE_WALKTHROUGH_KEYS.switch_to_widget,
- );
- !isFeatureWalkthroughShown &&
- pushFeature &&
- pushFeature(SignpostingWalkthroughConfig.EXPLORER_WIDGET_TAB);
- };
-
- useEffect(() => {
- if (
- activeSwitchIndex === 0 &&
- signpostingEnabled &&
- !hasWidgets &&
- adaptiveSignposting &&
- actionsExist
- ) {
- checkAndShowSwitchWidgetWalkthrough();
- }
- }, [
- activeSwitchIndex,
- signpostingEnabled,
- hasWidgets,
- adaptiveSignposting,
- actionsExist,
- ]);
-
return (
<ExplorerWrapper>
<div
diff --git a/app/client/src/pages/Editor/FirstTimeUserOnboarding/Checklist.tsx b/app/client/src/pages/Editor/FirstTimeUserOnboarding/Checklist.tsx
index c82ab6a603b6..b133aa7723ec 100644
--- a/app/client/src/pages/Editor/FirstTimeUserOnboarding/Checklist.tsx
+++ b/app/client/src/pages/Editor/FirstTimeUserOnboarding/Checklist.tsx
@@ -1,4 +1,4 @@
-import React, { useContext, useEffect, useRef } from "react";
+import React, { useEffect, useRef } from "react";
import { Button, Divider, Text, Tooltip } from "design-system";
import styled from "styled-components";
import { useDispatch, useSelector } from "react-redux";
@@ -46,19 +46,13 @@ import {
import type { Datasource } from "entities/Datasource";
import type { ActionDataState } from "@appsmith/reducers/entityReducers/actionsReducer";
import type { CanvasWidgetsReduxState } from "reducers/entityReducers/canvasWidgetsReducer";
-import { SIGNPOSTING_STEP, SignpostingWalkthroughConfig } from "./Utils";
+import { SIGNPOSTING_STEP } from "./Utils";
import { builderURL, integrationEditorURL } from "@appsmith/RouteBuilder";
import { DatasourceCreateEntryPoints } from "constants/Datasource";
import classNames from "classnames";
import lazyLottie from "utils/lazyLottie";
import tickMarkAnimationURL from "assets/lottie/guided-tour-tick-mark.json.txt";
import { getAppsmithConfigs } from "@appsmith/configs";
-import WalkthroughContext from "components/featureWalkthrough/walkthroughContext";
-
-import { getFeatureWalkthroughShown } from "utils/storage";
-import { FEATURE_WALKTHROUGH_KEYS } from "constants/WalkthroughConstants";
-import { setExplorerSwitchIndex } from "actions/editorContextActions";
-import { adaptiveSignpostingEnabled } from "@appsmith/selectors/featureFlagsSelectors";
import { DOCS_BASE_URL } from "constants/ThirdPartyConstants";
const { intercomAppID } = getAppsmithConfigs();
@@ -368,9 +362,6 @@ export default function OnboardingChecklist() {
getFirstTimeUserOnboardingComplete,
);
- const { pushFeature } = useContext(WalkthroughContext) || {};
- const adapativeSignposting = useSelector(adaptiveSignpostingEnabled);
-
const onconnectYourWidget = () => {
const action = actions[0];
dispatch(showSignpostingModal(false));
@@ -447,26 +438,6 @@ export default function OnboardingChecklist() {
);
}
- const checkAndShowWalkthrough = async () => {
- const isFeatureWalkthroughShown = await getFeatureWalkthroughShown(
- FEATURE_WALKTHROUGH_KEYS.add_datasouce,
- );
-
- // Adding walkthrough tutorial
- if (!isFeatureWalkthroughShown) {
- dispatch(setExplorerSwitchIndex(0));
- pushFeature &&
- pushFeature(SignpostingWalkthroughConfig.CONNECT_A_DATASOURCE);
- } else {
- history.push(
- integrationEditorURL({
- pageId,
- selectedTab: INTEGRATION_TABS.NEW,
- }),
- );
- }
- };
-
return (
<>
<div className="flex-1">
@@ -523,16 +494,12 @@ export default function OnboardingChecklist() {
);
dispatch(showSignpostingModal(false));
- if (adapativeSignposting) {
- checkAndShowWalkthrough();
- } else {
- history.push(
- integrationEditorURL({
- pageId,
- selectedTab: INTEGRATION_TABS.NEW,
- }),
- );
- }
+ history.push(
+ integrationEditorURL({
+ pageId,
+ selectedTab: INTEGRATION_TABS.NEW,
+ }),
+ );
}}
step={SIGNPOSTING_STEP.CONNECT_A_DATASOURCE}
testid={"checklist-datasource"}
diff --git a/app/client/src/pages/Editor/FirstTimeUserOnboarding/Utils.ts b/app/client/src/pages/Editor/FirstTimeUserOnboarding/Utils.ts
index a1543f7e8323..b6cfa5ee4272 100644
--- a/app/client/src/pages/Editor/FirstTimeUserOnboarding/Utils.ts
+++ b/app/client/src/pages/Editor/FirstTimeUserOnboarding/Utils.ts
@@ -1,12 +1,7 @@
import { ReduxActionTypes } from "@appsmith/constants/ReduxActionConstants";
-import { getAssetUrl } from "@appsmith/utils/airgapHelpers";
-import type { FeatureParams } from "components/featureWalkthrough/walkthroughContext";
-import { ASSETS_CDN_URL } from "constants/ThirdPartyConstants";
-import { FEATURE_WALKTHROUGH_KEYS } from "constants/WalkthroughConstants";
import { APPLICATIONS_URL } from "constants/routes";
import type { Dispatch } from "react";
import history from "utils/history";
-import { setFeatureWalkthroughShown } from "utils/storage";
export const triggerWelcomeTour = (dispatch: Dispatch<any>) => {
history.push(APPLICATIONS_URL);
@@ -22,202 +17,3 @@ export enum SIGNPOSTING_STEP {
CONNECT_DATA_TO_WIDGET = "CONNECT_DATA_TO_WIDGET",
DEPLOY_APPLICATIONS = "DEPLOY_APPLICATIONS",
}
-
-export const SignpostingWalkthroughConfig: Record<string, FeatureParams> = {
- CONNECT_A_DATASOURCE: {
- targetId: "#add_datasources",
- details: {
- title: "Add New Datasource",
- description: "Datasources can be directly and easily accessed here",
- imageURL: getAssetUrl(`${ASSETS_CDN_URL}/create-datasource.gif`),
- },
- onDismiss: async () => {
- await setFeatureWalkthroughShown(
- FEATURE_WALKTHROUGH_KEYS.add_datasouce,
- true,
- );
- },
- overlayColor: "transparent",
- offset: {
- position: "right",
- top: -100,
- highlightPad: 5,
- indicatorLeft: -3,
- style: {
- transform: "none",
- boxShadow: "var(--ads-v2-shadow-popovers)",
- border: "1px solid var(--ads-v2-color-border-muted)",
- },
- },
- dismissOnOverlayClick: true,
- delay: 1000,
- },
- CREATE_A_QUERY: {
- targetId: "#create-query",
- details: {
- title: "Add New query",
- description:
- "A new query can be created using this button for this datasource",
- imageURL: getAssetUrl(`${ASSETS_CDN_URL}/create-new-query.gif`),
- },
- onDismiss: async () => {
- await setFeatureWalkthroughShown(
- FEATURE_WALKTHROUGH_KEYS.create_query,
- true,
- );
- },
- offset: {
- position: "bottom",
- highlightPad: 5,
- indicatorLeft: -3,
- left: -200,
- style: {
- transform: "none",
- boxShadow: "var(--ads-v2-shadow-popovers)",
- border: "1px solid var(--ads-v2-color-border-muted)",
- },
- },
- dismissOnOverlayClick: true,
- overlayColor: "transparent",
- delay: 1000,
- },
- BACK_TO_CANVAS: {
- targetId: "#back-to-canvas",
- onDismiss: async () => {
- await setFeatureWalkthroughShown(
- FEATURE_WALKTHROUGH_KEYS.back_to_canvas,
- true,
- );
- },
- details: {
- title: "Go back to canvas",
- description:
- "Go back to the canvas from here to start building the UI for your app using available widgets",
- imageURL: getAssetUrl(`${ASSETS_CDN_URL}/back-to-canvas.gif`),
- },
- offset: {
- position: "bottom",
- left: -200,
- highlightPad: 5,
- indicatorLeft: -3,
- style: {
- transform: "none",
- boxShadow: "var(--ads-v2-shadow-popovers)",
- border: "1px solid var(--ads-v2-color-border-muted)",
- },
- },
- delay: 1000,
- overlayColor: "transparent",
- dismissOnOverlayClick: true,
- },
- EXPLORER_WIDGET_TAB: {
- targetId: `#explorer-tab-options [data-value*="widgets"]`,
- details: {
- title: "Switch to Widgets section",
- description:
- "Segmented View in Entity Explorer enables swift switching between Explorer and Widgets. Select Widgets tab, then click on a widget to bind data",
- imageURL: getAssetUrl(`${ASSETS_CDN_URL}/switch-to-widget.gif`),
- },
- onDismiss: async () => {
- await setFeatureWalkthroughShown(
- FEATURE_WALKTHROUGH_KEYS.switch_to_widget,
- true,
- );
- },
- offset: {
- position: "right",
- highlightPad: 5,
- indicatorLeft: -3,
- style: {
- transform: "none",
- boxShadow: "var(--ads-v2-shadow-popovers)",
- border: "1px solid var(--ads-v2-color-border-muted)",
- },
- },
- dismissOnOverlayClick: true,
- overlayColor: "transparent",
- delay: 1000,
- },
- ADD_TABLE_WIDGET: {
- targetId: `#widget-card-draggable-tablewidgetv2`,
- details: {
- title: "Drag a widget on the canvas",
- description:
- "Drag and drop a table widget onto the canvas and then establish the connection with the Query you previously composed",
- imageURL: getAssetUrl(`${ASSETS_CDN_URL}/add-table-widget.gif`),
- },
- onDismiss: async () => {
- await setFeatureWalkthroughShown(
- FEATURE_WALKTHROUGH_KEYS.add_table_widget,
- true,
- );
- },
- offset: {
- position: "right",
- highlightPad: 5,
- indicatorLeft: -3,
- top: -200,
- style: {
- transform: "none",
- boxShadow: "var(--ads-v2-shadow-popovers)",
- border: "1px solid var(--ads-v2-color-border-muted)",
- },
- },
- delay: 1000,
- overlayColor: "transparent",
- dismissOnOverlayClick: true,
- },
- CONNECT_DATA: {
- targetId: `#table-overlay-connectdata`,
- details: {
- title: "Connect data",
- description:
- "Swiftly bind data to the widget by connecting your query with just a click of this button.",
- imageURL: `${ASSETS_CDN_URL}/connect-data.gif`,
- },
- onDismiss: async () => {
- await setFeatureWalkthroughShown(
- FEATURE_WALKTHROUGH_KEYS.connect_data,
- true,
- );
- },
- offset: {
- position: "right",
- highlightPad: 5,
- indicatorLeft: -3,
- style: {
- transform: "none",
- boxShadow: "var(--ads-v2-shadow-popovers)",
- border: "1px solid var(--ads-v2-color-border-muted)",
- },
- },
- dismissOnOverlayClick: true,
- overlayColor: "transparent",
- delay: 1000,
- },
- DEPLOY_APP: {
- targetId: `#application-publish-btn`,
- details: {
- title: "Deploy 🚀",
- description:
- "Use the deploy button to quickly launch and go live with your creation",
- },
- offset: {
- position: "bottom",
- highlightPad: 5,
- indicatorLeft: -3,
- left: -200,
- style: {
- transform: "none",
- boxShadow: "var(--ads-v2-shadow-popovers)",
- border: "1px solid var(--ads-v2-color-border-muted)",
- },
- },
- onDismiss: async () => {
- await setFeatureWalkthroughShown(FEATURE_WALKTHROUGH_KEYS.deploy, true);
- },
- overlayColor: "transparent",
- dismissOnOverlayClick: true,
- delay: 1000,
- },
-};
diff --git a/app/client/src/pages/Editor/WidgetCard.tsx b/app/client/src/pages/Editor/WidgetCard.tsx
index 5455824145fa..078ed73b9ae1 100644
--- a/app/client/src/pages/Editor/WidgetCard.tsx
+++ b/app/client/src/pages/Editor/WidgetCard.tsx
@@ -1,4 +1,4 @@
-import React, { useCallback, useContext } from "react";
+import React from "react";
import type { WidgetCardProps } from "widgets/BaseWidget";
import styled from "styled-components";
import { useWidgetDragResize } from "utils/hooks/dragResizeHooks";
@@ -7,7 +7,6 @@ import { generateReactKey } from "utils/generators";
import { useWidgetSelection } from "utils/hooks/useWidgetSelection";
import { IconWrapper } from "constants/IconConstants";
import { Text } from "design-system";
-import WalkthroughContext from "components/featureWalkthrough/walkthroughContext";
interface CardProps {
details: WidgetCardProps;
@@ -62,14 +61,6 @@ function WidgetCard(props: CardProps) {
const { setDraggingNewWidget } = useWidgetDragResize();
const { deselectAll } = useWidgetSelection();
- const { isOpened: isWalkthroughOpened, popFeature } =
- useContext(WalkthroughContext) || {};
- const closeWalkthrough = useCallback(() => {
- if (isWalkthroughOpened && popFeature) {
- popFeature();
- }
- }, [isWalkthroughOpened, popFeature]);
-
const onDragStart = (e: any) => {
e.preventDefault();
e.stopPropagation();
@@ -83,8 +74,6 @@ function WidgetCard(props: CardProps) {
widgetId: generateReactKey(),
});
deselectAll();
-
- closeWalkthrough();
};
const type = `${props.details.type.split("_").join("").toLowerCase()}`;
diff --git a/app/client/src/pages/Editor/WidgetSidebarWithTags.tsx b/app/client/src/pages/Editor/WidgetSidebarWithTags.tsx
index 8e69b9a7cbe1..a1b1c52d1783 100644
--- a/app/client/src/pages/Editor/WidgetSidebarWithTags.tsx
+++ b/app/client/src/pages/Editor/WidgetSidebarWithTags.tsx
@@ -1,4 +1,4 @@
-import React, { useContext, useEffect, useMemo, useRef, useState } from "react";
+import React, { useEffect, useMemo, useRef, useState } from "react";
import { useSelector } from "react-redux";
import WidgetCard from "./WidgetCard";
import { getWidgetCards } from "selectors/editorSelectors";
@@ -21,16 +21,6 @@ import {
SearchInput,
Text,
} from "design-system";
-import WalkthroughContext from "components/featureWalkthrough/walkthroughContext";
-import { getIsFirstTimeUserOnboardingEnabled } from "selectors/onboardingSelectors";
-import { adaptiveSignpostingEnabled } from "@appsmith/selectors/featureFlagsSelectors";
-import {
- actionsExistInCurrentPage,
- widgetsExistCurrentPage,
-} from "@appsmith/selectors/entitiesSelector";
-import { getFeatureWalkthroughShown } from "utils/storage";
-import { FEATURE_WALKTHROUGH_KEYS } from "constants/WalkthroughConstants";
-import { SignpostingWalkthroughConfig } from "./FirstTimeUserOnboarding/Utils";
function WidgetSidebarWithTags({ isActive }: { isActive: boolean }) {
const cards = useSelector(getWidgetCards);
@@ -90,37 +80,6 @@ function WidgetSidebarWithTags({ isActive }: { isActive: boolean }) {
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(() => {
- if (
- signpostingEnabled &&
- !hasWidgets &&
- actionsExist &&
- adaptiveSignposting &&
- isActive
- ) {
- checkAndShowTableWidgetWalkthrough();
- }
- }, [
- isActive,
- hasWidgets,
- signpostingEnabled,
- adaptiveSignposting,
- actionsExist,
- ]);
- const checkAndShowTableWidgetWalkthrough = async () => {
- const isFeatureWalkthroughShown = await getFeatureWalkthroughShown(
- FEATURE_WALKTHROUGH_KEYS.add_table_widget,
- );
- !isFeatureWalkthroughShown &&
- pushFeature &&
- pushFeature(SignpostingWalkthroughConfig.ADD_TABLE_WIDGET, true);
- };
-
return (
<div
className={`flex flex-col t--widget-sidebar overflow-hidden ${
diff --git a/app/client/src/widgets/ConnectDataOverlay.tsx b/app/client/src/widgets/ConnectDataOverlay.tsx
index 3daf0517ea93..e6086a9a718b 100644
--- a/app/client/src/widgets/ConnectDataOverlay.tsx
+++ b/app/client/src/widgets/ConnectDataOverlay.tsx
@@ -1,19 +1,8 @@
-import { adaptiveSignpostingEnabled } from "@appsmith/selectors/featureFlagsSelectors";
-import WalkthroughContext from "components/featureWalkthrough/walkthroughContext";
import { Colors } from "constants/Colors";
-import { FEATURE_WALKTHROUGH_KEYS } from "constants/WalkthroughConstants";
import { Button } from "design-system";
-import { SignpostingWalkthroughConfig } from "pages/Editor/FirstTimeUserOnboarding/Utils";
-import React, { useContext, useEffect } from "react";
-import { useSelector } from "react-redux";
-import { actionsExistInCurrentPage } from "@appsmith/selectors/entitiesSelector";
-import {
- getIsFirstTimeUserOnboardingEnabled,
- isWidgetActionConnectionPresent,
-} from "selectors/onboardingSelectors";
+import React from "react";
import styled from "styled-components";
-import { getFeatureWalkthroughShown } from "utils/storage";
const Wrapper = styled.div`
position: absolute;
@@ -57,49 +46,8 @@ export function ConnectDataOverlay(props: {
message: string;
btnText: string;
}) {
- const {
- isOpened: isWalkthroughOpened,
- popFeature,
- pushFeature,
- } = useContext(WalkthroughContext) || {};
- const signpostingEnabled = useSelector(getIsFirstTimeUserOnboardingEnabled);
- const adaptiveSignposting = useSelector(adaptiveSignpostingEnabled);
- const actionsExist = useSelector(actionsExistInCurrentPage);
- const isConnectionPresent = useSelector(isWidgetActionConnectionPresent);
-
- useEffect(() => {
- if (
- signpostingEnabled &&
- adaptiveSignposting &&
- !isConnectionPresent &&
- actionsExist
- ) {
- checkAndShowWalkthrough();
- }
- }, [
- signpostingEnabled,
- adaptiveSignposting,
- isConnectionPresent,
- actionsExist,
- ]);
- const closeWalkthrough = () => {
- if (popFeature && isWalkthroughOpened) {
- popFeature();
- }
- };
- const checkAndShowWalkthrough = async () => {
- const isFeatureWalkthroughShown = await getFeatureWalkthroughShown(
- FEATURE_WALKTHROUGH_KEYS.connect_data,
- );
- !isFeatureWalkthroughShown &&
- pushFeature &&
- pushFeature(SignpostingWalkthroughConfig.CONNECT_DATA, true);
- };
-
const onClick = () => {
props.onConnectData();
-
- closeWalkthrough();
};
return (
|
9406439bbb3a5dcbc8926ec7116d3b1ff98a2aed
|
2024-04-23 12:51:22
|
Abhijeet
|
chore: Add separate DTO class for projection and move CustomNewActionRepo method to NewActionRepo class (#32818)
| false
|
Add separate DTO class for projection and move CustomNewActionRepo method to NewActionRepo class (#32818)
|
chore
|
diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/newactions/projections/IdAndDatasourceIdNewActionView.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/newactions/projections/IdAndDatasourceIdNewActionView.java
new file mode 100644
index 000000000000..47d6deb943d6
--- /dev/null
+++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/newactions/projections/IdAndDatasourceIdNewActionView.java
@@ -0,0 +1,34 @@
+package com.appsmith.server.newactions.projections;
+
+import lombok.Getter;
+
+/**
+ * This projection is used to fetch only the id and datasource id of an action.
+ * <p>
+ * Nested projections are not working with JPA projections using interfaces because of a limitation in the way that
+ * Spring Data JPA handles projections. When you use an interface to define a projection, Spring Data JPA creates a
+ * dynamic proxy for the interface. This proxy is used to intercept calls to the getter methods on the interface and
+ * return the appropriate data from the database.
+ * However, when you try to use a nested projection, Spring Data JPA cannot create a dynamic proxy for the nested
+ * projection interface. This is because the nested projection interface is not a top-level interface. As a result,
+ * Spring Data JPA cannot intercept calls to the getter methods on the nested projection interface and return the
+ * appropriate data from the database.
+ * To work around this limitation, you can define the nested projection as a static inner class of the top-level.
+ * </p>
+ */
+@Getter
+public class IdAndDatasourceIdNewActionView {
+
+ String id;
+ ActionDTODatasourceView unpublishedAction;
+
+ @Getter
+ public static class ActionDTODatasourceView {
+ DatasourceIdView datasource;
+ }
+
+ @Getter
+ public static class DatasourceIdView {
+ String id;
+ }
+}
diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/NewActionRepositoryCE.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/NewActionRepositoryCE.java
index 524c587a2665..ec4934e3a808 100644
--- a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/NewActionRepositoryCE.java
+++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/NewActionRepositoryCE.java
@@ -1,6 +1,7 @@
package com.appsmith.server.repositories.ce;
import com.appsmith.server.domains.NewAction;
+import com.appsmith.server.newactions.projections.IdAndDatasourceIdNewActionView;
import com.appsmith.server.projections.IdPoliciesOnly;
import com.appsmith.server.repositories.BaseRepository;
import com.appsmith.server.repositories.CustomNewActionRepository;
@@ -21,4 +22,6 @@ public interface NewActionRepositoryCE extends BaseRepository<NewAction, String>
Mono<Long> countByDeletedAtNull();
Flux<IdPoliciesOnly> findIdsAndPoliciesByApplicationIdIn(List<String> applicationIds);
+
+ Flux<IdAndDatasourceIdNewActionView> findIdAndDatasourceIdByApplicationIdIn(List<String> applicationIds);
}
diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/ApplicationPageServiceCEImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/ApplicationPageServiceCEImpl.java
index 2f59c63b8f26..0f2abfcc1cd3 100644
--- a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/ApplicationPageServiceCEImpl.java
+++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/ApplicationPageServiceCEImpl.java
@@ -1527,9 +1527,8 @@ private Mono<Boolean> validateAllObjectsForPermissions(
private Mono<Boolean> validateDatasourcesForCreatePermission(Mono<Application> applicationMono) {
Flux<BaseDomain> datasourceFlux = applicationMono
- .flatMapMany(application -> newActionRepository.findAllByApplicationIdsWithoutPermission(
- List.of(application.getId()),
- List.of(NewAction.Fields.id, NewAction.Fields.unpublishedAction_datasource_id)))
+ .flatMapMany(application ->
+ newActionRepository.findIdAndDatasourceIdByApplicationIdIn(List.of(application.getId())))
.collectList()
.map(actions -> {
return actions.stream()
|
93cd24eb826f15ff60800d5dd5dd17d533e3b59b
|
2023-06-13 17:39:40
|
rahulramesha
|
fix: Disallow copying of individual tabs in tab widget (#24205)
| false
|
Disallow copying of individual tabs in tab widget (#24205)
|
fix
|
diff --git a/app/client/cypress/e2e/Regression/ClientSide/Widgets/WidgetCopyPaste_spec.js b/app/client/cypress/e2e/Regression/ClientSide/Widgets/WidgetCopyPaste_spec.js
index 5fad8ddacbd4..402eeb5e2d18 100644
--- a/app/client/cypress/e2e/Regression/ClientSide/Widgets/WidgetCopyPaste_spec.js
+++ b/app/client/cypress/e2e/Regression/ClientSide/Widgets/WidgetCopyPaste_spec.js
@@ -145,4 +145,22 @@ describe("Widget Copy paste", function () {
//verify a pasted list widget
cy.get(widgetsPage.listWidgetv2).should("have.length", 1);
});
+
+ it("8. Should not be able to copy/cut canvas widgets (i.e. Individual Tabs) of tabs widget", function () {
+ _.entityExplorer.AddNewPage("New blank page");
+
+ _.entityExplorer.DragDropWidgetNVerify(_.draggableWidgets.TAB, 400, 200);
+
+ _.entityExplorer.SelectEntityByName("Tab 1", "Tabs1");
+
+ cy.get("body").type(`{${modifierKey}}{c}`);
+
+ _.agHelper.ValidateToastMessage("This selected widget cannot be copied.");
+
+ _.agHelper.WaitUntilAllToastsDisappear();
+
+ cy.get("body").type(`{${modifierKey}}{x}`);
+
+ _.agHelper.ValidateToastMessage("This selected widget cannot be cut.");
+ });
});
diff --git a/app/client/src/sagas/WidgetOperationSagas.tsx b/app/client/src/sagas/WidgetOperationSagas.tsx
index 324c4481342f..e3180f7cc734 100644
--- a/app/client/src/sagas/WidgetOperationSagas.tsx
+++ b/app/client/src/sagas/WidgetOperationSagas.tsx
@@ -942,7 +942,12 @@ function* copyWidgetSaga(action: ReduxAction<{ isShortcut: boolean }>) {
}
const allAllowedToCopy = selectedWidgets.some((each) => {
- return allWidgets[each] && !allWidgets[each].disallowCopy;
+ //should not allow canvas widgets to be copied
+ return (
+ allWidgets[each] &&
+ !allWidgets[each].disallowCopy &&
+ allWidgets[each].type !== "CANVAS_WIDGET"
+ );
});
if (!allAllowedToCopy) {
@@ -1896,7 +1901,12 @@ function* cutWidgetSaga() {
}
const allAllowedToCut = selectedWidgets.some((each) => {
- return allWidgets[each] && !allWidgets[each].disallowCopy;
+ //should not allow canvas widgets to be cut
+ return (
+ allWidgets[each] &&
+ !allWidgets[each].disallowCopy &&
+ allWidgets[each].type !== "CANVAS_WIDGET"
+ );
});
if (!allAllowedToCut) {
|
3ce5a7a7cfb51a5d3da7cda9a77e1d60d117b894
|
2023-03-17 14:29:23
|
Nilesh Sarupriya
|
chore: add utility to check if a permission is for an entity (#21514)
| false
|
add utility to check if a permission is for an entity (#21514)
|
chore
|
diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/acl/AclPermission.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/acl/AclPermission.java
index 611efb1e7a17..371e24b12ac4 100644
--- a/app/server/appsmith-server/src/main/java/com/appsmith/server/acl/AclPermission.java
+++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/acl/AclPermission.java
@@ -3,8 +3,11 @@
import com.appsmith.external.models.BaseDomain;
import com.appsmith.external.models.Datasource;
import com.appsmith.server.domains.Action;
+import com.appsmith.server.domains.ActionCollection;
import com.appsmith.server.domains.Application;
import com.appsmith.server.domains.Config;
+import com.appsmith.server.domains.NewAction;
+import com.appsmith.server.domains.NewPage;
import com.appsmith.server.domains.Page;
import com.appsmith.server.domains.PermissionGroup;
import com.appsmith.server.domains.Tenant;
@@ -134,4 +137,21 @@ public static AclPermission getPermissionByValue(String value, Class<? extends B
}
return null;
}
+
+ public static boolean isPermissionForEntity(AclPermission aclPermission, Class clazz) {
+ Class entityClass = clazz;
+ /*
+ * Action class has been deprecated, and we have started using NewAction class instead.
+ * Page class has been deprecated, and we have started using NewPage class instead.
+ * NewAction and ActionCollection are similar entities w.r.t. AclPermissions.
+ * Hence, whenever we want to check for any Permission w.r.t. NewAction or Action Collection, we use Action, and
+ * whenever we want to check for any Permission w.r.t. NewPage, we use Page.
+ */
+ if (entityClass.equals(NewAction.class) || entityClass.equals(ActionCollection.class)) {
+ entityClass = Action.class;
+ } else if (entityClass.equals(NewPage.class)) {
+ entityClass = Page.class;
+ }
+ return aclPermission.getEntity().equals(entityClass);
+ }
}
diff --git a/app/server/appsmith-server/src/test/java/com/appsmith/server/acl/AclPermissionTest.java b/app/server/appsmith-server/src/test/java/com/appsmith/server/acl/AclPermissionTest.java
new file mode 100644
index 000000000000..7e44b54384c0
--- /dev/null
+++ b/app/server/appsmith-server/src/test/java/com/appsmith/server/acl/AclPermissionTest.java
@@ -0,0 +1,34 @@
+package com.appsmith.server.acl;
+
+import com.appsmith.server.domains.Action;
+import com.appsmith.server.domains.ActionCollection;
+import com.appsmith.server.domains.Application;
+import com.appsmith.server.domains.NewAction;
+import com.appsmith.server.domains.NewPage;
+import com.appsmith.server.domains.Page;
+import com.appsmith.server.domains.Theme;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
+import org.springframework.test.context.junit.jupiter.SpringExtension;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+@ExtendWith(SpringExtension.class)
+class AclPermissionTest {
+
+ @Test
+ void testIsPermissionForEntity() {
+ assertThat(AclPermission.isPermissionForEntity(AclPermission.READ_APPLICATIONS, Application.class)).isTrue();
+ assertThat(AclPermission.isPermissionForEntity(AclPermission.READ_APPLICATIONS, Theme.class)).isFalse();
+
+
+ // Assert that Action related Permission should return True, when checked against Action, NewAction and Action Collection.
+ assertThat(AclPermission.isPermissionForEntity(AclPermission.MANAGE_ACTIONS, Action.class)).isTrue();
+ assertThat(AclPermission.isPermissionForEntity(AclPermission.MANAGE_ACTIONS, NewAction.class)).isTrue();
+ assertThat(AclPermission.isPermissionForEntity(AclPermission.MANAGE_ACTIONS, ActionCollection.class)).isTrue();
+
+ // Assert that Page related Permission should return True, when checked against Page and NewPage.
+ assertThat(AclPermission.isPermissionForEntity(AclPermission.MANAGE_PAGES, Page.class)).isTrue();
+ assertThat(AclPermission.isPermissionForEntity(AclPermission.MANAGE_PAGES, NewPage.class)).isTrue();
+ }
+}
\ No newline at end of file
|
68bca33a5556859ab652b5a6bc14a6478ee17492
|
2022-04-12 17:03:35
|
arunvjn
|
fix: broken checklist onboarding flow (#12822)
| false
|
broken checklist onboarding flow (#12822)
|
fix
|
diff --git a/app/client/src/pages/Editor/MainContainer.tsx b/app/client/src/pages/Editor/MainContainer.tsx
index 9fd1a5739122..f4f48a09e4d9 100644
--- a/app/client/src/pages/Editor/MainContainer.tsx
+++ b/app/client/src/pages/Editor/MainContainer.tsx
@@ -9,12 +9,7 @@ import BottomBar from "./BottomBar";
import { DEFAULT_ENTITY_EXPLORER_WIDTH } from "constants/AppConstants";
import WidgetsEditor from "./WidgetsEditor";
import { updateExplorerWidthAction } from "actions/explorerActions";
-import {
- BUILDER_CHECKLIST_PATH,
- BUILDER_PATH,
- BUILDER_PATH_DEPRECATED,
-} from "constants/routes";
-import OnboardingChecklist from "./FirstTimeUserOnboarding/Checklist";
+import { BUILDER_PATH, BUILDER_PATH_DEPRECATED } from "constants/routes";
import EntityExplorerSidebar from "components/editorComponents/Sidebar";
import classNames from "classnames";
import { previewModeSelector } from "selectors/editorSelectors";
@@ -74,11 +69,6 @@ function MainContainer() {
exact
path={BUILDER_PATH_DEPRECATED}
/>
- <SentryRoute
- component={OnboardingChecklist}
- exact
- path={BUILDER_CHECKLIST_PATH}
- />
<SentryRoute component={EditorsRouter} />
</Switch>
</div>
diff --git a/app/client/src/pages/Editor/routes.tsx b/app/client/src/pages/Editor/routes.tsx
index 7757413dc2ed..8b4ce13f94a0 100644
--- a/app/client/src/pages/Editor/routes.tsx
+++ b/app/client/src/pages/Editor/routes.tsx
@@ -22,6 +22,7 @@ import {
GENERATE_TEMPLATE_PATH,
GENERATE_TEMPLATE_FORM_PATH,
matchBuilderPath,
+ BUILDER_CHECKLIST_PATH,
} from "constants/routes";
import styled from "styled-components";
import { useShowPropertyPane } from "utils/hooks/dragResizeHooks";
@@ -37,6 +38,7 @@ import { useWidgetSelection } from "utils/hooks/useWidgetSelection";
import PagesEditor from "./PagesEditor";
import { builderURL } from "RouteBuilder";
import history from "utils/history";
+import OnboardingChecklist from "./FirstTimeUserOnboarding/Checklist";
const Wrapper = styled.div<{ isVisible: boolean }>`
position: absolute;
@@ -97,6 +99,11 @@ function EditorsRouter() {
exact
path={`${path}${INTEGRATION_EDITOR_PATH}`}
/>
+ <SentryRoute
+ component={OnboardingChecklist}
+ exact
+ path={`${path}${BUILDER_CHECKLIST_PATH}`}
+ />
<SentryRoute
component={ApiEditor}
exact
diff --git a/app/client/src/sagas/js_snippets.json b/app/client/src/sagas/js_snippets.json
deleted file mode 100644
index ee893dadea47..000000000000
--- a/app/client/src/sagas/js_snippets.json
+++ /dev/null
@@ -1,765 +0,0 @@
-[
- {
- "entities": [
- "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}};});",
- "isTrigger": false,
- "args": [
- {
- "name": "data",
- "type": "OBJECT_ARRAY"
- },
- {
- "name": "key",
- "type": "TEXT"
- },
- {
- "name": "value",
- "type": "VAR"
- }
- ],
- "summary": "Merge data from two entities into a single response"
- }
- },
- {
- "entities": [
- "LIST_WIDGET",
- "TABLE_WIDGET"
- ],
- "language": "javascript",
- "dataType": "STRING",
- "fields": [],
- "body": {
- "snippetMeta": "",
- "shortTitle": "",
- "title": "Access attributes from a nested data",
- "template": "{{your_object}}.{{key}}",
- "args": [
- {
- "name": "your_object",
- "type": "OBJECT"
- },
- {
- "name": "key",
- "type": "VAR"
- }
- ],
- "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.",
- "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_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,
- "args": [
- {
- "name": "columnValue1",
- "type": "TEXT"
- },
- {
- "name": "color1",
- "type": "TEXT"
- },
- {
- "name": "columnValue2",
- "type": "TEXT"
- },
- {
- "name": "color2",
- "type": "TEXT"
- },
- {
- "name": "tableName",
- "type": "TEXT"
- },
- {
- "name": "columnName",
- "type": "TEXT"
- }
- ],
- "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.",
- "snippet": "//Javascript for Cell Background or Text Color property\n(function columnColor() {let colors = {\"True\": \"green\",\"False\": \"Red\"};return colors[currentRow[\"status\"]];})()"
- }
- },
- {
- "entities": [
- "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": [
- {
- "type": "ARRAY",
- "name": "your_array"
- },
- {
- "type": "VAR",
- "name": "Obj1"
- },
- {
- "type": "VAR",
- "name": "Obj2"
- }
- ],
- "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.",
- "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_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.",
- "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_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,
- "args": [
- {
- "name": "your_array",
- "type": "ARRAY"
- }
- ],
- "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.",
- "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": [
- "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,
- "args": [
- {
- "name": "queryData",
- "type": "OBJECT_ARRAY"
- },
- {
- "name": "attribute1",
- "type": "VAR"
- },
- {
- "name": "attribute2",
- "type": "VAR"
- }
- ],
- "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 }>`",
- "snippet": "(function () {let skills = [\"strength\",\"speed\",\"durability\",\"agility\",\"reflexes\"];let options_list = skills.map((item) => {return { label: item, value: item, };});return options_list;})()"
- }
- },
- {
- "entities": [
- "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": [
- {
- "type": "string",
- "name": "selectBox"
- },
- {
- "type": "string",
- "name": "value"
- },
- {
- "type": "string",
- "name": "QueryOne"
- },
- {
- "type": "string",
- "name": "QueryTwo"
- }
- ],
- "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.",
- "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_WIDGET"
- ],
- "language": "javascript",
- "dataType": "STRING",
- "fields": [],
- "body": {
- "snippetMeta": "",
- "shortTitle": "",
- "title": "Setting default value of checkbox based on a query",
- "template": "{{query}}.{{key}}",
- "isTrigger": false,
- "args": [
- {
- "name": "query",
- "type": "OBJECT"
- },
- {
- "name": "key",
- "type": "VAR"
- }
- ],
- "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.",
- "snippet": "function() {let iron_man = { hero: \"Iron Man\", team: \"Avengers\", skills: \"Superhuman strength\", status: true, };return iron_man.status; }()"
- }
- },
- {
- "entities": [
- "DATEPICKER_WIDGET"
- ],
- "language": "javascript",
- "dataType": "STRING",
- "fields": [],
- "body": {
- "snippetMeta": "",
- "shortTitle": "",
- "title": "Select current date in the date picker widget",
- "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. "
- }
- },
- {
- "entities": [
- "DATEPICKER_WIDGET"
- ],
- "language": "javascript",
- "dataType": "STRING",
- "fields": [],
- "body": {
- "snippetMeta": "",
- "shortTitle": "",
- "title": "Formatting date inside the data picker widget",
- "template": "moment({{date}}).format({{dateFormat}})",
- "args": [
- {
- "name": "date",
- "type": "TEXT"
- },
- {
- "name": "dateFormat",
- "type": "TEXT"
- }
- ],
- "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.",
- "snippet": "moment(\"2021-06-28 12:28:33 PM\").format(\"LL\")"
- }
- },
- {
- "entities": [
- "TEXT_WIDGET"
- ],
- "language": "javascript",
- "dataType": "STRING",
- "fields": [],
- "body": {
- "snippetMeta": "",
- "shortTitle": "",
- "title": "Binding current time in the text widget",
- "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."
- }
- },
- {
- "entities": [
- "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,
- "args": [
- {
- "name": "my_object",
- "type": "OBJECT"
- }
- ],
- "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.",
- "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_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.",
- "snippet": "(function(){let invoice_total = 120;let text = `The total amount on the invoice is ${invoice_total}`;return text;})()"
- }
- },
- {
- "entities": [
- "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,
- "args": [
- {
- "name": "query1",
- "type": "OBJECT"
- },
- {
- "name": "successMessage",
- "type": "TEXT"
- },
- {
- "name": "key",
- "type": "TEXT"
- },
- {
- "name": "queryData",
- "type": "VAR"
- },
- {
- "name": "pageName",
- "type": "TEXT"
- }
- ],
- "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.",
- "snippet": "getUsers.run(() => {showAlert(\"Query Executed\", \"info\");storeValue(\"name\", getUsers.data[0].name);navigateTo(\"#Page2\"));});"
- }
- },
- {
- "entities": [
- "modal",
- "workflow"
- ],
- "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,
- "args": [
- {
- "name": "modalName",
- "type": "TEXT"
- },
- {
- "name": "query",
- "type": "VAR"
- }
- ],
- "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.",
- "snippet": "showModal('Modal1');getUsers.run()"
- }
- },
- {
- "entities": [
- "modal",
- "workflow"
- ],
- "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,
- "args": [
- {
- "name": "query",
- "type": "VAR"
- },
- {
- "name": "modalName",
- "type": "TEXT"
- },
- {
- "name": "alertMessage",
- "type": "TEXT"
- }
- ],
- "summary": "",
- "snippet": "getUsers.run(() => {closeModal(\"Modal1\");showAlert(\"Success\");})"
- }
- },
- {
- "entities": [
- "action",
- "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,
- "args": [
- {
- "name": "query1",
- "type": "VAR"
- },
- {
- "name": "query2",
- "type": "VAR"
- },
- {
- "name": "query3",
- "type": "VAR"
- }
- ],
- "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.",
- "snippet": "getAvengers.run(() => getLeague.run(() => getRangers.run()));"
- }
- },
- {
- "entities": [
- "action",
- "BUTTON_WIDGET",
- "workflow"
- ],
- "language": "javascript",
- "dataType": "FUNCTION",
- "fields": [],
- "body": {
- "snippetMeta": "",
- "shortTitle": "",
- "title": "Running multiple queries in parallel",
- "template": "{{query1}}.run();{{query2}}.run();",
- "isTrigger": true,
- "args": [
- {
- "name": "query1",
- "type": "VAR"
- },
- {
- "name": "query2",
- "type": "VAR"
- }
- ],
- "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.",
- "snippet": "getAvengers.run(); getLeague.run();"
- }
- },
- {
- "entities": [
- "action",
- "workflow"
- ],
- "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,
- "args": [
- {
- "name": "query1",
- "type": "VAR"
- },
- {
- "name": "query2",
- "type": "VAR"
- },
- {
- "name": "successMessage",
- "type": "TEXT"
- },
- {
- "name": "errorMessage",
- "type": "TEXT"
- }
- ],
- "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.",
- "snippet": "updateUsers.run(() => {fetchUsers.run(() => {showAlert(\"User Updated\"); },() => showAlert(\"Fetch Users Failed\") );},() => showAlert(\"Update User Failed\", \"error\"));"
- }
- },
- {
- "entities": [
- "datasource",
- "postgres"
- ],
- "language": "sql",
- "dataType": "STRING",
- "fields": [],
- "body": {
- "snippetMeta": "",
- "shortTitle": "",
- "title": "Query data from Postgres table",
- "snippet": "SELECT * FROM table_name",
- "isTrigger": false,
- "args": [
- {
- "name": "table_name",
- "type": "string"
- }
- ],
- "summary": "To query the entire table data in postgres database, you can use the asterisk (*) in the SELECT clause, which is a shorthand for all column."
- }
- },
- {
- "entities": [
- "datasource",
- "postgres"
- ],
- "language": "sql",
- "dataType": "STRING",
- "fields": [],
- "body": {
- "snippetMeta": "",
- "shortTitle": "",
- "title": "PostgreSQL SELECT statement to query data from multiple columns",
- "snippet": "SELECT column1, column2, column3 FROM table_name",
- "isTrigger": false,
- "args": [
- {
- "name": "column1",
- "type": "string"
- },
- {
- "name": "column2",
- "type": "string"
- },
- {
- "name": "column3",
- "type": "string"
- },
- {
- "name": "table_name",
- "type": "string"
- }
- ],
- "summary": "When using Potgres as datasource, and you just want to know the first name, last name and email of customers, you can specify these column names in the SELECT clause."
- }
- },
- {
- "entities": [
- "datasource",
- "postgres"
- ],
- "language": "sql",
- "dataType": "STRING",
- "fields": [],
- "body": {
- "snippetMeta": "",
- "shortTitle": "",
- "title": "PostgreSQL SELECT statement to query data from one column",
- "snippet": "SELECT column_name FROM table_name",
- "isTrigger": false,
- "args": [
- {
- "name": "column_name",
- "type": "string"
- },
- {
- "name": "table_name",
- "type": "string"
- }
- ],
- "summary": "When using Postgres as datasource, and you just want to know the first name, last name and email of customers, you can specify these column names in the SELECT clause."
- }
- },
- {
- "entities": [
- "datasource",
- "postgres"
- ],
- "language": "sql",
- "dataType": "STRING",
- "fields": [],
- "body": {
- "snippetMeta": "",
- "shortTitle": "",
- "title": "Ordering table data in ascending order",
- "snippet": "SELECT column1, column2 FROM table_name ORDER BY column1 ASC;",
- "examples": [
- {
- "title": "",
- "code": "SELECT column1, column2 FROM table_name ORDER BY column1 ASC;",
- "summary": ""
- }
- ],
- "isTrigger": false,
- "args": [
- {
- "name": "column1",
- "type": "string"
- },
- {
- "name": "column2",
- "type": "string"
- },
- {
- "name": "table_name",
- "type": "string"
- }
- ],
- "summary": "When you query data from a table, the SELECT statement returns rows in an unspecified order. To sort the rows (ascending) of the result set, you use the ORDER BY and set ASC clause in the SELECT statement."
- }
- },
- {
- "entities": [
- "datasource",
- "postgres"
- ],
- "language": "sql",
- "dataType": "STRING",
- "fields": [],
- "body": {
- "snippetMeta": "",
- "shortTitle": "",
- "title": "Ordering table data in descending order",
- "snippet": "SELECT column1, column2 FROM table_name ORDER BY column1 DESC;",
- "examples": [
- {
- "title": "",
- "code": "SELECT column1, column2 FROM table_name ORDER BY column1 DESC;",
- "summary": ""
- }
- ],
- "isTrigger": false,
- "args": [
- {
- "name": "column1",
- "type": "string"
- },
- {
- "name": "column2",
- "type": "string"
- },
- {
- "name": "table_name",
- "type": "string"
- }
- ],
- "summary": "When you query data from a table, the SELECT statement returns rows in an unspecified order. To sort the rows (ascending) of the result set, you use the ORDER BY and set DESC clause in the SELECT statement."
- }
- },
- {
- "entities": [
- "postgres",
- "datasource"
- ],
- "language": "sql",
- "dataType": "STRING",
- "fields": [],
- "body": {
- "snippetMeta": "",
- "shortTitle": "",
- "title": "Ordering table data based on the length of column value",
- "snippet": "SELECT column1, LENGTH(column1) len FROM table_name ORDER BY len DESC;",
- "examples": [
- {
- "title": "",
- "code": "SELECT column1, LENGTH(column1) len FROM table_name ORDER BY len DESC;",
- "summary": ""
- }
- ],
- "isTrigger": false,
- "args": [
- {
- "name": "column1",
- "type": "string"
- },
- {
- "name": "table_name",
- "type": "string"
- }
- ],
- "summary": "If you want to sorts the rows by the lengths of the values in any column, you can use the LENGTH() function. This accepts a string and returns the length of the string."
- }
- }
-]
\ No newline at end of file
|
a46c7311790c0f8a68bc2ea28ada67333e9d8a88
|
2024-07-17 16:14:37
|
Anna Hariprasad
|
feat: add clear all option to columns field in google sheets plugin (#34620)
| false
|
add clear all option to columns field in google sheets plugin (#34620)
|
feat
|
diff --git a/app/client/src/components/formControls/DropDownControl.test.tsx b/app/client/src/components/formControls/DropDownControl.test.tsx
new file mode 100644
index 000000000000..c603988e15b4
--- /dev/null
+++ b/app/client/src/components/formControls/DropDownControl.test.tsx
@@ -0,0 +1,114 @@
+import React from "react";
+import { render, screen, waitFor, fireEvent } from "test/testUtils";
+import DropDownControl from "./DropDownControl";
+import { reduxForm } from "redux-form";
+import "@testing-library/jest-dom";
+import { Provider } from "react-redux";
+import configureStore from "redux-mock-store";
+
+const mockStore = configureStore([]);
+
+const initialValues = {
+ actionConfiguration: {
+ testPath: ["option1", "option2"],
+ },
+};
+
+function TestForm(props: any) {
+ return <div>{props.children}</div>;
+}
+
+const ReduxFormDecorator = reduxForm({
+ form: "TestForm",
+ initialValues,
+})(TestForm);
+
+const mockOptions = [
+ { label: "Option 1", value: "option1", children: "Option 1" },
+ { label: "Option 2", value: "option2", children: "Option 2" },
+ { label: "Option 3", value: "option3", children: "Option 3" },
+];
+
+const mockAction = {
+ type: "API_ACTION",
+ name: "Test API Action",
+ datasource: {
+ id: "datasource1",
+ name: "Datasource 1",
+ },
+ actionConfiguration: {
+ body: "",
+ headers: [],
+ testPath: ["option1", "option2"],
+ },
+};
+
+const dropDownProps = {
+ options: mockOptions,
+ placeholderText: "Select Columns",
+ isMultiSelect: true,
+ configProperty: "actionConfiguration.testPath",
+ controlType: "PROJECTION",
+ propertyValue: "",
+ label: "Columns",
+ id: "column",
+ formName: "",
+ isValid: true,
+ formValues: mockAction,
+ isLoading: false,
+};
+
+describe("DropDownControl", () => {
+ let store: any;
+
+ beforeEach(() => {
+ store = mockStore({
+ form: {
+ TestForm: {
+ values: initialValues,
+ },
+ },
+ appState: {},
+ });
+ });
+ it("should renders dropdownControl and options properly", async () => {
+ render(
+ <Provider store={store}>
+ <ReduxFormDecorator>
+ <DropDownControl {...dropDownProps} />
+ </ReduxFormDecorator>
+ </Provider>,
+ );
+
+ const dropdownSelect = await waitFor(async () =>
+ screen.findByTestId("t--dropdown-actionConfiguration.testPath"),
+ );
+
+ expect(dropdownSelect).toBeInTheDocument();
+
+ const options = screen.getAllByText(/Optio.../);
+ const optionCount = options.length;
+ expect(optionCount).toBe(2);
+ });
+
+ it("should clear all selected options", async () => {
+ render(
+ <Provider store={store}>
+ <ReduxFormDecorator>
+ <DropDownControl {...dropDownProps} />
+ </ReduxFormDecorator>
+ </Provider>,
+ );
+
+ const clearAllButton = document.querySelector(".rc-select-clear");
+
+ expect(clearAllButton).toBeInTheDocument();
+
+ fireEvent.click(clearAllButton!);
+
+ await waitFor(() => {
+ const options = screen.queryAllByText(/Option.../);
+ expect(options.length).toBe(0);
+ });
+ });
+});
diff --git a/app/client/src/components/formControls/DropDownControl.tsx b/app/client/src/components/formControls/DropDownControl.tsx
index ca24c9555e67..239fdaa2898c 100644
--- a/app/client/src/components/formControls/DropDownControl.tsx
+++ b/app/client/src/components/formControls/DropDownControl.tsx
@@ -185,6 +185,20 @@ function renderDropdown(
}
};
+ const clearAllOptions = () => {
+ if (!isNil(selectedValue)) {
+ if (props.isMultiSelect) {
+ if (Array.isArray(selectedValue)) {
+ selectedValue = [];
+ props.input?.onChange([]);
+ }
+ } else {
+ selectedValue = "";
+ props.input?.onChange("");
+ }
+ }
+ };
+
if (props.options.length > 0) {
if (props.isMultiSelect) {
const tempSelectedValues: string[] = [];
@@ -233,11 +247,13 @@ function renderDropdown(
return (
<Select
+ allowClear={props.isMultiSelect && !isEmpty(selectedValue)}
data-testid={`t--dropdown-${props?.configProperty}`}
defaultValue={props.initialValue}
isDisabled={props.disabled}
isLoading={props.isLoading}
isMultiSelect={props?.isMultiSelect}
+ onClear={clearAllOptions}
onDeselect={onRemoveOptions}
onSelect={(value) => onSelectOptions(value)}
placeholder={props?.placeholderText}
|
aa773f6950dc0689daf3bc1cc42bea89584c1de9
|
2024-06-25 13:03:36
|
Shrikant Sharat Kandula
|
chore: Strict payloads for update action and gen template API (#34446)
| false
|
Strict payloads for update action and gen template API (#34446)
|
chore
|
diff --git a/app/client/src/api/ActionAPI.tsx b/app/client/src/api/ActionAPI.tsx
index 4e16158c3c32..5097ac4efa3c 100644
--- a/app/client/src/api/ActionAPI.tsx
+++ b/app/client/src/api/ActionAPI.tsx
@@ -171,20 +171,28 @@ class ActionAPI extends API {
ActionAPI.apiUpdateCancelTokenSource.cancel();
}
ActionAPI.apiUpdateCancelTokenSource = axios.CancelToken.source();
- const action: Partial<Action & { entityReferenceType: unknown }> = {
+ const payload: Partial<Action & { entityReferenceType: unknown }> = {
...apiConfig,
name: undefined,
entityReferenceType: undefined,
- };
- if (action.datasource != null) {
- action.datasource = {
- ...(action as any).datasource,
+ actionConfiguration: apiConfig.actionConfiguration && {
+ ...apiConfig.actionConfiguration,
+ autoGeneratedHeaders:
+ apiConfig.actionConfiguration.autoGeneratedHeaders?.map(
+ (header: any) => ({
+ ...header,
+ isInvalid: undefined,
+ }),
+ ) ?? undefined,
+ },
+ datasource: apiConfig.datasource && {
+ ...(apiConfig as any).datasource,
datasourceStorages: undefined,
isValid: undefined,
new: undefined,
- };
- }
- return API.put(`${ActionAPI.url}/${action.id}`, action, undefined, {
+ },
+ };
+ return API.put(`${ActionAPI.url}/${apiConfig.id}`, payload, undefined, {
cancelToken: ActionAPI.apiUpdateCancelTokenSource.token,
});
}
@@ -228,7 +236,19 @@ class ActionAPI extends API {
}
static async moveAction(moveRequest: MoveActionRequest) {
- return API.put(ActionAPI.url + "/move", moveRequest, undefined, {
+ const payload = {
+ ...moveRequest,
+ action: moveRequest.action && {
+ ...moveRequest.action,
+ entityReferenceType: undefined,
+ datasource: moveRequest.action.datasource && {
+ ...moveRequest.action.datasource,
+ isValid: undefined,
+ new: undefined,
+ },
+ },
+ };
+ return API.put(ActionAPI.url + "/move", payload, undefined, {
timeout: DEFAULT_EXECUTE_ACTION_TIMEOUT_MS,
});
}
diff --git a/app/client/src/api/AppThemingApi.tsx b/app/client/src/api/AppThemingApi.tsx
index 695c5b258307..e5d8c7e908a8 100644
--- a/app/client/src/api/AppThemingApi.tsx
+++ b/app/client/src/api/AppThemingApi.tsx
@@ -45,9 +45,13 @@ class AppThemingApi extends API {
applicationId: string,
theme: AppTheme,
): Promise<AxiosPromise<ApiResponse<AppTheme[]>>> {
+ const payload = {
+ ...theme,
+ new: undefined,
+ };
return API.put(
`${AppThemingApi.baseUrl}/themes/applications/${applicationId}`,
- theme,
+ payload,
);
}
diff --git a/app/client/src/api/PageApi.tsx b/app/client/src/api/PageApi.tsx
index fdb81b344f07..8aeedfac9c8f 100644
--- a/app/client/src/api/PageApi.tsx
+++ b/app/client/src/api/PageApi.tsx
@@ -262,10 +262,14 @@ class PageApi extends Api {
static async generateTemplatePage(
request: GenerateTemplatePageRequest,
): Promise<AxiosPromise<ApiResponse>> {
+ const payload = {
+ ...request,
+ pageId: undefined,
+ };
if (request.pageId) {
- return Api.put(PageApi.getGenerateTemplateURL(request.pageId), request);
+ return Api.put(PageApi.getGenerateTemplateURL(request.pageId), payload);
} else {
- return Api.post(PageApi.getGenerateTemplateURL(), request);
+ return Api.post(PageApi.getGenerateTemplateURL(), payload);
}
}
|
cb84bc68c57c3cba4d9a3b70d5d52540ee6b91d0
|
2022-09-16 19:50:29
|
Keyur Paralkar
|
fix: chart widget color fontfamily (#16750)
| false
|
chart widget color fontfamily (#16750)
|
fix
|
diff --git a/app/client/src/constants/WidgetConstants.tsx b/app/client/src/constants/WidgetConstants.tsx
index f81fec6dfb59..f454b3bd780b 100644
--- a/app/client/src/constants/WidgetConstants.tsx
+++ b/app/client/src/constants/WidgetConstants.tsx
@@ -70,7 +70,7 @@ export const layoutConfigurations: LayoutConfigurations = {
FLUID: { minWidth: -1, maxWidth: -1 },
};
-export const LATEST_PAGE_VERSION = 61;
+export const LATEST_PAGE_VERSION = 62;
export const GridDefaults = {
DEFAULT_CELL_SIZE: 1,
diff --git a/app/client/src/utils/DSLMigration.test.ts b/app/client/src/utils/DSLMigration.test.ts
new file mode 100644
index 000000000000..31663e6848fa
--- /dev/null
+++ b/app/client/src/utils/DSLMigration.test.ts
@@ -0,0 +1,698 @@
+import { WidgetProps } from "widgets/BaseWidget";
+import { ContainerWidgetProps } from "widgets/ContainerWidget/widget";
+import * as DSLMigrations from "./DSLMigrations";
+import * as chartWidgetReskinningMigrations from "./migrations/ChartWidgetReskinningMigrations";
+import * as tableMigrations from "./migrations/TableWidget";
+import * as IncorrectDynamicBindingPathLists from "./migrations/IncorrectDynamicBindingPathLists";
+import * as TextStyleFromTextWidget from "./migrations/TextWidget";
+import * as MenuButtonWidgetButtonProperties from "./migrations/MenuButtonWidget";
+import * as modalMigration from "./migrations/ModalWidget";
+import * as mapWidgetMigration from "./migrations/MapWidget";
+import * as checkboxMigration from "./migrations/CheckboxGroupWidget";
+import * as buttonWidgetMigrations from "./migrations/ButtonWidgetMigrations";
+import * as phoneInputMigration from "./migrations/PhoneInputWidgetMigrations";
+import * as inputCurrencyMigration from "./migrations/CurrencyInputWidgetMigrations";
+import * as radioGroupMigration from "./migrations/RadioGroupWidget";
+import * as propertyPaneMigrations from "./migrations/PropertyPaneMigrations";
+import * as themingMigration from "./migrations/ThemingMigrations";
+import { LATEST_PAGE_VERSION } from "constants/WidgetConstants";
+import { originalDSLForDSLMigrations } from "./testDSLs";
+
+type Migration = {
+ functionLookup: {
+ moduleObj: any;
+ functionName: string;
+ }[];
+ version: number | undefined;
+};
+
+/**
+ * Migrations is an array of objects, were each object has
+ * - moduleObj: A namespace import that includes all the exported function present in the module. Refer to line 3.
+ * - functionName: Name of the migration function to spyOn
+ * - version: The DSL version in which the function is executing
+ *
+ * Migrations will be used to construct mockFnObj object where mockFnObj's key is the version and value is an array of jest mock functions.
+ *
+ * NOTE:
+ * - In Migrations the sequence of object should exactly match the sequence that is present in the transformDSL function.
+ *
+ * - For cases were migration is skipped, we include them in Migrations.
+ * Simply add the object with functionLookup and version of the skipped migration.
+ * Refer to the skippedMigration50 object inside Migrations
+ */
+const migrations: Migration[] = [
+ {
+ functionLookup: [
+ {
+ moduleObj: DSLMigrations,
+ functionName: "calculateDynamicHeight",
+ },
+ ],
+ version: undefined,
+ },
+ {
+ functionLookup: [
+ {
+ moduleObj: DSLMigrations,
+ functionName: "updateContainers",
+ },
+ ],
+ version: 1,
+ },
+ {
+ functionLookup: [
+ {
+ moduleObj: DSLMigrations,
+ functionName: "chartDataMigration",
+ },
+ ],
+ version: 2,
+ },
+ {
+ functionLookup: [
+ {
+ moduleObj: DSLMigrations,
+ functionName: "mapDataMigration",
+ },
+ ],
+ version: 3,
+ },
+ {
+ functionLookup: [
+ {
+ moduleObj: DSLMigrations,
+ functionName: "singleChartDataMigration",
+ },
+ ],
+ version: 4,
+ },
+ {
+ functionLookup: [
+ {
+ moduleObj: DSLMigrations,
+ functionName: "tabsWidgetTabsPropertyMigration",
+ },
+ ],
+ version: 5,
+ },
+ {
+ functionLookup: [
+ {
+ moduleObj: DSLMigrations,
+ functionName: "dynamicPathListMigration",
+ },
+ ],
+ version: 6,
+ },
+ {
+ functionLookup: [
+ {
+ moduleObj: DSLMigrations,
+ functionName: "canvasNameConflictMigration",
+ },
+ ],
+ version: 7,
+ },
+ {
+ functionLookup: [
+ {
+ moduleObj: DSLMigrations,
+ functionName: "renamedCanvasNameConflictMigration",
+ },
+ ],
+ version: 8,
+ },
+ {
+ functionLookup: [
+ {
+ moduleObj: tableMigrations,
+ functionName: "tableWidgetPropertyPaneMigrations",
+ },
+ ],
+ version: 9,
+ },
+ {
+ functionLookup: [
+ {
+ moduleObj: DSLMigrations,
+ functionName: "addVersionNumberMigration",
+ },
+ ],
+ version: 10,
+ },
+ {
+ functionLookup: [
+ {
+ moduleObj: tableMigrations,
+ functionName: "migrateTablePrimaryColumnsBindings",
+ },
+ ],
+ version: 11,
+ },
+ {
+ functionLookup: [
+ {
+ moduleObj: IncorrectDynamicBindingPathLists,
+ functionName: "migrateIncorrectDynamicBindingPathLists",
+ },
+ ],
+ version: 12,
+ },
+ {
+ functionLookup: [
+ {
+ moduleObj: DSLMigrations,
+ functionName: "migrateOldChartData",
+ },
+ ],
+ version: 13,
+ },
+ {
+ functionLookup: [
+ {
+ moduleObj: DSLMigrations,
+ functionName: "rteDefaultValueMigration",
+ },
+ ],
+ version: 14,
+ },
+ {
+ functionLookup: [
+ {
+ moduleObj: TextStyleFromTextWidget,
+ functionName: "migrateTextStyleFromTextWidget",
+ },
+ ],
+ version: 15,
+ },
+ {
+ functionLookup: [
+ {
+ moduleObj: DSLMigrations,
+ functionName: "migrateChartDataFromArrayToObject",
+ },
+ ],
+ version: 16,
+ },
+ {
+ functionLookup: [
+ {
+ moduleObj: DSLMigrations,
+ functionName: "migrateTabsData",
+ },
+ ],
+ version: 17,
+ },
+ {
+ functionLookup: [
+ {
+ moduleObj: DSLMigrations,
+ functionName: "migrateInitialValues",
+ },
+ ],
+ version: 18,
+ },
+ {
+ functionLookup: [
+ {
+ moduleObj: DSLMigrations,
+ functionName: "migrateToNewLayout",
+ },
+ ],
+ version: 19,
+ },
+ {
+ functionLookup: [
+ {
+ moduleObj: DSLMigrations,
+ functionName: "migrateNewlyAddedTabsWidgetsMissingData",
+ },
+ ],
+ version: 20,
+ },
+ {
+ functionLookup: [
+ {
+ moduleObj: DSLMigrations,
+ functionName: "migrateWidgetsWithoutLeftRightColumns",
+ },
+ {
+ moduleObj: DSLMigrations,
+ functionName: "migrateOverFlowingTabsWidgets",
+ },
+ ],
+ version: 21,
+ },
+ {
+ functionLookup: [
+ {
+ moduleObj: tableMigrations,
+ functionName: "migrateTableWidgetParentRowSpaceProperty",
+ },
+ ],
+ version: 22,
+ },
+ {
+ functionLookup: [
+ {
+ moduleObj: DSLMigrations,
+ functionName: "addLogBlackListToAllListWidgetChildren",
+ },
+ ],
+ version: 23,
+ },
+ {
+ functionLookup: [
+ {
+ moduleObj: tableMigrations,
+ functionName: "migrateTableWidgetHeaderVisibilityProperties",
+ },
+ ],
+ version: 24,
+ },
+ {
+ functionLookup: [
+ {
+ moduleObj: DSLMigrations,
+ functionName: "migrateItemsToListDataInListWidget",
+ },
+ ],
+ version: 25,
+ },
+ {
+ functionLookup: [
+ {
+ moduleObj: DSLMigrations,
+ functionName: "migrateDatePickerMinMaxDate",
+ },
+ ],
+ version: 26,
+ },
+ {
+ functionLookup: [
+ {
+ moduleObj: DSLMigrations,
+ functionName: "migrateFilterValueForDropDownWidget",
+ },
+ ],
+ version: 27,
+ },
+ {
+ functionLookup: [
+ {
+ moduleObj: tableMigrations,
+ functionName: "migrateTablePrimaryColumnsComputedValue",
+ },
+ ],
+ version: 28,
+ },
+ {
+ functionLookup: [
+ {
+ moduleObj: DSLMigrations,
+ functionName: "migrateToNewMultiSelect",
+ },
+ ],
+ version: 29,
+ },
+ {
+ functionLookup: [
+ {
+ moduleObj: tableMigrations,
+ functionName: "migrateTableWidgetDelimiterProperties",
+ },
+ ],
+ version: 30,
+ },
+ {
+ functionLookup: [
+ {
+ moduleObj: DSLMigrations,
+ functionName: "migrateIsDisabledToButtonColumn",
+ },
+ ],
+ version: 31,
+ },
+ {
+ functionLookup: [
+ {
+ moduleObj: DSLMigrations,
+ functionName: "migrateTableDefaultSelectedRow",
+ },
+ ],
+ version: 32,
+ },
+ {
+ functionLookup: [
+ {
+ moduleObj: MenuButtonWidgetButtonProperties,
+ functionName: "migrateMenuButtonWidgetButtonProperties",
+ },
+ ],
+ version: 33,
+ },
+ {
+ functionLookup: [
+ {
+ moduleObj: DSLMigrations,
+ functionName: "migrateButtonWidgetValidation",
+ },
+ ],
+ version: 34,
+ },
+ {
+ functionLookup: [
+ {
+ moduleObj: DSLMigrations,
+ functionName: "migrateInputValidation",
+ },
+ ],
+ version: 35,
+ },
+ {
+ functionLookup: [
+ {
+ moduleObj: DSLMigrations,
+ functionName: "revertTableDefaultSelectedRow",
+ },
+ ],
+ version: 36,
+ },
+ {
+ functionLookup: [
+ {
+ moduleObj: tableMigrations,
+ functionName: "migrateTableSanitizeColumnKeys",
+ },
+ ],
+ version: 37,
+ },
+ {
+ functionLookup: [
+ {
+ moduleObj: modalMigration,
+ functionName: "migrateResizableModalWidgetProperties",
+ },
+ ],
+ version: 38,
+ },
+ {
+ functionLookup: [
+ {
+ moduleObj: tableMigrations,
+ functionName: "migrateTableWidgetSelectedRowBindings",
+ },
+ ],
+ version: 39,
+ },
+ {
+ functionLookup: [
+ {
+ moduleObj: DSLMigrations,
+ functionName: "revertButtonStyleToButtonColor",
+ },
+ ],
+ version: 40,
+ },
+ {
+ functionLookup: [
+ {
+ moduleObj: DSLMigrations,
+ functionName: "migrateButtonVariant",
+ },
+ ],
+ version: 41,
+ },
+ {
+ functionLookup: [
+ {
+ moduleObj: mapWidgetMigration,
+ functionName: "migrateMapWidgetIsClickedMarkerCentered",
+ },
+ ],
+ version: 42,
+ },
+ {
+ functionLookup: [
+ {
+ moduleObj: DSLMigrations,
+ functionName: "mapAllowHorizontalScrollMigration",
+ },
+ ],
+ version: 43,
+ },
+ {
+ functionLookup: [
+ {
+ moduleObj: tableMigrations,
+ functionName: "isSortableMigration",
+ },
+ ],
+ version: 44,
+ },
+ {
+ functionLookup: [
+ {
+ moduleObj: tableMigrations,
+ functionName: "migrateTableWidgetIconButtonVariant",
+ },
+ ],
+ version: 45,
+ },
+ {
+ functionLookup: [
+ {
+ moduleObj: checkboxMigration,
+ functionName: "migrateCheckboxGroupWidgetInlineProperty",
+ },
+ ],
+ version: 46,
+ },
+ {
+ functionLookup: [
+ {
+ moduleObj: "",
+ functionName: "skippedMigration47",
+ },
+ ],
+ version: 47,
+ },
+ {
+ functionLookup: [
+ {
+ moduleObj: buttonWidgetMigrations,
+ functionName: "migrateRecaptchaType",
+ },
+ ],
+ version: 48,
+ },
+ {
+ functionLookup: [
+ {
+ moduleObj: DSLMigrations,
+ functionName: "addPrivateWidgetsToAllListWidgets",
+ },
+ ],
+ version: 49,
+ },
+ {
+ functionLookup: [
+ {
+ moduleObj: "",
+ functionName: "skippedMigration50",
+ },
+ ],
+ version: 50,
+ },
+ {
+ functionLookup: [
+ {
+ moduleObj: phoneInputMigration,
+ functionName: "migratePhoneInputWidgetAllowFormatting",
+ },
+ ],
+ version: 51,
+ },
+ {
+ functionLookup: [
+ {
+ moduleObj: modalMigration,
+ functionName: "migrateModalIconButtonWidget",
+ },
+ ],
+ version: 52,
+ },
+ {
+ functionLookup: [
+ {
+ moduleObj: TextStyleFromTextWidget,
+ functionName: "migrateScrollTruncateProperties",
+ },
+ ],
+ version: 53,
+ },
+ {
+ functionLookup: [
+ {
+ moduleObj: phoneInputMigration,
+ functionName: "migratePhoneInputWidgetDefaultDialCode",
+ },
+ ],
+ version: 54,
+ },
+ {
+ functionLookup: [
+ {
+ moduleObj: inputCurrencyMigration,
+ functionName: "migrateCurrencyInputWidgetDefaultCurrencyCode",
+ },
+ ],
+ version: 55,
+ },
+ {
+ functionLookup: [
+ {
+ moduleObj: radioGroupMigration,
+ functionName: "migrateRadioGroupAlignmentProperty",
+ },
+ ],
+ version: 56,
+ },
+ {
+ functionLookup: [
+ {
+ moduleObj: themingMigration,
+ functionName: "migrateStylingPropertiesForTheming",
+ },
+ ],
+ version: 57,
+ },
+ {
+ functionLookup: [
+ {
+ moduleObj: propertyPaneMigrations,
+ functionName: "migrateCheckboxSwitchProperty",
+ },
+ ],
+ version: 58,
+ },
+ {
+ functionLookup: [
+ {
+ moduleObj: chartWidgetReskinningMigrations,
+ functionName: "migrateChartWidgetReskinningData",
+ },
+ ],
+ version: 59,
+ },
+ {
+ functionLookup: [
+ {
+ moduleObj: tableMigrations,
+ functionName: "migrateTableWidgetV2Validation",
+ },
+ ],
+ version: 60,
+ },
+ {
+ functionLookup: [
+ {
+ moduleObj: chartWidgetReskinningMigrations,
+ functionName: "migrateChartWidgetReskinningData",
+ },
+ ],
+ version: 61,
+ },
+];
+
+const mockFnObj: Record<number, any> = {};
+let migratedDSL: ContainerWidgetProps<WidgetProps>;
+
+describe("Test all the migrations are running", () => {
+ afterAll(() => {
+ jest.clearAllMocks();
+ });
+ migrations.forEach((migration: Migration) => {
+ /**
+ * Generates mock fucntion for each migration function.
+ * Mocks the implementation
+ */
+ const version = migration.version ?? 0;
+ mockFnObj[version] = [];
+
+ migration.functionLookup.forEach((lookup) => {
+ const { functionName, moduleObj } = lookup;
+ if (moduleObj) {
+ mockFnObj[version].push({
+ spyOnFunc: jest
+ .spyOn(moduleObj, functionName)
+ .mockImplementation((dsl: any) => {
+ /**
+ * We need to delete the children property on the first migration(calculateDynamicHeight),
+ * to avoid the recursion in the second migration(updateContainers)
+ */
+ dsl && delete dsl.children;
+ return {
+ version: dsl?.version,
+ validationFuncName: functionName,
+ };
+ }),
+ });
+ }
+ });
+ });
+
+ // Runs all the migrations
+ migratedDSL = DSLMigrations.transformDSL(
+ (originalDSLForDSLMigrations as unknown) as ContainerWidgetProps<
+ WidgetProps
+ >,
+ );
+
+ migrations.forEach((item: any, testIdx: number) => {
+ const { functionLookup, version } = item;
+ const dslVersion = version ?? 0;
+
+ functionLookup.forEach(
+ (lookup: { moduleObj: any; functionName: string }, index: number) => {
+ const { functionName, moduleObj } = lookup;
+ if (moduleObj) {
+ const mockObj = mockFnObj[dslVersion][index].spyOnFunc;
+ const calls = mockObj.mock?.calls;
+ const results = mockObj.mock?.results;
+ const resultsLastIdx = mockObj.mock.results.length - 1;
+
+ describe(`Test ${testIdx}:`, () => {
+ test(`Has ${functionName} function executed?`, () => {
+ // Check if the migration function is called
+ expect(results[resultsLastIdx].value.validationFuncName).toEqual(
+ functionName,
+ );
+ });
+
+ // Check if the migration function is called with the current DSL version
+ calls.forEach((args: any) => {
+ test(`Does ${functionName} executes with DSL version: ${version}?`, () => {
+ if (args[0]?.version === version) {
+ expect(args[0]?.version).toEqual(version);
+ }
+ });
+ test(`For ${functionName}, is the ${args[0]?.version} registerd in tests?`, () => {
+ expect(
+ Object.keys(mockFnObj).includes(
+ args[0]?.version.toString() ?? "0",
+ ),
+ ).toBe(true);
+ });
+ });
+ });
+ }
+ },
+ );
+ });
+
+ test("Check the migration count matches the lates page version", () => {
+ expect(migrations.length).toEqual(LATEST_PAGE_VERSION);
+ });
+});
diff --git a/app/client/src/utils/DSLMigrations.ts b/app/client/src/utils/DSLMigrations.ts
index eb4bd49adb10..8ff4c5f75bf1 100644
--- a/app/client/src/utils/DSLMigrations.ts
+++ b/app/client/src/utils/DSLMigrations.ts
@@ -67,7 +67,7 @@ import { migrateChartWidgetReskinningData } from "./migrations/ChartWidgetReskin
* @param currentDSL
* @returns
*/
-const addLogBlackListToAllListWidgetChildren = (
+export const addLogBlackListToAllListWidgetChildren = (
currentDSL: ContainerWidgetProps<WidgetProps>,
) => {
currentDSL.children = currentDSL.children?.map((children: WidgetProps) => {
@@ -131,7 +131,7 @@ export const addPrivateWidgetsToAllListWidgets = (
* @param currentDSL
* @returns
*/
-const migrateItemsToListDataInListWidget = (
+export const migrateItemsToListDataInListWidget = (
currentDSL: ContainerWidgetProps<WidgetProps>,
) => {
if (currentDSL.type === "LIST_WIDGET") {
@@ -183,7 +183,7 @@ const migrateItemsToListDataInListWidget = (
return currentDSL;
};
-const updateContainers = (dsl: ContainerWidgetProps<WidgetProps>) => {
+export const updateContainers = (dsl: ContainerWidgetProps<WidgetProps>) => {
if (dsl.type === "CONTAINER_WIDGET" || dsl.type === "FORM_WIDGET") {
if (
!(
@@ -224,7 +224,9 @@ const updateContainers = (dsl: ContainerWidgetProps<WidgetProps>) => {
//transform chart data, from old chart widget to new chart widget
//updated chart widget has support for multiple series
-const chartDataMigration = (currentDSL: ContainerWidgetProps<WidgetProps>) => {
+export const chartDataMigration = (
+ currentDSL: ContainerWidgetProps<WidgetProps>,
+) => {
currentDSL.children = currentDSL.children?.map((children: WidgetProps) => {
if (
children.type === "CHART_WIDGET" &&
@@ -246,7 +248,7 @@ const chartDataMigration = (currentDSL: ContainerWidgetProps<WidgetProps>) => {
return currentDSL;
};
-const singleChartDataMigration = (
+export const singleChartDataMigration = (
currentDSL: ContainerWidgetProps<WidgetProps>,
) => {
currentDSL.children = currentDSL.children?.map((child) => {
@@ -277,7 +279,9 @@ const singleChartDataMigration = (
return currentDSL;
};
-const mapDataMigration = (currentDSL: ContainerWidgetProps<WidgetProps>) => {
+export const mapDataMigration = (
+ currentDSL: ContainerWidgetProps<WidgetProps>,
+) => {
currentDSL.children = currentDSL.children?.map((children: WidgetProps) => {
if (children.type === "MAP_WIDGET") {
if (children.markers) {
@@ -337,7 +341,7 @@ const mapDataMigration = (currentDSL: ContainerWidgetProps<WidgetProps>) => {
return currentDSL;
};
-const mapAllowHorizontalScrollMigration = (
+export const mapAllowHorizontalScrollMigration = (
currentDSL: ContainerWidgetProps<WidgetProps>,
) => {
currentDSL.children = currentDSL.children?.map((child: DSLWidget) => {
@@ -355,7 +359,7 @@ const mapAllowHorizontalScrollMigration = (
return currentDSL;
};
-const tabsWidgetTabsPropertyMigration = (
+export const tabsWidgetTabsPropertyMigration = (
currentDSL: ContainerWidgetProps<WidgetProps>,
) => {
currentDSL.children = currentDSL.children
@@ -388,7 +392,7 @@ const tabsWidgetTabsPropertyMigration = (
return currentDSL;
};
-const dynamicPathListMigration = (
+export const dynamicPathListMigration = (
currentDSL: ContainerWidgetProps<WidgetProps>,
) => {
if (currentDSL.children && currentDSL.children.length) {
@@ -415,7 +419,7 @@ const dynamicPathListMigration = (
return currentDSL;
};
-const addVersionNumberMigration = (
+export const addVersionNumberMigration = (
currentDSL: ContainerWidgetProps<WidgetProps>,
) => {
if (currentDSL.children && currentDSL.children.length) {
@@ -427,7 +431,7 @@ const addVersionNumberMigration = (
return currentDSL;
};
-const canvasNameConflictMigration = (
+export const canvasNameConflictMigration = (
currentDSL: ContainerWidgetProps<WidgetProps>,
props = { counter: 1 },
): ContainerWidgetProps<WidgetProps> => {
@@ -447,7 +451,7 @@ const canvasNameConflictMigration = (
return currentDSL;
};
-const renamedCanvasNameConflictMigration = (
+export const renamedCanvasNameConflictMigration = (
currentDSL: ContainerWidgetProps<WidgetProps>,
props = { counter: 1 },
): ContainerWidgetProps<WidgetProps> => {
@@ -468,7 +472,7 @@ const renamedCanvasNameConflictMigration = (
return currentDSL;
};
-const rteDefaultValueMigration = (
+export const rteDefaultValueMigration = (
currentDSL: ContainerWidgetProps<WidgetProps>,
): ContainerWidgetProps<WidgetProps> => {
if (currentDSL.type === "RICH_TEXT_EDITOR_WIDGET") {
@@ -503,7 +507,9 @@ function migrateTabsDataUsingMigrator(
return currentDSL;
}
-export function migrateTabsData(currentDSL: ContainerWidgetProps<WidgetProps>) {
+export const migrateTabsData = (
+ currentDSL: ContainerWidgetProps<WidgetProps>,
+) => {
if (
["TABS_WIDGET", "TABS_MIGRATOR_WIDGET"].includes(currentDSL.type as any) &&
currentDSL.version === 1
@@ -582,10 +588,12 @@ export function migrateTabsData(currentDSL: ContainerWidgetProps<WidgetProps>) {
currentDSL.children = currentDSL.children.map(migrateTabsData);
}
return currentDSL;
-}
+};
// A rudimentary transform function which updates the DSL based on its version.
-function migrateOldChartData(currentDSL: ContainerWidgetProps<WidgetProps>) {
+export const migrateOldChartData = (
+ currentDSL: ContainerWidgetProps<WidgetProps>,
+) => {
if (currentDSL.type === "CHART_WIDGET") {
if (isString(currentDSL.chartData)) {
try {
@@ -603,7 +611,7 @@ function migrateOldChartData(currentDSL: ContainerWidgetProps<WidgetProps>) {
currentDSL.children = currentDSL.children.map(migrateOldChartData);
}
return currentDSL;
-}
+};
/**
* changes chartData which we were using as array. now it will be a object
@@ -612,9 +620,9 @@ function migrateOldChartData(currentDSL: ContainerWidgetProps<WidgetProps>) {
* @param currentDSL
* @returns
*/
-export function migrateChartDataFromArrayToObject(
+export const migrateChartDataFromArrayToObject = (
currentDSL: ContainerWidgetProps<WidgetProps>,
-) {
+) => {
currentDSL.children = currentDSL.children?.map((children: WidgetProps) => {
if (children.type === "CHART_WIDGET") {
if (Array.isArray(children.chartData)) {
@@ -659,7 +667,7 @@ export function migrateChartDataFromArrayToObject(
});
return currentDSL;
-}
+};
const pixelToNumber = (pixel: string) => {
if (pixel.includes("px")) {
@@ -1086,19 +1094,27 @@ export const transformDSL = (
}
if (currentDSL.version === 59) {
+ /**
+ * migrateChartWidgetReskinningData function will be executed again in version 61,
+ * since for older apps the accentColor and fontFamily didn't get migrated.
+ */
currentDSL = migrateChartWidgetReskinningData(currentDSL);
currentDSL.version = 60;
}
if (currentDSL.version === 60) {
currentDSL = migrateTableWidgetV2Validation(currentDSL);
- currentDSL.version = LATEST_PAGE_VERSION;
+ currentDSL.version = 61;
}
+ if (currentDSL.version === 61) {
+ currentDSL = migrateChartWidgetReskinningData(currentDSL);
+ currentDSL.version = LATEST_PAGE_VERSION;
+ }
return currentDSL;
};
-const migrateButtonVariant = (
+export const migrateButtonVariant = (
currentDSL: ContainerWidgetProps<WidgetProps>,
) => {
if (
@@ -1281,7 +1297,7 @@ export const migrateInputValidation = (
return currentDSL;
};
-const migrateButtonWidgetValidation = (
+export const migrateButtonWidgetValidation = (
currentDSL: ContainerWidgetProps<WidgetProps>,
) => {
if (currentDSL.type === "INPUT_WIDGET") {
@@ -1335,7 +1351,7 @@ const addIsDisabledToButtonColumn = (
return currentDSL;
};
-const migrateIsDisabledToButtonColumn = (
+export const migrateIsDisabledToButtonColumn = (
currentDSL: ContainerWidgetProps<WidgetProps>,
) => {
const newDSL = addIsDisabledToButtonColumn(currentDSL);
@@ -1381,7 +1397,7 @@ export const migrateObjectFitToImageWidget = (
return dsl;
};
-const migrateOverFlowingTabsWidgets = (
+export const migrateOverFlowingTabsWidgets = (
currentDSL: ContainerWidgetProps<WidgetProps>,
canvasWidgets: any,
) => {
@@ -1417,7 +1433,7 @@ const migrateOverFlowingTabsWidgets = (
return currentDSL;
};
-const migrateWidgetsWithoutLeftRightColumns = (
+export const migrateWidgetsWithoutLeftRightColumns = (
currentDSL: ContainerWidgetProps<WidgetProps>,
canvasWidgets: any,
) => {
@@ -1461,7 +1477,7 @@ const migrateWidgetsWithoutLeftRightColumns = (
return currentDSL;
};
-const migrateNewlyAddedTabsWidgetsMissingData = (
+export const migrateNewlyAddedTabsWidgetsMissingData = (
currentDSL: ContainerWidgetProps<WidgetProps>,
) => {
if (currentDSL.type === "TABS_WIDGET" && currentDSL.version === 2) {
diff --git a/app/client/src/utils/migrations/ChartWidgetReskinningMigrations.ts b/app/client/src/utils/migrations/ChartWidgetReskinningMigrations.ts
index c3a96ba07da1..e9d0eeb9d8a0 100644
--- a/app/client/src/utils/migrations/ChartWidgetReskinningMigrations.ts
+++ b/app/client/src/utils/migrations/ChartWidgetReskinningMigrations.ts
@@ -4,18 +4,25 @@ import { DSLWidget } from "widgets/constants";
export const migrateChartWidgetReskinningData = (currentDSL: DSLWidget) => {
currentDSL.children = currentDSL.children?.map((child: WidgetProps) => {
if (child.type === "CHART_WIDGET") {
- child.accentColor = "{{appsmith.theme.colors.primaryColor}}";
- child.fontFamily = "{{appsmith.theme.fontFamily.appFont}}";
+ if (
+ !(
+ child.hasOwnProperty("accentColor") &&
+ child.hasOwnProperty("fontFamily")
+ )
+ ) {
+ child.accentColor = "{{appsmith.theme.colors.primaryColor}}";
+ child.fontFamily = "{{appsmith.theme.fontFamily.appFont}}";
- child.dynamicBindingPathList = [
- ...(child.dynamicBindingPathList || []),
- {
- key: "accentColor",
- },
- {
- key: "fontFamily",
- },
- ];
+ child.dynamicBindingPathList = [
+ ...(child.dynamicBindingPathList || []),
+ {
+ key: "accentColor",
+ },
+ {
+ key: "fontFamily",
+ },
+ ];
+ }
} else if (child.children && child.children.length > 0) {
child = migrateChartWidgetReskinningData(child);
}
diff --git a/app/client/src/utils/testDSLs.ts b/app/client/src/utils/testDSLs.ts
new file mode 100644
index 000000000000..45c21ec6ec71
--- /dev/null
+++ b/app/client/src/utils/testDSLs.ts
@@ -0,0 +1,3786 @@
+export const originalDSLForDSLMigrations = {
+ widgetName: "MainContainer",
+ backgroundColor: "none",
+ rightColumn: 450,
+ snapColumns: 64,
+ detachFromLayout: true,
+ widgetId: "0",
+ topRow: 0,
+ bottomRow: 840,
+ containerStyle: "none",
+ snapRows: 89,
+ parentRowSpace: 1,
+ type: "CANVAS_WIDGET",
+ canExtend: true,
+ version: undefined,
+ minHeight: 780,
+ parentColumnSpace: 1,
+ dynamicBindingPathList: [],
+ leftColumn: 0,
+ children: [
+ {
+ boxShadow: "{{appsmith.theme.boxShadow.appBoxShadow}}",
+ widgetName: "Container1",
+ borderColor: "transparent",
+ isCanvas: true,
+ dynamicPropertyPathList: [
+ {
+ key: "borderRadius",
+ },
+ ],
+ displayName: "Container",
+ iconSVG: "/static/media/icon.1977dca3.svg",
+ topRow: 0,
+ bottomRow: 6,
+ parentRowSpace: 10,
+ type: "CONTAINER_WIDGET",
+ hideCard: false,
+ animateLoading: true,
+ parentColumnSpace: 6.84375,
+ dynamicTriggerPathList: [],
+ leftColumn: 0,
+ dynamicBindingPathList: [
+ {
+ key: "backgroundColor",
+ },
+ {
+ key: "boxShadow",
+ },
+ {
+ key: "borderRadius",
+ },
+ ],
+ children: [
+ {
+ boxShadow: "none",
+ widgetName: "Canvas1",
+ displayName: "Canvas",
+ topRow: 0,
+ bottomRow: 390,
+ parentRowSpace: 1,
+ type: "CANVAS_WIDGET",
+ canExtend: false,
+ hideCard: true,
+ minHeight: 400,
+ parentColumnSpace: 1,
+ leftColumn: 0,
+ dynamicBindingPathList: [],
+ children: [
+ {
+ boxShadow: "none",
+ widgetName: "Text1",
+ dynamicPropertyPathList: [],
+ displayName: "Text",
+ iconSVG: "/static/media/icon.97c59b52.svg",
+ topRow: 0,
+ bottomRow: 4,
+ parentRowSpace: 10,
+ type: "TEXT_WIDGET",
+ hideCard: false,
+ animateLoading: true,
+ overflow: "NONE",
+ parentColumnSpace: 6.53125,
+ dynamicTriggerPathList: [],
+ fontFamily: "Montserrat",
+ leftColumn: 7,
+ dynamicBindingPathList: [],
+ shouldTruncate: false,
+ truncateButtonColor: "#FFC13D",
+ text: "Employee Time Tracker",
+ key: "s3ajdid629",
+ labelTextSize: "0.875rem",
+ rightColumn: 55,
+ textAlign: "LEFT",
+ widgetId: "xw0918rbsp",
+ isVisible: true,
+ fontStyle: "BOLD",
+ textColor: "#fff",
+ version: 1,
+ parentId: "22al9skq4c",
+ renderMode: "CANVAS",
+ isLoading: false,
+ borderRadius: "0px",
+ fontSize: "1.25rem",
+ },
+ {
+ boxShadow: "none",
+ widgetName: "IconButton8",
+ buttonColor: "#fff",
+ displayName: "Icon Button",
+ iconSVG:
+ "/static/media/icon.1a0c634ac75f9fa6b6ae7a8df882a3ba.svg",
+ searchTags: ["click", "submit"],
+ topRow: 0,
+ bottomRow: 4,
+ parentRowSpace: 10,
+ type: "ICON_BUTTON_WIDGET",
+ hideCard: false,
+ animateLoading: true,
+ parentColumnSpace: 6.53125,
+ dynamicTriggerPathList: [],
+ leftColumn: 2,
+ dynamicBindingPathList: [
+ {
+ key: "borderRadius",
+ },
+ ],
+ isDisabled: false,
+ key: "2my0dvhc2p",
+ isDeprecated: false,
+ rightColumn: 7,
+ iconName: "time",
+ widgetId: "df7pyl6z5m",
+ isVisible: true,
+ version: 1,
+ parentId: "22al9skq4c",
+ renderMode: "CANVAS",
+ isLoading: false,
+ borderRadius: "{{appsmith.theme.borderRadius.appBorderRadius}}",
+ buttonVariant: "TERTIARY",
+ },
+ ],
+ key: "53ftpwo2aq",
+ labelTextSize: "0.875rem",
+ rightColumn: 164.25,
+ detachFromLayout: true,
+ widgetId: "22al9skq4c",
+ containerStyle: "none",
+ isVisible: true,
+ version: 1,
+ parentId: "og1bsi36p4",
+ renderMode: "CANVAS",
+ isLoading: false,
+ borderRadius: "0px",
+ },
+ ],
+ borderWidth: "0",
+ key: "a4gmk81297",
+ labelTextSize: "0.875rem",
+ backgroundColor: "{{appsmith.theme.colors.primaryColor}}",
+ rightColumn: 64,
+ widgetId: "og1bsi36p4",
+ containerStyle: "card",
+ isVisible: true,
+ version: 1,
+ parentId: "0",
+ renderMode: "CANVAS",
+ isLoading: false,
+ borderRadius: "{{appsmith.theme.borderRadius.appBorderRadius}}",
+ },
+ {
+ boxShadow: "{{appsmith.theme.boxShadow.appBoxShadow}}",
+ widgetName: "Container1Copy",
+ borderColor: "transparent",
+ isCanvas: true,
+ dynamicPropertyPathList: [],
+ displayName: "Container",
+ iconSVG: "/static/media/icon.1977dca3.svg",
+ topRow: 6,
+ bottomRow: 82,
+ parentRowSpace: 10,
+ type: "CONTAINER_WIDGET",
+ hideCard: false,
+ animateLoading: true,
+ parentColumnSpace: 6.84375,
+ dynamicTriggerPathList: [],
+ leftColumn: 0,
+ dynamicBindingPathList: [
+ {
+ key: "boxShadow",
+ },
+ ],
+ children: [
+ {
+ boxShadow: "none",
+ widgetName: "Canvas1Copy",
+ displayName: "Canvas",
+ topRow: 0,
+ bottomRow: 730,
+ parentRowSpace: 1,
+ type: "CANVAS_WIDGET",
+ canExtend: false,
+ hideCard: true,
+ minHeight: 400,
+ parentColumnSpace: 1,
+ leftColumn: 0,
+ dynamicBindingPathList: [],
+ children: [
+ {
+ boxShadow: "none",
+ widgetName: "Tabs1",
+ isCanvas: true,
+ displayName: "Tabs",
+ iconSVG: "/static/media/icon.74a6d653.svg",
+ topRow: 5,
+ bottomRow: 71,
+ parentRowSpace: 10,
+ type: "TABS_WIDGET",
+ hideCard: false,
+ shouldScrollContents: false,
+ animateLoading: true,
+ parentColumnSpace: 6.53125,
+ dynamicTriggerPathList: [
+ {
+ key: "onTabSelected",
+ },
+ ],
+ leftColumn: 0,
+ dynamicBindingPathList: [
+ {
+ key: "defaultTab",
+ },
+ ],
+ children: [
+ {
+ tabId: "tab1",
+ boxShadow: "none",
+ widgetName: "Canvas2",
+ displayName: "Canvas",
+ topRow: 0,
+ bottomRow: 610,
+ parentRowSpace: 1,
+ type: "CANVAS_WIDGET",
+ canExtend: true,
+ hideCard: true,
+ shouldScrollContents: false,
+ minHeight: 400,
+ parentColumnSpace: 1,
+ dynamicTriggerPathList: [],
+ leftColumn: 0,
+ dynamicBindingPathList: [],
+ children: [
+ {
+ boxShadow: "none",
+ widgetName: "Text7",
+ dynamicPropertyPathList: [],
+ displayName: "Text",
+ iconSVG: "/static/media/icon.97c59b52.svg",
+ topRow: 1,
+ bottomRow: 6,
+ parentRowSpace: 10,
+ type: "TEXT_WIDGET",
+ hideCard: false,
+ animateLoading: true,
+ overflow: "NONE",
+ parentColumnSpace: 6.21875,
+ dynamicTriggerPathList: [],
+ fontFamily: "System Default",
+ leftColumn: 9,
+ dynamicBindingPathList: [
+ {
+ key: "text",
+ },
+ {
+ key: "textColor",
+ },
+ ],
+ shouldTruncate: false,
+ truncateButtonColor: "#FFC13D",
+ text: "{{lst_user.selectedItem.name}}",
+ key: "e6of5n4o7o",
+ labelTextSize: "0.875rem",
+ rightColumn: 45,
+ textAlign: "LEFT",
+ widgetId: "lzn17wpnmn",
+ isVisible: true,
+ fontStyle: "BOLD",
+ textColor: "{{appsmith.theme.colors.primaryColor}}",
+ version: 1,
+ parentId: "z05jlsrkmt",
+ renderMode: "CANVAS",
+ isLoading: false,
+ borderRadius: "0px",
+ fontSize: "1.25rem",
+ },
+ {
+ boxShadow: "none",
+ widgetName: "Image2",
+ displayName: "Image",
+ iconSVG:
+ "/static/media/icon.52d8fb963abcb95c79b10f1553389f22.svg",
+ topRow: 1,
+ bottomRow: 6,
+ parentRowSpace: 10,
+ type: "IMAGE_WIDGET",
+ hideCard: false,
+ animateLoading: true,
+ parentColumnSpace: 6.84375,
+ dynamicTriggerPathList: [],
+ imageShape: "RECTANGLE",
+ leftColumn: 0,
+ dynamicBindingPathList: [
+ {
+ key: "image",
+ },
+ ],
+ defaultImage:
+ "https://assets.appsmith.com/widgets/default.png",
+ key: "52v1r95ynr",
+ image: "{{lst_user.selectedItem.image}}",
+ isDeprecated: false,
+ rightColumn: 9,
+ objectFit: "contain",
+ widgetId: "e2whboroyt",
+ isVisible: true,
+ version: 1,
+ parentId: "z05jlsrkmt",
+ renderMode: "CANVAS",
+ isLoading: false,
+ maxZoomLevel: 1,
+ enableDownload: false,
+ borderRadius: "0px",
+ enableRotation: false,
+ },
+ {
+ resetFormOnClick: false,
+ boxShadow: "none",
+ widgetName: "Button4",
+ onClick: "{{JSObject1.onClick()}}",
+ buttonColor: "{{appsmith.theme.colors.primaryColor}}",
+ displayName: "Button",
+ iconSVG:
+ "/static/media/icon.cca026338f1c8eb6df8ba03d084c2fca.svg",
+ searchTags: ["click", "submit"],
+ topRow: 1,
+ bottomRow: 6,
+ parentRowSpace: 10,
+ type: "BUTTON_WIDGET",
+ hideCard: false,
+ animateLoading: true,
+ parentColumnSpace: 6.21875,
+ dynamicTriggerPathList: [
+ {
+ key: "onClick",
+ },
+ ],
+ leftColumn: 45,
+ dynamicBindingPathList: [
+ {
+ key: "buttonColor",
+ },
+ {
+ key: "borderRadius",
+ },
+ ],
+ text: "Clock In",
+ isDisabled: false,
+ key: "y8fmp30elx",
+ isDeprecated: false,
+ rightColumn: 63,
+ isDefaultClickDisabled: true,
+ widgetId: "eljn3wfgac",
+ isVisible: true,
+ recaptchaType: "V3",
+ version: 1,
+ parentId: "z05jlsrkmt",
+ renderMode: "CANVAS",
+ isLoading: false,
+ disabledWhenInvalid: false,
+ borderRadius:
+ "{{appsmith.theme.borderRadius.appBorderRadius}}",
+ buttonVariant: "SECONDARY",
+ placement: "CENTER",
+ },
+ {
+ template: {
+ IconButton2: {
+ boxShadow: "NONE",
+ widgetName: "IconButton2",
+ buttonColor: "#2E3D49",
+ displayName: "Icon Button",
+ iconSVG: "/static/media/icon.1a0c634a.svg",
+ topRow: 5,
+ bottomRow: 9,
+ parentRowSpace: 10,
+ type: "ICON_BUTTON_WIDGET",
+ hideCard: false,
+ animateLoading: true,
+ parentColumnSpace: 5.5869140625,
+ dynamicTriggerPathList: [],
+ leftColumn: 55,
+ dynamicBindingPathList: [],
+ isDisabled: false,
+ key: "qu8lf50ktl",
+ rightColumn: 64,
+ iconName: "time",
+ widgetId: "adfuulfvjx",
+ logBlackList: {
+ isVisible: true,
+ iconName: true,
+ borderRadius: true,
+ boxShadow: true,
+ buttonColor: true,
+ buttonVariant: true,
+ isDisabled: true,
+ widgetName: true,
+ version: true,
+ animateLoading: true,
+ type: true,
+ hideCard: true,
+ displayName: true,
+ key: true,
+ iconSVG: true,
+ isCanvas: true,
+ minHeight: true,
+ widgetId: true,
+ renderMode: true,
+ isLoading: true,
+ parentColumnSpace: true,
+ parentRowSpace: true,
+ leftColumn: true,
+ rightColumn: true,
+ topRow: true,
+ bottomRow: true,
+ parentId: true,
+ },
+ isVisible: true,
+ version: 1,
+ parentId: "snzcjlyy9x",
+ renderMode: "CANVAS",
+ isLoading: false,
+ borderRadius: "CIRCLE",
+ buttonVariant: "TERTIARY",
+ onClick: "{{JSObject1.clockout()}}",
+ },
+ btn_clockout: {
+ groupButtons: {
+ groupButton1: {
+ onClick: "{{JSObject1.clockout()}}",
+ },
+ },
+ borderRadius:
+ "{{List1.listData.map((currentItem, currentIndex) => {\n return (function(){\n return 'ROUNDED';\n })();\n })}}",
+ boxShadow:
+ "{{List1.listData.map((currentItem, currentIndex) => {\n return (function(){\n return 'NONE';\n })();\n })}}",
+ buttonVariant:
+ "{{List1.listData.map((currentItem, currentIndex) => {\n return (function(){\n return 'SECONDARY';\n })();\n })}}",
+ },
+ Text3CopyCopy: {
+ boxShadow: "none",
+ widgetName: "Text3CopyCopy",
+ dynamicPropertyPathList: [
+ {
+ key: "fontSize",
+ },
+ ],
+ displayName: "Text",
+ iconSVG: "/static/media/icon.97c59b52.svg",
+ topRow: 0,
+ bottomRow: 5,
+ type: "TEXT_WIDGET",
+ hideCard: false,
+ animateLoading: true,
+ overflow: "NONE",
+ dynamicTriggerPathList: [],
+ fontFamily: "System Default",
+ dynamicBindingPathList: [
+ {
+ key: "text",
+ },
+ {
+ key: "textColor",
+ },
+ ],
+ leftColumn: 38,
+ shouldTruncate: false,
+ borderWidth: "",
+ truncateButtonColor: "#FFC13D",
+ text:
+ "{{List1.listData.map((currentItem) => JSObject1.diffHrsMins(currentItem.time_start, currentItem.time_end))}}",
+ key: "s3ajdid629",
+ labelTextSize: "0.875rem",
+ rightColumn: 64,
+ backgroundColor: "transparent",
+ textAlign: "RIGHT",
+ widgetId: "j2qem8c0ac",
+ logBlackList: {
+ isVisible: true,
+ text: true,
+ fontSize: true,
+ fontStyle: true,
+ textAlign: true,
+ textColor: true,
+ truncateButtonColor: true,
+ widgetName: true,
+ shouldTruncate: true,
+ overflow: true,
+ version: true,
+ animateLoading: true,
+ type: true,
+ hideCard: true,
+ displayName: true,
+ key: true,
+ iconSVG: true,
+ isCanvas: true,
+ textStyle: true,
+ dynamicBindingPathList: true,
+ dynamicTriggerPathList: true,
+ minHeight: true,
+ widgetId: true,
+ renderMode: true,
+ isLoading: true,
+ parentColumnSpace: true,
+ parentRowSpace: true,
+ leftColumn: true,
+ rightColumn: true,
+ topRow: true,
+ bottomRow: true,
+ parentId: true,
+ },
+ isVisible: true,
+ fontStyle: "BOLD",
+ textColor: "{{appsmith.theme.colors.primaryColor}}",
+ version: 1,
+ parentId: "y3jz5nm8of",
+ renderMode: "CANVAS",
+ isLoading: false,
+ borderRadius: "0px",
+ fontSize: "1.5rem",
+ textStyle: "BODY",
+ },
+ Text3Copy1: {
+ boxShadow: "none",
+ widgetName: "Text3Copy1",
+ dynamicPropertyPathList: [
+ {
+ key: "textColor",
+ },
+ {
+ key: "fontSize",
+ },
+ ],
+ displayName: "Text",
+ iconSVG: "/static/media/icon.97c59b52.svg",
+ topRow: 5,
+ bottomRow: 10,
+ type: "TEXT_WIDGET",
+ hideCard: false,
+ animateLoading: true,
+ overflow: "NONE",
+ dynamicTriggerPathList: [],
+ fontFamily: "System Default",
+ dynamicBindingPathList: [
+ {
+ key: "text",
+ },
+ {
+ key: "textColor",
+ },
+ ],
+ leftColumn: 0,
+ shouldTruncate: false,
+ truncateButtonColor: "#FFC13D",
+ text:
+ "{{List1.listData.map((currentItem) => JSObject1.timeDisplay(\ncurrentItem.time_start,\ncurrentItem.time_end))}}",
+ key: "s3ajdid629",
+ labelTextSize: "0.875rem",
+ rightColumn: 33,
+ textAlign: "LEFT",
+ widgetId: "xlxxn7mjer",
+ logBlackList: {
+ isVisible: true,
+ text: true,
+ fontSize: true,
+ fontStyle: true,
+ textAlign: true,
+ textColor: true,
+ truncateButtonColor: true,
+ widgetName: true,
+ shouldTruncate: true,
+ overflow: true,
+ version: true,
+ animateLoading: true,
+ type: true,
+ hideCard: true,
+ displayName: true,
+ key: true,
+ iconSVG: true,
+ isCanvas: true,
+ textStyle: true,
+ dynamicBindingPathList: true,
+ dynamicTriggerPathList: true,
+ minHeight: true,
+ widgetId: true,
+ renderMode: true,
+ isLoading: true,
+ parentColumnSpace: true,
+ parentRowSpace: true,
+ leftColumn: true,
+ rightColumn: true,
+ topRow: true,
+ bottomRow: true,
+ parentId: true,
+ },
+ isVisible: true,
+ fontStyle: "",
+ textColor:
+ "{{List1.listData.map((currentItem) => currentItem.time_end ? 'black' : 'green')}}",
+ version: 1,
+ parentId: "y3jz5nm8of",
+ renderMode: "CANVAS",
+ isLoading: false,
+ borderRadius: "0px",
+ fontSize: "0.75rem",
+ textStyle: "BODY",
+ },
+ IconButton3Copy: {
+ boxShadow: "none",
+ widgetName: "IconButton3Copy",
+ onClick:
+ "{{delTimeLog.run(() => getTimeLogs.run(), () => {})}}",
+ buttonColor: "#FF5858",
+ dynamicPropertyPathList: [
+ {
+ key: "borderRadius",
+ },
+ ],
+ displayName: "Icon Button",
+ iconSVG: "/static/media/icon.1a0c634a.svg",
+ topRow: 5,
+ bottomRow: 10,
+ parentRowSpace: 10,
+ type: "ICON_BUTTON_WIDGET",
+ hideCard: false,
+ animateLoading: true,
+ parentColumnSpace: 5.5869140625,
+ dynamicTriggerPathList: [
+ {
+ key: "onClick",
+ },
+ ],
+ leftColumn: 56,
+ dynamicBindingPathList: [
+ {
+ key: "borderRadius",
+ },
+ ],
+ isDisabled: false,
+ key: "qu8lf50ktl",
+ labelTextSize: "0.875rem",
+ rightColumn: 64,
+ iconName: "trash",
+ widgetId: "hbveofpr91",
+ logBlackList: {
+ isVisible: true,
+ iconName: true,
+ borderRadius: true,
+ boxShadow: true,
+ buttonColor: true,
+ buttonVariant: true,
+ isDisabled: true,
+ widgetName: true,
+ version: true,
+ animateLoading: true,
+ type: true,
+ hideCard: true,
+ displayName: true,
+ key: true,
+ iconSVG: true,
+ isCanvas: true,
+ minHeight: true,
+ widgetId: true,
+ renderMode: true,
+ isLoading: true,
+ parentColumnSpace: true,
+ parentRowSpace: true,
+ leftColumn: true,
+ rightColumn: true,
+ topRow: true,
+ bottomRow: true,
+ parentId: true,
+ },
+ isVisible: true,
+ version: 1,
+ parentId: "y3jz5nm8of",
+ renderMode: "CANVAS",
+ isLoading: false,
+ borderRadius:
+ "{{appsmith.theme.borderRadius.appBorderRadius}}",
+ buttonVariant: "SECONDARY",
+ },
+ Text2Copy: {
+ boxShadow: "none",
+ widgetName: "Text2Copy",
+ dynamicPropertyPathList: [
+ {
+ key: "fontSize",
+ },
+ ],
+ displayName: "Text",
+ iconSVG: "/static/media/icon.97c59b52.svg",
+ topRow: 0,
+ bottomRow: 5,
+ type: "TEXT_WIDGET",
+ hideCard: false,
+ animateLoading: true,
+ overflow: "NONE",
+ dynamicTriggerPathList: [],
+ fontFamily: "System Default",
+ dynamicBindingPathList: [
+ {
+ key: "text",
+ },
+ ],
+ leftColumn: 0,
+ shouldTruncate: false,
+ truncateButtonColor: "#FFC13D",
+ text:
+ "{{List1.listData.map((currentItem) => 'Task: ' + currentItem.task)}}",
+ key: "s3ajdid629",
+ labelTextSize: "0.875rem",
+ rightColumn: 22,
+ textAlign: "LEFT",
+ widgetId: "1iy9e9hnnq",
+ logBlackList: {
+ isVisible: true,
+ text: true,
+ fontSize: true,
+ fontStyle: true,
+ textAlign: true,
+ textColor: true,
+ truncateButtonColor: true,
+ widgetName: true,
+ shouldTruncate: true,
+ overflow: true,
+ version: true,
+ animateLoading: true,
+ type: true,
+ hideCard: true,
+ displayName: true,
+ key: true,
+ iconSVG: true,
+ isCanvas: true,
+ textStyle: true,
+ dynamicBindingPathList: true,
+ dynamicTriggerPathList: true,
+ minHeight: true,
+ widgetId: true,
+ renderMode: true,
+ isLoading: true,
+ parentColumnSpace: true,
+ parentRowSpace: true,
+ leftColumn: true,
+ rightColumn: true,
+ topRow: true,
+ bottomRow: true,
+ parentId: true,
+ },
+ isVisible: true,
+ fontStyle: "BOLD",
+ textColor: "#231F20",
+ version: 1,
+ parentId: "y3jz5nm8of",
+ renderMode: "CANVAS",
+ isLoading: false,
+ borderRadius: "0px",
+ fontSize: "1.125rem",
+ textStyle: "HEADING",
+ },
+ Button3Copy: {
+ boxShadow: "none",
+ widgetName: "Button3Copy",
+ onClick: "{{JSObject1.clockout()}}",
+ buttonColor: "{{appsmith.theme.colors.primaryColor}}",
+ dynamicPropertyPathList: [
+ {
+ key: "isDisabled",
+ },
+ {
+ key: "borderRadius",
+ },
+ ],
+ displayName: "Button",
+ iconSVG: "/static/media/icon.cca02633.svg",
+ topRow: 5,
+ bottomRow: 10,
+ parentRowSpace: 10,
+ type: "BUTTON_WIDGET",
+ hideCard: false,
+ animateLoading: true,
+ parentColumnSpace: 5.78125,
+ dynamicTriggerPathList: [
+ {
+ key: "onClick",
+ },
+ ],
+ leftColumn: 37,
+ dynamicBindingPathList: [
+ {
+ key: "isDisabled",
+ },
+ {
+ key: "buttonColor",
+ },
+ {
+ key: "borderRadius",
+ },
+ ],
+ text: "Clock Out",
+ isDisabled:
+ "{{List1.listData.map((currentItem) => currentItem.time_end !== null)}}",
+ key: "6mxrybslxf",
+ labelTextSize: "0.875rem",
+ rightColumn: 56,
+ isDefaultClickDisabled: true,
+ widgetId: "690l18wovc",
+ logBlackList: {
+ isVisible: true,
+ animateLoading: true,
+ text: true,
+ buttonColor: true,
+ buttonVariant: true,
+ placement: true,
+ widgetName: true,
+ isDisabled: true,
+ isDefaultClickDisabled: true,
+ recaptchaType: true,
+ version: true,
+ type: true,
+ hideCard: true,
+ displayName: true,
+ key: true,
+ iconSVG: true,
+ isCanvas: true,
+ minHeight: true,
+ widgetId: true,
+ renderMode: true,
+ isLoading: true,
+ parentColumnSpace: true,
+ parentRowSpace: true,
+ leftColumn: true,
+ rightColumn: true,
+ topRow: true,
+ bottomRow: true,
+ parentId: true,
+ },
+ isVisible: true,
+ recaptchaType: "V3",
+ version: 1,
+ parentId: "y3jz5nm8of",
+ renderMode: "CANVAS",
+ isLoading: false,
+ borderRadius:
+ "{{appsmith.theme.borderRadius.appBorderRadius}}",
+ buttonVariant: "PRIMARY",
+ iconAlign: "left",
+ placement: "CENTER",
+ },
+ Canvas5Copy: {
+ boxShadow: "none",
+ widgetName: "Canvas5Copy",
+ displayName: "Canvas",
+ topRow: 0,
+ bottomRow: 390,
+ parentRowSpace: 1,
+ type: "CANVAS_WIDGET",
+ canExtend: false,
+ hideCard: true,
+ dropDisabled: true,
+ openParentPropertyPane: true,
+ minHeight: 400,
+ noPad: true,
+ parentColumnSpace: 1,
+ leftColumn: 0,
+ dynamicBindingPathList: [],
+ children: ["szq2vx6r6m"],
+ key: "ir2wg4nsvm",
+ labelTextSize: "0.875rem",
+ rightColumn: 149.25,
+ detachFromLayout: true,
+ widgetId: "3vja4gvycq",
+ containerStyle: "none",
+ isVisible: true,
+ version: 1,
+ parentId: "zismwyzhny",
+ renderMode: "CANVAS",
+ isLoading: false,
+ borderRadius: "0px",
+ },
+ Container2Copy: {
+ boxShadow: "none",
+ widgetName: "Container2Copy",
+ borderColor: "transparent",
+ disallowCopy: true,
+ isCanvas: true,
+ dynamicPropertyPathList: [
+ {
+ key: "borderRadius",
+ },
+ ],
+ displayName: "Container",
+ iconSVG: "/static/media/icon.1977dca3.svg",
+ topRow: 0,
+ bottomRow: 13,
+ dragDisabled: true,
+ type: "CONTAINER_WIDGET",
+ hideCard: false,
+ openParentPropertyPane: true,
+ isDeletable: false,
+ animateLoading: true,
+ leftColumn: 0,
+ dynamicBindingPathList: [],
+ children: ["y3jz5nm8of"],
+ borderWidth: "0",
+ key: "lpcgapoau4",
+ disablePropertyPane: true,
+ labelTextSize: "0.875rem",
+ backgroundColor: "white",
+ rightColumn: 64,
+ widgetId: "szq2vx6r6m",
+ containerStyle: "card",
+ isVisible: true,
+ version: 1,
+ parentId: "3vja4gvycq",
+ renderMode: "CANVAS",
+ isLoading: false,
+ borderRadius: "0px",
+ },
+ Canvas6Copy: {
+ boxShadow: "none",
+ widgetName: "Canvas6Copy",
+ displayName: "Canvas",
+ topRow: 0,
+ bottomRow: 370,
+ parentRowSpace: 1,
+ type: "CANVAS_WIDGET",
+ canExtend: false,
+ hideCard: true,
+ parentColumnSpace: 1,
+ leftColumn: 0,
+ dynamicBindingPathList: [],
+ children: [
+ "1iy9e9hnnq",
+ "hbveofpr91",
+ "xlxxn7mjer",
+ "j2qem8c0ac",
+ "690l18wovc",
+ ],
+ key: "ir2wg4nsvm",
+ labelTextSize: "0.875rem",
+ detachFromLayout: true,
+ widgetId: "y3jz5nm8of",
+ containerStyle: "none",
+ isVisible: true,
+ version: 1,
+ parentId: "szq2vx6r6m",
+ renderMode: "CANVAS",
+ isLoading: false,
+ borderRadius: "0px",
+ },
+ },
+ boxShadow: "{{appsmith.theme.boxShadow.appBoxShadow}}",
+ widgetName: "List1",
+ listData: "{{getTimeLogs.data.reverse()}}",
+ isCanvas: true,
+ dynamicPropertyPathList: [
+ {
+ key: "isVisible",
+ },
+ ],
+ displayName: "List",
+ iconSVG: "/static/media/icon.9925ee17.svg",
+ topRow: 6,
+ bottomRow: 59,
+ parentRowSpace: 10,
+ onPageChange:
+ '{{getTimeLogs.run(() => resetWidget("List1",true), () => {})}}',
+ type: "LIST_WIDGET",
+ hideCard: false,
+ gridGap: 0,
+ animateLoading: true,
+ parentColumnSpace: 6.21875,
+ dynamicTriggerPathList: [
+ {
+ key: "template.IconButton3Copy.onClick",
+ },
+ {
+ key: "template.Button3Copy.onClick",
+ },
+ {
+ key: "onPageChange",
+ },
+ ],
+ leftColumn: 0,
+ dynamicBindingPathList: [
+ {
+ key: "listData",
+ },
+ {
+ key: "isVisible",
+ },
+ {
+ key: "boxShadow",
+ },
+ {
+ key: "template.Button3Copy.buttonColor",
+ },
+ {
+ key: "template.Button3Copy.borderRadius",
+ },
+ {
+ key: "template.IconButton3Copy.borderRadius",
+ },
+ {
+ key: "template.Text2Copy.text",
+ },
+ {
+ key: "template.Text3Copy1.text",
+ },
+ {
+ key: "template.Text3Copy1.textColor",
+ },
+ {
+ key: "template.Text3CopyCopy.text",
+ },
+ {
+ key: "template.Button3Copy.isDisabled",
+ },
+ ],
+ gridType: "vertical",
+ enhancements: true,
+ children: [
+ {
+ boxShadow: "none",
+ widgetName: "Canvas5Copy",
+ displayName: "Canvas",
+ topRow: 0,
+ bottomRow: 390,
+ parentRowSpace: 1,
+ type: "CANVAS_WIDGET",
+ canExtend: false,
+ hideCard: true,
+ dropDisabled: true,
+ openParentPropertyPane: true,
+ minHeight: 400,
+ noPad: true,
+ parentColumnSpace: 1,
+ leftColumn: 0,
+ dynamicBindingPathList: [],
+ children: [
+ {
+ boxShadow: "none",
+ widgetName: "Container2Copy",
+ borderColor: "transparent",
+ disallowCopy: true,
+ isCanvas: true,
+ dynamicPropertyPathList: [
+ {
+ key: "borderRadius",
+ },
+ ],
+ displayName: "Container",
+ iconSVG: "/static/media/icon.1977dca3.svg",
+ topRow: 0,
+ bottomRow: 11,
+ dragDisabled: true,
+ type: "CONTAINER_WIDGET",
+ hideCard: false,
+ openParentPropertyPane: true,
+ isDeletable: false,
+ animateLoading: true,
+ leftColumn: 0,
+ dynamicBindingPathList: [],
+ children: [
+ {
+ boxShadow: "none",
+ widgetName: "Canvas6Copy",
+ displayName: "Canvas",
+ topRow: 0,
+ bottomRow: 370,
+ parentRowSpace: 1,
+ type: "CANVAS_WIDGET",
+ canExtend: false,
+ hideCard: true,
+ parentColumnSpace: 1,
+ leftColumn: 0,
+ dynamicBindingPathList: [],
+ children: [
+ {
+ boxShadow: "none",
+ widgetName: "Text2Copy",
+ dynamicPropertyPathList: [
+ {
+ key: "fontSize",
+ },
+ ],
+ displayName: "Text",
+ iconSVG:
+ "/static/media/icon.97c59b52.svg",
+ topRow: 0,
+ bottomRow: 4,
+ type: "TEXT_WIDGET",
+ hideCard: false,
+ animateLoading: true,
+ overflow: "NONE",
+ dynamicTriggerPathList: [],
+ fontFamily: "System Default",
+ dynamicBindingPathList: [
+ {
+ key: "text",
+ },
+ ],
+ leftColumn: 0,
+ shouldTruncate: false,
+ truncateButtonColor: "#FFC13D",
+ text: "Task: {{currentItem.task}}",
+ key: "s3ajdid629",
+ labelTextSize: "0.875rem",
+ rightColumn: 22,
+ textAlign: "LEFT",
+ widgetId: "1iy9e9hnnq",
+ logBlackList: {
+ isVisible: true,
+ text: true,
+ fontSize: true,
+ fontStyle: true,
+ textAlign: true,
+ textColor: true,
+ truncateButtonColor: true,
+ widgetName: true,
+ shouldTruncate: true,
+ overflow: true,
+ version: true,
+ animateLoading: true,
+ type: true,
+ hideCard: true,
+ displayName: true,
+ key: true,
+ iconSVG: true,
+ isCanvas: true,
+ textStyle: true,
+ dynamicBindingPathList: true,
+ dynamicTriggerPathList: true,
+ minHeight: true,
+ widgetId: true,
+ renderMode: true,
+ isLoading: true,
+ parentColumnSpace: true,
+ parentRowSpace: true,
+ leftColumn: true,
+ rightColumn: true,
+ topRow: true,
+ bottomRow: true,
+ parentId: true,
+ },
+ isVisible: true,
+ fontStyle: "BOLD",
+ textColor: "#231F20",
+ version: 1,
+ parentId: "y3jz5nm8of",
+ renderMode: "CANVAS",
+ isLoading: false,
+ borderRadius: "0px",
+ fontSize: "1.125rem",
+ textStyle: "HEADING",
+ },
+ {
+ boxShadow: "none",
+ widgetName: "IconButton3Copy",
+ onClick:
+ "{{delTimeLog.run(() => getTimeLogs.run(), () => {})}}",
+ buttonColor: "#FF5858",
+ dynamicPropertyPathList: [
+ {
+ key: "borderRadius",
+ },
+ ],
+ displayName: "Icon Button",
+ iconSVG:
+ "/static/media/icon.1a0c634a.svg",
+ topRow: 4,
+ bottomRow: 9,
+ parentRowSpace: 10,
+ type: "ICON_BUTTON_WIDGET",
+ hideCard: false,
+ animateLoading: true,
+ parentColumnSpace: 5.5869140625,
+ dynamicTriggerPathList: [
+ {
+ key: "onClick",
+ },
+ ],
+ leftColumn: 56,
+ dynamicBindingPathList: [
+ {
+ key: "borderRadius",
+ },
+ ],
+ isDisabled: false,
+ key: "qu8lf50ktl",
+ labelTextSize: "0.875rem",
+ rightColumn: 64,
+ iconName: "trash",
+ widgetId: "hbveofpr91",
+ logBlackList: {
+ isVisible: true,
+ iconName: true,
+ borderRadius: true,
+ boxShadow: true,
+ buttonColor: true,
+ buttonVariant: true,
+ isDisabled: true,
+ widgetName: true,
+ version: true,
+ animateLoading: true,
+ type: true,
+ hideCard: true,
+ displayName: true,
+ key: true,
+ iconSVG: true,
+ isCanvas: true,
+ minHeight: true,
+ widgetId: true,
+ renderMode: true,
+ isLoading: true,
+ parentColumnSpace: true,
+ parentRowSpace: true,
+ leftColumn: true,
+ rightColumn: true,
+ topRow: true,
+ bottomRow: true,
+ parentId: true,
+ },
+ isVisible: true,
+ version: 1,
+ parentId: "y3jz5nm8of",
+ renderMode: "CANVAS",
+ isLoading: false,
+ borderRadius:
+ "{{appsmith.theme.borderRadius.appBorderRadius}}",
+ buttonVariant: "SECONDARY",
+ },
+ {
+ boxShadow: "none",
+ widgetName: "Text3Copy1",
+ dynamicPropertyPathList: [
+ {
+ key: "textColor",
+ },
+ {
+ key: "fontSize",
+ },
+ ],
+ displayName: "Text",
+ iconSVG:
+ "/static/media/icon.97c59b52.svg",
+ topRow: 4,
+ bottomRow: 9,
+ type: "TEXT_WIDGET",
+ hideCard: false,
+ animateLoading: true,
+ overflow: "NONE",
+ dynamicTriggerPathList: [],
+ fontFamily: "System Default",
+ dynamicBindingPathList: [
+ {
+ key: "text",
+ },
+ {
+ key: "textColor",
+ },
+ ],
+ leftColumn: 0,
+ shouldTruncate: false,
+ truncateButtonColor: "#FFC13D",
+ text:
+ "{{JSObject1.timeDisplay(\ncurrentItem.time_start,\ncurrentItem.time_end)}}",
+ key: "s3ajdid629",
+ labelTextSize: "0.875rem",
+ rightColumn: 33,
+ textAlign: "LEFT",
+ widgetId: "xlxxn7mjer",
+ logBlackList: {
+ isVisible: true,
+ text: true,
+ fontSize: true,
+ fontStyle: true,
+ textAlign: true,
+ textColor: true,
+ truncateButtonColor: true,
+ widgetName: true,
+ shouldTruncate: true,
+ overflow: true,
+ version: true,
+ animateLoading: true,
+ type: true,
+ hideCard: true,
+ displayName: true,
+ key: true,
+ iconSVG: true,
+ isCanvas: true,
+ textStyle: true,
+ dynamicBindingPathList: true,
+ dynamicTriggerPathList: true,
+ minHeight: true,
+ widgetId: true,
+ renderMode: true,
+ isLoading: true,
+ parentColumnSpace: true,
+ parentRowSpace: true,
+ leftColumn: true,
+ rightColumn: true,
+ topRow: true,
+ bottomRow: true,
+ parentId: true,
+ },
+ isVisible: true,
+ fontStyle: "",
+ textColor:
+ "{{currentItem.time_end ? 'black' : 'green'}}",
+ version: 1,
+ parentId: "y3jz5nm8of",
+ renderMode: "CANVAS",
+ isLoading: false,
+ borderRadius: "0px",
+ fontSize: "0.75rem",
+ textStyle: "BODY",
+ },
+ {
+ boxShadow: "none",
+ widgetName: "Text3CopyCopy",
+ dynamicPropertyPathList: [
+ {
+ key: "fontSize",
+ },
+ ],
+ displayName: "Text",
+ iconSVG:
+ "/static/media/icon.97c59b52.svg",
+ topRow: 0,
+ bottomRow: 4,
+ type: "TEXT_WIDGET",
+ hideCard: false,
+ animateLoading: true,
+ overflow: "NONE",
+ dynamicTriggerPathList: [],
+ fontFamily: "System Default",
+ dynamicBindingPathList: [
+ {
+ key: "text",
+ },
+ {
+ key: "textColor",
+ },
+ ],
+ leftColumn: 38,
+ shouldTruncate: false,
+ borderWidth: "",
+ truncateButtonColor: "#FFC13D",
+ text:
+ "{{JSObject1.diffHrsMins(currentItem.time_start, currentItem.time_end)}}",
+ key: "s3ajdid629",
+ labelTextSize: "0.875rem",
+ rightColumn: 64,
+ backgroundColor: "transparent",
+ textAlign: "RIGHT",
+ widgetId: "j2qem8c0ac",
+ logBlackList: {
+ isVisible: true,
+ text: true,
+ fontSize: true,
+ fontStyle: true,
+ textAlign: true,
+ textColor: true,
+ truncateButtonColor: true,
+ widgetName: true,
+ shouldTruncate: true,
+ overflow: true,
+ version: true,
+ animateLoading: true,
+ type: true,
+ hideCard: true,
+ displayName: true,
+ key: true,
+ iconSVG: true,
+ isCanvas: true,
+ textStyle: true,
+ dynamicBindingPathList: true,
+ dynamicTriggerPathList: true,
+ minHeight: true,
+ widgetId: true,
+ renderMode: true,
+ isLoading: true,
+ parentColumnSpace: true,
+ parentRowSpace: true,
+ leftColumn: true,
+ rightColumn: true,
+ topRow: true,
+ bottomRow: true,
+ parentId: true,
+ },
+ isVisible: true,
+ fontStyle: "BOLD",
+ textColor:
+ "{{appsmith.theme.colors.primaryColor}}",
+ version: 1,
+ parentId: "y3jz5nm8of",
+ renderMode: "CANVAS",
+ isLoading: false,
+ borderRadius: "0px",
+ fontSize: "1.5rem",
+ textStyle: "BODY",
+ },
+ {
+ boxShadow: "none",
+ widgetName: "Button3Copy",
+ onClick: "{{JSObject1.clockout()}}",
+ buttonColor:
+ "{{appsmith.theme.colors.primaryColor}}",
+ dynamicPropertyPathList: [
+ {
+ key: "isDisabled",
+ },
+ {
+ key: "borderRadius",
+ },
+ ],
+ displayName: "Button",
+ iconSVG:
+ "/static/media/icon.cca02633.svg",
+ topRow: 4,
+ bottomRow: 9,
+ parentRowSpace: 10,
+ type: "BUTTON_WIDGET",
+ hideCard: false,
+ animateLoading: true,
+ parentColumnSpace: 5.78125,
+ dynamicTriggerPathList: [
+ {
+ key: "onClick",
+ },
+ ],
+ leftColumn: 37,
+ dynamicBindingPathList: [
+ {
+ key: "isDisabled",
+ },
+ {
+ key: "buttonColor",
+ },
+ {
+ key: "borderRadius",
+ },
+ ],
+ text: "Clock Out",
+ isDisabled:
+ "{{currentItem.time_end !== null}}",
+ key: "6mxrybslxf",
+ labelTextSize: "0.875rem",
+ rightColumn: 56,
+ isDefaultClickDisabled: true,
+ widgetId: "690l18wovc",
+ logBlackList: {
+ isVisible: true,
+ animateLoading: true,
+ text: true,
+ buttonColor: true,
+ buttonVariant: true,
+ placement: true,
+ widgetName: true,
+ isDisabled: true,
+ isDefaultClickDisabled: true,
+ recaptchaType: true,
+ version: true,
+ type: true,
+ hideCard: true,
+ displayName: true,
+ key: true,
+ iconSVG: true,
+ isCanvas: true,
+ minHeight: true,
+ widgetId: true,
+ renderMode: true,
+ isLoading: true,
+ parentColumnSpace: true,
+ parentRowSpace: true,
+ leftColumn: true,
+ rightColumn: true,
+ topRow: true,
+ bottomRow: true,
+ parentId: true,
+ },
+ isVisible: true,
+ recaptchaType: "V3",
+ version: 1,
+ parentId: "y3jz5nm8of",
+ renderMode: "CANVAS",
+ isLoading: false,
+ borderRadius:
+ "{{appsmith.theme.borderRadius.appBorderRadius}}",
+ buttonVariant: "PRIMARY",
+ iconAlign: "left",
+ placement: "CENTER",
+ },
+ ],
+ key: "ir2wg4nsvm",
+ labelTextSize: "0.875rem",
+ detachFromLayout: true,
+ widgetId: "y3jz5nm8of",
+ containerStyle: "none",
+ isVisible: true,
+ version: 1,
+ parentId: "szq2vx6r6m",
+ renderMode: "CANVAS",
+ isLoading: false,
+ borderRadius: "0px",
+ },
+ ],
+ borderWidth: "0",
+ key: "lpcgapoau4",
+ disablePropertyPane: true,
+ labelTextSize: "0.875rem",
+ backgroundColor: "white",
+ rightColumn: 64,
+ widgetId: "szq2vx6r6m",
+ containerStyle: "card",
+ isVisible: true,
+ version: 1,
+ parentId: "3vja4gvycq",
+ renderMode: "CANVAS",
+ isLoading: false,
+ borderRadius: "0px",
+ },
+ ],
+ key: "ir2wg4nsvm",
+ labelTextSize: "0.875rem",
+ rightColumn: 149.25,
+ detachFromLayout: true,
+ widgetId: "3vja4gvycq",
+ containerStyle: "none",
+ isVisible: true,
+ version: 1,
+ parentId: "zismwyzhny",
+ renderMode: "CANVAS",
+ isLoading: false,
+ borderRadius: "0px",
+ },
+ ],
+ privateWidgets: {
+ undefined: true,
+ },
+ key: "mhpuav1a5z",
+ labelTextSize: "0.875rem",
+ backgroundColor: "transparent",
+ rightColumn: 64,
+ itemBackgroundColor: "#FFFFFF",
+ widgetId: "zismwyzhny",
+ accentColor: "{{appsmith.theme.colors.primaryColor}}",
+ isVisible: "{{List1.items.length > 0}}",
+ parentId: "z05jlsrkmt",
+ serverSidePaginationEnabled: true,
+ renderMode: "CANVAS",
+ isLoading: false,
+ borderRadius: "0.375rem",
+ },
+ ],
+ isDisabled: false,
+ key: "53ftpwo2aq",
+ labelTextSize: "0.875rem",
+ tabName: "Time Log",
+ rightColumn: 156.75,
+ detachFromLayout: true,
+ widgetId: "z05jlsrkmt",
+ isVisible: true,
+ version: 1,
+ parentId: "5i1ijofu5u",
+ renderMode: "CANVAS",
+ isLoading: false,
+ borderRadius: "0px",
+ },
+ {
+ tabId: "tab2",
+ boxShadow: "none",
+ widgetName: "Canvas3",
+ displayName: "Canvas",
+ topRow: 0,
+ bottomRow: 610,
+ parentRowSpace: 1,
+ type: "CANVAS_WIDGET",
+ canExtend: true,
+ hideCard: true,
+ shouldScrollContents: false,
+ minHeight: 400,
+ parentColumnSpace: 1,
+ dynamicTriggerPathList: [],
+ leftColumn: 0,
+ dynamicBindingPathList: [],
+ children: [
+ {
+ template: {
+ Image1Copy: {
+ boxShadow: "none",
+ widgetName: "Image1Copy",
+ displayName: "Image",
+ iconSVG:
+ "/static/media/icon.52d8fb963abcb95c79b10f1553389f22.svg",
+ topRow: 0,
+ bottomRow: 8,
+ type: "IMAGE_WIDGET",
+ hideCard: false,
+ animateLoading: true,
+ dynamicTriggerPathList: [],
+ imageShape: "RECTANGLE",
+ dynamicBindingPathList: [
+ {
+ key: "image",
+ },
+ {
+ key: "borderRadius",
+ },
+ ],
+ leftColumn: 0,
+ defaultImage:
+ "https://assets.appsmith.com/widgets/default.png",
+ key: "6zvrwxg59v",
+ image:
+ "{{lst_user.listData.map((currentItem) => currentItem.image)}}",
+ isDeprecated: false,
+ rightColumn: 16,
+ objectFit: "cover",
+ widgetId: "bnxe5gjbpt",
+ logBlackList: {
+ isVisible: true,
+ defaultImage: true,
+ imageShape: true,
+ maxZoomLevel: true,
+ enableRotation: true,
+ enableDownload: true,
+ objectFit: true,
+ image: true,
+ widgetName: true,
+ version: true,
+ animateLoading: true,
+ searchTags: true,
+ type: true,
+ hideCard: true,
+ isDeprecated: true,
+ replacement: true,
+ displayName: true,
+ key: true,
+ iconSVG: true,
+ isCanvas: true,
+ boxShadow: true,
+ dynamicBindingPathList: true,
+ dynamicTriggerPathList: true,
+ minHeight: true,
+ widgetId: true,
+ renderMode: true,
+ borderRadius: true,
+ isLoading: true,
+ parentColumnSpace: true,
+ parentRowSpace: true,
+ leftColumn: true,
+ rightColumn: true,
+ topRow: true,
+ bottomRow: true,
+ parentId: true,
+ },
+ isVisible: true,
+ version: 1,
+ parentId: "3smlbuidsm",
+ renderMode: "CANVAS",
+ isLoading: false,
+ maxZoomLevel: 1,
+ enableDownload: false,
+ borderRadius:
+ "{{appsmith.theme.borderRadius.appBorderRadius}}",
+ enableRotation: false,
+ },
+ Text9Copy: {
+ boxShadow: "none",
+ widgetName: "Text9Copy",
+ dynamicPropertyPathList: [
+ {
+ key: "textColor",
+ },
+ ],
+ displayName: "Text",
+ iconSVG:
+ "/static/media/icon.97c59b523e6f70ba6f40a10fc2c7c5b5.svg",
+ searchTags: ["typography", "paragraph", "label"],
+ topRow: 0,
+ bottomRow: 4,
+ type: "TEXT_WIDGET",
+ hideCard: false,
+ animateLoading: true,
+ overflow: "NONE",
+ dynamicTriggerPathList: [],
+ fontFamily: "{{appsmith.theme.fontFamily.appFont}}",
+ dynamicBindingPathList: [
+ {
+ key: "text",
+ },
+ {
+ key: "textColor",
+ },
+ {
+ key: "fontFamily",
+ },
+ ],
+ leftColumn: 18,
+ shouldTruncate: false,
+ truncateButtonColor: "#FFC13D",
+ text:
+ "{{lst_user.listData.map((currentItem) => currentItem.name)}}",
+ key: "u6pcautxph",
+ isDeprecated: false,
+ rightColumn: 51,
+ textAlign: "LEFT",
+ widgetId: "5k7hnpoca5",
+ logBlackList: {
+ isVisible: true,
+ text: true,
+ fontSize: true,
+ fontStyle: true,
+ textAlign: true,
+ textColor: true,
+ truncateButtonColor: true,
+ widgetName: true,
+ shouldTruncate: true,
+ overflow: true,
+ version: true,
+ animateLoading: true,
+ searchTags: true,
+ type: true,
+ hideCard: true,
+ isDeprecated: true,
+ replacement: true,
+ displayName: true,
+ key: true,
+ iconSVG: true,
+ isCanvas: true,
+ textStyle: true,
+ boxShadow: true,
+ dynamicBindingPathList: true,
+ dynamicTriggerPathList: true,
+ minHeight: true,
+ widgetId: true,
+ renderMode: true,
+ fontFamily: true,
+ borderRadius: true,
+ isLoading: true,
+ parentColumnSpace: true,
+ parentRowSpace: true,
+ leftColumn: true,
+ rightColumn: true,
+ topRow: true,
+ bottomRow: true,
+ parentId: true,
+ },
+ isVisible: true,
+ fontStyle: "BOLD",
+ textColor: "{{appsmith.theme.colors.primaryColor}}",
+ version: 1,
+ parentId: "3smlbuidsm",
+ renderMode: "CANVAS",
+ isLoading: false,
+ borderRadius:
+ "{{appsmith.theme.borderRadius.appBorderRadius}}",
+ fontSize: "1rem",
+ textStyle: "HEADING",
+ },
+ Text10Copy: {
+ widgetName: "Text10Copy",
+ displayName: "Text",
+ iconSVG:
+ "/static/media/icon.97c59b523e6f70ba6f40a10fc2c7c5b5.svg",
+ searchTags: ["typography", "paragraph", "label"],
+ topRow: 4,
+ bottomRow: 8,
+ parentRowSpace: 10,
+ type: "TEXT_WIDGET",
+ hideCard: false,
+ animateLoading: true,
+ overflow: "NONE",
+ fontFamily: "{{appsmith.theme.fontFamily.appFont}}",
+ parentColumnSpace: 5.78125,
+ dynamicTriggerPathList: [],
+ leftColumn: 18,
+ dynamicBindingPathList: [
+ {
+ key: "text",
+ },
+ {
+ key: "fontFamily",
+ },
+ ],
+ shouldTruncate: false,
+ truncateButtonColor: "#FFC13D",
+ text:
+ "{{lst_user.listData.map((currentItem) => currentItem.email)}}",
+ key: "u6pcautxph",
+ isDeprecated: false,
+ rightColumn: 63,
+ disableLink: true,
+ textAlign: "LEFT",
+ widgetId: "oatmji4m6z",
+ logBlackList: {
+ isVisible: true,
+ text: true,
+ fontSize: true,
+ fontStyle: true,
+ textAlign: true,
+ textColor: true,
+ truncateButtonColor: true,
+ widgetName: true,
+ shouldTruncate: true,
+ overflow: true,
+ version: true,
+ animateLoading: true,
+ searchTags: true,
+ type: true,
+ hideCard: true,
+ isDeprecated: true,
+ replacement: true,
+ displayName: true,
+ key: true,
+ iconSVG: true,
+ isCanvas: true,
+ minHeight: true,
+ widgetId: true,
+ renderMode: true,
+ fontFamily: true,
+ borderRadius: true,
+ isLoading: true,
+ parentColumnSpace: true,
+ parentRowSpace: true,
+ leftColumn: true,
+ rightColumn: true,
+ topRow: true,
+ bottomRow: true,
+ parentId: true,
+ dynamicBindingPathList: true,
+ },
+ isVisible: true,
+ fontStyle: "BOLD",
+ textColor: "#231F20",
+ version: 1,
+ parentId: "3smlbuidsm",
+ renderMode: "CANVAS",
+ isLoading: false,
+ borderRadius:
+ "{{appsmith.theme.borderRadius.appBorderRadius}}",
+ fontSize: "1rem",
+ },
+ IconButton9Copy: {
+ boxShadow: "none",
+ widgetName: "IconButton9Copy",
+ buttonColor:
+ "{{lst_user.listData.map((currentItem) => getAllTimeLogs.data.some(l=>l.time_end==undefined&& l.user_id==currentItem.id) ? 'limegreen' : 'grey')}}",
+ dynamicPropertyPathList: [
+ {
+ key: "buttonColor",
+ },
+ ],
+ displayName: "Icon Button",
+ iconSVG:
+ "/static/media/icon.1a0c634ac75f9fa6b6ae7a8df882a3ba.svg",
+ searchTags: ["click", "submit"],
+ topRow: 0,
+ bottomRow: 4,
+ tooltip: "Clock in/out",
+ parentRowSpace: 10,
+ type: "ICON_BUTTON_WIDGET",
+ hideCard: false,
+ animateLoading: true,
+ parentColumnSpace: 5.78125,
+ dynamicTriggerPathList: [],
+ leftColumn: 58,
+ dynamicBindingPathList: [
+ {
+ key: "buttonColor",
+ },
+ {
+ key: "borderRadius",
+ },
+ ],
+ isDisabled: false,
+ key: "6sipw8yyt6",
+ isDeprecated: false,
+ rightColumn: 62,
+ iconName: "time",
+ widgetId: "j0zzppxt0f",
+ logBlackList: {
+ isVisible: true,
+ iconName: true,
+ buttonVariant: true,
+ isDisabled: true,
+ widgetName: true,
+ version: true,
+ animateLoading: true,
+ searchTags: true,
+ type: true,
+ hideCard: true,
+ isDeprecated: true,
+ replacement: true,
+ displayName: true,
+ key: true,
+ iconSVG: true,
+ isCanvas: true,
+ minHeight: true,
+ widgetId: true,
+ renderMode: true,
+ buttonColor: true,
+ borderRadius: true,
+ boxShadow: true,
+ isLoading: true,
+ parentColumnSpace: true,
+ parentRowSpace: true,
+ leftColumn: true,
+ rightColumn: true,
+ topRow: true,
+ bottomRow: true,
+ parentId: true,
+ dynamicBindingPathList: true,
+ },
+ isVisible: true,
+ version: 1,
+ parentId: "3smlbuidsm",
+ renderMode: "CANVAS",
+ isLoading: false,
+ borderRadius:
+ "{{appsmith.theme.borderRadius.appBorderRadius}}",
+ buttonVariant: "TERTIARY",
+ },
+ Canvas10Copy: {
+ boxShadow: "none",
+ widgetName: "Canvas10Copy",
+ displayName: "Canvas",
+ topRow: 0,
+ bottomRow: 390,
+ parentRowSpace: 1,
+ type: "CANVAS_WIDGET",
+ canExtend: false,
+ hideCard: true,
+ dropDisabled: true,
+ openParentPropertyPane: true,
+ minHeight: 400,
+ noPad: true,
+ parentColumnSpace: 1,
+ leftColumn: 0,
+ dynamicBindingPathList: [],
+ children: ["jtnfj3x31z"],
+ key: "yefglrbgux",
+ isDeprecated: false,
+ rightColumn: 149.25,
+ detachFromLayout: true,
+ widgetId: "a3pfuntay2",
+ accentColor: "{{appsmith.theme.colors.primaryColor}}",
+ containerStyle: "none",
+ isVisible: true,
+ version: 1,
+ parentId: "2vn64tqgfn",
+ renderMode: "CANVAS",
+ isLoading: false,
+ borderRadius:
+ "{{appsmith.theme.borderRadius.appBorderRadius}}",
+ },
+ Container3Copy: {
+ boxShadow:
+ "{{appsmith.theme.boxShadow.appBoxShadow}}",
+ widgetName: "Container3Copy",
+ borderColor: "transparent",
+ disallowCopy: true,
+ isCanvas: true,
+ displayName: "Container",
+ iconSVG:
+ "/static/media/icon.1977dca3370505e2db3a8e44cfd54907.svg",
+ searchTags: ["div", "parent", "group"],
+ topRow: 0,
+ bottomRow: 10,
+ dragDisabled: true,
+ type: "CONTAINER_WIDGET",
+ hideCard: false,
+ openParentPropertyPane: true,
+ isDeletable: false,
+ animateLoading: true,
+ leftColumn: 0,
+ dynamicBindingPathList: [
+ {
+ key: "borderRadius",
+ },
+ {
+ key: "boxShadow",
+ },
+ ],
+ children: ["3smlbuidsm"],
+ borderWidth: "0",
+ key: "dnbh2d72dk",
+ disablePropertyPane: true,
+ backgroundColor: "white",
+ isDeprecated: false,
+ rightColumn: 64,
+ widgetId: "jtnfj3x31z",
+ containerStyle: "card",
+ isVisible: true,
+ version: 1,
+ parentId: "a3pfuntay2",
+ renderMode: "CANVAS",
+ isLoading: false,
+ borderRadius:
+ "{{appsmith.theme.borderRadius.appBorderRadius}}",
+ },
+ Canvas11Copy: {
+ boxShadow: "none",
+ widgetName: "Canvas11Copy",
+ displayName: "Canvas",
+ topRow: 0,
+ bottomRow: 370,
+ parentRowSpace: 1,
+ type: "CANVAS_WIDGET",
+ canExtend: false,
+ hideCard: true,
+ parentColumnSpace: 1,
+ leftColumn: 0,
+ dynamicBindingPathList: [],
+ children: [
+ "bnxe5gjbpt",
+ "5k7hnpoca5",
+ "oatmji4m6z",
+ "j0zzppxt0f",
+ ],
+ key: "yefglrbgux",
+ isDeprecated: false,
+ detachFromLayout: true,
+ widgetId: "3smlbuidsm",
+ accentColor: "{{appsmith.theme.colors.primaryColor}}",
+ containerStyle: "none",
+ isVisible: true,
+ version: 1,
+ parentId: "jtnfj3x31z",
+ renderMode: "CANVAS",
+ isLoading: false,
+ borderRadius:
+ "{{appsmith.theme.borderRadius.appBorderRadius}}",
+ },
+ },
+ boxShadow: "{{appsmith.theme.boxShadow.appBoxShadow}}",
+ widgetName: "lst_user",
+ listData: "{{getUsers.data}}",
+ isCanvas: true,
+ dynamicPropertyPathList: [],
+ displayName: "List",
+ iconSVG:
+ "/static/media/icon.9925ee17dee37bf1ba7374412563a8a7.svg",
+ topRow: 0,
+ bottomRow: 59,
+ parentRowSpace: 10,
+ onPageChange:
+ '{{getUsers.run(() => resetWidget("lst_user",true), () => {})}}',
+ type: "LIST_WIDGET",
+ hideCard: false,
+ onPageSizeChange: "",
+ gridGap: 0,
+ animateLoading: true,
+ parentColumnSpace: 6.21875,
+ dynamicTriggerPathList: [
+ {
+ key: "onListItemClick",
+ },
+ {
+ key: "onPageSizeChange",
+ },
+ {
+ key: "onPageChange",
+ },
+ ],
+ leftColumn: 0,
+ dynamicBindingPathList: [
+ {
+ key: "listData",
+ },
+ {
+ key: "borderRadius",
+ },
+ {
+ key: "boxShadow",
+ },
+ {
+ key: "template.Image1Copy.image",
+ },
+ {
+ key: "template.Text9Copy.text",
+ },
+ {
+ key: "template.Text10Copy.text",
+ },
+ {
+ key: "template.IconButton9Copy.buttonColor",
+ },
+ ],
+ gridType: "vertical",
+ enhancements: true,
+ children: [
+ {
+ boxShadow: "none",
+ widgetName: "Canvas10Copy",
+ displayName: "Canvas",
+ topRow: 0,
+ bottomRow: 390,
+ parentRowSpace: 1,
+ type: "CANVAS_WIDGET",
+ canExtend: false,
+ hideCard: true,
+ dropDisabled: true,
+ openParentPropertyPane: true,
+ minHeight: 400,
+ noPad: true,
+ parentColumnSpace: 1,
+ leftColumn: 0,
+ dynamicBindingPathList: [],
+ children: [
+ {
+ boxShadow:
+ "{{appsmith.theme.boxShadow.appBoxShadow}}",
+ widgetName: "Container3Copy",
+ borderColor: "transparent",
+ disallowCopy: true,
+ isCanvas: true,
+ displayName: "Container",
+ iconSVG:
+ "/static/media/icon.1977dca3370505e2db3a8e44cfd54907.svg",
+ searchTags: ["div", "parent", "group"],
+ topRow: 0,
+ bottomRow: 10,
+ dragDisabled: true,
+ type: "CONTAINER_WIDGET",
+ hideCard: false,
+ openParentPropertyPane: true,
+ isDeletable: false,
+ animateLoading: true,
+ leftColumn: 0,
+ dynamicBindingPathList: [
+ {
+ key: "borderRadius",
+ },
+ {
+ key: "boxShadow",
+ },
+ ],
+ children: [
+ {
+ boxShadow: "none",
+ widgetName: "Canvas11Copy",
+ displayName: "Canvas",
+ topRow: 0,
+ bottomRow: 370,
+ parentRowSpace: 1,
+ type: "CANVAS_WIDGET",
+ canExtend: false,
+ hideCard: true,
+ parentColumnSpace: 1,
+ leftColumn: 0,
+ dynamicBindingPathList: [],
+ children: [
+ {
+ boxShadow: "none",
+ widgetName: "Image1Copy",
+ displayName: "Image",
+ iconSVG:
+ "/static/media/icon.52d8fb963abcb95c79b10f1553389f22.svg",
+ topRow: 0,
+ bottomRow: 8,
+ type: "IMAGE_WIDGET",
+ hideCard: false,
+ animateLoading: true,
+ dynamicTriggerPathList: [],
+ imageShape: "RECTANGLE",
+ dynamicBindingPathList: [
+ {
+ key: "image",
+ },
+ {
+ key: "borderRadius",
+ },
+ ],
+ leftColumn: 0,
+ defaultImage:
+ "https://assets.appsmith.com/widgets/default.png",
+ key: "6zvrwxg59v",
+ image: "{{currentItem.image}}",
+ isDeprecated: false,
+ rightColumn: 16,
+ objectFit: "cover",
+ widgetId: "bnxe5gjbpt",
+ logBlackList: {
+ isVisible: true,
+ defaultImage: true,
+ imageShape: true,
+ maxZoomLevel: true,
+ enableRotation: true,
+ enableDownload: true,
+ objectFit: true,
+ image: true,
+ widgetName: true,
+ version: true,
+ animateLoading: true,
+ searchTags: true,
+ type: true,
+ hideCard: true,
+ isDeprecated: true,
+ replacement: true,
+ displayName: true,
+ key: true,
+ iconSVG: true,
+ isCanvas: true,
+ boxShadow: true,
+ dynamicBindingPathList: true,
+ dynamicTriggerPathList: true,
+ minHeight: true,
+ widgetId: true,
+ renderMode: true,
+ borderRadius: true,
+ isLoading: true,
+ parentColumnSpace: true,
+ parentRowSpace: true,
+ leftColumn: true,
+ rightColumn: true,
+ topRow: true,
+ bottomRow: true,
+ parentId: true,
+ },
+ isVisible: true,
+ version: 1,
+ parentId: "3smlbuidsm",
+ renderMode: "CANVAS",
+ isLoading: false,
+ maxZoomLevel: 1,
+ enableDownload: false,
+ borderRadius:
+ "{{appsmith.theme.borderRadius.appBorderRadius}}",
+ enableRotation: false,
+ },
+ {
+ boxShadow: "none",
+ widgetName: "Text9Copy",
+ dynamicPropertyPathList: [
+ {
+ key: "textColor",
+ },
+ ],
+ displayName: "Text",
+ iconSVG:
+ "/static/media/icon.97c59b523e6f70ba6f40a10fc2c7c5b5.svg",
+ searchTags: [
+ "typography",
+ "paragraph",
+ "label",
+ ],
+ topRow: 0,
+ bottomRow: 4,
+ type: "TEXT_WIDGET",
+ hideCard: false,
+ animateLoading: true,
+ overflow: "NONE",
+ dynamicTriggerPathList: [],
+ fontFamily:
+ "{{appsmith.theme.fontFamily.appFont}}",
+ dynamicBindingPathList: [
+ {
+ key: "text",
+ },
+ {
+ key: "textColor",
+ },
+ {
+ key: "fontFamily",
+ },
+ ],
+ leftColumn: 18,
+ shouldTruncate: false,
+ truncateButtonColor: "#FFC13D",
+ text: "{{currentItem.name}}",
+ key: "u6pcautxph",
+ isDeprecated: false,
+ rightColumn: 51,
+ textAlign: "LEFT",
+ widgetId: "5k7hnpoca5",
+ logBlackList: {
+ isVisible: true,
+ text: true,
+ fontSize: true,
+ fontStyle: true,
+ textAlign: true,
+ textColor: true,
+ truncateButtonColor: true,
+ widgetName: true,
+ shouldTruncate: true,
+ overflow: true,
+ version: true,
+ animateLoading: true,
+ searchTags: true,
+ type: true,
+ hideCard: true,
+ isDeprecated: true,
+ replacement: true,
+ displayName: true,
+ key: true,
+ iconSVG: true,
+ isCanvas: true,
+ textStyle: true,
+ boxShadow: true,
+ dynamicBindingPathList: true,
+ dynamicTriggerPathList: true,
+ minHeight: true,
+ widgetId: true,
+ renderMode: true,
+ fontFamily: true,
+ borderRadius: true,
+ isLoading: true,
+ parentColumnSpace: true,
+ parentRowSpace: true,
+ leftColumn: true,
+ rightColumn: true,
+ topRow: true,
+ bottomRow: true,
+ parentId: true,
+ },
+ isVisible: true,
+ fontStyle: "BOLD",
+ textColor:
+ "{{appsmith.theme.colors.primaryColor}}",
+ version: 1,
+ parentId: "3smlbuidsm",
+ renderMode: "CANVAS",
+ isLoading: false,
+ borderRadius:
+ "{{appsmith.theme.borderRadius.appBorderRadius}}",
+ fontSize: "1rem",
+ textStyle: "HEADING",
+ },
+ {
+ widgetName: "Text10Copy",
+ displayName: "Text",
+ iconSVG:
+ "/static/media/icon.97c59b523e6f70ba6f40a10fc2c7c5b5.svg",
+ searchTags: [
+ "typography",
+ "paragraph",
+ "label",
+ ],
+ topRow: 4,
+ bottomRow: 8,
+ parentRowSpace: 10,
+ type: "TEXT_WIDGET",
+ hideCard: false,
+ animateLoading: true,
+ overflow: "NONE",
+ fontFamily:
+ "{{appsmith.theme.fontFamily.appFont}}",
+ parentColumnSpace: 5.78125,
+ dynamicTriggerPathList: [],
+ leftColumn: 18,
+ dynamicBindingPathList: [
+ {
+ key: "text",
+ },
+ {
+ key: "fontFamily",
+ },
+ ],
+ shouldTruncate: false,
+ truncateButtonColor: "#FFC13D",
+ text: "{{currentItem.email}}",
+ key: "u6pcautxph",
+ isDeprecated: false,
+ rightColumn: 63,
+ disableLink: true,
+ textAlign: "LEFT",
+ widgetId: "oatmji4m6z",
+ logBlackList: {
+ isVisible: true,
+ text: true,
+ fontSize: true,
+ fontStyle: true,
+ textAlign: true,
+ textColor: true,
+ truncateButtonColor: true,
+ widgetName: true,
+ shouldTruncate: true,
+ overflow: true,
+ version: true,
+ animateLoading: true,
+ searchTags: true,
+ type: true,
+ hideCard: true,
+ isDeprecated: true,
+ replacement: true,
+ displayName: true,
+ key: true,
+ iconSVG: true,
+ isCanvas: true,
+ minHeight: true,
+ widgetId: true,
+ renderMode: true,
+ fontFamily: true,
+ borderRadius: true,
+ isLoading: true,
+ parentColumnSpace: true,
+ parentRowSpace: true,
+ leftColumn: true,
+ rightColumn: true,
+ topRow: true,
+ bottomRow: true,
+ parentId: true,
+ dynamicBindingPathList: true,
+ },
+ isVisible: true,
+ fontStyle: "BOLD",
+ textColor: "#231F20",
+ version: 1,
+ parentId: "3smlbuidsm",
+ renderMode: "CANVAS",
+ isLoading: false,
+ borderRadius:
+ "{{appsmith.theme.borderRadius.appBorderRadius}}",
+ fontSize: "1rem",
+ },
+ {
+ boxShadow: "none",
+ widgetName: "IconButton9Copy",
+ buttonColor:
+ "{{getAllTimeLogs.data.some(l=>l.time_end==undefined&& l.user_id==currentItem.id) ? 'limegreen' : 'grey'}}",
+ dynamicPropertyPathList: [
+ {
+ key: "buttonColor",
+ },
+ ],
+ displayName: "Icon Button",
+ iconSVG:
+ "/static/media/icon.1a0c634ac75f9fa6b6ae7a8df882a3ba.svg",
+ searchTags: ["click", "submit"],
+ topRow: 0,
+ bottomRow: 4,
+ tooltip: "Clock in/out",
+ parentRowSpace: 10,
+ type: "ICON_BUTTON_WIDGET",
+ hideCard: false,
+ animateLoading: true,
+ parentColumnSpace: 5.78125,
+ dynamicTriggerPathList: [],
+ leftColumn: 58,
+ dynamicBindingPathList: [
+ {
+ key: "buttonColor",
+ },
+ {
+ key: "borderRadius",
+ },
+ ],
+ isDisabled: false,
+ key: "6sipw8yyt6",
+ isDeprecated: false,
+ rightColumn: 62,
+ iconName: "time",
+ widgetId: "j0zzppxt0f",
+ logBlackList: {
+ isVisible: true,
+ iconName: true,
+ buttonVariant: true,
+ isDisabled: true,
+ widgetName: true,
+ version: true,
+ animateLoading: true,
+ searchTags: true,
+ type: true,
+ hideCard: true,
+ isDeprecated: true,
+ replacement: true,
+ displayName: true,
+ key: true,
+ iconSVG: true,
+ isCanvas: true,
+ minHeight: true,
+ widgetId: true,
+ renderMode: true,
+ buttonColor: true,
+ borderRadius: true,
+ boxShadow: true,
+ isLoading: true,
+ parentColumnSpace: true,
+ parentRowSpace: true,
+ leftColumn: true,
+ rightColumn: true,
+ topRow: true,
+ bottomRow: true,
+ parentId: true,
+ dynamicBindingPathList: true,
+ },
+ isVisible: true,
+ version: 1,
+ parentId: "3smlbuidsm",
+ renderMode: "CANVAS",
+ isLoading: false,
+ borderRadius:
+ "{{appsmith.theme.borderRadius.appBorderRadius}}",
+ buttonVariant: "TERTIARY",
+ },
+ ],
+ key: "yefglrbgux",
+ isDeprecated: false,
+ detachFromLayout: true,
+ widgetId: "3smlbuidsm",
+ accentColor:
+ "{{appsmith.theme.colors.primaryColor}}",
+ containerStyle: "none",
+ isVisible: true,
+ version: 1,
+ parentId: "jtnfj3x31z",
+ renderMode: "CANVAS",
+ isLoading: false,
+ borderRadius:
+ "{{appsmith.theme.borderRadius.appBorderRadius}}",
+ },
+ ],
+ borderWidth: "0",
+ key: "dnbh2d72dk",
+ disablePropertyPane: true,
+ backgroundColor: "white",
+ isDeprecated: false,
+ rightColumn: 64,
+ widgetId: "jtnfj3x31z",
+ containerStyle: "card",
+ isVisible: true,
+ version: 1,
+ parentId: "a3pfuntay2",
+ renderMode: "CANVAS",
+ isLoading: false,
+ borderRadius:
+ "{{appsmith.theme.borderRadius.appBorderRadius}}",
+ },
+ ],
+ key: "yefglrbgux",
+ isDeprecated: false,
+ rightColumn: 149.25,
+ detachFromLayout: true,
+ widgetId: "a3pfuntay2",
+ accentColor: "{{appsmith.theme.colors.primaryColor}}",
+ containerStyle: "none",
+ isVisible: true,
+ version: 1,
+ parentId: "2vn64tqgfn",
+ renderMode: "CANVAS",
+ isLoading: false,
+ borderRadius:
+ "{{appsmith.theme.borderRadius.appBorderRadius}}",
+ },
+ ],
+ privateWidgets: {
+ undefined: true,
+ },
+ key: "q9apcnizxn",
+ backgroundColor: "transparent",
+ isDeprecated: false,
+ rightColumn: 64,
+ onListItemClick: "{{JSObject1.selectEmployee()}}",
+ itemBackgroundColor: "#FFFFFF",
+ widgetId: "2vn64tqgfn",
+ accentColor: "{{appsmith.theme.colors.primaryColor}}",
+ isVisible: true,
+ parentId: "5nj3rw1joi",
+ serverSidePaginationEnabled: false,
+ renderMode: "CANVAS",
+ isLoading: false,
+ borderRadius:
+ "{{appsmith.theme.borderRadius.appBorderRadius}}",
+ },
+ ],
+ isDisabled: false,
+ key: "53ftpwo2aq",
+ labelTextSize: "0.875rem",
+ tabName: "Employees",
+ rightColumn: 156.75,
+ detachFromLayout: true,
+ widgetId: "5nj3rw1joi",
+ isVisible: true,
+ version: 1,
+ parentId: "5i1ijofu5u",
+ renderMode: "CANVAS",
+ isLoading: false,
+ borderRadius: "0px",
+ },
+ {
+ tabId: "tab0uectdsv5x",
+ boxShadow: "none",
+ widgetName: "Canvas9",
+ displayName: "Canvas",
+ topRow: 1,
+ bottomRow: 620,
+ parentRowSpace: 1,
+ type: "CANVAS_WIDGET",
+ canExtend: false,
+ hideCard: true,
+ minHeight: 600,
+ parentColumnSpace: 1,
+ dynamicTriggerPathList: [],
+ leftColumn: 0,
+ dynamicBindingPathList: [],
+ children: [
+ {
+ boxShadow: "{{appsmith.theme.boxShadow.appBoxShadow}}",
+ setAdaptiveYMin: false,
+ widgetName: "Chart1",
+ allowScroll: false,
+ dynamicPropertyPathList: [
+ {
+ key: "onDataPointClick",
+ },
+ ],
+ displayName: "Chart",
+ iconSVG:
+ "/static/media/icon.6adbe31ed817fc4bfd66f9f0a6fc105c.svg",
+ searchTags: ["graph", "visuals", "visualisations"],
+ topRow: 0,
+ bottomRow: 25,
+ parentRowSpace: 10,
+ type: "CHART_WIDGET",
+ hideCard: false,
+ chartData: {
+ zwbffmrap1: {
+ seriesName: "Time",
+ data: "{{JSObject1.totalsChart()}}",
+ },
+ },
+ animateLoading: true,
+ parentColumnSpace: 6.21875,
+ dynamicTriggerPathList: [
+ {
+ key: "onDataPointClick",
+ },
+ ],
+ fontFamily: "{{appsmith.theme.fontFamily.appFont}}",
+ leftColumn: 0,
+ dynamicBindingPathList: [
+ {
+ key: "chartData.zwbffmrap1.data",
+ },
+ {
+ key: "borderRadius",
+ },
+ {
+ key: "boxShadow",
+ },
+ {
+ key: "accentColor",
+ },
+ {
+ key: "fontFamily",
+ },
+ ],
+ customFusionChartConfig: {
+ type: "column2d",
+ dataSource: {
+ data: [
+ {
+ label: "Product1",
+ value: 20000,
+ },
+ {
+ label: "Product2",
+ value: 22000,
+ },
+ {
+ label: "Product3",
+ value: 32000,
+ },
+ ],
+ chart: {
+ caption: "Sales Report",
+ xAxisName: "Product Line",
+ yAxisName: "Revenue($)",
+ theme: "fusion",
+ alignCaptionWithCanvas: 1,
+ captionFontSize: "24",
+ captionAlignment: "center",
+ captionPadding: "20",
+ captionFontColor: "#231F20",
+ legendIconSides: "4",
+ legendIconBgAlpha: "100",
+ legendIconAlpha: "100",
+ legendPosition: "top",
+ canvasPadding: "0",
+ chartLeftMargin: "20",
+ chartTopMargin: "10",
+ chartRightMargin: "40",
+ chartBottomMargin: "10",
+ xAxisNameFontSize: "14",
+ labelFontSize: "12",
+ labelFontColor: "#716E6E",
+ xAxisNameFontColor: "#716E6E",
+ yAxisNameFontSize: "14",
+ yAxisValueFontSize: "12",
+ yAxisValueFontColor: "#716E6E",
+ yAxisNameFontColor: "#716E6E",
+ },
+ },
+ },
+ onDataPointClick:
+ "{{storeValue('task',Chart1.selectedDataPoint.x,false)}}",
+ key: "3p90n51o2w",
+ isDeprecated: false,
+ rightColumn: 64,
+ widgetId: "202hvtgzef",
+ accentColor: "{{appsmith.theme.colors.primaryColor}}",
+ isVisible: true,
+ version: 1,
+ parentId: "demz6wbjrc",
+ labelOrientation: "auto",
+ renderMode: "CANVAS",
+ isLoading: false,
+ yAxisName: "Duration (Hours)",
+ chartName: "Time spent per Task",
+ borderRadius:
+ "{{appsmith.theme.borderRadius.appBorderRadius}}",
+ xAxisName: "Task",
+ chartType: "BAR_CHART",
+ },
+ {
+ boxShadow: "{{appsmith.theme.boxShadow.appBoxShadow}}",
+ isVisibleDownload: false,
+ iconSVG:
+ "/static/media/icon.db8a9cbd2acd22a31ea91cc37ea2a46c.svg",
+ topRow: 29,
+ isSortable: false,
+ type: "TABLE_WIDGET_V2",
+ inlineEditingSaveOption: "ROW_LEVEL",
+ animateLoading: true,
+ dynamicBindingPathList: [
+ {
+ key: "tableData",
+ },
+ {
+ key: "primaryColumns.customColumn3.computedValue",
+ },
+ {
+ key: "primaryColumns.customColumn2.computedValue",
+ },
+ {
+ key: "primaryColumns.customColumn1.computedValue",
+ },
+ {
+ key: "primaryColumns.time_end.computedValue",
+ },
+ {
+ key: "primaryColumns.date_end.computedValue",
+ },
+ {
+ key: "primaryColumns.time_start.computedValue",
+ },
+ {
+ key: "primaryColumns.date_start.computedValue",
+ },
+ {
+ key: "primaryColumns.rate.computedValue",
+ },
+ {
+ key: "primaryColumns.notes.computedValue",
+ },
+ {
+ key: "primaryColumns.user_id.computedValue",
+ },
+ {
+ key: "primaryColumns.id.computedValue",
+ },
+ {
+ key: "primaryColumns.task.computedValue",
+ },
+ {
+ key: "accentColor",
+ },
+ {
+ key: "borderRadius",
+ },
+ {
+ key: "boxShadow",
+ },
+ ],
+ leftColumn: 0,
+ delimiter: ",",
+ defaultSelectedRowIndex: 0,
+ accentColor: "{{appsmith.theme.colors.primaryColor}}",
+ isVisibleFilters: false,
+ isVisible: true,
+ enableClientSideSearch: false,
+ version: 1,
+ totalRecordsCount: 0,
+ isLoading: false,
+ childStylesheet: {
+ button: {
+ buttonColor: "{{appsmith.theme.colors.primaryColor}}",
+ borderRadius:
+ "{{appsmith.theme.borderRadius.appBorderRadius}}",
+ boxShadow: "none",
+ },
+ menuButton: {
+ menuColor: "{{appsmith.theme.colors.primaryColor}}",
+ borderRadius:
+ "{{appsmith.theme.borderRadius.appBorderRadius}}",
+ boxShadow: "none",
+ },
+ iconButton: {
+ menuColor: "{{appsmith.theme.colors.primaryColor}}",
+ borderRadius:
+ "{{appsmith.theme.borderRadius.appBorderRadius}}",
+ boxShadow: "none",
+ },
+ editActions: {
+ saveButtonColor:
+ "{{appsmith.theme.colors.primaryColor}}",
+ saveBorderRadius:
+ "{{appsmith.theme.borderRadius.appBorderRadius}}",
+ discardButtonColor:
+ "{{appsmith.theme.colors.primaryColor}}",
+ discardBorderRadius:
+ "{{appsmith.theme.borderRadius.appBorderRadius}}",
+ },
+ },
+ borderRadius:
+ "{{appsmith.theme.borderRadius.appBorderRadius}}",
+ primaryColumnId: "id",
+ defaultSelectedRowIndices: [0],
+ widgetName: "Table2",
+ defaultPageSize: 0,
+ columnOrder: [
+ "customColumn3",
+ "customColumn1",
+ "customColumn2",
+ "id",
+ "user_id",
+ "task",
+ "notes",
+ "rate",
+ "date_start",
+ "time_start",
+ "date_end",
+ "time_end",
+ ],
+ dynamicPropertyPathList: [],
+ compactMode: "SHORT",
+ displayName: "Table",
+ bottomRow: 60,
+ columnWidthMap: {
+ task: 245,
+ step: 62,
+ status: 75,
+ time_start: 194,
+ customColumn1: 137,
+ customColumn2: 72,
+ customColumn3: 60,
+ },
+ parentRowSpace: 10,
+ hideCard: false,
+ parentColumnSpace: 6.21875,
+ dynamicTriggerPathList: [],
+ primaryColumns: {
+ task: {
+ index: 1,
+ width: 150,
+ id: "task",
+ originalId: "task",
+ alias: "task",
+ horizontalAlignment: "LEFT",
+ verticalAlignment: "CENTER",
+ columnType: "text",
+ textSize: "0.875rem",
+ enableFilter: true,
+ enableSort: true,
+ isVisible: false,
+ isCellVisible: true,
+ isCellEditable: false,
+ isDerived: false,
+ label: "task",
+ computedValue:
+ '{{Table2.processedTableData.map((currentRow, currentIndex) => ( currentRow["task"]))}}',
+ labelColor: "#FFFFFF",
+ validation: {},
+ },
+ id: {
+ allowCellWrapping: false,
+ index: 0,
+ width: 150,
+ originalId: "id",
+ id: "id",
+ alias: "id",
+ horizontalAlignment: "LEFT",
+ verticalAlignment: "CENTER",
+ columnType: "text",
+ textSize: "0.875rem",
+ enableFilter: true,
+ enableSort: true,
+ isVisible: false,
+ isDisabled: false,
+ isCellEditable: false,
+ isEditable: false,
+ isCellVisible: true,
+ isDerived: false,
+ label: "id",
+ isSaveVisible: true,
+ isDiscardVisible: true,
+ computedValue:
+ '{{Table2.processedTableData.map((currentRow, currentIndex) => ( currentRow["id"]))}}',
+ validation: {},
+ },
+ user_id: {
+ allowCellWrapping: false,
+ index: 1,
+ width: 150,
+ originalId: "user_id",
+ id: "user_id",
+ alias: "user_id",
+ horizontalAlignment: "LEFT",
+ verticalAlignment: "CENTER",
+ columnType: "text",
+ textSize: "0.875rem",
+ enableFilter: true,
+ enableSort: true,
+ isVisible: false,
+ isDisabled: false,
+ isCellEditable: false,
+ isEditable: false,
+ isCellVisible: true,
+ isDerived: false,
+ label: "user_id",
+ isSaveVisible: true,
+ isDiscardVisible: true,
+ computedValue:
+ '{{Table2.processedTableData.map((currentRow, currentIndex) => ( currentRow["user_id"]))}}',
+ validation: {},
+ },
+ notes: {
+ allowCellWrapping: false,
+ index: 3,
+ width: 150,
+ originalId: "notes",
+ id: "notes",
+ alias: "notes",
+ horizontalAlignment: "LEFT",
+ verticalAlignment: "CENTER",
+ columnType: "text",
+ textSize: "0.875rem",
+ enableFilter: true,
+ enableSort: true,
+ isVisible: false,
+ isDisabled: false,
+ isCellEditable: false,
+ isEditable: false,
+ isCellVisible: true,
+ isDerived: false,
+ label: "notes",
+ isSaveVisible: true,
+ isDiscardVisible: true,
+ computedValue:
+ '{{Table2.processedTableData.map((currentRow, currentIndex) => ( currentRow["notes"]))}}',
+ validation: {},
+ },
+ rate: {
+ allowCellWrapping: false,
+ index: 4,
+ width: 150,
+ originalId: "rate",
+ id: "rate",
+ alias: "rate",
+ horizontalAlignment: "LEFT",
+ verticalAlignment: "CENTER",
+ columnType: "text",
+ textSize: "0.875rem",
+ enableFilter: true,
+ enableSort: true,
+ isVisible: false,
+ isDisabled: false,
+ isCellEditable: false,
+ isEditable: false,
+ isCellVisible: true,
+ isDerived: false,
+ label: "rate",
+ isSaveVisible: true,
+ isDiscardVisible: true,
+ computedValue:
+ '{{Table2.processedTableData.map((currentRow, currentIndex) => ( currentRow["rate"]))}}',
+ validation: {},
+ },
+ date_start: {
+ allowCellWrapping: false,
+ index: 5,
+ width: 150,
+ originalId: "date_start",
+ id: "date_start",
+ alias: "date_start",
+ horizontalAlignment: "LEFT",
+ verticalAlignment: "CENTER",
+ columnType: "text",
+ textSize: "0.875rem",
+ enableFilter: true,
+ enableSort: true,
+ isVisible: false,
+ isDisabled: false,
+ isCellEditable: false,
+ isEditable: false,
+ isCellVisible: true,
+ isDerived: false,
+ label: "date_start",
+ isSaveVisible: true,
+ isDiscardVisible: true,
+ computedValue:
+ '{{Table2.processedTableData.map((currentRow, currentIndex) => ( currentRow["date_start"]))}}',
+ validation: {},
+ },
+ time_start: {
+ allowCellWrapping: false,
+ index: 6,
+ width: 150,
+ originalId: "time_start",
+ id: "time_start",
+ alias: "time_start",
+ horizontalAlignment: "LEFT",
+ verticalAlignment: "CENTER",
+ columnType: "text",
+ textSize: "0.875rem",
+ enableFilter: true,
+ enableSort: true,
+ isVisible: true,
+ isDisabled: false,
+ isCellEditable: false,
+ isEditable: false,
+ isCellVisible: true,
+ isDerived: false,
+ label: "time_start",
+ isSaveVisible: true,
+ isDiscardVisible: true,
+ computedValue:
+ '{{Table2.processedTableData.map((currentRow, currentIndex) => ( currentRow["time_start"]))}}',
+ validation: {},
+ },
+ date_end: {
+ allowCellWrapping: false,
+ index: 7,
+ width: 150,
+ originalId: "date_end",
+ id: "date_end",
+ alias: "date_end",
+ horizontalAlignment: "LEFT",
+ verticalAlignment: "CENTER",
+ columnType: "text",
+ textSize: "0.875rem",
+ enableFilter: true,
+ enableSort: true,
+ isVisible: false,
+ isDisabled: false,
+ isCellEditable: false,
+ isEditable: false,
+ isCellVisible: true,
+ isDerived: false,
+ label: "date_end",
+ isSaveVisible: true,
+ isDiscardVisible: true,
+ computedValue:
+ '{{Table2.processedTableData.map((currentRow, currentIndex) => ( currentRow["date_end"]))}}',
+ validation: {},
+ },
+ time_end: {
+ allowCellWrapping: false,
+ index: 8,
+ width: 150,
+ originalId: "time_end",
+ id: "time_end",
+ alias: "time_end",
+ horizontalAlignment: "LEFT",
+ verticalAlignment: "CENTER",
+ columnType: "text",
+ textSize: "0.875rem",
+ enableFilter: true,
+ enableSort: true,
+ isVisible: false,
+ isDisabled: false,
+ isCellEditable: false,
+ isEditable: false,
+ isCellVisible: true,
+ isDerived: false,
+ label: "time_end",
+ isSaveVisible: true,
+ isDiscardVisible: true,
+ computedValue:
+ '{{Table2.processedTableData.map((currentRow, currentIndex) => ( currentRow["time_end"]))}}',
+ validation: {},
+ },
+ customColumn1: {
+ allowCellWrapping: false,
+ index: 9,
+ width: 150,
+ originalId: "customColumn1",
+ id: "customColumn1",
+ alias: "Employee",
+ horizontalAlignment: "LEFT",
+ verticalAlignment: "CENTER",
+ columnType: "text",
+ textSize: "0.875rem",
+ enableFilter: true,
+ enableSort: true,
+ isVisible: true,
+ isDisabled: false,
+ isCellEditable: false,
+ isEditable: false,
+ isCellVisible: true,
+ isDerived: true,
+ label: "Employee",
+ isSaveVisible: true,
+ isDiscardVisible: true,
+ computedValue:
+ "{{Table2.processedTableData.map((currentRow, currentIndex) => ( getUsers.data.find(u=>u.id==currentRow.user_id).name))}}",
+ buttonStyle: "rgb(3, 179, 101)",
+ labelColor: "#FFFFFF",
+ validation: {},
+ },
+ customColumn2: {
+ allowCellWrapping: false,
+ index: 10,
+ width: 150,
+ originalId: "customColumn2",
+ id: "customColumn2",
+ alias: "duration",
+ horizontalAlignment: "RIGHT",
+ verticalAlignment: "CENTER",
+ columnType: "text",
+ textSize: "0.875rem",
+ enableFilter: true,
+ enableSort: true,
+ isVisible: true,
+ isDisabled: false,
+ isCellEditable: false,
+ isEditable: false,
+ isCellVisible: true,
+ isDerived: true,
+ label: "Duration",
+ isSaveVisible: true,
+ isDiscardVisible: true,
+ computedValue:
+ "{{Table2.processedTableData.map((currentRow, currentIndex) => ( JSObject1.diffHrsMins(currentRow.time_start,currentRow.time_end)))}}",
+ buttonStyle: "rgb(3, 179, 101)",
+ labelColor: "#FFFFFF",
+ validation: {},
+ },
+ customColumn3: {
+ allowCellWrapping: false,
+ index: 10,
+ width: 150,
+ originalId: "customColumn3",
+ id: "customColumn3",
+ alias: "image",
+ horizontalAlignment: "LEFT",
+ verticalAlignment: "CENTER",
+ columnType: "image",
+ textSize: "0.875rem",
+ enableFilter: true,
+ enableSort: true,
+ isVisible: true,
+ isDisabled: false,
+ isCellEditable: false,
+ isEditable: false,
+ isCellVisible: true,
+ isDerived: true,
+ label: "image",
+ isSaveVisible: true,
+ isDiscardVisible: true,
+ computedValue:
+ "{{Table2.processedTableData.map((currentRow, currentIndex) => ( getUsers.data.find(u=>u.id==currentRow.user_id).image))}}",
+ buttonStyle: "rgb(3, 179, 101)",
+ labelColor: "#FFFFFF",
+ validation: {},
+ },
+ },
+ key: "gijedibkh6",
+ isDeprecated: false,
+ rightColumn: 64,
+ textSize: "0.875rem",
+ widgetId: "kug5m016a2",
+ tableData:
+ "{{getAllTimeLogs.data.filter(log=>log.task==appsmith.store.task || appsmith.store.task ==''|| appsmith.store.task ==undefined)}}",
+ label: "Data",
+ searchKey: "",
+ parentId: "demz6wbjrc",
+ serverSidePaginationEnabled: true,
+ renderMode: "CANVAS",
+ horizontalAlignment: "LEFT",
+ isVisibleSearch: false,
+ isVisiblePagination: false,
+ verticalAlignment: "CENTER",
+ },
+ {
+ widgetName: "Text8",
+ dynamicPropertyPathList: [
+ {
+ key: "textColor",
+ },
+ ],
+ displayName: "Text",
+ iconSVG:
+ "/static/media/icon.97c59b523e6f70ba6f40a10fc2c7c5b5.svg",
+ searchTags: ["typography", "paragraph", "label"],
+ topRow: 25,
+ bottomRow: 29,
+ parentRowSpace: 10,
+ type: "TEXT_WIDGET",
+ hideCard: false,
+ animateLoading: true,
+ overflow: "NONE",
+ fontFamily: "{{appsmith.theme.fontFamily.appFont}}",
+ parentColumnSpace: 6.21875,
+ dynamicTriggerPathList: [],
+ leftColumn: 1,
+ dynamicBindingPathList: [
+ {
+ key: "fontFamily",
+ },
+ {
+ key: "text",
+ },
+ {
+ key: "textColor",
+ },
+ ],
+ shouldTruncate: false,
+ truncateButtonColor: "#FFC13D",
+ text:
+ "{{'task' in appsmith.store && appsmith.store.task?.length>0 ? `TASK ${appsmith.store.task}` : 'select a bar segment to view log entries for each Task'}}",
+ key: "oqp9xeolbr",
+ isDeprecated: false,
+ rightColumn: 57,
+ textAlign: "CENTER",
+ widgetId: "d7cjjtd9xc",
+ isVisible: true,
+ fontStyle: "ITALIC",
+ textColor:
+ "{{'task' in appsmith.store && appsmith.store.task?.length>0 ? 'grey' :'#ff5858'}}",
+ version: 1,
+ parentId: "demz6wbjrc",
+ renderMode: "CANVAS",
+ isLoading: false,
+ borderRadius:
+ "{{appsmith.theme.borderRadius.appBorderRadius}}",
+ fontSize: "1rem",
+ },
+ {
+ boxShadow: "none",
+ widgetName: "IconButton9",
+ onClick: "{{storeValue('task',undefined,false)}}",
+ buttonColor: "{{appsmith.theme.colors.primaryColor}}",
+ dynamicPropertyPathList: [
+ {
+ key: "onClick",
+ },
+ ],
+ displayName: "Icon Button",
+ iconSVG:
+ "/static/media/icon.1a0c634ac75f9fa6b6ae7a8df882a3ba.svg",
+ searchTags: ["click", "submit"],
+ topRow: 25,
+ bottomRow: 29,
+ parentRowSpace: 10,
+ type: "ICON_BUTTON_WIDGET",
+ hideCard: false,
+ animateLoading: true,
+ parentColumnSpace: 6.21875,
+ dynamicTriggerPathList: [
+ {
+ key: "onClick",
+ },
+ ],
+ leftColumn: 59,
+ dynamicBindingPathList: [
+ {
+ key: "buttonColor",
+ },
+ {
+ key: "borderRadius",
+ },
+ ],
+ isDisabled: false,
+ key: "6493kijvjm",
+ isDeprecated: false,
+ rightColumn: 63,
+ iconName: "reset",
+ widgetId: "v5sz0wjggu",
+ isVisible: true,
+ version: 1,
+ parentId: "demz6wbjrc",
+ renderMode: "CANVAS",
+ isLoading: false,
+ borderRadius:
+ "{{appsmith.theme.borderRadius.appBorderRadius}}",
+ buttonVariant: "PRIMARY",
+ },
+ ],
+ key: "tgc855brd3",
+ isDeprecated: false,
+ tabName: "Report",
+ rightColumn: 418,
+ detachFromLayout: true,
+ widgetId: "demz6wbjrc",
+ accentColor: "{{appsmith.theme.colors.primaryColor}}",
+ containerStyle: "none",
+ isVisible: true,
+ version: 1,
+ parentId: "5i1ijofu5u",
+ renderMode: "CANVAS",
+ isLoading: false,
+ borderRadius:
+ "{{appsmith.theme.borderRadius.appBorderRadius}}",
+ },
+ ],
+ key: "dmj9a5cird",
+ labelTextSize: "0.875rem",
+ rightColumn: 64,
+ widgetId: "5i1ijofu5u",
+ accentColor: "{{appsmith.theme.colors.primaryColor}}",
+ defaultTab: "{{appsmith.store.default_tab }}",
+ onTabSelected: "{{storeValue('default_tab','')}}",
+ shouldShowTabs: true,
+ tabsObj: {
+ tab0uectdsv5x: {
+ id: "tab0uectdsv5x",
+ index: 0,
+ label: "Report",
+ widgetId: "demz6wbjrc",
+ isVisible: true,
+ isDuplicateLabel: false,
+ },
+ tab2: {
+ label: "Employees",
+ id: "tab2",
+ widgetId: "5nj3rw1joi",
+ isVisible: true,
+ index: 1,
+ isDuplicateLabel: false,
+ },
+ tab1: {
+ label: "Time Log",
+ id: "tab1",
+ widgetId: "z05jlsrkmt",
+ isVisible: true,
+ index: 2,
+ isDuplicateLabel: false,
+ },
+ },
+ isVisible: true,
+ version: 3,
+ parentId: "cmd4xuwm4c",
+ renderMode: "CANVAS",
+ isLoading: false,
+ borderRadius: "0px",
+ },
+ {
+ boxShadow: "none",
+ widgetName: "Text5",
+ dynamicPropertyPathList: [
+ {
+ key: "fontSize",
+ },
+ ],
+ displayName: "Text",
+ iconSVG: "/static/media/icon.97c59b52.svg",
+ topRow: 0,
+ bottomRow: 5,
+ parentRowSpace: 10,
+ type: "TEXT_WIDGET",
+ hideCard: false,
+ animateLoading: true,
+ overflow: "NONE",
+ parentColumnSpace: 6.53125,
+ dynamicTriggerPathList: [],
+ fontFamily: "System Default",
+ leftColumn: 3,
+ dynamicBindingPathList: [
+ {
+ key: "text",
+ },
+ ],
+ shouldTruncate: false,
+ truncateButtonColor: "#FFC13D",
+ text:
+ "Last Updated: {{appsmith.store?.updated_at || moment().format('LLL')}}",
+ key: "sm2eopm278",
+ labelTextSize: "0.875rem",
+ rightColumn: 52,
+ textAlign: "LEFT",
+ widgetId: "u1jlz3uo52",
+ isVisible: true,
+ fontStyle: "",
+ textColor: "#716e6e",
+ version: 1,
+ parentId: "cmd4xuwm4c",
+ renderMode: "CANVAS",
+ isLoading: false,
+ borderRadius: "0px",
+ fontSize: "0.75rem",
+ },
+ {
+ boxShadow: "none",
+ widgetName: "IconButton7",
+ onClick:
+ "{{getUsers.run(() => getTimeLogs.run(), () => {}); \ngetAllTimeLogs.run();\nstoreValue('updated_at',moment().format('LLL'))}}",
+ buttonColor: "{{appsmith.theme.colors.primaryColor}}",
+ dynamicPropertyPathList: [
+ {
+ key: "onClick",
+ },
+ {
+ key: "borderRadius",
+ },
+ ],
+ displayName: "Icon Button",
+ iconSVG: "/static/media/icon.1a0c634a.svg",
+ topRow: 0,
+ bottomRow: 5,
+ parentRowSpace: 10,
+ type: "ICON_BUTTON_WIDGET",
+ hideCard: false,
+ animateLoading: true,
+ parentColumnSpace: 6.53125,
+ dynamicTriggerPathList: [
+ {
+ key: "onClick",
+ },
+ ],
+ leftColumn: 54,
+ dynamicBindingPathList: [
+ {
+ key: "buttonColor",
+ },
+ ],
+ isDisabled: false,
+ key: "iifq91zxtp",
+ labelTextSize: "0.875rem",
+ rightColumn: 61,
+ iconName: "refresh",
+ widgetId: "smr6ubs5fn",
+ isVisible: true,
+ version: 1,
+ parentId: "cmd4xuwm4c",
+ renderMode: "CANVAS",
+ isLoading: false,
+ borderRadius: "0.575rem",
+ buttonVariant: "TERTIARY",
+ },
+ ],
+ key: "53ftpwo2aq",
+ labelTextSize: "0.875rem",
+ rightColumn: 164.25,
+ detachFromLayout: true,
+ widgetId: "cmd4xuwm4c",
+ containerStyle: "none",
+ isVisible: true,
+ version: 1,
+ parentId: "gpxgpyyask",
+ renderMode: "CANVAS",
+ isLoading: false,
+ borderRadius: "0px",
+ },
+ ],
+ borderWidth: "0",
+ key: "a4gmk81297",
+ labelTextSize: "0.875rem",
+ backgroundColor: "#FFFFFF",
+ rightColumn: 64,
+ widgetId: "gpxgpyyask",
+ containerStyle: "card",
+ isVisible: true,
+ version: 1,
+ parentId: "0",
+ renderMode: "CANVAS",
+ isLoading: false,
+ borderRadius: "{{appsmith.theme.borderRadius.appBorderRadius}}",
+ },
+ {
+ boxShadow: "none",
+ widgetName: "Modal1",
+ isCanvas: true,
+ dynamicPropertyPathList: [
+ {
+ key: "borderRadius",
+ },
+ ],
+ displayName: "Modal",
+ iconSVG: "/static/media/icon.4975978e.svg",
+ topRow: 0,
+ bottomRow: 0,
+ parentRowSpace: 1,
+ type: "MODAL_WIDGET",
+ hideCard: false,
+ shouldScrollContents: true,
+ animateLoading: true,
+ parentColumnSpace: 1,
+ dynamicTriggerPathList: [
+ {
+ key: "onClose",
+ },
+ ],
+ leftColumn: 0,
+ dynamicBindingPathList: [],
+ children: [
+ {
+ boxShadow: "none",
+ widgetName: "Canvas8",
+ displayName: "Canvas",
+ topRow: 0,
+ bottomRow: 310,
+ parentRowSpace: 1,
+ type: "CANVAS_WIDGET",
+ canExtend: true,
+ hideCard: true,
+ shouldScrollContents: false,
+ minHeight: 284,
+ parentColumnSpace: 1,
+ leftColumn: 0,
+ dynamicBindingPathList: [],
+ children: [
+ {
+ boxShadow: "none",
+ widgetName: "IconButton6",
+ onClick: "{{closeModal('Modal1')}}",
+ buttonColor: "{{appsmith.theme.colors.primaryColor}}",
+ displayName: "Icon Button",
+ iconSVG: "/static/media/icon.1a0c634a.svg",
+ topRow: 1,
+ bottomRow: 6,
+ type: "ICON_BUTTON_WIDGET",
+ hideCard: false,
+ animateLoading: true,
+ dynamicTriggerPathList: [],
+ leftColumn: 55,
+ dynamicBindingPathList: [
+ {
+ key: "buttonColor",
+ },
+ ],
+ iconSize: 24,
+ isDisabled: false,
+ key: "n2rpp1efil",
+ labelTextSize: "0.875rem",
+ rightColumn: 62,
+ iconName: "cross",
+ widgetId: "6ckbxk9taj",
+ isVisible: true,
+ version: 1,
+ parentId: "jforpydvyp",
+ renderMode: "CANVAS",
+ isLoading: false,
+ borderRadius: "0.375rem",
+ buttonVariant: "PRIMARY",
+ },
+ {
+ boxShadow: "none",
+ widgetName: "Text6",
+ dynamicPropertyPathList: [
+ {
+ key: "fontSize",
+ },
+ ],
+ displayName: "Text",
+ iconSVG: "/static/media/icon.97c59b52.svg",
+ topRow: 1,
+ bottomRow: 6,
+ type: "TEXT_WIDGET",
+ hideCard: false,
+ animateLoading: true,
+ overflow: "NONE",
+ dynamicTriggerPathList: [],
+ fontFamily: "System Default",
+ leftColumn: 2,
+ dynamicBindingPathList: [
+ {
+ key: "textColor",
+ },
+ ],
+ shouldTruncate: false,
+ truncateButtonColor: "#FFC13D",
+ text: "Start New Task",
+ key: "xdyuhi8ryb",
+ labelTextSize: "0.875rem",
+ rightColumn: 51,
+ textAlign: "LEFT",
+ widgetId: "qv4c77718j",
+ isVisible: true,
+ fontStyle: "BOLD",
+ textColor: "{{appsmith.theme.colors.primaryColor}}",
+ version: 1,
+ parentId: "jforpydvyp",
+ renderMode: "CANVAS",
+ isLoading: false,
+ borderRadius: "0px",
+ fontSize: "1.5rem",
+ },
+ {
+ boxShadow: "none",
+ widgetName: "Button2",
+ onClick: "{{JSObject1.saveTimeLog()}}",
+ buttonColor: "{{appsmith.theme.colors.primaryColor}}",
+ dynamicPropertyPathList: [
+ {
+ key: "borderRadius",
+ },
+ {
+ key: "isDisabled",
+ },
+ ],
+ displayName: "Button",
+ iconSVG: "/static/media/icon.cca02633.svg",
+ topRow: 18,
+ bottomRow: 23,
+ type: "BUTTON_WIDGET",
+ hideCard: false,
+ animateLoading: true,
+ dynamicTriggerPathList: [
+ {
+ key: "onClick",
+ },
+ ],
+ leftColumn: 37,
+ dynamicBindingPathList: [
+ {
+ key: "buttonColor",
+ },
+ {
+ key: "isDisabled",
+ },
+ ],
+ text: "Clock In",
+ isDisabled: "{{!Select1.selectedOptionValue}}",
+ key: "4u2z3j5asa",
+ labelTextSize: "0.875rem",
+ rightColumn: 62,
+ isDefaultClickDisabled: true,
+ widgetId: "bxshlknohf",
+ buttonStyle: "PRIMARY_BUTTON",
+ isVisible: true,
+ recaptchaType: "V3",
+ version: 1,
+ parentId: "jforpydvyp",
+ renderMode: "CANVAS",
+ isLoading: false,
+ borderRadius: "0.700rem",
+ buttonVariant: "PRIMARY",
+ iconAlign: "left",
+ placement: "CENTER",
+ },
+ {
+ boxShadow: "none",
+ widgetName: "Select1",
+ isFilterable: true,
+ displayName: "Select",
+ iconSVG: "/static/media/icon.bd99caba.svg",
+ labelText: "Task",
+ topRow: 13,
+ bottomRow: 17,
+ parentRowSpace: 10,
+ labelWidth: "14",
+ type: "SELECT_WIDGET",
+ serverSideFiltering: false,
+ hideCard: false,
+ defaultOptionValue: "",
+ animateLoading: true,
+ parentColumnSpace: 6.4921875,
+ dynamicTriggerPathList: [],
+ leftColumn: 2,
+ dynamicBindingPathList: [
+ {
+ key: "accentColor",
+ },
+ ],
+ labelPosition: "Left",
+ options:
+ '[\n {\n "label": "Task1",\n "value": "1"\n },\n {\n "label": "Task2",\n "value": "2"\n },\n {\n "label": "Task3",\n "value": "3"\n },\n {\n "label": "Task4",\n "value": "4"\n },\n {\n "label": "Task5",\n "value": "5"\n }\n]',
+ labelStyle: "BOLD",
+ placeholderText: "Select option",
+ isDisabled: false,
+ key: "1yzaq5vf81",
+ labelTextSize: "1rem",
+ isRequired: true,
+ rightColumn: 62,
+ widgetId: "3bcb22pmkm",
+ accentColor: "{{appsmith.theme.colors.primaryColor}}",
+ isVisible: true,
+ version: 1,
+ parentId: "jforpydvyp",
+ renderMode: "CANVAS",
+ isLoading: false,
+ labelAlignment: "left",
+ borderRadius: "0.375rem",
+ },
+ {
+ boxShadow: "none",
+ widgetName: "Input1",
+ displayName: "Input",
+ iconSVG: "/static/media/icon.9f505595.svg",
+ topRow: 8,
+ bottomRow: 12,
+ parentRowSpace: 10,
+ labelWidth: "14",
+ autoFocus: false,
+ type: "INPUT_WIDGET_V2",
+ hideCard: false,
+ animateLoading: true,
+ parentColumnSpace: 6.4921875,
+ dynamicTriggerPathList: [],
+ resetOnSubmit: true,
+ leftColumn: 2,
+ dynamicBindingPathList: [
+ {
+ key: "defaultText",
+ },
+ {
+ key: "accentColor",
+ },
+ ],
+ labelPosition: "Left",
+ labelStyle: "BOLD",
+ labelTextColor: "#231f20",
+ inputType: "TEXT",
+ isDisabled: true,
+ key: "b2fum05x5g",
+ labelTextSize: "1rem",
+ isRequired: true,
+ rightColumn: 62,
+ widgetId: "2ryk9b0he3",
+ accentColor: "{{appsmith.theme.colors.primaryColor}}",
+ isVisible: true,
+ label: "Employee",
+ version: 2,
+ parentId: "jforpydvyp",
+ renderMode: "CANVAS",
+ isLoading: false,
+ borderRadius: "0.375rem",
+ iconAlign: "left",
+ defaultText: "{{lst_user.selectedItem.name}}",
+ },
+ ],
+ isDisabled: false,
+ key: "6i5snc4omt",
+ labelTextSize: "0.875rem",
+ rightColumn: 0,
+ detachFromLayout: true,
+ widgetId: "jforpydvyp",
+ isVisible: true,
+ version: 1,
+ parentId: "ccfshnc4ef",
+ renderMode: "CANVAS",
+ isLoading: false,
+ borderRadius: "0px",
+ },
+ ],
+ key: "tb04uy1los",
+ height: 284,
+ labelTextSize: "0.875rem",
+ rightColumn: 0,
+ detachFromLayout: true,
+ widgetId: "ccfshnc4ef",
+ canOutsideClickClose: true,
+ canEscapeKeyClose: true,
+ version: 2,
+ parentId: "0",
+ renderMode: "CANVAS",
+ isLoading: false,
+ onClose: '{{resetWidget("Modal1",true)}}',
+ borderRadius: "1.100rem",
+ width: 427.5,
+ },
+ ],
+};
|
0c74e7273e6434e83ef281b6129e1e2830472c43
|
2021-12-15 17:21:57
|
Aman Agarwal
|
fix(handle-enter-confirm-popup): added key action to confirm popup wi… (#8980)
| false
|
added key action to confirm popup wi… (#8980)
|
fix
|
diff --git a/app/client/src/pages/Editor/ConfirmRunModal.tsx b/app/client/src/pages/Editor/ConfirmRunModal.tsx
index cabc089d8085..c462e8d4563e 100644
--- a/app/client/src/pages/Editor/ConfirmRunModal.tsx
+++ b/app/client/src/pages/Editor/ConfirmRunModal.tsx
@@ -1,6 +1,7 @@
import React from "react";
import { connect } from "react-redux";
import { AppState } from "reducers";
+import { Keys } from "@blueprintjs/core";
import {
showRunActionConfirmModal,
cancelRunActionConfirmModal,
@@ -33,19 +34,50 @@ const ModalFooter = styled.div`
`;
class ConfirmRunModal extends React.Component<Props> {
+ addEventListener = () => {
+ document.addEventListener("keydown", this.onKeyUp);
+ };
+
+ removeEventListener = () => {
+ document.removeEventListener("keydown", this.onKeyUp);
+ };
+
+ onKeyUp = (event: KeyboardEvent) => {
+ if (event.keyCode === Keys.ENTER) {
+ this.onConfirm();
+ }
+ };
+
+ onConfirm = () => {
+ const { dispatch } = this.props;
+ dispatch(acceptRunActionConfirmModal());
+ this.handleClose();
+ };
+
+ handleClose = () => {
+ const { dispatch } = this.props;
+ dispatch(showRunActionConfirmModal(false));
+ dispatch(cancelRunActionConfirmModal());
+ };
+
+ componentDidUpdate() {
+ const { isModalOpen } = this.props;
+ if (isModalOpen) {
+ this.addEventListener();
+ } else {
+ this.removeEventListener();
+ }
+ }
+
render() {
const { dispatch, isModalOpen } = this.props;
- const handleClose = () => {
- dispatch(showRunActionConfirmModal(false));
-
- dispatch(cancelRunActionConfirmModal());
- };
return (
<DialogComponent
+ canEscapeKeyClose
isOpen={isModalOpen}
maxHeight={"80vh"}
- onClose={handleClose}
+ onClose={this.handleClose}
title="Confirm Action"
width={"580px"}
>
@@ -55,7 +87,7 @@ class ConfirmRunModal extends React.Component<Props> {
category={Category.tertiary}
onClick={() => {
dispatch(cancelRunActionConfirmModal());
- handleClose();
+ this.handleClose();
}}
size={Size.medium}
tag="button"
@@ -64,10 +96,7 @@ class ConfirmRunModal extends React.Component<Props> {
/>
<Button
category={Category.primary}
- onClick={() => {
- dispatch(acceptRunActionConfirmModal());
- handleClose();
- }}
+ onClick={this.onConfirm}
size={Size.medium}
tag="button"
text="Confirm"
|
4a91204e4dcead439a8d0329cd6bd27fd440c250
|
2024-12-19 17:46:22
|
Hetu Nandu
|
chore: Analytics util refactor (#38089)
| false
|
Analytics util refactor (#38089)
|
chore
|
diff --git a/app/client/package.json b/app/client/package.json
index 02bd681ec3f3..7330ec7e966c 100644
--- a/app/client/package.json
+++ b/app/client/package.json
@@ -88,6 +88,7 @@
"@redux-saga/core": "1.1.3",
"@redux-saga/types": "1.2.1",
"@reduxjs/toolkit": "^2.4.0",
+ "@segment/analytics-next": "^1.76.0",
"@sentry/react": "^6.2.4",
"@shared/ast": "workspace:^",
"@shared/dsl": "workspace:^",
diff --git a/app/client/public/index.html b/app/client/public/index.html
index 1bd179b00a00..dc9ca3ddc494 100755
--- a/app/client/public/index.html
+++ b/app/client/public/index.html
@@ -39,7 +39,6 @@
return result;
};
const CLOUD_HOSTING = parseConfig('{{env "APPSMITH_CLOUD_HOSTING"}}');
- const ZIPY_KEY = parseConfig('{{env "APPSMITH_ZIPY_SDK_KEY"}}');
const AIRGAPPED = parseConfig('{{env "APPSMITH_AIRGAP_ENABLED"}}');
const REO_CLIENT_ID = parseConfig('{{env "APPSMITH_REO_CLIENT_ID"}}');
</script>
@@ -64,21 +63,6 @@
})()
%>
</script>
- <script>
- if (CLOUD_HOSTING && ZIPY_KEY) {
- const script = document.createElement("script");
- script.crossOrigin = "anonymous";
- script.defer = true;
- script.src = "https://cdn.zipy.ai/sdk/v1.0/zipy.min.umd.js";
- script.onload = () => {
- window.zipy && window.zipy.init(ZIPY_KEY);
- };
- const head = document.getElementsByTagName("head")[0];
- head && head.appendChild(script);
- }
-
-
- </script>
<!-- Start of Reo Javascript -->
<script type="text/javascript">
diff --git a/app/client/src/actions/analyticsActions.ts b/app/client/src/actions/analyticsActions.ts
deleted file mode 100644
index 27415c1d4c97..000000000000
--- a/app/client/src/actions/analyticsActions.ts
+++ /dev/null
@@ -1,9 +0,0 @@
-import { ReduxActionTypes } from "ee/constants/ReduxActionConstants";
-
-export const segmentInitSuccess = () => ({
- type: ReduxActionTypes.SEGMENT_INITIALIZED,
-});
-
-export const segmentInitUncertain = () => ({
- type: ReduxActionTypes.SEGMENT_INIT_UNCERTAIN,
-});
diff --git a/app/client/src/api/interceptors/request/addAnonymousUserIdHeader.ts b/app/client/src/api/interceptors/request/addAnonymousUserIdHeader.ts
index d87e95c63072..b78a2c437849 100644
--- a/app/client/src/api/interceptors/request/addAnonymousUserIdHeader.ts
+++ b/app/client/src/api/interceptors/request/addAnonymousUserIdHeader.ts
@@ -1,8 +1,9 @@
import type { InternalAxiosRequestConfig } from "axios";
+import type { ID } from "@segment/analytics-next";
export const addAnonymousUserIdHeader = (
config: InternalAxiosRequestConfig,
- options: { anonymousId?: string; segmentEnabled?: boolean },
+ options: { anonymousId: ID; segmentEnabled?: boolean },
) => {
const { anonymousId, segmentEnabled } = options;
diff --git a/app/client/src/ce/constants/ReduxActionConstants.tsx b/app/client/src/ce/constants/ReduxActionConstants.tsx
index 5039dc0a272b..faf894223afc 100644
--- a/app/client/src/ce/constants/ReduxActionConstants.tsx
+++ b/app/client/src/ce/constants/ReduxActionConstants.tsx
@@ -1214,8 +1214,6 @@ const TenantActionErrorTypes = {
};
const AnalyticsActionTypes = {
- SEGMENT_INITIALIZED: "SEGMENT_INITIALIZED",
- SEGMENT_INIT_UNCERTAIN: "SEGMENT_INIT_UNCERTAIN",
SET_BUILDING_BLOCK_DRAG_START_TIME: "SET_BUILDING_BLOCK_DRAG_START_TIME",
RESET_BUILDING_BLOCK_DRAG_START_TIME: "RESET_BUILDING_BLOCK_DRAG_START_TIME",
SEND_ANALYTICS_FOR_SIDE_BY_SIDE_HOVER:
diff --git a/app/client/src/ce/reducers/index.tsx b/app/client/src/ce/reducers/index.tsx
index 90790e6fe4bf..f6bb8801940e 100644
--- a/app/client/src/ce/reducers/index.tsx
+++ b/app/client/src/ce/reducers/index.tsx
@@ -64,7 +64,6 @@ import type { CanvasLevelsReduxState } from "reducers/entityReducers/autoHeightR
import type { LintErrorsStore } from "reducers/lintingReducers/lintErrorsReducers";
import lintErrorReducer from "reducers/lintingReducers";
import type { AutoHeightUIState } from "reducers/uiReducers/autoHeightReducer";
-import type { AnalyticsReduxState } from "reducers/uiReducers/analyticsReducer";
import type { MetaWidgetsReduxState } from "reducers/entityReducers/metaWidgetsReducer";
import type { layoutConversionReduxState } from "reducers/uiReducers/layoutConversionReducer";
import type { OneClickBindingState } from "reducers/uiReducers/oneClickBindingReducer";
@@ -92,7 +91,6 @@ export const reducerObject = {
export interface AppState {
ui: {
consolidatedPageLoad: ConsolidatedPageLoadState;
- analytics: AnalyticsReduxState;
editor: EditorReduxState;
propertyPane: PropertyPaneReduxState;
tableFilterPane: TableFilterPaneReduxState;
diff --git a/app/client/src/ce/reducers/uiReducers/index.tsx b/app/client/src/ce/reducers/uiReducers/index.tsx
index 3685e13afb75..d59c5aa1a63a 100644
--- a/app/client/src/ce/reducers/uiReducers/index.tsx
+++ b/app/client/src/ce/reducers/uiReducers/index.tsx
@@ -39,7 +39,6 @@ import { editorContextReducer } from "ee/reducers/uiReducers/editorContextReduce
import libraryReducer from "reducers/uiReducers/libraryReducer";
import appSettingsPaneReducer from "reducers/uiReducers/appSettingsPaneReducer";
import autoHeightUIReducer from "reducers/uiReducers/autoHeightReducer";
-import analyticsReducer from "reducers/uiReducers/analyticsReducer";
import layoutConversionReducer from "reducers/uiReducers/layoutConversionReducer";
import oneClickBindingReducer from "reducers/uiReducers/oneClickBindingReducer";
import activeFieldReducer from "reducers/uiReducers/activeFieldEditorReducer";
@@ -49,7 +48,6 @@ import consolidatedPageLoadReducer from "reducers/uiReducers/consolidatedPageLoa
import { pluginActionReducer } from "PluginActionEditor/store";
export const uiReducerObject = {
- analytics: analyticsReducer,
editor: editorReducer,
errors: errorReducer,
propertyPane: propertyPaneReducer,
diff --git a/app/client/src/ce/sagas/analyticsSaga.ts b/app/client/src/ce/sagas/analyticsSaga.ts
index 6cd7c5799da5..355db4e04c0b 100644
--- a/app/client/src/ce/sagas/analyticsSaga.ts
+++ b/app/client/src/ce/sagas/analyticsSaga.ts
@@ -1,4 +1,3 @@
-import { getCurrentUser } from "selectors/usersSelectors";
import { getInstanceId } from "ee/selectors/tenantSelectors";
import { call, select } from "redux-saga/effects";
import type { APP_MODE } from "entities/App";
@@ -10,44 +9,37 @@ import AnalyticsUtil from "ee/utils/AnalyticsUtil";
import { getAppMode } from "ee/selectors/entitiesSelector";
import type { AppState } from "ee/reducers";
import { getWidget } from "sagas/selectors";
-import { getUserSource } from "ee/utils/AnalyticsUtil";
import { getCurrentApplication } from "ee/selectors/applicationSelectors";
-export interface UserAndAppDetails {
+export interface AppDetails {
pageId: string;
appId: string;
appMode: APP_MODE | undefined;
appName: string;
isExampleApp: boolean;
- userId: string;
- email: string;
- source: string;
instanceId: string;
}
-export function* getUserAndAppDetails() {
+export function* getAppDetails() {
const appMode: ReturnType<typeof getAppMode> = yield select(getAppMode);
const currentApp: ReturnType<typeof getCurrentApplication> = yield select(
getCurrentApplication,
);
- const user: ReturnType<typeof getCurrentUser> = yield select(getCurrentUser);
const instanceId: ReturnType<typeof getInstanceId> =
yield select(getInstanceId);
const pageId: ReturnType<typeof getCurrentPageId> =
yield select(getCurrentPageId);
- const userAndAppDetails: UserAndAppDetails = {
+
+ const appDetails: AppDetails = {
pageId,
appId: currentApp?.id || "",
appMode,
appName: currentApp?.name || "",
isExampleApp: currentApp?.appIsExample || false,
- userId: user?.username || "",
- email: user?.email || "",
- source: getUserSource(),
instanceId: instanceId,
};
- return userAndAppDetails;
+ return appDetails;
}
export function* logDynamicTriggerExecution({
dynamicTrigger,
@@ -65,13 +57,10 @@ export function* logDynamicTriggerExecution({
appId,
appMode,
appName,
- email,
instanceId,
isExampleApp,
pageId,
- source,
- userId,
- }: UserAndAppDetails = yield call(getUserAndAppDetails);
+ }: AppDetails = yield call(getAppDetails);
const widget: ReturnType<typeof getWidget> | undefined = yield select(
(state: AppState) => getWidget(state, triggerMeta.source?.id || ""),
);
@@ -89,12 +78,6 @@ export function* logDynamicTriggerExecution({
appMode,
appName,
isExampleApp,
- userData: {
- userId,
- email,
- appId,
- source,
- },
widgetName: widget?.widgetName,
widgetType: widget?.type,
propertyName: triggerMeta.triggerPropertyName,
@@ -114,12 +97,6 @@ export function* logDynamicTriggerExecution({
appMode,
appName,
isExampleApp,
- userData: {
- userId,
- email,
- appId,
- source,
- },
widgetName: widget?.widgetName,
widgetType: widget?.type,
propertyName: triggerMeta.triggerPropertyName,
diff --git a/app/client/src/ce/sagas/userSagas.tsx b/app/client/src/ce/sagas/userSagas.tsx
index 34e229fea2c5..ff8409ef4fd8 100644
--- a/app/client/src/ce/sagas/userSagas.tsx
+++ b/app/client/src/ce/sagas/userSagas.tsx
@@ -1,4 +1,4 @@
-import { call, fork, put, race, select, take } from "redux-saga/effects";
+import { call, fork, put, select, take } from "redux-saga/effects";
import type {
ReduxAction,
ReduxActionWithPromise,
@@ -57,14 +57,7 @@ import {
getFirstTimeUserOnboardingApplicationIds,
getFirstTimeUserOnboardingIntroModalVisibility,
} from "utils/storage";
-import { initializeAnalyticsAndTrackers } from "utils/AppsmithUtils";
import { getAppsmithConfigs } from "ee/configs";
-import { getSegmentState } from "selectors/analyticsSelectors";
-import {
- segmentInitUncertain,
- segmentInitSuccess,
-} from "actions/analyticsActions";
-import type { SegmentState } from "reducers/uiReducers/analyticsReducer";
import type { FeatureFlags } from "ee/entities/FeatureFlag";
import { DEFAULT_FEATURE_FLAG_VALUE } from "ee/entities/FeatureFlag";
import UsagePulse from "usagePulse";
@@ -82,25 +75,6 @@ import type {
import { selectFeatureFlags } from "ee/selectors/featureFlagsSelectors";
import { getFromServerWhenNoPrefetchedResult } from "sagas/helper";
-export function* waitForSegmentInit(skipWithAnonymousId: boolean) {
- if (skipWithAnonymousId && AnalyticsUtil.getAnonymousId()) return;
-
- const currentUser: User | undefined = yield select(getCurrentUser);
- const segmentState: SegmentState | undefined = yield select(getSegmentState);
- const appsmithConfig = getAppsmithConfigs();
-
- if (
- currentUser?.enableTelemetry &&
- appsmithConfig.segment.enabled &&
- !segmentState
- ) {
- yield race([
- take(ReduxActionTypes.SEGMENT_INITIALIZED),
- take(ReduxActionTypes.SEGMENT_INIT_UNCERTAIN),
- ]);
- }
-}
-
export function* getCurrentUserSaga(action?: {
payload?: { userProfile?: ApiResponse };
}) {
@@ -134,14 +108,10 @@ export function* getCurrentUserSaga(action?: {
}
function* initTrackers(currentUser: User) {
- const initializeSentry = initializeAnalyticsAndTrackers(currentUser);
-
- const sentryInitialized: boolean = yield initializeSentry;
-
- if (sentryInitialized) {
- yield put(segmentInitSuccess());
- } else {
- yield put(segmentInitUncertain());
+ try {
+ yield call(AnalyticsUtil.initialize, currentUser);
+ } catch (e) {
+ log.error(e);
}
}
diff --git a/app/client/src/ce/utils/Analytics/getEventExtraProperties.ts b/app/client/src/ce/utils/Analytics/getEventExtraProperties.ts
new file mode 100644
index 000000000000..05f3192d5932
--- /dev/null
+++ b/app/client/src/ce/utils/Analytics/getEventExtraProperties.ts
@@ -0,0 +1,36 @@
+import { getAppsmithConfigs } from "ee/configs";
+import TrackedUser from "ee/utils/Analytics/trackedUser";
+import { noop } from "lodash";
+
+let instanceId = "";
+
+function initLicense() {
+ return noop();
+}
+
+function initInstanceId(id: string) {
+ instanceId = id;
+}
+
+function getInstanceId() {
+ return instanceId;
+}
+
+function getEventExtraProperties() {
+ const { appVersion } = getAppsmithConfigs();
+ let userData;
+
+ try {
+ userData = TrackedUser.getInstance().getUser();
+ } catch (e) {
+ userData = {};
+ }
+
+ return {
+ instanceId,
+ version: appVersion.id,
+ userData,
+ };
+}
+
+export { getEventExtraProperties, initInstanceId, getInstanceId, initLicense };
diff --git a/app/client/src/ce/utils/Analytics/trackedUser.ts b/app/client/src/ce/utils/Analytics/trackedUser.ts
new file mode 100644
index 000000000000..baca30d04222
--- /dev/null
+++ b/app/client/src/ce/utils/Analytics/trackedUser.ts
@@ -0,0 +1,117 @@
+import { ANONYMOUS_USERNAME, type User } from "constants/userConstants";
+import { getAppsmithConfigs } from "ee/configs";
+import { sha256 } from "js-sha256";
+
+interface TrackedUserProperties {
+ userId: string;
+ source: string;
+ email?: string;
+ name?: string;
+ emailVerified?: boolean;
+}
+
+/**
+ * Function to get the application id from the URL
+ * @param location current location object based on URL
+ * @returns application id
+ */
+export function getApplicationId(location: Location) {
+ const pathSplit = location.pathname.split("/");
+ const applicationsIndex = pathSplit.findIndex(
+ (path) => path === "applications",
+ );
+
+ if (applicationsIndex === -1 || applicationsIndex + 1 >= pathSplit.length) {
+ return undefined;
+ }
+
+ return pathSplit[applicationsIndex + 1];
+}
+
+class TrackedUser {
+ private static instance: TrackedUser;
+ private readonly user: User;
+ private readonly userId: string;
+ public readonly selfHosted: boolean;
+
+ protected constructor(user: User) {
+ this.user = user;
+ const { cloudHosting, segment } = getAppsmithConfigs();
+
+ this.selfHosted = !(segment.apiKey || cloudHosting);
+
+ if (this.selfHosted) {
+ this.userId = sha256(user.username);
+ } else {
+ this.userId = user.username;
+ }
+ }
+
+ static init(user: User) {
+ if (!TrackedUser.instance) {
+ TrackedUser.instance = new TrackedUser(user);
+ }
+
+ return TrackedUser.instance;
+ }
+
+ static getInstance(): TrackedUser {
+ if (!TrackedUser.instance) {
+ throw new Error("TrackedUser is not initialized. Call init() first.");
+ }
+
+ return TrackedUser.instance;
+ }
+
+ protected getUserSource(): string {
+ return this.selfHosted ? "ce" : "cloud";
+ }
+
+ public getUser(): TrackedUserProperties {
+ if (this.selfHosted) {
+ return this.getAnonymousUserDetails();
+ } else {
+ return this.getAllUserDetails();
+ }
+ }
+
+ public getEventUserProperties() {
+ const { email, userId } = this.getUser();
+
+ if (this.userId === ANONYMOUS_USERNAME) {
+ return undefined;
+ }
+
+ const appId = getApplicationId(window.location);
+
+ return {
+ userId,
+ email,
+ appId: this.selfHosted ? undefined : appId,
+ };
+ }
+
+ private getAllUserDetails() {
+ const { email, emailVerified, name } = this.user;
+ const source = this.getUserSource();
+
+ return {
+ userId: this.userId,
+ source,
+ email,
+ name,
+ emailVerified,
+ };
+ }
+
+ private getAnonymousUserDetails() {
+ const source = this.getUserSource();
+
+ return {
+ userId: this.userId,
+ source,
+ };
+ }
+}
+
+export default TrackedUser;
diff --git a/app/client/src/ce/utils/AnalyticsUtil.tsx b/app/client/src/ce/utils/AnalyticsUtil.tsx
index 4aebc519ed61..622ad9c59c2a 100644
--- a/app/client/src/ce/utils/AnalyticsUtil.tsx
+++ b/app/client/src/ce/utils/AnalyticsUtil.tsx
@@ -1,375 +1,139 @@
-// Events
-import * as log from "loglevel";
-import smartlookClient from "smartlook-client";
+import log from "loglevel";
import { getAppsmithConfigs } from "ee/configs";
-import * as Sentry from "@sentry/react";
import type { User } from "constants/userConstants";
import { ANONYMOUS_USERNAME } from "constants/userConstants";
-import { sha256 } from "js-sha256";
import type { EventName } from "ee/utils/analyticsUtilTypes";
+import type { EventProperties } from "@segment/analytics-next";
-export function getUserSource() {
- const { cloudHosting, segment } = getAppsmithConfigs();
- const source = cloudHosting || segment.apiKey ? "cloud" : "ce";
+import SegmentSingleton from "utils/Analytics/segment";
+import MixpanelSingleton from "utils/Analytics/mixpanel";
+import SentryUtil from "utils/Analytics/sentry";
+import SmartlookUtil from "utils/Analytics/smartlook";
+import TrackedUser from "ee/utils/Analytics/trackedUser";
- return source;
-}
-
-declare global {
- interface Window {
- // Zipy is added via script tags in index.html
- zipy: {
- identify: (uid: string, userInfo: Record<string, string>) => void;
- anonymize: () => void;
- };
- }
-}
-
-export const parentContextTypeTokens = ["pkg", "workflow"];
-
-/**
- * Function to check the current URL and return the parent context.
- * For app, function was returning app name due to the way app urls are structured
- * So this function will only return the parent context for pkg and workflow
- * @param location current location object based on URL
- * @returns object {id, type} where type is either pkg or workflow and id is the id of the pkg or workflow
- */
-export function getParentContextFromURL(location: Location) {
- const pathSplit = location.pathname.split("/");
- let type = parentContextTypeTokens[0];
- const editorIndex = pathSplit.findIndex((path) =>
- parentContextTypeTokens.includes(path),
- );
-
- if (editorIndex !== -1) {
- type = pathSplit[editorIndex];
-
- const id = pathSplit[editorIndex + 1];
-
- return { id, type };
- }
-}
-
-export function getApplicationId(location: Location) {
- const pathSplit = location.pathname.split("/");
- const applicationsIndex = pathSplit.findIndex(
- (path) => path === "applications",
- );
- const appId = pathSplit[applicationsIndex + 1];
-
- return appId;
-}
+import {
+ initLicense,
+ initInstanceId,
+ getInstanceId,
+ getEventExtraProperties,
+} from "ee/utils/Analytics/getEventExtraProperties";
export enum AnalyticsEventType {
error = "error",
}
-class AnalyticsUtil {
- static cachedAnonymoustId: string;
- static cachedUserId: string;
- static user?: User = undefined;
- static blockTrackEvent: boolean | undefined;
- static instanceId?: string = "";
- static blockErrorLogs = false;
-
- static initializeSmartLook(id: string) {
- smartlookClient.init(id);
- }
-
- static async initializeSegment(key: string) {
- const initPromise = new Promise<boolean>((resolve) => {
- // TODO: Fix this the next time the file is edited
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
- (function init(window: any) {
- const analytics = (window.analytics = window.analytics || []);
-
- if (!analytics.initialize) {
- if (analytics.invoked) {
- log.error("Segment snippet included twice.");
- } else {
- analytics.invoked = !0;
- analytics.methods = [
- "trackSubmit",
- "trackClick",
- "trackLink",
- "trackForm",
- "pageview",
- "identify",
- "reset",
- "group",
- "track",
- "ready",
- "alias",
- "debug",
- "page",
- "once",
- "off",
- "on",
- ];
- // TODO: Fix this the next time the file is edited
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
- analytics.factory = function (t: any) {
- return function () {
- const e = Array.prototype.slice.call(arguments); //eslint-disable-line prefer-rest-params
-
- e.unshift(t);
- analytics.push(e);
-
- return analytics;
- };
- };
- }
+let blockErrorLogs = false;
+let segmentAnalytics: SegmentSingleton | null = null;
- // TODO: Fix this the next time the file is edited
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
- for (let t: any = 0; t < analytics.methods.length; t++) {
- const e = analytics.methods[t];
+async function initialize(user: User) {
+ SentryUtil.init();
+ await SmartlookUtil.init();
- analytics[e] = analytics.factory(e);
- }
+ segmentAnalytics = SegmentSingleton.getInstance();
- // TODO: Fix this the next time the file is edited
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
- analytics.load = function (t: any, e: any) {
- const n = document.createElement("script");
+ await segmentAnalytics.init();
- n.type = "text/javascript";
- n.async = !0;
- // Ref: https://www.notion.so/appsmith/530051a2083040b5bcec15a46121aea3
- n.src = "https://a.appsmith.com/reroute/" + t + "/main.js";
- // TODO: Fix this the next time the file is edited
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
- const a: any = document.getElementsByTagName("script")[0];
+ // Mixpanel needs to be initialized after Segment
+ await MixpanelSingleton.getInstance().init();
- a.parentNode.insertBefore(n, a);
- analytics._loadOptions = e;
- };
- analytics.ready(() => {
- resolve(true);
- });
- setTimeout(() => {
- resolve(false);
- }, 2000);
- analytics.SNIPPET_VERSION = "4.1.0";
- // Ref: https://segment.com/docs/connections/sources/catalog/libraries/website/javascript/#batching
- analytics.load(key, {
- integrations: {
- "Segment.io": {
- deliveryStrategy: {
- strategy: "batching", // The delivery strategy used for sending events to Segment
- config: {
- size: 100, // The batch size is the threshold that forces all batched events to be sent once it’s reached.
- timeout: 1000, // The number of milliseconds that forces all events queued for batching to be sent, regardless of the batch size, once it’s reached
- },
- },
- },
- },
- });
-
- if (!AnalyticsUtil.blockTrackEvent) {
- analytics.page();
- }
- }
- })(window);
- });
+ // Identify the user after all services are initialized
+ await identifyUser(user);
+}
- return initPromise;
+function logEvent(
+ eventName: EventName,
+ eventData?: EventProperties,
+ eventType?: AnalyticsEventType,
+) {
+ if (blockErrorLogs && eventType === AnalyticsEventType.error) {
+ return;
}
- static logEvent(
- eventName: EventName,
- // TODO: Fix this the next time the file is edited
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
- eventData: any = {},
- eventType?: AnalyticsEventType,
- ) {
- if (AnalyticsUtil.blockTrackEvent) {
- return;
- }
-
- if (
- AnalyticsUtil.blockErrorLogs &&
- eventType === AnalyticsEventType.error
- ) {
- return;
- }
+ const finalEventData = {
+ ...eventData,
+ ...getEventExtraProperties(),
+ };
- // TODO: Fix this the next time the file is edited
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
- const windowDoc: any = window;
- let finalEventData = eventData;
- const userData = AnalyticsUtil.user;
- const parentContext = getParentContextFromURL(windowDoc.location);
- const instanceId = AnalyticsUtil.instanceId;
- const appId = getApplicationId(windowDoc.location);
- const { appVersion, segment } = getAppsmithConfigs();
+ if (segmentAnalytics) {
+ segmentAnalytics.track(eventName, finalEventData);
+ }
+}
- if (userData) {
- const source = getUserSource();
- // TODO: Fix this the next time the file is edited
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
- let user: any = {};
+async function identifyUser(userData: User, sendAdditionalData?: boolean) {
+ const { appVersion } = getAppsmithConfigs();
- if (segment.apiKey) {
- user = {
- userId: userData.username,
- email: userData.email,
- appId,
- };
- } else {
- const userId = userData.username;
+ // we don't want to identify anonymous users (anonymous users are not logged-in users)
+ if (userData.isAnonymous || userData.username === ANONYMOUS_USERNAME) {
+ return;
+ }
- if (userId !== AnalyticsUtil.cachedUserId) {
- AnalyticsUtil.cachedAnonymoustId = sha256(userId);
- AnalyticsUtil.cachedUserId = userId;
- }
+ // Initialize the TrackedUser singleton
+ const trackedUserInstance = TrackedUser.init(userData);
- user = {
- userId: AnalyticsUtil.cachedAnonymoustId,
- };
- }
+ const trackedUser = trackedUserInstance.getUser();
+ const instanceId = getInstanceId();
- finalEventData = {
- ...eventData,
- userData:
- user.userId === ANONYMOUS_USERNAME ? undefined : { ...user, source },
- };
- }
+ const additionalData = {
+ id: trackedUser.userId,
+ version: `Appsmith ${appVersion.edition} ${appVersion.id}`,
+ instanceId,
+ };
- finalEventData = {
- ...finalEventData,
- instanceId,
- version: appVersion.id,
- ...(parentContext ? { parentContext } : {}),
+ if (segmentAnalytics) {
+ const userProperties = {
+ ...trackedUser,
+ ...(sendAdditionalData ? additionalData : {}),
};
- if (windowDoc.analytics) {
- log.debug("Event fired", eventName, finalEventData);
- windowDoc.analytics.track(eventName, finalEventData);
- } else {
- log.debug("Event fired locally", eventName, finalEventData);
- }
+ log.debug("Identify User " + trackedUser.userId);
+ await segmentAnalytics.identify(trackedUser.userId, userProperties);
}
- static identifyUser(userData: User, sendAdditionalData?: boolean) {
- const { appVersion, segment, sentry, smartLook } = getAppsmithConfigs();
- // TODO: Fix this the next time the file is edited
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
- const windowDoc: any = window;
- const userId = userData.username;
-
- if (windowDoc.analytics) {
- const source = getUserSource();
-
- // This flag is only set on Appsmith Cloud. In this case, we get more detailed analytics of the user
- if (segment.apiKey) {
- const userProperties = {
- userId: userId,
- source,
- email: userData.email,
- name: userData.name,
- emailVerified: userData.emailVerified,
- };
-
- AnalyticsUtil.user = userData;
- log.debug("Identify User " + userId);
- windowDoc.analytics.identify(userId, userProperties);
- } else if (segment.ceKey) {
- // This is a self-hosted instance. Only send data if the analytics are NOT disabled by the user
- if (userId !== AnalyticsUtil.cachedUserId) {
- AnalyticsUtil.cachedAnonymoustId = sha256(userId);
- AnalyticsUtil.cachedUserId = userId;
- }
-
- const userProperties = {
- userId: AnalyticsUtil.cachedAnonymoustId,
- source,
- ...(sendAdditionalData
- ? {
- id: AnalyticsUtil.cachedAnonymoustId,
- email: userData.email,
- version: `Appsmith ${appVersion.edition} ${appVersion.id}`,
- instanceId: AnalyticsUtil.instanceId,
- }
- : {}),
- };
-
- log.debug(
- "Identify Anonymous User " + AnalyticsUtil.cachedAnonymoustId,
- );
- windowDoc.analytics.identify(
- AnalyticsUtil.cachedAnonymoustId,
- userProperties,
- );
- }
- }
-
- if (sentry.enabled) {
- Sentry.configureScope(function (scope) {
- scope.setUser({
- id: userId,
- username: userData.username,
- email: userData.email,
- });
- });
- }
-
- if (smartLook.enabled) {
- smartlookClient.identify(userId, { email: userData.email });
- }
-
- // If zipy was included, identify this user on the platform
- if (window.zipy && userId) {
- window.zipy.identify(userId, {
- email: userData.email,
- username: userData.username,
- });
- }
+ SentryUtil.identifyUser(trackedUser.userId, userData);
- AnalyticsUtil.blockTrackEvent = false;
+ if (trackedUser.email) {
+ SmartlookUtil.identify(trackedUser.userId, trackedUser.email);
}
+}
- static initInstanceId(instanceId: string) {
- AnalyticsUtil.instanceId = instanceId;
- }
+function setBlockErrorLogs(value: boolean) {
+ blockErrorLogs = value;
+}
- static getAnonymousId() {
- // TODO: Fix this the next time the file is edited
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
- const windowDoc: any = window;
- const { segment } = getAppsmithConfigs();
+function getAnonymousId(): string | undefined | null {
+ const { segment } = getAppsmithConfigs();
- if (windowDoc.analytics && windowDoc.analytics.user) {
- return windowDoc.analytics.user().anonymousId();
- } else if (segment.enabled) {
- return localStorage.getItem("ajs_anonymous_id")?.replaceAll('"', "");
- }
- }
-
- static reset() {
- // TODO: Fix this the next time the file is edited
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
- const windowDoc: any = window;
+ if (segmentAnalytics) {
+ const user = segmentAnalytics.getUser();
- if (windowDoc.Intercom) {
- windowDoc.Intercom("shutdown");
+ if (user) {
+ return user.anonymousId();
}
-
- windowDoc.analytics && windowDoc.analytics.reset();
- windowDoc.mixpanel && windowDoc.mixpanel.reset();
- window.zipy && window.zipy.anonymize();
+ } else if (segment.enabled) {
+ return localStorage.getItem("ajs_anonymous_id")?.replaceAll('"', "");
}
+}
- static removeAnalytics() {
- AnalyticsUtil.blockTrackEvent = false;
- // TODO: Fix this the next time the file is edited
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
- (window as any).analytics = undefined;
- }
+function reset() {
+ // TODO: Fix this the next time the file is edited
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ const windowDoc: any = window;
- static setBlockErrorLogs(value: boolean) {
- AnalyticsUtil.blockErrorLogs = value;
+ if (windowDoc.Intercom) {
+ windowDoc.Intercom("shutdown");
}
+
+ segmentAnalytics && segmentAnalytics.reset();
}
-export default AnalyticsUtil;
+export {
+ initialize,
+ logEvent,
+ identifyUser,
+ initInstanceId,
+ setBlockErrorLogs,
+ getAnonymousId,
+ reset,
+ getEventExtraProperties,
+ initLicense,
+};
diff --git a/app/client/src/ee/utils/Analytics/getEventExtraProperties.ts b/app/client/src/ee/utils/Analytics/getEventExtraProperties.ts
new file mode 100644
index 000000000000..15d392e3fc20
--- /dev/null
+++ b/app/client/src/ee/utils/Analytics/getEventExtraProperties.ts
@@ -0,0 +1,8 @@
+import {
+ getEventExtraProperties,
+ initInstanceId,
+ getInstanceId,
+ initLicense,
+} from "ce/utils/Analytics/getEventExtraProperties";
+
+export { getEventExtraProperties, initInstanceId, getInstanceId, initLicense };
diff --git a/app/client/src/ee/utils/Analytics/trackedUser.ts b/app/client/src/ee/utils/Analytics/trackedUser.ts
new file mode 100644
index 000000000000..e644d5912683
--- /dev/null
+++ b/app/client/src/ee/utils/Analytics/trackedUser.ts
@@ -0,0 +1,3 @@
+import { default as CE_TrackedUser } from "ce/utils/Analytics/trackedUser";
+
+export default CE_TrackedUser;
diff --git a/app/client/src/ee/utils/AnalyticsUtil.tsx b/app/client/src/ee/utils/AnalyticsUtil.tsx
index 46fb527986c4..a051fb50050e 100644
--- a/app/client/src/ee/utils/AnalyticsUtil.tsx
+++ b/app/client/src/ee/utils/AnalyticsUtil.tsx
@@ -1,3 +1,4 @@
export * from "ce/utils/AnalyticsUtil";
-import { default as CE_AnalyticsUtil } from "ce/utils/AnalyticsUtil";
+import * as CE_AnalyticsUtil from "ce/utils/AnalyticsUtil";
+
export default CE_AnalyticsUtil;
diff --git a/app/client/src/entities/Engine/AppEditorEngine.ts b/app/client/src/entities/Engine/AppEditorEngine.ts
index b69063d05cd1..30ee9158ae7c 100644
--- a/app/client/src/entities/Engine/AppEditorEngine.ts
+++ b/app/client/src/entities/Engine/AppEditorEngine.ts
@@ -47,10 +47,7 @@ import AppEngine, {
} from ".";
import { fetchJSLibraries } from "actions/JSLibraryActions";
import CodemirrorTernService from "utils/autocomplete/CodemirrorTernService";
-import {
- waitForSegmentInit,
- waitForFetchUserSuccess,
-} from "ee/sagas/userSagas";
+import { waitForFetchUserSuccess } from "ee/sagas/userSagas";
import { getFirstTimeUserOnboardingComplete } from "selectors/onboardingSelectors";
import { isAirgapped } from "ee/utils/airgapHelpers";
import { getAIPromptTriggered, setLatestGitBranchInLocal } from "utils/storage";
@@ -182,14 +179,6 @@ export default class AppEditorEngine extends AppEngine {
yield call(waitForFetchUserSuccess);
endSpan(waitForUserSpan);
- const waitForSegmentInitSpan = startNestedSpan(
- "AppEditorEngine.waitForSegmentInit",
- rootSpan,
- );
-
- yield call(waitForSegmentInit, true);
- endSpan(waitForSegmentInitSpan);
-
const waitForFetchEnvironmentsSpan = startNestedSpan(
"AppEditorEngine.waitForFetchEnvironments",
rootSpan,
diff --git a/app/client/src/entities/Engine/AppViewerEngine.ts b/app/client/src/entities/Engine/AppViewerEngine.ts
index f088f615812a..fc5aa028e116 100644
--- a/app/client/src/entities/Engine/AppViewerEngine.ts
+++ b/app/client/src/entities/Engine/AppViewerEngine.ts
@@ -21,10 +21,7 @@ import {
import type { AppEnginePayload } from ".";
import AppEngine, { ActionsNotFoundError } from ".";
import { fetchJSLibraries } from "actions/JSLibraryActions";
-import {
- waitForSegmentInit,
- waitForFetchUserSuccess,
-} from "ee/sagas/userSagas";
+import { waitForFetchUserSuccess } from "ee/sagas/userSagas";
import { fetchJSCollectionsForView } from "actions/jsActionActions";
import {
fetchAppThemesAction,
@@ -145,14 +142,6 @@ export default class AppViewerEngine extends AppEngine {
yield call(waitForFetchUserSuccess);
endSpan(waitForUserSpan);
- const waitForSegmentSpan = startNestedSpan(
- "AppViewerEngine.waitForSegmentInit",
- rootSpan,
- );
-
- yield call(waitForSegmentInit, true);
- endSpan(waitForSegmentSpan);
-
yield put(fetchAllPageEntityCompletion([executePageLoadActions()]));
endSpan(loadAppEntitiesSpan);
diff --git a/app/client/src/git/hooks/useAppsmithEnterpriseUrl.ts b/app/client/src/git/hooks/useAppsmithEnterpriseUrl.ts
index 7313c2bb1e71..dfe46397247e 100644
--- a/app/client/src/git/hooks/useAppsmithEnterpriseUrl.ts
+++ b/app/client/src/git/hooks/useAppsmithEnterpriseUrl.ts
@@ -2,11 +2,20 @@ import { getInstanceId } from "ee/selectors/tenantSelectors";
import { useSelector } from "react-redux";
import { ENTERPRISE_PRICING_PAGE } from "constants/ThirdPartyConstants";
import { useMemo } from "react";
-import { getUserSource } from "ee/utils/AnalyticsUtil";
+import TrackedUser from "ee/utils/Analytics/trackedUser";
+import log from "loglevel";
export const useAppsmithEnterpriseUrl = (feature: string) => {
const instanceId = useSelector(getInstanceId);
- const source = getUserSource();
+ let source = "unknown";
+
+ try {
+ const user = TrackedUser.getInstance().getUser();
+
+ source = user.source;
+ } catch (e) {
+ log.error("Failed to get user source:", e);
+ }
const constructedUrl = useMemo(() => {
const url = new URL(ENTERPRISE_PRICING_PAGE);
diff --git a/app/client/src/pages/AdminSettings/index.tsx b/app/client/src/pages/AdminSettings/index.tsx
index 36828beb4628..5067e7ce6d2b 100644
--- a/app/client/src/pages/AdminSettings/index.tsx
+++ b/app/client/src/pages/AdminSettings/index.tsx
@@ -13,6 +13,7 @@ import { LoaderContainer } from "pages/AdminSettings/components";
import { useParams } from "react-router";
import AdminConfig from "ee/pages/AdminSettings/config";
import { Spinner } from "@appsmith/ads";
+import MixpanelSingleton from "../../utils/Analytics/mixpanel";
const FlexContainer = styled.div`
display: flex;
@@ -31,6 +32,16 @@ function Settings() {
subCategory ?? category,
);
+ useEffect(() => {
+ // Stop recording this screen
+ MixpanelSingleton.getInstance().stopRecording();
+
+ return () => {
+ // Start recording after this screen unmounts
+ MixpanelSingleton.getInstance().startRecording();
+ };
+ }, []);
+
useEffect(() => {
if (user?.isSuperUser) {
dispatch({
diff --git a/app/client/src/pages/Editor/gitSync/GitSettingsModal/TabBranch/hooks.ts b/app/client/src/pages/Editor/gitSync/GitSettingsModal/TabBranch/hooks.ts
index d93e825d06db..79adb77e8a1c 100644
--- a/app/client/src/pages/Editor/gitSync/GitSettingsModal/TabBranch/hooks.ts
+++ b/app/client/src/pages/Editor/gitSync/GitSettingsModal/TabBranch/hooks.ts
@@ -2,12 +2,23 @@ import { getInstanceId } from "ee/selectors/tenantSelectors";
import { useSelector } from "react-redux";
import { ENTERPRISE_PRICING_PAGE } from "constants/ThirdPartyConstants";
import { useMemo } from "react";
-import { getUserSource } from "ee/utils/AnalyticsUtil";
+import TrackedUser from "ee/utils/Analytics/trackedUser";
+import log from "loglevel";
export const useAppsmithEnterpriseLink = (feature: string) => {
const instanceId = useSelector(getInstanceId);
- const source = getUserSource();
- const constructedUrl = useMemo(() => {
+
+ let source = "unknown";
+
+ try {
+ const user = TrackedUser.getInstance().getUser();
+
+ source = user.source;
+ } catch (e) {
+ log.error("Failed to get user source:", e);
+ }
+
+ return useMemo(() => {
const url = new URL(ENTERPRISE_PRICING_PAGE);
if (source) url.searchParams.append("source", source);
@@ -18,6 +29,4 @@ export const useAppsmithEnterpriseLink = (feature: string) => {
return url.href;
}, [source, instanceId, feature]);
-
- return constructedUrl;
};
diff --git a/app/client/src/reducers/uiReducers/analyticsReducer.ts b/app/client/src/reducers/uiReducers/analyticsReducer.ts
deleted file mode 100644
index debb5416d845..000000000000
--- a/app/client/src/reducers/uiReducers/analyticsReducer.ts
+++ /dev/null
@@ -1,37 +0,0 @@
-import { ReduxActionTypes } from "ee/constants/ReduxActionConstants";
-import { createReducer } from "utils/ReducerUtils";
-
-export type SegmentState = "INIT_SUCCESS" | "INIT_UNCERTAIN";
-
-export const initialState: AnalyticsReduxState = {
- telemetry: {},
-};
-
-export interface AnalyticsReduxState {
- telemetry: {
- segmentState?: SegmentState;
- };
-}
-
-export const handlers = {
- [ReduxActionTypes.SEGMENT_INITIALIZED]: (
- state: AnalyticsReduxState,
- ): AnalyticsReduxState => ({
- ...state,
- telemetry: {
- ...state.telemetry,
- segmentState: "INIT_SUCCESS",
- },
- }),
- [ReduxActionTypes.SEGMENT_INIT_UNCERTAIN]: (
- state: AnalyticsReduxState,
- ): AnalyticsReduxState => ({
- ...state,
- telemetry: {
- ...state.telemetry,
- segmentState: "INIT_UNCERTAIN",
- },
- }),
-};
-
-export default createReducer(initialState, handlers);
diff --git a/app/client/src/selectors/analyticsSelectors.tsx b/app/client/src/selectors/analyticsSelectors.tsx
deleted file mode 100644
index 0f3eb5ba64bd..000000000000
--- a/app/client/src/selectors/analyticsSelectors.tsx
+++ /dev/null
@@ -1,4 +0,0 @@
-import type { AppState } from "ee/reducers";
-
-export const getSegmentState = (state: AppState) =>
- state.ui.analytics.telemetry.segmentState;
diff --git a/app/client/src/utils/Analytics/mixpanel.ts b/app/client/src/utils/Analytics/mixpanel.ts
new file mode 100644
index 000000000000..cc7f6e382886
--- /dev/null
+++ b/app/client/src/utils/Analytics/mixpanel.ts
@@ -0,0 +1,132 @@
+import log from "loglevel";
+import type { OverridedMixpanel } from "mixpanel-browser";
+import { getAppsmithConfigs } from "ee/configs";
+import SegmentSingleton from "./segment";
+import type { ID } from "@segment/analytics-next";
+
+class MixpanelSingleton {
+ private static instance: MixpanelSingleton;
+ private mixpanel: OverridedMixpanel | null = null;
+
+ public static getInstance(): MixpanelSingleton {
+ if (!MixpanelSingleton.instance) {
+ MixpanelSingleton.instance = new MixpanelSingleton();
+ }
+
+ return MixpanelSingleton.instance;
+ }
+
+ // Segment needs to be initialized before Mixpanel
+ public async init(): Promise<boolean> {
+ if (this.mixpanel) {
+ log.warn("Mixpanel is already initialized.");
+
+ return true;
+ }
+
+ try {
+ const { default: loadedMixpanel } = await import("mixpanel-browser");
+ const { mixpanel } = getAppsmithConfigs();
+
+ if (mixpanel.enabled) {
+ this.mixpanel = loadedMixpanel;
+ this.mixpanel.init(mixpanel.apiKey, {
+ record_sessions_percent: 100,
+ });
+
+ await this.addSegmentMiddleware();
+ }
+
+ return true;
+ } catch (error) {
+ log.error("Failed to initialize Mixpanel:", error);
+
+ return false;
+ }
+ }
+
+ public startRecording() {
+ if (this.mixpanel) {
+ this.mixpanel.start_session_recording();
+ }
+ }
+
+ public stopRecording() {
+ if (this.mixpanel) {
+ this.mixpanel.stop_session_recording();
+ }
+ }
+
+ private registerDevice(token: string) {
+ if (this.mixpanel) {
+ this.mixpanel.register({ $device_id: token, distinct_id: token });
+ } else {
+ log.warn("Mixpanel is not initialized.");
+ }
+ }
+
+ private identify(userId: ID) {
+ if (!userId) {
+ log.warn("Mixpanel identify was called without userId.");
+
+ return;
+ }
+
+ if (this.mixpanel) {
+ this.mixpanel.identify(userId);
+ } else {
+ log.warn("Mixpanel is not initialized.");
+ }
+ }
+
+ private getSessionRecordingProperties() {
+ if (this.mixpanel) {
+ return this.mixpanel.get_session_recording_properties();
+ } else {
+ log.warn("Mixpanel is not initialized.");
+
+ return {};
+ }
+ }
+
+ // Middleware to add Mixpanel's session recording properties to Segment events
+ // https://segment.com/docs/connections/sources/catalog/libraries/website/javascript/middleware/
+ // https://docs.mixpanel.com/docs/session-replay/session-replay-web#segment-analyticsjs
+ private async addSegmentMiddleware() {
+ if (this.mixpanel) {
+ await SegmentSingleton.getInstance().addMiddleware((middleware) => {
+ if (
+ middleware.payload.obj.type === "track" ||
+ middleware.payload.obj.type === "page"
+ ) {
+ const segmentDeviceId = middleware.payload.obj.anonymousId;
+
+ //original id
+ if (segmentDeviceId) {
+ this.registerDevice(segmentDeviceId);
+ }
+
+ const sessionReplayProperties = this.getSessionRecordingProperties();
+
+ // Add session recording properties to the event
+ middleware.payload.obj.properties = {
+ ...middleware.payload.obj.properties,
+ ...sessionReplayProperties,
+ };
+ }
+
+ if (middleware.payload.obj.type === "identify") {
+ const userId = middleware.payload.obj.userId;
+
+ this.identify(userId);
+ }
+
+ middleware.next(middleware.payload);
+ });
+ } else {
+ log.warn("Mixpanel is not initialized.");
+ }
+ }
+}
+
+export default MixpanelSingleton;
diff --git a/app/client/src/utils/Analytics/segment.ts b/app/client/src/utils/Analytics/segment.ts
new file mode 100644
index 000000000000..2aa73671174b
--- /dev/null
+++ b/app/client/src/utils/Analytics/segment.ts
@@ -0,0 +1,122 @@
+import {
+ type Analytics,
+ type EventProperties,
+ type MiddlewareFunction,
+ type UserTraits,
+} from "@segment/analytics-next";
+import { getAppsmithConfigs } from "ee/configs";
+import log from "loglevel";
+
+class SegmentSingleton {
+ private static instance: SegmentSingleton;
+ private analytics: Analytics | null = null;
+
+ public static getInstance(): SegmentSingleton {
+ if (!SegmentSingleton.instance) {
+ SegmentSingleton.instance = new SegmentSingleton();
+ }
+
+ return SegmentSingleton.instance;
+ }
+
+ public getUser() {
+ if (this.analytics) {
+ return this.analytics.user();
+ }
+ }
+
+ private getWriteKey(): string | undefined {
+ const { segment } = getAppsmithConfigs();
+
+ // This value is only enabled for Appsmith's cloud hosted version. It is not set in self-hosted environments
+ if (segment.apiKey) {
+ return segment.apiKey;
+ }
+
+ // This value is set in self-hosted environments. But if the analytics are disabled, it's never used.
+ if (segment.ceKey) {
+ return segment.ceKey;
+ }
+ }
+
+ public async init(): Promise<boolean> {
+ const { segment } = getAppsmithConfigs();
+
+ if (!segment.enabled) {
+ return true;
+ }
+
+ if (this.analytics) {
+ log.warn("Segment is already initialized.");
+
+ return true;
+ }
+
+ const writeKey = this.getWriteKey();
+
+ if (!writeKey) {
+ log.error("Segment key was not found.");
+
+ return true;
+ }
+
+ try {
+ const { AnalyticsBrowser } = await import("@segment/analytics-next");
+ const [analytics] = await AnalyticsBrowser.load(
+ { writeKey },
+ {
+ integrations: {
+ "Segment.io": {
+ deliveryStrategy: {
+ strategy: "batching", // The delivery strategy used for sending events to Segment
+ config: {
+ size: 100, // The batch size is the threshold that forces all batched events to be sent once it’s reached.
+ timeout: 1000, // The number of milliseconds that forces all events queued for batching to be sent, regardless of the batch size, once it’s reached
+ },
+ },
+ },
+ },
+ },
+ );
+
+ this.analytics = analytics;
+
+ return true;
+ } catch (error) {
+ log.error("Failed to initialize Segment:", error);
+
+ return false;
+ }
+ }
+
+ public track(eventName: string, eventData: EventProperties) {
+ // In scenarios where segment was never initialised, we are logging the event locally
+ // This is done so that we can debug event logging locally
+ if (this.analytics) {
+ log.debug("Event fired", eventName, eventData);
+ this.analytics.track(eventName, eventData);
+ } else {
+ log.debug("Event fired locally", eventName, eventData);
+ }
+ }
+
+ public async identify(userId: string, traits: UserTraits) {
+ if (this.analytics) {
+ await this.analytics.identify(userId, traits);
+ }
+ }
+
+ public async addMiddleware(middleware: MiddlewareFunction) {
+ if (this.analytics) {
+ await this.analytics.addSourceMiddleware(middleware);
+ }
+ }
+
+ public reset() {
+ if (this.analytics) {
+ this.analytics.reset();
+ }
+ }
+}
+
+export default SegmentSingleton;
diff --git a/app/client/src/utils/Analytics/sentry.ts b/app/client/src/utils/Analytics/sentry.ts
new file mode 100644
index 000000000000..23475001a806
--- /dev/null
+++ b/app/client/src/utils/Analytics/sentry.ts
@@ -0,0 +1,99 @@
+import * as Sentry from "@sentry/react";
+import { getAppsmithConfigs } from "ee/configs";
+import log from "loglevel";
+import type { User } from "constants/userConstants";
+
+class SentryUtil {
+ static init() {
+ const { sentry } = getAppsmithConfigs();
+
+ try {
+ if (sentry.enabled && !window.Sentry) {
+ window.Sentry = Sentry;
+ Sentry.init({
+ ...sentry,
+ beforeSend(event) {
+ const exception = SentryUtil.extractSentryException(event);
+
+ if (exception?.type === "ChunkLoadError") {
+ // Only log ChunkLoadErrors after the 2 retries
+ if (!exception.value?.includes("failed after 2 retries")) {
+ return null;
+ }
+ }
+
+ // Handle Non-Error rejections
+ if (exception?.value?.startsWith("Non-Error")) {
+ // TODO: Fix this the next time the file is edited
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ const serializedData: any = event.extra?.__serialized__;
+
+ if (!serializedData) return null; // if no data is attached, ignore error
+
+ const actualErrorMessage = serializedData.error
+ ? serializedData.error.message
+ : serializedData.message;
+
+ if (!actualErrorMessage) return null; // If no message is attached, ignore error
+
+ // Now modify the original error
+ exception.value = actualErrorMessage;
+ event.message = actualErrorMessage;
+ }
+
+ return event;
+ },
+ beforeBreadcrumb(breadcrumb) {
+ if (
+ breadcrumb.category === "console" &&
+ breadcrumb.level !== "error"
+ ) {
+ return null;
+ }
+
+ if (breadcrumb.category === "sentry.transaction") {
+ return null;
+ }
+
+ if (breadcrumb.category === "redux.action") {
+ if (
+ breadcrumb.data &&
+ breadcrumb.data.type === "SET_EVALUATED_TREE"
+ ) {
+ breadcrumb.data = undefined;
+ }
+ }
+
+ return breadcrumb;
+ },
+ });
+ }
+ } catch (error) {
+ log.error("Failed to initialize Sentry:", error);
+ }
+ }
+
+ public static identifyUser(userId: string, userData: User) {
+ const { sentry } = getAppsmithConfigs();
+
+ if (sentry.enabled) {
+ Sentry.configureScope(function (scope) {
+ scope.setUser({
+ id: userId,
+ username: userData.username,
+ email: userData.email,
+ });
+ });
+ }
+ }
+
+ private static extractSentryException(event: Sentry.Event) {
+ if (!event.exception) return null;
+
+ const value = event.exception.values ? event.exception.values[0] : null;
+
+ return value;
+ }
+}
+
+export default SentryUtil;
diff --git a/app/client/src/utils/Analytics/smartlook.ts b/app/client/src/utils/Analytics/smartlook.ts
new file mode 100644
index 000000000000..331022725f16
--- /dev/null
+++ b/app/client/src/utils/Analytics/smartlook.ts
@@ -0,0 +1,45 @@
+import type Smartlook from "smartlook-client";
+import { getAppsmithConfigs } from "ee/configs";
+import log from "loglevel";
+
+class SmartlookUtil {
+ private static smartlook: typeof Smartlook | null;
+
+ public static async init() {
+ const {
+ smartLook: { enabled, id },
+ } = getAppsmithConfigs();
+
+ if (this.smartlook) {
+ log.warn("Smartlook is already initialised.");
+
+ return;
+ }
+
+ if (enabled) {
+ try {
+ const { default: loadedSmartlook } = await import("smartlook-client");
+
+ // Sometimes smartlook could have been already initialized internally by
+ // the time this function is called
+ if (loadedSmartlook.initialized()) {
+ loadedSmartlook.init(id);
+ }
+
+ this.smartlook = loadedSmartlook;
+ } catch (e) {
+ log.error("Failed to initialize Smartlook:", e);
+ }
+ }
+ }
+
+ public static identify(userId: string, email: string) {
+ if (this.smartlook) {
+ this.smartlook.identify(userId, {
+ email,
+ });
+ }
+ }
+}
+
+export default SmartlookUtil;
diff --git a/app/client/src/utils/AppsmithUtils.tsx b/app/client/src/utils/AppsmithUtils.tsx
index 227b2c3ebba3..9152e4a48133 100644
--- a/app/client/src/utils/AppsmithUtils.tsx
+++ b/app/client/src/utils/AppsmithUtils.tsx
@@ -1,127 +1,14 @@
-import { getAppsmithConfigs } from "ee/configs";
import { ERROR_CODES } from "ee/constants/ApiConstants";
import { createMessage, ERROR_500 } from "ee/constants/messages";
-import * as Sentry from "@sentry/react";
-import type { Property } from "api/ActionAPI";
import type { AppIconName } from "@appsmith/ads-old";
import { AppIconCollection } from "@appsmith/ads-old";
import _, { isPlainObject } from "lodash";
-import * as log from "loglevel";
+import log from "loglevel";
import { osName } from "react-device-detect";
import type { ActionDataState } from "ee/reducers/entityReducers/actionsReducer";
import type { JSCollectionData } from "ee/reducers/entityReducers/jsActionsReducer";
-import AnalyticsUtil from "ee/utils/AnalyticsUtil";
import type { CreateNewActionKeyInterface } from "ee/entities/Engine/actionHelpers";
import { CreateNewActionKey } from "ee/entities/Engine/actionHelpers";
-import { ANONYMOUS_USERNAME } from "../constants/userConstants";
-import type { User } from "constants/userConstants";
-
-export const initializeAnalyticsAndTrackers = async (currentUser: User) => {
- const appsmithConfigs = getAppsmithConfigs();
-
- try {
- if (appsmithConfigs.sentry.enabled && !window.Sentry) {
- window.Sentry = Sentry;
- Sentry.init({
- ...appsmithConfigs.sentry,
- beforeSend(event) {
- const exception = extractSentryException(event);
-
- if (exception?.type === "ChunkLoadError") {
- // Only log ChunkLoadErrors after the 2 retires
- if (!exception.value?.includes("failed after 2 retries")) {
- return null;
- }
- }
-
- // Handle Non-Error rejections
- if (exception?.value?.startsWith("Non-Error")) {
- // TODO: Fix this the next time the file is edited
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
- const serializedData: any = event.extra?.__serialized__;
-
- if (!serializedData) return null; // if no data is attached, ignore error
-
- const actualErrorMessage = serializedData.error
- ? serializedData.error.message
- : serializedData.message;
-
- if (!actualErrorMessage) return null; // If no message is attached, ignore error
-
- // Now modify the original error
- exception.value = actualErrorMessage;
- event.message = actualErrorMessage;
- }
-
- return event;
- },
- beforeBreadcrumb(breadcrumb) {
- if (
- breadcrumb.category === "console" &&
- breadcrumb.level !== "error"
- ) {
- return null;
- }
-
- if (breadcrumb.category === "sentry.transaction") {
- return null;
- }
-
- if (breadcrumb.category === "redux.action") {
- if (
- breadcrumb.data &&
- breadcrumb.data.type === "SET_EVALUATED_TREE"
- ) {
- breadcrumb.data = undefined;
- }
- }
-
- return breadcrumb;
- },
- });
- }
- } catch (e) {
- log.error(e);
- }
-
- try {
- // TODO: Fix this the next time the file is edited
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
- if (appsmithConfigs.smartLook.enabled && !(window as any).smartlook) {
- const { id } = appsmithConfigs.smartLook;
-
- AnalyticsUtil.initializeSmartLook(id);
- }
-
- // TODO: Fix this the next time the file is edited
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
- if (appsmithConfigs.segment.enabled && !(window as any).analytics) {
- if (appsmithConfigs.segment.apiKey) {
- // This value is only enabled for Appsmith's cloud hosted version. It is not set in self-hosted environments
- await AnalyticsUtil.initializeSegment(appsmithConfigs.segment.apiKey);
- } else if (appsmithConfigs.segment.ceKey) {
- // This value is set in self-hosted environments. But if the analytics are disabled, it's never used.
- await AnalyticsUtil.initializeSegment(appsmithConfigs.segment.ceKey);
- }
- }
-
- if (
- !currentUser.isAnonymous &&
- currentUser.username !== ANONYMOUS_USERNAME
- ) {
- await AnalyticsUtil.identifyUser(currentUser);
- }
- } catch (e) {
- Sentry.captureException(e);
- log.error(e);
- }
-};
-
-export const mapToPropList = (map: Record<string, string>): Property[] => {
- return _.map(map, (value, key) => {
- return { key: key, value: value };
- });
-};
export const INTERACTION_ANALYTICS_EVENT = "INTERACTION_ANALYTICS_EVENT";
@@ -581,11 +468,3 @@ export function getDatatype(value: unknown) {
return DataType.UNDEFINED;
}
}
-
-function extractSentryException(event: Sentry.Event) {
- if (!event.exception) return null;
-
- const value = event.exception.values ? event.exception.values[0] : null;
-
- return value;
-}
diff --git a/app/client/yarn.lock b/app/client/yarn.lock
index 6b67641dc647..3d018b6438d8 100644
--- a/app/client/yarn.lock
+++ b/app/client/yarn.lock
@@ -4417,6 +4417,22 @@ __metadata:
languageName: node
linkType: hard
+"@lukeed/csprng@npm:^1.1.0":
+ version: 1.1.0
+ resolution: "@lukeed/csprng@npm:1.1.0"
+ checksum: 926f5f7fc629470ca9a8af355bfcd0271d34535f7be3890f69902432bddc3262029bb5dbe9025542cf6c9883d878692eef2815fc2f3ba5b92e9da1f9eba2e51b
+ languageName: node
+ linkType: hard
+
+"@lukeed/uuid@npm:^2.0.0":
+ version: 2.0.1
+ resolution: "@lukeed/uuid@npm:2.0.1"
+ dependencies:
+ "@lukeed/csprng": ^1.1.0
+ checksum: f5e71e4da852dbff49b93cad27d5a2f61c2241e307bbe89b3b54b889ecb7927f2487246467f90ebb6cbdb7e0ac2a213e2e58b1182cb7990cef6e049aa7c39e7b
+ languageName: node
+ linkType: hard
+
"@manaflair/redux-batch@npm:^1.0.0":
version: 1.0.0
resolution: "@manaflair/redux-batch@npm:1.0.0"
@@ -8181,6 +8197,82 @@ __metadata:
languageName: node
linkType: hard
+"@segment/analytics-core@npm:1.8.0":
+ version: 1.8.0
+ resolution: "@segment/analytics-core@npm:1.8.0"
+ dependencies:
+ "@lukeed/uuid": ^2.0.0
+ "@segment/analytics-generic-utils": 1.2.0
+ dset: ^3.1.4
+ tslib: ^2.4.1
+ checksum: c8e2a98670658d6400d8e517e141aff6eff581a12a4015ce8ff906185d148cf9dad79cc5bfb5376195794cc0c964a9c9ca79d36f3d4b49affeb7344251dcde1f
+ languageName: node
+ linkType: hard
+
+"@segment/analytics-generic-utils@npm:1.2.0":
+ version: 1.2.0
+ resolution: "@segment/analytics-generic-utils@npm:1.2.0"
+ dependencies:
+ tslib: ^2.4.1
+ checksum: f36aa093722e4f51dddd4dfa37164bd082175bb0c0960096f9b03073c482e96a17012bc99782259a9d3787e52a48f03ab3447902c6c635654a8ce544892073e5
+ languageName: node
+ linkType: hard
+
+"@segment/analytics-next@npm:^1.76.0":
+ version: 1.76.0
+ resolution: "@segment/analytics-next@npm:1.76.0"
+ dependencies:
+ "@lukeed/uuid": ^2.0.0
+ "@segment/analytics-core": 1.8.0
+ "@segment/analytics-generic-utils": 1.2.0
+ "@segment/analytics.js-video-plugins": ^0.2.1
+ "@segment/facade": ^3.4.9
+ dset: ^3.1.4
+ js-cookie: 3.0.1
+ node-fetch: ^2.6.7
+ tslib: ^2.4.1
+ unfetch: ^4.1.0
+ checksum: 0819212b39499b4ba5a02dd9c58ed0716bbb236237f458f641842b72f3766620142d57bbb583fb5fe8be13d6d3871ff970f0c76002ebcf691411e92b32089cc7
+ languageName: node
+ linkType: hard
+
+"@segment/analytics.js-video-plugins@npm:^0.2.1":
+ version: 0.2.1
+ resolution: "@segment/analytics.js-video-plugins@npm:0.2.1"
+ dependencies:
+ unfetch: ^3.1.1
+ checksum: 284b42bb05569366ac4a7c51c90d64bcea64315b2dd330ff8b58c63fa11949443b3d2f7e92d2e3c118495e9018352249183f7d3fb05e4b904148302536d385ba
+ languageName: node
+ linkType: hard
+
+"@segment/facade@npm:^3.4.9":
+ version: 3.4.10
+ resolution: "@segment/facade@npm:3.4.10"
+ dependencies:
+ "@segment/isodate-traverse": ^1.1.1
+ inherits: ^2.0.4
+ new-date: ^1.0.3
+ obj-case: 0.2.1
+ checksum: 5d10861f586ecebe3a71b25c9f37b3c922298188965047efcfd5b7e6f7147dc6967c3760726c43db99f33ef285191498e0726fc8d2556d5bdd82312a5f647ef2
+ languageName: node
+ linkType: hard
+
+"@segment/isodate-traverse@npm:^1.1.1":
+ version: 1.1.1
+ resolution: "@segment/isodate-traverse@npm:1.1.1"
+ dependencies:
+ "@segment/isodate": ^1.0.3
+ checksum: 06f783623c74a7a2310bdcca50355a1f7b9cbb7a1d77f0c7408def29bd0a355dbc2ff31516d025b7cd6baebfdca7d771fb62899f446366f86cd6d34cae9a7000
+ languageName: node
+ linkType: hard
+
+"@segment/isodate@npm:1.0.3, @segment/isodate@npm:^1.0.3":
+ version: 1.0.3
+ resolution: "@segment/isodate@npm:1.0.3"
+ checksum: 31faf12e83fa6ab5ba7dfd5600dfaf8d224a00ab24f3a2d3d9ba7f4ecdc1683a55c00fc9246585361aa5cb67c6d7846e1d5497cc3bcca58c105902b79c91c34a
+ languageName: node
+ linkType: hard
+
"@sentry/browser@npm:6.2.4":
version: 6.2.4
resolution: "@sentry/browser@npm:6.2.4"
@@ -12733,6 +12825,7 @@ __metadata:
"@redux-saga/core": 1.1.3
"@redux-saga/types": 1.2.1
"@reduxjs/toolkit": ^2.4.0
+ "@segment/analytics-next": ^1.76.0
"@sentry/react": ^6.2.4
"@sentry/webpack-plugin": ^1.18.9
"@shared/ast": "workspace:^"
@@ -17169,6 +17262,13 @@ __metadata:
languageName: node
linkType: hard
+"dset@npm:^3.1.4":
+ version: 3.1.4
+ resolution: "dset@npm:3.1.4"
+ checksum: 9a7677e9ffd3c13ad850f7cf367aa94b39984006510e84c3c09b7b88bba0a5b3b7196d85a99d0c4cae4e47d67bdeca43dc1834a41d80f31bcdc86dd26121ecec
+ languageName: node
+ linkType: hard
+
"duck@npm:^0.1.12":
version: 0.1.12
resolution: "duck@npm:0.1.12"
@@ -22956,6 +23056,13 @@ __metadata:
languageName: node
linkType: hard
+"js-cookie@npm:3.0.1":
+ version: 3.0.1
+ resolution: "js-cookie@npm:3.0.1"
+ checksum: bb48de67e2a6bd1ae3dfd6b2d5a167c33dd0c5a37e909206161eb0358c98f17cb55acd55827a58e9eea3630d89444e7479f7938ef4420dda443218b8c434a4c3
+ languageName: node
+ linkType: hard
+
"js-levenshtein@npm:^1.1.6":
version: 1.1.6
resolution: "js-levenshtein@npm:1.1.6"
@@ -25360,6 +25467,15 @@ __metadata:
languageName: node
linkType: hard
+"new-date@npm:^1.0.3":
+ version: 1.0.3
+ resolution: "new-date@npm:1.0.3"
+ dependencies:
+ "@segment/isodate": 1.0.3
+ checksum: 5bc778542276f5d947b77654f10ad796c7502b184bd7f9b87749064a3f69a5cb5631acfceb234b433b3408cfe151de34ee484d5751d1fd87a74d6ec1e7e1ac9c
+ languageName: node
+ linkType: hard
+
"no-case@npm:^3.0.4":
version: 3.0.4
resolution: "no-case@npm:3.0.4"
@@ -25659,6 +25775,13 @@ __metadata:
languageName: node
linkType: hard
+"obj-case@npm:0.2.1":
+ version: 0.2.1
+ resolution: "obj-case@npm:0.2.1"
+ checksum: 2726b29d054027c52c6ac1a18531c3f995fcc313047847c7f7357889a56cf07bd88bef459bd4645c139fa56f9432c282806e0f1c7ab444d6cbdb662e39073e36
+ languageName: node
+ linkType: hard
+
"object-assign@npm:^4.0.1, object-assign@npm:^4.1.0, object-assign@npm:^4.1.1":
version: 4.1.1
resolution: "object-assign@npm:4.1.1"
@@ -32804,10 +32927,10 @@ __metadata:
languageName: node
linkType: hard
-"tslib@npm:^2.0.0, tslib@npm:^2.0.1, tslib@npm:^2.0.3, tslib@npm:^2.1.0, tslib@npm:^2.3.1, tslib@npm:^2.4.0, tslib@npm:^2.5.0, tslib@npm:^2.6.0, tslib@npm:^2.6.2":
- version: 2.6.3
- resolution: "tslib@npm:2.6.3"
- checksum: 74fce0e100f1ebd95b8995fbbd0e6c91bdd8f4c35c00d4da62e285a3363aaa534de40a80db30ecfd388ed7c313c42d930ee0eaf108e8114214b180eec3dbe6f5
+"tslib@npm:^2.0.0, tslib@npm:^2.0.1, tslib@npm:^2.0.3, tslib@npm:^2.1.0, tslib@npm:^2.3.1, tslib@npm:^2.4.0, tslib@npm:^2.4.1, tslib@npm:^2.5.0, tslib@npm:^2.6.0, tslib@npm:^2.6.2":
+ version: 2.8.1
+ resolution: "tslib@npm:2.8.1"
+ checksum: e4aba30e632b8c8902b47587fd13345e2827fa639e7c3121074d5ee0880723282411a8838f830b55100cbe4517672f84a2472667d355b81e8af165a55dc6203a
languageName: node
linkType: hard
@@ -33152,6 +33275,20 @@ __metadata:
languageName: node
linkType: hard
+"unfetch@npm:^3.1.1":
+ version: 3.1.2
+ resolution: "unfetch@npm:3.1.2"
+ checksum: 5529f0021c51ffa52b5eb36b7b7824f5cbb2167c4a7a09365d071af7534a87a7968a93f1d71f8cdb1aab930af5692af10f53521100999021a05bfb738ff859ab
+ languageName: node
+ linkType: hard
+
+"unfetch@npm:^4.1.0":
+ version: 4.2.0
+ resolution: "unfetch@npm:4.2.0"
+ checksum: 6a4b2557e1d921eaa80c4425ce27a404945ec26491ed06e62598f333996a91a44c7908cb26dc7c2746d735762b13276cf4aa41829b4c8f438dde63add3045d7a
+ languageName: node
+ linkType: hard
+
"unicode-canonical-property-names-ecmascript@npm:^2.0.0":
version: 2.0.0
resolution: "unicode-canonical-property-names-ecmascript@npm:2.0.0"
|
ecec0e19756c96ff70dd6eaed314f865279abdfb
|
2022-09-15 21:09:01
|
Sumit Kumar
|
fix: re-install graphql plugin in workspaces (#16764)
| false
|
re-install graphql plugin in workspaces (#16764)
|
fix
|
diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/migrations/DatabaseChangelog.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/migrations/DatabaseChangelog.java
index 83393d8b57a3..96890890459d 100644
--- a/app/server/appsmith-server/src/main/java/com/appsmith/server/migrations/DatabaseChangelog.java
+++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/migrations/DatabaseChangelog.java
@@ -54,6 +54,7 @@
import com.appsmith.server.domains.QOrganization;
import com.appsmith.server.domains.QPlugin;
import com.appsmith.server.domains.QUserData;
+import com.appsmith.server.domains.QWorkspace;
import com.appsmith.server.domains.Role;
import com.appsmith.server.domains.Sequence;
import com.appsmith.server.domains.User;
@@ -235,18 +236,23 @@ private ActionDTO copyActionToDTO(Action action) {
}
public static void installPluginToAllWorkspaces(MongockTemplate mongockTemplate, String pluginId) {
- for (Workspace workspace : mongockTemplate.findAll(Workspace.class)) {
+ Query queryToFetchAllWorkspaceIds = new Query();
+ /* Filter in only those workspaces that don't have the plugin installed */
+ queryToFetchAllWorkspaceIds.addCriteria(Criteria.where("plugins.pluginId").ne(pluginId));
+ /* Only read the workspace id and leave out other fields */
+ queryToFetchAllWorkspaceIds.fields().include(fieldName(QWorkspace.workspace.id));
+ List<Workspace> workspacesWithOnlyId = mongockTemplate.find(queryToFetchAllWorkspaceIds, Workspace.class);
+ for (Workspace workspaceWithId : workspacesWithOnlyId) {
+ Workspace workspace =
+ mongockTemplate.findOne(query(where(fieldName(QWorkspace.workspace.id)).is(workspaceWithId.getId())),
+ Workspace.class);
+
if (CollectionUtils.isEmpty(workspace.getPlugins())) {
workspace.setPlugins(new HashSet<>());
}
- final Set<String> installedPlugins = workspace.getPlugins()
- .stream().map(WorkspacePlugin::getPluginId).collect(Collectors.toSet());
-
- if (!installedPlugins.contains(pluginId)) {
- workspace.getPlugins()
- .add(new WorkspacePlugin(pluginId, WorkspacePluginStatus.FREE));
- }
+ workspace.getPlugins()
+ .add(new WorkspacePlugin(pluginId, WorkspacePluginStatus.FREE));
mongockTemplate.save(workspace);
}
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 a29ad9e6287f..30b66fbe43e7 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
@@ -2580,4 +2580,17 @@ public void addGraphQLPlugin(MongockTemplate mongoTemplate) {
installPluginToAllWorkspaces(mongoTemplate, plugin.getId());
}
+
+ /**
+ * This method attempts to add GraphQL plugin to all workspaces once again since the last migration was
+ * interrupted due to issues on prod cluster. Hence, during the last migration the plugin could not be installed in
+ * few workspaces.The method installPluginToAllWorkspaces only installs the plugin in those workspaces where it is
+ * missing.
+ */
+ @ChangeSet(order = "037", id = "install-graphql-plugin-to-remaining-workspaces", author = "")
+ public void reInstallGraphQLPluginToWorkspaces(MongockTemplate mongoTemplate) {
+ Plugin graphQLPlugin = mongoTemplate
+ .findOne(query(where("packageName").is("graphql-plugin")), Plugin.class);
+ installPluginToAllWorkspaces(mongoTemplate, graphQLPlugin.getId());
+ }
}
\ No newline at end of file
|
59833b05d29c8537c8335b6f53602309087644b8
|
2024-12-09 20:56:41
|
Sagar Khalasi
|
fix: Property control spec (#38004)
| false
|
Property control spec (#38004)
|
fix
|
diff --git a/app/client/cypress/e2e/Regression/ClientSide/OneClickBinding/PropertyControl_spec.ts b/app/client/cypress/e2e/Regression/ClientSide/OneClickBinding/PropertyControl_spec.ts
index 003c08a2d5cb..465f5d765297 100644
--- a/app/client/cypress/e2e/Regression/ClientSide/OneClickBinding/PropertyControl_spec.ts
+++ b/app/client/cypress/e2e/Regression/ClientSide/OneClickBinding/PropertyControl_spec.ts
@@ -97,7 +97,7 @@ describe(
propPane.ToggleJSMode("Table data", false);
oneClickBinding.ChooseAndAssertForm("Users", "Users", "public.users", {
- searchableColumn: "gender",
+ searchableColumn: "email",
});
propPane.MoveToTab("Style");
@@ -105,7 +105,7 @@ describe(
propPane.MoveToTab("Content");
oneClickBinding.ChooseAndAssertForm("sample Movies", "movies", "movies", {
- searchableColumn: "status",
+ searchableColumn: "imdb_id",
});
dataSources.NavigateToDSCreateNew();
dataSources.CreatePlugIn("Mongo");
|
d665511c8d001a8bf5f96a1cde7b453762e052d3
|
2023-04-27 22:11:40
|
Favour Ohanekwu
|
fix: Get default value from entityTree instead of configTree (#22682)
| false
|
Get default value from entityTree instead of configTree (#22682)
|
fix
|
diff --git a/app/client/cypress/integration/Regression_TestSuite/ClientSideTests/Widgets/ListV2/Listv2_Meta_Hydration_ServerSide_spec.js b/app/client/cypress/integration/Regression_TestSuite/ClientSideTests/Widgets/ListV2/Listv2_Meta_Hydration_ServerSide_spec.js
index 95bb20573bfc..49fba26bfdef 100644
--- a/app/client/cypress/integration/Regression_TestSuite/ClientSideTests/Widgets/ListV2/Listv2_Meta_Hydration_ServerSide_spec.js
+++ b/app/client/cypress/integration/Regression_TestSuite/ClientSideTests/Widgets/ListV2/Listv2_Meta_Hydration_ServerSide_spec.js
@@ -1,8 +1,7 @@
const dsl = require("../../../../../fixtures/Listv2/MetaHydrationDSL.json");
const commonlocators = require("../../../../../locators/commonlocators.json");
-const datasource = require("../../../../../locators/DatasourcesEditor.json");
-const queryLocators = require("../../../../../locators/QueryEditor.json");
const publishPage = require("../../../../../locators/publishWidgetspage.json");
+import * as _ from "../../../../../support/Objects/ObjectsCore";
import { ObjectsRegistry } from "../../../../../support/Objects/Registry";
@@ -74,25 +73,7 @@ function testJsontextClear(endp) {
.type(`{${modifierKey}}{del}`, { force: true });
}
-function verifyMultiDropdownValuesCount(count, page = 1) {
- cy.get(".rc-select-selection-overflow").then(($ele) => {
- if (
- $ele.find(".rc-select-selection-overflow-item .remove-icon").length ==
- count
- ) {
- cy.reload();
- if (page == 2) {
- // Go to next page
- cy.get(commonlocators.listPaginateNextButton).click({
- force: true,
- });
- }
- }
- });
-}
-
-// Skipping this test due to regression, issue id to track this regression https://github.com/appsmithorg/appsmith/issues/22534
-describe.skip("List widget v2 - meta hydration tests", () => {
+describe("List widget v2 - meta hydration tests", () => {
before(() => {
agHelper.AddDsl(dsl);
});
@@ -105,51 +86,12 @@ describe.skip("List widget v2 - meta hydration tests", () => {
});
it("1. setup serverside data", () => {
- cy.wait(1000);
- cy.NavigateToDatasourceEditor();
-
- // // Click on sample(mock) user database.
- // cy.get(datasource.mockUserDatabase).click();
-
- // Choose the first data source which consists of users keyword & Click on the "New Query +"" button
- // Choose the first data source which consists of users keyword & Click on the "New Query +"" button
- cy.get(`${datasource.datasourceCard}`)
- .filter(":contains('Users')")
- .first()
- .within(() => {
- cy.get(`${datasource.createQuery}`).click({ force: true });
- });
- // Click the editing field
- cy.get(".t--action-name-edit-field").click({ force: true });
-
- // Click the editing field
- cy.get(queryLocators.queryNameField).type("Query1");
-
- // switching off Use Prepared Statement toggle
- cy.get(queryLocators.switch).last().click({ force: true });
-
- //.1: Click on Write query area
- cy.get(queryLocators.templateMenu).click();
- cy.get(queryLocators.query).click({
- force: true,
- });
-
- // writing query to get the schema
- cy.get(".CodeMirror textarea")
- .first()
- .focus()
- .type(
- "SELECT * FROM users OFFSET {{List1.pageNo * List1.pageSize}} LIMIT {{List1.pageSize}};",
- {
- force: true,
- parseSpecialCharSequences: false,
- },
- );
- cy.WaitAutoSave();
-
- cy.runQuery();
-
- cy.get('.t--entity-name:contains("Page1")').click({ force: true });
+ cy.createAndFillApi(
+ "http://host.docker.internal:5001/v1/mock-api?records=20&page={{List1.pageNo}}&size={{List1.pageSize}}",
+ "",
+ );
+ cy.RunAPI();
+ cy.SearchEntityandOpen("List1");
cy.wait(1000);
@@ -157,18 +99,17 @@ describe.skip("List widget v2 - meta hydration tests", () => {
testJsontextClear("items");
- cy.testJsontext("items", "{{Query1.data}}");
+ cy.testJsontext("items", "{{Api1.data}}");
cy.togglebar(commonlocators.serverSidePaginationCheckbox);
cy.get(toggleJSButton("onpagechange")).click({ force: true });
- cy.testJsontext("onpagechange", "{{Query1.run()}}");
+ cy.testJsontext("onpagechange", "{{Api1.run()}}");
cy.get(`${widgetSelector("List1")} ${containerWidgetSelector}`).should(
"have.length",
3,
);
- verifyMultiDropdownValuesCount(6);
});
it("2. using server side data", () => {
@@ -215,7 +156,6 @@ describe.skip("List widget v2 - meta hydration tests", () => {
);
});
- verifyMultiDropdownValuesCount(6, 2);
// SecondPage
// First Row
cy.get(`${widgetSelector("List1")}`).scrollIntoView();
@@ -251,15 +191,15 @@ describe.skip("List widget v2 - meta hydration tests", () => {
.should("have.length", 3),
);
- cy.get(`${widgetSelector("List1")} ${containerWidgetSelector}`)
- .eq(0)
- .within(() => {
- cy.waitUntil(() =>
- cy
- .get(".rc-select-selection-overflow-item .remove-icon")
- .should("exist"),
- );
- });
+ cy.waitUntil(() =>
+ cy
+ .get(
+ `${widgetSelector(
+ "List1",
+ )} ${containerWidgetSelector} .rc-select-selection-overflow-item .remove-icon`,
+ )
+ .should("have.length", 3),
+ );
cy.waitUntil(
() =>
@@ -311,15 +251,15 @@ describe.skip("List widget v2 - meta hydration tests", () => {
.should("have.length", 3),
);
- cy.get(`${widgetSelector("List1")} ${containerWidgetSelector}`)
- .eq(0)
- .within(() => {
- cy.waitUntil(() =>
- cy
- .get(".rc-select-selection-overflow-item .remove-icon")
- .should("exist"),
- );
- });
+ cy.waitUntil(() =>
+ cy
+ .get(
+ `${widgetSelector(
+ "List1",
+ )} ${containerWidgetSelector} .rc-select-selection-overflow-item .remove-icon`,
+ )
+ .should("have.length", 3),
+ );
cy.waitUntil(
() =>
@@ -436,15 +376,15 @@ describe.skip("List widget v2 - meta hydration tests", () => {
.should("have.length", 3),
);
- cy.get(`${widgetSelector("List1")} ${containerWidgetSelector}`)
- .eq(0)
- .within(() => {
- cy.waitUntil(() =>
- cy
- .get(".rc-select-selection-overflow-item .remove-icon")
- .should("exist"),
- );
- });
+ cy.waitUntil(() =>
+ cy
+ .get(
+ `${widgetSelector(
+ "List1",
+ )} ${containerWidgetSelector} .rc-select-selection-overflow-item .remove-icon`,
+ )
+ .should("have.length", 3),
+ );
cy.waitUntil(
() =>
@@ -496,15 +436,15 @@ describe.skip("List widget v2 - meta hydration tests", () => {
.should("have.length", 3),
);
- cy.get(`${widgetSelector("List1")} ${containerWidgetSelector}`)
- .eq(0)
- .within(() => {
- cy.waitUntil(() =>
- cy
- .get(".rc-select-selection-overflow-item .remove-icon")
- .should("exist"),
- );
- });
+ cy.waitUntil(() =>
+ cy
+ .get(
+ `${widgetSelector(
+ "List1",
+ )} ${containerWidgetSelector} .rc-select-selection-overflow-item .remove-icon`,
+ )
+ .should("have.length", 3),
+ );
cy.waitUntil(
() =>
diff --git a/app/client/src/ce/workers/Evaluation/evaluationUtils.ts b/app/client/src/ce/workers/Evaluation/evaluationUtils.ts
index d9623dda1e5d..1e66ce44f6de 100644
--- a/app/client/src/ce/workers/Evaluation/evaluationUtils.ts
+++ b/app/client/src/ce/workers/Evaluation/evaluationUtils.ts
@@ -838,7 +838,7 @@ export const overrideWidgetProperties = (params: {
const propertyOverridingKeyMap =
configEntity.propertyOverrideDependency[propertyPath];
if (propertyOverridingKeyMap.DEFAULT) {
- const defaultValue = configEntity[propertyOverridingKeyMap.DEFAULT];
+ const defaultValue = entity[propertyOverridingKeyMap.DEFAULT];
const clonedDefaultValue = klona(defaultValue);
if (defaultValue !== undefined) {
const propertyPathArray = propertyPath.split(".");
|
a2240c7107ff78f074470ad5eea1a4d67cc3f485
|
2022-02-26 16:21:39
|
NandanAnantharamu
|
test: Added test for Table Switch binding (#11423)
| false
|
Added test for Table Switch binding (#11423)
|
test
|
diff --git a/app/client/cypress/fixtures/swtchTableDsl.json b/app/client/cypress/fixtures/swtchTableDsl.json
new file mode 100644
index 000000000000..c23c865c401e
--- /dev/null
+++ b/app/client/cypress/fixtures/swtchTableDsl.json
@@ -0,0 +1,181 @@
+{
+ "dsl": {
+ "widgetName": "MainContainer",
+ "backgroundColor": "none",
+ "rightColumn": 1056,
+ "snapColumns": 64,
+ "detachFromLayout": true,
+ "widgetId": "0",
+ "topRow": 0,
+ "bottomRow": 650,
+ "containerStyle": "none",
+ "snapRows": 125,
+ "parentRowSpace": 1,
+ "type": "CANVAS_WIDGET",
+ "canExtend": true,
+ "version": 52,
+ "minHeight": 730,
+ "parentColumnSpace": 1,
+ "dynamicBindingPathList": [],
+ "leftColumn": 0,
+ "children": [
+ {
+ "isVisible": true,
+ "label": "Label",
+ "defaultSwitchState": true,
+ "widgetName": "Switch1",
+ "alignWidget": "LEFT",
+ "version": 1,
+ "isDisabled": false,
+ "animateLoading": true,
+ "type": "SWITCH_WIDGET",
+ "hideCard": false,
+ "displayName": "Switch",
+ "key": "jx5835myoq",
+ "iconSVG": "/static/media/icon.a3115bc1.svg",
+ "widgetId": "cj9lioq97p",
+ "renderMode": "CANVAS",
+ "isLoading": false,
+ "parentColumnSpace": 16.3125,
+ "parentRowSpace": 10,
+ "leftColumn": 3,
+ "rightColumn": 15,
+ "topRow": 13,
+ "bottomRow": 17,
+ "parentId": "0"
+ },
+ {
+ "isVisible": true,
+ "animateLoading": true,
+ "defaultSelectedRow": "0",
+ "label": "Data",
+ "widgetName": "Table1",
+ "searchKey": "",
+ "textSize": "PARAGRAPH",
+ "horizontalAlignment": "LEFT",
+ "verticalAlignment": "CENTER",
+ "totalRecordsCount": 0,
+ "defaultPageSize": 0,
+ "dynamicBindingPathList": [
+ {
+ "key": "tableData"
+ },
+ {
+ "key": "primaryColumns.name.computedValue"
+ },
+ {
+ "key": "primaryColumns.age.computedValue"
+ }
+ ],
+ "primaryColumns": {
+ "name": {
+ "index": 0,
+ "width": 150,
+ "id": "name",
+ "horizontalAlignment": "LEFT",
+ "verticalAlignment": "CENTER",
+ "columnType": "text",
+ "textSize": "PARAGRAPH",
+ "enableFilter": true,
+ "enableSort": true,
+ "isVisible": true,
+ "isDisabled": false,
+ "isCellVisible": true,
+ "isDerived": false,
+ "label": "name",
+ "computedValue": "{{Table1.sanitizedTableData.map((currentRow) => ( currentRow.name))}}"
+ },
+ "age": {
+ "index": 1,
+ "width": 150,
+ "id": "age",
+ "horizontalAlignment": "LEFT",
+ "verticalAlignment": "CENTER",
+ "columnType": "text",
+ "textSize": "PARAGRAPH",
+ "enableFilter": true,
+ "enableSort": true,
+ "isVisible": true,
+ "isDisabled": false,
+ "isCellVisible": true,
+ "isDerived": false,
+ "label": "age",
+ "computedValue": "{{Table1.sanitizedTableData.map((currentRow) => ( currentRow.age))}}"
+ }
+ },
+ "derivedColumns": {},
+ "tableData": "{{Switch1.isSwitchedOn ? [\n\t\t\t{\n\t\t\t\tname: \"balaji\",\n\t\t\t\tage: 29\n\t\t\t},\n\t {\n\t\t\t\tname: \"yogesh\",\n\t\t\t\tage: 30\n\t\t\t}\n\t\t] : [\n\t\t\t{\n\t\t\t\temployee_name: \"Prapulla\",\n\t\t\t\texperience: 8\n\t\t\t},\n\t\t\t{\n\t\t\t\temployee_name: \"vivek\",\n\t\t\t\texperience: 9\n\t\t\t}\n\t\t]\n}}",
+ "columnSizeMap": {
+ "task": 245,
+ "step": 62,
+ "status": 75
+ },
+ "columnOrder": [
+ "name",
+ "age"
+ ],
+ "enableClientSideSearch": true,
+ "isVisibleSearch": true,
+ "isVisibleFilters": true,
+ "isVisibleDownload": true,
+ "isVisiblePagination": true,
+ "isSortable": true,
+ "delimiter": ",",
+ "version": 3,
+ "type": "TABLE_WIDGET",
+ "hideCard": false,
+ "displayName": "Table",
+ "key": "w7wkbuaqfz",
+ "iconSVG": "/static/media/icon.db8a9cbd.svg",
+ "widgetId": "fa1h4xzjf0",
+ "renderMode": "CANVAS",
+ "isLoading": false,
+ "parentColumnSpace": 16.3125,
+ "parentRowSpace": 10,
+ "leftColumn": 18,
+ "rightColumn": 52,
+ "topRow": 12,
+ "bottomRow": 40,
+ "parentId": "0",
+ "dynamicTriggerPathList": [],
+ "dynamicPropertyPathList": [],
+ "multiRowSelection": true
+ },
+ {
+ "isVisible": true,
+ "text": "{{Table1.selectedRow.age}}",
+ "fontSize": "PARAGRAPH",
+ "fontStyle": "BOLD",
+ "textAlign": "LEFT",
+ "textColor": "#231F20",
+ "truncateButtonColor": "#FFC13D",
+ "widgetName": "Text1",
+ "shouldScroll": false,
+ "shouldTruncate": false,
+ "version": 1,
+ "animateLoading": true,
+ "type": "TEXT_WIDGET",
+ "hideCard": false,
+ "displayName": "Text",
+ "key": "bf8iighnap",
+ "iconSVG": "/static/media/icon.97c59b52.svg",
+ "widgetId": "yf97cq9bn0",
+ "renderMode": "CANVAS",
+ "isLoading": false,
+ "parentColumnSpace": 16.3125,
+ "parentRowSpace": 10,
+ "leftColumn": 14,
+ "rightColumn": 30,
+ "topRow": 45,
+ "bottomRow": 49,
+ "parentId": "0",
+ "dynamicBindingPathList": [
+ {
+ "key": "text"
+ }
+ ],
+ "dynamicTriggerPathList": []
+ }
+ ]
+ }
+}
\ No newline at end of file
diff --git a/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/DisplayWidgets/Table_Switch_spec.js b/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/DisplayWidgets/Table_Switch_spec.js
new file mode 100644
index 000000000000..ffc380f8603d
--- /dev/null
+++ b/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/DisplayWidgets/Table_Switch_spec.js
@@ -0,0 +1,62 @@
+/* eslint-disable cypress/no-unnecessary-waiting */
+const widgetsPage = require("../../../../locators/Widgets.json");
+const commonlocators = require("../../../../locators/commonlocators.json");
+const publish = require("../../../../locators/publishWidgetspage.json");
+const dsl = require("../../../../fixtures/swtchTableDsl.json");
+const explorer = require("../../../../locators/explorerlocators.json");
+
+describe("Table Widget and Switch binding Functionality", function() {
+ before(() => {
+ cy.addDsl(dsl);
+ });
+
+ it("Table Widget Data validation with Switch ON", function() {
+ cy.openPropertyPane("tablewidget");
+ cy.readTabledataPublish("1", "1").then((tabData) => {
+ const tabValue = tabData;
+ expect(tabValue).to.be.equal("30");
+ cy.log("the value is" + tabValue);
+ });
+ cy.get(".t--switch-widget-active .bp3-control-indicator").click({
+ force: true,
+ });
+ cy.wait(5000);
+ cy.readTabledataPublish("1", "1").then((tabData) => {
+ const tabValue = tabData;
+ expect(tabValue).to.be.equal("9");
+ cy.log("the value is" + tabValue);
+ });
+ cy.get(".t--switch-widget-inactive .bp3-control-indicator").click({
+ force: true,
+ });
+ cy.wait(5000);
+
+ cy.readTabledataPublish("1", "1").then((tabData) => {
+ const tabValue = tabData;
+ expect(tabValue).to.be.equal("30");
+ cy.log("the value is" + tabValue);
+ });
+ });
+
+ it("Selected row and binding with Text widget", function() {
+ cy.wait(5000);
+ cy.get(".t--table-multiselect")
+ .eq(1)
+ .click({ force: true });
+ cy.get(".t--draggable-textwidget .bp3-ui-text span").should(
+ "contain.text",
+ "30",
+ );
+ cy.get(".t--table-multiselect")
+ .eq(0)
+ .click({ force: true });
+ cy.get(".t--draggable-textwidget .bp3-ui-text span").should(
+ "contain.text",
+ "29",
+ );
+ });
+
+ afterEach(() => {
+ // put your clean up code if any
+ });
+});
|
0b37812b5616d8a07bfa67af1114e10403ec45d9
|
2021-09-20 22:36:13
|
rahulramesha
|
feat: resizable modal (#7312)
| false
|
resizable modal (#7312)
|
feat
|
diff --git a/app/client/cypress/fixtures/example.json b/app/client/cypress/fixtures/example.json
index 626d24f331c2..d744119834bf 100644
--- a/app/client/cypress/fixtures/example.json
+++ b/app/client/cypress/fixtures/example.json
@@ -104,8 +104,7 @@
"body": "Fixtures are a great way to mock data for responses to routes",
"ButtonLabel": "Test Button",
"ButtonName": "Submitbutton",
- "AlertModalName": "Alert_Modal",
- "FormModalName": "Form_Modal",
+ "ModalName": "Modal",
"TextLabelValue": "Test Text Label",
"TextLabelValueScrollable": "Test Text Label to check scroll feature",
"TextName": "TestTextBox",
diff --git a/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/DisplayWidgets/Chart_spec.js b/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/DisplayWidgets/Chart_spec.js
index 879d4b1b9210..db78774e5e7d 100644
--- a/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/DisplayWidgets/Chart_spec.js
+++ b/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/DisplayWidgets/Chart_spec.js
@@ -248,9 +248,9 @@ describe("Chart Widget Functionality", function() {
cy.PublishtheApp();
});
- it("Chart - Show Alert Modal", function() {
- //creating the Alert Modal and verify Modal name
- cy.createModal("Alert Modal", this.data.AlertModalName);
+ it("Chart - Modal", function() {
+ //creating the Modal and verify Modal name
+ cy.createModal(this.data.ModalName);
cy.PublishtheApp();
cy.get(widgetsPage.chartPlotGroup)
.children()
@@ -258,21 +258,7 @@ describe("Chart Widget Functionality", function() {
.click();
cy.get(modalWidgetPage.modelTextField).should(
"have.text",
- this.data.AlertModalName,
- );
- });
-
- it("Chart - Form Modal Validation", function() {
- //creating the Form Modal and verify Modal name
- cy.updateModal("Form Modal", this.data.FormModalName);
- cy.PublishtheApp();
- cy.get(widgetsPage.chartPlotGroup)
- .children()
- .first()
- .click();
- cy.get(modalWidgetPage.modelTextField).should(
- "have.text",
- this.data.FormModalName,
+ this.data.ModalName,
);
});
diff --git a/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/FormWidgets/Button_onClickAction_spec.js b/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/FormWidgets/Button_onClickAction_spec.js
index acb4cee764a8..2b0b19ff69ad 100644
--- a/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/FormWidgets/Button_onClickAction_spec.js
+++ b/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/FormWidgets/Button_onClickAction_spec.js
@@ -17,25 +17,14 @@ describe("Button Widget Functionality", function() {
cy.openPropertyPane("buttonwidget");
});
- it("Button-AlertModal Validation", function() {
- //creating the Alert Modal and verify Modal name
- cy.createModal("Alert Modal", this.data.AlertModalName);
+ it("Button-Modal Validation", function() {
+ //creating the Modal and verify Modal name
+ cy.createModal(this.data.ModalName);
cy.PublishtheApp();
cy.get(publishPage.buttonWidget).click();
cy.get(modalWidgetPage.modelTextField).should(
"have.text",
- this.data.AlertModalName,
- );
- });
-
- it("Button-FormModal Validation", function() {
- //creating the Form Modal and verify Modal name
- cy.updateModal("Form Modal", this.data.FormModalName);
- cy.PublishtheApp();
- cy.get(publishPage.buttonWidget).click();
- cy.get(modalWidgetPage.modelTextField).should(
- "have.text",
- this.data.FormModalName,
+ this.data.ModalName,
);
});
diff --git a/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/FormWidgets/Dropdown_onOptionChange_spec.js b/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/FormWidgets/Dropdown_onOptionChange_spec.js
index 8d5b321267c0..667dc368e460 100644
--- a/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/FormWidgets/Dropdown_onOptionChange_spec.js
+++ b/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/FormWidgets/Dropdown_onOptionChange_spec.js
@@ -13,11 +13,11 @@ describe("Dropdown Widget Functionality", function() {
cy.addDsl(dsl);
});
- it("Dropdown-AlertModal Validation", function() {
+ it("Dropdown-Modal Validation", function() {
cy.SearchEntityandOpen("Dropdown1");
cy.testJsontext("options", JSON.stringify(data.input));
- //creating the Alert Modal and verify Modal name
- cy.createModal("Alert Modal", this.data.AlertModalName);
+ //creating the Modal and verify Modal name
+ cy.createModal("Modal", this.data.ModalName);
cy.PublishtheApp();
// Changing the option to verify the success message
cy.get(formWidgetsPage.selectWidget)
@@ -29,25 +29,7 @@ describe("Dropdown Widget Functionality", function() {
cy.wait(1000);
cy.get(modalWidgetPage.modelTextField).should(
"have.text",
- this.data.AlertModalName,
- );
- });
-
- it("Dropdown-FromModal Validation", function() {
- cy.openPropertyPane("dropdownwidget");
- //creating the Alert Modal and verify Modal name
- cy.updateModal("Form Modal", this.data.FormModalName);
- cy.PublishtheApp();
- // Changing the option to verify the success message
- cy.get(formWidgetsPage.selectWidget)
- .find(widgetLocators.dropdownSingleSelect)
- .click({ force: true });
- cy.get(commonlocators.singleSelectMenuItem)
- .contains("Option 2")
- .click({ force: true });
- cy.get(modalWidgetPage.modelTextField).should(
- "have.text",
- this.data.FormModalName,
+ this.data.ModalName,
);
});
diff --git a/app/client/cypress/support/commands.js b/app/client/cypress/support/commands.js
index d9420a1fb93f..0393f7246c77 100644
--- a/app/client/cypress/support/commands.js
+++ b/app/client/cypress/support/commands.js
@@ -1096,7 +1096,7 @@ Cypress.Commands.add("AddActionWithModal", () => {
cy.get(commonlocators.editPropCrossButton).click({ force: true });
});
-Cypress.Commands.add("createModal", (modalType, ModalName) => {
+Cypress.Commands.add("createModal", (ModalName) => {
cy.get(widgetsPage.actionSelect)
.first()
.click({ force: true });
@@ -1104,13 +1104,6 @@ Cypress.Commands.add("createModal", (modalType, ModalName) => {
cy.get(modalWidgetPage.selectModal).click();
cy.get(modalWidgetPage.createModalButton).click({ force: true });
- cy.get(modalWidgetPage.controlModalType)
- .last()
- .click({ force: true });
- cy.get(commonlocators.dropdownmenu)
- .children()
- .contains(modalType)
- .click();
cy.assertPageSave();
// changing the model name verify
@@ -1142,42 +1135,6 @@ Cypress.Commands.add("selectOnClickOption", (option) => {
.click({ force: true });
});
-Cypress.Commands.add("updateModal", (modalType, ModalName) => {
- cy.get(widgetsPage.actionSelect)
- .first()
- .click({ force: true });
- cy.selectOnClickOption("Open Modal");
- cy.get(modalWidgetPage.selectModal).click();
- cy.get(modalWidgetPage.createModalButton).click({ force: true });
-
- cy.get(modalWidgetPage.controlModalType)
- .last()
- .click({ force: true });
- cy.get(commonlocators.dropdownmenu)
- .children()
- .contains(modalType)
- .click();
- cy.assertPageSave();
-
- // changing the model name verify
- cy.widgetText(
- ModalName,
- modalWidgetPage.modalName,
- modalWidgetPage.modalName,
- );
- cy.get(commonlocators.editPropCrossButton).click({ force: true });
-
- //changing the Model label
- cy.get(modalWidgetPage.modalWidget + " " + widgetsPage.textWidget)
- .first()
- .trigger("mouseover");
-
- cy.get(widgetsPage.textWidget + " " + commonlocators.editIcon).click();
- cy.testCodeMirror(ModalName);
- cy.get(widgetsPage.textCenterAlign).click({ force: true });
- cy.assertPageSave();
- cy.get(".bp3-overlay-backdrop").click({ force: true });
-});
Cypress.Commands.add("CheckWidgetProperties", (checkboxCss) => {
cy.get(checkboxCss).check({
force: true,
diff --git a/app/client/src/actions/pageActions.tsx b/app/client/src/actions/pageActions.tsx
index 0505709eca82..45bcb5dbe8ef 100644
--- a/app/client/src/actions/pageActions.tsx
+++ b/app/client/src/actions/pageActions.tsx
@@ -244,6 +244,13 @@ export type WidgetResize = {
bottomRow: number;
};
+export type ModalWidgetResize = {
+ height: number;
+ width: number;
+ widgetId: string;
+ canvasWidgetId: string;
+};
+
export type WidgetAddChildren = {
widgetId: string;
children: Array<{
diff --git a/app/client/src/components/editorComponents/ResizeStyledComponents.tsx b/app/client/src/components/editorComponents/ResizeStyledComponents.tsx
index 1068fd9e3683..6889193b8991 100644
--- a/app/client/src/components/editorComponents/ResizeStyledComponents.tsx
+++ b/app/client/src/components/editorComponents/ResizeStyledComponents.tsx
@@ -14,14 +14,19 @@ export const VisibilityContainer = styled.div<{
width: 100%;
`;
-const ResizeIndicatorStyle = css`
+const ResizeIndicatorStyle = css<{
+ showLightBorder: boolean;
+}>`
&::after {
position: absolute;
content: "";
width: 6px;
height: 6px;
border-radius: 50%;
- background: ${theme.colors.widgetBorder};
+ background: ${(props) =>
+ props.showLightBorder
+ ? theme.colors.widgetLightBorder
+ : theme.colors.widgetBorder};
top: calc(50% - 2px);
left: calc(50% - 2px);
}
@@ -29,16 +34,20 @@ const ResizeIndicatorStyle = css`
export const EdgeHandleStyles = css<{
showAsBorder: boolean;
+ showLightBorder: boolean;
}>`
position: absolute;
width: ${EDGE_RESIZE_HANDLE_WIDTH}px;
height: ${EDGE_RESIZE_HANDLE_WIDTH}px;
&::before {
position: absolute;
- background: ${(props) =>
- props.showAsBorder
- ? theme.colors.widgetMultiSelectBorder
- : theme.colors.widgetBorder};
+ background: ${(props) => {
+ if (props.showLightBorder) return theme.colors.widgetLightBorder;
+
+ if (props.showAsBorder) return theme.colors.widgetMultiSelectBorder;
+
+ return theme.colors.widgetBorder;
+ }};
content: "";
}
${(props) => (!props.showAsBorder ? ResizeIndicatorStyle : "")}
@@ -46,6 +55,7 @@ export const EdgeHandleStyles = css<{
export const VerticalHandleStyles = css<{
showAsBorder: boolean;
+ showLightBorder: boolean;
}>`
${EdgeHandleStyles}
top:-${WIDGET_PADDING - 1}px;
@@ -61,6 +71,7 @@ export const VerticalHandleStyles = css<{
export const HorizontalHandleStyles = css<{
showAsBorder: boolean;
+ showLightBorder: boolean;
}>`
${EdgeHandleStyles}
left: -${WIDGET_PADDING}px;
diff --git a/app/client/src/constants/DefaultTheme.tsx b/app/client/src/constants/DefaultTheme.tsx
index bcc110a6360c..fe81bdcf918a 100644
--- a/app/client/src/constants/DefaultTheme.tsx
+++ b/app/client/src/constants/DefaultTheme.tsx
@@ -2818,6 +2818,7 @@ export const theme: Theme = {
builderBodyBG: Colors.WHITE,
widgetMultiSelectBorder: Colors.MALIBU,
widgetBorder: Colors.SLATE_GRAY,
+ widgetLightBorder: Colors.WHITE_SMOKE,
widgetSecondaryBorder: Colors.MERCURY,
messageBG: Colors.CONCRETE,
paneIcon: Colors.TROUT,
diff --git a/app/client/src/constants/ReduxActionConstants.tsx b/app/client/src/constants/ReduxActionConstants.tsx
index 891a5a879f31..dc0f3a587e6a 100644
--- a/app/client/src/constants/ReduxActionConstants.tsx
+++ b/app/client/src/constants/ReduxActionConstants.tsx
@@ -737,6 +737,7 @@ export const WidgetReduxActionTypes: { [key: string]: string } = {
WIDGET_CHILD_ADDED: "WIDGET_CHILD_ADDED",
WIDGET_REMOVE_CHILD: "WIDGET_REMOVE_CHILD",
WIDGET_RESIZE: "WIDGET_RESIZE",
+ WIDGET_MODAL_RESIZE: "WIDGET_MODAL_RESIZE",
WIDGET_DELETE: "WIDGET_DELETE",
WIDGET_BULK_DELETE: "WIDGET_BULK_DELETE",
WIDGET_SINGLE_DELETE: "WIDGET_SINGLE_DELETE",
diff --git a/app/client/src/constants/WidgetConstants.tsx b/app/client/src/constants/WidgetConstants.tsx
index 1fa922ac2aa5..06322aa9d6ab 100644
--- a/app/client/src/constants/WidgetConstants.tsx
+++ b/app/client/src/constants/WidgetConstants.tsx
@@ -69,7 +69,7 @@ export const layoutConfigurations: LayoutConfigurations = {
FLUID: { minWidth: -1, maxWidth: -1 },
};
-export const LATEST_PAGE_VERSION = 38;
+export const LATEST_PAGE_VERSION = 39;
export const GridDefaults = {
DEFAULT_CELL_SIZE: 1,
diff --git a/app/client/src/resizable/index.tsx b/app/client/src/resizable/index.tsx
index 4ca734207553..501759f5b6c3 100644
--- a/app/client/src/resizable/index.tsx
+++ b/app/client/src/resizable/index.tsx
@@ -28,6 +28,7 @@ const getSnappedValues = (
type ResizableHandleProps = {
allowResize: boolean;
+ showLightBorder?: boolean;
dragCallback: (x: number, y: number) => void;
component: StyledComponent<"div", Record<string, unknown>>;
onStart: () => void;
@@ -60,6 +61,7 @@ function ResizableHandle(props: ResizableHandleProps) {
const propsToPass = {
...bind(),
showAsBorder: !props.allowResize,
+ showLightBorder: props.showLightBorder,
};
return <props.component {...propsToPass} />;
@@ -92,6 +94,8 @@ type ResizableProps = {
position: { x: number; y: number },
) => boolean;
className?: string;
+ resizeDualSides?: boolean;
+ showLightBorder?: boolean;
zWidgetType?: string;
zWidgetId?: string;
};
@@ -126,6 +130,9 @@ export const Resizable = forwardRef(function Resizable(
reset: false,
});
+ const { resizeDualSides } = props;
+ const multiplier = resizeDualSides ? 2 : 1;
+
const setNewDimensions = (rect: {
width: number;
height: number;
@@ -155,9 +162,9 @@ export const Resizable = forwardRef(function Resizable(
handles.push({
dragCallback: (x: number) => {
setNewDimensions({
- width: props.componentWidth - x,
+ width: props.componentWidth - multiplier * x,
height: newDimensions.height,
- x,
+ x: resizeDualSides ? newDimensions.x : x,
y: newDimensions.y,
});
},
@@ -170,8 +177,8 @@ export const Resizable = forwardRef(function Resizable(
dragCallback: (x: number, y: number) => {
setNewDimensions({
width: newDimensions.width,
- height: props.componentHeight - y,
- y: y,
+ height: props.componentHeight - multiplier * y,
+ y: resizeDualSides ? newDimensions.y : y,
x: newDimensions.x,
});
},
@@ -183,7 +190,7 @@ export const Resizable = forwardRef(function Resizable(
handles.push({
dragCallback: (x: number) => {
setNewDimensions({
- width: props.componentWidth + x,
+ width: props.componentWidth + multiplier * x,
height: newDimensions.height,
x: newDimensions.x,
y: newDimensions.y,
@@ -198,7 +205,7 @@ export const Resizable = forwardRef(function Resizable(
dragCallback: (x: number, y: number) => {
setNewDimensions({
width: newDimensions.width,
- height: props.componentHeight + y,
+ height: props.componentHeight + multiplier * y,
x: newDimensions.x,
y: newDimensions.y,
});
@@ -286,6 +293,7 @@ export const Resizable = forwardRef(function Resizable(
props.onStart();
}}
onStop={onResizeStop}
+ showLightBorder={props.showLightBorder}
snapGrid={props.snapGrid}
/>
));
diff --git a/app/client/src/sagas/ModalSagas.ts b/app/client/src/sagas/ModalSagas.ts
index b7f251ab1de6..12c83dd8dda3 100644
--- a/app/client/src/sagas/ModalSagas.ts
+++ b/app/client/src/sagas/ModalSagas.ts
@@ -9,8 +9,15 @@ import {
} from "redux-saga/effects";
import { generateReactKey } from "utils/generators";
-import { WidgetAddChild } from "actions/pageActions";
-import { MAIN_CONTAINER_WIDGET_ID } from "constants/WidgetConstants";
+import {
+ updateAndSaveLayout,
+ WidgetAddChild,
+ ModalWidgetResize,
+} from "actions/pageActions";
+import {
+ GridDefaults,
+ MAIN_CONTAINER_WIDGET_ID,
+} from "constants/WidgetConstants";
import {
ReduxActionErrorTypes,
ReduxActionTypes,
@@ -19,13 +26,17 @@ import {
} from "constants/ReduxActionConstants";
import {
+ getWidget,
getWidgets,
getWidgetByName,
getWidgetsMeta,
getWidgetIdsByType,
getWidgetMetaProps,
} from "sagas/selectors";
-import { FlattenedWidgetProps } from "reducers/entityReducers/canvasWidgetsReducer";
+import {
+ CanvasWidgetsReduxState,
+ FlattenedWidgetProps,
+} from "reducers/entityReducers/canvasWidgetsReducer";
import { updateWidgetMetaProperty } from "actions/metaActions";
import { focusWidget } from "actions/widgetActions";
import log from "loglevel";
@@ -33,6 +44,7 @@ import { flatten } from "lodash";
import AppsmithConsole from "utils/AppsmithConsole";
import WidgetFactory from "utils/WidgetFactory";
+import { Toaster } from "components/ads/Toast";
const WidgetTypes = WidgetFactory.widgetTypes;
export function* createModalSaga(action: ReduxAction<{ modalName: string }>) {
@@ -194,6 +206,97 @@ export function* closeModalSaga(
}
}
+export function* resizeModalSaga(resizeAction: ReduxAction<ModalWidgetResize>) {
+ try {
+ Toaster.clear();
+ const start = performance.now();
+ const { canvasWidgetId, height, widgetId, width } = resizeAction.payload;
+
+ const stateWidget: FlattenedWidgetProps = yield select(getWidget, widgetId);
+ const stateWidgets = yield select(getWidgets);
+
+ let widget = { ...stateWidget };
+ const widgets = { ...stateWidgets };
+
+ widget = { ...widget, height, width };
+ widgets[widgetId] = widget;
+
+ if (canvasWidgetId) {
+ const bottomRow = getModalCanvasBottomRow(
+ widgets,
+ canvasWidgetId,
+ height,
+ );
+ const stateModalContainerWidget: FlattenedWidgetProps = yield select(
+ getWidget,
+ canvasWidgetId,
+ );
+ let modalContainerWidget = { ...stateModalContainerWidget };
+
+ modalContainerWidget = {
+ ...modalContainerWidget,
+ bottomRow,
+ minHeight: height,
+ };
+
+ widgets[canvasWidgetId] = modalContainerWidget;
+ }
+
+ log.debug("resize computations took", performance.now() - start, "ms");
+ yield put(updateAndSaveLayout(widgets));
+ } catch (error) {
+ yield put({
+ type: ReduxActionErrorTypes.WIDGET_OPERATION_ERROR,
+ payload: {
+ action: WidgetReduxActionTypes.WIDGET_RESIZE,
+ error,
+ },
+ });
+ }
+}
+
+/**
+ * Note: returns bottomRow of the lowest widget on the canvas
+ * @param finalWidgets
+ * @param parentId
+ * @param height
+ */
+const getModalCanvasBottomRow = (
+ finalWidgets: CanvasWidgetsReduxState,
+ parentId: string,
+ height: number,
+): number => {
+ if (
+ !finalWidgets[parentId] ||
+ finalWidgets[parentId].type !== WidgetTypes.CANVAS_WIDGET
+ ) {
+ return height;
+ }
+ const lowestBottomRowHeight =
+ height -
+ GridDefaults.CANVAS_EXTENSION_OFFSET *
+ GridDefaults.DEFAULT_GRID_ROW_HEIGHT -
+ GridDefaults.DEFAULT_GRID_ROW_HEIGHT;
+
+ let lowestBottomRow = Math.ceil(
+ lowestBottomRowHeight / GridDefaults.DEFAULT_GRID_ROW_HEIGHT,
+ );
+ const childIds = finalWidgets[parentId].children || [];
+
+ // find lowest row
+ childIds.forEach((cId: string) => {
+ const child = finalWidgets[cId];
+
+ if (child.bottomRow > lowestBottomRow) {
+ lowestBottomRow = child.bottomRow;
+ }
+ });
+ return (
+ (lowestBottomRow + GridDefaults.CANVAS_EXTENSION_OFFSET) *
+ GridDefaults.DEFAULT_GRID_ROW_HEIGHT
+ );
+};
+
export default function* modalSagas() {
yield all([
takeEvery(ReduxActionTypes.CLOSE_MODAL, closeModalSaga),
@@ -201,5 +304,6 @@ export default function* modalSagas() {
takeLatest(ReduxActionTypes.SHOW_MODAL, showModalSaga),
takeLatest(ReduxActionTypes.SHOW_MODAL_BY_NAME, showModalByNameSaga),
takeLatest(WidgetReduxActionTypes.WIDGET_CHILD_ADDED, showIfModalSaga),
+ takeLatest(WidgetReduxActionTypes.WIDGET_MODAL_RESIZE, resizeModalSaga),
]);
}
diff --git a/app/client/src/utils/DSLMigrations.ts b/app/client/src/utils/DSLMigrations.ts
index 0ddb4d6c0481..8ed4fc1e777c 100644
--- a/app/client/src/utils/DSLMigrations.ts
+++ b/app/client/src/utils/DSLMigrations.ts
@@ -34,6 +34,7 @@ import defaultTemplate from "templates/default";
import { renameKeyInObject } from "./helpers";
import { ColumnProperties } from "widgets/TableWidget/component/Constants";
import { migrateMenuButtonWidgetButtonProperties } from "./migrations/MenuButtonWidget";
+import { migrateResizableModalWidgetProperties } from "./migrations/ModalWidget";
/**
* adds logBlackList key for all list widget children
@@ -913,6 +914,11 @@ export const transformDSL = (currentDSL: ContainerWidgetProps<WidgetProps>) => {
if (currentDSL.version === 37) {
currentDSL = migrateTableSanitizeColumnKeys(currentDSL);
+ currentDSL.version = 38;
+ }
+
+ if (currentDSL.version === 38) {
+ currentDSL = migrateResizableModalWidgetProperties(currentDSL);
currentDSL.version = LATEST_PAGE_VERSION;
}
diff --git a/app/client/src/utils/migrations/ModalWidget.test.ts b/app/client/src/utils/migrations/ModalWidget.test.ts
new file mode 100644
index 000000000000..c7e7b19642a6
--- /dev/null
+++ b/app/client/src/utils/migrations/ModalWidget.test.ts
@@ -0,0 +1,191 @@
+import { GridDefaults } from "constants/WidgetConstants";
+import { DSLWidget } from "widgets/constants";
+import { migrateResizableModalWidgetProperties } from "./ModalWidget";
+
+const inputDsl1: DSLWidget = {
+ widgetName: "MainContainer",
+ widgetId: "0",
+ type: "CANVAS_WIDGET",
+ version: 15,
+ parentId: "",
+ renderMode: "CANVAS",
+ children: [
+ {
+ widgetName: "modal",
+ version: 1,
+ type: "MODAL_WIDGET",
+ size: "MODAL_SMALL",
+ parentId: "0",
+ widgetId: "yf8bhokz7d",
+ renderMode: "CANVAS",
+ parentColumnSpace: 0,
+ parentRowSpace: 0,
+ leftColumn: 0,
+ rightColumn: 0,
+ topRow: 0,
+ bottomRow: 0,
+ isLoading: false,
+ },
+ ],
+ parentColumnSpace: 0,
+ parentRowSpace: 0,
+ leftColumn: 0,
+ rightColumn: 0,
+ topRow: 0,
+ bottomRow: 0,
+ isLoading: false,
+};
+
+const outputDsl1: DSLWidget = {
+ widgetName: "MainContainer",
+ widgetId: "0",
+ type: "CANVAS_WIDGET",
+ version: 15,
+ parentId: "",
+ renderMode: "CANVAS",
+ children: [
+ {
+ widgetName: "modal",
+ version: 2,
+ type: "MODAL_WIDGET",
+ height: GridDefaults.DEFAULT_GRID_ROW_HEIGHT * 24,
+ width: 456,
+ parentId: "0",
+ widgetId: "yf8bhokz7d",
+ renderMode: "CANVAS",
+ parentColumnSpace: 0,
+ parentRowSpace: 0,
+ leftColumn: 0,
+ rightColumn: 0,
+ topRow: 0,
+ bottomRow: 0,
+ isLoading: false,
+ },
+ ],
+ parentColumnSpace: 0,
+ parentRowSpace: 0,
+ leftColumn: 0,
+ rightColumn: 0,
+ topRow: 0,
+ bottomRow: 0,
+ isLoading: false,
+};
+
+const inputDsl2: DSLWidget = {
+ widgetName: "MainContainer",
+ widgetId: "0",
+ type: "CANVAS_WIDGET",
+ version: 15,
+ parentId: "",
+ renderMode: "CANVAS",
+ children: [
+ {
+ widgetName: "modal",
+ version: 1,
+ type: "MODAL_WIDGET",
+ size: "MODAL_LARGE",
+ parentId: "0",
+ widgetId: "yf8bhokz7d",
+ renderMode: "CANVAS",
+ parentColumnSpace: 0,
+ parentRowSpace: 0,
+ leftColumn: 0,
+ rightColumn: 0,
+ topRow: 0,
+ bottomRow: 0,
+ isLoading: false,
+ },
+ ],
+ parentColumnSpace: 0,
+ parentRowSpace: 0,
+ leftColumn: 0,
+ rightColumn: 0,
+ topRow: 0,
+ bottomRow: 0,
+ isLoading: false,
+};
+
+const outputDsl2: DSLWidget = {
+ widgetName: "MainContainer",
+ widgetId: "0",
+ type: "CANVAS_WIDGET",
+ version: 15,
+ parentId: "",
+ renderMode: "CANVAS",
+ children: [
+ {
+ widgetName: "modal",
+ version: 2,
+ type: "MODAL_WIDGET",
+ height: GridDefaults.DEFAULT_GRID_ROW_HEIGHT * 60,
+ width: 532,
+ parentId: "0",
+ widgetId: "yf8bhokz7d",
+ renderMode: "CANVAS",
+ parentColumnSpace: 0,
+ parentRowSpace: 0,
+ leftColumn: 0,
+ rightColumn: 0,
+ topRow: 0,
+ bottomRow: 0,
+ isLoading: false,
+ },
+ ],
+ parentColumnSpace: 0,
+ parentRowSpace: 0,
+ leftColumn: 0,
+ rightColumn: 0,
+ topRow: 0,
+ bottomRow: 0,
+ isLoading: false,
+};
+
+const dsl3: DSLWidget = {
+ widgetName: "MainContainer",
+ widgetId: "0",
+ type: "CANVAS_WIDGET",
+ version: 15,
+ parentId: "",
+ renderMode: "CANVAS",
+ children: [
+ {
+ widgetName: "modal",
+ version: 2,
+ type: "MODAL_WIDGET",
+ height: 500,
+ width: 532,
+ parentId: "0",
+ widgetId: "yf8bhokz7d",
+ renderMode: "CANVAS",
+ parentColumnSpace: 0,
+ parentRowSpace: 0,
+ leftColumn: 0,
+ rightColumn: 0,
+ topRow: 0,
+ bottomRow: 0,
+ isLoading: false,
+ },
+ ],
+ parentColumnSpace: 0,
+ parentRowSpace: 0,
+ leftColumn: 0,
+ rightColumn: 0,
+ topRow: 0,
+ bottomRow: 0,
+ isLoading: false,
+};
+
+describe("Migrate to Resizable Modal", () => {
+ it("To test modal with type MODAL_SMALL", () => {
+ const newDsl = migrateResizableModalWidgetProperties(inputDsl1);
+ expect(JSON.stringify(newDsl) === JSON.stringify(outputDsl1));
+ });
+ it("To test modal with type MODAL_SMALL", () => {
+ const newDsl = migrateResizableModalWidgetProperties(inputDsl2);
+ expect(JSON.stringify(newDsl) === JSON.stringify(outputDsl2));
+ });
+ it("To test a migrated modal", () => {
+ const newDsl = migrateResizableModalWidgetProperties(dsl3);
+ expect(JSON.stringify(newDsl) === JSON.stringify(dsl3));
+ });
+});
diff --git a/app/client/src/utils/migrations/ModalWidget.ts b/app/client/src/utils/migrations/ModalWidget.ts
new file mode 100644
index 000000000000..46fecc1596c6
--- /dev/null
+++ b/app/client/src/utils/migrations/ModalWidget.ts
@@ -0,0 +1,33 @@
+import { GridDefaults } from "constants/WidgetConstants";
+import { WidgetProps } from "widgets/BaseWidget";
+import { DSLWidget } from "widgets/constants";
+
+export const migrateResizableModalWidgetProperties = (
+ currentDSL: DSLWidget,
+) => {
+ currentDSL.children = currentDSL.children?.map((child: WidgetProps) => {
+ if (child.type === "MODAL_WIDGET" && child.version === 1) {
+ const size = child.size;
+ switch (size) {
+ case "MODAL_SMALL":
+ child.width = 456;
+ child.height = GridDefaults.DEFAULT_GRID_ROW_HEIGHT * 24;
+ break;
+ case "MODAL_LARGE":
+ child.width = 532;
+ child.height = GridDefaults.DEFAULT_GRID_ROW_HEIGHT * 60;
+ break;
+ default:
+ child.width = 456;
+ child.height = GridDefaults.DEFAULT_GRID_ROW_HEIGHT * 24;
+ break;
+ }
+ child.version = 2;
+ delete child.size;
+ } else if (child.children && child.children.length > 0) {
+ child = migrateResizableModalWidgetProperties(child);
+ }
+ return child;
+ });
+ return currentDSL;
+};
diff --git a/app/client/src/widgets/ModalWidget/component/index.tsx b/app/client/src/widgets/ModalWidget/component/index.tsx
index de7104c52f09..78563710c4dd 100644
--- a/app/client/src/widgets/ModalWidget/component/index.tsx
+++ b/app/client/src/widgets/ModalWidget/component/index.tsx
@@ -1,14 +1,36 @@
-import React, { ReactNode, RefObject, useRef, useEffect } from "react";
+import React, { ReactNode, RefObject, useRef, useEffect, useMemo } from "react";
+
import { Overlay, Classes } from "@blueprintjs/core";
+import { get, omit } from "lodash";
import styled from "styled-components";
+import { useSelector } from "react-redux";
+
+import { UIElementSize } from "components/editorComponents/ResizableUtils";
+import {
+ LeftHandleStyles,
+ RightHandleStyles,
+ TopHandleStyles,
+ BottomHandleStyles,
+} from "components/editorComponents/ResizeStyledComponents";
+import { Layers } from "constants/Layers";
+import { MODAL_PORTAL_CLASSNAME } from "constants/WidgetConstants";
+import Resizable from "resizable";
import { getCanvasClassName } from "utils/generators";
+import { AppState } from "reducers";
+import { useWidgetDragResize } from "utils/hooks/dragResizeHooks";
+import AnalyticsUtil from "utils/AnalyticsUtil";
const Container = styled.div<{
- width: number;
- height: number;
+ width?: number;
+ height?: number;
top?: number;
left?: number;
+ bottom?: number;
+ right?: number;
zIndex?: number;
+ maxWidth?: number;
+ minSize?: number;
+ isEditMode?: boolean;
}>`
&&& {
.${Classes.OVERLAY} {
@@ -26,85 +48,187 @@ const Container = styled.div<{
justify-content: center;
align-items: center;
& .${Classes.OVERLAY_CONTENT} {
- max-width: 95%;
- width: ${(props) => props.width}px;
- min-height: ${(props) => props.height}px;
+ max-width: ${(props) => {
+ if (props.maxWidth) return `${props.maxWidth}px`;
+
+ if (props.isEditMode)
+ return `calc(95% - ${props.theme.sidebarWidth}))`;
+
+ return `95%`;
+ }};
+ max-height: 85%;
+ width: ${(props) => (props.width ? `${props.width}px` : "auto")};
+ height: ${(props) => (props.height ? `${props.height}px` : "auto")};
+ min-height: ${(props) => `${props.minSize}px`};
+ min-width: ${(props) => `${props.minSize}px`};
background: white;
border-radius: ${(props) => props.theme.radii[0]}px;
top: ${(props) => props.top}px;
left: ${(props) => props.left}px;
+ bottom: ${(props) => props.bottom}px;
+ right: ${(props) => props.right}px;
+ ${(props) => {
+ if (props.isEditMode)
+ return `transform: translate(${parseInt(props.theme.sidebarWidth) /
+ 2}px) !important`;
+ }}
}
}
}
`;
const Content = styled.div<{
- height: number;
+ height?: number;
scroll: boolean;
ref: RefObject<HTMLDivElement>;
}>`
overflow-y: ${(props) => (props.scroll ? "visible" : "hidden")};
overflow-x: hidden;
width: 100%;
- height: ${(props) => props.height}px;
+ height: 100%;
`;
export type ModalComponentProps = {
isOpen: boolean;
onClose: (e: any) => void;
+ onModalClose?: () => void;
children: ReactNode;
- width: number;
+ width?: number;
className?: string;
+ usePortal?: boolean;
+ portalContainer?: HTMLElement;
canOutsideClickClose: boolean;
canEscapeKeyClose: boolean;
+ overlayClassName?: string;
scrollContents: boolean;
- height: number;
+ height?: number;
top?: number;
left?: number;
+ bottom?: number;
+ right?: number;
hasBackDrop?: boolean;
zIndex?: number;
+ portalClassName?: string;
+ enableResize?: boolean;
+ isEditMode?: boolean;
+ resizeModal?: (dimensions: UIElementSize) => void;
+ maxWidth?: number;
+ minSize?: number;
+ widgetName: string;
};
-export function ModalComponent(props: ModalComponentProps) {
+/* eslint-disable react/display-name */
+export default function ModalComponent(props: ModalComponentProps) {
const modalContentRef: RefObject<HTMLDivElement> = useRef<HTMLDivElement>(
null,
);
+ const { enableResize = false } = props;
+ const resizeRef = React.useRef<HTMLDivElement>(null);
+
+ const { setIsResizing } = useWidgetDragResize();
+ const isResizing = useSelector(
+ (state: AppState) => state.ui.widgetDragResize.isResizing,
+ );
+
+ const handles = useMemo(() => {
+ const allHandles = {
+ left: LeftHandleStyles,
+ top: TopHandleStyles,
+ bottom: BottomHandleStyles,
+ right: RightHandleStyles,
+ };
+
+ return omit(allHandles, get(props, "disabledResizeHandles", []));
+ }, [props]);
+
useEffect(() => {
if (!props.scrollContents) {
modalContentRef.current?.scrollTo({ top: 0, behavior: "smooth" });
}
}, [props.scrollContents]);
+
+ const onResizeStop = (dimensions: UIElementSize) => {
+ props.resizeModal && props.resizeModal(dimensions);
+ // Tell the Canvas that we've stopped resizing
+ // Put it later in the stack so that other updates like click, are not propagated to the parent container
+ setTimeout(() => {
+ setIsResizing && setIsResizing(false);
+ }, 0);
+ };
+
+ const onResizeStart = () => {
+ setIsResizing && !isResizing && setIsResizing(true);
+ AnalyticsUtil.logEvent("WIDGET_RESIZE_START", {
+ widgetName: props.widgetName,
+ widgetType: "MODAL_WIDGET",
+ });
+ };
+
+ const getResizableContent = () => {
+ return (
+ <Resizable
+ allowResize
+ componentHeight={props.height || 0}
+ componentWidth={props.width || 0}
+ enable={enableResize}
+ handles={handles}
+ isColliding={() => false}
+ onStart={onResizeStart}
+ onStop={onResizeStop}
+ ref={resizeRef}
+ resizeDualSides
+ showLightBorder
+ snapGrid={{ x: 1, y: 1 }}
+ >
+ <Content
+ className={`${getCanvasClassName()} ${props.className}`}
+ ref={modalContentRef}
+ scroll={props.scrollContents}
+ >
+ {props.children}
+ </Content>
+ </Resizable>
+ );
+ };
+
return (
- <Container
- height={props.height}
- left={props.left}
- top={props.top}
- width={props.width}
- zIndex={props.zIndex !== undefined ? props.zIndex : 2}
+ <Overlay
+ canEscapeKeyClose={false}
+ canOutsideClickClose={false}
+ enforceFocus={false}
+ hasBackdrop={false}
+ isOpen={props.isOpen}
+ onClose={props.onClose}
+ portalClassName={`${MODAL_PORTAL_CLASSNAME} ${props.portalClassName}`}
+ portalContainer={props.portalContainer}
+ usePortal={props.usePortal}
>
- <Overlay
- canEscapeKeyClose={props.canEscapeKeyClose}
- canOutsideClickClose={props.canOutsideClickClose}
- enforceFocus={false}
- hasBackdrop={
- props.hasBackDrop !== undefined ? !!props.hasBackDrop : true
- }
- isOpen={props.isOpen}
- onClose={props.onClose}
- usePortal={false}
+ <Container
+ bottom={props.bottom}
+ height={props.height}
+ isEditMode={props.isEditMode}
+ left={props.left}
+ maxWidth={props.maxWidth}
+ minSize={props.minSize}
+ right={props.bottom}
+ top={props.top}
+ width={props.width}
+ zIndex={props.zIndex !== undefined ? props.zIndex : Layers.modalWidget}
>
- <div>
- <Content
- className={`${getCanvasClassName()} ${props.className}`}
- height={props.height}
- ref={modalContentRef}
- scroll={props.scrollContents}
- >
- {props.children}
- </Content>
- </div>
- </Overlay>
- </Container>
+ <Overlay
+ canEscapeKeyClose={props.canEscapeKeyClose}
+ canOutsideClickClose={props.canOutsideClickClose}
+ className={props.overlayClassName}
+ enforceFocus={false}
+ hasBackdrop={
+ props.hasBackDrop !== undefined ? !!props.hasBackDrop : true
+ }
+ isOpen={props.isOpen}
+ onClose={props.onClose}
+ usePortal={false}
+ >
+ {getResizableContent()}
+ </Overlay>
+ </Container>
+ </Overlay>
);
}
-
-export default ModalComponent;
diff --git a/app/client/src/widgets/ModalWidget/index.ts b/app/client/src/widgets/ModalWidget/index.ts
index fdc7152e69a0..c9c6cd7c3aa2 100644
--- a/app/client/src/widgets/ModalWidget/index.ts
+++ b/app/client/src/widgets/ModalWidget/index.ts
@@ -6,6 +6,7 @@ import {
FlattenedWidgetProps,
GRID_DENSITY_MIGRATION_V1,
} from "widgets/constants";
+import { GridDefaults } from "constants/WidgetConstants";
export const CONFIG = {
type: Widget.getWidgetType(),
@@ -16,7 +17,8 @@ export const CONFIG = {
defaults: {
rows: 6 * GRID_DENSITY_MIGRATION_V1,
columns: 6 * GRID_DENSITY_MIGRATION_V1,
- size: "MODAL_SMALL",
+ width: 456,
+ height: GridDefaults.DEFAULT_GRID_ROW_HEIGHT * 24,
canEscapeKeyClose: true,
// detachFromLayout is set true for widgets that are not bound to the widgets within the layout.
// setting it to true will only render the widgets(from sidebar) on the main container without any collision check.
@@ -25,7 +27,7 @@ export const CONFIG = {
shouldScrollContents: true,
widgetName: "Modal",
children: [],
- version: 1,
+ version: 2,
blueprint: {
view: [
{
@@ -93,7 +95,7 @@ export const CONFIG = {
},
size: {
rows: 1 * GRID_DENSITY_MIGRATION_V1,
- cols: 4 * GRID_DENSITY_MIGRATION_V1,
+ cols: 3 * GRID_DENSITY_MIGRATION_V1,
},
props: {
text: "Confirm",
diff --git a/app/client/src/widgets/ModalWidget/widget/index.tsx b/app/client/src/widgets/ModalWidget/widget/index.tsx
index 1b99a78f2787..c70729cefb24 100644
--- a/app/client/src/widgets/ModalWidget/widget/index.tsx
+++ b/app/client/src/widgets/ModalWidget/widget/index.tsx
@@ -1,34 +1,26 @@
import React, { ReactNode } from "react";
import { connect } from "react-redux";
+
+import { UIElementSize } from "components/editorComponents/ResizableUtils";
import { ReduxActionTypes } from "constants/ReduxActionConstants";
-import BaseWidget, { WidgetProps, WidgetState } from "widgets/BaseWidget";
import { EventType } from "constants/AppsmithActionConstants/ActionConstants";
+import BaseWidget, { WidgetProps, WidgetState } from "widgets/BaseWidget";
import WidgetFactory from "utils/WidgetFactory";
import ModalComponent from "../component";
import {
RenderMode,
- GridDefaults,
MAIN_CONTAINER_WIDGET_ID,
+ WIDGET_PADDING,
} from "constants/WidgetConstants";
import { generateClassName } from "utils/generators";
-
+import { ClickContentToOpenPropPane } from "utils/hooks/useClickToSelectWidget";
import { AppState } from "reducers";
import { getWidget } from "sagas/selectors";
-import { ClickContentToOpenPropPane } from "utils/hooks/useClickToSelectWidget";
+import { commentModeSelector } from "selectors/commentsSelectors";
+import { snipingModeSelector } from "selectors/editorSelectors";
-const MODAL_SIZE: { [id: string]: { width: number; height: number } } = {
- MODAL_SMALL: {
- width: 456,
- // adjust if DEFAULT_GRID_ROW_HEIGHT changes
- height: GridDefaults.DEFAULT_GRID_ROW_HEIGHT * 24,
- },
- MODAL_LARGE: {
- width: 532,
- // adjust if DEFAULT_GRID_ROW_HEIGHT changes
- height: GridDefaults.DEFAULT_GRID_ROW_HEIGHT * 60,
- },
-};
+const minSize = 100;
export class ModalWidget extends BaseWidget<ModalWidgetProps, WidgetState> {
static getPropertyPaneConfig() {
@@ -36,23 +28,6 @@ export class ModalWidget extends BaseWidget<ModalWidgetProps, WidgetState> {
{
sectionName: "General",
children: [
- {
- propertyName: "size",
- label: "Modal Type",
- controlType: "DROP_DOWN",
- options: [
- {
- label: "Form Modal",
- value: "MODAL_LARGE",
- },
- {
- label: "Alert Modal",
- value: "MODAL_SMALL",
- },
- ],
- isBindProperty: false,
- isTriggerProperty: false,
- },
{
propertyName: "shouldScrollContents",
label: "Scroll Contents",
@@ -91,12 +66,12 @@ export class ModalWidget extends BaseWidget<ModalWidgetProps, WidgetState> {
canEscapeKeyClose: false,
};
- getModalWidth() {
- const widthFromOverlay = this.props.mainContainer.rightColumn * 0.95;
- const defaultModalWidth = MODAL_SIZE[this.props.size].width;
- return widthFromOverlay < defaultModalWidth
- ? widthFromOverlay
- : defaultModalWidth;
+ getMaxModalWidth() {
+ return this.props.mainContainer.rightColumn * 0.95;
+ }
+
+ getModalWidth(width: number) {
+ return Math.min(this.getMaxModalWidth(), width);
}
renderChildWidget = (childWidgetData: WidgetProps): ReactNode => {
@@ -104,12 +79,13 @@ export class ModalWidget extends BaseWidget<ModalWidgetProps, WidgetState> {
childWidgetData.shouldScrollContents = false;
childWidgetData.canExtend = this.props.shouldScrollContents;
childWidgetData.bottomRow = this.props.shouldScrollContents
- ? Math.max(childWidgetData.bottomRow, MODAL_SIZE[this.props.size].height)
- : MODAL_SIZE[this.props.size].height;
+ ? Math.max(childWidgetData.bottomRow, this.props.height)
+ : this.props.height;
childWidgetData.isVisible = this.props.isVisible;
childWidgetData.containerStyle = "none";
- childWidgetData.minHeight = MODAL_SIZE[this.props.size].height;
- childWidgetData.rightColumn = this.getModalWidth();
+ childWidgetData.minHeight = this.props.height;
+ childWidgetData.rightColumn =
+ this.getModalWidth(this.props.width) + WIDGET_PADDING * 2;
return WidgetFactory.createWidget(childWidgetData, this.props.renderMode);
};
@@ -125,6 +101,22 @@ export class ModalWidget extends BaseWidget<ModalWidgetProps, WidgetState> {
}
};
+ onModalResize = (dimensions: UIElementSize) => {
+ const newDimensions = {
+ height: Math.max(minSize, dimensions.height),
+ width: Math.max(minSize, this.getModalWidth(dimensions.width)),
+ };
+
+ const canvasWidgetId =
+ this.props.children && this.props.children.length > 0
+ ? this.props.children[0]?.widgetId
+ : "";
+ this.updateWidget("MODAL_RESIZE", this.props.widgetId, {
+ ...newDimensions,
+ canvasWidgetId,
+ });
+ };
+
closeModal = (e: any) => {
this.props.showPropertyPane(undefined);
this.onModalClose();
@@ -136,7 +128,12 @@ export class ModalWidget extends BaseWidget<ModalWidgetProps, WidgetState> {
};
getChildren(): ReactNode {
- if (this.props.children && this.props.children.length > 0) {
+ if (
+ this.props.height &&
+ this.props.width &&
+ this.props.children &&
+ this.props.children.length > 0
+ ) {
const children = this.props.children.filter(Boolean);
return children.length > 0 && children.map(this.renderChildWidget);
}
@@ -151,17 +148,51 @@ export class ModalWidget extends BaseWidget<ModalWidgetProps, WidgetState> {
);
}
- makeModalComponent(content: ReactNode) {
+ makeModalComponent(content: ReactNode, isEditMode: boolean) {
+ const artBoard = document.getElementById("art-board");
+ const portalContainer = isEditMode && artBoard ? artBoard : undefined;
+ const {
+ focusedWidget,
+ isCommentMode,
+ isDragging,
+ isSnipingMode,
+ selectedWidget,
+ selectedWidgets,
+ widgetId,
+ } = this.props;
+
+ const isWidgetFocused =
+ focusedWidget === widgetId ||
+ selectedWidget === widgetId ||
+ selectedWidgets.includes(widgetId);
+
+ const isResizeEnabled =
+ !isDragging &&
+ isWidgetFocused &&
+ isEditMode &&
+ !isCommentMode &&
+ !isSnipingMode;
+
return (
<ModalComponent
canEscapeKeyClose={!!this.props.canEscapeKeyClose}
canOutsideClickClose={!!this.props.canOutsideClickClose}
className={`t--modal-widget ${generateClassName(this.props.widgetId)}`}
- height={MODAL_SIZE[this.props.size].height}
+ enableResize={isResizeEnabled}
+ hasBackDrop
+ height={this.props.height}
+ isEditMode={isEditMode}
isOpen={!!this.props.isVisible}
+ maxWidth={this.getMaxModalWidth()}
+ minSize={minSize}
onClose={this.closeModal}
+ onModalClose={this.onModalClose}
+ portalContainer={portalContainer}
+ resizeModal={this.onModalResize}
scrollContents={!!this.props.shouldScrollContents}
- width={this.getModalWidth()}
+ usePortal={false}
+ widgetName={this.props.widgetName}
+ width={this.getModalWidth(this.props.width)}
>
{content}
</ModalComponent>
@@ -172,12 +203,12 @@ export class ModalWidget extends BaseWidget<ModalWidgetProps, WidgetState> {
let children = this.getChildren();
children = this.makeModalSelectable(children);
children = this.showWidgetName(children, true);
- return this.makeModalComponent(children);
+ return this.makeModalComponent(children, true);
}
getPageView() {
const children = this.getChildren();
- return this.makeModalComponent(children);
+ return this.makeModalComponent(children, false);
}
static getWidgetType() {
@@ -190,8 +221,8 @@ export interface ModalWidgetProps extends WidgetProps {
isOpen?: boolean;
children?: WidgetProps[];
canOutsideClickClose?: boolean;
- width?: number;
- height?: number;
+ width: number;
+ height: number;
showPropertyPane: (widgetId?: string) => void;
canEscapeKeyClose?: boolean;
shouldScrollContents?: boolean;
@@ -221,6 +252,13 @@ const mapDispatchToProps = (dispatch: any) => ({
const mapStateToProps = (state: AppState) => {
const props = {
mainContainer: getWidget(state, MAIN_CONTAINER_WIDGET_ID),
+ isCommentMode: commentModeSelector(state),
+ isSnipingMode: snipingModeSelector(state),
+ selectedWidget: state.ui.widgetDragResize.lastSelectedWidget,
+ selectedWidgets: state.ui.widgetDragResize.selectedWidgets,
+ focusedWidget: state.ui.widgetDragResize.focusedWidget,
+ isDragging: state.ui.widgetDragResize.isDragging,
+ isResizing: state.ui.widgetDragResize.isResizing,
};
return props;
};
|
5bc439d4785b300835d07fc1752136300153c858
|
2023-05-22 13:17:30
|
Sumit Kumar
|
chore: MsSQL Integration: add JUnit TC for SSL options (#23528)
| false
|
MsSQL Integration: add JUnit TC for SSL options (#23528)
|
chore
|
diff --git a/app/server/appsmith-plugins/mssqlPlugin/src/test/java/com/external/plugins/MssqlPluginTest.java b/app/server/appsmith-plugins/mssqlPlugin/src/test/java/com/external/plugins/MssqlPluginTest.java
index 323253dea4d1..885434cbc749 100755
--- a/app/server/appsmith-plugins/mssqlPlugin/src/test/java/com/external/plugins/MssqlPluginTest.java
+++ b/app/server/appsmith-plugins/mssqlPlugin/src/test/java/com/external/plugins/MssqlPluginTest.java
@@ -715,4 +715,77 @@ public void verifyUniquenessOfMssqlPluginErrorCode() {
.collect(Collectors.toList()).size() == 0);
}
+
+ @Test
+ public void testSSLNoVerifyConnectionIsEncrypted() {
+ ActionConfiguration actionConfiguration = new ActionConfiguration();
+ String queryToFetchEncryptionStatusOfSelfConnection =
+ "SELECT \n" +
+ " c.encrypt_option \n" +
+ "FROM sys.dm_exec_connections AS c \n" +
+ "JOIN sys.dm_exec_sessions AS s \n" +
+ " ON c.session_id = s.session_id \n" +
+ "WHERE c.session_id = @@SPID;";
+ actionConfiguration.setBody(queryToFetchEncryptionStatusOfSelfConnection);
+
+ List<Property> pluginSpecifiedTemplates = new ArrayList<>();
+ pluginSpecifiedTemplates.add(new Property("preparedStatement", "true"));
+ actionConfiguration.setPluginSpecifiedTemplates(pluginSpecifiedTemplates);
+
+ ExecuteActionDTO executeActionDTO = new ExecuteActionDTO();
+ List<Param> params = new ArrayList<>();
+ executeActionDTO.setParams(params);
+
+ DatasourceConfiguration dsConfig = createDatasourceConfiguration();
+ dsConfig.getConnection().getSsl().setAuthType(SSLDetails.AuthType.NO_VERIFY);
+
+ Mono<HikariDataSource> connectionCreateMono = pluginExecutor.datasourceCreate(dsConfig);
+ Mono<ActionExecutionResult> resultMono = connectionCreateMono
+ .flatMap(pool -> pluginExecutor.executeParameterized(pool, executeActionDTO, dsConfig, actionConfiguration));
+
+ StepVerifier.create(resultMono)
+ .assertNext(result -> {
+ assertTrue(result.getIsExecutionSuccess());
+ String expectedResultString = "[{\"encrypt_option\":\"TRUE\"}]";
+ assertEquals(expectedResultString, result.getBody().toString());
+ })
+ .verifyComplete();
+ }
+
+ @Test
+ public void testSSLDisabledConnectionIsNotEncrypted() {
+ ActionConfiguration actionConfiguration = new ActionConfiguration();
+ String queryToFetchEncryptionStatusOfSelfConnection =
+ "SELECT \n" +
+ " c.encrypt_option \n" +
+ "FROM sys.dm_exec_connections AS c \n" +
+ "JOIN sys.dm_exec_sessions AS s \n" +
+ " ON c.session_id = s.session_id \n" +
+ "WHERE c.session_id = @@SPID;";
+ actionConfiguration.setBody(queryToFetchEncryptionStatusOfSelfConnection);
+
+ List<Property> pluginSpecifiedTemplates = new ArrayList<>();
+ pluginSpecifiedTemplates.add(new Property("preparedStatement", "true"));
+ actionConfiguration.setPluginSpecifiedTemplates(pluginSpecifiedTemplates);
+
+ ExecuteActionDTO executeActionDTO = new ExecuteActionDTO();
+ List<Param> params = new ArrayList<>();
+ executeActionDTO.setParams(params);
+
+ DatasourceConfiguration dsConfig = createDatasourceConfiguration();
+ dsConfig.getConnection().getSsl().setAuthType(SSLDetails.AuthType.DISABLE);
+
+ Mono<HikariDataSource> connectionCreateMono = pluginExecutor.datasourceCreate(dsConfig);
+ Mono<ActionExecutionResult> resultMono = connectionCreateMono
+ .flatMap(pool -> pluginExecutor.executeParameterized(pool, executeActionDTO, dsConfig, actionConfiguration));
+
+ StepVerifier.create(resultMono)
+ .assertNext(result -> {
+ assertTrue(result.getIsExecutionSuccess());
+ String expectedResultString = "[{\"encrypt_option\":\"FALSE\"}]";
+ assertEquals(expectedResultString, result.getBody().toString());
+ })
+ .verifyComplete();
+ }
+
}
|
b61ceab94b7c71fbce24110048d79555451ebc43
|
2022-01-28 16:40:05
|
Rishabh Rathod
|
fix: Add meta to eval cycle and update it when default changes (#10401)
| false
|
Add meta to eval cycle and update it when default changes (#10401)
|
fix
|
diff --git a/app/client/cypress/fixtures/FlowerVase.jpeg b/app/client/cypress/fixtures/AAAFlowerVase.jpeg
similarity index 100%
rename from app/client/cypress/fixtures/FlowerVase.jpeg
rename to app/client/cypress/fixtures/AAAFlowerVase.jpeg
diff --git a/app/client/cypress/fixtures/GlobeChristmas.jpeg b/app/client/cypress/fixtures/AAAGlobeChristmas.jpeg
similarity index 100%
rename from app/client/cypress/fixtures/GlobeChristmas.jpeg
rename to app/client/cypress/fixtures/AAAGlobeChristmas.jpeg
diff --git a/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/FormWidgets/FilePicker_with_fileTypes_spec.js b/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/FormWidgets/FilePicker_with_fileTypes_spec.js
index 6c1fe36b790d..dae78e038477 100644
--- a/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/FormWidgets/FilePicker_with_fileTypes_spec.js
+++ b/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/FormWidgets/FilePicker_with_fileTypes_spec.js
@@ -8,13 +8,13 @@ describe("FilePicker Widget Functionality with different file types", function()
it("Check file upload of type jpeg", function() {
cy.SearchEntityandOpen("FilePicker1");
- const fixturePath = "FlowerVase.jpeg";
+ const fixturePath = "AAAFlowerVase.jpeg";
cy.get(commonlocators.filepickerv2).click();
cy.get(commonlocators.filePickerInput)
.first()
.attachFile(fixturePath);
cy.get(commonlocators.filePickerUploadButton).click();
- cy.get(commonlocators.dashboardItemName).contains("FlowerVase.jpeg");
+ cy.get(commonlocators.dashboardItemName).contains("AAAFlowerVase.jpeg");
//eslint-disable-next-line cypress/no-unnecessary-waiting
cy.wait(500);
cy.get("button").contains("Upload 1 file");
diff --git a/app/client/cypress/integration/Smoke_TestSuite/ServerSideTests/QueryPane/S3_spec.js b/app/client/cypress/integration/Smoke_TestSuite/ServerSideTests/QueryPane/S3_spec.js
index bd1ba649d9f8..c30864bed03f 100644
--- a/app/client/cypress/integration/Smoke_TestSuite/ServerSideTests/QueryPane/S3_spec.js
+++ b/app/client/cypress/integration/Smoke_TestSuite/ServerSideTests/QueryPane/S3_spec.js
@@ -470,7 +470,7 @@ describe("Validate CRUD queries for Amazon S3 along with UI flow verifications",
cy.ClickGotIt();
//Upload: 1
- let fixturePath = "GlobeChristmas.jpeg";
+ let fixturePath = "AAAGlobeChristmas.jpeg";
cy.wait(3000);
cy.clickButton("Select Files"); //1 files selected
cy.get(generatePage.uploadFilesS3).attachFile(fixturePath);
@@ -490,8 +490,8 @@ describe("Validate CRUD queries for Amazon S3 along with UI flow verifications",
//Verifying Searching File from UI
cy.xpath(queryLocators.searchFilefield)
- .type("GlobeChri")
- .wait(4000); //for search to finish
+ .type("AAAGlobeChri")
+ .wait(7000); //for search to finish
expect(
cy.xpath(
"//div[@data-cy='overlay-comments-wrapper']//span[text()='" +
@@ -507,14 +507,18 @@ describe("Validate CRUD queries for Amazon S3 along with UI flow verifications",
).scrollIntoView();
//Verifying DeleteFile icon from UI
- cy.xpath(
+
+ const deleteIconButtonXPATH =
"//button/span[@icon='trash']/ancestor::div[contains(@class,'t--widget-iconbuttonwidget')]/preceding-sibling::div[contains(@class, 't--widget-textwidget')]//span[text()='" +
- fixturePath +
- "']/ancestor::div[contains(@class, 't--widget-textwidget')]/following-sibling::div[contains(@class,'t--widget-iconbuttonwidget')]",
- )
- .should("be.visible")
+ fixturePath +
+ "']/ancestor::div[contains(@class, 't--widget-textwidget')]/following-sibling::div[contains(@class,'t--widget-iconbuttonwidget')]";
+
+ cy.xpath(deleteIconButtonXPATH).should("be.visible");
+
+ cy.xpath(deleteIconButtonXPATH)
.last()
.click(); //Verifies 8684
+
cy.VerifyErrorMsgAbsence("Cyclic dependency found while evaluating"); //Verifies 8686
expect(
@@ -529,7 +533,7 @@ describe("Validate CRUD queries for Amazon S3 along with UI flow verifications",
); //verify Deletion of file is success from UI also
//Upload: 2 - Bug verification 9201
- fixturePath = "FlowerVase.jpeg";
+ fixturePath = "AAAFlowerVase.jpeg";
cy.wait(3000);
cy.clickButton("Select Files"); //1 files selected
cy.get(generatePage.uploadFilesS3).attachFile(fixturePath);
@@ -551,8 +555,8 @@ describe("Validate CRUD queries for Amazon S3 along with UI flow verifications",
cy.xpath(queryLocators.searchFilefield)
.clear()
.wait(500)
- .type("Flow")
- .wait(3000); //for search to finish
+ .type("AAAFlowerVase")
+ .wait(7000); //for search to finish
expect(
cy.xpath(
"//div[@data-cy='overlay-comments-wrapper']//span[text()='" +
diff --git a/app/client/cypress/support/index.js b/app/client/cypress/support/index.js
index 7c74d8247ebb..f0b478d00626 100644
--- a/app/client/cypress/support/index.js
+++ b/app/client/cypress/support/index.js
@@ -13,15 +13,17 @@
// https://on.cypress.io/configuration
// ***********************************************************
/// <reference types="Cypress" />
-require("cypress-xpath");
+
import "cypress-real-events/support";
-let pageid;
+import "cypress-xpath";
+/// <reference types="cypress-xpath" />
+
let appId;
// Import commands.js using ES2015 syntax:
import "./commands";
import { initLocalstorage } from "./commands";
-import * as MESSAGES from "../../../client/src/constants/messages.ts";
+import * as MESSAGES from "../../../client/src/constants/messages";
Cypress.on("uncaught:exception", (err, runnable) => {
// returning false here prevents Cypress from
diff --git a/app/client/cypress/tsconfig.json b/app/client/cypress/tsconfig.json
index 0c7f14157dde..635f2def5113 100644
--- a/app/client/cypress/tsconfig.json
+++ b/app/client/cypress/tsconfig.json
@@ -33,7 +33,7 @@
"sourceMap": true,
"baseUrl": "./cypress",
"noFallthroughCasesInSwitch": true,
- "types": ["cypress"]
+ "types": ["cypress", "cypress-xpath"]
},
"include": ["/**/*.ts"]
}
diff --git a/app/client/src/actions/metaActions.ts b/app/client/src/actions/metaActions.ts
index d08e5f09935c..2de6ff500caf 100644
--- a/app/client/src/actions/metaActions.ts
+++ b/app/client/src/actions/metaActions.ts
@@ -1,5 +1,9 @@
import { ReduxActionTypes, ReduxAction } from "constants/ReduxActionConstants";
import { BatchAction, batchAction } from "actions/batchActions";
+import { DataTree } from "entities/DataTree/dataTreeFactory";
+import { isWidget } from "../workers/evaluationUtils";
+import { MetaState } from "../reducers/entityReducers/metaReducer";
+import isEmpty from "lodash/isEmpty";
export interface UpdateWidgetMetaPropertyPayload {
widgetId: string;
@@ -42,3 +46,19 @@ export const resetChildrenMetaProperty = (
},
};
};
+
+export const updateMetaState = (evaluatedDataTree: DataTree) => {
+ const updatedWidgetMetaState: MetaState = {};
+ Object.values(evaluatedDataTree).forEach((entity) => {
+ if (isWidget(entity) && entity.widgetId && !isEmpty(entity.meta)) {
+ updatedWidgetMetaState[entity.widgetId] = entity.meta;
+ }
+ });
+
+ return {
+ type: ReduxActionTypes.UPDATE_META_STATE,
+ payload: {
+ updatedWidgetMetaState,
+ },
+ };
+};
diff --git a/app/client/src/constants/ReduxActionConstants.tsx b/app/client/src/constants/ReduxActionConstants.tsx
index d7aeb943488c..bc0012534aa4 100644
--- a/app/client/src/constants/ReduxActionConstants.tsx
+++ b/app/client/src/constants/ReduxActionConstants.tsx
@@ -11,6 +11,7 @@ export const ReduxSagaChannels = {
};
export const ReduxActionTypes = {
+ UPDATE_META_STATE: "UPDATE_META_STATE",
DISCONNECT_GIT: "DISCONNECT_GIT",
SHOW_CONNECT_GIT_MODAL: "SHOW_CONNECT_GIT_MODAL",
SET_SHOULD_SHOW_REPO_LIMIT_ERROR_MODAL:
diff --git a/app/client/src/entities/DataTree/dataTreeFactory.ts b/app/client/src/entities/DataTree/dataTreeFactory.ts
index a285558e1000..d33c59d00bc1 100644
--- a/app/client/src/entities/DataTree/dataTreeFactory.ts
+++ b/app/client/src/entities/DataTree/dataTreeFactory.ts
@@ -80,12 +80,34 @@ export interface DataTreeJSAction {
export interface MetaArgs {
arguments: Variable[];
}
+/**
+ * Map of overriding property as key and overridden property as values
+ */
+export type OverridingPropertyPaths = Record<string, string[]>;
+
+export enum OverridingPropertyType {
+ META = "META",
+ DEFAULT = "DEFAULT",
+}
+/**
+ * Map of property name as key and value as object with defaultPropertyName and metaPropertyName which it depends on.
+ */
+export type PropertyOverrideDependency = Record<
+ string,
+ {
+ DEFAULT: string | undefined;
+ META: string | undefined;
+ }
+>;
+
export interface DataTreeWidget extends WidgetProps {
bindingPaths: Record<string, EvaluationSubstitutionType>;
triggerPaths: Record<string, boolean>;
validationPaths: Record<string, ValidationConfig>;
ENTITY_TYPE: ENTITY_TYPE.WIDGET;
logBlackList: Record<string, true>;
+ propertyOverrideDependency: PropertyOverrideDependency;
+ overridingPropertyPaths: OverridingPropertyPaths;
privateWidgets: PrivateWidgets;
}
diff --git a/app/client/src/entities/DataTree/dataTreeWidget.test.ts b/app/client/src/entities/DataTree/dataTreeWidget.test.ts
index 09227e1a5a45..95d4e23296fe 100644
--- a/app/client/src/entities/DataTree/dataTreeWidget.test.ts
+++ b/app/client/src/entities/DataTree/dataTreeWidget.test.ts
@@ -168,7 +168,7 @@ describe("generateDataTreeWidget", () => {
version: 0,
widgetId: "123",
widgetName: "Input1",
- defaultText: "Testing",
+ defaultText: "",
};
const widgetMetaProps: Record<string, unknown> = {
@@ -201,6 +201,10 @@ describe("generateDataTreeWidget", () => {
resetOnSubmit: EvaluationSubstitutionType.TEMPLATE,
text: EvaluationSubstitutionType.TEMPLATE,
value: EvaluationSubstitutionType.TEMPLATE,
+ "meta.text": EvaluationSubstitutionType.TEMPLATE,
+ },
+ meta: {
+ text: "Tester",
},
triggerPaths: {
onSubmit: true,
@@ -238,6 +242,12 @@ describe("generateDataTreeWidget", () => {
leftColumn: 0,
parentColumnSpace: 0,
parentRowSpace: 0,
+ propertyOverrideDependency: {
+ text: {
+ DEFAULT: "defaultText",
+ META: "meta.text",
+ },
+ },
renderMode: RenderModes.CANVAS,
rightColumn: 0,
topRow: 0,
@@ -246,16 +256,19 @@ describe("generateDataTreeWidget", () => {
widgetId: "123",
widgetName: "Input1",
ENTITY_TYPE: ENTITY_TYPE.WIDGET,
- defaultText: "Testing",
+ defaultText: "",
defaultMetaProps: ["text", "isDirty", "isFocused"],
defaultProps: {
text: "defaultText",
},
+ overridingPropertyPaths: {
+ defaultText: ["text", "meta.text"],
+ "meta.text": ["text"],
+ },
privateWidgets: {},
};
const result = generateDataTreeWidget(widget, widgetMetaProps);
-
expect(result).toStrictEqual(expected);
});
});
diff --git a/app/client/src/entities/DataTree/dataTreeWidget.ts b/app/client/src/entities/DataTree/dataTreeWidget.ts
index 281ac540820a..1644ce83daac 100644
--- a/app/client/src/entities/DataTree/dataTreeWidget.ts
+++ b/app/client/src/entities/DataTree/dataTreeWidget.ts
@@ -2,13 +2,26 @@ import WidgetFactory from "utils/WidgetFactory";
import { getAllPathsFromPropertyConfig } from "entities/Widget/utils";
import { getEntityDynamicBindingPathList } from "utils/DynamicBindingUtils";
import _ from "lodash";
-import { DataTreeWidget, ENTITY_TYPE } from "entities/DataTree/dataTreeFactory";
+
import { FlattenedWidgetProps } from "reducers/entityReducers/canvasWidgetsReducer";
+import { setOverridingProperty } from "./utils";
+import {
+ OverridingPropertyPaths,
+ PropertyOverrideDependency,
+ OverridingPropertyType,
+ DataTreeWidget,
+ ENTITY_TYPE,
+} from "./dataTreeFactory";
export const generateDataTreeWidget = (
widget: FlattenedWidgetProps,
- widgetMetaProps: Record<string, unknown>,
+ widgetMetaProps: Record<string, unknown> = {},
): DataTreeWidget => {
+ const derivedProps: any = {};
+ const blockedDerivedProps: Record<string, true> = {};
+ const unInitializedDefaultProps: Record<string, undefined> = {};
+ const propertyOverrideDependency: PropertyOverrideDependency = {};
+ const overridingPropertyPaths: OverridingPropertyPaths = {};
const defaultMetaProps = WidgetFactory.getWidgetMetaPropertiesMap(
widget.type,
);
@@ -21,8 +34,8 @@ export const generateDataTreeWidget = (
const propertyPaneConfigs = WidgetFactory.getWidgetPropertyPaneConfig(
widget.type,
);
- const derivedProps: any = {};
const dynamicBindingPathList = getEntityDynamicBindingPathList(widget);
+ // Ensure all dynamic bindings are strings as they will be evaluated
dynamicBindingPathList.forEach((dynamicPath) => {
const propertyPath = dynamicPath.key;
const propertyValue = _.get(widget, propertyPath);
@@ -31,26 +44,67 @@ export const generateDataTreeWidget = (
_.set(widget, propertyPath, JSON.stringify(propertyValue));
}
});
+ // Derived props are stored in different maps for further treatment
Object.keys(derivedPropertyMap).forEach((propertyName) => {
// TODO regex is too greedy
+ // Replace the references to `this` with the widget name reference
+ // in the derived property bindings
derivedProps[propertyName] = derivedPropertyMap[propertyName].replace(
/this./g,
`${widget.widgetName}.`,
);
+ // Add these to the dynamicBindingPathList as well
dynamicBindingPathList.push({
key: propertyName,
});
});
- const unInitializedDefaultProps: Record<string, undefined> = {};
- Object.values(defaultProps).forEach((propertyName) => {
- if (!(propertyName in widget)) {
- unInitializedDefaultProps[propertyName] = undefined;
- }
- });
- const blockedDerivedProps: Record<string, true> = {};
+
Object.keys(derivedProps).forEach((propertyName) => {
+ // Do not log errors for the derived property bindings
blockedDerivedProps[propertyName] = true;
});
+
+ const overridingMetaPropsMap: Record<string, boolean> = {};
+
+ Object.entries(defaultProps).forEach(
+ ([propertyName, defaultPropertyName]) => {
+ // why default value is undefined ?
+ if (!(defaultPropertyName in widget)) {
+ unInitializedDefaultProps[defaultPropertyName] = undefined;
+ }
+ // defaultProperty on eval needs to override the widget's property eg: defaultText overrides text
+ setOverridingProperty({
+ propertyOverrideDependency,
+ overridingPropertyPaths,
+ value: defaultPropertyName,
+ key: propertyName,
+ type: OverridingPropertyType.DEFAULT,
+ });
+
+ if (propertyName in defaultMetaProps) {
+ // Overriding properties will override the values of a property when evaluated
+ setOverridingProperty({
+ propertyOverrideDependency,
+ overridingPropertyPaths,
+ value: `meta.${propertyName}`,
+ key: propertyName,
+ type: OverridingPropertyType.META,
+ });
+ overridingMetaPropsMap[propertyName] = true;
+ }
+ },
+ );
+
+ const overridingMetaProps: Record<string, unknown> = {};
+
+ // overridingMetaProps has all meta property value either from metaReducer or default set by widget whose dependent property also has default property.
+ Object.entries(defaultMetaProps).forEach(([key, value]) => {
+ if (overridingMetaPropsMap[key]) {
+ overridingMetaProps[key] =
+ key in widgetMetaProps ? widgetMetaProps[key] : value;
+ }
+ });
+
const {
bindingPaths,
triggerPaths,
@@ -60,13 +114,15 @@ export const generateDataTreeWidget = (
...defaultMetaProps,
...unInitializedDefaultProps,
..._.keyBy(dynamicBindingPathList, "key"),
+ ...overridingPropertyPaths,
});
+
return {
...widget,
+ ...unInitializedDefaultProps,
...defaultMetaProps,
...widgetMetaProps,
...derivedProps,
- ...unInitializedDefaultProps,
defaultProps,
defaultMetaProps: Object.keys(defaultMetaProps),
dynamicBindingPathList,
@@ -74,6 +130,11 @@ export const generateDataTreeWidget = (
...widget.logBlackList,
...blockedDerivedProps,
},
+ meta: {
+ ...overridingMetaProps,
+ },
+ propertyOverrideDependency,
+ overridingPropertyPaths,
bindingPaths,
triggerPaths,
validationPaths,
diff --git a/app/client/src/entities/DataTree/utils.ts b/app/client/src/entities/DataTree/utils.ts
new file mode 100644
index 000000000000..a0b96189fcef
--- /dev/null
+++ b/app/client/src/entities/DataTree/utils.ts
@@ -0,0 +1,59 @@
+import {
+ PropertyOverrideDependency,
+ OverridingPropertyPaths,
+ OverridingPropertyType,
+} from "./dataTreeFactory";
+
+type SetOverridingPropertyParams = {
+ key: string;
+ value: string;
+ propertyOverrideDependency: PropertyOverrideDependency;
+ overridingPropertyPaths: OverridingPropertyPaths;
+ type: OverridingPropertyType;
+};
+
+export const setOverridingProperty = ({
+ key: propertyName,
+ overridingPropertyPaths,
+ propertyOverrideDependency,
+ type,
+ value: overridingPropertyKey,
+}: SetOverridingPropertyParams) => {
+ if (!(propertyName in propertyOverrideDependency)) {
+ propertyOverrideDependency[propertyName] = {
+ [OverridingPropertyType.DEFAULT]: undefined,
+ [OverridingPropertyType.META]: undefined,
+ };
+ }
+ switch (type) {
+ case OverridingPropertyType.DEFAULT:
+ propertyOverrideDependency[propertyName][
+ OverridingPropertyType.DEFAULT
+ ] = overridingPropertyKey;
+ break;
+
+ case OverridingPropertyType.META:
+ propertyOverrideDependency[propertyName][
+ OverridingPropertyType.META
+ ] = overridingPropertyKey;
+
+ break;
+ default:
+ }
+
+ if (Array.isArray(overridingPropertyPaths[overridingPropertyKey])) {
+ const updatedOverridingProperty = new Set(
+ overridingPropertyPaths[overridingPropertyKey],
+ );
+ overridingPropertyPaths[overridingPropertyKey] = [
+ ...updatedOverridingProperty.add(propertyName),
+ ];
+ } else {
+ overridingPropertyPaths[overridingPropertyKey] = [propertyName];
+ }
+ // if property dependent on metaProperty also has defaultProperty then defaultProperty will also override metaProperty on eval.
+ const defaultPropertyName = propertyOverrideDependency[propertyName].DEFAULT;
+ if (type === OverridingPropertyType.META && defaultPropertyName) {
+ overridingPropertyPaths[defaultPropertyName].push(overridingPropertyKey);
+ }
+};
diff --git a/app/client/src/pages/Editor/WidgetsEditor/index.tsx b/app/client/src/pages/Editor/WidgetsEditor/index.tsx
index cf49ffad1037..c37563cbacdd 100644
--- a/app/client/src/pages/Editor/WidgetsEditor/index.tsx
+++ b/app/client/src/pages/Editor/WidgetsEditor/index.tsx
@@ -1,6 +1,5 @@
import React, { useEffect, useCallback } from "react";
import { useSelector, useDispatch } from "react-redux";
-import * as log from "loglevel";
import {
getIsFetchingPage,
@@ -107,8 +106,6 @@ function WidgetsEditor() {
[allowDragToSelect],
);
- log.debug("Canvas rendered");
-
PerformanceTracker.stopTracking();
return (
<EditorContextProvider>
diff --git a/app/client/src/reducers/entityReducers/metaReducer.ts b/app/client/src/reducers/entityReducers/metaReducer.ts
index df1712344093..9facbe6fae17 100644
--- a/app/client/src/reducers/entityReducers/metaReducer.ts
+++ b/app/client/src/reducers/entityReducers/metaReducer.ts
@@ -1,6 +1,8 @@
import { set, cloneDeep } from "lodash";
import { createReducer } from "utils/AppsmithUtils";
import { UpdateWidgetMetaPropertyPayload } from "actions/metaActions";
+import isObject from "lodash/isObject";
+import { DataTreeWidget } from "entities/DataTree/dataTreeFactory";
import {
ReduxActionTypes,
ReduxAction,
@@ -12,6 +14,29 @@ export type MetaState = Record<string, Record<string, unknown>>;
const initialState: MetaState = {};
export const metaReducer = createReducer(initialState, {
+ [ReduxActionTypes.UPDATE_META_STATE]: (
+ state: MetaState,
+ action: ReduxAction<{
+ updatedWidgetMetaState: Record<string, DataTreeWidget>;
+ }>,
+ ) => {
+ // if metaObject is updated in dataTree we also update meta values, to keep meta state in sync.
+ const newMetaState = cloneDeep(state);
+ const { updatedWidgetMetaState } = action.payload;
+
+ Object.entries(updatedWidgetMetaState).forEach(
+ ([entityWidgetId, entityMetaState]) => {
+ if (isObject(newMetaState[entityWidgetId])) {
+ Object.keys(newMetaState[entityWidgetId]).forEach((key) => {
+ if (key in entityMetaState) {
+ newMetaState[entityWidgetId][key] = entityMetaState[key];
+ }
+ });
+ }
+ },
+ );
+ return newMetaState;
+ },
[ReduxActionTypes.SET_META_PROP]: (
state: MetaState,
action: ReduxAction<UpdateWidgetMetaPropertyPayload>,
diff --git a/app/client/src/sagas/EvaluationsSaga.ts b/app/client/src/sagas/EvaluationsSaga.ts
index 6d0c3cc3a57b..8ff1dbf042fd 100644
--- a/app/client/src/sagas/EvaluationsSaga.ts
+++ b/app/client/src/sagas/EvaluationsSaga.ts
@@ -2,12 +2,12 @@ import {
actionChannel,
all,
call,
+ delay,
fork,
put,
select,
spawn,
take,
- delay,
} from "redux-saga/effects";
import {
@@ -85,6 +85,7 @@ import { Channel } from "redux-saga";
import { ActionDescription } from "entities/DataTree/actionTriggers";
import { FormEvaluationState } from "reducers/evaluationReducers/formEvaluationReducer";
import { FormEvalActionPayload } from "./FormEvaluationSaga";
+import { updateMetaState } from "../actions/metaActions";
import { getAllActionValidationConfig } from "selectors/entitiesSelector";
let widgetTypeConfigMap: WidgetTypeConfigMap;
@@ -139,6 +140,8 @@ function* evaluateTreeSaga(
PerformanceTransactionName.SET_EVALUATED_TREE,
);
+ yield put(updateMetaState(dataTree));
+
const updatedDataTree = yield select(getDataTree);
log.debug({ jsUpdates: jsUpdates });
log.debug({ dataTree: updatedDataTree });
@@ -213,7 +216,7 @@ export function* evaluateAndExecuteDynamicTrigger(
keepAlive = false;
/* Handle errors during evaluation
* A finish event with errors means that the error was not caught by the user code.
- * We raise an error telling the user that an uncaught error has occured
+ * We raise an error telling the user that an uncaught error has occurred
* */
if (requestData.result.errors.length) {
throw new UncaughtPromiseError(
@@ -303,12 +306,6 @@ export function* clearEvalCache() {
return true;
}
-export function* clearEvalPropertyCache(propertyPath: string) {
- yield call(worker.request, EVAL_WORKER_ACTIONS.CLEAR_PROPERTY_CACHE, {
- propertyPath,
- });
-}
-
export function* executeFunction(collectionName: string, action: JSAction) {
const functionCall = `${collectionName}.${action.name}()`;
const { isAsync } = action.actionConfiguration;
@@ -338,21 +335,6 @@ export function* executeFunction(collectionName: string, action: JSAction) {
return result;
}
-/**
- * clears all cache keys of a widget
- *
- * @param widgetName
- */
-export function* clearEvalPropertyCacheOfWidget(widgetName: string) {
- yield call(
- worker.request,
- EVAL_WORKER_ACTIONS.CLEAR_PROPERTY_CACHE_OF_WIDGET,
- {
- widgetName,
- },
- );
-}
-
export function* validateProperty(
property: string,
value: any,
@@ -559,23 +541,17 @@ export function* updateReplayEntitySaga(
//Delay updates to replay object to not persist every keystroke
yield delay(REPLAY_DELAY);
const { entity, entityId, entityType } = actionPayload.payload;
- const workerResponse = yield call(
- worker.request,
- EVAL_WORKER_ACTIONS.UPDATE_REPLAY_OBJECT,
- {
- entityId,
- entity,
- entityType,
- },
- );
- return workerResponse;
+ return yield call(worker.request, EVAL_WORKER_ACTIONS.UPDATE_REPLAY_OBJECT, {
+ entityId,
+ entity,
+ entityType,
+ });
}
export function* workerComputeUndoRedo(operation: string, entityId: string) {
- const workerResponse: any = yield call(worker.request, operation, {
+ return yield call(worker.request, operation, {
entityId,
});
- return workerResponse;
}
// Type to represent the state of the evaluation reducer
diff --git a/app/client/src/sagas/WidgetDeletionSagas.ts b/app/client/src/sagas/WidgetDeletionSagas.ts
index 3e603e57cbe5..458361862e0b 100644
--- a/app/client/src/sagas/WidgetDeletionSagas.ts
+++ b/app/client/src/sagas/WidgetDeletionSagas.ts
@@ -24,7 +24,6 @@ import { getSelectedWidgets } from "selectors/ui";
import AnalyticsUtil from "utils/AnalyticsUtil";
import AppsmithConsole from "utils/AppsmithConsole";
import { WidgetProps } from "widgets/BaseWidget";
-import { clearEvalPropertyCacheOfWidget } from "./EvaluationsSaga";
import { getSelectedWidget, getWidget, getWidgets } from "./selectors";
import {
getAllWidgetsInTree,
@@ -154,8 +153,6 @@ function* getUpdatedDslAfterDeletingWidget(widgetId: string, parentId: string) {
widgetName = widget.tabName;
}
- yield call(clearEvalPropertyCacheOfWidget, widgetName);
-
let finalWidgets: CanvasWidgetsReduxState = updateListWidgetPropertiesOnChildDelete(
widgets,
widgetId,
@@ -247,8 +244,8 @@ function* deleteAllSelectedWidgetsSaga(
return call(getAllWidgetsInTree, eachId, widgets);
}),
);
- const falttendedWidgets: any = flattenDeep(widgetsToBeDeleted);
- const parentUpdatedWidgets = falttendedWidgets.reduce(
+ const flattenedWidgets: any = flattenDeep(widgetsToBeDeleted);
+ const parentUpdatedWidgets = flattenedWidgets.reduce(
(allWidgets: any, eachWidget: any) => {
const { parentId, widgetId } = eachWidget;
const stateParent: FlattenedWidgetProps = allWidgets[parentId];
@@ -266,7 +263,7 @@ function* deleteAllSelectedWidgetsSaga(
);
const finalWidgets: CanvasWidgetsReduxState = omit(
parentUpdatedWidgets,
- falttendedWidgets.map((widgets: any) => widgets.widgetId),
+ flattenedWidgets.map((widgets: any) => widgets.widgetId),
);
// assuming only widgets with same parent can be selected
const parentId = widgets[selectedWidgets[0]].parentId;
@@ -281,7 +278,7 @@ function* deleteAllSelectedWidgetsSaga(
yield put(closeTableFilterPane());
showUndoRedoToast(`${selectedWidgets.length}`, true, false, true);
if (bulkDeleteKey) {
- falttendedWidgets.map((widget: any) => {
+ flattenedWidgets.map((widget: any) => {
AppsmithConsole.info({
logType: LOG_TYPE.ENTITY_DELETED,
text: "Widget was deleted",
@@ -357,7 +354,7 @@ function resizeCanvasToLowestWidget(
);
const childIds = finalWidgets[parentId].children || [];
- // find lowest row
+ // find the lowest row
childIds.forEach((cId) => {
const child = finalWidgets[cId];
diff --git a/app/client/src/selectors/editorSelectors.tsx b/app/client/src/selectors/editorSelectors.tsx
index a4818e878802..8d48bfa8c2bc 100644
--- a/app/client/src/selectors/editorSelectors.tsx
+++ b/app/client/src/selectors/editorSelectors.tsx
@@ -402,6 +402,8 @@ const createLoadingWidget = (
validationPaths: {},
logBlackList: {},
isLoading: true,
+ propertyOverrideDependency: {},
+ overridingPropertyPaths: {},
privateWidgets: {},
};
};
diff --git a/app/client/src/utils/DynamicBindingUtils.ts b/app/client/src/utils/DynamicBindingUtils.ts
index e39e0e8fb6c4..68955665ad9b 100644
--- a/app/client/src/utils/DynamicBindingUtils.ts
+++ b/app/client/src/utils/DynamicBindingUtils.ts
@@ -132,8 +132,6 @@ export enum EVAL_WORKER_ACTIONS {
EVAL_ACTION_BINDINGS = "EVAL_ACTION_BINDINGS",
EVAL_TRIGGER = "EVAL_TRIGGER",
PROCESS_TRIGGER = "PROCESS_TRIGGER",
- CLEAR_PROPERTY_CACHE = "CLEAR_PROPERTY_CACHE",
- CLEAR_PROPERTY_CACHE_OF_WIDGET = "CLEAR_PROPERTY_CACHE_OF_WIDGET",
CLEAR_CACHE = "CLEAR_CACHE",
VALIDATE_PROPERTY = "VALIDATE_PROPERTY",
UNDO = "undo",
diff --git a/app/client/src/utils/WidgetFactory.tsx b/app/client/src/utils/WidgetFactory.tsx
index a9bb7247c215..2a07f0486920 100644
--- a/app/client/src/utils/WidgetFactory.tsx
+++ b/app/client/src/utils/WidgetFactory.tsx
@@ -208,7 +208,7 @@ class WidgetFactory {
static getWidgetMetaPropertiesMap(
widgetType: WidgetType,
- ): Record<string, string> {
+ ): Record<string, unknown> {
const map = this.metaPropertiesMap.get(widgetType);
if (!map) {
log.error("Widget meta properties not defined: ", widgetType);
diff --git a/app/client/src/widgets/MetaHOC.tsx b/app/client/src/widgets/MetaHOC.tsx
index 7700921b470c..6bb93022545e 100644
--- a/app/client/src/widgets/MetaHOC.tsx
+++ b/app/client/src/widgets/MetaHOC.tsx
@@ -1,8 +1,7 @@
import React from "react";
import BaseWidget, { WidgetProps } from "./BaseWidget";
import _ from "lodash";
-import { EditorContext } from "../components/editorComponents/EditorContextProvider";
-import { clearEvalPropertyCache } from "sagas/EvaluationsSaga";
+import { EditorContext } from "components/editorComponents/EditorContextProvider";
import AppsmithConsole from "utils/AppsmithConsole";
import { ENTITY_TYPE } from "entities/AppsmithConsole";
import LOG_TYPE from "entities/AppsmithConsole/logtype";
@@ -116,17 +115,16 @@ const withMeta = (WrappedWidget: typeof BaseWidget) => {
propertyValue: any,
): void => {
const { updateWidgetMetaProperty } = this.context;
- const { widgetId, widgetName } = this.props;
+ const { widgetId } = this.props;
this.setState({
[propertyName]: propertyValue,
});
- clearEvalPropertyCache(`${widgetName}.${propertyName}`);
updateWidgetMetaProperty(widgetId, propertyName, propertyValue);
};
handleUpdateWidgetMetaProperty() {
const { executeAction, updateWidgetMetaProperty } = this.context;
- const { widgetId, widgetName } = this.props;
+ const { widgetId } = this.props;
const metaOptions = this.props.__metaOptions;
/*
We have kept a map of all updated properties. After debouncing we will
@@ -139,8 +137,6 @@ const withMeta = (WrappedWidget: typeof BaseWidget) => {
[...this.updatedProperties.keys()].forEach((propertyName) => {
if (updateWidgetMetaProperty) {
const propertyValue = this.state[propertyName];
-
- clearEvalPropertyCache(`${widgetName}.${propertyName}`);
// step 6 - look at this.props.options, check for metaPropPath value
// if they exist, then update the propertyName
updateWidgetMetaProperty(widgetId, propertyName, propertyValue);
diff --git a/app/client/src/workers/DataTreeEvaluator.ts b/app/client/src/workers/DataTreeEvaluator.ts
index 121daaa1dc4b..04ff391b62c5 100644
--- a/app/client/src/workers/DataTreeEvaluator.ts
+++ b/app/client/src/workers/DataTreeEvaluator.ts
@@ -53,7 +53,6 @@ import {
import _ from "lodash";
import { applyChange, Diff, diff } from "deep-diff";
import toposort from "toposort";
-import equal from "fast-deep-equal/es6";
import {
EXECUTION_PARAM_KEY,
EXECUTION_PARAM_REFERENCE_REGEX,
@@ -73,6 +72,10 @@ import { getLintingErrors } from "workers/lint";
import { error as logError } from "loglevel";
import { extractIdentifiersFromCode } from "workers/ast";
import { JSUpdate } from "utils/JSPaneUtils";
+import {
+ addWidgetPropertyDependencies,
+ overrideWidgetProperties,
+} from "./evaluationUtils";
import {
ActionValidationConfigMap,
ValidationConfig,
@@ -90,13 +93,6 @@ export default class DataTreeEvaluator {
errors: EvalError[] = [];
resolvedFunctions: Record<string, any> = {};
currentJSCollectionState: Record<string, any> = {};
- parsedValueCache: Map<
- string,
- {
- value: any;
- version: number;
- }
- > = new Map();
logs: any[] = [];
allActionValidationConfig?: { [actionId: string]: ActionValidationConfigMap };
public hasCyclicalDependency = false;
@@ -265,7 +261,7 @@ export default class DataTreeEvaluator {
const differences: Diff<DataTree, DataTree>[] =
diff(this.oldUnEvalTree, localUnEvalTree) || [];
- // Since eval tree is listening to possible events that dont cause differences
+ // Since eval tree is listening to possible events that don't cause differences
// We want to check if no diffs are present and bail out early
if (differences.length === 0) {
return {
@@ -501,28 +497,27 @@ export default class DataTreeEvaluator {
entity: DataTreeWidget | DataTreeAction | DataTreeJSAction,
entityName: string,
): DependencyMap {
- const dependencies: DependencyMap = {};
+ let dependencies: DependencyMap = {};
if (isWidget(entity)) {
- // Make property dependant on the default property as any time the default changes
- // the property needs to change
- const defaultProperties = this.widgetConfigMap[entity.type]
- .defaultProperties;
- Object.entries(defaultProperties).forEach(
- ([property, defaultPropertyPath]) => {
- dependencies[`${entityName}.${property}`] = [
- `${entityName}.${defaultPropertyPath}`,
- ];
- },
- );
// Adding the dynamic triggers in the dependency list as they need linting whenever updated
- // we dont make it dependant on anything else
+ // we don't make it dependent on anything else
if (entity.dynamicTriggerPathList) {
Object.values(entity.dynamicTriggerPathList).forEach(({ key }) => {
dependencies[`${entityName}.${key}`] = [];
});
}
+ const widgetDependencies = addWidgetPropertyDependencies({
+ entity,
+ entityName,
+ });
+
+ dependencies = {
+ ...dependencies,
+ ...widgetDependencies,
+ };
}
+
if (isAction(entity) || isJSAction(entity)) {
Object.entries(entity.dependencyMap).forEach(
([path, entityDependencies]) => {
@@ -544,9 +539,9 @@ export default class DataTreeEvaluator {
);
}
if (isJSAction(entity)) {
+ // making functions dependent on their function body entities
if (entity.bindingPaths) {
Object.keys(entity.bindingPaths).forEach((propertyPath) => {
- // dependencies[`${entityName}.${path}`] = [];
const existingDeps =
dependencies[`${entityName}.${propertyPath}`] || [];
const jsSnippets = [_.get(entity, propertyPath)];
@@ -558,6 +553,7 @@ export default class DataTreeEvaluator {
}
if (isAction(entity) || isWidget(entity)) {
+ // add the dynamic binding paths to the dependency map
const dynamicBindingPathList = getEntityDynamicBindingPathList(entity);
if (dynamicBindingPathList.length) {
dynamicBindingPathList.forEach((dynamicPath) => {
@@ -641,33 +637,23 @@ export default class DataTreeEvaluator {
evalPropertyValue = unEvalPropertyValue;
}
if (isWidget(entity) && !isATriggerPath) {
- const widgetEntity = entity;
- const defaultPropertyMap = this.widgetConfigMap[widgetEntity.type]
- .defaultProperties;
- const isDefaultProperty = !!Object.values(
- defaultPropertyMap,
- ).filter(
- (defaultPropertyName) => propertyPath === defaultPropertyName,
- ).length;
if (propertyPath) {
- let parsedValue = this.validateAndParseWidgetProperty(
+ let parsedValue = this.validateAndParseWidgetProperty({
fullPropertyPath,
- widgetEntity,
+ widget: entity,
currentTree,
- resolvedFunctions,
evalPropertyValue,
unEvalPropertyValue,
- isDefaultProperty,
+ });
+ const overwriteObj = overrideWidgetProperties(
+ entity,
+ propertyPath,
+ parsedValue,
+ currentTree,
);
- const hasDefaultProperty = propertyPath in defaultPropertyMap;
- if (hasDefaultProperty) {
- const defaultProperty = defaultPropertyMap[propertyPath];
- parsedValue = this.overwriteDefaultDependentProps(
- defaultProperty,
- parsedValue,
- fullPropertyPath,
- widgetEntity,
- );
+
+ if (overwriteObj && overwriteObj.overwriteParsedValue) {
+ parsedValue = overwriteObj.newValue;
}
return _.set(currentTree, fullPropertyPath, parsedValue);
}
@@ -778,29 +764,6 @@ export default class DataTreeEvaluator {
}
}
- getParsedValueCache(propertyPath: string) {
- return (
- this.parsedValueCache.get(propertyPath) || {
- value: undefined,
- version: 0,
- }
- );
- }
-
- clearPropertyCache(propertyPath: string) {
- this.parsedValueCache.delete(propertyPath);
- }
-
- clearPropertyCacheOfWidget(widgetName: string) {
- // TODO check if this loop mutating itself is safe
- this.parsedValueCache.forEach((value, key) => {
- const match = key.match(`${widgetName}.`);
- if (match) {
- this.parsedValueCache.delete(key);
- }
- });
- }
-
getDynamicValue(
dynamicBinding: string,
data: DataTree,
@@ -845,7 +808,7 @@ export default class DataTreeEvaluator {
}
});
- // We dont need to substitute template of the result if only one binding exists
+ // We don't need to substitute template of the result if only one binding exists
// But it should not be of prepared statements since that does need a string
if (
stringSegments.length === 1 &&
@@ -925,19 +888,23 @@ export default class DataTreeEvaluator {
}
}
- validateAndParseWidgetProperty(
- fullPropertyPath: string,
- widget: DataTreeWidget,
- currentTree: DataTree,
- resolvedFunctions: Record<string, any>,
- evalPropertyValue: any,
- unEvalPropertyValue: string,
- isDefaultProperty: boolean,
- ): any {
+ validateAndParseWidgetProperty({
+ currentTree,
+ evalPropertyValue,
+ fullPropertyPath,
+ unEvalPropertyValue,
+ widget,
+ }: {
+ fullPropertyPath: string;
+ widget: DataTreeWidget;
+ currentTree: DataTree;
+ evalPropertyValue: any;
+ unEvalPropertyValue: string;
+ }): any {
const { propertyPath } = getEntityNameAndPropertyPath(fullPropertyPath);
if (isPathADynamicTrigger(widget, propertyPath)) {
// TODO find a way to validate triggers
- return;
+ return unEvalPropertyValue;
}
const validation = widget.validationPaths[propertyPath];
@@ -971,21 +938,9 @@ export default class DataTreeEvaluator {
addErrorToEntityProperty(evalErrors, currentTree, fullPropertyPath);
}
- if (isPathADynamicTrigger(widget, propertyPath)) {
- return unEvalPropertyValue;
- } else {
- const parsedCache = this.getParsedValueCache(fullPropertyPath);
- // In case this is a default property, always set the cache even if the value remains the same so that the version
- // in cache gets updated and the property dependent on default property updates accordingly.
- if (!equal(parsedCache.value, parsed) || isDefaultProperty) {
- this.parsedValueCache.set(fullPropertyPath, {
- value: parsed,
- version: Date.now(),
- });
- }
- return parsed;
- }
+ return parsed;
}
+
// validates the user input saved as action property based on a validationConfig
validateActionProperty(
fullPropertyPath: string,
@@ -1018,25 +973,6 @@ export default class DataTreeEvaluator {
}
}
- overwriteDefaultDependentProps(
- defaultProperty: string,
- propertyValue: any,
- propertyPath: string,
- entity: DataTreeWidget,
- ) {
- const defaultPropertyCache = this.getParsedValueCache(
- `${entity.widgetName}.${defaultProperty}`,
- );
- const propertyCache = this.getParsedValueCache(propertyPath);
- if (
- propertyValue === undefined ||
- propertyCache.version < defaultPropertyCache.version
- ) {
- return defaultPropertyCache.value;
- }
- return propertyValue;
- }
-
saveResolvedFunctionsAndJSUpdates(
entity: DataTreeJSAction,
jsUpdates: Record<string, any>,
@@ -1476,6 +1412,7 @@ export default class DataTreeEvaluator {
unEvalTree: DataTree,
) {
const changePaths: Set<string> = new Set(dependenciesOfRemovedPaths);
+
for (const d of differences) {
if (!Array.isArray(d.path) || d.path.length === 0) continue; // Null check for typescript
// Apply the changes into the evalTree so that it gets the latest changes
@@ -1532,7 +1469,7 @@ export default class DataTreeEvaluator {
trimmedChangedPaths,
this.inverseDependencyMap,
);
- // Remove any paths that do no exist in the data tree any more
+ // Remove any paths that do not exist in the data tree anymore
return _.difference(completeSortOrder, removedPaths);
}
@@ -1690,7 +1627,7 @@ export const extractReferencesFromBinding = (
// We want to keep going till we reach top level, but not add top level
// Eg: Input1.text should not depend on entire Table1 unless it explicitly asked for that.
// This is mainly to avoid a lot of unnecessary evals, if we feel this is wrong
- // we can remove the length requirement and it will still work
+ // we can remove the length requirement, and it will still work
while (subpaths.length > 1) {
current = convertPathToString(subpaths);
// We've found the dep, add it and return
diff --git a/app/client/src/workers/evaluation.test.ts b/app/client/src/workers/evaluation.test.ts
index 9d22e62e571f..a08627d27771 100644
--- a/app/client/src/workers/evaluation.test.ts
+++ b/app/client/src/workers/evaluation.test.ts
@@ -3,12 +3,27 @@ import {
DataTreeWidget,
ENTITY_TYPE,
EvaluationSubstitutionType,
-} from "../entities/DataTree/dataTreeFactory";
-import { WidgetTypeConfigMap } from "../utils/WidgetFactory";
-import { RenderModes } from "../constants/WidgetConstants";
-import { PluginType } from "../entities/Action";
+} from "entities/DataTree/dataTreeFactory";
+import { WidgetTypeConfigMap } from "utils/WidgetFactory";
+import { RenderModes } from "constants/WidgetConstants";
+import { PluginType } from "entities/Action";
import DataTreeEvaluator from "workers/DataTreeEvaluator";
import { ValidationTypes } from "constants/WidgetValidation";
+import WidgetFactory from "utils/WidgetFactory";
+import { generateDataTreeWidget } from "entities/DataTree/dataTreeWidget";
+
+/**
+ * This function sorts the object's value which is array of string.
+ *
+ * @param {Record<string, Array<string>>} data
+ * @return {*}
+ */
+const sortObject = (data: Record<string, Array<string>>) => {
+ Object.entries(data).map(([key, value]) => {
+ data[key] = value.sort();
+ });
+ return data;
+};
const WIDGET_CONFIG_MAP: WidgetTypeConfigMap = {
CONTAINER_WIDGET: {
@@ -225,6 +240,8 @@ const BASE_WIDGET: DataTreeWidget = {
triggerPaths: {},
validationPaths: {},
ENTITY_TYPE: ENTITY_TYPE.WIDGET,
+ propertyOverrideDependency: {},
+ overridingPropertyPaths: {},
privateWidgets: {},
};
@@ -233,6 +250,7 @@ const BASE_ACTION: DataTreeAction = {
logBlackList: {},
actionId: "randomId",
name: "randomActionName",
+ datasourceUrl: "",
config: {
timeoutInMillisecond: 10,
},
@@ -251,100 +269,160 @@ const BASE_ACTION: DataTreeAction = {
datasourceUrl: "",
};
+const metaMock = jest.spyOn(WidgetFactory, "getWidgetMetaPropertiesMap");
+
+const mockDefault = jest.spyOn(WidgetFactory, "getWidgetDefaultPropertiesMap");
+
+const mockDerived = jest.spyOn(WidgetFactory, "getWidgetDerivedPropertiesMap");
+
+const dependencyMap = {
+ Dropdown1: [
+ "Dropdown1.defaultOptionValue",
+ "Dropdown1.isValid",
+ "Dropdown1.selectedIndex",
+ "Dropdown1.selectedIndexArr",
+ "Dropdown1.selectedOption",
+ "Dropdown1.selectedOptionArr",
+ "Dropdown1.selectedOptionValue",
+ "Dropdown1.selectedOptionValueArr",
+ "Dropdown1.selectedOptionValues",
+ "Dropdown1.value",
+ ],
+ "Dropdown1.isValid": [],
+ "Dropdown1.selectedIndex": [],
+ "Dropdown1.selectedIndexArr": [],
+ "Dropdown1.selectedOption": [],
+ "Dropdown1.selectedOptionArr": [],
+ "Dropdown1.selectedOptionValue": ["Dropdown1.defaultOptionValue"],
+ "Dropdown1.selectedOptionValueArr": ["Dropdown1.defaultOptionValue"],
+ "Dropdown1.selectedOptionValues": [],
+ "Dropdown1.value": [],
+ Table1: [
+ "Table1.defaultSearchText",
+ "Table1.defaultSelectedRow",
+ "Table1.searchText",
+ "Table1.selectedRow",
+ "Table1.selectedRowIndex",
+ "Table1.selectedRowIndices",
+ "Table1.selectedRows",
+ "Table1.tableData",
+ ],
+ "Table1.searchText": ["Table1.defaultSearchText"],
+ "Table1.selectedRow": [],
+ "Table1.selectedRowIndex": ["Table1.defaultSelectedRow"],
+ "Table1.selectedRowIndices": ["Table1.defaultSelectedRow"],
+ "Table1.selectedRows": [],
+ "Table1.tableData": ["Text1.text"],
+ Text1: ["Text1.text", "Text1.value"],
+ "Text1.value": ["Text1.text"],
+ Text2: ["Text2.text", "Text2.value"],
+ "Text2.text": ["Text1.text"],
+ "Text2.value": ["Text2.text"],
+ Text3: ["Text3.text", "Text3.value"],
+ "Text3.value": ["Text3.text"],
+ Text4: ["Text4.text", "Text4.value"],
+ "Text4.text": ["Table1.selectedRow"],
+ "Text4.value": [],
+};
+
describe("DataTreeEvaluator", () => {
- const unEvalTree: Record<string, DataTreeWidget> = {
- Text1: {
+ metaMock.mockImplementation((type) => {
+ return WIDGET_CONFIG_MAP[type].metaProperties;
+ });
+ mockDefault.mockImplementation((type) => {
+ return WIDGET_CONFIG_MAP[type].defaultProperties;
+ });
+ mockDerived.mockImplementation((type) => {
+ return WIDGET_CONFIG_MAP[type].derivedProperties;
+ });
+ const Input1 = generateDataTreeWidget(
+ {
...BASE_WIDGET,
- widgetName: "Text1",
- text: "Label",
- type: "TEXT_WIDGET",
+ text: undefined,
+ defaultText: "Default value",
+ widgetName: "Input1",
+ type: "INPUT_WIDGET_V2",
bindingPaths: {
+ defaultText: EvaluationSubstitutionType.TEMPLATE,
+ isValid: EvaluationSubstitutionType.TEMPLATE,
+ value: EvaluationSubstitutionType.TEMPLATE,
text: EvaluationSubstitutionType.TEMPLATE,
},
- validationPaths: {
- text: { type: ValidationTypes.TEXT },
- },
},
- Text2: {
- ...BASE_WIDGET,
- widgetName: "Text2",
- text: "{{Text1.text}}",
- dynamicBindingPathList: [{ key: "text" }],
- type: "TEXT_WIDGET",
- bindingPaths: {
- text: EvaluationSubstitutionType.TEMPLATE,
+ {},
+ );
+ const unEvalTree: Record<string, DataTreeWidget> = {
+ Text1: generateDataTreeWidget(
+ {
+ ...BASE_WIDGET,
+ widgetName: "Text1",
+ text: "Label",
+ type: "TEXT_WIDGET",
},
- validationPaths: {
- text: { type: ValidationTypes.TEXT },
+ {},
+ ),
+ Text2: generateDataTreeWidget(
+ {
+ ...BASE_WIDGET,
+ widgetName: "Text2",
+ text: "{{Text1.text}}",
+ dynamicBindingPathList: [{ key: "text" }],
+ type: "TEXT_WIDGET",
},
- },
- Text3: {
- ...BASE_WIDGET,
- widgetName: "Text3",
- text: "{{Text1.text}}",
- dynamicBindingPathList: [{ key: "text" }],
- type: "TEXT_WIDGET",
- bindingPaths: {
- text: EvaluationSubstitutionType.TEMPLATE,
+ {},
+ ),
+ Text3: generateDataTreeWidget(
+ {
+ ...BASE_WIDGET,
+ widgetName: "Text3",
+ text: "{{Text1.text}}",
+ dynamicBindingPathList: [{ key: "text" }],
+ type: "TEXT_WIDGET",
+ },
+ {},
+ ),
+ Dropdown1: generateDataTreeWidget(
+ {
+ ...BASE_WIDGET,
+ options: [
+ {
+ label: "test",
+ value: "valueTest",
+ },
+ {
+ label: "test2",
+ value: "valueTest2",
+ },
+ ],
+ type: "DROP_DOWN_WIDGET",
},
- validationPaths: {
- text: { type: ValidationTypes.TEXT },
+ {},
+ ),
+ Table1: generateDataTreeWidget(
+ {
+ ...BASE_WIDGET,
+ tableData:
+ "{{Api1.data.map(datum => ({ ...datum, raw: Text1.text }) )}}",
+ dynamicBindingPathList: [{ key: "tableData" }],
+ type: "TABLE_WIDGET",
},
- },
- Dropdown1: {
- ...BASE_WIDGET,
- options: [
- {
- label: "test",
- value: "valueTest",
+ {},
+ ),
+ Text4: generateDataTreeWidget(
+ {
+ ...BASE_WIDGET,
+ text: "{{Table1.selectedRow.test}}",
+ dynamicBindingPathList: [{ key: "text" }],
+ type: "TEXT_WIDGET",
+ bindingPaths: {
+ text: EvaluationSubstitutionType.TEMPLATE,
},
- {
- label: "test2",
- value: "valueTest2",
+ validationPaths: {
+ text: { type: ValidationTypes.TEXT },
},
- ],
- type: "DROP_DOWN_WIDGET",
- bindingPaths: {
- options: EvaluationSubstitutionType.TEMPLATE,
- defaultOptionValue: EvaluationSubstitutionType.TEMPLATE,
- isRequired: EvaluationSubstitutionType.TEMPLATE,
- isVisible: EvaluationSubstitutionType.TEMPLATE,
- isDisabled: EvaluationSubstitutionType.TEMPLATE,
- isValid: EvaluationSubstitutionType.TEMPLATE,
- selectedOption: EvaluationSubstitutionType.TEMPLATE,
- selectedOptionArr: EvaluationSubstitutionType.TEMPLATE,
- selectedIndex: EvaluationSubstitutionType.TEMPLATE,
- selectedIndexArr: EvaluationSubstitutionType.TEMPLATE,
- value: EvaluationSubstitutionType.TEMPLATE,
- selectedOptionValues: EvaluationSubstitutionType.TEMPLATE,
- },
- },
- Table1: {
- ...BASE_WIDGET,
- tableData: "{{Api1.data.map(datum => ({ ...datum, raw: Text1.text }) )}}",
- dynamicBindingPathList: [{ key: "tableData" }],
- type: "TABLE_WIDGET",
- bindingPaths: {
- tableData: EvaluationSubstitutionType.TEMPLATE,
- selectedRow: EvaluationSubstitutionType.TEMPLATE,
- selectedRows: EvaluationSubstitutionType.TEMPLATE,
- },
- validationPaths: {
- tableData: { type: ValidationTypes.OBJECT_ARRAY },
},
- },
- Text4: {
- ...BASE_WIDGET,
- text: "{{Table1.selectedRow.test}}",
- dynamicBindingPathList: [{ key: "text" }],
- type: "TEXT_WIDGET",
- bindingPaths: {
- text: EvaluationSubstitutionType.TEMPLATE,
- },
- validationPaths: {
- text: { type: ValidationTypes.TEXT },
- },
- },
+ {},
+ ),
};
const evaluator = new DataTreeEvaluator(WIDGET_CONFIG_MAP);
evaluator.createFirstTree(unEvalTree);
@@ -354,31 +432,7 @@ describe("DataTreeEvaluator", () => {
expect(evaluation).toHaveProperty("Text2.text", "Label");
expect(evaluation).toHaveProperty("Text3.text", "Label");
- expect(dependencyMap).toStrictEqual({
- Text1: ["Text1.text"],
- Text2: ["Text2.text"],
- Text3: ["Text3.text"],
- Text4: ["Text4.text"],
- Table1: expect.arrayContaining([
- "Table1.tableData",
- "Table1.searchText",
- "Table1.selectedRowIndex",
- "Table1.selectedRowIndices",
- ]),
- Dropdown1: expect.arrayContaining([
- "Dropdown1.selectedOptionValue",
- "Dropdown1.selectedOptionValueArr",
- ]),
- "Text2.text": ["Text1.text"],
- "Text3.text": ["Text1.text"],
- "Dropdown1.selectedOptionValue": [],
- "Dropdown1.selectedOptionValueArr": [],
- "Table1.tableData": ["Text1.text"],
- "Table1.searchText": [],
- "Table1.selectedRowIndex": [],
- "Table1.selectedRowIndices": [],
- "Text4.text": [],
- });
+ expect(sortObject(dependencyMap)).toStrictEqual(dependencyMap);
});
it("Evaluates a value change in update run", () => {
@@ -408,48 +462,14 @@ describe("DataTreeEvaluator", () => {
const updatedDependencyMap = evaluator.dependencyMap;
expect(dataTree).toHaveProperty("Text2.text", "Label");
expect(dataTree).toHaveProperty("Text3.text", "Label 3");
- expect(updatedDependencyMap).toStrictEqual({
- Text1: ["Text1.text"],
- Text2: ["Text2.text"],
- Text3: ["Text3.text"],
- Text4: ["Text4.text"],
- Table1: [
- "Table1.tableData",
- "Table1.searchText",
- "Table1.selectedRowIndex",
- "Table1.selectedRowIndices",
- ],
- Dropdown1: [
- "Dropdown1.selectedOptionValue",
- "Dropdown1.selectedOptionValueArr",
- ],
- "Text2.text": ["Text1.text"],
- "Dropdown1.selectedOptionValue": [],
- "Dropdown1.selectedOptionValueArr": [],
- "Table1.tableData": ["Text1.text"],
- "Table1.searchText": [],
- "Table1.selectedRowIndex": [],
- "Table1.selectedRowIndices": [],
- "Text4.text": [],
- });
+
+ expect(sortObject(updatedDependencyMap)).toStrictEqual(dependencyMap);
});
it("Overrides with default value", () => {
const updatedUnEvalTree = {
...unEvalTree,
- Input1: {
- ...BASE_WIDGET,
- text: undefined,
- defaultText: "Default value",
- widgetName: "Input1",
- type: "INPUT_WIDGET_V2",
- bindingPaths: {
- defaultText: EvaluationSubstitutionType.TEMPLATE,
- isValid: EvaluationSubstitutionType.TEMPLATE,
- value: EvaluationSubstitutionType.TEMPLATE,
- text: EvaluationSubstitutionType.TEMPLATE,
- },
- },
+ Input1,
};
evaluator.updateDataTree(updatedUnEvalTree);
@@ -523,31 +543,12 @@ describe("DataTreeEvaluator", () => {
raw: "Label",
},
]);
- expect(updatedDependencyMap).toStrictEqual({
+
+ expect(sortObject(updatedDependencyMap)).toStrictEqual({
Api1: ["Api1.data"],
- Text1: ["Text1.text"],
- Text2: ["Text2.text"],
- Text3: ["Text3.text"],
- Text4: ["Text4.text"],
- Table1: [
- "Table1.tableData",
- "Table1.searchText",
- "Table1.selectedRowIndex",
- "Table1.selectedRowIndices",
- ],
- Dropdown1: [
- "Dropdown1.selectedOptionValue",
- "Dropdown1.selectedOptionValueArr",
- ],
- "Text2.text": ["Text1.text"],
- "Text3.text": ["Text1.text"],
- "Dropdown1.selectedOptionValue": [],
- "Dropdown1.selectedOptionValueArr": [],
+ ...dependencyMap,
"Table1.tableData": ["Api1.data", "Text1.text"],
- "Table1.searchText": [],
- "Table1.selectedRowIndex": [],
- "Table1.selectedRowIndices": [],
- "Text4.text": [],
+ "Text3.text": ["Text1.text"],
});
});
@@ -589,33 +590,11 @@ describe("DataTreeEvaluator", () => {
},
]);
expect(dataTree).toHaveProperty("Text4.text", "Hey");
- expect(updatedDependencyMap).toStrictEqual({
+ expect(sortObject(updatedDependencyMap)).toStrictEqual({
Api1: ["Api1.data"],
- Text1: ["Text1.text"],
- Text2: ["Text2.text"],
- Text3: ["Text3.text"],
- Text4: ["Text4.text"],
- Table1: [
- "Table1.tableData",
- "Table1.selectedRowIndex",
- "Table1.searchText",
- "Table1.selectedRowIndices",
- "Table1.selectedRow",
- ],
- "Table1.selectedRow": ["Table1.selectedRow.test"],
- Dropdown1: [
- "Dropdown1.selectedOptionValue",
- "Dropdown1.selectedOptionValueArr",
- ],
- "Text2.text": ["Text1.text"],
- "Text3.text": ["Text1.text"],
- "Dropdown1.selectedOptionValue": [],
- "Dropdown1.selectedOptionValueArr": [],
+ ...dependencyMap,
"Table1.tableData": ["Api1.data", "Text1.text"],
- "Table1.searchText": [],
- "Table1.selectedRowIndex": [],
- "Table1.selectedRowIndices": [],
- "Text4.text": ["Table1.selectedRow.test"],
+ "Text3.text": ["Text1.text"],
});
});
diff --git a/app/client/src/workers/evaluation.worker.ts b/app/client/src/workers/evaluation.worker.ts
index b0b566ff6b2c..75fd287a7c9c 100644
--- a/app/client/src/workers/evaluation.worker.ts
+++ b/app/client/src/workers/evaluation.worker.ts
@@ -240,22 +240,6 @@ ctx.addEventListener(
dataTreeEvaluator = undefined;
return true;
}
- case EVAL_WORKER_ACTIONS.CLEAR_PROPERTY_CACHE: {
- const { propertyPath } = requestData;
- if (!dataTreeEvaluator) {
- return true;
- }
- dataTreeEvaluator.clearPropertyCache(propertyPath);
- return true;
- }
- case EVAL_WORKER_ACTIONS.CLEAR_PROPERTY_CACHE_OF_WIDGET: {
- const { widgetName } = requestData;
- if (!dataTreeEvaluator) {
- return true;
- }
- dataTreeEvaluator.clearPropertyCacheOfWidget(widgetName);
- return true;
- }
case EVAL_WORKER_ACTIONS.VALIDATE_PROPERTY: {
const { props, validation, value } = requestData;
return removeFunctions(
diff --git a/app/client/src/workers/evaluationUtils.ts b/app/client/src/workers/evaluationUtils.ts
index 30356319652a..2808024ef85e 100644
--- a/app/client/src/workers/evaluationUtils.ts
+++ b/app/client/src/workers/evaluationUtils.ts
@@ -27,6 +27,7 @@ import { ValidationConfig } from "constants/PropertyControlConstants";
import { Severity } from "entities/AppsmithConsole";
import { ParsedBody, ParsedJSSubAction } from "utils/JSPaneUtils";
import { Variable } from "entities/JSCollection";
+import { cloneDeep } from "lodash";
// Dropdown1.options[1].value -> Dropdown1.options[1]
// Dropdown1.options[1] -> Dropdown1.options
@@ -725,6 +726,39 @@ export const removeFunctionsAndVariableJSCollection = (
return modifiedDataTree;
};
+export const addWidgetPropertyDependencies = ({
+ entity,
+ entityName,
+}: {
+ entity: DataTreeWidget;
+ entityName: string;
+}) => {
+ const dependencies: DependencyMap = {};
+
+ Object.entries(entity.propertyOverrideDependency).forEach(
+ ([overriddenPropertyKey, overridingPropertyKeyMap]) => {
+ const existingDependenciesSet = new Set(
+ dependencies[`${entityName}.${overriddenPropertyKey}`] || [],
+ );
+ // add meta dependency
+ overridingPropertyKeyMap.META &&
+ existingDependenciesSet.add(
+ `${entityName}.${overridingPropertyKeyMap.META}`,
+ );
+ // add default dependency
+ overridingPropertyKeyMap.DEFAULT &&
+ existingDependenciesSet.add(
+ `${entityName}.${overridingPropertyKeyMap.DEFAULT}`,
+ );
+
+ dependencies[`${entityName}.${overriddenPropertyKey}`] = [
+ ...existingDependenciesSet,
+ ];
+ },
+ );
+ return dependencies;
+};
+
export const isPrivateEntityPath = (
privateWidgets: PrivateWidgets,
fullPropertyPath: string,
@@ -759,3 +793,47 @@ export const getDataTreeWithoutPrivateWidgets = (
const treeWithoutPrivateWidgets = _.omit(dataTree, privateWidgetNames);
return treeWithoutPrivateWidgets;
};
+
+export const overrideWidgetProperties = (
+ entity: DataTreeWidget,
+ propertyPath: string,
+ value: unknown,
+ currentTree: DataTree,
+) => {
+ const clonedValue = cloneDeep(value);
+ if (propertyPath in entity.overridingPropertyPaths) {
+ const overridingPropertyPaths =
+ entity.overridingPropertyPaths[propertyPath];
+
+ overridingPropertyPaths.forEach((overriddenPropertyKey) => {
+ _.set(
+ currentTree,
+ `${entity.widgetName}.${overriddenPropertyKey}`,
+ clonedValue,
+ );
+ });
+ } else if (
+ propertyPath in entity.propertyOverrideDependency &&
+ clonedValue === undefined
+ ) {
+ // when value is undefined and has default value then set value to default value.
+ // this is for resetForm
+ const propertyOverridingKeyMap =
+ entity.propertyOverrideDependency[propertyPath];
+ if (propertyOverridingKeyMap.DEFAULT) {
+ const defaultValue = entity[propertyOverridingKeyMap.DEFAULT];
+ const clonedDefaultValue = cloneDeep(defaultValue);
+ if (defaultValue !== undefined) {
+ _.set(
+ currentTree,
+ `${entity.widgetName}.${propertyPath}`,
+ clonedDefaultValue,
+ );
+ return {
+ overwriteParsedValue: true,
+ newValue: clonedDefaultValue,
+ };
+ }
+ }
+ }
+};
|
c7eb8c115c1ab0b59b38c552090d9e537d81a435
|
2024-01-18 00:20:48
|
Rishabh Rathod
|
fix: JSModule action selector bug (#30400)
| false
|
JSModule action selector bug (#30400)
|
fix
|
diff --git a/app/client/src/components/editorComponents/ActionCreator/helpers.tsx b/app/client/src/components/editorComponents/ActionCreator/helpers.tsx
index 359e3ca3aea1..066c761f629a 100644
--- a/app/client/src/components/editorComponents/ActionCreator/helpers.tsx
+++ b/app/client/src/components/editorComponents/ActionCreator/helpers.tsx
@@ -604,7 +604,7 @@ export function getJSOptions(
const jsFunction = {
label: js.name,
id: js.id,
- value: jsModuleInstance.config.name + "." + js.name,
+ value: jsModuleInstance.name + "." + js.name,
type: jsOption.value,
icon: <Icon name="js-function" size="md" />,
args: argValue,
|
c285acac63a2ad2bdd168df433b4fadcfbbaf78a
|
2023-07-27 21:24:29
|
Aishwarya-U-R
|
test: Cypress | Fix Datasources/MockDBs_Spec.ts (#25796)
| false
|
Cypress | Fix Datasources/MockDBs_Spec.ts (#25796)
|
test
|
diff --git a/app/client/cypress/e2e/Sanity/Datasources/MockDBs_Spec.ts b/app/client/cypress/e2e/Sanity/Datasources/MockDBs_Spec.ts
index d72c36b6c927..87ed2a7713ae 100644
--- a/app/client/cypress/e2e/Sanity/Datasources/MockDBs_Spec.ts
+++ b/app/client/cypress/e2e/Sanity/Datasources/MockDBs_Spec.ts
@@ -15,6 +15,7 @@ describe(
it("1. Create Query from Mock Mongo DB & verify active queries count", () => {
dataSources.CreateMockDB("Movies").then((mockDBName) => {
dsName = mockDBName;
+ cy.log("Mock DB Name: " + mockDBName);
// delay is introduced so that structure fetch is complete before moving to query creation
// feat: #25320, new query created for mock db movies, will be populated with default values
@@ -26,7 +27,7 @@ describe(
assertHelper.AssertNetworkStatus("@trigger");
dataSources.ValidateNSelectDropdown("Commands", "Find document(s)");
dataSources.ValidateNSelectDropdown("Collection", "movies");
- dataSources.RunQueryNVerifyResponseViews(1, false);
+ dataSources.RunQueryNVerifyResponseViews(2, false);
dataSources.NavigateToActiveTab();
agHelper
.GetText(dataSources._queriesOnPageText(mockDBName))
@@ -37,7 +38,7 @@ describe(
entityExplorer.CreateNewDsQuery(mockDBName);
dataSources.ValidateNSelectDropdown("Commands", "Find document(s)");
dataSources.ValidateNSelectDropdown("Collection", "movies");
- dataSources.RunQueryNVerifyResponseViews(1, false);
+ dataSources.RunQueryNVerifyResponseViews(2, false);
dataSources.NavigateToActiveTab();
agHelper
.GetText(dataSources._queriesOnPageText(mockDBName))
@@ -50,6 +51,7 @@ describe(
it("2. Create Query from Mock Postgres DB & verify active queries count", () => {
dataSources.CreateMockDB("Users").then((mockDBName) => {
dsName = mockDBName;
+ cy.log("Mock DB Name: " + mockDBName);
assertHelper.AssertNetworkStatus("@getDatasourceStructure", 200);
dataSources.CreateQueryAfterDSSaved();
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.