Coder Social home page Coder Social logo

icerockdev / moko-units Goto Github PK

View Code? Open in Web Editor NEW
25.0 6.0 11.0 473 KB

Composing units into list and show in RecyclerView/UITableView/UICollectionView. Control your lists from common code for mobile (android & ios) Kotlin Multiplatform development

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

License: Apache License 2.0

Ruby 1.54% Kotlin 79.93% Swift 18.53%
android ios kotlin kotlin-multiplatform kotlin-native cocoapod recyclerview uitableview uicollectionview moko

moko-units's Introduction

moko-units
GitHub license Download kotlin-version

Mobile Kotlin units

This is a Kotlin MultiPlatform library that provides RecyclerView/UITableView/UICollectionView filling from common code.

Table of Contents

Features

  • Control UI lists from common code - content for RecyclerView/UITableView/UICollectionView creating from common kotlin code.

Requirements

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

Installation

root build.gradle

buildscript {
    repositories {
        gradlePluginPortal()
    }

    dependencies {
        classpath("dev.icerock.moko:units-generator:0.8.0")
    }
}


allprojects {
    repositories {
       mavenCentral()
    }
}

project build.gradle

dependencies {
    commonMainApi("dev.icerock.moko:units:0.8.0")
    commonMainImplementation("dev.icerock.moko:units-basic:0.8.0")

    commonTestImplementation("dev.icerock.moko:units-test:0.8.0")
}

On iOS, in addition to the Kotlin library add Pod in the Podfile.

pod 'MultiPlatformLibraryUnits', :git => 'https://github.com/icerockdev/moko-units.git', :tag => 'release/0.8.0'

MultiPlatformLibraryUnits CocoaPod requires that the framework compiled from Kotlin be named MultiPlatformLibrary and be connected as a CocoaPod MultiPlatformLibrary. Here's an example. To simplify integration with MultiPlatformFramework you can use mobile-multiplatform-plugin.
MultiPlatformLibraryUnits CocoaPod contains an swift additions for UnitDataSources of UITableView/UICollectionView.

In android build.gradle

databinding usage

apply plugin: "dev.icerock.mobile.multiplatform-units"

dependencies {
    implementation("dev.icerock.moko:units-databinding:0.8.0")
}

multiplatformUnits {
    classesPackage = "org.example.library.units"
    dataBindingPackage = "org.example.library"
    layoutsSourceSet = "main"
}

viewbinding usage

dependencies {
    implementation("dev.icerock.moko:units-viewbinding:0.8.0")
}

Usage

common:

interface UnitFactory {
    fun createHeader(text: String): TableUnitItem
    fun createProfileTile(profileId: Long, avatarUrl: String, username: String): TableUnitItem
}

class ViewModel(unitFactory: UnitFactory) {
    val items = listOf(
        unitFactory.createHeader("Programmers"),
        unitFactory.createProfileTile(1, "url", "Mikhailov"),
        unitFactory.createProfileTile(2, "url", "Babenko"),
        unitFactory.createProfileTile(3, "url", "Tchernov"),
        unitFactory.createHeader("Designers"),
        unitFactory.createProfileTile(4, "url", "Eugeny")
    )
}

android with databinding (using module units-databinding)

<androidx.recyclerview.widget.RecyclerView
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            app:bindValue="@{viewModel.items}"
            app:adapter="@{`dev.icerock.moko.units.adapter.UnitsRecyclerViewAdapter`}"
            app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager"/>
object UnitFactoryImpl: UnitFactory {
    fun createHeader(text: String): TableUnitItem {
        return LayoutHeader()
            .setText(text)
            .setItemId(text.hashCode())
    }
    
    fun createProfileTile(profileId: Long, avatarUrl: String, username: String): TableUnitItem {
        return LayoutProfileTile()
            .setAvatarUrl(avatarUrl)
            .setUserName(username)
            .setItemId(profileId)
    }
}
mBinding.viewModel = ViewModel(UnitFactoryImpl)

android with viewbinding (using module units-viewbinding)

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">

    <TextView
        android:id="@+id/unit_blue_divider_textView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="#2196F3" />
</LinearLayout>

For every unit_layout.xml should create class using viewbinding-generated class UnitLayoutBinding

