diff options
Diffstat (limited to 'src/main/kotlin')
24 files changed, 385 insertions, 166 deletions
diff --git a/src/main/kotlin/pl/treksoft/kvision/core/Widget.kt b/src/main/kotlin/pl/treksoft/kvision/core/Widget.kt index 52f60813..9f28c52c 100644 --- a/src/main/kotlin/pl/treksoft/kvision/core/Widget.kt +++ b/src/main/kotlin/pl/treksoft/kvision/core/Widget.kt @@ -312,7 +312,7 @@ open class Widget(classes: Set<String> = setOf()) : StyledComponent() { afterPostpatch(v) } } - destroy = { _ -> + destroy = { afterDestroy() vnode = null vnode diff --git a/src/main/kotlin/pl/treksoft/kvision/data/DataContainer.kt b/src/main/kotlin/pl/treksoft/kvision/data/DataContainer.kt index 80a05ba7..d8b74c54 100644 --- a/src/main/kotlin/pl/treksoft/kvision/data/DataContainer.kt +++ b/src/main/kotlin/pl/treksoft/kvision/data/DataContainer.kt @@ -61,7 +61,7 @@ class DataContainer<M, C : Component>( init { container.parent = this - model.onUpdate += { _ -> + model.onUpdate += { update() } update() diff --git a/src/main/kotlin/pl/treksoft/kvision/dropdown/DropDown.kt b/src/main/kotlin/pl/treksoft/kvision/dropdown/DropDown.kt index 4ae1e93b..a521fe95 100644 --- a/src/main/kotlin/pl/treksoft/kvision/dropdown/DropDown.kt +++ b/src/main/kotlin/pl/treksoft/kvision/dropdown/DropDown.kt @@ -61,6 +61,7 @@ enum class DD(val option: String) { * @param withCaret determines if the dropdown button renders caret * @param classes a set of CSS class names */ +@Suppress("TooManyFunctions") open class DropDown( text: String, elements: List<StringPair>? = null, icon: String? = null, style: ButtonStyle = ButtonStyle.DEFAULT, disabled: Boolean = false, val forNavbar: Boolean = false, @@ -74,7 +75,7 @@ open class DropDown( set(value) { button.text = value } - private var elements by refreshOnUpdate(elements, { setChildrenFromElements() }) + private var elements by refreshOnUpdate(elements) { setChildrenFromElements() } /** * The icon of the dropdown button. */ @@ -207,18 +208,18 @@ open class DropDown( @Suppress("UnsafeCastFromDynamic") override fun afterInsert(node: VNode) { - this.getElementJQuery()?.on("show.bs.dropdown", { e, _ -> + this.getElementJQuery()?.on("show.bs.dropdown") { e, _ -> this.dispatchEvent("showBsDropdown", obj { detail = e }) - }) - this.getElementJQuery()?.on("shown.bs.dropdown", { e, _ -> + } + this.getElementJQuery()?.on("shown.bs.dropdown") { e, _ -> this.dispatchEvent("shownBsDropdown", obj { detail = e }) - }) - this.getElementJQuery()?.on("hide.bs.dropdown", { e, _ -> + } + this.getElementJQuery()?.on("hide.bs.dropdown") { e, _ -> this.dispatchEvent("hideBsDropdown", obj { detail = e }) - }) - this.getElementJQuery()?.on("hidden.bs.dropdown", { e, _ -> + } + this.getElementJQuery()?.on("hidden.bs.dropdown") { e, _ -> this.dispatchEvent("hiddenBsDropdown", obj { detail = e }) - }) + } } override fun getSnClass(): List<StringBoolPair> { diff --git a/src/main/kotlin/pl/treksoft/kvision/form/Form.kt b/src/main/kotlin/pl/treksoft/kvision/form/Form.kt index 19f7e68a..8f93c7ea 100644 --- a/src/main/kotlin/pl/treksoft/kvision/form/Form.kt +++ b/src/main/kotlin/pl/treksoft/kvision/form/Form.kt @@ -23,12 +23,15 @@ package pl.treksoft.kvision.form import kotlinx.serialization.KSerializer import kotlinx.serialization.Mapper +import kotlinx.serialization.context.MutableSerialContextImpl import kotlinx.serialization.decode -import kotlinx.serialization.json.JSON import kotlinx.serialization.serializer import pl.treksoft.kvision.i18n.I18n.trans -import pl.treksoft.kvision.types.KDate +import pl.treksoft.kvision.types.DateSerializer import pl.treksoft.kvision.types.KFile +import pl.treksoft.kvision.types.toStringF +import pl.treksoft.kvision.utils.JSON +import kotlin.js.Date import kotlin.js.Json import kotlin.reflect.KProperty1 @@ -84,8 +87,8 @@ class Form<K : Any>(private val panel: FormPanel<K>? = null, private val seriali modelFactory = { val map = it.flatMap { entry -> when (entry.value) { - is KDate -> { - listOf(entry.key to entry.value, "${entry.key}.time" to (entry.value as KDate).time) + is Date -> { + listOf(entry.key to (entry.value as? Date)?.toStringF()) } is List<*> -> { @Suppress("UNCHECKED_CAST") @@ -93,9 +96,9 @@ class Form<K : Any>(private val panel: FormPanel<K>? = null, private val seriali listOf(entry.key to entry.value, "${entry.key}.size" to list.size) + list.mapIndexed { index, kFile -> listOf( - "${entry.key}.${index}.name" to kFile.name, - "${entry.key}.${index}.size" to kFile.size, - "${entry.key}.${index}.content" to kFile.content + "${entry.key}.$index.name" to kFile.name, + "${entry.key}.$index.size" to kFile.size, + "${entry.key}.$index.content" to kFile.content ) }.flatten() } ?: listOf() @@ -104,6 +107,7 @@ class Form<K : Any>(private val panel: FormPanel<K>? = null, private val seriali } }.toMap() val mapper = Mapper.InNullableMapper(FormMapWrapper(map)) + mapper.context = MutableSerialContextImpl().apply { registerSerializer(Date::class, DateSerializer) } mapper.decode(serializer) } } @@ -182,8 +186,8 @@ class Form<K : Any>(private val panel: FormPanel<K>? = null, private val seriali * @param validator optional validation function * @return current form */ - fun <C : KDateFormControl> add( - key: KProperty1<K, KDate?>, control: C, required: Boolean = false, requiredMessage: String? = null, + fun <C : DateFormControl> add( + key: KProperty1<K, Date?>, control: C, required: Boolean = false, requiredMessage: String? = null, validatorMessage: ((C) -> String?)? = null, validator: ((C) -> Boolean?)? = null ): Form<K> { @@ -278,7 +282,7 @@ class Form<K : Any>(private val panel: FormPanel<K>? = null, private val seriali * @return data model as JSON */ fun getDataJson(): Json { - return kotlin.js.JSON.parse(JSON.stringify(serializer, getData())) + return kotlin.js.JSON.parse(JSON.plain.stringify(serializer, getData())) } /** diff --git a/src/main/kotlin/pl/treksoft/kvision/form/FormControl.kt b/src/main/kotlin/pl/treksoft/kvision/form/FormControl.kt index 6aff842a..6759fef9 100644 --- a/src/main/kotlin/pl/treksoft/kvision/form/FormControl.kt +++ b/src/main/kotlin/pl/treksoft/kvision/form/FormControl.kt @@ -22,8 +22,8 @@ package pl.treksoft.kvision.form import pl.treksoft.kvision.core.Component -import pl.treksoft.kvision.types.KDate import pl.treksoft.kvision.types.KFile +import kotlin.js.Date /** * Input controls sizes. @@ -190,15 +190,15 @@ interface BoolFormControl : FormControl { /** * Base interface of a form control with a date value. */ -interface KDateFormControl : FormControl { +interface DateFormControl : FormControl { /** * Date value. */ - var value: KDate? + var value: Date? - override fun getValue(): KDate? = value + override fun getValue(): Date? = value override fun setValue(v: Any?) { - value = v as? KDate + value = v as? Date } override fun getValueAsString(): String? = value?.toString() diff --git a/src/main/kotlin/pl/treksoft/kvision/form/FormPanel.kt b/src/main/kotlin/pl/treksoft/kvision/form/FormPanel.kt index 3811ed82..3533dee5 100644 --- a/src/main/kotlin/pl/treksoft/kvision/form/FormPanel.kt +++ b/src/main/kotlin/pl/treksoft/kvision/form/FormPanel.kt @@ -32,8 +32,8 @@ import pl.treksoft.kvision.form.check.Radio import pl.treksoft.kvision.html.TAG import pl.treksoft.kvision.html.Tag import pl.treksoft.kvision.panel.SimplePanel -import pl.treksoft.kvision.types.KDate import pl.treksoft.kvision.types.KFile +import kotlin.js.Date import kotlin.js.Json import kotlin.reflect.KProperty1 @@ -287,8 +287,8 @@ open class FormPanel<K : Any>( * @param validator optional validation function * @return current form panel */ - open fun <C : KDateFormControl> add( - key: KProperty1<K, KDate?>, control: C, required: Boolean = false, requiredMessage: String? = null, + open fun <C : DateFormControl> add( + key: KProperty1<K, Date?>, control: C, required: Boolean = false, requiredMessage: String? = null, validatorMessage: ((C) -> String?)? = null, validator: ((C) -> Boolean?)? = null ): FormPanel<K> { diff --git a/src/main/kotlin/pl/treksoft/kvision/form/check/CheckInput.kt b/src/main/kotlin/pl/treksoft/kvision/form/check/CheckInput.kt index f79c1b48..2df3a055 100644 --- a/src/main/kotlin/pl/treksoft/kvision/form/check/CheckInput.kt +++ b/src/main/kotlin/pl/treksoft/kvision/form/check/CheckInput.kt @@ -67,14 +67,14 @@ open class CheckInput( /** * The selection state of the input. */ - var value by refreshOnUpdate(value, { refreshState() }) + var value by refreshOnUpdate(value) { refreshState() } /** * The value attribute of the generated HTML input element. * * This value is placed directly in generated HTML code, while the [value] property is dynamically * bound to the input selection state. */ - var startValue by refreshOnUpdate(value, { this.value = it; refresh() }) + var startValue by refreshOnUpdate(value) { this.value = it; refresh() } /** * The type of the generated HTML input element. */ diff --git a/src/main/kotlin/pl/treksoft/kvision/form/check/RadioGroup.kt b/src/main/kotlin/pl/treksoft/kvision/form/check/RadioGroup.kt index fdc1e3af..e2f27c36 100644 --- a/src/main/kotlin/pl/treksoft/kvision/form/check/RadioGroup.kt +++ b/src/main/kotlin/pl/treksoft/kvision/form/check/RadioGroup.kt @@ -54,12 +54,12 @@ open class RadioGroup( /** * A list of options (label to value pairs) for the group. */ - var options by refreshOnUpdate(options, { setChildrenFromOptions() }) + var options by refreshOnUpdate(options) { setChildrenFromOptions() } /** * A value of the selected option. */ - override var value by refreshOnUpdate(value, { setValueToChildren(it) }) + override var value by refreshOnUpdate(value) { setValueToChildren(it) } /** * Determines if the options are rendered inline. diff --git a/src/main/kotlin/pl/treksoft/kvision/form/text/AbstractTextInput.kt b/src/main/kotlin/pl/treksoft/kvision/form/text/AbstractTextInput.kt index e41cfb8f..3a06f47b 100644 --- a/src/main/kotlin/pl/treksoft/kvision/form/text/AbstractTextInput.kt +++ b/src/main/kotlin/pl/treksoft/kvision/form/text/AbstractTextInput.kt @@ -51,14 +51,14 @@ abstract class AbstractTextInput( /** * Text input value. */ - var value by refreshOnUpdate(value, { refreshState() }) + var value by refreshOnUpdate(value) { refreshState() } /** * The value attribute of the generated HTML input element. * * This value is placed directly in generated HTML code, while the [value] property is dynamically * bound to the text input value. */ - var startValue by refreshOnUpdate(value, { this.value = it; refresh() }) + var startValue by refreshOnUpdate(value) { this.value = it; refresh() } /** * The placeholder for the text input. */ diff --git a/src/main/kotlin/pl/treksoft/kvision/html/Template.kt b/src/main/kotlin/pl/treksoft/kvision/html/Template.kt index 9a52eb5b..1f377406 100644 --- a/src/main/kotlin/pl/treksoft/kvision/html/Template.kt +++ b/src/main/kotlin/pl/treksoft/kvision/html/Template.kt @@ -47,6 +47,6 @@ interface Template { set(value) { if (!rich) rich = true templateDataObj = value - content = template?.invoke(value) ?: templates.get(I18n.language)?.invoke(value) + content = template?.invoke(value) ?: templates[I18n.language]?.invoke(value) } } diff --git a/src/main/kotlin/pl/treksoft/kvision/modal/Confirm.kt b/src/main/kotlin/pl/treksoft/kvision/modal/Confirm.kt index 693ecbaa..e16ca87e 100644 --- a/src/main/kotlin/pl/treksoft/kvision/modal/Confirm.kt +++ b/src/main/kotlin/pl/treksoft/kvision/modal/Confirm.kt @@ -78,7 +78,7 @@ open class Confirm( /** * Determines if Cancel button is visible. */ - var cancelVisible by refreshOnUpdate(cancelVisible, { refreshCancelButton() }) + var cancelVisible by refreshOnUpdate(cancelVisible) { refreshCancelButton() } /** * Yes button text. diff --git a/src/main/kotlin/pl/treksoft/kvision/modal/Dialog.kt b/src/main/kotlin/pl/treksoft/kvision/modal/Dialog.kt index d5695db3..e67a6f17 100644 --- a/src/main/kotlin/pl/treksoft/kvision/modal/Dialog.kt +++ b/src/main/kotlin/pl/treksoft/kvision/modal/Dialog.kt @@ -37,7 +37,6 @@ import kotlin.coroutines.resume * @param classes a set of CSS class names * @param init an initializer extension function */ -@Suppress("EXPERIMENTAL_FEATURE_WARNING") open class Dialog<R>( caption: String? = null, closeButton: Boolean = true, size: ModalSize? = null, animation: Boolean = true, escape: Boolean = true, diff --git a/src/main/kotlin/pl/treksoft/kvision/modal/Modal.kt b/src/main/kotlin/pl/treksoft/kvision/modal/Modal.kt index e09e9f7f..a0456e7e 100644 --- a/src/main/kotlin/pl/treksoft/kvision/modal/Modal.kt +++ b/src/main/kotlin/pl/treksoft/kvision/modal/Modal.kt @@ -218,20 +218,20 @@ open class Modal( keyboard = escape backdrop = if (escape) "true" else "static" }) - this.getElementJQuery()?.on("show.bs.modal", { e, _ -> + this.getElementJQuery()?.on("show.bs.modal") { e, _ -> this.dispatchEvent("showBsModal", obj { detail = e }) - }) - this.getElementJQuery()?.on("shown.bs.modal", { e, _ -> + } + this.getElementJQuery()?.on("shown.bs.modal") { e, _ -> this.dispatchEvent("shownBsModal", obj { detail = e }) - }) - this.getElementJQuery()?.on("hide.bs.modal", { e, _ -> + } + this.getElementJQuery()?.on("hide.bs.modal") { e, _ -> this.dispatchEvent("hideBsModal", obj { detail = e }) - }) - this.getElementJQuery()?.on("hidden.bs.modal", { e, _ -> + } + this.getElementJQuery()?.on("hidden.bs.modal") { e, _ -> this.visible = false hide() this.dispatchEvent("hiddenBsModal", obj { detail = e }) - }) + } } override fun hide(): Widget { diff --git a/src/main/kotlin/pl/treksoft/kvision/panel/FlexPanel.kt b/src/main/kotlin/pl/treksoft/kvision/panel/FlexPanel.kt index d22a285b..310d4d49 100644 --- a/src/main/kotlin/pl/treksoft/kvision/panel/FlexPanel.kt +++ b/src/main/kotlin/pl/treksoft/kvision/panel/FlexPanel.kt @@ -104,7 +104,7 @@ open class FlexPanel( /** * CSS flexbox direction. */ - var direction by refreshOnUpdate(direction, { refreshSpacing(); refresh() }) + var direction by refreshOnUpdate(direction) { refreshSpacing(); refresh() } /** * CSS flexbox wrap mode. */ @@ -124,7 +124,7 @@ open class FlexPanel( /** * The spacing between columns/rows. */ - var spacing by refreshOnUpdate(spacing, { refreshSpacing(); refresh() }) + var spacing by refreshOnUpdate(spacing) { refreshSpacing(); refresh() } init { @Suppress("LeakingThis") diff --git a/src/main/kotlin/pl/treksoft/kvision/panel/ResponsiveGridPanel.kt b/src/main/kotlin/pl/treksoft/kvision/panel/ResponsiveGridPanel.kt index edcf5789..7a5b07d6 100644 --- a/src/main/kotlin/pl/treksoft/kvision/panel/ResponsiveGridPanel.kt +++ b/src/main/kotlin/pl/treksoft/kvision/panel/ResponsiveGridPanel.kt @@ -62,7 +62,7 @@ open class ResponsiveGridPanel( /** * Text align of grid cells. */ - var align by refreshOnUpdate(align, { refreshRowContainers() }) + var align by refreshOnUpdate(align) { refreshRowContainers() } internal val map = mutableMapOf<Int, MutableMap<Int, WidgetParam>>() private var auto: Boolean = true @@ -86,7 +86,7 @@ open class ResponsiveGridPanel( val cCol = maxOf(col, 0) if (row > rows - 1) rows = cRow + 1 if (col > cols - 1) cols = cCol + 1 - map.getOrPut(cRow, { mutableMapOf() })[cCol] = WidgetParam(child, size, offset) + map.getOrPut(cRow) { mutableMapOf() }[cCol] = WidgetParam(child, size, offset) if (size > 0 || offset > 0) auto = false refreshRowContainers() return this diff --git a/src/main/kotlin/pl/treksoft/kvision/progress/ProgressIndicator.kt b/src/main/kotlin/pl/treksoft/kvision/progress/ProgressIndicator.kt index 479ad62e..256d15d7 100644 --- a/src/main/kotlin/pl/treksoft/kvision/progress/ProgressIndicator.kt +++ b/src/main/kotlin/pl/treksoft/kvision/progress/ProgressIndicator.kt @@ -67,15 +67,15 @@ internal class ProgressIndicator( /** * The current progress. */ - var progress by refreshOnUpdate(progress, { refreshWidth() }) + var progress by refreshOnUpdate(progress) { refreshWidth() } /** * The minimal progress. */ - var min by refreshOnUpdate(min, { refreshWidth() }) + var min by refreshOnUpdate(min) { refreshWidth() } /** * The maximal progress. */ - var max by refreshOnUpdate(max, { refreshWidth() }) + var max by refreshOnUpdate(max) { refreshWidth() } /** * The style of the progress indicator. */ diff --git a/src/main/kotlin/pl/treksoft/kvision/remote/CallAgent.kt b/src/main/kotlin/pl/treksoft/kvision/remote/CallAgent.kt index 4247b0b7..a48a6b1f 100644 --- a/src/main/kotlin/pl/treksoft/kvision/remote/CallAgent.kt +++ b/src/main/kotlin/pl/treksoft/kvision/remote/CallAgent.kt @@ -21,10 +21,10 @@ */ package pl.treksoft.kvision.remote -import kotlinx.serialization.json.JSON import pl.treksoft.jquery.JQueryAjaxSettings import pl.treksoft.jquery.JQueryXHR import pl.treksoft.jquery.jQuery +import pl.treksoft.kvision.utils.JSON import pl.treksoft.kvision.utils.obj import kotlin.js.Promise import kotlin.js.undefined @@ -56,8 +56,8 @@ open class CallAgent { method: RpcHttpMethod = RpcHttpMethod.POST ): Promise<String> { val jsonRpcRequest = JsonRpcRequest(counter++, url, data) - val jsonData = JSON.stringify(jsonRpcRequest) - return Promise({ resolve, reject -> + val jsonData = JSON.plain.stringify(jsonRpcRequest) + return Promise { resolve, reject -> jQuery.ajax(url, obj { this.contentType = "application/json" this.data = jsonData @@ -85,7 +85,7 @@ open class CallAgent { } } }) - }) + } } /** @@ -103,7 +103,7 @@ open class CallAgent { contentType: String = "application/json", beforeSend: ((JQueryXHR, JQueryAjaxSettings) -> Boolean)? = null ): Promise<dynamic> { - return Promise({ resolve, reject -> + return Promise { resolve, reject -> jQuery.ajax(url, obj { this.contentType = contentType this.data = data @@ -127,6 +127,6 @@ open class CallAgent { } this.beforeSend = beforeSend }) - }) + } } } diff --git a/src/main/kotlin/pl/treksoft/kvision/remote/RemoteAgent.kt b/src/main/kotlin/pl/treksoft/kvision/remote/RemoteAgent.kt index 25c20445..b4c8561e 100644 --- a/src/main/kotlin/pl/treksoft/kvision/remote/RemoteAgent.kt +++ b/src/main/kotlin/pl/treksoft/kvision/remote/RemoteAgent.kt @@ -24,25 +24,24 @@ package pl.treksoft.kvision.remote import kotlinx.coroutines.Deferred import kotlinx.coroutines.asDeferred import kotlinx.serialization.KSerializer -import kotlinx.serialization.internal.ArrayListSerializer -import kotlinx.serialization.internal.BooleanSerializer -import kotlinx.serialization.internal.CharSerializer -import kotlinx.serialization.internal.DoubleSerializer -import kotlinx.serialization.internal.LongSerializer -import kotlinx.serialization.internal.StringSerializer -import kotlinx.serialization.json.JSON +import kotlinx.serialization.internal.* import kotlinx.serialization.list import kotlinx.serialization.serializer -import kotlin.js.js +import pl.treksoft.kvision.types.DateSerializer +import pl.treksoft.kvision.types.toStringF +import pl.treksoft.kvision.utils.JSON +import kotlin.js.Date import kotlin.reflect.KClass import kotlin.js.JSON as NativeJSON -internal class NonStandardTypeException(type: String) : Exception("Non standard type: $type!") +internal class NotStandardTypeException(type: String) : Exception("Not a standard type: $type!") + +internal class NotEnumTypeException : Exception("Not the Enum type!") /** * Client side agent for JSON-RPC remote calls. */ -@Suppress("EXPERIMENTAL_FEATURE_WARNING", "LargeClass", "TooManyFunctions") +@Suppress("LargeClass", "TooManyFunctions") open class RemoteAgent<out T>(val serviceManager: ServiceManager<T>) { val callAgent = CallAgent() @@ -55,9 +54,15 @@ open class RemoteAgent<out T>(val serviceManager: ServiceManager<T>) { serviceManager.getCalls()[function.toString()] ?: throw IllegalStateException("Function not specified!") return callAgent.jsonRpcCall(url, method = method).then { try { + @Suppress("UNCHECKED_CAST") deserialize<RET>(it, RET::class.js.name) - } catch (t: NonStandardTypeException) { - JSON.nonstrict.parse(RET::class.serializer(), it) + } catch (t: NotStandardTypeException) { + try { + @Suppress("UNCHECKED_CAST") + tryDeserializeEnum(RET::class as KClass<Any>, it) as RET + } catch (t: NotEnumTypeException) { + JSON.nonstrict.parse(RET::class.serializer(), it) + } } }.asDeferred() } @@ -72,9 +77,14 @@ open class RemoteAgent<out T>(val serviceManager: ServiceManager<T>) { serviceManager.getCalls()[function.toString()] ?: throw IllegalStateException("Function not specified!") return callAgent.jsonRpcCall(url, method = method).then { try { - deserializeLists<RET>(it, RET::class.js.name) - } catch (t: NonStandardTypeException) { - JSON.nonstrict.parse(RET::class.serializer().list, it) + deserializeList<RET>(it, RET::class.js.name) + } catch (t: NotStandardTypeException) { + try { + @Suppress("UNCHECKED_CAST") + tryDeserializeEnumList(RET::class as KClass<Any>, it) as List<RET> + } catch (t: NotEnumTypeException) { + JSON.nonstrict.parse(RET::class.serializer().list, it) + } } }.asDeferred() } @@ -92,9 +102,14 @@ open class RemoteAgent<out T>(val serviceManager: ServiceManager<T>) { return callAgent.jsonRpcCall(url, listOf(data), method).then { try { @Suppress("UNCHECKED_CAST") - deserialize<RET>(it, (RET::class as KClass<Any>).js.name) - } catch (t: NonStandardTypeException) { - JSON.nonstrict.parse(RET::class.serializer(), it) + deserialize<RET>(it, RET::class.js.name) + } catch (t: NotStandardTypeException) { + try { + @Suppress("UNCHECKED_CAST") + tryDeserializeEnum(RET::class as KClass<Any>, it) as RET + } catch (t: NotEnumTypeException) { + JSON.nonstrict.parse(RET::class.serializer(), it) + } } }.asDeferred() } @@ -111,9 +126,14 @@ open class RemoteAgent<out T>(val serviceManager: ServiceManager<T>) { serviceManager.getCalls()[function.toString()] ?: throw IllegalStateException("Function not specified!") return callAgent.jsonRpcCall(url, listOf(data), method).then { try { - deserializeLists<RET>(it, RET::class.js.name) - } catch (t: NonStandardTypeException) { - JSON.nonstrict.parse(RET::class.serializer().list, it) + deserializeList<RET>(it, RET::class.js.name) + } catch (t: NotStandardTypeException) { + try { + @Suppress("UNCHECKED_CAST") + tryDeserializeEnumList(RET::class as KClass<Any>, it) as List<RET> + } catch (t: NotEnumTypeException) { + JSON.nonstrict.parse(RET::class.serializer().list, it) + } } }.asDeferred() } @@ -131,9 +151,15 @@ open class RemoteAgent<out T>(val serviceManager: ServiceManager<T>) { serviceManager.getCalls()[function.toString()] ?: throw IllegalStateException("Function not specified!") return callAgent.jsonRpcCall(url, listOf(data1, data2), method).then { try { + @Suppress("UNCHECKED_CAST") deserialize<RET>(it, RET::class.js.name) - } catch (t: NonStandardTypeException) { - JSON.nonstrict.parse(RET::class.serializer(), it) + } catch (t: NotStandardTypeException) { + try { + @Suppress("UNCHECKED_CAST") + tryDeserializeEnum(RET::class as KClass<Any>, it) as RET + } catch (t: NotEnumTypeException) { + JSON.nonstrict.parse(RET::class.serializer(), it) + } } }.asDeferred() } @@ -151,9 +177,14 @@ open class RemoteAgent<out T>(val serviceManager: ServiceManager<T>) { serviceManager.getCalls()[function.toString()] ?: throw IllegalStateException("Function not specified!") return callAgent.jsonRpcCall(url, listOf(data1, data2), method).then { try { - deserializeLists<RET>(it, RET::class.js.name) - } catch (t: NonStandardTypeException) { - JSON.nonstrict.parse(RET::class.serializer().list, it) + deserializeList<RET>(it, RET::class.js.name) + } catch (t: NotStandardTypeException) { + try { + @Suppress("UNCHECKED_CAST") + tryDeserializeEnumList(RET::class as KClass<Any>, it) as List<RET> + } catch (t: NotEnumTypeException) { + JSON.nonstrict.parse(RET::class.serializer().list, it) + } } }.asDeferred() } @@ -173,9 +204,15 @@ open class RemoteAgent<out T>(val serviceManager: ServiceManager<T>) { serviceManager.getCalls()[function.toString()] ?: throw IllegalStateException("Function not specified!") return callAgent.jsonRpcCall(url, listOf(data1, data2, data3), method).then { try { + @Suppress("UNCHECKED_CAST") deserialize<RET>(it, RET::class.js.name) - } catch (t: NonStandardTypeException) { - JSON.nonstrict.parse(RET::class.serializer(), it) + } catch (t: NotStandardTypeException) { + try { + @Suppress("UNCHECKED_CAST") + tryDeserializeEnum(RET::class as KClass<Any>, it) as RET + } catch (t: NotEnumTypeException) { + JSON.nonstrict.parse(RET::class.serializer(), it) + } } }.asDeferred() } @@ -195,9 +232,14 @@ open class RemoteAgent<out T>(val serviceManager: ServiceManager<T>) { serviceManager.getCalls()[function.toString()] ?: throw IllegalStateException("Function not specified!") return callAgent.jsonRpcCall(url, listOf(data1, data2, data3), method).then { try { - deserializeLists<RET>(it, RET::class.js.name) - } catch (t: NonStandardTypeException) { - JSON.nonstrict.parse(RET::class.serializer().list, it) + deserializeList<RET>(it, RET::class.js.name) + } catch (t: NotStandardTypeException) { + try { + @Suppress("UNCHECKED_CAST") + tryDeserializeEnumList(RET::class as KClass<Any>, it) as List<RET> + } catch (t: NotEnumTypeException) { + JSON.nonstrict.parse(RET::class.serializer().list, it) + } } }.asDeferred() } @@ -224,9 +266,15 @@ open class RemoteAgent<out T>(val serviceManager: ServiceManager<T>) { serviceManager.getCalls()[function.toString()] ?: throw IllegalStateException("Function not specified!") return callAgent.jsonRpcCall(url, listOf(data1, data2, data3, data4), method).then { try { + @Suppress("UNCHECKED_CAST") deserialize<RET>(it, RET::class.js.name) - } catch (t: NonStandardTypeException) { - JSON.nonstrict.parse(RET::class.serializer(), it) + } catch (t: NotStandardTypeException) { + try { + @Suppress("UNCHECKED_CAST") + tryDeserializeEnum(RET::class as KClass<Any>, it) as RET + } catch (t: NotEnumTypeException) { + JSON.nonstrict.parse(RET::class.serializer(), it) + } } }.asDeferred() } @@ -253,9 +301,14 @@ open class RemoteAgent<out T>(val serviceManager: ServiceManager<T>) { serviceManager.getCalls()[function.toString()] ?: throw IllegalStateException("Function not specified!") return callAgent.jsonRpcCall(url, listOf(data1, data2, data3, data4), method).then { try { - deserializeLists<RET>(it, RET::class.js.name) - } catch (t: NonStandardTypeException) { - JSON.nonstrict.parse(RET::class.serializer().list, it) + deserializeList<RET>(it, RET::class.js.name) + } catch (t: NotStandardTypeException) { + try { + @Suppress("UNCHECKED_CAST") + tryDeserializeEnumList(RET::class as KClass<Any>, it) as List<RET> + } catch (t: NotEnumTypeException) { + JSON.nonstrict.parse(RET::class.serializer().list, it) + } } }.asDeferred() } @@ -287,9 +340,15 @@ open class RemoteAgent<out T>(val serviceManager: ServiceManager<T>) { serviceManager.getCalls()[function.toString()] ?: throw IllegalStateException("Function not specified!") return callAgent.jsonRpcCall(url, listOf(data1, data2, data3, data4, data5), method).then { try { + @Suppress("UNCHECKED_CAST") deserialize<RET>(it, RET::class.js.name) - } catch (t: NonStandardTypeException) { - JSON.nonstrict.parse(RET::class.serializer(), it) + } catch (t: NotStandardTypeException) { + try { + @Suppress("UNCHECKED_CAST") + tryDeserializeEnum(RET::class as KClass<Any>, it) as RET + } catch (t: NotEnumTypeException) { + JSON.nonstrict.parse(RET::class.serializer(), it) + } } }.asDeferred() } @@ -321,9 +380,14 @@ open class RemoteAgent<out T>(val serviceManager: ServiceManager<T>) { serviceManager.getCalls()[function.toString()] ?: throw IllegalStateException("Function not specified!") return callAgent.jsonRpcCall(url, listOf(data1, data2, data3, data4, data5), method).then { try { - deserializeLists<RET>(it, RET::class.js.name) - } catch (t: NonStandardTypeException) { - JSON.nonstrict.parse(RET::class.serializer().list, it) + deserializeList<RET>(it, RET::class.js.name) + } catch (t: NotStandardTypeException) { + try { + @Suppress("UNCHECKED_CAST") + tryDeserializeEnumList(RET::class as KClass<Any>, it) as List<RET> + } catch (t: NotEnumTypeException) { + JSON.nonstrict.parse(RET::class.serializer().list, it) + } } }.asDeferred() } @@ -337,18 +401,81 @@ open class RemoteAgent<out T>(val serviceManager: ServiceManager<T>) { inline fun <reified PAR> serialize(value: PAR, serializer: KSerializer<PAR>?): String? { return value?.let { if (serializer != null) { - JSON.stringify(serializer, it) + JSON.plain.stringify(serializer, it) } else { - if (it is Enum<*>) { - "\"$it\"" - } else { - try { + @Suppress("UNCHECKED_CAST") + trySerialize((PAR::class as KClass<Any>), it as Any) + } + } + } + + /** + * @suppress + * Internal function + */ + @Suppress("ComplexMethod", "TooGenericExceptionCaught", "NestedBlockDepth") + fun trySerialize(kClass: KClass<Any>, value: Any): String { + return if (value is List<*>) { + if (value.size > 0) { + when { + value[0] is String -> + @Suppress("UNCHECKED_CAST") + JSON.plain.stringify(ArrayListSerializer(StringSerializer) as KSerializer<Any>, value) + value[0] is Date -> + @Suppress("UNCHECKED_CAST") + JSON.plain.stringify(ArrayListSerializer(DateSerializer) as KSerializer<Any>, value) + value[0] is Int -> + @Suppress("UNCHECKED_CAST") + JSON.plain.stringify(ArrayListSerializer(IntSerializer) as KSerializer<Any>, value) + value[0] is Long -> + @Suppress("UNCHECKED_CAST") + JSON.plain.stringify(ArrayListSerializer(LongSerializer) as KSerializer<Any>, value) + value[0] is Boolean -> @Suppress("UNCHECKED_CAST") - JSON.stringify((PAR::class as KClass<Any>).serializer(), it as Any) + JSON.plain.stringify(ArrayListSerializer(BooleanSerializer) as KSerializer<Any>, value) + value[0] is Float -> + @Suppress("UNCHECKED_CAST") + JSON.plain.stringify(ArrayListSerializer(FloatSerializer) as KSerializer<Any>, value) + value[0] is Double -> + @Suppress("UNCHECKED_CAST") + JSON.plain.stringify(ArrayListSerializer(DoubleSerializer) as KSerializer<Any>, value) + value[0] is Char -> + @Suppress("UNCHECKED_CAST") + JSON.plain.stringify(ArrayListSerializer(CharSerializer) as KSerializer<Any>, value) + value[0] is Short -> + @Suppress("UNCHECKED_CAST") + JSON.plain.stringify(ArrayListSerializer(ShortSerializer) as KSerializer<Any>, value) + value[0] is Byte -> + @Suppress("UNCHECKED_CAST") + JSON.plain.stringify(ArrayListSerializer(ByteSerializer) as KSerializer<Any>, value) + value[0] is Enum<*> -> "[" + value.joinToString(",") { "\"$it\"" } + "]" + else -> try { + @Suppress("UNCHECKED_CAST") + JSON.plain.stringify(ArrayListSerializer(kClass.serializer()) as KSerializer<Any>, value) } catch (e: Throwable) { - it.toString() + try { + @Suppress("UNCHECKED_CAST") + JSON.plain.stringify(ArrayListSerializer(StringSerializer) as KSerializer<Any>, value) + } catch (e: Throwable) { + value.toString() + } } } + } else { + "[]" + } + } else { + when (value) { + is Enum<*> -> "\"$value\"" + is String -> value + is Char -> "\"$value\"" + is Date -> "\"${value.toStringF()}\"" + else -> try { + @Suppress("UNCHECKED_CAST") + JSON.plain.stringify(kClass.serializer(), value) + } catch (e: Throwable) { + value.toString() + } } } } @@ -357,15 +484,37 @@ open class RemoteAgent<out T>(val serviceManager: ServiceManager<T>) { * @suppress * Internal function */ - @Suppress("UNCHECKED_CAST") - fun <RET> deserialize(value: String, type: String): RET { - return when (type) { - "String" -> JSON.parse(StringSerializer, value) as RET - "Number" -> JSON.parse(DoubleSerializer, value) as RET - "Long" -> JSON.parse(LongSerializer, value) as RET - "Boolean" -> JSON.parse(BooleanSerializer, value) as RET - "Char" -> JSON.parse(CharSerializer, value) as RET - else -> throw NonStandardTypeException(type) + @Suppress("UNCHECKED_CAST", "ComplexMethod") + fun <RET> deserialize(value: String, jsType: String): RET { + return when (jsType) { + "String" -> JSON.plain.parse(StringSerializer, value) as RET + "Number" -> JSON.plain.parse(DoubleSerializer, value) as RET + "Long" -> JSON.plain.parse(LongSerializer, value) as RET + "Boolean" -> JSON.plain.parse(BooleanSerializer, value) as RET + "BoxedChar" -> JSON.plain.parse(CharSerializer, value) as RET + "Short" -> JSON.plain.parse(ShortSerializer, value) as RET + "Date" -> JSON.plain.parse(DateSerializer, value) as RET + "Byte" -> JSON.plain.parse(ByteSerializer, value) as RET + else -> throw NotStandardTypeException(jsType) + } + } + + /** + * @suppress + * Internal function + */ + @Suppress("UNCHECKED_CAST", "ComplexMethod") + fun <RET> deserializeList(value: String, jsType: String): List<RET> { + return when (jsType) { + "String" -> JSON.plain.parse(ArrayListSerializer(StringSerializer), value) as List<RET> + "Number" -> JSON.plain.parse(ArrayListSerializer(DoubleSerializer), value) as List<RET> + "Long" -> JSON.plain.parse(ArrayListSerializer(LongSerializer), value) as List<RET> + "Boolean" -> JSON.plain.parse(ArrayListSerializer(BooleanSerializer), value) as List<RET> + "BoxedChar" -> JSON.plain.parse(ArrayListSerializer(CharSerializer), value) as List<RET> + "Short" -> JSON.plain.parse(ArrayListSerializer(ShortSerializer), value) as List<RET> + "Date" -> JSON.plain.parse(ArrayListSerializer(DateSerializer), value) as List<RET> + "Byte" -> JSON.plain.parse(ArrayListSerializer(ByteSerializer), value) as List<RET> + else -> throw NotStandardTypeException(jsType) } } @@ -373,15 +522,41 @@ open class RemoteAgent<out T>(val serviceManager: ServiceManager<T>) { * @suppress * Internal function */ - @Suppress("UNCHECKED_CAST") - fun <RET> deserializeLists(value: String, type: String): List<RET> { - return when (type) { - "String" -> JSON.parse(ArrayListSerializer(StringSerializer), value) as List<RET> - "Number" -> JSON.parse(ArrayListSerializer(DoubleSerializer), value) as List<RET> - "Long" -> JSON.parse(ArrayListSerializer(LongSerializer), value) as List<RET> - "Boolean" -> JSON.parse(ArrayListSerializer(BooleanSerializer), value) as List<RET> - "Char" -> JSON.parse(ArrayListSerializer(CharSerializer), value) as List<RET> - else -> throw NonStandardTypeException(type) + @Suppress("TooGenericExceptionCaught", "ThrowsCount") + fun tryDeserializeEnum(kClass: KClass<Any>, value: String): Any { + return try { + if (kClass.asDynamic().jClass.`$metadata$`.interfaces[0].name == "Enum") { + findEnumValue(kClass, JSON.plain.parse(StringSerializer, value)) ?: throw NotEnumTypeException() + } else { + throw NotEnumTypeException() + } + } catch (e: Throwable) { + throw NotEnumTypeException() + } + } + + /** + * @suppress + * Internal function + */ + @Suppress("TooGenericExceptionCaught", "ThrowsCount") + fun tryDeserializeEnumList(kClass: KClass<Any>, value: String): List<Any> { + return try { + if (kClass.asDynamic().jClass.`$metadata$`.interfaces[0].name == "Enum") { + JSON.plain.parse(ArrayListSerializer(StringSerializer), value).map { + findEnumValue(kClass, JSON.plain.parse(StringSerializer, it)) ?: throw NotEnumTypeException() + } + } else { + throw NotEnumTypeException() + } + } catch (e: Throwable) { + throw NotEnumTypeException() + } + } + + private fun findEnumValue(kClass: KClass<Any>, value: String): Any? { + return (kClass.asDynamic().jClass.values() as Array<Any>).find { + it.asDynamic().name == value } } } diff --git a/src/main/kotlin/pl/treksoft/kvision/remote/Security.kt b/src/main/kotlin/pl/treksoft/kvision/remote/Security.kt index 56141f5e..bf77a06b 100644 --- a/src/main/kotlin/pl/treksoft/kvision/remote/Security.kt +++ b/src/main/kotlin/pl/treksoft/kvision/remote/Security.kt @@ -61,7 +61,6 @@ class LoginService { /** * Pac4j form login dispatcher. */ -@Suppress("EXPERIMENTAL_FEATURE_WARNING") abstract class SecurityMgr { private var isLoggedIn = false diff --git a/src/main/kotlin/pl/treksoft/kvision/table/Table.kt b/src/main/kotlin/pl/treksoft/kvision/table/Table.kt index 1d44633d..f78d3f84 100644 --- a/src/main/kotlin/pl/treksoft/kvision/table/Table.kt +++ b/src/main/kotlin/pl/treksoft/kvision/table/Table.kt @@ -63,7 +63,7 @@ open class Table( /** * Table headers names. */ - var headerNames by refreshOnUpdate(headerNames, { refreshHeaders() }) + var headerNames by refreshOnUpdate(headerNames) { refreshHeaders() } /** * Table types. */ diff --git a/src/main/kotlin/pl/treksoft/kvision/types/Date.kt b/src/main/kotlin/pl/treksoft/kvision/types/Date.kt new file mode 100644 index 00000000..b6b60d5c --- /dev/null +++ b/src/main/kotlin/pl/treksoft/kvision/types/Date.kt @@ -0,0 +1,65 @@ +/* + * Copyright (c) 2017-present Robert Jaros + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +package pl.treksoft.kvision.types + +import kotlinx.serialization.Decoder +import kotlinx.serialization.Encoder +import kotlinx.serialization.KSerializer +import kotlinx.serialization.SerialDescriptor +import kotlinx.serialization.internal.SerialClassDescImpl +import pl.treksoft.kvision.KVManager +import kotlin.js.Date + +actual typealias Date = kotlin.js.Date + +/** + * Extension function to convert String to Date with a given date format. + * @param format date/time format + * @return Date object + */ +@Suppress("UnsafeCastFromDynamic") +actual fun String.toDateF(format: String): Date { + val result = KVManager.fecha.parse(this, format) + return if (result) result else Date() +} + +/** + * Extension function to convert Date to String with a given date format. + * @param format date/time format + * @return String object + */ +@Suppress("UnsafeCastFromDynamic") +actual fun Date.toStringF(format: String): String { + return KVManager.fecha.format(this, format) +} + +object DateSerializer : KSerializer<Date> { + override val descriptor: SerialDescriptor = SerialClassDescImpl("kotlin.js.Date") + + override fun deserialize(input: Decoder): Date { + return input.decodeString().toDateF() + } + + override fun serialize(output: Encoder, obj: Date) { + output.encodeString(obj.toStringF()) + } +} diff --git a/src/main/kotlin/pl/treksoft/kvision/types/KDate.kt b/src/main/kotlin/pl/treksoft/kvision/utils/JSON.kt index c81ebde1..e47351ac 100644 --- a/src/main/kotlin/pl/treksoft/kvision/types/KDate.kt +++ b/src/main/kotlin/pl/treksoft/kvision/utils/JSON.kt @@ -19,21 +19,21 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package pl.treksoft.kvision.types +package pl.treksoft.kvision.utils -import pl.treksoft.kvision.utils.toDateF -import pl.treksoft.kvision.utils.toStringF +import kotlinx.serialization.context.SimpleModule +import kotlinx.serialization.json.JSON +import pl.treksoft.kvision.types.DateSerializer import kotlin.js.Date -@Suppress("MayBeConstant", "TopLevelPropertyNaming") -actual val KDATE_FORMAT = "YYYY-MM-DD HH:mm:ss" +object JSON { -actual fun nowDate(): KDate = - KDate(Date().getTime().toLong()) + val plain = JSON().apply { + install(SimpleModule(Date::class, DateSerializer)) + } -actual fun String.toKDateF(format: String): KDate = - this.toDateF(format)?.getTime()?.toLong()?.let { KDate(it) } ?: KDate() + val nonstrict = JSON(strictMode = false).apply { + install(SimpleModule(Date::class, DateSerializer)) + } -actual fun KDate.toStringF(format: String) = this.toJS().toStringF(format) - -fun KDate.toJS(): kotlin.js.Date = kotlin.js.Date(this.time) +} diff --git a/src/main/kotlin/pl/treksoft/kvision/utils/Utils.kt b/src/main/kotlin/pl/treksoft/kvision/utils/Utils.kt index e5f608c2..e252d672 100644 --- a/src/main/kotlin/pl/treksoft/kvision/utils/Utils.kt +++ b/src/main/kotlin/pl/treksoft/kvision/utils/Utils.kt @@ -27,13 +27,11 @@ import com.lightningkite.kotlin.observable.list.ObservableList import kotlinx.coroutines.suspendCancellableCoroutine import org.w3c.files.File import org.w3c.files.FileReader -import pl.treksoft.kvision.KVManager import pl.treksoft.kvision.core.CssSize import pl.treksoft.kvision.core.UNIT import kotlin.browser.window import kotlin.coroutines.resume import kotlin.coroutines.resumeWithException -import kotlin.js.Date /** * Extension property to convert Int to CSS px units. @@ -186,27 +184,6 @@ fun Int.toHexString(): String { } /** - * Extension function to convert String to Date with a given date format. - * @param format date/time format - * @return Date object - */ -@Suppress("UnsafeCastFromDynamic") -fun String.toDateF(format: String = "YYYY-MM-DD HH:mm:ss"): Date? { - val result = KVManager.fecha.parse(this, format) - return if (result) result else null -} - -/** - * Extension function to convert Date to String with a given date format. - * @param format date/time format - * @return String object - */ -@Suppress("UnsafeCastFromDynamic") -fun Date.toStringF(format: String = "YYYY-MM-DD HH:mm:ss"): String { - return KVManager.fecha.format(this, format) -} - -/** * Utility function to detect Internet Explorer 11. * @return true if the current browser is IE11 */ @@ -216,7 +193,6 @@ fun isIE11(): Boolean = window.navigator.userAgent.matches("Trident\\/7\\.") * Suspending extension function to get file content. * @return file content */ -@Suppress("EXPERIMENTAL_FEATURE_WARNING") suspend fun File.getContent(): String = suspendCancellableCoroutine { cont -> val reader = FileReader() reader.onload = { diff --git a/src/main/kotlin/pl/treksoft/kvision/window/Window.kt b/src/main/kotlin/pl/treksoft/kvision/window/Window.kt index bdfb2c0f..ee20dc51 100644 --- a/src/main/kotlin/pl/treksoft/kvision/window/Window.kt +++ b/src/main/kotlin/pl/treksoft/kvision/window/Window.kt @@ -105,11 +105,11 @@ open class Window( /** * Determines if the window is resizable. */ - var isResizable by refreshOnUpdate(isResizable, { checkIsResizable() }) + var isResizable by refreshOnUpdate(isResizable) { checkIsResizable() } /** * Determines if the window is draggable. */ - var isDraggable by refreshOnUpdate(isDraggable, { checkIsDraggable(); checkHeaderVisibility() }) + var isDraggable by refreshOnUpdate(isDraggable) { checkIsDraggable(); checkHeaderVisibility() } /** * Determines if Close button is visible. */ @@ -201,7 +201,7 @@ open class Window( } kotlin.browser.window.addEventListener("mousemove", moveCallback) var upCallback: ((Event) -> Unit)? = null - upCallback = { _ -> + upCallback = { isDrag = false kotlin.browser.window.removeEventListener("mousemove", moveCallback) kotlin.browser.window.removeEventListener("mouseup", upCallback) |