Coder Social home page Coder Social logo

icerockdev / moko-fields Goto Github PK

View Code? Open in Web Editor NEW
19.0 6.0 7.0 291 KB

Input forms for mobile (android & ios) Kotlin Multiplatform development

Home Page: https://moko.icerock.dev/

License: Apache License 2.0

Kotlin 74.46% Ruby 0.43% Swift 25.11%
android ios kotlin-native kotlin-multiplatform forms livedata moko kotlin-multiplatform-mobile

moko-fields's Introduction

moko-fields
GitHub license Download kotlin-version

Mobile Kotlin fields

This is a Kotlin MultiPlatform library that add form fields abstraction to implement any input forms with validations.

Table of Contents

Features

  • Input field abstraction;
  • Validation based on reactive approach (on LiveData from moko-mvvm or Flow from kotlinx.coroutines).

Requirements

  • Gradle version 6.8+
  • Android API 16+
  • iOS version 11.0+

Installation

root build.gradle

allprojects {
    repositories {
      mavenCentral()
    }
}

project build.gradle

dependencies {
    commonMainApi("dev.icerock.moko:fields-core:0.12.0")

    // integration with reactive flows
    commonMainApi("dev.icerock.moko:fields-livedata:0.12.0")
    commonMainApi("dev.icerock.moko:fields-flow:0.12.0")
 
    androidMainApi("dev.icerock.moko:fields-material:0.12.0")
}

Flow additions

to work correctly on the iOS side, you need to export the mvvm-flow and mvvm-core dependencies to the iOS framework.

Usage

Live Data

Create FormField to text input with empty validation:

val textField = FormField<String, StringDesc>("", { inputLiveData ->
    inputLiveData.map { text ->
        if (text.isBlank()) "should be not blank!".desc()
        else null
    }
})

Use liveBlock to simplify validation create.

val textField = FormField<String, StringDesc>("", liveBlock { text ->
    if (text.isBlank()) "should be not blank!".desc()
    else null
})

Use LiveData in validation lambda to merge with other fields.

val passwordField = FormField<String, StringDesc>("", { inputLiveData ->
    inputLiveData.map { text ->
        if (text.isBlank()) "should be not blank!".desc()
        else null
    }
})
val passwordConfirmField = FormField<String, StringDesc>("", { inputLiveData ->
    passwordField.data.mergeWith(inputLiveData) { password, passwordConfirm ->
        if (passwordConfirm.isBlank()) "should be not blank!".desc()
        else if(passwordConfirm != password) "passwords not same".desc()
        else null
    }
})

Call validate to perform validations and show error to user by field.error LiveData.

class LoginViewModel(
    override val eventsDispatcher: EventsDispatcher<EventsListener>
) : ViewModel(), EventsDispatcherOwner<LoginViewModel.EventsListener> {
    val emailField = FormField<String, StringDesc>("", liveBlock { email ->
        if (email.isBlank()) MR.strings.cant_be_blank.desc()
        else null
    })
    val passwordField = FormField<String, StringDesc>("", liveBlock { password ->
        if (password.isBlank()) MR.strings.cant_be_blank.desc()
        else null
    })

    private val fields = listOf(emailField, passwordField)

    fun onLoginPressed() {
        if (!fields.validate()) return

        val email = emailField.value()
        val password = passwordField.value()
        val message = "$email:$password"

        eventsDispatcher.dispatchEvent { showMessage(message.desc()) }
    }

    interface EventsListener {
        fun showMessage(message: StringDesc)
    }
}

Bind FormField to UI by data and error LiveDatas.

<com.google.android.material.textfield.TextInputLayout
    app:error="@{viewModel.emailField.error.ld}">

    <EditText
        android:text="@={viewModel.emailField.data.ld}" />
</com.google.android.material.textfield.TextInputLayout>
emailField.bindTextTwoWay(liveData: viewModel.emailField.data)
emailField.bindError(liveData: viewModel.emailField.error)

Flow

Create FormField to text input with empty validation:

val emailField: FormField<String, StringDesc> = FormField(
    scope = viewModelScope,
    initialValue = "",
    validationTransform = { email ->
        ValidationResult.of(email) {
            notBlank(MR.strings.cant_be_blank.desc())
            matchRegex(MR.strings.wrong_format.desc(), EMAIL_REGEX)
        }
    }
)

FormField to work with coroutines, CoroutineScope is required.