class UnitBlueDivider(override val itemId: Long) :
    VBTableUnitItem<UnitBlueDividerBinding>() {

    override val layoutId: Int = R.layout.unit_blue_divider

    override fun bindView(view: View): UnitBlueDividerBinding {
        return UnitBlueDividerBinding.bind(view)
    }

    override fun UnitBlueDividerBinding.bindData(
        context: Context,
        lifecycleOwner: LifecycleOwner,
        viewHolder: VBViewHolder<UnitBlueDividerBinding>
    ) {
        this.unitBlueDividerTextView.setBackgroundColor(Color.parseColor("#2196F3"))
    }
}

override fun createBlueDividerUnit(id: Long): TableUnitItem {
    return UnitBlueDivider(
        itemId = id
    )
}

On Android you can use units with viewbinding or with databinding, just plug in the corresponding module: units-viewbinding or units-databinding

iOS:

class UnitFactoryImpl: NSObject, UnitFactory {

  func createHeader(text: String) -> TableUnitItem {
    let data = HeaderTableViewCell.CellModel(text: text)
    return UITableViewCellUnit<HeaderTableViewCell>(
      data: data,
      itemId: text.hashCode(),
      configurator: nil)
  }
  
  func createProfileTile(profileId: Long, avatarUrl: String, username: String) -> TableUnitItem {
    let data = ProfileTableViewCell.CellModel(avatarUrl: avatarUrl, username: username)
    return UITableViewCellUnit<ProfileTableViewCell>(
      data: data,
      itemId: profileId,
      configurator: nil)
  }
}
let viewModel = ViewModel(unitFactory: UnitFactoryImpl())
let tableDataSource = TableUnitsSourceKt.default(for: tableView)
tableDataSource.units = viewModel.items
tableView.reloadTable()

Different unit's UI in dropdown list with units-viewbinding

If you want to use units in dropdown list you should implement DropDownUnitItem. Abstract class VBDropDownUnitItem already implement it so you can use it. If you want the units UI will be different when dropdown list is close or open, you need to implement another interface TableUnitItem which already implemented in VBTableUnitItem. The sample you can see here

Different unit's UI in dropdown list with units-databinding

Only what you need to make different UI to units in closed and open dropdown list with databinding is an another layout with _dropdown postfix sample_unit.xml for sample unit, sample_unit_dropdown.xml for dropdown unit

Samples

Please see more examples in the sample directory.

Set Up Locally

Contributing

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

The develop branch is pushed to master on release.

For more details on contributing please see the 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-units's People

Contributors

alex009 avatar anton6tak avatar atchernov avatar belousovgm avatar dorofeev avatar khachapurya avatar kovalandrew avatar zixops avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  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-units's Issues

ItemGenerator plugin issues

  1. Incorrect parse of Generic-types into another Generic, like LiveData<List<Double>>
  2. Java-types should be converted to Kotlin-types. Currently types like Integer generate to kotlin.Integer, but should be kotlin.Int. Check for another types and fix generator

0.2.1 version don't compile

e: Compilation failed: Could not find serialized descriptor for index: -2639035847497420885 dev.icerock.moko.units,UnitCollectionViewDataSource,<init>
cannot compile 0.2.1 version with top error. 0.2.0-dev-4 release work.

Generate `setup` method for better developer experience

Now tile setup looks like this:
image
And I have to manually write setup stuff, while with IDE support I can get hints like below:
image

This looks like a little improvement, but actually, it may be very useful for someone (including me).

Potentially, it may decrease the amount of boilerplate code when writing factory functions, since you can just copy parameters to your function from this:
image

Wrong calculating of units diff

It looks like sometimes the diff calculation does not work correctly after updating the unit list. A prime example is adding the end of the list the loading unit to display the loading process of the next page of the list. After deleting the loading unit then for all units will be called binding again.

Maybe we can add a callback to calculate the diff or to specify the correct identifier or hash of the unit data outside (or pass a comparator or something).

Break down a list by section

Hi, guys!

I have a ๐Ÿš€Feature request.

Is it possible to group items by sections? Ideally make them expandable/collapsable. I understand that in this case pagination wouldn't be supported. Looking for something like this:
Expand/collapse sections image

