aboutsummaryrefslogtreecommitdiff
path: root/src/main/kotlin/pl/treksoft/kvision/form
diff options
context:
space:
mode:
authorRobert Jaros <rjaros@finn.pl>2018-04-25 08:12:25 +0200
committerRobert Jaros <rjaros@finn.pl>2018-04-25 08:12:25 +0200
commit5b9535e9964816eb228d3797f4c8a3e7676d1f53 (patch)
tree00889e3c489288d6386367e8ac26973868e11f8f /src/main/kotlin/pl/treksoft/kvision/form
parent76c436567b87672609879a11762202599ed27af4 (diff)
downloadkvision-5b9535e9964816eb228d3797f4c8a3e7676d1f53.tar.gz
kvision-5b9535e9964816eb228d3797f4c8a3e7676d1f53.tar.bz2
kvision-5b9535e9964816eb228d3797f4c8a3e7676d1f53.zip
Multiplatform kvision-common and kvision-server modules.
Support for automatic remote bindings (work in progress).
Diffstat (limited to 'src/main/kotlin/pl/treksoft/kvision/form')
-rw-r--r--src/main/kotlin/pl/treksoft/kvision/form/Form.kt111
-rw-r--r--src/main/kotlin/pl/treksoft/kvision/form/FormControl.kt18
-rw-r--r--src/main/kotlin/pl/treksoft/kvision/form/FormPanel.kt58
-rw-r--r--src/main/kotlin/pl/treksoft/kvision/form/time/DateTime.kt10
-rw-r--r--src/main/kotlin/pl/treksoft/kvision/form/time/DateTimeInput.kt15
-rw-r--r--src/main/kotlin/pl/treksoft/kvision/form/upload/Upload.kt15
-rw-r--r--src/main/kotlin/pl/treksoft/kvision/form/upload/UploadInput.kt25
7 files changed, 173 insertions, 79 deletions
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
+ }
}
/**