Call validate to perform validations and show error to user by field.error StateFlow.

class LoginViewModel : ViewModel() {
    private val _actions: Channel<Action> = Channel(Channel.BUFFERED)
    val actions: CFlow<Action> get() = _actions.receiveAsFlow().cFlow()

    val emailField: FormField<String, StringDesc> = FormField(
        scope = viewModelScope,
        initialValue = "",
        validation = flowBlock { email ->
            ValidationResult.of(email) {
                notBlank(MR.strings.cant_be_blank.desc())
                matchRegex(MR.strings.wrong_format.desc(), EMAIL_REGEX)
            }
        }
    )

    @Suppress("MagicNumber")
    val passwordField: FormField<String, StringDesc> = FormField(
        scope = viewModelScope,
        initialValue = "",
        validation = fieldValidation {
            notBlank(MR.strings.cant_be_blank.desc())
            minLength(MR.strings.must_contain_more_char.desc(), 4)
        }
    )

    private val fields = listOf(emailField, passwordField)

    fun onLoginPressed() {
        if (!fields.validate()) return

        val email = emailField.value()
        val password = passwordField.value()
        val message = "$email:$password"

        _actions.trySend(Action.ShowMessage(message.desc()))
    }

    sealed interface Action {
        data class ShowMessage(val message: StringDesc) : Action
    }

    companion object {
        @Suppress("MaxLineLength")
        private val EMAIL_REGEX =
            Regex("[a-zA-Z0-9\\+\\.\\_\\%\\-\\+]{1,256}\\@[a-zA-Z0-9][a-zA-Z0-9\\-]{0,64}(\\.[a-zA-Z0-9][a-zA-Z0-9\\-]{0,25})+")
    }
}

Bind FormField to UI by data and error StateFlows:

val email: String by viewModel.emailField.data.collectAsState()

TextField(
    placeholder = @Composable { 
        Text("Email") 
    }, 
    value = email, 
    onValueChange = { viewModel.emailField.data.value = it }
)

For ease of use in working with SwiftUI, you can use this CocoaPods dependency.

struct LoginScreen: View {
    @StateObject var viewModel: LoginViewModel = LoginViewModel()
    
    var body: some View {
        LoginScreenBody(
             email: viewModel.binding(\.emailField.data),
             emailError: viewModel.state(\.emailField.error)
        )
    }
}

struct LoginScreenBody: View {
    @Binding var email: String
    let emailError: StringDesc?
    
    var body: some View {
        VStack {
            TextField("email", text: viewModel.binding(\.passwordField.data))
            if let emailError = emailError {
                Text(emailError.localized())
            }
        }
    }
}

Validations packet

There is a useful ValidationResult class for building validation monads for a form fields. Two formats for creating validation are implemented:

  • Chain/monad validation:
ValidationResult.of(emailFieldValue)
    .notBlank(blankErrorStringDesc)
    .matchRegex(wrongEmailErrorStringDesc, EMAIL_REGEX)
    .validate()

For this variant, do not forget to call function validate at the end!

  • DSL validation:
ValidationResult.of(emailFieldValue) {
    notBlank(blankErrorStringDesc)
    matchRegex(wrongEmailErrorStringDesc, EMAIL_REGEX)
}

To create a new function for validation monad, you need to create an extension function of class ValidationResult using builder nextValidation. For example, this is how the ready-made function for checking String values for blankness looks like:

fun ValidationResult<String>.notBlank(errorText: StringDesc) = nextValidation { value ->
    if (value.isNotBlank()) {
        ValidationResult.success(value)
    } else {
        ValidationResult.failure(errorText)
    }
}

All the ready-made validation functions of the library can be found in the source codes in the files AnyValidations.kt for Any class and StringValidations.kt for String class.

To simplify of adding validation to the FormField object (without mapping of a LiveData objects) you can use the builder-function fieldValidation:

val passwordField = FormField<String, StringDesc>(
    initialValue = "",
    validation = fieldValidation {
        notBlank(MR.strings.cant_be_blank.desc())
        minLength(MR.strings.must_contain_more_char.desc(), 4)
    }
)

Samples

More examples can be found in the sample directory or sample-declarative-ui directory.

