├── modules
├── viform-core
│ ├── src
│ │ ├── androidMain
│ │ │ └── AndroidManifest.xml
│ │ └── commonMain
│ │ │ └── kotlin
│ │ │ └── io
│ │ │ └── github.windedge.viform.core
│ │ │ ├── ValidatorContainer.kt
│ │ │ ├── FormSchema.kt
│ │ │ ├── ValidateResult.kt
│ │ │ ├── String.kt
│ │ │ ├── FormHost.kt
│ │ │ ├── FormField.kt
│ │ │ ├── Form.kt
│ │ │ ├── ValidatorContainerExtension.kt
│ │ │ └── FieldValidator.kt
│ ├── gradle.properties
│ └── build.gradle.kts
├── viform-compose
│ ├── src
│ │ ├── androidMain
│ │ │ └── AndroidManifest.xml
│ │ └── commonMain
│ │ │ └── kotlin
│ │ │ └── Composable.kt
│ ├── gradle.properties
│ └── build.gradle.kts
└── viform-orbitmvi
│ ├── gradle.properties
│ ├── build.gradle.kts
│ └── src
│ └── commonMain
│ └── kotlin
│ └── FormContainerHost.kt
├── gradle
├── wrapper
│ ├── gradle-wrapper.jar
│ └── gradle-wrapper.properties
└── libs.versions.toml
├── sandbox
├── signupapp
│ ├── src
│ │ ├── androidMain
│ │ │ ├── res
│ │ │ │ ├── values
│ │ │ │ │ └── strings.xml
│ │ │ │ ├── mipmap-hdpi
│ │ │ │ │ ├── ic_launcher.png
│ │ │ │ │ └── ic_launcher_round.png
│ │ │ │ ├── mipmap-mdpi
│ │ │ │ │ ├── ic_launcher.png
│ │ │ │ │ └── ic_launcher_round.png
│ │ │ │ ├── mipmap-xhdpi
│ │ │ │ │ ├── ic_launcher.png
│ │ │ │ │ └── ic_launcher_round.png
│ │ │ │ ├── mipmap-xxhdpi
│ │ │ │ │ ├── ic_launcher.png
│ │ │ │ │ └── ic_launcher_round.png
│ │ │ │ ├── mipmap-xxxhdpi
│ │ │ │ │ ├── ic_launcher.png
│ │ │ │ │ └── ic_launcher_round.png
│ │ │ │ ├── mipmap-anydpi-v26
│ │ │ │ │ ├── ic_launcher.xml
│ │ │ │ │ └── ic_launcher_round.xml
│ │ │ │ ├── drawable-v24
│ │ │ │ │ └── ic_launcher_foreground.xml
│ │ │ │ └── drawable
│ │ │ │ │ └── ic_launcher_background.xml
│ │ │ ├── kotlin
│ │ │ │ └── MainActivity.kt
│ │ │ └── AndroidManifest.xml
│ │ ├── wasmJsMain
│ │ │ ├── kotlin
│ │ │ │ └── main.kt
│ │ │ └── resources
│ │ │ │ └── index.html
│ │ ├── commonMain
│ │ │ └── kotlin
│ │ │ │ ├── Signup.kt
│ │ │ │ └── SignupApp.kt
│ │ └── desktopMain
│ │ │ └── kotlin
│ │ │ └── main.kt
│ └── build.gradle.kts
├── gradle
│ └── wrapper
│ │ ├── gradle-wrapper.jar
│ │ └── gradle-wrapper.properties
├── build.gradle.kts
├── gradle.properties
├── settings.gradle.kts
├── gradlew.bat
└── gradlew
├── renovate.json
├── .gitignore
├── .editorconfig
├── settings.gradle.kts
├── LICENSE
├── .github
└── workflows
│ ├── publish.yml
│ └── release.yml
├── gradle.properties
├── gradlew.bat
├── README-CN.md
├── README.md
├── gradlew
└── kotlin-js-store
└── yarn.lock
/modules/viform-core/src/androidMain/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
--------------------------------------------------------------------------------
/modules/viform-compose/src/androidMain/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
--------------------------------------------------------------------------------
/modules/viform-core/gradle.properties:
--------------------------------------------------------------------------------
1 | POM_ARTIFACT_ID=viform-core
2 | POM_NAME=Viform Core Library
3 |
--------------------------------------------------------------------------------
/modules/viform-compose/gradle.properties:
--------------------------------------------------------------------------------
1 | POM_ARTIFACT_ID=viform-compose
2 | POM_NAME=Viform Compose Library
3 |
--------------------------------------------------------------------------------
/modules/viform-orbitmvi/gradle.properties:
--------------------------------------------------------------------------------
1 | POM_ARTIFACT_ID=viform-orbitmvi
2 | POM_NAME=Viform OrbitMVI Library
3 |
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/windedge/viform-multiplatform/HEAD/gradle/wrapper/gradle-wrapper.jar
--------------------------------------------------------------------------------
/sandbox/signupapp/src/androidMain/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 | Signup
3 |
--------------------------------------------------------------------------------
/renovate.json:
--------------------------------------------------------------------------------
1 | {
2 | "$schema": "https://docs.renovatebot.com/renovate-schema.json",
3 | "extends": [
4 | "config:base"
5 | ]
6 | }
7 |
--------------------------------------------------------------------------------
/sandbox/gradle/wrapper/gradle-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/windedge/viform-multiplatform/HEAD/sandbox/gradle/wrapper/gradle-wrapper.jar
--------------------------------------------------------------------------------
/sandbox/signupapp/src/androidMain/res/mipmap-hdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/windedge/viform-multiplatform/HEAD/sandbox/signupapp/src/androidMain/res/mipmap-hdpi/ic_launcher.png
--------------------------------------------------------------------------------
/sandbox/signupapp/src/androidMain/res/mipmap-mdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/windedge/viform-multiplatform/HEAD/sandbox/signupapp/src/androidMain/res/mipmap-mdpi/ic_launcher.png
--------------------------------------------------------------------------------
/sandbox/signupapp/src/androidMain/res/mipmap-xhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/windedge/viform-multiplatform/HEAD/sandbox/signupapp/src/androidMain/res/mipmap-xhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/sandbox/signupapp/src/androidMain/res/mipmap-xxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/windedge/viform-multiplatform/HEAD/sandbox/signupapp/src/androidMain/res/mipmap-xxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/sandbox/signupapp/src/androidMain/res/mipmap-xxxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/windedge/viform-multiplatform/HEAD/sandbox/signupapp/src/androidMain/res/mipmap-xxxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/sandbox/signupapp/src/androidMain/res/mipmap-hdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/windedge/viform-multiplatform/HEAD/sandbox/signupapp/src/androidMain/res/mipmap-hdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/sandbox/signupapp/src/androidMain/res/mipmap-mdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/windedge/viform-multiplatform/HEAD/sandbox/signupapp/src/androidMain/res/mipmap-mdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/sandbox/signupapp/src/androidMain/res/mipmap-xhdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/windedge/viform-multiplatform/HEAD/sandbox/signupapp/src/androidMain/res/mipmap-xhdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/sandbox/signupapp/src/androidMain/res/mipmap-xxhdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/windedge/viform-multiplatform/HEAD/sandbox/signupapp/src/androidMain/res/mipmap-xxhdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/sandbox/signupapp/src/androidMain/res/mipmap-xxxhdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/windedge/viform-multiplatform/HEAD/sandbox/signupapp/src/androidMain/res/mipmap-xxxhdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | .gradle/
2 | .idea/
3 | .vscode/
4 | .kotlin/
5 | build/
6 | out/
7 | dist/
8 | local.properties
9 | lint.xml
10 | *.hprof
11 | *.out
12 | *.log
13 | *.bak.*
14 | *.cmd
15 | .aider.*
16 | .excludes.txt
17 | tasks.py
18 | fabfile.py
19 |
--------------------------------------------------------------------------------
/sandbox/build.gradle.kts:
--------------------------------------------------------------------------------
1 | description = "Local consumer sandbox"
2 |
3 | subprojects {
4 | repositories {
5 | mavenLocal()
6 | google()
7 | mavenCentral()
8 | maven("https://s01.oss.sonatype.org/content/repositories/snapshots")
9 | }
10 | }
11 |
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.properties:
--------------------------------------------------------------------------------
1 | distributionBase=GRADLE_USER_HOME
2 | distributionPath=wrapper/dists
3 | distributionUrl=https\://services.gradle.org/distributions/gradle-8.5-bin.zip
4 | networkTimeout=10000
5 | validateDistributionUrl=true
6 | zipStoreBase=GRADLE_USER_HOME
7 | zipStorePath=wrapper/dists
8 |
--------------------------------------------------------------------------------
/sandbox/gradle/wrapper/gradle-wrapper.properties:
--------------------------------------------------------------------------------
1 | distributionBase=GRADLE_USER_HOME
2 | distributionPath=wrapper/dists
3 | distributionUrl=https\://services.gradle.org/distributions/gradle-8.5-bin.zip
4 | networkTimeout=10000
5 | validateDistributionUrl=true
6 | zipStoreBase=GRADLE_USER_HOME
7 | zipStorePath=wrapper/dists
8 |
--------------------------------------------------------------------------------
/sandbox/signupapp/src/androidMain/res/mipmap-anydpi-v26/ic_launcher.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
--------------------------------------------------------------------------------
/.editorconfig:
--------------------------------------------------------------------------------
1 | root = true
2 |
3 | [*.kt]
4 | indent_size = 4
5 | continuation_indent_size = 4
6 | ij_kotlin_name_count_to_use_star_import = unset
7 | disabled_rules = no-wildcard-imports
8 |
9 | [*.kts]
10 | indent_size = 2
11 | continuation_indent_size = 4
12 | ij_kotlin_name_count_to_use_star_import = unset
13 | disabled_rules = no-wildcard-imports
14 |
--------------------------------------------------------------------------------
/sandbox/signupapp/src/androidMain/res/mipmap-anydpi-v26/ic_launcher_round.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
--------------------------------------------------------------------------------
/sandbox/signupapp/src/wasmJsMain/kotlin/main.kt:
--------------------------------------------------------------------------------
1 | package local.sandbox.signupapp
2 |
3 | import androidx.compose.ui.ExperimentalComposeUiApi
4 | import androidx.compose.ui.window.CanvasBasedWindow
5 |
6 | @OptIn(ExperimentalComposeUiApi::class)
7 | fun main() {
8 | CanvasBasedWindow(canvasElementId = "root") {
9 | SignupApp()
10 | }
11 | }
--------------------------------------------------------------------------------
/modules/viform-core/src/commonMain/kotlin/io/github.windedge.viform.core/ValidatorContainer.kt:
--------------------------------------------------------------------------------
1 | package io.github.windedge.viform.core
2 |
3 | public interface ValidatorContainer {
4 |
5 | public fun addValidator(validator: FieldValidator)
6 |
7 | public fun getValidators(): List>
8 |
9 | public fun clearValidators()
10 |
11 | }
12 |
--------------------------------------------------------------------------------
/settings.gradle.kts:
--------------------------------------------------------------------------------
1 | pluginManagement {
2 | repositories {
3 | gradlePluginPortal()
4 | mavenCentral()
5 | google()
6 | mavenLocal()
7 | }
8 | }
9 |
10 |
11 | rootProject.name = "viform-multiplatform"
12 |
13 | include(
14 | // ":modules:viform-ksp",
15 | ":modules:viform-core",
16 | ":modules:viform-compose",
17 | ":modules:viform-orbitmvi",
18 | )
19 |
--------------------------------------------------------------------------------
/sandbox/signupapp/src/wasmJsMain/resources/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | Signup
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
--------------------------------------------------------------------------------
/sandbox/signupapp/src/commonMain/kotlin/Signup.kt:
--------------------------------------------------------------------------------
1 | package local.sandbox.signupapp
2 |
3 | import io.github.windedge.copybuilder.KopyBuilder
4 | import io.github.windedge.viform.core.*
5 |
6 | @KopyBuilder
7 | data class Signup(
8 | val name: String = "",
9 | val email: String? = null,
10 | val age: Int? = null,
11 | val password: String = "",
12 | val confirmPassword: String = "",
13 | val accept: Boolean = false,
14 | )
15 |
--------------------------------------------------------------------------------
/modules/viform-orbitmvi/build.gradle.kts:
--------------------------------------------------------------------------------
1 | plugins {
2 | id(libs.plugins.kotlin.kmp.get().pluginId)
3 | id(libs.plugins.android.library.get().pluginId)
4 | id(libs.plugins.maven.publish.get().pluginId)
5 | }
6 |
7 | android {
8 | namespace = "io.github.windedge.viform.orbitmvi"
9 | }
10 |
11 | kotlin {
12 | sourceSets {
13 | val commonMain by getting {
14 | dependencies {
15 | api(project(":modules:viform-core"))
16 | implementation(libs.kotlinx.coroutines.core)
17 | api(libs.orbitmvi.core)
18 | }
19 | }
20 | }
21 | }
22 |
--------------------------------------------------------------------------------
/sandbox/signupapp/src/desktopMain/kotlin/main.kt:
--------------------------------------------------------------------------------
1 | package local.sandbox.signupapp
2 |
3 | import androidx.compose.material.MaterialTheme
4 | import androidx.compose.ui.unit.dp
5 | import androidx.compose.ui.window.Window
6 | import androidx.compose.ui.window.application
7 | import androidx.compose.ui.window.rememberWindowState
8 |
9 |
10 | fun main() = application {
11 | val winState = rememberWindowState(width = 800.dp, height = 700.dp)
12 | Window(onCloseRequest = ::exitApplication, winState, title = "Sign Up") {
13 | MaterialTheme {
14 | SignupApp()
15 | }
16 | }
17 | }
18 |
19 |
--------------------------------------------------------------------------------
/sandbox/signupapp/src/androidMain/kotlin/MainActivity.kt:
--------------------------------------------------------------------------------
1 | package local.sandbox.signupapp
2 |
3 | import android.os.Bundle
4 | import androidx.activity.ComponentActivity
5 | import androidx.activity.compose.setContent
6 | import androidx.compose.runtime.Composable
7 | import androidx.compose.ui.tooling.preview.Preview
8 |
9 | class MainActivity : ComponentActivity() {
10 | override fun onCreate(savedInstanceState: Bundle?) {
11 | super.onCreate(savedInstanceState)
12 |
13 | setContent {
14 | SignupApp()
15 | }
16 | }
17 | }
18 |
19 | @Preview
20 | @Composable
21 | fun AppAndroidPreview() {
22 | SignupApp()
23 | }
--------------------------------------------------------------------------------
/modules/viform-core/build.gradle.kts:
--------------------------------------------------------------------------------
1 | plugins {
2 | id(libs.plugins.kotlin.kmp.get().pluginId)
3 | id(libs.plugins.android.library.get().pluginId)
4 | id(libs.plugins.maven.publish.get().pluginId)
5 | }
6 |
7 | android {
8 | namespace = "io.github.windedge.viform.core"
9 | }
10 |
11 | kotlin {
12 | sourceSets {
13 | val commonMain by getting {
14 | dependencies {
15 | implementation(libs.kotlinx.coroutines.core)
16 | api(libs.kopybuilder.runtime)
17 | }
18 | }
19 | }
20 |
21 | @OptIn(org.jetbrains.kotlin.gradle.ExperimentalWasmDsl::class)
22 | wasmJs {
23 | browser()
24 | }
25 | }
26 |
--------------------------------------------------------------------------------
/modules/viform-core/src/commonMain/kotlin/io/github.windedge.viform.core/FormSchema.kt:
--------------------------------------------------------------------------------
1 | package io.github.windedge.viform.core
2 |
3 | public class FormSchema private constructor(private val builderBlock: FormBuilder.() -> Unit) {
4 |
5 | public companion object {
6 | public fun create(build: FormBuilder.() -> Unit): FormSchema {
7 | val formSchema = FormSchema(build)
8 | return formSchema
9 | }
10 | }
11 |
12 | public fun buildForm(formData: T): Form {
13 | val form = FormImpl(formData).apply {
14 | FormBuilder(this).apply(builderBlock)
15 | }
16 | return form
17 | }
18 | }
19 |
--------------------------------------------------------------------------------
/sandbox/gradle.properties:
--------------------------------------------------------------------------------
1 | # Makes sure we can debug our Kotlin plugin with breakpoints
2 | kotlin.compiler.execution.strategy=in-process
3 | org.gradle.jvmargs=-Xmx3g
4 | kotlin.native.cacheKind=none
5 | kotlin.mpp.androidSourceSetLayoutVersion=2
6 | kotlin.mpp.applyDefaultHierarchyTemplate=false
7 | kotlin.native.useEmbeddableCompilerJar=true
8 | # Enable kotlin/native experimental memory model
9 | kotlin.native.binary.memoryModel=experimental
10 | kotlin.js.ir.output.granularity=whole-program
11 | org.jetbrains.compose.experimental.jscanvas.enabled=true
12 | #Compose for Web is Experimental
13 | org.jetbrains.compose.experimental.wasm.enabled=true
14 | android.useAndroidX=true
15 | android.nonTransitiveRClass=true
--------------------------------------------------------------------------------
/modules/viform-core/src/commonMain/kotlin/io/github.windedge.viform.core/ValidateResult.kt:
--------------------------------------------------------------------------------
1 | package io.github.windedge.viform.core
2 |
3 | public sealed class ValidateResult {
4 |
5 | public object None : ValidateResult()
6 |
7 | public object Success : ValidateResult()
8 |
9 | public class Failure(public val message: String) : ValidateResult()
10 |
11 | public val isSuccess: Boolean get() = this is None || this is Success
12 |
13 | public val isError: Boolean get() = this is Failure
14 |
15 | public val errorMessage: String?
16 | get() {
17 | if (this is Failure) {
18 | return this.message
19 | }
20 | return null
21 | }
22 | }
--------------------------------------------------------------------------------
/modules/viform-compose/build.gradle.kts:
--------------------------------------------------------------------------------
1 | plugins {
2 | id(libs.plugins.kotlin.kmp.get().pluginId)
3 | id(libs.plugins.android.library.get().pluginId)
4 | id(libs.plugins.compose.get().pluginId)
5 | id(libs.plugins.kotlin.compose.get().pluginId)
6 | id(libs.plugins.maven.publish.get().pluginId)
7 | }
8 |
9 | android {
10 | namespace = "io.github.windedge.viform.compose"
11 | }
12 |
13 | kotlin {
14 | sourceSets {
15 | val commonMain by getting {
16 | dependencies {
17 | api(project(":modules:viform-core"))
18 | implementation(libs.kotlinx.coroutines.core)
19 | implementation(compose.runtime)
20 | }
21 | }
22 | }
23 |
24 | @OptIn(org.jetbrains.kotlin.gradle.ExperimentalWasmDsl::class)
25 | wasmJs {
26 | browser()
27 | }
28 | }
--------------------------------------------------------------------------------
/sandbox/settings.gradle.kts:
--------------------------------------------------------------------------------
1 | pluginManagement {
2 | repositories {
3 | mavenLocal()
4 | gradlePluginPortal()
5 | google()
6 | mavenCentral()
7 | maven("https://s01.oss.sonatype.org/content/repositories/snapshots")
8 | }
9 | }
10 |
11 | dependencyResolutionManagement {
12 | versionCatalogs {
13 | create("libs") {
14 | from(files("../gradle/libs.versions.toml"))
15 | }
16 | }
17 | }
18 |
19 |
20 | includeBuild("../") {
21 |
22 | dependencySubstitution {
23 | val group = "io.github.windedge.viform"
24 | substitute(module("$group:viform-core")).using(project(":modules:viform-core"))
25 | substitute(module("$group:viform-compose")).using(project(":modules:viform-compose"))
26 | substitute(module("$group:viform-orbitmvi")).using(project(":modules:viform-orbitmvi"))
27 | }
28 | }
29 |
30 | include(
31 | ":signupapp"
32 | )
--------------------------------------------------------------------------------
/sandbox/signupapp/src/androidMain/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | MIT License
2 |
3 | Copyright (c) 2018 windedge
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE.
--------------------------------------------------------------------------------
/modules/viform-core/src/commonMain/kotlin/io/github.windedge.viform.core/String.kt:
--------------------------------------------------------------------------------
1 | @file:Suppress("unused")
2 |
3 | package io.github.windedge.viform.core
4 |
5 |
6 | internal fun String.isNumeric(): Boolean {
7 | return this.matches(Regex("[+-]?\\d+(\\.\\d+)?"))
8 | }
9 |
10 | internal fun String.isInt(): Boolean {
11 | return this.matches(Regex("[+-]?\\d+"))
12 | }
13 |
14 | internal fun String.isFloat(): Boolean {
15 | return this.matches(Regex("[+-]?\\d+\\.\\d+"))
16 | }
17 |
18 | internal fun String.isEmail(): Boolean {
19 | return this.matches(Regex("^[a-zA-Z0-9_!#$%&’*+/=?`{|}~^-]+(?:\\.[a-zA-Z0-9_!#$%&’*+/=?`{|}~^-]+)*@[a-zA-Z0-9-]+(?:\\.[a-zA-Z0-9-]{2,})*$"))
20 | }
21 |
22 | internal fun String.isUrl(): Boolean {
23 | return this.matches(Regex("^(http|https)://[^\\s$.?#].[^\\s]*$"))
24 | }
25 |
26 | internal fun String.isIPv4(): Boolean {
27 | return this.matches(Regex("^(?:(?:25[0-5]|2[0-4]\\d|[0-1]\\d{2}|[1-9]?\\d)\\.){3}(?:25[0-5]|2[0-4]\\d|[0-1]\\d{2}|[1-9]?\\d)\$"))
28 | }
29 |
30 | internal fun String.isIPv6(): Boolean {
31 | return this.matches(Regex("^(?:[A-F0-9]{1,4}:){7}[A-F0-9]{1,4}\$"))
32 | }
33 |
34 | internal fun String.isHexColor(): Boolean {
35 | return this.matches(Regex("^#?([a-fA-F0-9]{6}|[a-fA-F0-9]{3})\$"))
36 | }
37 |
38 | internal fun String.isHexadecimal(): Boolean {
39 | return this.matches(Regex("^[0-9a-fA-F]+\$"))
40 | }
41 |
42 | internal fun String.isCreditCard(): Boolean {
43 | return this.matches(Regex("^((4\\d{3})|(5[1-5]\\d{2})|(6011)|(7\\d{3}))-?\\d{4}-?\\d{4}-?\\d{4}|3[4,7]\\d{13}\$"))
44 | }
45 |
46 | internal fun String.isAlphaNumeric(): Boolean {
47 | return this.matches(Regex("^[a-zA-Z][a-zA-Z0-9]*$"))
48 | }
49 |
50 |
--------------------------------------------------------------------------------
/modules/viform-core/src/commonMain/kotlin/io/github.windedge.viform.core/FormHost.kt:
--------------------------------------------------------------------------------
1 | package io.github.windedge.viform.core
2 |
3 |
4 | import kotlinx.coroutines.flow.MutableStateFlow
5 | import kotlinx.coroutines.flow.StateFlow
6 | import kotlinx.coroutines.flow.asStateFlow
7 |
8 | public interface FormHost {
9 |
10 | public val form: Form
11 |
12 | public val stateFlow: StateFlow
13 |
14 | public val currentState: T
15 |
16 | public fun submit(formData: T, validate: Boolean = true): Boolean
17 |
18 | public fun validate(): Boolean
19 |
20 | public fun pop(): T
21 |
22 | public fun reset()
23 | }
24 |
25 | public fun FormHost.form(build: FormBuilder.() -> Unit): Form {
26 | val form = FormImpl(currentState)
27 | val builder = FormBuilder(form)
28 | builder.build()
29 | return form
30 | }
31 |
32 | public class DefaultFormHost(override val form: Form) : FormHost {
33 |
34 | private val _stateFlow: MutableStateFlow = MutableStateFlow(form.pop())
35 |
36 | override val stateFlow: StateFlow get() = _stateFlow.asStateFlow()
37 |
38 | override val currentState: T get() = _stateFlow.value
39 |
40 | override fun submit(formData: T, validate: Boolean): Boolean {
41 | _stateFlow.value = formData
42 | return form.submit(formData, validate)
43 | }
44 |
45 | override fun validate(): Boolean {
46 | return form.validate()
47 | }
48 |
49 | override fun pop(): T {
50 | val newState = form.pop(currentState)
51 | _stateFlow.value = newState
52 | return newState
53 | }
54 |
55 | override fun reset() {
56 | form.reset()
57 | _stateFlow.value = form.pop()
58 | }
59 |
60 | }
--------------------------------------------------------------------------------
/sandbox/signupapp/src/androidMain/res/drawable-v24/ic_launcher_foreground.xml:
--------------------------------------------------------------------------------
1 |
7 |
8 |
9 |
15 |
18 |
21 |
22 |
23 |
24 |
30 |
--------------------------------------------------------------------------------
/modules/viform-orbitmvi/src/commonMain/kotlin/FormContainerHost.kt:
--------------------------------------------------------------------------------
1 | package io.github.windedge.viform.mvi
2 |
3 | import io.github.windedge.viform.core.FormHost
4 | import kotlinx.coroutines.flow.StateFlow
5 | import org.orbitmvi.orbit.ContainerHost
6 | import org.orbitmvi.orbit.annotation.OrbitDsl
7 | import org.orbitmvi.orbit.annotation.OrbitInternal
8 | import org.orbitmvi.orbit.syntax.simple.SimpleContext
9 | import org.orbitmvi.orbit.syntax.simple.SimpleSyntax
10 | import org.orbitmvi.orbit.syntax.simple.intent
11 |
12 |
13 | public abstract class FormContainerHost
14 | : ContainerHost, FormHost {
15 |
16 | override val stateFlow: StateFlow get() = container.stateFlow
17 |
18 | override val currentState: STATE get() = container.stateFlow.value
19 |
20 | override fun submit(formData: STATE, validate: Boolean) : Boolean {
21 | intent { reduce { formData } }
22 | return form.submit(formData, validate)
23 | }
24 |
25 | override fun validate(): Boolean = form.validate()
26 |
27 | override fun pop(): STATE {
28 | val state = form.pop(currentState)
29 | intent { reduce { state } }
30 | return state
31 | }
32 |
33 | override fun reset() {
34 | form.reset()
35 | intent { reduce { form.pop() } }
36 | }
37 |
38 | @OptIn(OrbitInternal::class)
39 | @OrbitDsl
40 | public suspend fun SimpleSyntax.reduce(
41 | validate: Boolean = false,
42 | reducer: SimpleContext.() -> STATE
43 | ) {
44 | containerContext.reduce { oldState ->
45 | val newState = SimpleContext(oldState).reducer()
46 | val success = this@FormContainerHost.form.submit(newState, validate)
47 | if (success) newState else oldState
48 | }
49 | }
50 | }
51 |
--------------------------------------------------------------------------------
/gradle/libs.versions.toml:
--------------------------------------------------------------------------------
1 | [versions]
2 | viform = "0.0.0"
3 |
4 | kotlin = "2.1.21"
5 | agp = "8.2.0"
6 | java = "17"
7 | compose = "1.8.0"
8 | androidx-activity-compose = "1.9.3"
9 | kotlinx-coroutines = "1.9.0"
10 | kotlinx-serilization = "1.7.3"
11 | orbitmvi = "6.1.0"
12 | kotlinpoet = "1.12.0"
13 | ksp = "2.1.0-1.0.29"
14 | kopybuilder = "0.2.4"
15 | maven-publish = "0.25.2"
16 |
17 |
18 | [libraries]
19 | kotlinx-coroutines-core = { module = "org.jetbrains.kotlinx:kotlinx-coroutines-core", version.ref = "kotlinx-coroutines" }
20 | kotlinx-coroutines-test = { module = "org.jetbrains.kotlinx:kotlinx-coroutines-test", version.ref = "kotlinx-coroutines" }
21 | kotlinx-serilization-json = { module = "org.jetbrains.kotlinx:kotlinx-serialization-json", version.ref = "kotlinx-serilization" }
22 | orbitmvi-core = { module = "org.orbit-mvi:orbit-core", version.ref = "orbitmvi" }
23 | ksp = { module = "com.google.devtools.ksp:symbol-processing-api", version.ref = "ksp" }
24 | kotlinpoet-ksp = { module = "com.squareup:kotlinpoet-ksp", version.ref = "kotlinpoet" }
25 | kopybuilder-runtime = { module = "io.github.windedge.copybuilder:copybuilder-runtime", version.ref = "kopybuilder" }
26 |
27 | viform-core = { module = "io.github.windedge.viform:viform-core", version.ref = "viform" }
28 | viform-compose = { module = "io.github.windedge.viform:viform-compose", version.ref = "viform" }
29 |
30 | androidx-activity-compose = { module = "androidx.activity:activity-compose", version.ref = "androidx-activity-compose" }
31 |
32 |
33 | [plugins]
34 | maven-publish = { id = "com.vanniktech.maven.publish", version.ref = "maven-publish" }
35 | android-application = { id = "com.android.application", version.ref = "agp" }
36 | android-library = { id = "com.android.library", version.ref = "agp" }
37 | compose = { id = "org.jetbrains.compose", version.ref = "compose" }
38 | kotlin-kmp = { id = "org.jetbrains.kotlin.multiplatform", version.ref = "kotlin" }
39 | kotlin-compose = { id = "org.jetbrains.kotlin.plugin.compose", version.ref = "kotlin" }
40 | kopybuilder = { id = "io.github.windedge.kopybuilder", version.ref = "kopybuilder" }
41 |
--------------------------------------------------------------------------------
/modules/viform-core/src/commonMain/kotlin/io/github.windedge.viform.core/FormField.kt:
--------------------------------------------------------------------------------
1 | package io.github.windedge.viform.core
2 |
3 |
4 | import kotlinx.coroutines.flow.*
5 |
6 | public interface FormField : ValidatorContainer {
7 | public val name: String
8 |
9 | public val valueFlow: StateFlow
10 |
11 | public val resultFlow: StateFlow
12 |
13 | public val currentValue: V
14 |
15 | public fun setValue(value: V, validate: Boolean = false)
16 |
17 | public fun setResult(result: ValidateResult)
18 |
19 | public fun showError(message: String)
20 |
21 | public fun validate(): Boolean
22 | }
23 |
24 | public fun FormField(name: String, initialValue: V): FormField {
25 | return FormFieldImpl(name, initialValue)
26 | }
27 |
28 | internal class FormFieldImpl(override val name: String, initialValue: V) : FormField {
29 | private val _valueFlow: MutableStateFlow = MutableStateFlow(initialValue)
30 | override val valueFlow: StateFlow get() = _valueFlow.asStateFlow()
31 |
32 | private val _resultFlow: MutableStateFlow = MutableStateFlow(ValidateResult.None)
33 | override val resultFlow: StateFlow get() = _resultFlow.asStateFlow()
34 |
35 | override val currentValue: V get() = valueFlow.value
36 |
37 | private val validators = mutableListOf>()
38 |
39 | override fun addValidator(validator: FieldValidator) {
40 | validators.add(validator)
41 | }
42 |
43 | override fun clearValidators(): Unit = validators.clear()
44 |
45 | override fun getValidators(): List> = validators.toList()
46 |
47 | override fun setValue(value: V, validate: Boolean) {
48 | _valueFlow.value = value
49 | _resultFlow.value = ValidateResult.None
50 |
51 | if (validate) validate()
52 | }
53 |
54 | override fun setResult(result: ValidateResult) {
55 | _resultFlow.value = result
56 | }
57 |
58 | override fun showError(message: String) {
59 | setResult(ValidateResult.Failure(message))
60 | }
61 |
62 | override fun validate(): Boolean =
63 | validators.validateAndGet(currentValue).also { _resultFlow.value = it }.isSuccess
64 | }
65 |
--------------------------------------------------------------------------------
/.github/workflows/publish.yml:
--------------------------------------------------------------------------------
1 | name: Publish to Maven Central
2 |
3 | on:
4 | workflow_dispatch: # Allows manual triggering of the workflow
5 | release:
6 | types: [published] # Triggers when a new release is published
7 |
8 | jobs:
9 | publish:
10 | runs-on: macos-latest # Or ubuntu-latest, depending on your needs
11 |
12 | steps:
13 | - name: Checkout
14 | uses: actions/checkout@v4 # Use a newer version of the checkout action
15 |
16 | - name: Set up JDK 17 # Consistent with KopyBuilder; change if viform-multiplatform needs a different version
17 | uses: actions/setup-java@v4
18 | with:
19 | java-version: '17' # Consistent with KopyBuilder; change if viform-multiplatform needs a different version
20 | distribution: 'temurin'
21 | cache: gradle
22 |
23 | - name: Grant execute permission for gradlew
24 | run: chmod +x gradlew
25 |
26 | - name: Setup Gradle
27 | uses: gradle/actions/setup-gradle@v3 # Use the new Gradle action path
28 |
29 | - name: Import GPG key
30 | run: |
31 | # Create GPG directory
32 | mkdir -p ~/.gnupg/
33 | chmod 700 ~/.gnupg/
34 |
35 | # Set GPG agent and conf for loopback pinentry
36 | echo "allow-loopback-pinentry" >> ~/.gnupg/gpg-agent.conf
37 | echo "pinentry-mode loopback" >> ~/.gnupg/gpg.conf
38 |
39 | # Import key
40 | echo "${{ secrets.GPG_KEY_CONTENTS }}" | base64 --decode | gpg --batch --import
41 | gpg --list-secret-keys --keyid-format LONG
42 | env:
43 | GPG_KEY_CONTENTS: ${{ secrets.GPG_KEY_CONTENTS }} # Needs to be configured in GitHub secrets
44 |
45 | - name: Publish to Maven Central
46 | env:
47 | ORG_GRADLE_PROJECT_mavenCentralUsername: ${{ secrets.OSSRH_USERNAME }}
48 | ORG_GRADLE_PROJECT_mavenCentralPassword: ${{ secrets.OSSRH_PASSWORD }}
49 | ORG_GRADLE_PROJECT_signingInMemoryKey: ${{ secrets.GPG_KEY_CONTENTS }}
50 | ORG_GRADLE_PROJECT_signingInMemoryKeyId: ${{ secrets.SIGNING_KEY_ID }}
51 | ORG_GRADLE_PROJECT_signingInMemoryKeyPassword: ${{ secrets.SIGNING_PASSWORD }}
52 | # ORG_GRADLE_PROJECT_sonatypeStagingProfileId: ${{ secrets.SONATYPE_STAGING_PROFILE_ID }}
53 | run: |
54 | ./gradlew publishAllPublicationsToMavenCentral --no-daemon --no-parallel
55 |
--------------------------------------------------------------------------------
/.github/workflows/release.yml:
--------------------------------------------------------------------------------
1 | name: Create Release
2 |
3 | on:
4 | push:
5 | tags:
6 | - 'v*' # Tags starting with 'v' will trigger this workflow
7 |
8 | jobs:
9 | release:
10 | runs-on: ubuntu-latest
11 | steps:
12 | - name: Checkout
13 | uses: actions/checkout@v3
14 | with:
15 | fetch-depth: 0 # Fetch full history to support version calculation
16 |
17 | - name: Get tag version
18 | id: get_version
19 | run: echo "VERSION=${GITHUB_REF#refs/tags/v}" >> $GITHUB_OUTPUT
20 |
21 | - name: Update version in gradle.properties
22 | run: |
23 | # Ensure we have the latest code
24 | git fetch origin
25 | git checkout main
26 |
27 | # Update version number
28 | sed -i "s/^version=.*/version=${{ steps.get_version.outputs.VERSION }}/" gradle.properties
29 |
30 | # Commit and push changes
31 | git config --local user.email "action@github.com"
32 | git config --local user.name "GitHub Action"
33 | # Update version in README.md and README-CN.md
34 | for file in README.md README-CN.md; do
35 | if [ -f "$file" ]; then
36 | sed -i "s/implementation(\"io.github.windedge.viform:viform-core:.*\")/implementation(\"io.github.windedge.viform:viform-core:${{ steps.get_version.outputs.VERSION }}\")/g" "$file"
37 | sed -i "s/implementation(\"io.github.windedge.viform:viform-compose:.*\")/implementation(\"io.github.windedge.viform:viform-compose:${{ steps.get_version.outputs.VERSION }}\")/g" "$file"
38 | fi
39 | done
40 |
41 | # Commit and push changes
42 | git add README.md README-CN.md
43 | git commit -m "Update version to ${{ steps.get_version.outputs.VERSION }}" -a || echo "No changes to commit"
44 | git push origin HEAD:main
45 |
46 | - name: Create GitHub Release
47 | uses: softprops/action-gh-release@v2
48 | with:
49 | name: Release ${{ steps.get_version.outputs.VERSION }}
50 | body: |
51 | Release version ${{ steps.get_version.outputs.VERSION }}
52 | draft: false
53 | prerelease: false
54 | env:
55 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
56 | # files: | # Optional: Attach build artifacts to the release
57 | # build/libs/*.jar
58 |
--------------------------------------------------------------------------------
/gradle.properties:
--------------------------------------------------------------------------------
1 | #======================================== Gradle ========================================
2 | org.gradle.project.sourceCompatibility=11
3 | org.gradle.project.targetCompatibility=11
4 | org.gradle.vfs.watch=true
5 | org.gradle.cache=true
6 | #org.gradle.parallel=true
7 | org.gradle.jvmargs=-XX:MaxMetaspaceSize=2g -Xmx2g
8 |
9 | #======================================== Kotlin ========================================
10 | kotlin.style=official
11 | kotlin.stdlib.default.dependency=true
12 | kotlin.js.generate.externals=false
13 | kotlin.js.browser.karma.browsers=chromium-headless
14 | kotlin.incremental.js=true
15 | kotlin.mpp.stability.nowarn=true
16 |
17 | kotlin.wasm.js.generate.types=true
18 | kotlin.wasm.js.ir.memoryModel=unlimited
19 | kotlin.wasm.js.ir.optimize=true
20 | kotlin.incremental.wasm=false
21 | kotlin.native.ignoreDisabledTargets=true
22 | kotlin.mpp.androidSourceSetLayoutVersion=2
23 | # https://youtrack.jetbrains.com/issue/KT-51293/Unresolved-references-with-hierarchical-project-structure-when-building-KotlinMetadata-from-native-common-source-set#focus=Comments-27-6220848.0-0
24 | kotlin.mpp.import.enableKgpDependencyResolution=true
25 |
26 | kotlin.mpp.androidSourceSetLayoutV2AndroidStyleDirs.nowarn=true
27 |
28 | # Makes sure we can debug our Kotlin plugin with breakpoints
29 | kotlin.compiler.execution.strategy=in-process
30 | #======================================== Android =======================================
31 | android.useAndroidX=true
32 | android.enableJetifier=true
33 |
34 | #======================================= Project ========================================
35 | group=io.github.windedge.viform
36 | version=0.2.2
37 |
38 | #======================================= Maven Publish =================================
39 | SONATYPE_HOST=S01
40 | RELEASE_SIGNING_ENABLED=true
41 | SONATYPE_AUTOMATIC_RELEASE=true
42 |
43 | POM_DESCRIPTION=A kotlin multiplatform form validation library, primarily used for jetpack compose and orbit-mvi
44 | POM_URL=https://github.com/windedge/viform-multiplatform
45 |
46 | POM_LICENSE_NAME=MIT License
47 | POM_LICENSE_URL=https://github.com/windedge/viform-multiplatform/blob/main/LICENSE
48 | POM_LICENSE_DIST=repo
49 |
50 | POM_SCM_URL=https://github.com/windedge/viform-multiplatform/tree/main
51 | POM_SCM_CONNECTION=scm:git:github.com/windedge/viform-multiplatform.git
52 | POM_SCM_DEV_CONNECTION=scm:git:ssh://github.com/windedge/viform-multiplatform.git
53 |
54 | POM_DEVELOPER_ID=windedge
55 | POM_DEVELOPER_NAME=xujl
56 | POM_DEVELOPER_EMAIL=windedge99@gmail.com
57 |
--------------------------------------------------------------------------------
/sandbox/signupapp/build.gradle.kts:
--------------------------------------------------------------------------------
1 | @file:OptIn(org.jetbrains.kotlin.gradle.ExperimentalWasmDsl::class)
2 |
3 | plugins {
4 | alias(libs.plugins.kotlin.kmp)
5 | alias(libs.plugins.compose)
6 | alias(libs.plugins.kotlin.compose)
7 | alias(libs.plugins.android.application)
8 | alias(libs.plugins.kopybuilder)
9 | }
10 |
11 | kotlin {
12 | jvmToolchain(17)
13 |
14 | androidTarget("android") {
15 | compilations.all {
16 | kotlinOptions {
17 | jvmTarget = "17"
18 | }
19 | }
20 | }
21 |
22 | jvm("desktop")
23 |
24 | wasmJs {
25 | browser()
26 | binaries.executable()
27 | }
28 |
29 | sourceSets {
30 | all {
31 | languageSettings {
32 | optIn("org.jetbrains.compose.resources.ExperimentalResourceApi")
33 | }
34 | }
35 |
36 | val commonMain by getting {
37 | dependencies {
38 | implementation(libs.kotlinx.coroutines.core)
39 |
40 | implementation(compose.runtime)
41 | implementation(compose.foundation)
42 | implementation(compose.material)
43 | implementation(compose.ui)
44 | @OptIn(org.jetbrains.compose.ExperimentalComposeLibrary::class)
45 | api(compose.components.resources)
46 |
47 | implementation(libs.viform.core)
48 | implementation(libs.viform.compose)
49 | }
50 | }
51 | val androidMain by getting {
52 | dependsOn(commonMain)
53 |
54 | dependencies {
55 | implementation(compose.uiTooling)
56 | implementation(libs.androidx.activity.compose)
57 | }
58 | }
59 | val desktopMain by getting {
60 | dependsOn(commonMain)
61 |
62 | dependencies {
63 | implementation(compose.desktop.currentOs)
64 | }
65 | }
66 | val wasmJsMain by getting {
67 | dependsOn(commonMain)
68 | }
69 | }
70 | }
71 |
72 | compose {
73 | desktop {
74 | application {
75 | mainClass = "local.sandbox.signupapp.MainKt"
76 | }
77 | }
78 | }
79 |
80 | android {
81 | namespace = "local.sandbox.signupapp"
82 | compileSdk = 35
83 | sourceSets["main"].manifest.srcFile("src/androidMain/AndroidManifest.xml")
84 | sourceSets["main"].res.srcDirs("src/androidMain/res")
85 | sourceSets["main"].resources.srcDirs("src/androidMain/resources")
86 |
87 | defaultConfig {
88 | applicationId = "local.sandbox.signupapp"
89 | minSdk = 24
90 | targetSdk = 35
91 | versionCode = 1
92 | versionName = "1.0"
93 | testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
94 | }
95 | buildTypes {
96 | getByName("release") {
97 | isMinifyEnabled = true
98 | signingConfig = signingConfigs.getByName("debug")
99 | }
100 | getByName("debug") {
101 | isMinifyEnabled = false
102 | }
103 | }
104 | compileOptions {
105 | sourceCompatibility = JavaVersion.VERSION_17
106 | targetCompatibility = JavaVersion.VERSION_17
107 | }
108 | composeOptions {
109 | kotlinCompilerExtensionVersion = libs.versions.compose.get()
110 | }
111 | }
--------------------------------------------------------------------------------
/gradlew.bat:
--------------------------------------------------------------------------------
1 | @rem
2 | @rem Copyright 2015 the original author or authors.
3 | @rem
4 | @rem Licensed under the Apache License, Version 2.0 (the "License");
5 | @rem you may not use this file except in compliance with the License.
6 | @rem You may obtain a copy of the License at
7 | @rem
8 | @rem https://www.apache.org/licenses/LICENSE-2.0
9 | @rem
10 | @rem Unless required by applicable law or agreed to in writing, software
11 | @rem distributed under the License is distributed on an "AS IS" BASIS,
12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | @rem See the License for the specific language governing permissions and
14 | @rem limitations under the License.
15 | @rem
16 |
17 | @if "%DEBUG%"=="" @echo off
18 | @rem ##########################################################################
19 | @rem
20 | @rem Gradle startup script for Windows
21 | @rem
22 | @rem ##########################################################################
23 |
24 | @rem Set local scope for the variables with windows NT shell
25 | if "%OS%"=="Windows_NT" setlocal
26 |
27 | set DIRNAME=%~dp0
28 | if "%DIRNAME%"=="" set DIRNAME=.
29 | @rem This is normally unused
30 | set APP_BASE_NAME=%~n0
31 | set APP_HOME=%DIRNAME%
32 |
33 | @rem Resolve any "." and ".." in APP_HOME to make it shorter.
34 | for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
35 |
36 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
37 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
38 |
39 | @rem Find java.exe
40 | if defined JAVA_HOME goto findJavaFromJavaHome
41 |
42 | set JAVA_EXE=java.exe
43 | %JAVA_EXE% -version >NUL 2>&1
44 | if %ERRORLEVEL% equ 0 goto execute
45 |
46 | echo.
47 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
48 | echo.
49 | echo Please set the JAVA_HOME variable in your environment to match the
50 | echo location of your Java installation.
51 |
52 | goto fail
53 |
54 | :findJavaFromJavaHome
55 | set JAVA_HOME=%JAVA_HOME:"=%
56 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe
57 |
58 | if exist "%JAVA_EXE%" goto execute
59 |
60 | echo.
61 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
62 | echo.
63 | echo Please set the JAVA_HOME variable in your environment to match the
64 | echo location of your Java installation.
65 |
66 | goto fail
67 |
68 | :execute
69 | @rem Setup the command line
70 |
71 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
72 |
73 |
74 | @rem Execute Gradle
75 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
76 |
77 | :end
78 | @rem End local scope for the variables with windows NT shell
79 | if %ERRORLEVEL% equ 0 goto mainEnd
80 |
81 | :fail
82 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
83 | rem the _cmd.exe /c_ return code!
84 | set EXIT_CODE=%ERRORLEVEL%
85 | if %EXIT_CODE% equ 0 set EXIT_CODE=1
86 | if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE%
87 | exit /b %EXIT_CODE%
88 |
89 | :mainEnd
90 | if "%OS%"=="Windows_NT" endlocal
91 |
92 | :omega
93 |
--------------------------------------------------------------------------------
/sandbox/gradlew.bat:
--------------------------------------------------------------------------------
1 | @rem
2 | @rem Copyright 2015 the original author or authors.
3 | @rem
4 | @rem Licensed under the Apache License, Version 2.0 (the "License");
5 | @rem you may not use this file except in compliance with the License.
6 | @rem You may obtain a copy of the License at
7 | @rem
8 | @rem https://www.apache.org/licenses/LICENSE-2.0
9 | @rem
10 | @rem Unless required by applicable law or agreed to in writing, software
11 | @rem distributed under the License is distributed on an "AS IS" BASIS,
12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | @rem See the License for the specific language governing permissions and
14 | @rem limitations under the License.
15 | @rem
16 |
17 | @if "%DEBUG%"=="" @echo off
18 | @rem ##########################################################################
19 | @rem
20 | @rem Gradle startup script for Windows
21 | @rem
22 | @rem ##########################################################################
23 |
24 | @rem Set local scope for the variables with windows NT shell
25 | if "%OS%"=="Windows_NT" setlocal
26 |
27 | set DIRNAME=%~dp0
28 | if "%DIRNAME%"=="" set DIRNAME=.
29 | @rem This is normally unused
30 | set APP_BASE_NAME=%~n0
31 | set APP_HOME=%DIRNAME%
32 |
33 | @rem Resolve any "." and ".." in APP_HOME to make it shorter.
34 | for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
35 |
36 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
37 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
38 |
39 | @rem Find java.exe
40 | if defined JAVA_HOME goto findJavaFromJavaHome
41 |
42 | set JAVA_EXE=java.exe
43 | %JAVA_EXE% -version >NUL 2>&1
44 | if %ERRORLEVEL% equ 0 goto execute
45 |
46 | echo.
47 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
48 | echo.
49 | echo Please set the JAVA_HOME variable in your environment to match the
50 | echo location of your Java installation.
51 |
52 | goto fail
53 |
54 | :findJavaFromJavaHome
55 | set JAVA_HOME=%JAVA_HOME:"=%
56 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe
57 |
58 | if exist "%JAVA_EXE%" goto execute
59 |
60 | echo.
61 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
62 | echo.
63 | echo Please set the JAVA_HOME variable in your environment to match the
64 | echo location of your Java installation.
65 |
66 | goto fail
67 |
68 | :execute
69 | @rem Setup the command line
70 |
71 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
72 |
73 |
74 | @rem Execute Gradle
75 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
76 |
77 | :end
78 | @rem End local scope for the variables with windows NT shell
79 | if %ERRORLEVEL% equ 0 goto mainEnd
80 |
81 | :fail
82 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
83 | rem the _cmd.exe /c_ return code!
84 | set EXIT_CODE=%ERRORLEVEL%
85 | if %EXIT_CODE% equ 0 set EXIT_CODE=1
86 | if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE%
87 | exit /b %EXIT_CODE%
88 |
89 | :mainEnd
90 | if "%OS%"=="Windows_NT" endlocal
91 |
92 | :omega
93 |
--------------------------------------------------------------------------------
/README-CN.md:
--------------------------------------------------------------------------------
1 | # ViForm
2 |
3 | ViForm是一个用于表单验证的Kotlin库,主要目标是用在Compose Multiplatform项目,它具有下面几个特点:
4 | * 支持Kotlin多平台(android, jvm, js, wasmjs, ios)
5 | * 类型安全的验证规则,同时支持DSL风格和链式风格的验证规则写法
6 | * 表单状态管理
7 | * Compose Multiplatform的集成支持(android, desktop, wasmjs, ios)
8 |
9 |
10 | ## 前提条件
11 | - Kotlin Coroutine
12 | - KopyBuilder
13 | - Compose Multiplatform(可选)
14 |
15 | ## 安装
16 |
17 | 添加KopyBuilder的Gradle插件
18 | ```kotlin
19 | plugins {
20 | id("io.github.windedge.kopybuilder") version "0.2.4"
21 | }
22 | ```
23 |
24 | 在Multiplatform项目添加依赖
25 | ```Kotlin
26 | kotlin {
27 | sourceSets {
28 | commonMain {
29 | dependencies {
30 | implementation("io.github.windedge.viform:viform-core:0.2.2")
31 |
32 | // 可选
33 | implementation("io.github.windedge.viform:viform-compose:0.2.2")
34 | }
35 | }
36 | }
37 | }
38 | ```
39 |
40 | 在JVM项目添加依赖
41 | ```Kotlin
42 | dependencies {
43 | implementation("io.github.windedge.viform:viform-core:0.2.2")
44 |
45 | // 可选
46 | implementation("io.github.windedge.viform:viform-compose:0.2.2")
47 | }
48 | ```
49 |
50 | ## 快速开始
51 |
52 | 定义验证规则:
53 |
54 | ```kotlin
55 | import io.github.windedge.copybuilder.KopyBuilder
56 | import io.github.windedge.viform.core.*
57 |
58 |
59 | @KopyBuilder
60 | data class Signup(
61 | val name: String = "",
62 | val email: String? = null,
63 | val password: String = "",
64 | val confirmPassword: String = "",
65 | )
66 |
67 |
68 | val schema = FormSchema.create {
69 | field(Signup::name) {
70 | required("User name is required.")
71 | isAlphaNumeric()
72 | }
73 |
74 | field(Signup::email).optional {
75 | isEmail()
76 | }
77 |
78 | // 链式风格
79 | field(Signup::password).required().lengthBetween(8, 20)
80 |
81 | // 自定义规则
82 | field(Signup::confirmPassword).required().lengthBetween(8, 20)
83 | .custom("Passwords must be the same.") {
84 | it == field(Signup::password).currentValue
85 | }
86 | }
87 | ```
88 |
89 | 在Jetpack Compose项目中使用:
90 |
91 | ```kotlin
92 | import io.github.windedge.viform.compose.use
93 |
94 | @Compose
95 | fun SignupApp() {
96 | val form = schema.buildForm(Signup())
97 | Column {
98 | form.use() {
99 | field(it::name) {
100 | TextInput("User Name: ", currentValue, hasError, errorMessage, onValueChange = {
101 | setValue(it, validate = true) // 实时验证
102 | })
103 | }
104 |
105 | field(it::email) {
106 | watchLazily { validate() } // 延迟验证
107 | TextInput("Email:", currentValue ?: "", hasError, errorMessage), onValueChange=::setValue)
108 | }
109 |
110 | field(it::password) {
111 | watchLazily { if (it.isNotEmpty()) validate() }
112 | TextInput("Password:", currentValue, hasError, errorMessage, onValueChange=::setValue)
113 | }
114 |
115 | field(it::confirmPassword) {
116 | watchLazily { if (it.isNotEmpty()) validate() }
117 | TextInput("Confirm Password:", currentValue, hasError, errorMessage, onValueChange=::setValue)
118 | }
119 |
120 | // 提交时验证
121 | Button(onClick = {
122 | if(form.validate()) {
123 | val data = form.pop() // 获取数据
124 | // ...
125 | }
126 | }) { Text("Sign up") }
127 | }
128 | }
129 | }
130 | ```
131 |
132 |
133 | ## 已知问题
134 |
135 | 在编译 WebAssembly (WASM) 目标时,可能会遇到 `Can't link symbol kotlin.internal.ir/ANDAND` 错误。
136 |
137 | ## 许可证
138 | [MIT License](./LICENSE)
139 |
140 | ## 作者
141 |
142 | [Ken Xu](https://github.com/windedge)
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | English | [中文](README-CN.md)
2 |
3 | # ViForm
4 |
5 | ViForm is a Kotlin library for form validation, mainly aimed at Compose Multiplatform projects. It has the following features:
6 | * Supports Kotlin Multiplatform(android, jvm, js/wasmjs, ios)
7 | * Type-safe validation rules, supporting both DSL style and chained style validation declaration
8 | * Form state management
9 | * Integrated support for Compose Multiplatform(android, desktop, wasmjs, ios)
10 |
11 |
12 | ## Prerequisites
13 | - Kotlin Coroutine
14 | - KopyBuilder
15 | - Compose Multiplatform (optional)
16 |
17 | ## Installation
18 |
19 | Apply the KopyBuilder Gradle plugin
20 | ```kotlin
21 | plugins {
22 | id("io.github.windedge.kopybuilder") version "0.2.4"
23 | }
24 | ```
25 |
26 | Add dependency to Multiplatform project
27 | ```Kotlin
28 | kotlin {
29 | sourceSets {
30 | commonMain {
31 | dependencies {
32 | implementation("io.github.windedge.viform:viform-core:0.2.2")
33 |
34 | // Optional
35 | implementation("io.github.windedge.viform:viform-compose:0.2.2")
36 | }
37 | }
38 | }
39 | }
40 | ```
41 |
42 | Add dependency to JVM project
43 | ```Kotlin
44 | dependencies {
45 | implementation("io.github.windedge.viform:viform-core:0.2.2")
46 |
47 | // Optional
48 | implementation("io.github.windedge.viform:viform-compose:0.2.2")
49 | }
50 | ```
51 |
52 | ## Quick Start
53 |
54 | Define validation rules:
55 |
56 | ```kotlin
57 | import io.github.windedge.copybuilder.KopyBuilder
58 | import io.github.windedge.viform.core.*
59 |
60 |
61 | @KopyBuilder
62 | data class Signup(
63 | val name: String = "",
64 | val email: String? = null,
65 | val password: String = "",
66 | val confirmPassword: String = "",
67 | )
68 |
69 |
70 | val schema = FormSchema.create {
71 | field(Signup::name) {
72 | required("User name is required.")
73 | isAlphaNumeric()
74 | }
75 |
76 | field(Signup::email).optional {
77 | isEmail()
78 | }
79 |
80 | // Chain style
81 | field(Signup::password).required().lengthBetween(8, 20)
82 |
83 | // Custom rule
84 | field(Signup::confirmPassword).required().lengthBetween(8, 20)
85 | .custom("Passwords must be the same.") {
86 | it == field(Signup::password).currentValue
87 | }
88 | }
89 | ```
90 |
91 | Use in Jetpack Compose project:
92 |
93 | ```kotlin
94 | import io.github.windedge.viform.compose.use
95 |
96 | @Compose
97 | fun SignupApp() {
98 | val form = schema.buildForm(Signup())
99 | Column {
100 | form.use {
101 | field(it::name) {
102 | TextInput("User Name: ", currentValue, hasError, errorMessage, onValueChange = {
103 | setValue(it, validate = true) // validate synchronously
104 | })
105 | }
106 |
107 | field(it::email) {
108 | watchLazily { validate() } // validate asynchronously
109 | TextInput("Email:", currentValue ?: "", hasError, errorMessage, onValueChange=::setValue)
110 | }
111 |
112 | field(it::password) {
113 | watchLazily { if (it.isNotEmpty()) validate() }
114 | TextInput("Password:", currentValue, hasError, errorMessage, onValueChange=::setValue)
115 | }
116 |
117 | field(it::confirmPassword) {
118 | watchLazily { if (it.isNotEmpty()) validate() }
119 | TextInput("Confirm Password:", currentValue, hasError, errorMessage, onValueChange=::setValue)
120 | }
121 |
122 | // validate on submit
123 | Button(onClick = {
124 | if(form.validate()) {
125 | val signup = form.pop() // get form data
126 | // ...
127 | }
128 | }) { Text("Sign up") }
129 | }
130 | }
131 | }
132 | ```
133 |
134 |
135 | ## Known Issues
136 |
137 | When compiling the WebAssembly (WASM) target, you may encounter the error `Can't link symbol kotlin.internal.ir/ANDAND`.
138 |
139 | ## License
140 | [MIT License](./LICENSE)
141 |
142 | ## Author
143 |
144 | [Ken Xu](https://github.com/windedge)
145 |
--------------------------------------------------------------------------------
/modules/viform-core/src/commonMain/kotlin/io/github.windedge.viform.core/Form.kt:
--------------------------------------------------------------------------------
1 | package io.github.windedge.viform.core
2 |
3 |
4 | import io.github.windedge.copybuilder.CopyBuilderHost
5 | import kotlinx.coroutines.sync.Mutex
6 | import kotlin.reflect.*
7 |
8 |
9 | public interface Form {
10 |
11 | public fun getOrRegisterField(property: KProperty): FormField
12 |
13 | public fun getField(name: String): FormField?
14 |
15 | public fun replaceField(formField: FormField): FormField
16 |
17 | public val fields: List>
18 |
19 | public fun validate(): Boolean
20 |
21 | public fun submit(formData: T, validate: Boolean = true): Boolean
22 |
23 | public fun pop(shadowedState: T? = null): T
24 |
25 | public fun reset()
26 | }
27 |
28 | public fun Form(initialState: T): Form {
29 | return FormImpl(initialState)
30 | }
31 |
32 | public fun Form(initialState: T, build: FormBuilder.(T) -> Unit): Form {
33 | val form = FormImpl(initialState)
34 | val builder = FormBuilder(form)
35 | builder.build(initialState)
36 | return form
37 | }
38 |
39 | internal class FormImpl(private val initialState: T) : Form {
40 | private val fieldsMap = mutableMapOf>()
41 |
42 | override val fields: List> get() = fieldsMap.values.toList()
43 |
44 | private fun registerField(property: KProperty): FormField {
45 | if (fieldsMap.containsKey(property.name)) {
46 | error("The field cannot be registered repeatedly, field: ${property.name}")
47 | }
48 | val initialValue = when (property) {
49 | is KProperty0<*> -> (property as KProperty0).get()
50 | is KProperty1<*, *> -> @Suppress("UNCHECKED_CAST") (property as KProperty1).get(initialState)
51 | else -> error("Can't get the value from the property: ${property.name}")
52 | }
53 | val formField = FormFieldImpl(property.name, initialValue)
54 | fieldsMap[property.name] = formField
55 | return formField
56 | }
57 |
58 | override fun getOrRegisterField(property: KProperty): FormField {
59 | if (fieldsMap.containsKey(property.name)) {
60 | @Suppress("UNCHECKED_CAST")
61 | return fieldsMap[property.name] as FormField
62 | }
63 | return registerField(property)
64 | }
65 |
66 | override fun getField(name: String): FormField? {
67 | @Suppress("UNCHECKED_CAST")
68 | return fieldsMap[name] as? FormField
69 | }
70 |
71 | override fun replaceField(formField: FormField): FormField {
72 | if (!fieldsMap.containsKey(formField.name)) {
73 | error("The field is not registered, field: ${formField.name}")
74 | }
75 |
76 | @Suppress("UNCHECKED_CAST")
77 | return fieldsMap.put(formField.name, formField) as FormField
78 | }
79 |
80 | override fun validate(): Boolean {
81 | return fieldsMap.values.map { it.validate() }.all { it }
82 | }
83 |
84 | override fun submit(formData: T, validate: Boolean): Boolean {
85 | @Suppress("UNCHECKED_CAST")
86 | formData as? CopyBuilderHost
87 | ?: error("CopyBuilder is not implemented, please apply the `KopyBuilder` plugin")
88 |
89 | val builder = formData.toCopyBuilder()
90 | fieldsMap.filter { builder.contains(it.key) }.forEach {
91 | @Suppress("UNCHECKED_CAST")
92 | val field = it.value as FormField
93 | val value = builder.get(it.key)
94 | field.setValue(value, false)
95 | }
96 |
97 | if (validate) return validate()
98 | return true
99 | }
100 |
101 | override fun pop(shadowedState: T?): T {
102 | val initialState = shadowedState ?: this.initialState
103 | if (fieldsMap.isEmpty()) return initialState
104 |
105 | @Suppress("UNCHECKED_CAST")
106 | initialState as? CopyBuilderHost
107 | ?: error("CopyBuilder is not implemented, please apply the `KopyBuilder` plugin")
108 |
109 | val result = initialState.copyBuild {
110 | fieldsMap
111 | .filter { contains(it.key) }
112 | .forEach { (name, field) ->
113 | put(name, field.currentValue)
114 | }
115 | }
116 | return result
117 | }
118 |
119 | override fun reset() {
120 | this.submit(this.initialState, validate = false)
121 | }
122 |
123 | }
124 |
125 |
126 | public class FormBuilder(public val form: Form) {
127 | public fun field(property: KProperty1): FormField {
128 | return form.getOrRegisterField(property)
129 | }
130 |
131 | public fun field(
132 | property: KProperty1,
133 | build: FormField.() -> Unit
134 | ): FormField {
135 | val field = form.getOrRegisterField(property)
136 | field.build()
137 | return field
138 | }
139 |
140 | /*
141 |
142 | public fun field(property: KProperty0): FormField {
143 | return form.registerField(property)
144 | }
145 |
146 | public fun field(
147 | property: KProperty0,
148 | build: FormField.() -> Unit
149 | ): FormField {
150 | val field = form.registerField(property)
151 | field.build()
152 | return field
153 | }
154 | */
155 | }
156 |
--------------------------------------------------------------------------------
/modules/viform-core/src/commonMain/kotlin/io/github.windedge.viform.core/ValidatorContainerExtension.kt:
--------------------------------------------------------------------------------
1 | package io.github.windedge.viform.core
2 |
3 | public fun ValidatorContainer.addValidator(create: () -> FieldValidator): ValidatorContainer {
4 | val validator = create()
5 | addValidator(validator)
6 | return this
7 | }
8 |
9 | public fun ValidatorContainer.nullable(): ValidatorContainer {
10 | this.addValidator(Nullable())
11 | @Suppress("UNCHECKED_CAST")
12 | return this as ValidatorContainer
13 | }
14 |
15 | public fun ValidatorContainer.nullable(constrains: ValidatorContainer.() -> ValidatorContainer) {
16 | this.addValidator(Nullable())
17 | @Suppress("UNCHECKED_CAST")
18 | (this as ValidatorContainer).constrains()
19 | }
20 |
21 | public fun ValidatorContainer.not(
22 | errorMessage: String? = null,
23 | build: () -> FieldValidator
24 | ): ValidatorContainer =
25 | addValidator { Not(build(), errorMessage) }
26 |
27 | public fun ValidatorContainer.anyOf(
28 | errorMessage: String? = null,
29 | vararg validators: FieldValidator
30 | ): ValidatorContainer =
31 | addValidator { AnyOf(*validators, errorMessage = errorMessage) }
32 |
33 | public fun ValidatorContainer.allOf(
34 | errorMessage: String? = null,
35 | validators: Array>
36 | ): ValidatorContainer =
37 | addValidator { AllOf(*validators, errorMessage = errorMessage) }
38 |
39 | public fun ValidatorContainer.noneOf(
40 | errorMessage: String? = null,
41 | vararg validators: FieldValidator
42 | ): ValidatorContainer =
43 | addValidator { NoneOf(*validators, errorMessage = errorMessage) }
44 |
45 | public fun ValidatorContainer.custom(
46 | errorMessage: String? = null,
47 | validation: (V) -> Boolean
48 | ): ValidatorContainer =
49 | addValidator { Custom(validation, errorMessage) }
50 |
51 | public fun ValidatorContainer.required(errorMessage: String? = null): ValidatorContainer =
52 | addValidator { Required(errorMessage) }
53 |
54 | public fun ValidatorContainer.equals(value: V, errorMessage: String? = null): ValidatorContainer =
55 | addValidator { Equals(value, errorMessage) }
56 |
57 | public fun ValidatorContainer.isNumeric(errorMessage: String? = null): ValidatorContainer =
58 | addValidator { Numeric(errorMessage) }
59 |
60 | public fun ValidatorContainer.isInt(errorMessage: String? = null): ValidatorContainer =
61 | addValidator { Integer(errorMessage) }
62 |
63 | public fun ValidatorContainer.isFloat(errorMessage: String? = null): ValidatorContainer =
64 | addValidator { Integer(errorMessage) }
65 |
66 | public fun ValidatorContainer.isChecked(errorMessage: String? = null): ValidatorContainer =
67 | addValidator { Checked(errorMessage) }
68 |
69 | public fun ValidatorContainer.optional(): ValidatorContainer {
70 | addValidator(Optional())
71 | @Suppress("UNCHECKED_CAST")
72 | return this as ValidatorContainer
73 | }
74 |
75 | public fun ValidatorContainer.optional(constrains: ValidatorContainer.() -> ValidatorContainer): ValidatorContainer {
76 | addValidator(Optional())
77 | @Suppress("UNCHECKED_CAST")
78 | return (this as ValidatorContainer).constrains()
79 | }
80 |
81 | public fun ValidatorContainer.isBlank(errorMessage: String? = null): ValidatorContainer =
82 | addValidator { Blank(errorMessage) }
83 |
84 | public fun ValidatorContainer.isNotBlank(errorMessage: String? = null): ValidatorContainer =
85 | addValidator { NotBlank(errorMessage) }
86 |
87 | public fun ValidatorContainer.isEmpty(errorMessage: String? = null): ValidatorContainer =
88 | addValidator { Empty(errorMessage) }
89 |
90 | public fun ValidatorContainer.isNotEmpty(errorMessage: String? = null): ValidatorContainer =
91 | addValidator { NotEmpty(errorMessage) }
92 |
93 | public fun ValidatorContainer.matchesRegex(
94 | regex: String,
95 | errorMessage: String? = null
96 | ): ValidatorContainer =
97 | addValidator { MatchesRegex(regex, errorMessage) }
98 |
99 | public fun ValidatorContainer.isAlphaNumeric(errorMessage: String? = null): ValidatorContainer =
100 | addValidator { AlphaNumeric(errorMessage) }
101 |
102 | public fun ValidatorContainer.isUrl(errorMessage: String? = null): ValidatorContainer =
103 | addValidator { Url(errorMessage) }
104 |
105 | public fun ValidatorContainer.isEmail(errorMessage: String? = null): ValidatorContainer =
106 | addValidator { Email(errorMessage) }
107 |
108 | public fun ValidatorContainer.minLength(length: Int, errorMessage: String? = null): ValidatorContainer =
109 | addValidator { MinLength(length, errorMessage) }
110 |
111 | public fun ValidatorContainer.maxLength(length: Int, errorMessage: String? = null): ValidatorContainer =
112 | addValidator { MaxLength(length, errorMessage) }
113 |
114 | public fun ValidatorContainer.lengthBetween(
115 | minLength: Int, maxLength: Int, errorMessage: String? = null
116 | ): ValidatorContainer = addValidator { LengthBetween(minLength, maxLength, errorMessage) }
117 |
118 | public fun ValidatorContainer.greaterThan(value: Number, errMsg: String? = null): ValidatorContainer =
119 | addValidator { GreaterThan(value, errMsg) }
120 |
121 | public fun ValidatorContainer.greaterThanOrEquals(
122 | value: Number, errMsg: String? = null
123 | ): ValidatorContainer =
124 | addValidator { GreaterThanOrEquals(value, errMsg) }
125 |
126 | public fun ValidatorContainer.lesserThan(value: Number, errMsg: String? = null): ValidatorContainer =
127 | addValidator { LesserThan(value, errMsg) }
128 |
129 | public fun ValidatorContainer.lesserThanOrEquals(
130 | value: Number, errMsg: String? = null
131 | ): ValidatorContainer =
132 | addValidator { LesserThanOrEquals(value, errMsg) }
133 |
--------------------------------------------------------------------------------
/sandbox/signupapp/src/androidMain/res/drawable/ic_launcher_background.xml:
--------------------------------------------------------------------------------
1 |
2 |
7 |
10 |
15 |
20 |
25 |
30 |
35 |
40 |
45 |
50 |
55 |
60 |
65 |
70 |
75 |
80 |
85 |
90 |
95 |
100 |
105 |
110 |
115 |
120 |
125 |
130 |
135 |
140 |
145 |
150 |
155 |
160 |
165 |
170 |
171 |
--------------------------------------------------------------------------------
/modules/viform-compose/src/commonMain/kotlin/Composable.kt:
--------------------------------------------------------------------------------
1 | package io.github.windedge.viform.compose
2 |
3 | import androidx.compose.runtime.*
4 | import io.github.windedge.viform.core.*
5 | import kotlinx.coroutines.FlowPreview
6 | import kotlinx.coroutines.flow.*
7 | import kotlin.reflect.*
8 |
9 | @Composable
10 | public fun FormHost.useForm(content: @Composable FormScope.(T) -> Unit) {
11 | val state = this.stateFlow.collectAsState()
12 | FormScope(this).content(state.value)
13 | }
14 |
15 | @Composable
16 | public fun Form.use(content: @Composable FormScope.(T) -> Unit) {
17 | val formHost = DefaultFormHost(this)
18 | formHost.useForm(content)
19 | }
20 |
21 | public class FormScope(private val formHost: FormHost) {
22 | private val form: Form = formHost.form
23 |
24 | public val stateFlow: StateFlow = formHost.stateFlow
25 |
26 | @Composable
27 | public fun field(property: KProperty0): FormField {
28 | return form.getOrRegisterField(property)
29 | }
30 |
31 | @Composable
32 | public inline fun field(
33 | property: KProperty0, noinline content: @Composable FieldScope.() -> Unit
34 | ) {
35 | val wrappedType = typeOf()
36 | field(property).wrapAsType(wrappedType, { it }, { it }, content = content)
37 | }
38 |
39 | @Composable
40 | public inline fun FormField.wrapAs(
41 | noinline wrap: FormField.(V) -> R,
42 | noinline unwrap: FormField.(R) -> V,
43 | noinline constraints: ValidatorContainer.() -> Unit = {},
44 | noinline content: @Composable FieldScope.() -> Unit,
45 | ) {
46 | val wrappedType = typeOf()
47 | this.wrapAsType(wrappedType, wrap, unwrap, constraints, content)
48 | }
49 |
50 | @Composable
51 | public fun FormField.wrapAsType(
52 | wrappedType: KType,
53 | wrap: FormField.(V) -> R,
54 | unwrap: FormField.(R) -> V,
55 | constraints: ValidatorContainer.() -> Unit = {},
56 | content: @Composable() (FieldScope.() -> Unit),
57 | ) {
58 | @Suppress("UNCHECKED_CAST")
59 | val wrappedFormField = this as? WrappedFormField ?: remember(this.name) {
60 | WrappedFormField(this, wrappedType, wrap, unwrap).apply {
61 | form.replaceField(this)
62 | applyConstraints(constraints)
63 | }
64 | }
65 | if (wrappedFormField.wrappedType != wrappedType) {
66 | error("Can't wrap as another type!")
67 | }
68 |
69 | DisposableEffect(name) {
70 | onDispose { form.replaceField(wrappedFormField.origin) }
71 | }
72 |
73 | val resultState = this.resultFlow.collectAsState(ValidateResult.None)
74 | val fieldScope: FieldScope = with(wrappedFormField) {
75 | FieldScope(
76 | wrappedState.value,
77 | resultState.value,
78 | ::setWrappedSate,
79 | ::validate,
80 | ::showError,
81 | formHost::pop
82 | )
83 | }
84 | fieldScope.content()
85 | }
86 |
87 | }
88 |
89 | public class FieldScope(
90 | value: V,
91 | result: ValidateResult,
92 | private val onValueChanged: (V, Boolean) -> Unit,
93 | private val onValidate: () -> Boolean,
94 | private val onShowError: (String) -> Unit,
95 | private val onSubmitted: () -> Unit,
96 | ) {
97 | public val currentValue: V = value
98 | public val hasError: Boolean = result.isError
99 | public val errorMessage: String? = result.errorMessage
100 |
101 |
102 | public fun setValue(value: V, validate: Boolean = false, submit: Boolean = false) {
103 | onValueChanged(value, validate)
104 | if (submit) {
105 | onSubmitted()
106 | }
107 | }
108 |
109 | public fun submit() {
110 | onSubmitted()
111 | }
112 |
113 | public fun validate(): Boolean {
114 | return onValidate()
115 | }
116 |
117 | public fun showError(message: String) {
118 | onShowError(message)
119 | }
120 |
121 | @OptIn(FlowPreview::class)
122 | @Composable
123 | public fun watchLazily(debouncedTimeoutMills: Long = 800, block: (V) -> Unit) {
124 | LaunchedEffect(currentValue) {
125 | snapshotFlow { currentValue }.distinctUntilChanged().debounce(debouncedTimeoutMills).collectLatest {
126 | block(it)
127 | }
128 | }
129 | }
130 | }
131 |
132 | internal class WrappedFormField(
133 | val origin: FormField,
134 | val wrappedType: KType,
135 | val wrap: FormField.(V) -> R,
136 | val unwrap: FormField.(R) -> V
137 | ) : FormField by origin {
138 |
139 | private val wrappedValidators = mutableListOf>()
140 |
141 | private val _wrappedState: MutableState = mutableStateOf(wrap(currentValue))
142 | val wrappedState: State get() = _wrappedState
143 |
144 | override fun setValue(value: V, validate: Boolean) {
145 | origin.setValue(value, false)
146 | _wrappedState.value = wrap(value)
147 |
148 | if (validate) validate()
149 | }
150 |
151 | override fun validate(): Boolean {
152 | val results = listOf(
153 | origin.getValidators().validateAndGet(unwrap(_wrappedState.value)),
154 | wrappedValidators.validateAndGet(_wrappedState.value)
155 | )
156 |
157 | return results.find { it.isError }?.also { origin.setResult(it) }?.isSuccess ?: true
158 | }
159 |
160 | fun setWrappedSate(value: R, validate: Boolean = false) {
161 | _wrappedState.value = value
162 | val unwrapValue = unwrap(value)
163 | origin.setValue(unwrapValue, false)
164 |
165 | if (validate) validate()
166 | }
167 |
168 | fun applyConstraints(constraints: ValidatorContainer.() -> Unit) {
169 | val container = SimpleValidatorContainer().apply(constraints)
170 | wrappedValidators.addAll(container.getValidators())
171 | }
172 |
173 | }
174 |
175 | internal class SimpleValidatorContainer : ValidatorContainer {
176 | private val validators = mutableListOf>()
177 |
178 | override fun addValidator(validator: FieldValidator) {
179 | validators.add(validator)
180 | }
181 |
182 | override fun getValidators(): List> = validators.toList()
183 | override fun clearValidators(): Unit = validators.clear()
184 |
185 | }
186 |
187 |
188 | internal class ValidateException(override val message: String) : Exception(message)
--------------------------------------------------------------------------------
/sandbox/signupapp/src/commonMain/kotlin/SignupApp.kt:
--------------------------------------------------------------------------------
1 | package local.sandbox.signupapp
2 |
3 | import androidx.compose.foundation.clickable
4 | import androidx.compose.foundation.layout.*
5 | import androidx.compose.foundation.rememberScrollState
6 | import androidx.compose.foundation.verticalScroll
7 | import androidx.compose.material.*
8 | import androidx.compose.runtime.*
9 | import androidx.compose.ui.Alignment
10 | import androidx.compose.ui.Modifier
11 | import androidx.compose.ui.composed
12 | import androidx.compose.ui.focus.FocusDirection
13 | import androidx.compose.ui.graphics.Color
14 | import androidx.compose.ui.input.key.*
15 | import androidx.compose.ui.platform.LocalFocusManager
16 | import androidx.compose.ui.text.input.PasswordVisualTransformation
17 | import androidx.compose.ui.text.input.VisualTransformation
18 | import androidx.compose.ui.unit.dp
19 | import io.github.windedge.viform.compose.use
20 | import io.github.windedge.viform.core.*
21 |
22 | val schema = FormSchema.create {
23 | field(Signup::name) {
24 | required("User name is required.")
25 | }
26 | field(Signup::email).optional {
27 | isEmail()
28 | }
29 | field(Signup::age).nullable {
30 | greaterThan(0)
31 | }
32 |
33 | // chained style
34 | field(Signup::password).required().lengthBetween(8, 20)
35 |
36 | //custom rule
37 | field(Signup::confirmPassword).required().lengthBetween(8, 20)
38 | .custom("Passwords must be the same.") {
39 | it == field(Signup::password).currentValue
40 | }
41 |
42 | field(Signup::accept) {
43 | isChecked("Your must accept the terms of agreement.")
44 | }
45 | }
46 |
47 | @Composable
48 | fun SignupApp() {
49 | val form = schema.buildForm(Signup())
50 | form.use {
51 | Column(
52 | horizontalAlignment = Alignment.CenterHorizontally,
53 | modifier = Modifier.fillMaxSize().padding(horizontal = 10.dp, vertical = 20.dp)
54 | .verticalScroll(rememberScrollState())
55 | ) {
56 | Surface(elevation = 5.dp) {
57 | Column(modifier = Modifier.padding(horizontal = 20.dp, vertical = 10.dp)) {
58 | field(it::name) {
59 | TextInput("User Name: ", currentValue, hasError, errorMessage, onValueChange = {
60 | setValue(it, validate = true)
61 | })
62 | }
63 | field(it::email) {
64 | watchLazily { validate() }
65 | TextInput("Email:", currentValue ?: "", hasError, errorMessage) {
66 | setValue(it)
67 | }
68 | }
69 | field(it::age).wrapAs(
70 | wrap = { it?.toString() },
71 | unwrap = { it?.toIntOrNull() },
72 | constraints = { optional { isInt() } },
73 | ) {
74 | TextInput("Age:", currentValue ?: "", hasError, errorMessage) {
75 | setValue(it)
76 | }
77 | }
78 | field(it::password) {
79 | watchLazily { if (it.isNotEmpty()) validate() }
80 | TextInput("Password:", currentValue, hasError, errorMessage, true) {
81 | setValue(it)
82 | }
83 | }
84 |
85 | field(it::confirmPassword) {
86 | watchLazily { if (it.isNotEmpty()) validate() }
87 | TextInput("Confirm Password:", currentValue, hasError, errorMessage, true) {
88 | setValue(it)
89 | }
90 | }
91 |
92 | }
93 | }
94 |
95 | field(it::accept) {
96 | InputLayout(hasError, errorMessage) {
97 | Checkbox(currentValue, onCheckedChange = { setValue(it) })
98 | Text("I accept the terms of the agreement",
99 | modifier = Modifier.clickable { setValue(!currentValue) })
100 | }
101 | }
102 |
103 | Spacer(modifier = androidx.compose.ui.Modifier.height(10.dp))
104 |
105 | var signedUp by remember { mutableStateOf(false) }
106 | if (signedUp) {
107 | Button(onClick = { signedUp = false; form.reset() }) {
108 | Text("Reset", color = Color.White)
109 | }
110 | } else {
111 | Button(onClick = {
112 | signedUp = form.validate()
113 |
114 |
115 | form.pop()
116 |
117 | }) {
118 | Text("Sign up", color = Color.White)
119 | }
120 | }
121 |
122 | if (signedUp) {
123 | val result = form.pop()
124 | Spacer(modifier = androidx.compose.ui.Modifier.height(10.dp))
125 | Text("Your signup's information is: \n${result}")
126 | }
127 | }
128 | }
129 | }
130 |
131 | @Composable
132 | fun TextInput(
133 | label: String,
134 | text: String,
135 | isError: Boolean,
136 | errorMessage: String? = "",
137 | isPassword: Boolean = false,
138 | onValueChange: (String) -> Unit,
139 | ) {
140 | InputLayout(isError = isError, errorMessage = errorMessage) {
141 | OutlinedTextField(
142 | text,
143 | label = { Text(label) },
144 | onValueChange = onValueChange,
145 | singleLine = true,
146 | modifier = Modifier.moveFocusOnTab(),
147 | isError = isError,
148 | visualTransformation = if (isPassword) PasswordVisualTransformation() else VisualTransformation.None
149 | )
150 | }
151 | }
152 |
153 | @Composable
154 | fun InputLayout(isError: Boolean, errorMessage: String? = "", content: @Composable RowScope.() -> Unit) {
155 | Column(modifier = androidx.compose.ui.Modifier.padding(5.dp)) {
156 | Row(
157 | verticalAlignment = Alignment.CenterVertically,
158 | horizontalArrangement = Arrangement.SpaceBetween
159 | ) {
160 | this.content()
161 | }
162 | if (isError) {
163 | Text(
164 | errorMessage ?: "",
165 | color = Color.Red,
166 | modifier = Modifier.padding(top = 5.dp).align(Alignment.End)
167 | )
168 | }
169 | }
170 | }
171 |
172 | fun Modifier.moveFocusOnTab() = composed {
173 | val focusManager = LocalFocusManager.current
174 | onPreviewKeyEvent {
175 | if (it.type == KeyEventType.KeyDown && it.key == Key.Tab) {
176 | focusManager.moveFocus(
177 | if (it.isShiftPressed) FocusDirection.Previous else FocusDirection.Next
178 | )
179 | true
180 | } else {
181 | false
182 | }
183 | }
184 | }
--------------------------------------------------------------------------------
/gradlew:
--------------------------------------------------------------------------------
1 | #!/bin/sh
2 |
3 | #
4 | # Copyright © 2015-2021 the original authors.
5 | #
6 | # Licensed under the Apache License, Version 2.0 (the "License");
7 | # you may not use this file except in compliance with the License.
8 | # You may obtain a copy of the License at
9 | #
10 | # https://www.apache.org/licenses/LICENSE-2.0
11 | #
12 | # Unless required by applicable law or agreed to in writing, software
13 | # distributed under the License is distributed on an "AS IS" BASIS,
14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 | # See the License for the specific language governing permissions and
16 | # limitations under the License.
17 | #
18 |
19 | ##############################################################################
20 | #
21 | # Gradle start up script for POSIX generated by Gradle.
22 | #
23 | # Important for running:
24 | #
25 | # (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
26 | # noncompliant, but you have some other compliant shell such as ksh or
27 | # bash, then to run this script, type that shell name before the whole
28 | # command line, like:
29 | #
30 | # ksh Gradle
31 | #
32 | # Busybox and similar reduced shells will NOT work, because this script
33 | # requires all of these POSIX shell features:
34 | # * functions;
35 | # * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
36 | # «${var#prefix}», «${var%suffix}», and «$( cmd )»;
37 | # * compound commands having a testable exit status, especially «case»;
38 | # * various built-in commands including «command», «set», and «ulimit».
39 | #
40 | # Important for patching:
41 | #
42 | # (2) This script targets any POSIX shell, so it avoids extensions provided
43 | # by Bash, Ksh, etc; in particular arrays are avoided.
44 | #
45 | # The "traditional" practice of packing multiple parameters into a
46 | # space-separated string is a well documented source of bugs and security
47 | # problems, so this is (mostly) avoided, by progressively accumulating
48 | # options in "$@", and eventually passing that to Java.
49 | #
50 | # Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
51 | # and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
52 | # see the in-line comments for details.
53 | #
54 | # There are tweaks for specific operating systems such as AIX, CygWin,
55 | # Darwin, MinGW, and NonStop.
56 | #
57 | # (3) This script is generated from the Groovy template
58 | # https://github.com/gradle/gradle/blob/HEAD/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
59 | # within the Gradle project.
60 | #
61 | # You can find Gradle at https://github.com/gradle/gradle/.
62 | #
63 | ##############################################################################
64 |
65 | # Attempt to set APP_HOME
66 |
67 | # Resolve links: $0 may be a link
68 | app_path=$0
69 |
70 | # Need this for daisy-chained symlinks.
71 | while
72 | APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
73 | [ -h "$app_path" ]
74 | do
75 | ls=$( ls -ld "$app_path" )
76 | link=${ls#*' -> '}
77 | case $link in #(
78 | /*) app_path=$link ;; #(
79 | *) app_path=$APP_HOME$link ;;
80 | esac
81 | done
82 |
83 | # This is normally unused
84 | # shellcheck disable=SC2034
85 | APP_BASE_NAME=${0##*/}
86 | # Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036)
87 | APP_HOME=$( cd "${APP_HOME:-./}" > /dev/null && pwd -P ) || exit
88 |
89 | # Use the maximum available, or set MAX_FD != -1 to use that value.
90 | MAX_FD=maximum
91 |
92 | warn () {
93 | echo "$*"
94 | } >&2
95 |
96 | die () {
97 | echo
98 | echo "$*"
99 | echo
100 | exit 1
101 | } >&2
102 |
103 | # OS specific support (must be 'true' or 'false').
104 | cygwin=false
105 | msys=false
106 | darwin=false
107 | nonstop=false
108 | case "$( uname )" in #(
109 | CYGWIN* ) cygwin=true ;; #(
110 | Darwin* ) darwin=true ;; #(
111 | MSYS* | MINGW* ) msys=true ;; #(
112 | NONSTOP* ) nonstop=true ;;
113 | esac
114 |
115 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
116 |
117 |
118 | # Determine the Java command to use to start the JVM.
119 | if [ -n "$JAVA_HOME" ] ; then
120 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
121 | # IBM's JDK on AIX uses strange locations for the executables
122 | JAVACMD=$JAVA_HOME/jre/sh/java
123 | else
124 | JAVACMD=$JAVA_HOME/bin/java
125 | fi
126 | if [ ! -x "$JAVACMD" ] ; then
127 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
128 |
129 | Please set the JAVA_HOME variable in your environment to match the
130 | location of your Java installation."
131 | fi
132 | else
133 | JAVACMD=java
134 | if ! command -v java >/dev/null 2>&1
135 | then
136 | die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
137 |
138 | Please set the JAVA_HOME variable in your environment to match the
139 | location of your Java installation."
140 | fi
141 | fi
142 |
143 | # Increase the maximum file descriptors if we can.
144 | if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
145 | case $MAX_FD in #(
146 | max*)
147 | # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
148 | # shellcheck disable=SC2039,SC3045
149 | MAX_FD=$( ulimit -H -n ) ||
150 | warn "Could not query maximum file descriptor limit"
151 | esac
152 | case $MAX_FD in #(
153 | '' | soft) :;; #(
154 | *)
155 | # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
156 | # shellcheck disable=SC2039,SC3045
157 | ulimit -n "$MAX_FD" ||
158 | warn "Could not set maximum file descriptor limit to $MAX_FD"
159 | esac
160 | fi
161 |
162 | # Collect all arguments for the java command, stacking in reverse order:
163 | # * args from the command line
164 | # * the main class name
165 | # * -classpath
166 | # * -D...appname settings
167 | # * --module-path (only if needed)
168 | # * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
169 |
170 | # For Cygwin or MSYS, switch paths to Windows format before running java
171 | if "$cygwin" || "$msys" ; then
172 | APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
173 | CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" )
174 |
175 | JAVACMD=$( cygpath --unix "$JAVACMD" )
176 |
177 | # Now convert the arguments - kludge to limit ourselves to /bin/sh
178 | for arg do
179 | if
180 | case $arg in #(
181 | -*) false ;; # don't mess with options #(
182 | /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
183 | [ -e "$t" ] ;; #(
184 | *) false ;;
185 | esac
186 | then
187 | arg=$( cygpath --path --ignore --mixed "$arg" )
188 | fi
189 | # Roll the args list around exactly as many times as the number of
190 | # args, so each arg winds up back in the position where it started, but
191 | # possibly modified.
192 | #
193 | # NB: a `for` loop captures its iteration list before it begins, so
194 | # changing the positional parameters here affects neither the number of
195 | # iterations, nor the values presented in `arg`.
196 | shift # remove old arg
197 | set -- "$@" "$arg" # push replacement arg
198 | done
199 | fi
200 |
201 |
202 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
203 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
204 |
205 | # Collect all arguments for the java command:
206 | # * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments,
207 | # and any embedded shellness will be escaped.
208 | # * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be
209 | # treated as '${Hostname}' itself on the command line.
210 |
211 | set -- \
212 | "-Dorg.gradle.appname=$APP_BASE_NAME" \
213 | -classpath "$CLASSPATH" \
214 | org.gradle.wrapper.GradleWrapperMain \
215 | "$@"
216 |
217 | # Stop when "xargs" is not available.
218 | if ! command -v xargs >/dev/null 2>&1
219 | then
220 | die "xargs is not available"
221 | fi
222 |
223 | # Use "xargs" to parse quoted args.
224 | #
225 | # With -n1 it outputs one arg per line, with the quotes and backslashes removed.
226 | #
227 | # In Bash we could simply go:
228 | #
229 | # readarray ARGS < <( xargs -n1 <<<"$var" ) &&
230 | # set -- "${ARGS[@]}" "$@"
231 | #
232 | # but POSIX shell has neither arrays nor command substitution, so instead we
233 | # post-process each arg (as a line of input to sed) to backslash-escape any
234 | # character that might be a shell metacharacter, then use eval to reverse
235 | # that process (while maintaining the separation between arguments), and wrap
236 | # the whole thing up as a single "set" statement.
237 | #
238 | # This will of course break if any of these variables contains a newline or
239 | # an unmatched quote.
240 | #
241 |
242 | eval "set -- $(
243 | printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
244 | xargs -n1 |
245 | sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
246 | tr '\n' ' '
247 | )" '"$@"'
248 |
249 | exec "$JAVACMD" "$@"
250 |
--------------------------------------------------------------------------------
/sandbox/gradlew:
--------------------------------------------------------------------------------
1 | #!/bin/sh
2 |
3 | #
4 | # Copyright © 2015-2021 the original authors.
5 | #
6 | # Licensed under the Apache License, Version 2.0 (the "License");
7 | # you may not use this file except in compliance with the License.
8 | # You may obtain a copy of the License at
9 | #
10 | # https://www.apache.org/licenses/LICENSE-2.0
11 | #
12 | # Unless required by applicable law or agreed to in writing, software
13 | # distributed under the License is distributed on an "AS IS" BASIS,
14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 | # See the License for the specific language governing permissions and
16 | # limitations under the License.
17 | #
18 |
19 | ##############################################################################
20 | #
21 | # Gradle start up script for POSIX generated by Gradle.
22 | #
23 | # Important for running:
24 | #
25 | # (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
26 | # noncompliant, but you have some other compliant shell such as ksh or
27 | # bash, then to run this script, type that shell name before the whole
28 | # command line, like:
29 | #
30 | # ksh Gradle
31 | #
32 | # Busybox and similar reduced shells will NOT work, because this script
33 | # requires all of these POSIX shell features:
34 | # * functions;
35 | # * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
36 | # «${var#prefix}», «${var%suffix}», and «$( cmd )»;
37 | # * compound commands having a testable exit status, especially «case»;
38 | # * various built-in commands including «command», «set», and «ulimit».
39 | #
40 | # Important for patching:
41 | #
42 | # (2) This script targets any POSIX shell, so it avoids extensions provided
43 | # by Bash, Ksh, etc; in particular arrays are avoided.
44 | #
45 | # The "traditional" practice of packing multiple parameters into a
46 | # space-separated string is a well documented source of bugs and security
47 | # problems, so this is (mostly) avoided, by progressively accumulating
48 | # options in "$@", and eventually passing that to Java.
49 | #
50 | # Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
51 | # and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
52 | # see the in-line comments for details.
53 | #
54 | # There are tweaks for specific operating systems such as AIX, CygWin,
55 | # Darwin, MinGW, and NonStop.
56 | #
57 | # (3) This script is generated from the Groovy template
58 | # https://github.com/gradle/gradle/blob/HEAD/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
59 | # within the Gradle project.
60 | #
61 | # You can find Gradle at https://github.com/gradle/gradle/.
62 | #
63 | ##############################################################################
64 |
65 | # Attempt to set APP_HOME
66 |
67 | # Resolve links: $0 may be a link
68 | app_path=$0
69 |
70 | # Need this for daisy-chained symlinks.
71 | while
72 | APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
73 | [ -h "$app_path" ]
74 | do
75 | ls=$( ls -ld "$app_path" )
76 | link=${ls#*' -> '}
77 | case $link in #(
78 | /*) app_path=$link ;; #(
79 | *) app_path=$APP_HOME$link ;;
80 | esac
81 | done
82 |
83 | # This is normally unused
84 | # shellcheck disable=SC2034
85 | APP_BASE_NAME=${0##*/}
86 | # Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036)
87 | APP_HOME=$( cd "${APP_HOME:-./}" > /dev/null && pwd -P ) || exit
88 |
89 | # Use the maximum available, or set MAX_FD != -1 to use that value.
90 | MAX_FD=maximum
91 |
92 | warn () {
93 | echo "$*"
94 | } >&2
95 |
96 | die () {
97 | echo
98 | echo "$*"
99 | echo
100 | exit 1
101 | } >&2
102 |
103 | # OS specific support (must be 'true' or 'false').
104 | cygwin=false
105 | msys=false
106 | darwin=false
107 | nonstop=false
108 | case "$( uname )" in #(
109 | CYGWIN* ) cygwin=true ;; #(
110 | Darwin* ) darwin=true ;; #(
111 | MSYS* | MINGW* ) msys=true ;; #(
112 | NONSTOP* ) nonstop=true ;;
113 | esac
114 |
115 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
116 |
117 |
118 | # Determine the Java command to use to start the JVM.
119 | if [ -n "$JAVA_HOME" ] ; then
120 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
121 | # IBM's JDK on AIX uses strange locations for the executables
122 | JAVACMD=$JAVA_HOME/jre/sh/java
123 | else
124 | JAVACMD=$JAVA_HOME/bin/java
125 | fi
126 | if [ ! -x "$JAVACMD" ] ; then
127 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
128 |
129 | Please set the JAVA_HOME variable in your environment to match the
130 | location of your Java installation."
131 | fi
132 | else
133 | JAVACMD=java
134 | if ! command -v java >/dev/null 2>&1
135 | then
136 | die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
137 |
138 | Please set the JAVA_HOME variable in your environment to match the
139 | location of your Java installation."
140 | fi
141 | fi
142 |
143 | # Increase the maximum file descriptors if we can.
144 | if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
145 | case $MAX_FD in #(
146 | max*)
147 | # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
148 | # shellcheck disable=SC2039,SC3045
149 | MAX_FD=$( ulimit -H -n ) ||
150 | warn "Could not query maximum file descriptor limit"
151 | esac
152 | case $MAX_FD in #(
153 | '' | soft) :;; #(
154 | *)
155 | # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
156 | # shellcheck disable=SC2039,SC3045
157 | ulimit -n "$MAX_FD" ||
158 | warn "Could not set maximum file descriptor limit to $MAX_FD"
159 | esac
160 | fi
161 |
162 | # Collect all arguments for the java command, stacking in reverse order:
163 | # * args from the command line
164 | # * the main class name
165 | # * -classpath
166 | # * -D...appname settings
167 | # * --module-path (only if needed)
168 | # * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
169 |
170 | # For Cygwin or MSYS, switch paths to Windows format before running java
171 | if "$cygwin" || "$msys" ; then
172 | APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
173 | CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" )
174 |
175 | JAVACMD=$( cygpath --unix "$JAVACMD" )
176 |
177 | # Now convert the arguments - kludge to limit ourselves to /bin/sh
178 | for arg do
179 | if
180 | case $arg in #(
181 | -*) false ;; # don't mess with options #(
182 | /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
183 | [ -e "$t" ] ;; #(
184 | *) false ;;
185 | esac
186 | then
187 | arg=$( cygpath --path --ignore --mixed "$arg" )
188 | fi
189 | # Roll the args list around exactly as many times as the number of
190 | # args, so each arg winds up back in the position where it started, but
191 | # possibly modified.
192 | #
193 | # NB: a `for` loop captures its iteration list before it begins, so
194 | # changing the positional parameters here affects neither the number of
195 | # iterations, nor the values presented in `arg`.
196 | shift # remove old arg
197 | set -- "$@" "$arg" # push replacement arg
198 | done
199 | fi
200 |
201 |
202 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
203 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
204 |
205 | # Collect all arguments for the java command:
206 | # * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments,
207 | # and any embedded shellness will be escaped.
208 | # * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be
209 | # treated as '${Hostname}' itself on the command line.
210 |
211 | set -- \
212 | "-Dorg.gradle.appname=$APP_BASE_NAME" \
213 | -classpath "$CLASSPATH" \
214 | org.gradle.wrapper.GradleWrapperMain \
215 | "$@"
216 |
217 | # Stop when "xargs" is not available.
218 | if ! command -v xargs >/dev/null 2>&1
219 | then
220 | die "xargs is not available"
221 | fi
222 |
223 | # Use "xargs" to parse quoted args.
224 | #
225 | # With -n1 it outputs one arg per line, with the quotes and backslashes removed.
226 | #
227 | # In Bash we could simply go:
228 | #
229 | # readarray ARGS < <( xargs -n1 <<<"$var" ) &&
230 | # set -- "${ARGS[@]}" "$@"
231 | #
232 | # but POSIX shell has neither arrays nor command substitution, so instead we
233 | # post-process each arg (as a line of input to sed) to backslash-escape any
234 | # character that might be a shell metacharacter, then use eval to reverse
235 | # that process (while maintaining the separation between arguments), and wrap
236 | # the whole thing up as a single "set" statement.
237 | #
238 | # This will of course break if any of these variables contains a newline or
239 | # an unmatched quote.
240 | #
241 |
242 | eval "set -- $(
243 | printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
244 | xargs -n1 |
245 | sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
246 | tr '\n' ' '
247 | )" '"$@"'
248 |
249 | exec "$JAVACMD" "$@"
250 |
--------------------------------------------------------------------------------
/modules/viform-core/src/commonMain/kotlin/io/github.windedge.viform.core/FieldValidator.kt:
--------------------------------------------------------------------------------
1 | package io.github.windedge.viform.core
2 |
3 |
4 | public interface FieldValidator {
5 | public fun preview(input: V): ValidateResult = ValidateResult.None
6 | public fun validate(input: V): ValidateResult = ValidateResult.None
7 | public val errorMessage: String?
8 | }
9 |
10 | public fun List>.validateAndGet(input: V): ValidateResult {
11 | this.map { it.preview(input) }.find { it != ValidateResult.None }?.let { return it }
12 | return this.map { it.validate(input) }.find { it.isError } ?: ValidateResult.Success
13 | }
14 |
15 | public class Nullable(override val errorMessage: String? = null) : FieldValidator {
16 | override fun preview(input: V): ValidateResult {
17 | if (input == null) {
18 | return ValidateResult.Success
19 | }
20 | return ValidateResult.None
21 | }
22 | }
23 |
24 | public abstract class LogicalValidator : FieldValidator {
25 | public abstract fun validateFunc(input: V): ValidateResult
26 |
27 | override fun preview(input: V): ValidateResult = ValidateResult.None
28 |
29 | override fun validate(input: V): ValidateResult = validateFunc(input)
30 | }
31 |
32 | public class Not(
33 | private val validator: FieldValidator, override val errorMessage: String? = null
34 | ) : LogicalValidator() {
35 |
36 | override fun validateFunc(input: V): ValidateResult {
37 | val result = validator.validate(input)
38 | if (result.isSuccess) {
39 | return ValidateResult.Failure(errorMessage ?: "Value: $input do not satisfy the negative validation")
40 | }
41 | return ValidateResult.Success
42 | }
43 |
44 | }
45 |
46 | public class AnyOf(
47 | private vararg val validators: FieldValidator, override val errorMessage: String? = null
48 | ) : LogicalValidator() {
49 | override fun validateFunc(input: V): ValidateResult {
50 | val results = validators.map { it.validate(input) }
51 | val success = results.any { it.isSuccess }
52 | if (success) {
53 | return ValidateResult.Success
54 | }
55 |
56 | return results.first { it.isError }
57 | }
58 | }
59 |
60 | public class AllOf(
61 | private vararg val validators: FieldValidator, override val errorMessage: String? = null
62 | ) : LogicalValidator() {
63 | override fun validateFunc(input: V): ValidateResult {
64 | val results = validators.map { it.validate(input) }
65 | val success = results.all { it.isSuccess }
66 | if (success) {
67 | return ValidateResult.Success
68 | }
69 |
70 | return results.first { it.isError }
71 | }
72 | }
73 |
74 | public class NoneOf(
75 | private vararg val validators: FieldValidator