Skip to content

armgit / core

Public Imported from GitHub
0

100% open-source IoT Platform - Integrate your devices, add intelligence, build custom apps

Fix schema generator generating duplicate type properties for the OAuthGrant subtypes (#2558)

Koendd24cb13a977
diff --git a/agent/src/main/java/org/openremote/agent/protocol/simulator/SimulatorAgentLink.java b/agent/src/main/java/org/openremote/agent/protocol/simulator/SimulatorAgentLink.java
index 00459fee4..d25f12d44 100644
--- a/agent/src/main/java/org/openremote/agent/protocol/simulator/SimulatorAgentLink.java
+++ b/agent/src/main/java/org/openremote/agent/protocol/simulator/SimulatorAgentLink.java
@@ -32,7 +32,6 @@ import java.util.Arrays;
import java.util.Optional;
import java.util.TimeZone;
-@JsonSchemaDefault("{\"timezone\":\"\"}")
public class SimulatorAgentLink extends AgentLink<SimulatorAgentLink> {
@JsonSchemaDescription("Used to store a dataset of values that should be replayed (i.e. written to the" +
@@ -51,6 +50,7 @@ public class SimulatorAgentLink extends AgentLink<SimulatorAgentLink> {
@JsonSchemaFormat("simulator-schedule")
protected SimulatorProtocol.Schedule schedule;
+ @JsonSchemaDefault("")
@JsonSchemaDescription("The timezone the Simulator should follow to replay the dataset.")
@JsonSchemaFormat("timezone")
protected TimeZone timezone;
diff --git a/agent/src/main/java/org/openremote/agent/protocol/websocket/WebsocketHTTPSubscription.java b/agent/src/main/java/org/openremote/agent/protocol/websocket/WebsocketHTTPSubscription.java
index 6f315ab1c..b763b3de8 100644
--- a/agent/src/main/java/org/openremote/agent/protocol/websocket/WebsocketHTTPSubscription.java
+++ b/agent/src/main/java/org/openremote/agent/protocol/websocket/WebsocketHTTPSubscription.java
@@ -20,6 +20,7 @@
package org.openremote.agent.protocol.websocket;
import com.fasterxml.jackson.annotation.JsonTypeName;
+import org.openremote.model.util.JSONSchemaUtil.*;
import org.openremote.model.value.ValueType;
@JsonTypeName(WebsocketHTTPSubscription.TYPE)
@@ -35,6 +36,7 @@ public class WebsocketHTTPSubscription extends WebsocketSubscription {
public Method method;
public String contentType;
+ @JsonSchemaTitle(value = "Headers", i18n = false)
public ValueType.MultivaluedStringMap headers;
public String uri;
diff --git a/agent/src/main/java/org/openremote/agent/protocol/websocket/WebsocketSubscription.java b/agent/src/main/java/org/openremote/agent/protocol/websocket/WebsocketSubscription.java
index d4a2ae639..94f02c641 100644
--- a/agent/src/main/java/org/openremote/agent/protocol/websocket/WebsocketSubscription.java
+++ b/agent/src/main/java/org/openremote/agent/protocol/websocket/WebsocketSubscription.java
@@ -21,6 +21,7 @@ package org.openremote.agent.protocol.websocket;
import com.fasterxml.jackson.annotation.JsonSubTypes;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
+import org.openremote.model.util.JSONSchemaUtil.*;
import java.io.Serializable;
@@ -30,11 +31,11 @@ import java.io.Serializable;
})
@JsonTypeInfo(
use = JsonTypeInfo.Id.NAME,
- property = "type",
- defaultImpl = WebsocketSubscriptionImpl.class
+ property = "type"
)
public abstract class WebsocketSubscription implements Serializable {
+ @JsonSchemaTitle(value = "Body", i18n = false)
public Object body;
public WebsocketSubscription body(Object body) {
diff --git a/model/src/main/java/org/openremote/model/auth/OAuthGrant.java b/model/src/main/java/org/openremote/model/auth/OAuthGrant.java
index ef3b9df5c..5378b1399 100644
--- a/model/src/main/java/org/openremote/model/auth/OAuthGrant.java
+++ b/model/src/main/java/org/openremote/model/auth/OAuthGrant.java
@@ -22,6 +22,7 @@ package org.openremote.model.auth;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonSubTypes;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
+import jakarta.validation.constraints.NotNull;
import org.openremote.model.util.TextUtil;
import jakarta.ws.rs.core.MultivaluedHashMap;
@@ -44,11 +45,13 @@ public abstract class OAuthGrant implements Serializable {
public static final String VALUE_KEY_CLIENT_ID = "client_id";
public static final String VALUE_KEY_CLIENT_SECRET = "client_secret";
public static final String VALUE_KEY_SCOPE = "scope";
+ @NotNull
protected String tokenEndpointUri;
protected boolean basicAuthHeader;
protected Map<String, List<String>> additionalValueMap = null;
@JsonProperty(VALUE_KEY_GRANT_TYPE)
protected String grantType;
+ @NotNull
@JsonProperty(VALUE_KEY_CLIENT_ID)
String clientId;
@JsonProperty(VALUE_KEY_CLIENT_SECRET)
diff --git a/model/src/main/java/org/openremote/model/util/JSONSchemaUtil.java b/model/src/main/java/org/openremote/model/util/JSONSchemaUtil.java
index b3bb496b6..b011c1c8a 100644
--- a/model/src/main/java/org/openremote/model/util/JSONSchemaUtil.java
+++ b/model/src/main/java/org/openremote/model/util/JSONSchemaUtil.java
@@ -211,6 +211,7 @@ public class JSONSchemaUtil {
// Remap Byte to type integer, see https://github.com/victools/jsonschema-generator/blob/995a71eaf7a9a05cc2e335f8a7821b4a9019fa1b/CHANGELOG.md?plain=1#L530
builder.with(new SimpleTypeModule().withIntegerType(Byte.class));
+ // TODO: check whether we can set this to false as this does not align with most of our APIs
// Apply additionalProperties true to all object values that haven't already set additionalProperties
builder.forTypesInGeneral().withTypeAttributeOverride((attrs, typeScope, context) -> {
if (attrs.has("type") && !attrs.has("additionalProperties") && Objects.equals(attrs.get("type").textValue(), "object")) {
@@ -265,6 +266,8 @@ public class JSONSchemaUtil {
.withPropertyNameOverrideResolver(jacksonResolvers::getPropertyNameOverrideBasedOnJsonPropertyAnnotation)
// Primitive types cannot be null, thus they are always required and handle Jackson required properties
.withRequiredCheck((f) -> f.getType().getErasedType().isPrimitive() || jacksonResolvers.getRequiredCheckBasedOnJsonPropertyAnnotation(f))
+ // Explicitly set default to false for primitive booleans
+ .withDefaultResolver(CustomModule::resolveBooleanDefault)
// direct class to class mapping through annotations
.withTargetTypeOverridesResolver(this::remapFieldType)
// remapping using supplier through annotations
@@ -325,19 +328,16 @@ public class JSONSchemaUtil {
Class<?> rawType = resolvedType.getErasedType();
- // Custom subtype handling mimicking createSubtypeDefinition referencing subtypes as enum type value
- // for polymorphic types
- if (rawType.isAnnotationPresent(JsonTypeInfo.class) && rawType.getAnnotation(JsonTypeInfo.class).include() == JsonTypeInfo.As.EXTERNAL_PROPERTY) {
- ArrayNode enumTypeArray = definition
- .withObject(context.getKeyword(SchemaKeyword.TAG_PROPERTIES))
- .withObject(context.getKeyword(SchemaKeyword.TAG_TYPE))
- .withArray(context.getKeyword(SchemaKeyword.TAG_ENUM));
-
+ // This adds a discriminator property to the root of a polymorphic type that should be used to
+ // determine the subtype, and also adds missing subtype references (in favor of
+ // com.github.victools.jsonschema.module.jackson.JsonSubTypesResolver.createSubtypeDefinition).
+ // Note: The "discriminator" property is not part of the standard JSON Schema spec (DRAFT-7)
+ if (isPolymorphicType(rawType)) {
+ String discriminator = rawType.getAnnotation(JsonTypeInfo.class).property();
+ definition.putObject("discriminator").put("propertyName", discriminator);
// Removing and adding the `oneOf` property on the schema ensures the definitions are referenced
definition.remove(context.getKeyword(SchemaKeyword.TAG_ONEOF));
for (ResolvedType subType : subTypes) {
- // Add subtype to the enum type array of the abstract class
- enumTypeArray.add(subType.getErasedType().getSimpleName());
// Add back subtype definitions to `oneOf` property
definition.withArray(context.getKeyword(SchemaKeyword.TAG_ONEOF)).add(context.createDefinitionReference(subType));
}
@@ -350,36 +350,15 @@ public class JSONSchemaUtil {
return new CustomDefinition(definition, CustomDefinition.DefinitionType.INLINE, CustomDefinition.AttributeInclusion.YES);
});
- // Set the default keyword for subtypes so AJV in the frontend can tell jsonforms/core to consider the
- // subtype schema valid
+ // Remove duplicate discriminator "type" keywords and add missing discriminator properties for classes using
+ // JsonTypeInfo.As.EXTERNAL_PROPERTY
builder.forTypesInGeneral().withTypeAttributeOverride((attrs, typeScope, context) -> {
Class<?> erasedType = typeScope.getType().getErasedType();
if (erasedType.getSuperclass() == Object.class) {
return;
}
-
- Class<?> current = erasedType;
- JsonTypeInfo annotation = null;
- String key = null;
- do {
- current = current.getSuperclass();
- if (current != null) {
- annotation = current.getAnnotation(JsonTypeInfo.class);
- if (annotation != null) key = annotation.property();
- }
- } while (current != null && current.getSuperclass() != Object.class && key == null);
-
- // If EXTERNAL_PROPERTY specified, manually add 'const', 'default' and 'required' properties
- if (annotation != null && annotation.include() == JsonTypeInfo.As.EXTERNAL_PROPERTY) {
- attrs.withArray(context.getKeyword(SchemaKeyword.TAG_REQUIRED))
- .add(context.getKeyword(SchemaKeyword.TAG_TYPE));
- attrs.withObject(context.getKeyword(SchemaKeyword.TAG_PROPERTIES))
- .withObject(context.getKeyword(SchemaKeyword.TAG_TYPE))
- .put(context.getKeyword(SchemaKeyword.TAG_CONST), erasedType.getSimpleName())
- .put(context.getKeyword(SchemaKeyword.TAG_DEFAULT), erasedType.getSimpleName());
- return;
- }
- addDefaultToDiscriminator(attrs, context, key);
+ JsonTypeInfo annotation = resolveTypeInfoAnnotation(erasedType);
+ normalizeDiscriminator(attrs, erasedType, context, annotation);
});
// Effectively disable const generation (on the root of subtypes)
@@ -492,6 +471,23 @@ public class JSONSchemaUtil {
return fieldScope.getMember().getDeclaringType().getErasedType().getCanonicalName() + "." + fieldScope.getMember().getName();
}
+ private static Object resolveBooleanDefault(FieldScope field) {
+ if (field.getType().isInstanceOf(boolean.class)) {
+ JsonSchemaDefault annotation = field.getAnnotation(JsonSchemaDefault.class);
+ // If annotation is present, parse the string; otherwise, fallback to false
+ return annotation != null && Boolean.parseBoolean(annotation.value());
+ }
+ // Return null for non-boolean fields so other resolvers can run
+ return null;
+ }
+
+ private static boolean isPolymorphicType(Class<?> clazz) {
+ return clazz.isAnnotationPresent(JsonTypeInfo.class)
+ && (clazz.getAnnotation(JsonTypeInfo.class).include() == JsonTypeInfo.As.PROPERTY ||
+ clazz.getAnnotation(JsonTypeInfo.class).include() == JsonTypeInfo.As.EXISTING_PROPERTY ||
+ clazz.getAnnotation(JsonTypeInfo.class).include() == JsonTypeInfo.As.EXTERNAL_PROPERTY);
+ }
+
private static void setFormat(ObjectNode node, String format) {
node.put("format", format);
}
@@ -539,13 +535,7 @@ public class JSONSchemaUtil {
*/
@Override
public void overrideTypeAttributes(ObjectNode attrs, TypeScope scope, SchemaGenerationContext context) {
- if ((this.rootType.get() == scope.getType() && !attrs.has(context.getKeyword(SchemaKeyword.TAG_TITLE))) ||
- (!attrs.has(context.getKeyword(SchemaKeyword.TAG_TITLE))
- && !scope.getType().isInstanceOf(Map.class)
- && attrs.has(context.getKeyword(SchemaKeyword.TAG_TYPE))
- && attrs.get(context.getKeyword(SchemaKeyword.TAG_TYPE)).isTextual()
- && attrs.get(context.getKeyword(SchemaKeyword.TAG_TYPE)).textValue().equals(context.getKeyword(SchemaKeyword.TAG_TYPE_OBJECT)))
- ) {
+ if (shouldReceiveTitle(attrs, scope, context)) {
// Code found here: http://stackoverflow.com/questions/2559759/how-do-i-convert-camelcase-into-human-readable-names-in-java
String title = scope.getType().getErasedType().getSimpleName().replaceAll(
String.format("%s|%s|%s",
@@ -563,46 +553,71 @@ public class JSONSchemaUtil {
public void resetAfterSchemaGenerationFinished() {
this.rootType.remove();
}
+
+ private boolean shouldReceiveTitle(ObjectNode attrs, TypeScope scope, SchemaGenerationContext context) {
+ ResolvedType type = scope.getType(); Class<?> erasedType = type.getErasedType();
+ if (attrs.has(context.getKeyword(SchemaKeyword.TAG_TITLE))
+ || (type.isInstanceOf(Map.class) && !erasedType.getPackageName().startsWith("org.openremote.model"))
+ || erasedType.isAnnotationPresent(JsonSchemaTitle.class)
+ ) {
+ return false;
+ }
+ if (this.rootType.get() == type) {
+ return true;
+ }
+ boolean isObject = attrs.has(context.getKeyword(SchemaKeyword.TAG_TYPE))
+ && attrs.get(context.getKeyword(SchemaKeyword.TAG_TYPE)).isTextual()
+ && attrs.get(context.getKeyword(SchemaKeyword.TAG_TYPE)).textValue().equals(context.getKeyword(SchemaKeyword.TAG_TYPE_OBJECT));
+ return isObject || attrs.has(context.getKeyword(SchemaKeyword.TAG_ONEOF));
+ }
+ }
+
+ private JsonTypeInfo resolveTypeInfoAnnotation(Class<?> type) {
+ JsonTypeInfo annotation = null;
+
+ while (annotation == null && type.getSuperclass() != Object.class) {
+ type = type.getSuperclass();
+
+ if (type == null) return annotation;
+
+ annotation = type.getAnnotation(JsonTypeInfo.class);
+ }
+
+ return annotation;
}
/**
- * Find and modify the main subtype object under the {@code allOf} keyword of a subtype to add a {@code default}
- * property alongside the {@code const} discriminator property.
+ * Find and modify the main subtype object of a subtype to add the {@code const} discriminator property.
* @param attrs The {@link ObjectNode} representation of the subtype
* @param context The schema generator {@link SchemaGenerationContext}
*/
- private void addDefaultToDiscriminator(ObjectNode attrs, SchemaGenerationContext context, String customTypeKey) {
+ private void normalizeDiscriminator(ObjectNode attrs, Class<?> type, SchemaGenerationContext context, JsonTypeInfo annotation) {
+ if (annotation == null) return;
+
+ // If EXTERNAL_PROPERTY specified, manually add 'const', 'default' and 'required' properties
+ if (annotation.include() == JsonTypeInfo.As.EXTERNAL_PROPERTY) {
+ attrs.withArray(context.getKeyword(SchemaKeyword.TAG_REQUIRED))
+ .add(context.getKeyword(SchemaKeyword.TAG_TYPE));
+ attrs.withObject(context.getKeyword(SchemaKeyword.TAG_PROPERTIES))
+ .withObject(context.getKeyword(SchemaKeyword.TAG_TYPE))
+ .put(context.getKeyword(SchemaKeyword.TAG_CONST), type.getSimpleName());
+ return;
+ }
+
String typeKey = context.getKeyword(SchemaKeyword.TAG_TYPE);
+ String customTypeKey = annotation.property();
JsonNode allOfNode = attrs.get(context.getKeyword(SchemaKeyword.TAG_ALLOF));
- if (!(allOfNode instanceof ArrayNode allOf)) {
+ if (!(allOfNode instanceof ArrayNode)) {
JsonNode props = attrs.get(context.getKeyword(SchemaKeyword.TAG_PROPERTIES));
+ if (attrs.has(typeKey)) {
+ attrs.remove(typeKey);
+ }
if (props instanceof ObjectNode propsObj) {
- // Remove type property on type property for subtypes to enable definition merging
+ // Remove the type property on the type property for subtypes to enable definition merging
propsObj.remove(typeKey);
- }
- return;
- }
-
- for (JsonNode node : allOf) {
- JsonNode props = node.get(context.getKeyword(SchemaKeyword.TAG_PROPERTIES));
- if (!(props instanceof ObjectNode propsObj)) {
- continue;
- }
-
- // Add property indicating the custom discriminator property name
- if (customTypeKey != null && !customTypeKey.equals(typeKey)) {
- attrs.putObject("discriminator").put("propertyName", customTypeKey);
- typeKey = customTypeKey;
- }
-
- JsonNode typeNode = propsObj.get(typeKey);
- if (typeNode instanceof ObjectNode typeProp) {
-
- String constKey = context.getKeyword(SchemaKeyword.TAG_CONST);
- String defaultKey = context.getKeyword(SchemaKeyword.TAG_DEFAULT);
- if (typeProp.has(constKey) && !typeProp.has(defaultKey)) {
- typeProp.put(defaultKey, typeProp.get(constKey).asText());
- }
+ // If the custom type property is already present on the abstract class, the generator creates a
+ // duplicate which needs to be removed.
+ propsObj.remove(customTypeKey);
}
}
}
diff --git a/model/src/test/java/org/openremote/model/util/JSONSchemaUtilTest.java b/model/src/test/java/org/openremote/model/util/JSONSchemaUtilTest.java
index 494f68192..90c7260a3 100644
--- a/model/src/test/java/org/openremote/model/util/JSONSchemaUtilTest.java
+++ b/model/src/test/java/org/openremote/model/util/JSONSchemaUtilTest.java
@@ -13,6 +13,7 @@ import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import org.openremote.model.util.JSONSchemaUtil.*;
+import org.reflections.Reflections;
import java.io.IOException;
import java.io.InputStream;
@@ -21,10 +22,13 @@ import java.time.*;
import java.util.Date;
import java.util.Map;
+import static org.junit.jupiter.api.Assertions.*;
import static org.skyscreamer.jsonassert.JSONAssert.assertEquals;
public class JSONSchemaUtilTest {
+ private static final Reflections reflections = new Reflections("org.openremote");
+
@BeforeAll
static void setup() {
ValueUtil.doInitialise();
@@ -214,7 +218,7 @@ public class JSONSchemaUtilTest {
"$schema": "http://json-schema.org/draft-07/schema#",
"type": "object",
"properties": {
- "test1": { "type": "boolean" },
+ "test1": { "type": "boolean", "default": false },
"test2": { "type": "integer" },
"test3": { "type": "integer" },
"test4": { "type": "number" },
@@ -314,7 +318,6 @@ public class JSONSchemaUtilTest {
{
"$schema": "http://json-schema.org/draft-07/schema#",
"type": "object",
- "title": "I 18n Annotations",
"i18n": "org.openremote.model.util.JSONSchemaUtilTest.I18nAnnotations",
"additionalProperties": true
}"""
@@ -345,19 +348,19 @@ public class JSONSchemaUtilTest {
assertEquals(expected.toString(), actual.toString(), true);
}
- @JsonTypeInfo(property = "type", use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.EXISTING_PROPERTY)
+ @JsonTypeInfo(property = "type", use = JsonTypeInfo.Id.NAME)
@JsonSubTypes({
@JsonSubTypes.Type(SubType.class),
@JsonSubTypes.Type(SubTypeSuperclass.class),
})
- abstract static class PolymorphicType<T extends PolymorphicType<?>> implements Serializable {}
+ abstract static class PolymorphicType<T extends PolymorphicType<?>> implements Serializable { }
@JsonTypeName("SubType")
- static class SubType extends PolymorphicType<SubType> {}
+ static class SubType extends PolymorphicType<SubType> { }
@JsonTypeName("SubTypeSuperclass")
static class SubTypeSuperclass extends SubType { }
@Test
- public void shouldHaveSubtypesWithDefaultTypeProperty() throws JsonProcessingException, JSONException {
+ public void shouldHaveSubtypesWithTypeProperty() throws JsonProcessingException, JSONException {
JsonNode expected = ValueUtil.JSON.readTree("""
{
"$schema": "http://json-schema.org/draft-07/schema#",
@@ -368,8 +371,7 @@ public class JSONSchemaUtilTest {
"additionalProperties": true,
"properties": {
"type": {
- "const": "SubType",
- "default": "SubType"
+ "const": "SubType"
}
},
"required": [
@@ -382,8 +384,7 @@ public class JSONSchemaUtilTest {
"additionalProperties": true,
"properties": {
"type": {
- "const": "SubTypeSuperclass",
- "default": "SubTypeSuperclass"
+ "const": "SubTypeSuperclass"
}
},
"required": [
@@ -391,6 +392,9 @@ public class JSONSchemaUtilTest {
]
}
},
+ "discriminator": {
+ "propertyName": "type"
+ },
"oneOf": [
{ "$ref": "#/definitions/SubType" },
{ "$ref": "#/definitions/SubTypeSuperclass" }
@@ -405,16 +409,16 @@ public class JSONSchemaUtilTest {
assertEquals(expected.toString(), actual.toString(), true);
}
- @JsonTypeInfo(property = "customType", use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.EXISTING_PROPERTY)
+ @JsonTypeInfo(property = "customType", use = JsonTypeInfo.Id.NAME)
@JsonSubTypes({
- @JsonSubTypes.Type(CustomSubType.class),
- @JsonSubTypes.Type(CustomSubTypeSuperclass.class),
+ @JsonSubTypes.Type(SubTypeWithCustomProperty.class),
+ @JsonSubTypes.Type(SubTypeSuperClassWithCustomProperty.class),
})
- abstract static class CustomPolymorphicType<T extends CustomPolymorphicType<?>> implements Serializable {}
- @JsonTypeName("SubType")
- static class CustomSubType extends CustomPolymorphicType<CustomSubType> {}
- @JsonTypeName("SubTypeSuperclass")
- static class CustomSubTypeSuperclass extends CustomSubType { }
+ abstract static class PolymorphicTypeWithCustomProperty<T extends PolymorphicTypeWithCustomProperty<?>> implements Serializable { }
+ @JsonTypeName("SubTypeWithCustomProperty")
+ static class SubTypeWithCustomProperty extends PolymorphicTypeWithCustomProperty<SubTypeWithCustomProperty> { }
+ @JsonTypeName("SubTypeSuperClassWithCustomProperty")
+ static class SubTypeSuperClassWithCustomProperty extends SubTypeWithCustomProperty { }
@Test
public void shouldHaveSubtypesWithCustomTypeProperty() throws JsonProcessingException, JSONException {
@@ -422,52 +426,121 @@ public class JSONSchemaUtilTest {
{
"$schema": "http://json-schema.org/draft-07/schema#",
"definitions": {
- "CustomSubType": {
- "title": "Custom Sub Type",
+ "SubTypeWithCustomProperty": {
+ "title": "Sub Type With Custom Property",
"type": "object",
"additionalProperties": true,
"properties": {
"customType": {
- "const": "SubType",
- "default": "SubType"
+ "const": "SubTypeWithCustomProperty"
}
},
"required": [
"customType"
- ],
- "discriminator": {
- "propertyName": "customType"
- }
+ ]
},
- "CustomSubTypeSuperclass": {
- "title": "Custom Sub Type Superclass",
+ "SubTypeSuperClassWithCustomProperty": {
+ "title": "Sub Type Super Class With Custom Property",
"type": "object",
"additionalProperties": true,
"properties": {
"customType": {
- "const": "SubTypeSuperclass",
- "default": "SubTypeSuperclass"
+ "const": "SubTypeSuperClassWithCustomProperty"
}
},
"required": [
"customType"
- ],
- "discriminator": {
- "propertyName": "customType"
- }
+ ]
+ }
+ },
+ "discriminator": {
+ "propertyName": "customType"
+ },
+ "oneOf": [
+ { "$ref": "#/definitions/SubTypeWithCustomProperty" },
+ { "$ref": "#/definitions/SubTypeSuperClassWithCustomProperty" }
+ ],
+ "type": "object",
+ "additionalProperties": true,
+ "title": "Polymorphic Type With Custom Property"
+ }"""
+ );
+
+ JsonNode actual = ValueUtil.getSchema(PolymorphicTypeWithCustomProperty.class);
+ assertEquals(expected.toString(), actual.toString(), true);
+ }
+
+ // Note: JsonTypeInfo.As.EXISTING_PROPERTY doesn't necessarily change the behavior mainly the
+ // "customType" property on the abstract class matters.
+ @JsonTypeInfo(property = PolymorphicTypeWithCustomExistingProperty.VALUE_KEY_CUSTOM_TYPE, use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.EXISTING_PROPERTY)
+ @JsonSubTypes({
+ @JsonSubTypes.Type(name=SubTypeWithCustomExistingProperty.SUB_CUSTOM_TYPE, value=SubTypeWithCustomExistingProperty.class),
+ @JsonSubTypes.Type(name=SubTypeSuperClassWithCustomExistingProperty.SUPER_CUSTOM_TYPE, value=SubTypeSuperClassWithCustomExistingProperty.class),
+ })
+ abstract static class PolymorphicTypeWithCustomExistingProperty<T extends PolymorphicTypeWithCustomExistingProperty<?>> implements Serializable {
+ public static final String VALUE_KEY_CUSTOM_TYPE = "customType";
+ @JsonProperty(VALUE_KEY_CUSTOM_TYPE)
+ protected String customType;
+ public String getCustomType() {
+ return customType;
+ }
+ }
+ @JsonTypeName(SubTypeWithCustomExistingProperty.SUB_CUSTOM_TYPE)
+ static class SubTypeWithCustomExistingProperty extends PolymorphicTypeWithCustomExistingProperty<SubTypeWithCustomExistingProperty> {
+ public static final String SUB_CUSTOM_TYPE = "sub";
+ }
+ @JsonTypeName(SubTypeSuperClassWithCustomExistingProperty.SUPER_CUSTOM_TYPE)
+ static class SubTypeSuperClassWithCustomExistingProperty extends SubTypeWithCustomExistingProperty {
+ public static final String SUPER_CUSTOM_TYPE = "super";
+ }
+
+ @Test
+ public void shouldHaveSubtypesWithExistingCustomTypeProperty() throws JsonProcessingException, JSONException {
+ JsonNode expected = ValueUtil.JSON.readTree("""
+ {
+ "$schema": "http://json-schema.org/draft-07/schema#",
+ "definitions": {
+ "SubTypeWithCustomExistingProperty": {
+ "title": "Sub Type With Custom Existing Property",
+ "type": "object",
+ "additionalProperties": true,
+ "properties": {
+ "customType": {
+ "const": "sub"
+ }
+ },
+ "required": [
+ "customType"
+ ]
+ },
+ "SubTypeSuperClassWithCustomExistingProperty": {
+ "title": "Sub Type Super Class With Custom Existing Property",
+ "type": "object",
+ "additionalProperties": true,
+ "properties": {
+ "customType": {
+ "const": "super"
+ }
+ },
+ "required": [
+ "customType"
+ ]
}
},
+ "discriminator": {
+ "propertyName": "customType"
+ },
"oneOf": [
- { "$ref": "#/definitions/CustomSubType" },
- { "$ref": "#/definitions/CustomSubTypeSuperclass" }
+ { "$ref": "#/definitions/SubTypeWithCustomExistingProperty" },
+ { "$ref": "#/definitions/SubTypeSuperClassWithCustomExistingProperty" }
],
"type": "object",
"additionalProperties": true,
- "title": "Custom Polymorphic Type"
+ "title": "Polymorphic Type With Custom Existing Property"
}"""
);
- JsonNode actual = ValueUtil.getSchema(CustomPolymorphicType.class);
+ JsonNode actual = ValueUtil.getSchema(PolymorphicTypeWithCustomExistingProperty.class);
assertEquals(expected.toString(), actual.toString(), true);
}
@@ -492,8 +565,7 @@ public class JSONSchemaUtilTest {
"additionalProperties": true,
"properties": {
"type": {
- "const": "ExternalSubType",
- "default": "ExternalSubType"
+ "const": "ExternalSubType"
}
},
"required": [
@@ -506,8 +578,7 @@ public class JSONSchemaUtilTest {
"additionalProperties": true,
"properties": {
"type": {
- "const": "ExternalSubTypeSuperclass",
- "default": "ExternalSubTypeSuperclass"
+ "const": "ExternalSubTypeSuperclass"
}
},
"required": [
@@ -515,18 +586,13 @@ public class JSONSchemaUtilTest {
]
}
},
+ "discriminator": {
+ "propertyName": "type"
+ },
"oneOf": [
{ "$ref": "#/definitions/ExternalSubType" },
{ "$ref": "#/definitions/ExternalSubTypeSuperclass" }
],
- "properties": {
- "type": {
- "enum": [
- "ExternalSubType",
- "ExternalSubTypeSuperclass"
- ]
- }
- },
"type": "object",
"additionalProperties": true,
"title": "External Polymorphic Type"
@@ -538,7 +604,7 @@ public class JSONSchemaUtilTest {
}
@JsonTypeName("ReflectedPolymorphicType")
- @JsonTypeInfo(property = "type", use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.EXISTING_PROPERTY)
+ @JsonTypeInfo(property = "type", use = JsonTypeInfo.Id.NAME)
abstract static class ReflectedPolymorphicType<T extends ReflectedPolymorphicType<?>> implements Serializable {}
@JsonTypeName("ResolvedSubType")
static class ResolvedSubType extends ReflectedPolymorphicType<ResolvedSubType> { }
@@ -555,8 +621,7 @@ public class JSONSchemaUtilTest {
"additionalProperties": true,
"properties": {
"type": {
- "const": "ResolvedSubType",
- "default": "ResolvedSubType"
+ "const": "ResolvedSubType"
}
},
"required": [
@@ -564,6 +629,9 @@ public class JSONSchemaUtilTest {
]
}
},
+ "discriminator": {
+ "propertyName": "type"
+ },
"title": "Reflected Polymorphic Type",
"oneOf": [
{ "$ref": "#/definitions/ResolvedSubType" }
@@ -585,6 +653,13 @@ public class JSONSchemaUtilTest {
assertEquals(expected.toString(), actual.toString(), true);
}
+ @Test
+ public void shouldNotHaveAllOf() {
+ for (Class<?> clazz : reflections.getTypesAnnotatedWith(JsonTypeInfo.class)) {
+ assertFalse(ValueUtil.getSchema(clazz).toString().contains("allOf"));
+ }
+ }
+
static class JavaTimeJacksonModule {
public Duration duration;
public LocalDateTime localDateTime;
diff --git a/ui/component/core/src/util.ts b/ui/component/core/src/util.ts
index c6490ec35..6dc3ae899 100644
--- a/ui/component/core/src/util.ts
+++ b/ui/component/core/src/util.ts
@@ -537,20 +537,20 @@ export function hasMetaItem(name: string | NameHolder, attribute: Attribute<any>
return false;
}
-export function isPrimitiveMetaItem(descriptor: ValueDescriptor | undefined): boolean {
- return !isComplexMetaItem(descriptor);
+export function isPrimitiveValueDescriptor(descriptor: ValueDescriptor | undefined): boolean {
+ return !isComplexValueDescriptor(descriptor);
}
-export function isComplexMetaItem(descriptor: ValueDescriptor | undefined): boolean {
+export function isComplexValueDescriptor(descriptor: ValueDescriptor | undefined): boolean {
return Boolean(descriptor?.jsonType === "object" || descriptor?.arrayDimensions && descriptor.arrayDimensions > 0);
}
export function getPrimitiveMetaItems(): MetaItemDescriptor[] {
- return AssetModelUtil.getMetaItemDescriptors().filter(m => isPrimitiveMetaItem(AssetModelUtil.getValueDescriptor(m.type)));
+ return AssetModelUtil.getMetaItemDescriptors().filter(m => isPrimitiveValueDescriptor(AssetModelUtil.getValueDescriptor(m.type)));
}
export function getComplexMetaItems(): MetaItemDescriptor[] {
- return AssetModelUtil.getMetaItemDescriptors().filter(m => isComplexMetaItem(AssetModelUtil.getValueDescriptor(m.type)));
+ return AssetModelUtil.getMetaItemDescriptors().filter(m => isComplexValueDescriptor(AssetModelUtil.getValueDescriptor(m.type)));
}
export function getAssetTypeLabel(type: string | AssetDescriptor | undefined): string {
diff --git a/ui/component/or-asset-viewer/src/or-edit-asset-panel.ts b/ui/component/or-asset-viewer/src/or-edit-asset-panel.ts
index 29e65d09c..daa3894a5 100644
--- a/ui/component/or-asset-viewer/src/or-edit-asset-panel.ts
+++ b/ui/component/or-asset-viewer/src/or-edit-asset-panel.ts
@@ -1,7 +1,16 @@
import {css, html, LitElement, PropertyValues, TemplateResult, unsafeCSS} from "lit";
import {until} from "lit/directives/until.js";
import {customElement, property, state} from "lit/decorators.js";
-import {InputType, OrMwcInput, OrInputChangedEvent, getValueHolderInputTemplateProvider, ValueInputProviderOptions, OrInputChangedEventDetail, ValueInputProvider} from "@openremote/or-mwc-components/or-mwc-input";
+import {
+ InputType,
+ OrMwcInput,
+ OrInputChangedEvent,
+ getValueHolderInputTemplateProvider,
+ ValueInputProviderOptions,
+ OrInputChangedEventDetail,
+ ValueInputProvider,
+ ValueInputProviderGenerator
+} from "@openremote/or-mwc-components/or-mwc-input";
import {i18next} from "@openremote/or-translate"
import {Asset, Attribute, NameValueHolder, AssetModelUtil, WellknownMetaItems} from "@openremote/model";
import { DefaultColor5, DefaultColor3, DefaultColor2, Util} from "@openremote/core";
diff --git a/ui/component/or-attribute-input/src/attribute-value-template-provider.ts b/ui/component/or-attribute-input/src/attribute-value-template-provider.ts
new file mode 100644
index 000000000..e69de29bb
diff --git a/ui/component/or-attribute-input/src/index.ts b/ui/component/or-attribute-input/src/index.ts
index f9725ad02..dc1f4b0d4 100644
--- a/ui/component/or-attribute-input/src/index.ts
+++ b/ui/component/or-attribute-input/src/index.ts
@@ -3,6 +3,7 @@ import {customElement, property} from "lit/decorators.js";
import {ifDefined} from "lit/directives/if-defined.js";
import {until} from "lit/directives/until.js";
import {createRef, Ref, ref} from 'lit/directives/ref.js';
+import {when} from 'lit/directives/when.js';
import { i18next, translate } from "@openremote/or-translate";
import {
Attribute,
@@ -36,8 +37,8 @@ import "@openremote/or-map";
import {geoJsonPointInputTemplateProvider} from "@openremote/or-map";
import "@openremote/or-json-forms";
import {ErrorObject, OrJSONForms, StandardRenderers} from "@openremote/or-json-forms";
-import {agentIdRendererRegistryEntry} from "./agent-link-json-forms-renderer";
-import {schedulerRendererRegistryEntry} from "./scheduler-renderer";
+import {agentIdRendererRegistryEntry} from "./renderers/agent-link";
+import {schedulerRendererRegistryEntry} from "./renderers/scheduler";
export class OrAttributeInputChangedEvent extends CustomEvent<OrAttributeInputChangedEventDetail> {
@@ -91,7 +92,7 @@ export function getAttributeInputWrapper(content: TemplateResult, value: any, lo
}
return html`
- <div id="wrapper" class="${buttonIcon || fullWidth ? "no-padding" : "right-padding"}">
+ <div id="wrapper" style="width: 100%" class="${buttonIcon || fullWidth ? "no-padding" : "right-padding"}">
${content}
<div id="scrim" class="${ifDefined(loading ? undefined : "hidden")}"><progress class="pure-material-progress-circular"></progress></div>
</div>
@@ -146,8 +147,8 @@ async function getSchema(valueDescriptor: ValueDescriptor) {
return promise;
}
-export const jsonFormsInputTemplateProvider: (fallback: ValueInputProvider) => ValueInputProviderGenerator = (fallback) => (assetDescriptor, valueHolder, valueHolderDescriptor, valueDescriptor, valueChangeNotifier, options) => {
- if (Util.isComplexMetaItem(valueDescriptor)) {
+export const jsonFormsInputTemplateProvider: (fallback: ValueInputProvider, clear?: boolean) => ValueInputProviderGenerator = (fallback, clear) => (assetDescriptor, valueHolder, valueHolderDescriptor, valueDescriptor, valueChangeNotifier, options) => {
+ if (Util.isComplexValueDescriptor(valueDescriptor)) {
const disabled = !!(options && options.disabled);
const readonly = !!(options && options.readonly);
const label = options.label;
@@ -164,13 +165,12 @@ export const jsonFormsInputTemplateProvider: (fallback: ValueInputProvider) => V
const onChanged = (dataAndErrors: {errors: ErrorObject[] | undefined, data: any}) => {
if (!initialised) {
return
- };
-
+ }
+
if (!Util.objectsEqual(dataAndErrors.data, prevValue)) {
prevValue = dataAndErrors.data;
- valueChangeNotifier({
- value: dataAndErrors.data
- });
+ const errors = !!dataAndErrors.errors?.length;
+ valueChangeNotifier({ value: dataAndErrors.data, errors });
}
};
@@ -203,11 +203,26 @@ export const jsonFormsInputTemplateProvider: (fallback: ValueInputProvider) => V
or-loading-wrapper {
width: 100%;
}
+ or-json-forms {
+ max-width: 100%;
+ min-width: 0; /* Allows the element to shrink */
+ }
+ #clear {
+ width: unset !important;
+ }
</style>
<or-loading-wrapper ${ref(loadingWrapper)} .loading="${true}">
+ <div style="display: flex; width: 100%">
<or-json-forms .renderers="${jsonFormsAttributeRenderers}" ${ref(jsonForms)}
.disabled="${disabled}" .readonly="${readonly}" .label="${label}"
- .schema="${schema}" .uischema="${uiSchema}" .onChange="${onChanged}"></or-json-forms>
+ .schema="${schema}" .uischema="${uiSchema}" .onChange="${onChanged}">
+ </or-json-forms>
+ ${when(clear, () => html`
+ <or-mwc-input id="clear" outlined .type="${InputType.BUTTON}" icon="backspace" @or-mwc-input-changed="${
+ () => valueChangeNotifier({ value: null })
+ }"></or-mwc-input>
+ `)}
+ </div>
</or-loading-wrapper>
`;
};
@@ -273,6 +288,7 @@ export class OrAttributeInput extends subscribe(manager)(translate(i18next)(LitE
display: flex;
flex: 1;
flex-direction: column;
+ max-width: 100%;
}
#wrapper-input {
@@ -555,7 +571,8 @@ export class OrAttributeInput extends subscribe(manager)(translate(i18next)(LitE
// Use json forms with fallback to simple input provider
- const valueChangeHandler = (detail: OrInputChangedEventDetail | undefined) => {
+ const valueChangeHandler = (detail: OrInputChangedEventDetail & { errors?: boolean } | undefined) => {
+ if (detail?.errors) return;
const value = detail ? detail.value : undefined;
const updateImmediately = (detail && detail.enterPressed) || !this._templateProvider || !this.showButton || !this._templateProvider.supportsSendButton;
this._onInputValueChanged(value, updateImmediately);
@@ -573,7 +590,7 @@ export class OrAttributeInput extends subscribe(manager)(translate(i18next)(LitE
}
const standardInputProvider = getValueHolderInputTemplateProvider(this.assetType, this.attribute, this._attributeDescriptor, valueDescriptor, (detail) => valueChangeHandler(detail), options);
- this._templateProvider = jsonFormsInputTemplateProvider(standardInputProvider)(this.assetType, this.attribute, this._attributeDescriptor, valueDescriptor, (detail) => valueChangeHandler(detail), options);
+ this._templateProvider = jsonFormsInputTemplateProvider(standardInputProvider, true)(this.assetType, this.attribute, this._attributeDescriptor, valueDescriptor, (detail) => valueChangeHandler(detail), options);
if (!this._templateProvider) {
this._templateProvider = standardInputProvider;
diff --git a/ui/component/or-attribute-input/src/agent-link-json-forms-renderer.ts b/ui/component/or-attribute-input/src/renderers/agent-link.ts
similarity index 95%
rename from ui/component/or-attribute-input/src/agent-link-json-forms-renderer.ts
rename to ui/component/or-attribute-input/src/renderers/agent-link.ts
index 3a0693bf3..fad268880 100644
--- a/ui/component/or-attribute-input/src/agent-link-json-forms-renderer.ts
+++ b/ui/component/or-attribute-input/src/renderers/agent-link.ts
@@ -98,9 +98,8 @@ const agentIdRenderer = (state: JsonFormsStateContext, props: ControlProps) => {
const newAgentDescriptor = AssetModelUtil.getAssetDescriptor(agent.type) as AgentDescriptor;
if (newAgentDescriptor) {
props.handleChange("", {
- id: agent.id,
- type: newAgentDescriptor.agentLinkType,
- ...(props.rootSchema?.definitions?.[newAgentDescriptor.agentLinkType ?? ""].default ?? {}),
+ id: agent.id,
+ type: newAgentDescriptor.agentLinkType,
});
}
}
diff --git a/ui/component/or-attribute-input/src/scheduler-renderer.ts b/ui/component/or-attribute-input/src/renderers/scheduler.ts
similarity index 100%
rename from ui/component/or-attribute-input/src/scheduler-renderer.ts
rename to ui/component/or-attribute-input/src/renderers/scheduler.ts
diff --git a/ui/component/or-components/src/or-collapsible-panel.ts b/ui/component/or-components/src/or-collapsible-panel.ts
index 0373fe8a6..c5d726bc7 100644
--- a/ui/component/or-components/src/or-collapsible-panel.ts
+++ b/ui/component/or-components/src/or-collapsible-panel.ts
@@ -52,7 +52,7 @@ const style = css`
font-size: 15px;
font-weight: 400;
align-items: center;
- padding: 0 24px 0 16px;
+ padding: 0 16px 0 16px;
border-radius: inherit;
}
@@ -73,6 +73,11 @@ const style = css`
display: flex;
flex-direction: row;
overflow: hidden;
+ min-width: 0; /* Allows the element to shrink */
+ }
+
+ #header-title {
+ min-width: 0; /* Allows the element to shrink */
}
#header-title, #header-description {
diff --git a/ui/component/or-components/src/or-loading-wrapper.ts b/ui/component/or-components/src/or-loading-wrapper.ts
index f7068f785..431d6341b 100644
--- a/ui/component/or-components/src/or-loading-wrapper.ts
+++ b/ui/component/or-components/src/or-loading-wrapper.ts
@@ -46,6 +46,10 @@ export class OrLoadingWrapper extends LitElement {
width: 100%;
height: 100%;
}
+
+ #content-wrapper {
+ display: flex;
+ }
`;
}
diff --git a/ui/component/or-json-forms/README.md b/ui/component/or-json-forms/README.md
index 520e8fc9e..afc14792e 100644
--- a/ui/component/or-json-forms/README.md
+++ b/ui/component/or-json-forms/README.md
@@ -1,114 +1,127 @@
-# @openremote/or-map \<or-map\>
+# @openremote/or-json-forms \<or-json-forms\>
[![NPM Version][npm-image]][npm-url]
[![Linux Build][travis-image]][travis-url]
[![Test Coverage][coveralls-image]][coveralls-url]
-Web Component for displaying a Mapbox map; either raster or vector (default). This component requires an OpenRemote
-Manager to retrieve map settings and tiles.
+Web Component for generating forms based on JSON Schema. This can be useful for creating forms for complex data structures and validating user input.
+
+This component expects the JSON Schemas to be formatted as described in [Usage](#usage).
## Install
```bash
-npm i @openremote/or-map
-yarn add @openremote/or-map
+npm i @openremote/or-json-forms
+yarn add @openremote/or-json-forms
```
## Usage
-For a full list of properties, methods and options refer to the TypeDoc generated [documentation]().
+<!--For a full list of properties, methods and options refer to the TypeDoc generated [documentation]().-->
-```$html
-<or-map center="5.454250, 51.445990" zoom="5" style="height: 500px; width: 100%;" />
-```
+The JSON Forms expects [Draft-07](http://json-schema.org/draft-07) schemas.
-For a raster map (raster tile serving in the OpenRemote Manager must be properly configured):
+### Unsupported keywords
-```$html
-<or-map type="RASTER" center="5.454250, 51.445990" zoom="5" style="height: 500px; width: 100%;" />
-```
+The following keywords are not (fully) supported:
-The center and zoom are optional overrides for the defaults that will be defined in the `mapsettings` loaded from the
-OpenRemote Manager; each realm can have different `mapsettings` with a fallback to the default.
+- `anyOf`: ???
+- `allOf`: ???
+- `$ref`: will only resolve the reference if it is in the schema.
+- `examples`: planned
-Markers can be added via markup as children:
+### Behavior Specification
-```$html
-<or-map id="vectorMap" center="5.454250, 51.445990" zoom="5" style="height: 500px; width: 100%;">
- <or-map-marker id="demo-marker" lng="5.454250" class="marker" icon="or:logo-plain"></or-map-marker>
-</or-map>
-```
+- `{ "type": "string" }` - Displays a text input field.
+- `{ "type": "number" }` - Displays a number input field.
+- `{ "type": "integer" }` - Displays a number input field.
+- `{ "type": "array" }` - Displays a wrapper with a button to add items.
+- `{ "type": "object" }` - Displays a wrapper with a button to add properties.
-Or programmatically:
+#### Renderers & Testers
-```$typescript
-const vectorMap = docuemnt.getElementById("vectorMap");
-const assetMarker = document.createElement("or-map-marker-asset");
-assetMarker.setAttribute("asset", apartment1.id!);
-vectorMap.appendChild(assetMarker);
-```
+<!--#### Polymorphism
+
+<!--'oneOf', 'anyOf', 'allOf'-->-->
+
+#### Default values
+
+The JSON Forms will resolve default values from the schema based on the `default` property or infer it from the type.
-There are two types of built in markers:
+It derives the type from the schema's `type` property, or from properties that are characteristic of the type.
-### \<or-map-marker\>
-This is a basic marker and the base class for any other markers and it has the following attributes:
+| property | type |
+| ----------------------- | ------------------ |
+| `type` | The specified type |
+| `properties` | object |
+| `additionalProperties` | object |
+| `items` | array |
-* lat*
-* lng*
-* visible (show/hide the marker)
-* icon (uses `or-icon` to render an icon inside the default marker)
-* interactive (sets pointer events for the marker)
+<!--CombinatorKeyword[] = ['oneOf', 'anyOf', 'allOf']-->
-*required
+<!-- See `doCreateDefaultValue` in node_modules/@jsonforms/core/src/mappers/renderer.ts -->
-The visual content of the marker can be controlled by adding child content to the `or-map-marker` element; any child
-content is rendered inside a `div`. If no children are specified then the default marker will be used. Subclasses can
-override the `createMarkerContent()` method to control the look of the marker.
+Depending on the type, it derives the default value as follows:
-### \<or-map-marker-asset\>
-This links the marker to an Asset in the OpenRemote Manager by using the `asset-mixin` and adds the following attribute:
+| type | value | formats | Formatted default |
+| ----------------------- | ----- | ------- | ------- |
+| [...] (array of values) | [...] | | |
+| string | `""` | date-time, date, time | `new Date()` |
+| integer, number | `0` | | |
+| boolean | `false` | |
+| array | `[]` | |
+| object | An object with the required properties, otherwise an empty object | |
+| null | `null` | |
-* asset* (ID of the Asset to link)
+### Example usage
-*required
+```typescript
+import { html } from 'lit';
+import { ErrorObject, StandardRenderers } from "@openremote/or-json-forms";
+import "@openremote/or-json-forms";
+
+public class MyJsonForms extends LitElement {
+ private static schema = {
+ $schema: "http://json-schema.org/draft-07/schema#",
+ title: "MyObject",
+ type: "object",
+ properties: {
+ firstname: { type: "string" },
+ lastname: { type: "string" },
+ birthday: { type: "integer", minimum: 0 },
+ },
+ };
+ // Apply a custom UI schema to remove the outer VerticalLayout
+ private static uiSchema: any = { type: "Control", scope: "#" };
+
+ render() {
+ return html`<or-json-forms .renderers="${jsonFormsAttributeRenderers}" .schema="${schema}" .uischema="${uiSchema}" .onChange="${onChanged}"></or-json-forms>`
+ }
+
+ onChanged(dataAndErrors: { errors: ErrorObject[] | undefined, data: any }) {
+ // Do something with the data and errors
+ }
+};
+```
+
+### Custom renderers
-The Asset must be valid, accessible and must have a valid `location` attribute otherwise no marker will be shown. By
-default the `AssetType` is used to set the icon of the marker but this can be controlled by setting the `assetTypeAsIcon`
-property.
-
### Styling
All styling is done through CSS, the following CSS variables can be used:
-```$css
---or-map-marker-fill (default: #1D5632)
---or-map-marker-stroke (default: none)
---or-map-marker-width (default: 48px)
---or-map-marker-height (default: 48px)
---or-map-marker-transform (default: translate(-24px, -45px))
-
---or-map-marker-icon-fill (default: #FFF)
---or-map-marker-icon-stroke (default: none)
---or-map-marker-icon-width (default: 24px)
---or-map-marker-icon-height (default: 24px)
---or-map-marker-icon-transform (default: translate(-50%, -19px))
+```css
+--or-app-color3 /* Change text colors */
+--or-app-color4 /* Change border colors */
+--or-app-color5 /* Change border colors */
+--or-icon-fill
```
-### Events
-The following DOM events may be fired by the component and markers:
-
-* `click` - Standard click event is fired when the map itself is clicked
-* `OrMapMarkerEvent.CLICKED` - A map marker has been clicked; details contains the clicked `marker`
-* `OrMapMarkerEvent.CHANGED` - A map marker has been modified; details contains the changed `marker` and name of changed
-`property`
-
## Supported Browsers
-The last 2 versions of all modern browsers are supported, including Chrome, Safari, Opera, Firefox, Edge. In addition,
-Internet Explorer 11 is also supported.
-
+The last 2 versions of all modern browsers are supported, including Chrome, Safari, Opera, Firefox, Edge.
## License
[GNU AGPL](https://www.gnu.org/licenses/agpl-3.0.en.html)
[npm-image]: https://img.shields.io/npm/v/live-xxx.svg
-[npm-url]: https://npmjs.org/package/@openremote/or-map
+[npm-url]: https://npmjs.org/package/@openremote/or-json-forms
[travis-image]: https://img.shields.io/travis/live-js/live-xxx/master.svg
[travis-url]: https://travis-ci.org/live-js/live-xxx
[coveralls-image]: https://img.shields.io/coveralls/live-js/live-xxx/master.svg
-[coveralls-url]: https://coveralls.io/r/live-js/live-xxx?branch=master
\ No newline at end of file
+[coveralls-url]: https://coveralls.io/r/live-js/live-xxx?branch=master
diff --git a/ui/component/or-json-forms/src/controls/control-array-element.ts b/ui/component/or-json-forms/src/controls/control-array-element.ts
index ee08ef04b..de03bd2f2 100644
--- a/ui/component/or-json-forms/src/controls/control-array-element.ts
+++ b/ui/component/or-json-forms/src/controls/control-array-element.ts
@@ -77,6 +77,22 @@ const style = css`
.drag-container > button {
cursor: grab;
}
+
+ #content-wrapper {
+ overflow: auto;
+ }
+
+ [slot="header"] {
+ display: flex;
+ min-width: 0; /* Allows slotted element to shrink */
+ & span {
+ align-content: center;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ word-break: break-all;
+ }
+ }
`;
@customElement("or-json-forms-array-control")
@@ -142,7 +158,9 @@ export class ControlArrayElement extends ControlBaseElement {
const itemCount = Array.isArray(this.data) ? (this.data as []).length : 0;
const header = this.minimal ? `` : html`
- <span slot="header">${this.label ? computeLabel(this.label, this.required, false) : ""}</span>
+ <div slot="header">
+ <span>${this.label ? computeLabel(this.label, this.required, false) : ""}</span>
+ </div>
<div id="header-description" slot="header-description">
<div id="errors">
${!this.errors ? `` : html`<or-icon icon="alert"></or-icon><span>${this.errors}</span>`}
diff --git a/ui/component/or-json-forms/src/controls/control-input-element.ts b/ui/component/or-json-forms/src/controls/control-input-element.ts
index a0d447229..3137e0a40 100644
--- a/ui/component/or-json-forms/src/controls/control-input-element.ts
+++ b/ui/component/or-json-forms/src/controls/control-input-element.ts
@@ -60,10 +60,6 @@ export class ControlInputElement extends ControlBaseElement {
this.inputType = InputType.JSON;
} else if (isBooleanControl(uischema, schema, context)) {
this.inputType = InputType.CHECKBOX;
- if (typeof this.data !== "boolean") {
- this.data = Boolean(this.data);
- this.handleChange(this.path, this.data);
- }
} else if (isNumberControl(uischema, schema, context) || isIntegerControl(uischema, schema, context)) {
step = isNumberControl(uischema, schema, context) ? 0.1 : 1;
this.inputType = InputType.NUMBER;
diff --git a/ui/component/or-json-forms/src/index.ts b/ui/component/or-json-forms/src/index.ts
index 690c11fbf..464fd5463 100644
--- a/ui/component/or-json-forms/src/index.ts
+++ b/ui/component/or-json-forms/src/index.ts
@@ -121,6 +121,8 @@ export class OrJSONForms extends translate(i18next)(LitElement) implements OwnPr
}
if (!this.data) {
+ // AJV will not modify the root instance, only properties, thus we initialize with a default
+ // see https://ajv.js.org/guide/modifying-data.html#general-considerations
this.data = createDefaultValue(this.schema, this.schema);
}
@@ -129,13 +131,12 @@ export class OrJSONForms extends translate(i18next)(LitElement) implements OwnPr
}
if (!this.core) {
- this.core = {
- ajv: createAjv({useDefaults: true, validateFormats: false}),
- data: {},
- schema: this.schema!,
- uischema: this.uischema!
- };
- this.updateCore(Actions.init(this.data, this.schema, this.uischema));
+ const ajv = createAjv({
+ discriminator: true, // This is required for polymorphic types that contain defaults in their subtypes
+ useDefaults: true, // AJV will mutate the data adding missing properties that have a "default"
+ validateFormats: false
+ });
+ this.updateCore(Actions.init(this.data, this.schema, this.uischema, ajv));
this.config = configReducer(undefined, setConfig(this.config));
}
@@ -145,7 +146,6 @@ export class OrJSONForms extends translate(i18next)(LitElement) implements OwnPr
);
}
-
if (!this.contextValue
|| _changedProperties.has("core")
|| _changedProperties.has("renderers")
diff --git a/ui/component/or-json-forms/src/layouts/layout-vertical-element.ts b/ui/component/or-json-forms/src/layouts/layout-vertical-element.ts
index 5f8cdd73a..688a273b6 100644
--- a/ui/component/or-json-forms/src/layouts/layout-vertical-element.ts
+++ b/ui/component/or-json-forms/src/layouts/layout-vertical-element.ts
@@ -7,8 +7,6 @@ import {
isControl,
JsonSchema,
mapStateToControlProps,
- mapStateToControlWithDetailProps,
- mapStateToJsonFormsRendererProps,
OwnPropsOfControl,
OwnPropsOfRenderer,
Paths,
@@ -16,7 +14,7 @@ import {
StatePropsOfControl,
VerticalLayout
} from "@jsonforms/core";
-import {css, html, TemplateResult, unsafeCSS} from "lit";
+import {css, html, PropertyValues, TemplateResult} from "lit";
import {customElement, property} from "lit/decorators.js";
import {LayoutBaseElement} from "./layout-base-element";
import {
@@ -34,7 +32,6 @@ import "@openremote/or-mwc-components/or-mwc-list";
import "@openremote/or-components/or-collapsible-panel";
import {addItemOrParameterDialogStyle, baseStyle, panelStyle} from "../styles";
import {ListItem, OrMwcListChangedEvent} from "@openremote/or-mwc-components/or-mwc-list";
-import {DefaultColor5} from "@openremote/core";
import {AdditionalProps} from "../base-element";
// language=CSS
@@ -86,6 +83,22 @@ const style = css`
margin: 0;
flex: 1;
}
+
+ #content-wrapper {
+ overflow: auto;
+ }
+
+ [slot="header"] {
+ display: flex;
+ min-width: 0; /* Allows slotted element to shrink */
+ & span {
+ align-content: center;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ word-break: break-all;
+ }
+ }
`;
function isDynamic(schema: JsonSchema): boolean {
@@ -133,7 +146,7 @@ export class LayoutVerticalElement extends LayoutBaseElement<VerticalLayout | Gr
const header = this.minimal ? `` : html`
<div slot="header">
<span>${this.label ? computeLabel(this.label, this.required, false) : ""}</span>
- ${this.type ? html`<span id="type-label">${this.type}</span>` : ``}
+ ${this.type ? html`<span id="type-label" title="${this.type}">${this.type}</span>` : ``}
</div>
<div id="header-description" slot="header-description">
<div id="errors">
@@ -316,7 +329,7 @@ export class LayoutVerticalElement extends LayoutBaseElement<VerticalLayout | Gr
(dialog.shadowRoot!.getElementById("add-btn") as OrMwcInput).disabled = !selectedOneOf;
(dialog.shadowRoot!.getElementById("schema-description") as HTMLParagraphElement).innerHTML = (selectedOneOf ? selectedOneOf.description : i18next.t("schema.selectTypeMessage")) || i18next.t("schema.noDescriptionAvailable");
};
- schemaPicker = getSchemaPicker(rootSchema, selectedParameter.schema, selectedParameter.path, "oneOf", selectedParameter.label, handleChange);
+ schemaPicker = getSchemaPicker(rootSchema, selectedParameter.schema.oneOf, selectedParameter.label, handleChange);
}
return html`
diff --git a/ui/component/or-json-forms/src/standard-renderers.ts b/ui/component/or-json-forms/src/standard-renderers.ts
index ac51eafc4..4dca7002b 100644
--- a/ui/component/or-json-forms/src/standard-renderers.ts
+++ b/ui/component/or-json-forms/src/standard-renderers.ts
@@ -47,12 +47,10 @@ import {
getSchemaConst, getSchemaPicker,
getTemplateFromProps,
mapStateToCombinatorRendererProps,
- showJsonEditor
} from "./util";
import "./layouts/layout-vertical-element";
import "./controls/control-input-element";
import "./controls/control-array-element";
-import {InputType, OrInputChangedEvent} from "@openremote/or-mwc-components/or-mwc-input";
import {AdditionalProps} from "./base-element";
import {Util} from "@openremote/core";
@@ -100,7 +98,7 @@ export const verticalLayoutRenderer = (state: JsonFormsStateContext, props: OwnP
type: props.type
};
- const template = html`<or-json-forms-vertical-layout .state="${state}" .props="${contentProps}"></or-json-forms-vertical-layout>`;
+ const template = html`<or-json-forms-vertical-layout style="max-width: 100%" .state="${state}" .props="${contentProps}"></or-json-forms-vertical-layout>`;
let deleteHandler: undefined | (() => void);
if (!contentProps.required && contentProps.path) {
deleteHandler = () => {
@@ -209,7 +207,6 @@ export const anyOfOneOfControlTester: RankedTester = rankWith(
)
);
export const anyOfOneOfControlRenderer = (state: JsonFormsStateContext, props: ControlProps & AdditionalProps) => {
-
const jsonFormsContext = {jsonforms: {...state}};
const {
@@ -228,11 +225,11 @@ export const anyOfOneOfControlRenderer = (state: JsonFormsStateContext, props: C
} = mapStateToControlWithDetailProps(jsonFormsContext, props);
const keyword = schema.anyOf !== undefined ? "anyOf" : "oneOf";
- const resolvedSchema = resolveSchema(schema, keyword, rootSchema);
+ const resolvedSchema = resolveSchema(schema, keyword, rootSchema) as JsonSchema[];
const resolvedProps = mapStateToCombinatorRendererProps(jsonFormsContext, props, keyword);
const renderInfos = createCombinatorRenderInfos(
- resolvedSchema! as JsonSchema[],
+ resolvedSchema,
rootSchema,
keyword,
resolvedProps.uischema || uischema,
@@ -242,7 +239,7 @@ export const anyOfOneOfControlRenderer = (state: JsonFormsStateContext, props: C
if (data !== undefined && data !== null && (resolvedProps.indexOfFittingSchema === undefined || resolvedProps.indexOfFittingSchema < 0)) {
// Try and match the data using our own combinator info objects
- const combinatorInfos = getCombinatorInfos(resolvedSchema! as JsonSchema[], rootSchema);
+ const combinatorInfos = getCombinatorInfos(resolvedSchema, rootSchema);
const constProp = combinatorInfos.length > 0 ? combinatorInfos[0].constProperty : undefined;
if (constProp && typeof data === "object" && data[constProp]) {
@@ -254,25 +251,26 @@ export const anyOfOneOfControlRenderer = (state: JsonFormsStateContext, props: C
if (resolvedProps.indexOfFittingSchema === undefined || resolvedProps.indexOfFittingSchema < 0) {
const { handleChange } = mapDispatchToControlProps(state.dispatch);
- if (data !== undefined && data !== null) {
- // We have data that doesn't match a schema so show invalid template
- console.warn("Cannot match " + keyword + " schema to instance data");
+ // TODO: consider un-commenting when the AJV useDefaults option doesn't generate invalid schemas
+ // if (data != null) {
+ // // We have data that doesn't match a schema so show invalid template
+ // console.warn("Cannot match " + keyword + " schema to instance data");
- const showJson = (ev: Event) => {
- ev.stopPropagation();
+ // const showJson = (ev: Event) => {
+ // ev.stopPropagation();
- showJsonEditor(label, data, ((newValue) => {
- handleChange(path || "", newValue);
- }));
- };
+ // showJsonEditor(label, data, ((newValue) => {
+ // handleChange(path || "", newValue);
+ // }));
+ // };
- return html`
- <div class="item-container no-match-container"><span>${label}:</span><b><or-translate value="validation.noSchemaMatchFound"></b><or-mwc-input .type="${InputType.BUTTON}" outlined label="json" icon="pencil" @or-mwc-input-changed="${(ev: Event) => showJson(ev)}"></or-mwc-input></div>
- `;
- } else {
+ // return html`
+ // <div class="item-container no-match-container"><span>${label}:</span><b><or-translate value="validation.noSchemaMatchFound"></b><or-mwc-input .type="${InputType.BUTTON}" outlined label="json" icon="pencil" @or-mwc-input-changed="${(ev: Event) => showJson(ev)}"></or-mwc-input></div>
+ // `;
+ // } else {
// We have no data so show a schema picker
- return getSchemaPicker(rootSchema, resolvedSchema, path, keyword, props.label || label, (selectedSchema => handleChange(path, selectedSchema.defaultValueCreator())))
- }
+ return getSchemaPicker(rootSchema, resolvedSchema, props.label || label, (selectedSchema => handleChange(path, selectedSchema.defaultValueCreator())))
+ // }
}
// Return template for the anyOf/oneOf schema that matches the data
@@ -344,7 +342,7 @@ export const arrayControlRenderer = (state: JsonFormsStateContext, props: Contro
contentProps.required = !!props.required || contentProps.required;
contentProps.minimal = props.minimal;
- const template = html`<or-json-forms-array-control .state="${state}" .props="${contentProps}"></or-json-forms-array-control>`;
+ const template = html`<or-json-forms-array-control style="max-width: 100%" .state="${state}" .props="${contentProps}"></or-json-forms-array-control>`;
let deleteHandler: undefined | (() => void);
if (!contentProps.required && contentProps.path) {
deleteHandler = () => {
diff --git a/ui/component/or-json-forms/src/styles.ts b/ui/component/or-json-forms/src/styles.ts
index 4493f57a2..110104767 100644
--- a/ui/component/or-json-forms/src/styles.ts
+++ b/ui/component/or-json-forms/src/styles.ts
@@ -51,7 +51,6 @@ export const baseStyle = css`
.any-of-picker {
width: 100%;
- min-width: 200px;
}
#errors {
diff --git a/ui/component/or-json-forms/src/util.ts b/ui/component/or-json-forms/src/util.ts
index f1cbab368..554505005 100644
--- a/ui/component/or-json-forms/src/util.ts
+++ b/ui/component/or-json-forms/src/util.ts
@@ -2,7 +2,6 @@ import {
CombinatorKeyword,
composeWithUi,
ControlElement,
- ControlProps,
createDefaultValue,
deriveTypes,
getAjv,
@@ -28,10 +27,8 @@ import "@openremote/or-components/or-ace-editor";
import {OrAceEditor, OrAceEditorChangedEvent} from "@openremote/or-components/or-ace-editor";
import {html, TemplateResult, unsafeCSS} from "lit";
import {createRef, Ref, ref} from 'lit/directives/ref.js';
-import {ErrorObject} from "./index";
import {unknownTemplate} from "./standard-renderers";
import {OrMwcDialog, showDialog } from "@openremote/or-mwc-components/or-mwc-dialog";
-import {AdditionalProps} from "./base-element";
export function getTemplateFromProps<T extends OwnPropsOfRenderer>(state: JsonFormsSubStates | undefined, props: T | undefined): TemplateResult | undefined {
if (!state || !props) {
@@ -133,8 +130,8 @@ export function getSchemaConst(schema: JsonSchema): any {
}
}
-export function getSchemaPicker(rootSchema: JsonSchema, resolvedSchema: JsonSchema, path: string, keyword: "anyOf" | "oneOf", label: string, selectedCallback: (selectedSchema: CombinatorInfo) => void): TemplateResult {
- const combinatorInfos = getCombinatorInfos(resolvedSchema[keyword]!, rootSchema);
+export function getSchemaPicker(rootSchema: JsonSchema, resolvedSchemas: JsonSchema[], label: string, selectedCallback: (selectedSchema: CombinatorInfo) => void): TemplateResult {
+ const combinatorInfos = getCombinatorInfos(resolvedSchemas, rootSchema);
const options: [string, string][] = combinatorInfos.map((combinatorInfo, index) => [index+"", combinatorInfo.title || i18next.t("schema.title.indexedItem", {index: index})]);
const pickerUpdater = (index: number) => {
const matchedInfo = combinatorInfos[index];
@@ -196,7 +193,7 @@ const COMBINATOR_IDENTIFICATION_PROPERTY = "type";
export function getCombinatorIndexOfFittingSchema(
data: any,
keyword: CombinatorKeyword,
- schema: JsonSchema,
+ schema: JsonSchema & { discriminator?: { propertyName?: string } },
rootSchema: JsonSchema
): number {
if (typeof data !== 'object' || data === null) {
@@ -216,8 +213,8 @@ export function getCombinatorIndexOfFittingSchema(
// Check if the data matches the identification property of one of the resolved schemas
for (let i = 0; i < resolvedCombinatorSchemas.length; i++) {
- const resolvedSchema = resolvedCombinatorSchemas[i] as JsonSchema & { discriminator?: { propertyName?: string } };
- const combinatorIdentificationProperty = resolvedSchema?.discriminator?.propertyName || COMBINATOR_IDENTIFICATION_PROPERTY;
+ const resolvedSchema = resolvedCombinatorSchemas[i];
+ const combinatorIdentificationProperty = schema?.discriminator?.propertyName || COMBINATOR_IDENTIFICATION_PROPERTY;
// Match the identification property against a constant value in resolvedSchema
const maybeConstIdValue = resolvedSchema.properties?.[combinatorIdentificationProperty]?.const;
@@ -273,9 +270,7 @@ export function mapStateToCombinatorRendererProps(
rootSchema,
visible,
id,
- // Fall back to the first schema if none fits
- indexOfFittingSchema:
- indexOfFittingSchema !== -1 ? indexOfFittingSchema : 0,
+ indexOfFittingSchema,
uischemas: state.jsonforms.uischemas!,
uischema: uischema!,
};
diff --git a/ui/component/or-json-forms/test/fixtures/schemas.ts b/ui/component/or-json-forms/test/fixtures/schemas.ts
index cfed6209b..123673f52 100644
--- a/ui/component/or-json-forms/test/fixtures/schemas.ts
+++ b/ui/component/or-json-forms/test/fixtures/schemas.ts
@@ -94,6 +94,7 @@ export const schemas: JsonSchema[] = [
unresolvedBoolean: {
title: "Unresolved boolean",
type: "boolean",
+ default: false,
},
array: {
title: "Array",
@@ -116,33 +117,31 @@ export const schemas: JsonSchema[] = [
SubType: {
title: "Sub Type",
properties: {
- type: {
- const: "SubType",
- default: "SubType"
+ customType: {
+ const: "SubType"
},
},
required: [
- "type"
+ "customType"
],
},
CustomSubType: {
title: "Custom Sub Type",
properties: {
customType: {
- const: "CustomSubType",
- default: "CustomSubType"
+ const: "CustomSubType"
}
},
required: [
"customType"
- ],
- discriminator: {
- propertyName: "customType"
- }
+ ]
}
},
items: {
type: "object",
+ discriminator: {
+ propertyName: "customType"
+ },
oneOf: [
{ "$ref": "#/definitions/SubType" },
{ "$ref": "#/definitions/CustomSubType" },
diff --git a/ui/component/or-map/src/index.ts b/ui/component/or-map/src/index.ts
index b13876fd1..b508b9f30 100644
--- a/ui/component/or-map/src/index.ts
+++ b/ui/component/or-map/src/index.ts
@@ -260,8 +260,10 @@ export const geoJsonPointInputTemplateProvider: ValueInputProviderGenerator = (a
}
</style>
<div id="geo-json-point-input-compact-wrapper">
- <or-mwc-input style="width: auto;" .comfortable="${comfortable}" .type="${InputType.TEXT}" .value="${centerStr}" .pattern="${CoordinatesRegexPattern}" @keyup="${(e: KeyboardEvent) => getCoordinatesInputKeyHandler(valueChangeHandler)(e)}"></or-mwc-input>
- <or-mwc-input style="width: auto;" .type="${InputType.BUTTON}" compact icon="crosshairs-gps" @or-mwc-input-changed="${onClick}"></or-mwc-input>
+ <div style="display: flex">
+ <or-mwc-input .comfortable="${comfortable}" .type="${InputType.TEXT}" .value="${centerStr}" .pattern="${CoordinatesRegexPattern}" @keyup="${(e: KeyboardEvent) => getCoordinatesInputKeyHandler(valueChangeHandler)(e)}"></or-mwc-input>
+ <or-mwc-input style="width: unset" .type="${InputType.BUTTON}" compact icon="crosshairs-gps" @or-mwc-input-changed="${onClick}"></or-mwc-input>
+ </div>
</div>
`;
}
diff --git a/ui/component/or-mwc-components/src/or-mwc-input.ts b/ui/component/or-mwc-components/src/or-mwc-input.ts
index fb244068e..8e17c8e46 100644
--- a/ui/component/or-mwc-components/src/or-mwc-input.ts
+++ b/ui/component/or-mwc-components/src/or-mwc-input.ts
@@ -154,7 +154,7 @@ export interface ValueInputProvider {
export type ValueInputTemplateFunction = ((value: any, focused: boolean, loading: boolean, sending: boolean, error: boolean, helperText: string | undefined) => TemplateResult | PromiseLike<TemplateResult>) | undefined;
-export type ValueInputProviderGenerator = (assetDescriptor: AssetDescriptor | string, valueHolder: NameHolder & ValueHolder<any> | undefined, valueHolderDescriptor: ValueDescriptorHolder | undefined, valueDescriptor: ValueDescriptor, valueChangeNotifier: (value: OrInputChangedEventDetail | undefined) => void, options: ValueInputProviderOptions) => ValueInputProvider;
+export type ValueInputProviderGenerator = (assetDescriptor: AssetDescriptor | string, valueHolder: NameHolder & ValueHolder<any> | undefined, valueHolderDescriptor: ValueDescriptorHolder | undefined, valueDescriptor: ValueDescriptor, valueChangeNotifier: (value: OrInputChangedEventDetail & { errors?: boolean } | undefined) => void, options: ValueInputProviderOptions) => ValueInputProvider;
function inputTypeSupportsButton(inputType: InputType): boolean {
return inputType === InputType.NUMBER