Set Up Locally

  • In fields-core directory contains the core - validations logic and the interface for interacting with fields;
  • In fields-flow directory contains implementation of the FormField interface using kotlinx.coroutines;
  • In fields-livedata directory contains implementation of the FormField interface using moko-mvvm LiveDatas
  • In sample directory contains samples use fields-livedata on Android, iOS & mpp-library connected to apps
  • In sample-declarative-ui directory contains samples use fields-flow on Android with Compose,on iOS with SwiftUI and shared module connected to apps

Contributing

All development (both new features and bug fixes) is performed in develop branch. This way master sources always contain sources of the most recently released version. Please send PRs with bug fixes to develop branch. Fixes to documentation in markdown files are an exception to this rule. They are updated directly in master.

The develop branch is pushed to master during release.

More detailed guide for contributers see in contributing guide.

License

Copyright 2019 IceRock MAG Inc

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

   http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

moko-fields's People

Contributors

alex009 avatar anton6tak avatar exndy avatar tetraquark avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar

moko-fields's Issues

New extension function for validation: isEqual

It would be useful to have a function something like isEqual to validate equality of Strings or Any objects.

fun comparePasswords(password: String, repeatPassword: String) {
    return ValidationResult.of(password)
        .isEqual(
            sample = repeatPassword,
            errorText = "Passwords must be the same".desc()
        ).validate()
}

Accessor error

Could not find accessor dev.icerock.moko.fields.FormField.ld

Create DSL-like validation

It will be useful to remake fieldValidationBlock as DSL-like function or make new one.

It should look like:

fieldValidationBlock {
    notNull("Field should not be null".desc())
    notBlank("Field should not be blank".desc())
    maxLength("Max length of string is 8".desc(), 8)
}

New extension function for validation: containedIn

It would be useful to have a function containedIn or something for validation like this:

val validValues = listOf("ru", "us")

return ValidationResult.of(value)
    .containedIn(
        validValues = validValues,
        errorText = errorText
    ).validate()

Add bindFormFiled extention for TextInputLayout. Android

In my app i'm use binding with formfield with this short extention:

fun TextInputLayout.bindFormField(
    lifecycleOwner: LifecycleOwner,
    formField: FormField<String, StringDesc>,
) {
    val editText: EditText = this.editText ?: return

    with(editText) {
        this.bindTextTwoWay(lifecycleOwner, formField.data)
        this.setOnFocusChangeListener { _, focused ->
            if (focused) return@setOnFocusChangeListener
            formField.validate()
        }
        bindError(lifecycleOwner, formField.error)
    }
}

Update moko-resources dependency without cinterop-pluralizedString

In moko-resources 0.21.0 release cinterop was removed as unused. But Kotlin/Native have own list of dependencies inside klib. All libraries, that depends on moko-resources, have inside own manifest file in klib dependency to dev.icerock.moko:resources-cinterop-pluralizedString. So gradle download new version of moko-resources (0.21.0) and try to compile project, but Kotlin/Native see own dependencies list and see that moko-fields depends on dev.icerock.moko:resources-cinterop-pluralizedString but that library not exist anymore and gradle not download it.
As result we see:

error: could not find "dev.icerock.moko:resources-cinterop-pluralizedString" in [/Users/amikhailov/.konan/kotlin-native-prebuilt-macos-aarch64-1.8.10/bin, /Users/amikhailov/.konan/klib, /Users/amikhailov/.konan/kotlin-native-prebuilt-macos-aarch64-1.8.10/klib/common, /Users/amikhailov/.konan/kotlin-native-prebuilt-macos-aarch64-1.8.10/klib/platform/ios_arm64]

need to publish new version with updated moko resources

DSL validation ext problem: Type mismatch

Problem when using extension isEqual in block fieldValidation:
Type mismatch.
Required:
ValidationResult
Found:
ValidationResult<String?>
Sample:

val grzField = FormField<String, StringDesc>(
        initialValue = "",
        validation = fieldValidation {
            notBlank(notBlankErrorDesc) // OK
            matchRegex(matchRegexErrorDesc, grzRegex) // OK
            isEqual(isEqualErrorDesc, "") // Type mismatch
        }
    )

Improve SwiftUI usage

here snippet with useful api:

struct Binder {
  static func binding(field: FormField<NSString, StringDesc>) -> Binding<String> {
    return Binding(
      get: { String(field.data.value ?? "") },
      set: { field.setValue(value: ($0 as NSString)) }
    }
  }
}

but in this case we not receive updated of FormField on UI. works only UI -> FormField updates. FormField -> UI updated not implemented

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.