diff options
27 files changed, 1441 insertions, 232 deletions
@@ -70,6 +70,10 @@ CSS grid and Bootstrap responsive 12 columns gid). Bootstrap progress bar component. +# Package pl.treksoft.kvision.remote + +A set of components for creating multiplatform automatic connectivity with backend servers. + # Package pl.treksoft.kvision.routing Simple and easy to use JavaScript router wrapper. @@ -82,6 +86,10 @@ Clasess supporting HTML tables. Toolbar and button group components. +# Package pl.treksoft.kvision.types + +Multiplatform type definitions. + # Package pl.treksoft.kvision.utils Interfaces and helper functions for Snabbdom virtual dom implementation and a few useful extension functions. diff --git a/dokka/kvision-dokka-helper.jar b/dokka/kvision-dokka-helper.jar Binary files differindex ce048ea2..d600abd6 100644 --- a/dokka/kvision-dokka-helper.jar +++ b/dokka/kvision-dokka-helper.jar diff --git a/kvision-common/build.gradle b/kvision-common/build.gradle new file mode 100644 index 00000000..af3703e6 --- /dev/null +++ b/kvision-common/build.gradle @@ -0,0 +1,10 @@ +apply plugin: 'kotlin-platform-common' +apply plugin: 'kotlinx-serialization' + +dependencies { + compile "org.jetbrains.kotlin:kotlin-stdlib-common:$kotlinVersion" + compile "org.jetbrains.kotlinx:kotlinx-serialization-runtime-common:$serializationVersion" + compile "org.jetbrains.kotlinx:kotlinx-coroutines-core-common:$coroutinesVersion" + testCompile "org.jetbrains.kotlin:kotlin-test-common:$kotlinVersion" + testCompile "org.jetbrains.kotlin:kotlin-test-annotations-common:$kotlinVersion" +} diff --git a/kvision-common/src/main/kotlin/pl/treksoft/kvision/remote/Jooby.kt b/kvision-common/src/main/kotlin/pl/treksoft/kvision/remote/Jooby.kt new file mode 100644 index 00000000..918b1d1f --- /dev/null +++ b/kvision-common/src/main/kotlin/pl/treksoft/kvision/remote/Jooby.kt @@ -0,0 +1,32 @@ +/* + * 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.remote + +/** + * A Jooby based server. + */ +expect open class JoobyServer + +/** + * A server request. + */ +expect interface Request diff --git a/kvision-common/src/main/kotlin/pl/treksoft/kvision/remote/ServiceManager.kt b/kvision-common/src/main/kotlin/pl/treksoft/kvision/remote/ServiceManager.kt new file mode 100644 index 00000000..4a6be56b --- /dev/null +++ b/kvision-common/src/main/kotlin/pl/treksoft/kvision/remote/ServiceManager.kt @@ -0,0 +1,99 @@ +/* + * 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.remote + +import kotlinx.coroutines.experimental.Deferred + +const val SERVICE_PREFIX = "/kv_service" + +/** + * Multiplatform service manager. + */ +expect open class ServiceManager<out T>(service: T? = null) { + /** + * Binds a given route with a function of the receiver. + * @param route a route + * @param function a function of the receiver + */ + protected inline fun <reified RET> bind(route: String, noinline function: T.(Request?) -> Deferred<RET>) + + /** + * Binds a given route with a function of the receiver. + * @param route a route + * @param function a function of the receiver + */ + protected inline fun <reified PAR, reified RET> bind( + route: String, + noinline function: T.(PAR, Request?) -> Deferred<RET> + ) + + /** + * Binds a given route with a function of the receiver. + * @param route a route + * @param function a function of the receiver + */ + protected inline fun <reified PAR1, reified PAR2, reified RET> bind( + route: String, + noinline function: T.(PAR1, PAR2, Request?) -> Deferred<RET> + ) + + /** + * Binds a given route with a function of the receiver. + * @param route a route + * @param function a function of the receiver + */ + protected inline fun <reified PAR1, reified PAR2, reified PAR3, reified RET> bind( + route: String, + noinline function: T.(PAR1, PAR2, PAR3, Request?) -> Deferred<RET> + ) + + /** + * Binds a given route with a function of the receiver. + * @param route a route + * @param function a function of the receiver + */ + protected inline fun <reified PAR1, reified PAR2, reified PAR3, reified PAR4, reified RET> bind( + route: String, + noinline function: T.(PAR1, PAR2, PAR3, PAR4, Request?) -> Deferred<RET> + ) + + /** + * Binds a given route with a function of the receiver. + * @param route a route + * @param function a function of the receiver + */ + protected inline fun <reified PAR1, reified PAR2, reified PAR3, reified PAR4, reified PAR5, reified RET> bind( + route: String, + noinline function: T.(PAR1, PAR2, PAR3, PAR4, PAR5, Request?) -> Deferred<RET> + ) + + /** + * Applies all defined routes to the given server. + * @param k a Jooby server + */ + fun applyRoutes(k: JoobyServer) + + /** + * Returns the list of defined bindings. + */ + fun getCalls(): Map<String, String> +} diff --git a/kvision-common/src/main/kotlin/pl/treksoft/kvision/types/KDate.kt b/kvision-common/src/main/kotlin/pl/treksoft/kvision/types/KDate.kt new file mode 100644 index 00000000..583323de --- /dev/null +++ b/kvision-common/src/main/kotlin/pl/treksoft/kvision/types/KDate.kt @@ -0,0 +1,49 @@ +/* + * 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.Serializable + +expect val KDATE_FORMAT: String + +/** + * A serializable wrapper for a multiplatform Date type. + */ +@Serializable +data class KDate(val time: Long) { + constructor() : this(now().time) + constructor(str: String) : this(str.toKDateF(KDATE_FORMAT).time) + + override fun toString(): String { + return this.toStringF(KDATE_FORMAT) + } + + companion object { + fun now() = nowDate() + } +} + +internal expect fun nowDate(): KDate + +internal expect fun String.toKDateF(format: String): KDate + +internal expect fun KDate.toStringF(format: String): String diff --git a/kvision-common/src/main/kotlin/pl/treksoft/kvision/types/KFile.kt b/kvision-common/src/main/kotlin/pl/treksoft/kvision/types/KFile.kt new file mode 100644 index 00000000..ce4adca4 --- /dev/null +++ b/kvision-common/src/main/kotlin/pl/treksoft/kvision/types/KFile.kt @@ -0,0 +1,34 @@ +/* + * 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.Serializable + +/** + * A serializable class for a multiplatform File type. + */ +@Serializable +data class KFile( + val name: String, + val size: Int, + val content: String? = null +) diff --git a/kvision-server/build.gradle b/kvision-server/build.gradle new file mode 100644 index 00000000..8be34ecf --- /dev/null +++ b/kvision-server/build.gradle @@ -0,0 +1,29 @@ +apply plugin: "io.spring.dependency-management" +apply plugin: 'kotlin-platform-jvm' +apply plugin: 'kotlinx-serialization' + +dependencyManagement { + imports { + mavenBom "org.jooby:jooby-bom:${joobyVersion}" + } +} + +dependencies { + expectedBy project(":kvision-common") + compile "org.jetbrains.kotlin:kotlin-stdlib:$kotlinVersion" + compile "org.jetbrains.kotlinx:kotlinx-serialization-runtime:$serializationVersion" + compile "org.jetbrains.kotlinx:kotlinx-coroutines-core:$coroutinesVersion" + compile "org.jooby:jooby-lang-kotlin" + compile "org.jooby:jooby-jackson" + compile "com.fasterxml.jackson.module:jackson-module-kotlin:${jacksonModuleKotlinVersion}" + testCompile "org.jetbrains.kotlin:kotlin-test:$kotlinVersion" + testCompile project(":kvision-common") +} + +compileKotlin { + targetCompatibility = javaVersion + sourceCompatibility = javaVersion + kotlinOptions { + jvmTarget = javaVersion + } +} diff --git a/kvision-server/src/main/kotlin/pl/treksoft/kvision/remote/Jooby.kt b/kvision-server/src/main/kotlin/pl/treksoft/kvision/remote/Jooby.kt new file mode 100644 index 00000000..14b2b376 --- /dev/null +++ b/kvision-server/src/main/kotlin/pl/treksoft/kvision/remote/Jooby.kt @@ -0,0 +1,68 @@ +/* + * 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. + */ +@file:Suppress("EXPERIMENTAL_FEATURE_WARNING") + +package pl.treksoft.kvision.remote + +import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper +import kotlinx.coroutines.experimental.Deferred +import org.jooby.Kooby +import org.jooby.Session +import org.jooby.json.Jackson +import kotlinx.coroutines.experimental.async as coroutinesAsync + +/** + * A Jooby based server. + */ +actual open class JoobyServer(init: JoobyServer.() -> Unit) : Kooby() { + init { + val mapper = jacksonObjectMapper() + @Suppress("LeakingThis") + use(Jackson(mapper)) + @Suppress("LeakingThis") + init.invoke(this) + } +} + +/** + * A server request. + */ +actual typealias Request = org.jooby.Request + +/** + * A helper extension function for asynchronous request processing. + */ +fun <RESP> Request?.async(block: (Request) -> RESP): Deferred<RESP> = this?.let { req -> + coroutinesAsync { + block(req) + } +} ?: throw IllegalStateException("Request not set!") + +/** + * A helper extension function for asynchronous request processing with session. + */ +fun <RESP> Request?.asyncSession(block: (Request, Session) -> RESP): Deferred<RESP> = this?.let { req -> + val session = req.session() + coroutinesAsync { + block(req, session) + } +} ?: throw IllegalStateException("Request not set!") diff --git a/kvision-server/src/main/kotlin/pl/treksoft/kvision/remote/ServiceManager.kt b/kvision-server/src/main/kotlin/pl/treksoft/kvision/remote/ServiceManager.kt new file mode 100644 index 00000000..45a995ac --- /dev/null +++ b/kvision-server/src/main/kotlin/pl/treksoft/kvision/remote/ServiceManager.kt @@ -0,0 +1,230 @@ +/* + * 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.remote + +import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper +import kotlinx.coroutines.experimental.Deferred +import kotlinx.coroutines.experimental.runBlocking +import org.jooby.Status + +/** + * Multiplatform service manager. + */ +@Suppress("EXPERIMENTAL_FEATURE_WARNING") +actual open class ServiceManager<out T> actual constructor(val service: T?) { + + protected val routes: MutableList<JoobyServer.() -> Unit> = mutableListOf() + val mapper = jacksonObjectMapper() + + /** + * Binds a given route with a function of the receiver. + * @param route a route + * @param function a function of the receiver + */ + protected actual inline fun <reified RET> bind( + route: String, + noinline function: T.(Request?) -> Deferred<RET> + ) { + routes.add({ + post("$SERVICE_PREFIX/$route") { req, res -> + if (service != null) { + try { + res.send(runBlocking { function.invoke(service, req).await() }) + } catch (e: Exception) { + e.printStackTrace() + res.status(500).send(e.message ?: "Error") + } + } else { + res.status(Status.BAD_REQUEST) + } + } + }) + } + + /** + * Binds a given route with a function of the receiver. + * @param route a route + * @param function a function of the receiver + */ + protected actual inline fun <reified PAR, reified RET> bind( + route: String, + noinline function: T.(PAR, Request?) -> Deferred<RET> + ) { + routes.add({ + post("$SERVICE_PREFIX/$route") { req, res -> + val param = try { + req.body(PAR::class.java) + } catch (e: Exception) { + null as PAR + } + if (service != null) { + try { + res.send(runBlocking { function.invoke(service, param, req).await() }) + } catch (e: Exception) { + e.printStackTrace() + res.status(500).send(e.message ?: "Error") + } + } else { + res.status(Status.BAD_REQUEST) + } + } + }) + } + + /** + * Binds a given route with a function of the receiver. + * @param route a route + * @param function a function of the receiver + */ + protected actual inline fun <reified PAR1, reified PAR2, reified RET> bind( + route: String, + noinline function: T.(PAR1, PAR2, Request?) -> Deferred<RET> + ) { + routes.add({ + post("$SERVICE_PREFIX/$route") { req, res -> + val str = req.body(String::class.java) + val tree = mapper.readTree(str) + if (tree.size() == 2 && service != null) { + val p1 = mapper.treeToValue(tree[0], PAR1::class.java) + val p2 = mapper.treeToValue(tree[1], PAR2::class.java) + try { + res.send(runBlocking { function.invoke(service, p1, p2, req).await() }) + } catch (e: Exception) { + e.printStackTrace() + res.status(500).send(e.message ?: "Error") + } + } else { + res.status(Status.BAD_REQUEST) + } + } + }) + } + + /** + * Binds a given route with a function of the receiver. + * @param route a route + * @param function a function of the receiver + */ + protected actual inline fun <reified PAR1, reified PAR2, reified PAR3, reified RET> bind( + route: String, + noinline function: T.(PAR1, PAR2, PAR3, Request?) -> Deferred<RET> + ) { + routes.add({ + post("$SERVICE_PREFIX/$route") { req, res -> + val str = req.body(String::class.java) + val tree = mapper.readTree(str) + if (tree.size() == 3 && service != null) { + val p1 = mapper.treeToValue(tree[0], PAR1::class.java) + val p2 = mapper.treeToValue(tree[1], PAR2::class.java) + val p3 = mapper.treeToValue(tree[2], PAR3::class.java) + try { + res.send(runBlocking { function.invoke(service, p1, p2, p3, req).await() }) + } catch (e: Exception) { + e.printStackTrace() + res.status(500).send(e.message ?: "Error") + } + } else { + res.status(Status.BAD_REQUEST) + } + } + }) + } + + /** + * Binds a given route with a function of the receiver. + * @param route a route + * @param function a function of the receiver + */ + protected actual inline fun <reified PAR1, reified PAR2, reified PAR3, reified PAR4, reified RET> bind( + route: String, + noinline function: T.(PAR1, PAR2, PAR3, PAR4, Request?) -> Deferred<RET> + ) { + routes.add({ + post("$SERVICE_PREFIX/$route") { req, res -> + val str = req.body(String::class.java) + val tree = mapper.readTree(str) + if (tree.size() == 4 && service != null) { + val p1 = mapper.treeToValue(tree[0], PAR1::class.java) + val p2 = mapper.treeToValue(tree[1], PAR2::class.java) + val p3 = mapper.treeToValue(tree[2], PAR3::class.java) + val p4 = mapper.treeToValue(tree[3], PAR4::class.java) + try { + res.send(runBlocking { function.invoke(service, p1, p2, p3, p4, req).await() }) + } catch (e: Exception) { + e.printStackTrace() + res.status(500).send(e.message ?: "Error") + } + } else { + res.status(Status.BAD_REQUEST) + } + } + }) + } + + /** + * Binds a given route with a function of the receiver. + * @param route a route + * @param function a function of the receiver + */ + protected actual inline fun <reified PAR1, reified PAR2, reified PAR3, reified PAR4, reified PAR5, reified RET> bind( + route: String, + noinline function: T.(PAR1, PAR2, PAR3, PAR4, PAR5, Request?) -> Deferred<RET> + ) { + routes.add({ + post("$SERVICE_PREFIX/$route") { req, res -> + val str = req.body(String::class.java) + val tree = mapper.readTree(str) + if (tree.size() == 5 && service != null) { + val p1 = mapper.treeToValue(tree[0], PAR1::class.java) + val p2 = mapper.treeToValue(tree[1], PAR2::class.java) + val p3 = mapper.treeToValue(tree[2], PAR3::class.java) + val p4 = mapper.treeToValue(tree[3], PAR4::class.java) + val p5 = mapper.treeToValue(tree[4], PAR5::class.java) + try { + res.send(runBlocking { function.invoke(service, p1, p2, p3, p4, p5, req).await() }) + } catch (e: Exception) { + e.printStackTrace() + res.status(500).send(e.message ?: "Error") + } + } else { + res.status(Status.BAD_REQUEST) + } + } + }) + } + + /** + * Applies all defined routes to the given server. + * @param k a Jooby server + */ + actual fun applyRoutes(k: JoobyServer) { + routes.forEach { + it.invoke(k) + } + } + + /** + * Returns the list of defined bindings. + * Not used on the jvm platform. + */ + actual fun getCalls(): Map<String, String> = mapOf() +} diff --git a/kvision-server/src/main/kotlin/pl/treksoft/kvision/types/KDate.kt b/kvision-server/src/main/kotlin/pl/treksoft/kvision/types/KDate.kt new file mode 100644 index 00000000..1d174f88 --- /dev/null +++ b/kvision-server/src/main/kotlin/pl/treksoft/kvision/types/KDate.kt @@ -0,0 +1,42 @@ +/* + * 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 java.text.SimpleDateFormat +import java.util.* + +/** + * A serializable wrapper for a multiplatform Date type. + */ +@Suppress("MayBeConstant") +actual val KDATE_FORMAT = "yyyy-MM-dd HH:mm:ss" + +internal actual fun nowDate(): KDate = + KDate(Date().time) + +internal actual fun String.toKDateF(format: String): KDate = + KDate(SimpleDateFormat(format).parse(this).time) + +internal actual fun KDate.toStringF(format: String) = + SimpleDateFormat(format).format(this.toJava()) + +fun KDate.toJava(): java.util.Date = java.util.Date(this.time) diff --git a/settings.gradle b/settings.gradle index 829fca7b..2216afa8 100644 --- a/settings.gradle +++ b/settings.gradle @@ -1 +1,3 @@ rootProject.name = 'kvision' + +include 'kvision-common', 'kvision-server' diff --git a/src/main/kotlin/pl/treksoft/kvision/form/Form.kt b/src/main/kotlin/pl/treksoft/kvision/form/Form.kt index 65161303..18acdf9f 100644 --- a/src/main/kotlin/pl/treksoft/kvision/form/Form.kt +++ b/src/main/kotlin/pl/treksoft/kvision/form/Form.kt @@ -21,8 +21,14 @@ */ package pl.treksoft.kvision.form -import org.w3c.files.File -import kotlin.js.Date +import kotlinx.serialization.KSerializer +import kotlinx.serialization.Mapper +import kotlinx.serialization.json.JSON +import kotlinx.serialization.serializer +import pl.treksoft.kvision.form.upload.Upload +import pl.treksoft.kvision.types.KDate +import pl.treksoft.kvision.types.KFile +import pl.treksoft.kvision.utils.getContent import kotlin.js.Json import kotlin.reflect.KProperty1 @@ -41,16 +47,45 @@ internal data class FieldParams<in F : FormControl>( * @constructor Creates a form with a given modelFactory function * @param K model class type * @param panel optional instance of [FormPanel] - * @param modelFactory function transforming a Map<String, Any?> to a data model of class K + * @param serializer a serializer for model type */ @Suppress("TooManyFunctions") -class Form<K>(private val panel: FormPanel<K>? = null, private val modelFactory: (Map<String, Any?>) -> K) { +class Form<K : Any>(private val panel: FormPanel<K>? = null, private val serializer: KSerializer<K>) { + internal val modelFactory: (Map<String, Any?>) -> K internal val fields: MutableMap<String, FormControl> = mutableMapOf() internal val fieldsParams: MutableMap<String, Any> = mutableMapOf() internal var validatorMessage: ((Form<K>) -> String?)? = null internal var validator: ((Form<K>) -> Boolean?)? = null + init { + 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 List<*> -> { + @Suppress("UNCHECKED_CAST") + (entry.value as? List<KFile>)?.let { + listOf(entry.key to entry.value, "${entry.key}.size" to it.size) + + it.mapIndexed { index, kFile -> + listOf( + "${entry.key}.${index + 1}.name" to kFile.name, + "${entry.key}.${index + 1}.size" to kFile.size, + "${entry.key}.${index + 1}.content" to kFile.content + ) + }.flatten() + } ?: listOf() + } + else -> listOf(entry.key to entry.value) + } + }.toMap().withDefault { null } + val mapper = Mapper.InNullableMapper(map) + mapper.read(serializer) + } + } + internal fun <C : FormControl> addInternal( key: KProperty1<K, *>, control: C, required: Boolean = false, validatorMessage: ((C) -> String?)? = null, @@ -121,8 +156,8 @@ class Form<K>(private val panel: FormPanel<K>? = null, private val modelFactory: * @param validator optional validation function * @return current form */ - fun <C : DateFormControl> add( - key: KProperty1<K, Date?>, control: C, required: Boolean = false, + fun <C : KDateFormControl> add( + key: KProperty1<K, KDate?>, control: C, required: Boolean = false, validatorMessage: ((C) -> String?)? = null, validator: ((C) -> Boolean?)? = null ): Form<K> { @@ -138,8 +173,8 @@ class Form<K>(private val panel: FormPanel<K>? = null, private val modelFactory: * @param validator optional validation function * @return current form */ - fun <C : FilesFormControl> add( - key: KProperty1<K, List<File>?>, control: C, required: Boolean = false, + fun <C : KFilesFormControl> add( + key: KProperty1<K, List<KFile>?>, control: C, required: Boolean = false, validatorMessage: ((C) -> String?)? = null, validator: ((C) -> Boolean?)? = null ): Form<K> { @@ -189,16 +224,9 @@ class Form<K>(private val panel: FormPanel<K>? = null, private val modelFactory: */ fun setData(model: K) { fields.forEach { it.value.setValue(null) } - val map = model.asDynamic().map as? Map<String, Any?> - if (map != null) { - map.forEach { - fields[it.key]?.setValue(it.value) - } - } else { - for (key in js("Object").keys(model)) { - @Suppress("UnsafeCastFromDynamic") - fields[key]?.setValue(model.asDynamic()[key]) - } + for (key in js("Object").keys(model)) { + @Suppress("UnsafeCastFromDynamic") + fields[key]?.setValue(model.asDynamic()[key]) } } @@ -219,11 +247,27 @@ class Form<K>(private val panel: FormPanel<K>? = null, private val modelFactory: } /** + * Returns file with the content read. + * @param key key identifier of the control + * @param kFile object identifying the file + * @return KFile object + */ + @Suppress("EXPERIMENTAL_FEATURE_WARNING") + suspend fun getContent( + key: KProperty1<K, List<KFile>?>, + kFile: KFile + ): KFile { + val control = getControl(key) as Upload + val content = control.getNativeFile(kFile)?.getContent() + return kFile.copy(content = content) + } + + /** * Returns current data model as JSON. * @return data model as JSON */ fun getDataJson(): Json { - return fields.entries.associateBy({ it.key }, { it.value.getValue() }).asJson() + return kotlin.js.JSON.parse(JSON.stringify(serializer, getData())) } /** @@ -259,27 +303,20 @@ class Form<K>(private val panel: FormPanel<K>? = null, private val modelFactory: } return fieldWithError == null && validatorPassed } -} -/** - * Returns given value from the map as a String. - */ -fun Map<String, Any?>.string(key: String): String? = this[key] as? String + companion object { + inline fun <reified K : Any> create( + panel: FormPanel<K>? = null, + noinline init: (Form<K>.() -> Unit)? = null + ): Form<K> { + val form = Form(panel, K::class.serializer()) + init?.invoke(form) + return form + } -/** - * Returns given value from the map as a Number. - */ -fun Map<String, Any?>.number(key: String): Number? = this[key] as? Number -/** - * Returns given value from the map as a Boolean. - */ -fun Map<String, Any?>.bool(key: String): Boolean? = this[key] as? Boolean - -/** - * Returns given value from the map as a Date. - */ -fun Map<String, Any?>.date(key: String): Date? = this[key] as? Date + } +} /** * Extension function to convert Map to JSON. diff --git a/src/main/kotlin/pl/treksoft/kvision/form/FormControl.kt b/src/main/kotlin/pl/treksoft/kvision/form/FormControl.kt index be27ac7a..6aff842a 100644 --- a/src/main/kotlin/pl/treksoft/kvision/form/FormControl.kt +++ b/src/main/kotlin/pl/treksoft/kvision/form/FormControl.kt @@ -21,9 +21,9 @@ */ package pl.treksoft.kvision.form -import org.w3c.files.File import pl.treksoft.kvision.core.Component -import kotlin.js.Date +import pl.treksoft.kvision.types.KDate +import pl.treksoft.kvision.types.KFile /** * Input controls sizes. @@ -190,15 +190,15 @@ interface BoolFormControl : FormControl { /** * Base interface of a form control with a date value. */ -interface DateFormControl : FormControl { +interface KDateFormControl : FormControl { /** * Date value. */ - var value: Date? + var value: KDate? - override fun getValue(): Date? = value + override fun getValue(): KDate? = value override fun setValue(v: Any?) { - value = v as? Date + value = v as? KDate } override fun getValueAsString(): String? = value?.toString() @@ -207,13 +207,13 @@ interface DateFormControl : FormControl { /** * Base interface of a form control with a list of files value. */ -interface FilesFormControl : FormControl { +interface KFilesFormControl : FormControl { /** * List of files value. */ - var value: List<File>? + var value: List<KFile>? - override fun getValue(): List<File>? = value + override fun getValue(): List<KFile>? = value override fun setValue(v: Any?) { if (v == null) value = null } diff --git a/src/main/kotlin/pl/treksoft/kvision/form/FormPanel.kt b/src/main/kotlin/pl/treksoft/kvision/form/FormPanel.kt index 3eb2a0ca..88aed36b 100644 --- a/src/main/kotlin/pl/treksoft/kvision/form/FormPanel.kt +++ b/src/main/kotlin/pl/treksoft/kvision/form/FormPanel.kt @@ -22,7 +22,8 @@ package pl.treksoft.kvision.form import com.github.snabbdom.VNode -import org.w3c.files.File +import kotlinx.serialization.KSerializer +import kotlinx.serialization.serializer import pl.treksoft.kvision.core.Container import pl.treksoft.kvision.core.StringBoolPair import pl.treksoft.kvision.core.StringPair @@ -31,7 +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 kotlin.js.Date +import pl.treksoft.kvision.types.KDate +import pl.treksoft.kvision.types.KFile import kotlin.js.Json import kotlin.reflect.KProperty1 @@ -80,13 +82,13 @@ enum class FormTarget(internal val target: String) { * @param enctype form encoding type * @param type form layout * @param classes set of CSS class names - * @param modelFactory function transforming a Map<String, Any?> to a data model of class K + * @param serializer a serializer for model type */ @Suppress("TooManyFunctions") -open class FormPanel<K>( +open class FormPanel<K : Any>( method: FormMethod? = null, action: String? = null, enctype: FormEnctype? = null, private val type: FormType? = null, classes: Set<String> = setOf(), - modelFactory: (Map<String, Any?>) -> K + serializer: KSerializer<K> ) : SimplePanel(classes) { /** @@ -148,7 +150,7 @@ open class FormPanel<K>( * Internal property. */ @Suppress("LeakingThis") - protected val form = Form(this, modelFactory) + protected val form = Form(this, serializer) /** * @suppress * Internal property. @@ -281,8 +283,8 @@ open class FormPanel<K>( * @param validator optional validation function * @return current form panel */ - open fun <C : DateFormControl> add( - key: KProperty1<K, Date?>, control: C, required: Boolean = false, + open fun <C : KDateFormControl> add( + key: KProperty1<K, KDate?>, control: C, required: Boolean = false, validatorMessage: ((C) -> String?)? = null, validator: ((C) -> Boolean?)? = null ): FormPanel<K> { @@ -298,8 +300,8 @@ open class FormPanel<K>( * @param validator optional validation function * @return current form panel */ - open fun <C : FilesFormControl> add( - key: KProperty1<K, List<File>?>, control: C, required: Boolean = false, + open fun <C : KFilesFormControl> add( + key: KProperty1<K, List<KFile>?>, control: C, required: Boolean = false, validatorMessage: ((C) -> String?)? = null, validator: ((C) -> Boolean?)? = null ): FormPanel<K> { @@ -368,6 +370,20 @@ open class FormPanel<K>( } /** + * Returns an object with the content of the file. + * @param key key identifier of the control + * @param kFile object identifying the file + * @return KFile object + */ + @Suppress("EXPERIMENTAL_FEATURE_WARNING") + suspend fun getContent( + key: KProperty1<K, List<KFile>?>, + kFile: KFile + ): KFile { + return form.getContent(key, kFile) + } + + /** * Returns current data model as JSON. * @return data model as JSON */ @@ -389,14 +405,26 @@ open class FormPanel<K>( * * It takes the same parameters as the constructor of the built component. */ - fun <K> Container.formPanel( + inline fun <reified K : Any> Container.formPanel( method: FormMethod? = null, action: String? = null, enctype: FormEnctype? = null, type: FormType? = null, classes: Set<String> = setOf(), - modelFactory: (Map<String, Any?>) -> K + noinline init: (FormPanel<K>.() -> Unit)? = null ): FormPanel<K> { - val panel = FormPanel(method, action, enctype, type, classes, modelFactory) - this.add(panel) - return panel + val formPanel = FormPanel.create<K>(method, action, enctype, type, classes) + init?.invoke(formPanel) + this.add(formPanel) + return formPanel } + + inline fun <reified K : Any> create( + method: FormMethod? = null, action: String? = null, enctype: FormEnctype? = null, + type: FormType? = null, classes: Set<String> = setOf(), + noinline init: (FormPanel<K>.() -> Unit)? = null + ): FormPanel<K> { + val formPanel = FormPanel(method, action, enctype, type, classes, K::class.serializer()) + init?.invoke(formPanel) + return formPanel + } + } } diff --git a/src/main/kotlin/pl/treksoft/kvision/form/time/DateTime.kt b/src/main/kotlin/pl/treksoft/kvision/form/time/DateTime.kt index 3d32fd8c..9cdd0369 100644 --- a/src/main/kotlin/pl/treksoft/kvision/form/time/DateTime.kt +++ b/src/main/kotlin/pl/treksoft/kvision/form/time/DateTime.kt @@ -24,12 +24,12 @@ package pl.treksoft.kvision.form.time import pl.treksoft.kvision.core.Container import pl.treksoft.kvision.core.StringBoolPair import pl.treksoft.kvision.core.Widget -import pl.treksoft.kvision.form.DateFormControl import pl.treksoft.kvision.form.FieldLabel import pl.treksoft.kvision.form.HelpBlock +import pl.treksoft.kvision.form.KDateFormControl import pl.treksoft.kvision.panel.SimplePanel +import pl.treksoft.kvision.types.KDate import pl.treksoft.kvision.utils.SnOn -import kotlin.js.Date /** * Form field date/time chooser component. @@ -42,9 +42,9 @@ import kotlin.js.Date * @param rich determines if [label] can contain HTML code */ open class DateTime( - value: Date? = null, name: String? = null, format: String = "YYYY-MM-DD HH:mm", label: String? = null, + value: KDate? = null, name: String? = null, format: String = "YYYY-MM-DD HH:mm", label: String? = null, rich: Boolean = false -) : SimplePanel(setOf("form-group")), DateFormControl { +) : SimplePanel(setOf("form-group")), KDateFormControl { /** * Date/time input value. @@ -235,7 +235,7 @@ open class DateTime( * It takes the same parameters as the constructor of the built component. */ fun Container.dateTime( - value: Date? = null, name: String? = null, format: String = "YYYY-MM-DD HH:mm", label: String? = null, + value: KDate? = null, name: String? = null, format: String = "YYYY-MM-DD HH:mm", label: String? = null, rich: Boolean = false, init: (DateTime.() -> Unit)? = null ): DateTime { val dateTime = DateTime(value, name, format, label, rich).apply { init?.invoke(this) } diff --git a/src/main/kotlin/pl/treksoft/kvision/form/time/DateTimeInput.kt b/src/main/kotlin/pl/treksoft/kvision/form/time/DateTimeInput.kt index 86e9c7ba..3a40d1af 100644 --- a/src/main/kotlin/pl/treksoft/kvision/form/time/DateTimeInput.kt +++ b/src/main/kotlin/pl/treksoft/kvision/form/time/DateTimeInput.kt @@ -28,10 +28,11 @@ import pl.treksoft.kvision.core.StringPair import pl.treksoft.kvision.core.Widget import pl.treksoft.kvision.form.FormInput import pl.treksoft.kvision.form.InputSize +import pl.treksoft.kvision.types.KDate +import pl.treksoft.kvision.types.toJS +import pl.treksoft.kvision.types.toKDateF +import pl.treksoft.kvision.types.toStringF import pl.treksoft.kvision.utils.obj -import pl.treksoft.kvision.utils.toDateF -import pl.treksoft.kvision.utils.toStringF -import kotlin.js.Date internal const val DEFAULT_MINUTE_STEP = 5 internal const val MAX_VIEW = 4 @@ -46,7 +47,7 @@ internal const val MAX_VIEW = 4 */ @Suppress("TooManyFunctions") open class DateTimeInput( - value: Date? = null, format: String = "YYYY-MM-DD HH:mm", + value: KDate? = null, format: String = "YYYY-MM-DD HH:mm", classes: Set<String> = setOf() ) : Widget(classes + "form-control"), FormInput { @@ -162,7 +163,7 @@ open class DateTimeInput( @Suppress("UnsafeCastFromDynamic") protected open fun refreshState() { value?.let { - getElementJQueryD()?.datetimepicker("update", it) + getElementJQueryD()?.datetimepicker("update", it.toJS()) } ?: run { getElementJQueryD()?.`val`(null) getElementJQueryD()?.datetimepicker("update", null) @@ -179,7 +180,7 @@ open class DateTimeInput( protected open fun changeValue() { val v = getElementJQuery()?.`val`() as String? if (v != null && v.isNotEmpty()) { - this.value = v.toDateF(format) + this.value = v.toKDateF(format) } else { this.value = null } @@ -276,7 +277,7 @@ open class DateTimeInput( * It takes the same parameters as the constructor of the built component. */ fun Container.dateTimeInput( - value: Date? = null, format: String = "YYYY-MM-DD HH:mm", classes: Set<String> = setOf(), + value: KDate? = null, format: String = "YYYY-MM-DD HH:mm", classes: Set<String> = setOf(), init: (DateTimeInput.() -> Unit)? = null ): DateTimeInput { val dateTimeInput = DateTimeInput(value, format, classes).apply { init?.invoke(this) } diff --git a/src/main/kotlin/pl/treksoft/kvision/form/upload/Upload.kt b/src/main/kotlin/pl/treksoft/kvision/form/upload/Upload.kt index e6b397eb..5e3ac0df 100644 --- a/src/main/kotlin/pl/treksoft/kvision/form/upload/Upload.kt +++ b/src/main/kotlin/pl/treksoft/kvision/form/upload/Upload.kt @@ -3,13 +3,15 @@ */ package pl.treksoft.kvision.form.upload +import org.w3c.files.File import pl.treksoft.kvision.core.Container import pl.treksoft.kvision.core.StringBoolPair import pl.treksoft.kvision.core.Widget import pl.treksoft.kvision.form.FieldLabel -import pl.treksoft.kvision.form.FilesFormControl import pl.treksoft.kvision.form.HelpBlock +import pl.treksoft.kvision.form.KFilesFormControl import pl.treksoft.kvision.panel.SimplePanel +import pl.treksoft.kvision.types.KFile import pl.treksoft.kvision.utils.SnOn /** @@ -25,7 +27,7 @@ import pl.treksoft.kvision.utils.SnOn open class Upload( uploadUrl: String? = null, multiple: Boolean = false, label: String? = null, rich: Boolean = false -) : SimplePanel(setOf("form-group")), FilesFormControl { +) : SimplePanel(setOf("form-group")), KFilesFormControl { /** * File input value. @@ -228,6 +230,15 @@ open class Upload( } /** + * Returns the native JavaScript File object. + * @param kFile KFile object + * @return File object + */ + fun getNativeFile(kFile: KFile): File? { + return input.getNativeFile(kFile) + } + + /** * Resets the file input control. */ open fun resetInput() { diff --git a/src/main/kotlin/pl/treksoft/kvision/form/upload/UploadInput.kt b/src/main/kotlin/pl/treksoft/kvision/form/upload/UploadInput.kt index d77a9b9b..645cc69b 100644 --- a/src/main/kotlin/pl/treksoft/kvision/form/upload/UploadInput.kt +++ b/src/main/kotlin/pl/treksoft/kvision/form/upload/UploadInput.kt @@ -11,6 +11,7 @@ import pl.treksoft.kvision.core.StringPair import pl.treksoft.kvision.core.Widget import pl.treksoft.kvision.form.FormInput import pl.treksoft.kvision.form.InputSize +import pl.treksoft.kvision.types.KFile import pl.treksoft.kvision.utils.obj /** @@ -28,7 +29,7 @@ open class UploadInput(uploadUrl: String? = null, multiple: Boolean = false, cla /** * File input value. */ - var value: List<File>? + var value: List<KFile>? get() = getValue() set(value) { if (value == null) resetInput() @@ -112,6 +113,8 @@ open class UploadInput(uploadUrl: String? = null, multiple: Boolean = false, cla */ override var size: InputSize? by refreshOnUpdate() + private val nativeFiles: MutableMap<KFile, File> = mutableMapOf() + override fun render(): VNode { return render("input") } @@ -139,7 +142,7 @@ open class UploadInput(uploadUrl: String? = null, multiple: Boolean = false, cla return sn } - private fun getValue(): List<File>? { + private fun getValue(): List<KFile>? { val v = getFiles() return if (v.isNotEmpty()) v else null } @@ -217,8 +220,22 @@ open class UploadInput(uploadUrl: String? = null, multiple: Boolean = false, cla getElementJQueryD()?.fileinput("unlock") } - private fun getFiles(): List<File> { - return (getElementJQueryD()?.fileinput("getFileStack") as Array<File>).toList() + /** + * Returns the native JavaScript File object. + * @param kFile KFile object + * @return File object + */ + fun getNativeFile(kFile: KFile): File? { + return nativeFiles[kFile] + } + + private fun getFiles(): List<KFile> { + nativeFiles.clear() + return (getElementJQueryD()?.fileinput("getFileStack") as Array<File>).toList().map { + val kFile = KFile(it.name, it.size, null) + nativeFiles[kFile] = it + kFile + } } /** diff --git a/src/main/kotlin/pl/treksoft/kvision/remote/Jooby.kt b/src/main/kotlin/pl/treksoft/kvision/remote/Jooby.kt new file mode 100644 index 00000000..a5c580d6 --- /dev/null +++ b/src/main/kotlin/pl/treksoft/kvision/remote/Jooby.kt @@ -0,0 +1,34 @@ +/* + * 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.remote + +/** + * A Jooby based server. + * Not used on the js platform. + */ +actual open class JoobyServer + +/** + * A server request. + * Not used on the js platform. + */ +actual interface Request diff --git a/src/main/kotlin/pl/treksoft/kvision/remote/RemoteAgent.kt b/src/main/kotlin/pl/treksoft/kvision/remote/RemoteAgent.kt new file mode 100644 index 00000000..3f7276f0 --- /dev/null +++ b/src/main/kotlin/pl/treksoft/kvision/remote/RemoteAgent.kt @@ -0,0 +1,417 @@ +/* + * 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.remote + +import kotlinx.coroutines.experimental.Deferred +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.list +import kotlinx.serialization.serializer +import pl.treksoft.jquery.JQueryXHR +import pl.treksoft.jquery.jQuery +import pl.treksoft.kvision.utils.obj +import kotlin.js.Promise +import kotlin.js.js +import kotlin.js.undefined +import kotlin.reflect.KClass +import kotlin.js.JSON as NativeJSON + +internal class NonStandardTypeException(type: String) : Exception("Non standard type: $type!") + +/** + * Client side agent for remote calls. + */ +@Suppress("EXPERIMENTAL_FEATURE_WARNING", "LargeClass", "TooManyFunctions") +open class RemoteAgent<out T>(val serviceManager: ServiceManager<T>) { + + /** + * Executes defined call to a remote web service. + */ + inline fun <reified RET : Any, T> call(noinline function: T.(Request?) -> Deferred<RET>): Promise<RET> { + val url = + serviceManager.getCalls()[function.toString()] ?: throw IllegalStateException("Function not specified!") + return ajaxCall(url, null).then { + try { + deserialize<RET>(it, RET::class.js.name) + } catch (t: NonStandardTypeException) { + JSON.parse(RET::class.serializer(), it) + } + } + } + + /** + * Executes defined call to a remote web service. + */ + inline fun <reified RET : Any, T> call(noinline function: T.(Request?) -> Deferred<List<RET>>): Promise<List<RET>> { + val url = + serviceManager.getCalls()[function.toString()] ?: throw IllegalStateException("Function not specified!") + return ajaxCall(url, null).then { + try { + deserializeLists<RET>(it, RET::class.js.name) + } catch (t: NonStandardTypeException) { + JSON.parse(RET::class.serializer().list, it) + } + } + } + + /** + * Executes defined call to a remote web service. + */ + inline fun <reified PAR, reified RET : Any, T> call( + noinline function: T.(PAR, Request?) -> Deferred<RET>, + p: PAR, serializer: KSerializer<PAR>? = null + ): Promise<RET> { + val data = serialize(p, serializer) + val url = + serviceManager.getCalls()[function.toString()] ?: throw IllegalStateException("Function not specified!") + return ajaxCall(url, data).then { + try { + @Suppress("UNCHECKED_CAST") + deserialize<RET>(it, (RET::class as KClass<Any>).js.name) + } catch (t: NonStandardTypeException) { + JSON.parse(RET::class.serializer(), it) + } + } + } + + /** + * Executes defined call to a remote web service. + */ + inline fun <reified PAR, reified RET : Any, T> call( + noinline function: T.(PAR, Request?) -> Deferred<List<RET>>, + p: PAR, serializer: KSerializer<PAR>? = null + ): Promise<List<RET>> { + val data = serialize(p, serializer) + val url = + serviceManager.getCalls()[function.toString()] ?: throw IllegalStateException("Function not specified!") + return ajaxCall(url, data).then { + try { + deserializeLists<RET>(it, RET::class.js.name) + } catch (t: NonStandardTypeException) { + JSON.parse(RET::class.serializer().list, it) + } + } + } + + /** + * Executes defined call to a remote web service. + */ + inline fun <reified PAR1, reified PAR2, reified RET : Any, T> call( + noinline function: T.(PAR1, PAR2, Request?) -> Deferred<RET>, + p1: PAR1, p2: PAR2, serializer1: KSerializer<PAR1>? = null, serializer2: KSerializer<PAR2>? = null + ): Promise<RET> { + val data1 = serialize(p1, serializer1) + val data2 = serialize(p2, serializer2) + val data = "[ $data1 , $data2 ]" + val url = + serviceManager.getCalls()[function.toString()] ?: throw IllegalStateException("Function not specified!") + return ajaxCall(url, data).then { + try { + deserialize<RET>(it, RET::class.js.name) + } catch (t: NonStandardTypeException) { + JSON.parse(RET::class.serializer(), it) + } + } + } + + /** + * Executes defined call to a remote web service. + */ + inline fun <reified PAR1, reified PAR2, reified RET : Any, T> call( + noinline function: T.(PAR1, PAR2, Request?) -> Deferred<List<RET>>, + p1: PAR1, p2: PAR2, serializer1: KSerializer<PAR1>? = null, serializer2: KSerializer<PAR2>? = null + ): Promise<List<RET>> { + val data1 = serialize(p1, serializer1) + val data2 = serialize(p2, serializer2) + val data = "[ $data1 , $data2 ]" + val url = + serviceManager.getCalls()[function.toString()] ?: throw IllegalStateException("Function not specified!") + return ajaxCall(url, data).then { + try { + deserializeLists<RET>(it, RET::class.js.name) + } catch (t: NonStandardTypeException) { + JSON.parse(RET::class.serializer().list, it) + } + } + } + + /** + * Executes defined call to a remote web service. + */ + inline fun <reified PAR1, reified PAR2, reified PAR3, reified RET : Any, T> call( + noinline function: T.(PAR1, PAR2, PAR3, Request?) -> Deferred<RET>, + p1: PAR1, p2: PAR2, p3: PAR3, serializer1: KSerializer<PAR1>? = null, serializer2: KSerializer<PAR2>? = null, + serializer3: KSerializer<PAR3>? = null + ): Promise<RET> { + val data1 = serialize(p1, serializer1) + val data2 = serialize(p2, serializer2) + val data3 = serialize(p3, serializer3) + val data = "[ $data1 , $data2 , $data3 ]" + val url = + serviceManager.getCalls()[function.toString()] ?: throw IllegalStateException("Function not specified!") + return ajaxCall(url, data).then { + try { + deserialize<RET>(it, RET::class.js.name) + } catch (t: NonStandardTypeException) { + JSON.parse(RET::class.serializer(), it) + } + } + } + + /** + * Executes defined call to a remote web service. + */ + inline fun <reified PAR1, reified PAR2, reified PAR3, reified RET : Any, T> call( + noinline function: T.(PAR1, PAR2, PAR3, Request?) -> Deferred<List<RET>>, + p1: PAR1, p2: PAR2, p3: PAR3, serializer1: KSerializer<PAR1>? = null, serializer2: KSerializer<PAR2>? = null, + serializer3: KSerializer<PAR3>? = null + ): Promise<List<RET>> { + val data1 = serialize(p1, serializer1) + val data2 = serialize(p2, serializer2) + val data3 = serialize(p3, serializer3) + val data = "[ $data1 , $data2 , $data3 ]" + val url = + serviceManager.getCalls()[function.toString()] ?: throw IllegalStateException("Function not specified!") + return ajaxCall(url, data).then { + try { + deserializeLists<RET>(it, RET::class.js.name) + } catch (t: NonStandardTypeException) { + JSON.parse(RET::class.serializer().list, it) + } + } + } + + /** + * Executes defined call to a remote web service. + */ + inline fun <reified PAR1, reified PAR2, reified PAR3, reified PAR4, reified RET : Any, T> call( + noinline function: T.(PAR1, PAR2, PAR3, PAR4, Request?) -> Deferred<RET>, + p1: PAR1, + p2: PAR2, + p3: PAR3, + p4: PAR4, + serializer1: KSerializer<PAR1>? = null, + serializer2: KSerializer<PAR2>? = null, + serializer3: KSerializer<PAR3>? = null, + serializer4: KSerializer<PAR4>? = null + ): Promise<RET> { + val data1 = serialize(p1, serializer1) + val data2 = serialize(p2, serializer2) + val data3 = serialize(p3, serializer3) + val data4 = serialize(p4, serializer4) + val data = "[ $data1 , $data2 , $data3 , $data4 ]" + val url = + serviceManager.getCalls()[function.toString()] ?: throw IllegalStateException("Function not specified!") + return ajaxCall(url, data).then { + try { + deserialize<RET>(it, RET::class.js.name) + } catch (t: NonStandardTypeException) { + JSON.parse(RET::class.serializer(), it) + } + } + } + + /** + * Executes defined call to a remote web service. + */ + inline fun <reified PAR1, reified PAR2, reified PAR3, reified PAR4, reified RET : Any, T> call( + noinline function: T.(PAR1, PAR2, PAR3, PAR4, Request?) -> Deferred<List<RET>>, + p1: PAR1, + p2: PAR2, + p3: PAR3, + p4: PAR4, + serializer1: KSerializer<PAR1>? = null, + serializer2: KSerializer<PAR2>? = null, + serializer3: KSerializer<PAR3>? = null, + serializer4: KSerializer<PAR4>? = null + ): Promise<List<RET>> { + val data1 = serialize(p1, serializer1) + val data2 = serialize(p2, serializer2) + val data3 = serialize(p3, serializer3) + val data4 = serialize(p4, serializer4) + val data = "[ $data1 , $data2 , $data3 , $data4 ]" + val url = + serviceManager.getCalls()[function.toString()] ?: throw IllegalStateException("Function not specified!") + return ajaxCall(url, data).then { + try { + deserializeLists<RET>(it, RET::class.js.name) + } catch (t: NonStandardTypeException) { + JSON.parse(RET::class.serializer().list, it) + } + } + } + + /** + * Executes defined call to a remote web service. + */ + @Suppress("LongParameterList") + inline fun <reified PAR1, reified PAR2, reified PAR3, reified PAR4, reified PAR5, + reified RET : Any, T> call( + noinline function: T.(PAR1, PAR2, PAR3, PAR4, PAR5, Request?) -> Deferred<RET>, + p1: PAR1, + p2: PAR2, + p3: PAR3, + p4: PAR4, + p5: PAR5, + serializer1: KSerializer<PAR1>? = null, + serializer2: KSerializer<PAR2>? = null, + serializer3: KSerializer<PAR3>? = null, + serializer4: KSerializer<PAR4>? = null, + serializer5: KSerializer<PAR5>? = null + ): Promise<RET> { + val data1 = serialize(p1, serializer1) + val data2 = serialize(p2, serializer2) + val data3 = serialize(p3, serializer3) + val data4 = serialize(p4, serializer4) + val data5 = serialize(p5, serializer5) + val data = "[ $data1 , $data2 , $data3 , $data4 , $data5 ]" + val url = + serviceManager.getCalls()[function.toString()] ?: throw IllegalStateException("Function not specified!") + return ajaxCall(url, data).then { + try { + deserialize<RET>(it, RET::class.js.name) + } catch (t: NonStandardTypeException) { + JSON.parse(RET::class.serializer(), it) + } + } + } + + /** + * Executes defined call to a remote web service. + */ + @Suppress("LongParameterList") + inline fun <reified PAR1, reified PAR2, reified PAR3, reified PAR4, reified PAR5, + reified RET : Any, T> call( + noinline function: T.(PAR1, PAR2, PAR3, PAR4, PAR5, Request?) -> Deferred<List<RET>>, + p1: PAR1, + p2: PAR2, + p3: PAR3, + p4: PAR4, + p5: PAR5, + serializer1: KSerializer<PAR1>? = null, + serializer2: KSerializer<PAR2>? = null, + serializer3: KSerializer<PAR3>? = null, + serializer4: KSerializer<PAR4>? = null, + serializer5: KSerializer<PAR5>? = null + ): Promise<List<RET>> { + val data1 = serialize(p1, serializer1) + val data2 = serialize(p2, serializer2) + val data3 = serialize(p3, serializer3) + val data4 = serialize(p4, serializer4) + val data5 = serialize(p5, serializer5) + val data = "[ $data1 , $data2 , $data3 , $data4 , $data5 ]" + val url = + serviceManager.getCalls()[function.toString()] ?: throw IllegalStateException("Function not specified!") + return ajaxCall(url, data).then { + try { + deserializeLists<RET>(it, RET::class.js.name) + } catch (t: NonStandardTypeException) { + JSON.parse(RET::class.serializer().list, it) + } + } + } + + /** + * @suppress + * Internal function + */ + @Suppress("UnsafeCastFromDynamic") + fun ajaxCall(url: String, data: Any?): Promise<String> = + Promise({ resolve, reject -> + jQuery.ajax(url, obj { + this.contentType = "application/json" + this.data = data + this.method = "POST" + this.success = + { data: Any, _: Any, _: Any -> + resolve(NativeJSON.stringify(data)) + } + this.error = + { xhr: JQueryXHR, _: String, errorText: String -> + val message = if (xhr.responseJSON != null && xhr.responseJSON != undefined) { + xhr.responseJSON.toString() + } else { + errorText + } + reject(Exception(message)) + } + }) + }) + + /** + * @suppress + * Internal function + */ + @Suppress("TooGenericExceptionCaught") + inline fun <reified PAR> serialize(value: PAR, serializer: KSerializer<PAR>?): String? { + return value?.let { + if (serializer != null) { + JSON.stringify(serializer, it) + } else { + try { + @Suppress("UNCHECKED_CAST") + JSON.stringify((PAR::class as KClass<Any>).serializer(), it as Any) + } catch (e: Throwable) { + it.toString() + } + } + } + } + + /** + * @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 + * 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) + } + } +} diff --git a/src/main/kotlin/pl/treksoft/kvision/remote/ServiceManager.kt b/src/main/kotlin/pl/treksoft/kvision/remote/ServiceManager.kt new file mode 100644 index 00000000..cd42f038 --- /dev/null +++ b/src/main/kotlin/pl/treksoft/kvision/remote/ServiceManager.kt @@ -0,0 +1,117 @@ +/* + * 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.remote + +import kotlinx.coroutines.experimental.Deferred + +/** + * Multiplatform service manager. + */ +actual open class ServiceManager<out T> actual constructor(service: T?) { + protected val calls: MutableMap<String, String> = mutableMapOf() + + /** + * Binds a given route with a function of the receiver. + * @param route a route + * @param function a function of the receiver + */ + protected actual inline fun <reified RET> bind( + route: String, + noinline function: T.(Request?) -> Deferred<RET> + ) { + calls[function.toString()] = "$SERVICE_PREFIX/$route" + } + + /** + * Binds a given route with a function of the receiver. + * @param route a route + * @param function a function of the receiver + */ + protected actual inline fun <reified PAR, reified RET> bind( + route: String, + noinline function: T.(PAR, Request?) -> Deferred<RET> + ) { + calls[function.toString()] = "$SERVICE_PREFIX/$route" + } + + /** + * Binds a given route with a function of the receiver. + * @param route a route + * @param function a function of the receiver + */ + protected actual inline fun <reified PAR1, reified PAR2, reified RET> bind( + route: String, + noinline function: T.(PAR1, PAR2, Request?) -> Deferred<RET> + ) { + calls[function.toString()] = "$SERVICE_PREFIX/$route" + } + + /** + * Binds a given route with a function of the receiver. + * @param route a route + * @param function a function of the receiver + */ + protected actual inline fun <reified PAR1, reified PAR2, reified PAR3, reified RET> bind( + route: String, + noinline function: T.(PAR1, PAR2, PAR3, Request?) -> Deferred<RET> + ) { + calls[function.toString()] = "$SERVICE_PREFIX/$route" + } + + /** + * Binds a given route with a function of the receiver. + * @param route a route + * @param function a function of the receiver + */ + protected actual inline fun <reified PAR1, reified PAR2, reified PAR3, reified PAR4, reified RET> bind( + route: String, + noinline function: T.(PAR1, PAR2, PAR3, PAR4, Request?) -> Deferred<RET> + ) { + calls[function.toString()] = "$SERVICE_PREFIX/$route" + } + + /** + * Binds a given route with a function of the receiver. + * @param route a route + * @param function a function of the receiver + */ + protected actual inline fun <reified PAR1, reified PAR2, reified PAR3, + reified PAR4, reified PAR5, reified RET> bind( + route: String, + noinline function: T.(PAR1, PAR2, PAR3, PAR4, PAR5, Request?) -> Deferred<RET> + ) { + calls[function.toString()] = "$SERVICE_PREFIX/$route" + } + + /** + * Applies all defined routes to the given server. + * Not used on the js platform. + */ + actual fun applyRoutes(k: JoobyServer) { + } + + /** + * Returns the list of defined bindings. + * Not used on the jvm platform. + */ + actual fun getCalls(): Map<String, String> = calls +} diff --git a/src/main/kotlin/pl/treksoft/kvision/types/KDate.kt b/src/main/kotlin/pl/treksoft/kvision/types/KDate.kt new file mode 100644 index 00000000..798a02be --- /dev/null +++ b/src/main/kotlin/pl/treksoft/kvision/types/KDate.kt @@ -0,0 +1,39 @@ +/* + * 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 pl.treksoft.kvision.utils.toDateF +import pl.treksoft.kvision.utils.toStringF +import kotlin.js.Date + +@Suppress("MayBeConstant", "TopLevelPropertyNaming") +actual val KDATE_FORMAT = "YYYY-MM-DD HH:mm:ss" + +internal actual fun nowDate(): KDate = + KDate(Date().getTime().toLong()) + +internal actual fun String.toKDateF(format: String): KDate = + KDate(this.toDateF(format).getTime().toLong()) + +internal 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/test/kotlin/test/pl/treksoft/kvision/form/FormPanelSpec.kt b/src/test/kotlin/test/pl/treksoft/kvision/form/FormPanelSpec.kt index 33b439a5..5c07ca58 100644 --- a/src/test/kotlin/test/pl/treksoft/kvision/form/FormPanelSpec.kt +++ b/src/test/kotlin/test/pl/treksoft/kvision/form/FormPanelSpec.kt @@ -24,8 +24,8 @@ package test.pl.treksoft.kvision.form import pl.treksoft.kvision.form.FormPanel import pl.treksoft.kvision.form.text.Text import pl.treksoft.kvision.form.time.DateTime +import pl.treksoft.kvision.types.KDate import test.pl.treksoft.kvision.SimpleSpec -import kotlin.js.Date import kotlin.test.Test import kotlin.test.assertEquals import kotlin.test.assertNotNull @@ -37,16 +37,8 @@ class FormPanelSpec : SimpleSpec { @Test fun add() { run { - class DataForm(val map: Map<String, Any?>) { - val a: String? by map - val b: Boolean? by map - val c: Date? by map - } - - val formPanel = FormPanel { - DataForm(it) - } - val data = DataForm(mapOf("a" to "Test value")) + val formPanel = FormPanel.create<DataForm>() + val data = DataForm(a = "Test value") formPanel.setData(data) val result = formPanel.getData() assertNull(result.a, "FormPanel should return null without adding any control") @@ -61,16 +53,8 @@ class FormPanelSpec : SimpleSpec { @Test fun remove() { run { - class DataForm(val map: Map<String, Any?>) { - val a: String? by map - val b: Boolean? by map - val c: Date? by map - } - - val formPanel = FormPanel { - DataForm(it) - } - val data = DataForm(mapOf("a" to "Test value")) + val formPanel = FormPanel.create<DataForm>() + val data = DataForm(a = "Test value") formPanel.add(DataForm::a, Text()) formPanel.setData(data) formPanel.remove(DataForm::a) @@ -82,16 +66,8 @@ class FormPanelSpec : SimpleSpec { @Test fun removeAll() { run { - class DataForm(val map: Map<String, Any?>) { - val a: String? by map - val b: Boolean? by map - val c: Date? by map - } - - val formPanel = FormPanel { - DataForm(it) - } - val data = DataForm(mapOf("a" to "Test value")) + val formPanel = FormPanel.create<DataForm>() + val data = DataForm(a = "Test value") formPanel.add(DataForm::a, Text()) formPanel.setData(data) formPanel.removeAll() @@ -103,15 +79,7 @@ class FormPanelSpec : SimpleSpec { @Test fun getControl() { run { - class DataForm(val map: Map<String, Any?>) { - val a: String? by map - val b: Boolean? by map - val c: Date? by map - } - - val formPanel = FormPanel { - DataForm(it) - } + val formPanel = FormPanel.create<DataForm>() formPanel.add(DataForm::a, Text()) val control = formPanel.getControl(DataForm::b) assertNull(control, "Should return null when there is no such control") @@ -123,16 +91,8 @@ class FormPanelSpec : SimpleSpec { @Test fun get() { run { - class DataForm(val map: Map<String, Any?>) { - val a: String? by map - val b: Boolean? by map - val c: Date? by map - } - - val formPanel = FormPanel { - DataForm(it) - } - val data = DataForm(mapOf("a" to "Test value")) + val formPanel = FormPanel.create<DataForm>() + val data = DataForm(a = "Test value") formPanel.add(DataForm::a, Text()) val b = formPanel[DataForm::b] assertNull(b, "Should return null value when there is no added control") @@ -147,16 +107,8 @@ class FormPanelSpec : SimpleSpec { @Test fun getData() { run { - class DataForm(val map: Map<String, Any?>) { - val a: String? by map - val b: Boolean? by map - val c: Date? by map - } - - val formPanel = FormPanel { - DataForm(it) - } - val data = DataForm(mapOf("a" to "Test value")) + val formPanel = FormPanel.create<DataForm>() + val data = DataForm(a = "Test value") val textField = Text() formPanel.add(DataForm::a, textField) formPanel.setData(data) @@ -169,25 +121,18 @@ class FormPanelSpec : SimpleSpec { @Test fun validate() { run { - class DataForm(val map: Map<String, Any?>) { - val s: String? by map - val d: Date? by map - } - - val formPanel = FormPanel { - DataForm(it) - } - formPanel.add(DataForm::s, Text()) { + val formPanel = FormPanel.create<DataForm2>() + formPanel.add(DataForm2::s, Text()) { it.getValue()?.length ?: 0 > 4 } - formPanel.add(DataForm::d, DateTime(), required = true) - formPanel.setData(DataForm(mapOf("s" to "123"))) + formPanel.add(DataForm2::d, DateTime(), required = true) + formPanel.setData(DataForm2(s = "123")) val valid = formPanel.validate() assertEquals(false, valid, "Should be invalid with initial data") - formPanel.setData(DataForm(mapOf("s" to "12345"))) + formPanel.setData(DataForm2(s = "12345")) val valid2 = formPanel.validate() assertEquals(false, valid2, "Should be invalid with partially changed data") - formPanel.setData(DataForm(mapOf("s" to "12345", "d" to Date()))) + formPanel.setData(DataForm2(s = "12345", d = KDate())) val valid3 = formPanel.validate() assertEquals(true, valid3, "Should be valid") } diff --git a/src/test/kotlin/test/pl/treksoft/kvision/form/FormSpec.kt b/src/test/kotlin/test/pl/treksoft/kvision/form/FormSpec.kt index ee3cd2af..f673018a 100644 --- a/src/test/kotlin/test/pl/treksoft/kvision/form/FormSpec.kt +++ b/src/test/kotlin/test/pl/treksoft/kvision/form/FormSpec.kt @@ -21,32 +21,39 @@ */ package test.pl.treksoft.kvision.form +import kotlinx.serialization.Serializable import pl.treksoft.kvision.form.Form import pl.treksoft.kvision.form.text.Text import pl.treksoft.kvision.form.time.DateTime +import pl.treksoft.kvision.types.KDate import test.pl.treksoft.kvision.SimpleSpec -import kotlin.js.Date import kotlin.test.Test import kotlin.test.assertEquals import kotlin.test.assertNotNull import kotlin.test.assertNull +@Serializable +data class DataForm( + val a: String? = null, + val b: Boolean? = null, + val c: KDate? = null +) + +@Serializable +data class DataForm2( + val s: String? = null, + val d: KDate? = null +) + + @Suppress("CanBeParameter") class FormSpec : SimpleSpec { @Test fun add() { run { - class DataForm(val map: Map<String, Any?>) { - val a: String? by map - val b: Boolean? by map - val c: Date? by map - } - - val form = Form { - DataForm(it) - } - val data = DataForm(mapOf("a" to "Test value")) + val form = Form.create<DataForm>() + val data = DataForm(a = "Test value") form.setData(data) val result = form.getData() assertNull(result.a, "Form should return null without adding any control") @@ -61,16 +68,8 @@ class FormSpec : SimpleSpec { @Test fun remove() { run { - class DataForm(val map: Map<String, Any?>) { - val a: String? by map - val b: Boolean? by map - val c: Date? by map - } - - val form = Form { - DataForm(it) - } - val data = DataForm(mapOf("a" to "Test value")) + val form = Form.create<DataForm>() + val data = DataForm(a = "Test value") form.add(DataForm::a, Text()) form.setData(data) form.remove(DataForm::a) @@ -82,16 +81,8 @@ class FormSpec : SimpleSpec { @Test fun removeAll() { run { - class DataForm(val map: Map<String, Any?>) { - val a: String? by map - val b: Boolean? by map - val c: Date? by map - } - - val form = Form { - DataForm(it) - } - val data = DataForm(mapOf("a" to "Test value")) + val form = Form.create<DataForm>() + val data = DataForm(a = "Test value") form.add(DataForm::a, Text()) form.setData(data) form.removeAll() @@ -103,15 +94,7 @@ class FormSpec : SimpleSpec { @Test fun getControl() { run { - class DataForm(val map: Map<String, Any?>) { - val a: String? by map - val b: Boolean? by map - val c: Date? by map - } - - val form = Form { - DataForm(it) - } + val form = Form.create<DataForm>() form.add(DataForm::a, Text()) val control = form.getControl(DataForm::b) assertNull(control, "Should return null when there is no such control") @@ -123,16 +106,8 @@ class FormSpec : SimpleSpec { @Test fun get() { run { - class DataForm(val map: Map<String, Any?>) { - val a: String? by map - val b: Boolean? by map - val c: Date? by map - } - - val form = Form { - DataForm(it) - } - val data = DataForm(mapOf("a" to "Test value")) + val form = Form.create<DataForm>() + val data = DataForm(a = "Test value") form.add(DataForm::a, Text()) val b = form[DataForm::b] assertNull(b, "Should return null value when there is no added control") @@ -147,16 +122,8 @@ class FormSpec : SimpleSpec { @Test fun getData() { run { - class DataForm(val map: Map<String, Any?>) { - val a: String? by map - val b: Boolean? by map - val c: Date? by map - } - - val form = Form { - DataForm(it) - } - val data = DataForm(mapOf("a" to "Test value")) + val form = Form.create<DataForm>() + val data = DataForm(a = "Test value") val textField = Text() form.add(DataForm::a, textField) form.setData(data) @@ -169,25 +136,18 @@ class FormSpec : SimpleSpec { @Test fun validate() { run { - class DataForm(val map: Map<String, Any?>) { - val s: String? by map - val d: Date? by map - } - - val form = Form { - DataForm(it) - } - form.add(DataForm::s, Text()) { + val form = Form.create<DataForm2>() + form.add(DataForm2::s, Text()) { it.getValue()?.length ?: 0 > 4 } - form.add(DataForm::d, DateTime(), required = true) - form.setData(DataForm(mapOf("s" to "123"))) + form.add(DataForm2::d, DateTime(), required = true) + form.setData(DataForm2(s = "123")) val valid = form.validate() assertEquals(false, valid, "Should be invalid with initial data") - form.setData(DataForm(mapOf("s" to "12345"))) + form.setData(DataForm2(s = "12345")) val valid2 = form.validate() assertEquals(false, valid2, "Should be invalid with partially changed data") - form.setData(DataForm(mapOf("s" to "12345", "d" to Date()))) + form.setData(DataForm2(s = "12345", d = KDate())) val valid3 = form.validate() assertEquals(true, valid3, "Should be valid") } diff --git a/src/test/kotlin/test/pl/treksoft/kvision/form/time/DateTimeInputSpec.kt b/src/test/kotlin/test/pl/treksoft/kvision/form/time/DateTimeInputSpec.kt index fed0a1f4..d824125b 100644 --- a/src/test/kotlin/test/pl/treksoft/kvision/form/time/DateTimeInputSpec.kt +++ b/src/test/kotlin/test/pl/treksoft/kvision/form/time/DateTimeInputSpec.kt @@ -21,11 +21,11 @@ */ package test.pl.treksoft.kvision.form.time -import pl.treksoft.kvision.panel.Root import pl.treksoft.kvision.form.time.DateTimeInput -import pl.treksoft.kvision.utils.toStringF +import pl.treksoft.kvision.panel.Root +import pl.treksoft.kvision.types.KDate +import pl.treksoft.kvision.types.toStringF import test.pl.treksoft.kvision.DomSpec -import kotlin.js.Date import kotlin.test.Test import kotlin.test.assertEquals @@ -35,7 +35,7 @@ class DateTimeInputSpec : DomSpec { fun render() { run { val root = Root("test", true) - val data = Date() + val data = KDate() val dti = DateTimeInput(value = data).apply { placeholder = "place" id = "idti" diff --git a/src/test/kotlin/test/pl/treksoft/kvision/form/time/DateTimeSpec.kt b/src/test/kotlin/test/pl/treksoft/kvision/form/time/DateTimeSpec.kt index 76dc273b..482a7b7a 100644 --- a/src/test/kotlin/test/pl/treksoft/kvision/form/time/DateTimeSpec.kt +++ b/src/test/kotlin/test/pl/treksoft/kvision/form/time/DateTimeSpec.kt @@ -23,10 +23,10 @@ package test.pl.treksoft.kvision.form.time import pl.treksoft.kvision.form.time.DateTime import pl.treksoft.kvision.panel.Root -import pl.treksoft.kvision.utils.toStringF +import pl.treksoft.kvision.types.KDate +import pl.treksoft.kvision.types.toStringF import test.pl.treksoft.kvision.DomSpec import kotlin.browser.document -import kotlin.js.Date import kotlin.test.Test class DateTimeSpec : DomSpec { @@ -35,7 +35,7 @@ class DateTimeSpec : DomSpec { fun render() { run { val root = Root("test", true) - val data = Date() + val data = KDate() val ti = DateTime(value = data, label = "Label").apply { placeholder = "place" name = "name" |