Would be great to also support different type of cells/rows based on unit name/type. For example:
A mix of different type of cells image

Let me know if I should create a separate feature request for both. I wasn't sure if it's even on your scope of dev pipeline.

Thanks!

android.view.ContextThemeWrapper cannot be cast to android.app.Activity

The problem occurs when trying to use the @BindingAdapter("adapter") inside the android.support.design.widget.BottomSheetDialogFragment.

java.lang.ClassCastException: android.view.ContextThemeWrapper cannot be cast to androidx.lifecycle.LifecycleOwner
at dev.icerock.moko.units.databinding.BindingAdaptersKt.setAdapter(BindingAdapters.kt:50)

Disable Reusable protocol requiring on iOS unit constructors

Now on most project we've use default extension for Reusable protocol:

extension UITableViewCell: Reusable {
    // MARK: - Reusable
    static func xibName() -> String { return String(describing: self) }
    static func reusableIdentifier() -> String { return String(describing: self) }
}

So, will be nice to relocate that logic to unit creation and cell registering

Diffable datasource doesn't update currently visible cells when new units comes

extension TableUnitsSourceKt {
  public static func diffable(
    for tableView: UITableView,
    deletionAnimation: DiffRowAnimation = .automatic,
    insertionAnimation: DiffRowAnimation = .automatic) -> TableUnitsSource {
    return TableUnitsSourceKt.create(forTableView: tableView) { (view, old, new) in
      view.animateRowChanges(
        oldData: old ?? [],
        newData: new ?? [],
        isEqual: { $0.itemId == $1.itemId },
        deletionAnimation: deletionAnimation,
        insertionAnimation: insertionAnimation)
    //Visible cell should be updated here for forTableView.indexPathsForVisibleRows
    }
  }
}

And some for collection units source

Multiple RecyclerView UnitItems

I'd like to implement pagination on the RV, however I am not sure how to add a second unit (or a viewholder) for the loading view , that I then remove when more items are loaded.

Currently I only have a method to create a single ViewHolder (tile)

interface UnitsFactory<T> {
        fun createItemTile(data: T): CollectionUnitItem
    }

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-units-basic 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

Crash on reload with diffable data source

exception message:

Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Invalid update: invalid number of rows in section 0. The number of rows contained in an existing section after the update (7) must be equal to the number of rows contained in that section before the update (1), plus or minus the number of rows inserted or deleted from that section (0 inserted, 0 deleted) and plus or minus the number of rows moved into or out of that section (0 moved in, 0 moved out).

how to reproduce:

  • load table view with one set of units
  • begin update table view with another set of units using diffable data source
  • interrupt update animation, for example navigate to another screen
  • try to update table view with second set of units

Looks like table view have not updated with old units set, but it use to obtain diff with new units set.

Maybe need add extra check to ensure that old units set is actual before update

Cleanup swift additions

Now iOS-side components like UnitTableViewDataSource and UnitCollectionViewDataSource is converted to kotlin version. Now need decide what swift additions should be removed, what should be added to kotlin and what should be in pod.

ViewBinding support out of box

import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.lifecycle.LifecycleOwner
import androidx.recyclerview.widget.RecyclerView
import dev.icerock.moko.units.TableUnitItem
โ€‹
abstract class VBTableUnitItem<VB> : TableUnitItem {
โ€‹
    @Suppress("UNCHECKED_CAST")
    override fun bindViewHolder(viewHolder: RecyclerView.ViewHolder) {
        bind(viewHolder.itemView.context, (viewHolder as VBViewHolder<VB>).binding)
    }
โ€‹
    override fun createViewHolder(
        parent: ViewGroup,
        lifecycleOwner: LifecycleOwner
    ): RecyclerView.ViewHolder {
        val binding = inflate(LayoutInflater.from(parent.context), parent)
        return VBViewHolder(binding, binding.root())
    }
โ€‹
    abstract fun inflate(inflater: LayoutInflater, parent: ViewGroup): VB
โ€‹
    abstract fun VB.root(): View
โ€‹
    abstract fun bind(context: Context, binding: VB)
โ€‹
    class VBViewHolder<VB>(
        val binding: VB,
        root: View
    ) : RecyclerView.ViewHolder(root)
}

here sample of base support for units

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.