diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..687ca01 --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,52 @@ +name: Validation + +on: + pull_request: + workflow_dispatch: + +permissions: + contents: read + +concurrency: + group: validation-${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }} + cancel-in-progress: true + +jobs: + validate: + runs-on: ubuntu-latest + timeout-minutes: 90 + + steps: + - name: Checkout + uses: actions/checkout@v4 + + - name: Setup Java + uses: actions/setup-java@v4 + with: + distribution: temurin + java-version: '17' + + - name: Setup Gradle + uses: gradle/actions/setup-gradle@v4 + + - name: Setup Android SDK + uses: android-actions/setup-android@v3 + with: + packages: platform-tools + + - name: Install Android SDK packages + run: | + sdkmanager --install \ + "platforms;android-36" \ + "build-tools;36.0.0" + + - name: Run ktlint (Spotless) + run: ./gradlew --no-daemon --stacktrace spotlessCheck + + - name: Run tests and assemble validations + run: | + ./gradlew --no-daemon --stacktrace \ + :amvi-viewmodel:jvmTest \ + :amvi-viewmodel:assembleAndroidMain \ + :amvi-component-compose:jvmTest \ + :amvi-component-compose:assembleAndroidMain diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml new file mode 100644 index 0000000..4c06885 --- /dev/null +++ b/.github/workflows/release.yml @@ -0,0 +1,100 @@ +name: Release Libraries + +on: + push: + tags: + - 'v*' + +permissions: + contents: read + packages: write + +jobs: + publish-libraries: + # iOS targets only compile on macOS; on Linux they are skipped and the release would ship without them + runs-on: macos-latest + environment: release + + steps: + - name: Checkout + uses: actions/checkout@v4 + with: + fetch-depth: 0 + + - name: Setup Java + uses: actions/setup-java@v4 + with: + distribution: temurin + java-version: '17' + + - name: Setup Gradle + uses: gradle/actions/setup-gradle@v4 + + - name: Setup Android SDK + uses: android-actions/setup-android@v3 + with: + packages: platform-tools + + - name: Install Android SDK packages + run: | + sdkmanager --install \ + "platforms;android-36" \ + "build-tools;36.0.0" + - name: Run tests + run: | + ./gradlew --no-daemon --stacktrace \ + :amvi-viewmodel:jvmTest \ + :amvi-component-compose:jvmTest + + - name: Validate tag matches version + run: | + TAG="${GITHUB_REF#refs/tags/}" + VERSION=$(grep '^versionName=' gradle.properties | cut -d'=' -f2) + if [ "v${VERSION}" != "${TAG}" ] && [ "${VERSION}" != "${TAG}" ]; then + echo "Tag '${TAG}' does not match versionName '${VERSION}' in gradle.properties" + exit 1 + fi + + - name: Prepare publishing credentials + env: + NEXUS_USERTOKEN_NAME: ${{ secrets.NEXUS_USERTOKEN_NAME }} + NEXUS_USERTOKEN_PASSWORD: ${{ secrets.NEXUS_USERTOKEN_PASSWORD }} + SIGNING_KEY_ID: ${{ secrets.SIGNING_KEY_ID }} + SIGNING_PASSWORD: ${{ secrets.SIGNING_PASSWORD }} + SIGNING_SECRET_KEY_RING_FILE_BASE64: ${{ secrets.SIGNING_SECRET_KEY_RING_FILE_BASE64 }} + run: | + required_vars=( + NEXUS_USERTOKEN_NAME + NEXUS_USERTOKEN_PASSWORD + SIGNING_KEY_ID + SIGNING_PASSWORD + SIGNING_SECRET_KEY_RING_FILE_BASE64 + ) + + for var in "${required_vars[@]}"; do + if [ -z "${!var}" ]; then + echo "Missing required secret: ${var}" + exit 1 + fi + done + + keyring_file="${RUNNER_TEMP}/signing-secring.gpg" + echo "${SIGNING_SECRET_KEY_RING_FILE_BASE64}" | base64 --decode > "${keyring_file}" + chmod 600 "${keyring_file}" + + mkdir -p "${HOME}/.gradle" + { + echo "mavenCentralUsername=${NEXUS_USERTOKEN_NAME}" + echo "mavenCentralPassword=${NEXUS_USERTOKEN_PASSWORD}" + echo "NEXUS_USERTOKEN_NAME=${NEXUS_USERTOKEN_NAME}" + echo "NEXUS_USERTOKEN_PASSWORD=${NEXUS_USERTOKEN_PASSWORD}" + echo "signing.keyId=${SIGNING_KEY_ID}" + echo "signing.password=${SIGNING_PASSWORD}" + echo "signing.secretKeyRingFile=${keyring_file}" + } >> "${HOME}/.gradle/gradle.properties" + + - name: Publish libraries + run: | + ./gradlew --no-daemon --stacktrace \ + :amvi-viewmodel:publishAndReleaseToMavenCentral \ + :amvi-component-compose:publishAndReleaseToMavenCentral diff --git a/.gitignore b/.gitignore index 8ae6c19..253075a 100644 --- a/.gitignore +++ b/.gitignore @@ -12,3 +12,4 @@ build !/.idea/codeStyles/ !/.idea/dictionaries/ /local.properties +.kotlin/ diff --git a/CHANGELOG.md b/CHANGELOG.md index 5e08bf2..1657c85 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,14 @@ # Changelog +## 0.10.0 - 2026-11-08 + +* Kotlin Multiplatform: `jvm`, `android`, `iosArm64`, `iosSimulatorArm64`, `iosX64` targets +* Update to Kotlin 2.3.20, coroutines 1.10.2. Minimum JVM version is 11 +* Depend on unicorn `ru.kode:unicorn2:2.3.0` (new groupId, was `ru.dimsuz:unicorn2`) +* Add common `rememberViewIntents(factory)`. The reified no-arg `rememberViewIntents()` stays on JVM and Android +* `amvi-component-compose` depends only on Compose runtime (was Compose Desktop) +* Publish via Maven Central Portal + ## 0.9.1 - 2023-02-15 * Fix bug with `ViewModel.attach` calls on a "leaked" view model object diff --git a/amvi-component-compose/build.gradle.kts b/amvi-component-compose/build.gradle.kts index e0d6da5..7a835dc 100644 --- a/amvi-component-compose/build.gradle.kts +++ b/amvi-component-compose/build.gradle.kts @@ -1,16 +1,95 @@ +import com.vanniktech.maven.publish.JavadocJar +import com.vanniktech.maven.publish.KotlinMultiplatform + +@Suppress("DSL_SCOPE_VIOLATION") plugins { - kotlin("jvm") - id(libs.plugins.composeDesktop.get().pluginId) + id(libs.plugins.kotlinMultiplatform.get().pluginId) + id(libs.plugins.androidKmpLibrary.get().pluginId) + alias(libs.plugins.kotlinCompose) + alias(libs.plugins.vanniktech.maven.publish) } +group = providers.gradleProperty("pomGroupId").get() +version = providers.gradleProperty("versionName").get() + kotlin { + jvmToolchain(11) + + jvm() + + androidLibrary { + namespace = "ru.kode.amvi.component.compose" + compileSdk = libs.versions.compileSdk.get().toInt() + minSdk = 21 + } + + iosArm64() + iosSimulatorArm64() + iosX64() + + sourceSets { + commonMain.dependencies { + // Compose Multiplatform; on Android it resolves to the androidx artifact below + api(libs.cmpRuntime) + api(project(":amvi-viewmodel")) + } + androidMain.dependencies { + api(libs.composeRuntime) + } + jvmTest.dependencies { + implementation(libs.bundles.koTestCommon) + implementation(libs.bundles.koTestJvm) + } + } } -tasks.withType().configureEach { - useJUnitPlatform() +mavenPublishing { + coordinates(artifactId = "amvi-component-compose") + configure(KotlinMultiplatform(javadocJar = JavadocJar.Empty())) + + publishToMavenCentral() + signAllPublications() + + pom { + val pomName: String by project + val pomDescription: String by project + val pomUrl: String by project + val pomScmUrl: String by project + val pomScmConnection: String by project + val pomScmDevConnection: String by project + val pomLicenseName: String by project + val pomLicenseUrl: String by project + val pomLicenseDist: String by project + val pomDeveloperId: String by project + val pomDeveloperName: String by project + + name.set(pomName) + description.set(pomDescription) + url.set(pomUrl) + + scm { + url.set(pomScmUrl) + connection.set(pomScmConnection) + developerConnection.set(pomScmDevConnection) + } + + licenses { + license { + name.set(pomLicenseName) + url.set(pomLicenseUrl) + distribution.set(pomLicenseDist) + } + } + + developers { + developer { + id.set(pomDeveloperId) + name.set(pomDeveloperName) + } + } + } } -dependencies { - implementation(compose.desktop.currentOs) - api(project(":amvi-viewmodel")) +tasks.named("jvmTest") { + useJUnitPlatform() } diff --git a/amvi-component-compose/src/androidMain/kotlin/ru/kode/amvi/component/compose/RememberViewIntents.kt b/amvi-component-compose/src/androidMain/kotlin/ru/kode/amvi/component/compose/RememberViewIntents.kt new file mode 100644 index 0000000..89b470c --- /dev/null +++ b/amvi-component-compose/src/androidMain/kotlin/ru/kode/amvi/component/compose/RememberViewIntents.kt @@ -0,0 +1,9 @@ +package ru.kode.amvi.component.compose + +import androidx.compose.runtime.Composable +import androidx.compose.runtime.remember +import ru.kode.amvi.viewmodel.ViewIntents + +@Composable +inline fun rememberViewIntents(): VI = + remember { VI::class.java.getDeclaredConstructor().newInstance() } diff --git a/amvi-component-compose/src/main/kotlin/ru/kode/amvi/component/compose/MviComponent.kt b/amvi-component-compose/src/commonMain/kotlin/ru/kode/amvi/component/compose/MviComponent.kt similarity index 88% rename from amvi-component-compose/src/main/kotlin/ru/kode/amvi/component/compose/MviComponent.kt rename to amvi-component-compose/src/commonMain/kotlin/ru/kode/amvi/component/compose/MviComponent.kt index 16423ca..aab3049 100644 --- a/amvi-component-compose/src/main/kotlin/ru/kode/amvi/component/compose/MviComponent.kt +++ b/amvi-component-compose/src/commonMain/kotlin/ru/kode/amvi/component/compose/MviComponent.kt @@ -23,9 +23,7 @@ fun MviComponent( } @Composable -inline fun rememberViewIntents(): VI { - return remember { VI::class.java.getDeclaredConstructor().newInstance() } -} +fun rememberViewIntents(factory: () -> VI): VI = remember(calculation = factory) @Composable private fun > LifecycleEffect(viewModel: VM, intents: VI) { diff --git a/amvi-component-compose/src/jvmMain/kotlin/ru/kode/amvi/component/compose/RememberViewIntents.kt b/amvi-component-compose/src/jvmMain/kotlin/ru/kode/amvi/component/compose/RememberViewIntents.kt new file mode 100644 index 0000000..89b470c --- /dev/null +++ b/amvi-component-compose/src/jvmMain/kotlin/ru/kode/amvi/component/compose/RememberViewIntents.kt @@ -0,0 +1,9 @@ +package ru.kode.amvi.component.compose + +import androidx.compose.runtime.Composable +import androidx.compose.runtime.remember +import ru.kode.amvi.viewmodel.ViewIntents + +@Composable +inline fun rememberViewIntents(): VI = + remember { VI::class.java.getDeclaredConstructor().newInstance() } diff --git a/amvi-component-compose/src/jvmTest/kotlin/ru/kode/amvi/component/compose/MviComponentTest.kt b/amvi-component-compose/src/jvmTest/kotlin/ru/kode/amvi/component/compose/MviComponentTest.kt new file mode 100644 index 0000000..2650aa8 --- /dev/null +++ b/amvi-component-compose/src/jvmTest/kotlin/ru/kode/amvi/component/compose/MviComponentTest.kt @@ -0,0 +1,211 @@ +package ru.kode.amvi.component.compose + +import androidx.compose.runtime.AbstractApplier +import androidx.compose.runtime.BroadcastFrameClock +import androidx.compose.runtime.Composable +import androidx.compose.runtime.Composition +import androidx.compose.runtime.Recomposer +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.setValue +import androidx.compose.runtime.snapshots.Snapshot +import io.kotest.core.spec.style.ShouldSpec +import io.kotest.matchers.shouldBe +import io.kotest.matchers.types.shouldBeSameInstanceAs +import io.kotest.matchers.types.shouldNotBeSameInstanceAs +import kotlinx.coroutines.cancelAndJoin +import kotlinx.coroutines.coroutineScope +import kotlinx.coroutines.delay +import kotlinx.coroutines.flow.MutableSharedFlow +import kotlinx.coroutines.flow.first +import kotlinx.coroutines.launch +import kotlinx.coroutines.withTimeout +import ru.dimsuz.unicorn2.Machine +import ru.dimsuz.unicorn2.machine +import ru.kode.amvi.viewmodel.ViewIntents +import ru.kode.amvi.viewmodel.ViewModel + +class MviComponentTest : + ShouldSpec({ + should("attach on enter and detach on dispose") { + withComposition { + val viewModel = CountingViewModel() + val intents = TestIntents() + setContent { MviComponent(viewModel, intents) { _, _ -> } } + + viewModel.attached shouldBe 1 + viewModel.detached shouldBe 0 + + composition.dispose() + + viewModel.detached shouldBe 1 + } + } + + should("render initial and updated view state") { + withComposition { + val viewModel = CountingViewModel() + val rendered = mutableListOf() + setContent { MviComponent(viewModel, TestIntents()) { state, _ -> rendered += state } } + + rendered shouldBe listOf(0) + withTimeout(3000) { viewModel.events.subscriptionCount.first { it > 0 } } + viewModel.events.emit(5) + awaitUntil { rendered.last() == 5 } + } + } + + should("pass intents to content and route them to the view model") { + withComposition { + val viewModel = CountingViewModel() + var renderedState = -1 + var contentIntents: TestIntents? = null + val intents = TestIntents() + setContent { + MviComponent(viewModel, intents) { state, i -> + renderedState = state + contentIntents = i + } + } + + contentIntents shouldBeSameInstanceAs intents + // intent bindings subscribe asynchronously after attach: re-send until one is delivered + awaitUntil { + if (renderedState == 0) intents.add(3) + renderedState >= 3 + } + } + } + + should("detach previous view model and attach new one when it changes") { + withComposition { + val first = CountingViewModel() + val second = CountingViewModel() + var current by mutableStateOf(first) + setContent { MviComponent(current, TestIntents()) { _, _ -> } } + + current = second + awaitUntil { second.attached == 1 } + + first.attached shouldBe 1 + (first.detached >= 1) shouldBe true + second.detached shouldBe 0 + + composition.dispose() + second.detached shouldBe 1 + } + } + + should("keep remembered intents across recompositions") { + withComposition { + var trigger by mutableStateOf(0) + val created = mutableListOf() + val seen = mutableListOf() + setContent { + trigger.let { } + seen += rememberViewIntents { TestIntents().also { created += it } } + } + + trigger = 1 + awaitUntil { seen.size == 2 } + + created.size shouldBe 1 + seen[1] shouldBeSameInstanceAs seen[0] + } + } + + should("create intents reflectively with reified rememberViewIntents") { + withComposition { + var trigger by mutableStateOf(0) + val seen = mutableListOf() + setContent { + trigger.let { } + seen += rememberViewIntents() + } + + trigger = 1 + awaitUntil { seen.size == 2 } + + seen[1] shouldBeSameInstanceAs seen[0] + } + } + + should("create new intents for a new composition") { + val first = withComposition { + lateinit var i: TestIntents + setContent { i = rememberViewIntents() } + i + } + val second = withComposition { + lateinit var i: TestIntents + setContent { i = rememberViewIntents() } + i + } + + first shouldNotBeSameInstanceAs second + } + }) + +private class ComposeHarness(val composition: Composition, private val clock: BroadcastFrameClock) { + fun setContent(content: @Composable () -> Unit) = composition.setContent(content) + + suspend fun awaitUntil(condition: () -> Boolean) = withTimeout(3000) { + while (!condition()) { + Snapshot.sendApplyNotifications() + clock.sendFrame(System.nanoTime()) + delay(10) + } + } +} + +private suspend fun withComposition(block: suspend ComposeHarness.() -> T): T = coroutineScope { + val clock = BroadcastFrameClock() + val recomposer = Recomposer(coroutineContext + clock) + val loop = launch(clock) { recomposer.runRecomposeAndApplyChanges() } + val composition = Composition(UnitApplier, recomposer) + try { + ComposeHarness(composition, clock).block() + } finally { + composition.dispose() + recomposer.cancel() + loop.cancelAndJoin() + } +} + +private object UnitApplier : AbstractApplier(Unit) { + override fun insertTopDown(index: Int, instance: Unit) = Unit + override fun insertBottomUp(index: Int, instance: Unit) = Unit + override fun remove(index: Int, count: Int) = Unit + override fun move(from: Int, to: Int, count: Int) = Unit + override fun onClear() = Unit +} + +class TestIntents : ViewIntents() { + val add = intent(name = "add") +} + +private class CountingViewModel : ViewModel(log = {}) { + val events = MutableSharedFlow(extraBufferCapacity = 1) + var attached = 0 + var detached = 0 + + override fun buildMachine(): Machine = machine { + initial = 0 to null + + onEach(events) { + transitionTo { _, payload -> payload } + } + + onEach(intent(TestIntents::add)) { + transitionTo { state, payload -> state + payload } + } + } + + override fun postAttach() { + attached++ + } + + override fun postDetach() { + detached++ + } +} diff --git a/amvi-viewmodel/build.gradle.kts b/amvi-viewmodel/build.gradle.kts index 0f3831e..9793de2 100644 --- a/amvi-viewmodel/build.gradle.kts +++ b/amvi-viewmodel/build.gradle.kts @@ -1,21 +1,114 @@ +@Suppress("DSL_SCOPE_VIOLATION") plugins { - kotlin("jvm") + id(libs.plugins.kotlinMultiplatform.get().pluginId) + id(libs.plugins.androidKmpLibrary.get().pluginId) + // KSP before Kotest: the Kotest plugin needs it to run specs on native + id(libs.plugins.ksp.get().pluginId) + id(libs.plugins.kotest.get().pluginId) + alias(libs.plugins.vanniktech.maven.publish) } +group = providers.gradleProperty("pomGroupId").get() +version = providers.gradleProperty("versionName").get() + kotlin { -} + jvmToolchain(11) -tasks.withType().configureEach { - useJUnitPlatform() + jvm() + + androidLibrary { + namespace = "ru.kode.amvi.viewmodel" + compileSdk = libs.versions.compileSdk.get().toInt() + minSdk = 21 + } + + iosArm64() + iosSimulatorArm64() + iosX64() + + sourceSets { + // Kotest's KSP-generated native test runner uses kotlin.time.Clock + matching { it.name.endsWith("Test") }.configureEach { + languageSettings.optIn("kotlin.time.ExperimentalTime") + } + val commonMain by getting { + dependencies { + implementation(libs.bundles.coroutines) + api(libs.unicorn) + // for @Stable annotations + implementation(libs.composeRuntimeAnnotation) + } + } + val commonTest by getting { + dependencies { + implementation(libs.bundles.koTestCommon) + implementation(libs.turbine) + } + } + val jvmTest by getting { + dependencies { + implementation(libs.bundles.koTestJvm) + } + } + } } -dependencies { - implementation(libs.kotlinCoroutinesCore) - compileOnly(libs.composeRuntimeJvm) // for @Stable annotations - api(libs.unicorn) +mavenPublishing { + coordinates(artifactId = "amvi-viewmodel") + + publishToMavenCentral() + signAllPublications() - testImplementation(libs.koTestRunner) - testImplementation(libs.koTestAssertions) - testImplementation(libs.koTestProperty) - testImplementation(libs.turbine) + pom { + val pomName: String by project + val pomDescription: String by project + val pomUrl: String by project + val pomScmUrl: String by project + val pomScmConnection: String by project + val pomScmDevConnection: String by project + val pomLicenseName: String by project + val pomLicenseUrl: String by project + val pomLicenseDist: String by project + val pomDeveloperId: String by project + val pomDeveloperName: String by project + + name.set(pomName) + description.set(pomDescription) + url.set(pomUrl) + + scm { + url.set(pomScmUrl) + connection.set(pomScmConnection) + developerConnection.set(pomScmDevConnection) + } + + licenses { + license { + name.set(pomLicenseName) + url.set(pomLicenseUrl) + distribution.set(pomLicenseDist) + } + } + + developers { + developer { + id.set(pomDeveloperId) + name.set(pomDeveloperName) + } + } + } +} + +tasks.named("jvmTest") { + useJUnitPlatform() + testLogging { + showExceptions = true + showStandardStreams = true + events = setOf( + org.gradle.api.tasks.testing.logging.TestLogEvent.FAILED, + org.gradle.api.tasks.testing.logging.TestLogEvent.PASSED, + org.gradle.api.tasks.testing.logging.TestLogEvent.STANDARD_OUT, + ) + exceptionFormat = org.gradle.api.tasks.testing.logging.TestExceptionFormat.FULL + } } diff --git a/amvi-viewmodel/src/commonMain/kotlin/ru/kode/amvi/viewmodel/IntentFactory.kt b/amvi-viewmodel/src/commonMain/kotlin/ru/kode/amvi/viewmodel/IntentFactory.kt new file mode 100644 index 0000000..63be608 --- /dev/null +++ b/amvi-viewmodel/src/commonMain/kotlin/ru/kode/amvi/viewmodel/IntentFactory.kt @@ -0,0 +1,61 @@ +package ru.kode.amvi.viewmodel + +import androidx.compose.runtime.Stable +import kotlin.uuid.ExperimentalUuidApi +import kotlin.uuid.Uuid + +data class UiIntent internal constructor(val id: Long, val factoryId: String, val name: String, val payload: Any) + +interface UiIntentFactory { + val name: String + fun isOwnerOf(intent: UiIntent): Boolean + + override fun equals(other: Any?): Boolean + override fun hashCode(): Int +} + +@Stable +class UiIntentFactory0 internal constructor(override val name: String, emit: (UiIntent) -> Unit) : + Function0, + UiIntentFactory { + private val wrapped = UiIntentFactory1(name, emit) + + override fun invoke() { + wrapped.invoke(Unit) + } + + override fun isOwnerOf(intent: UiIntent): Boolean = wrapped.isOwnerOf(intent) + + override fun equals(other: Any?): Boolean = when { + this === other -> true + other is UiIntentFactory0 -> this.wrapped == other.wrapped + else -> this.wrapped == other + } + + override fun hashCode(): Int = wrapped.hashCode() +} + +@Stable +class UiIntentFactory1 internal constructor(override val name: String, private val emit: (UiIntent) -> Unit) : + Function1, + UiIntentFactory { + @OptIn(ExperimentalUuidApi::class) + private val factoryId = Uuid.random().toString() + private var nextId = 0L + + override fun isOwnerOf(intent: UiIntent) = intent.factoryId == factoryId + + override fun invoke(payload: T) { + emit(UiIntent(nextId++, factoryId, name, payload)) + } + + override fun equals(other: Any?): Boolean { + if (this === other) return true + if (other == null || this::class != other::class) return false + other as UiIntentFactory1<*> + if (factoryId != other.factoryId) return false + return true + } + + override fun hashCode(): Int = factoryId.hashCode() +} diff --git a/amvi-viewmodel/src/commonMain/kotlin/ru/kode/amvi/viewmodel/ViewIntents.kt b/amvi-viewmodel/src/commonMain/kotlin/ru/kode/amvi/viewmodel/ViewIntents.kt new file mode 100644 index 0000000..9c82fbd --- /dev/null +++ b/amvi-viewmodel/src/commonMain/kotlin/ru/kode/amvi/viewmodel/ViewIntents.kt @@ -0,0 +1,19 @@ +package ru.kode.amvi.viewmodel + +import kotlinx.coroutines.flow.Flow +import kotlinx.coroutines.flow.MutableSharedFlow +import kotlin.time.Clock +import kotlin.time.ExperimentalTime + +@OptIn(ExperimentalTime::class) +open class ViewIntents { + private val intentRelay = MutableSharedFlow(extraBufferCapacity = 12) + + internal val stream: Flow = intentRelay + + fun intent(name: String = "name-${Clock.System.now().toEpochMilliseconds()}"): UiIntentFactory0 = + UiIntentFactory0(name, intentRelay::tryEmit) + + fun intent(name: String = "name-${Clock.System.now().toEpochMilliseconds()}"): UiIntentFactory1 = + UiIntentFactory1(name, intentRelay::tryEmit) +} diff --git a/amvi-viewmodel/src/main/kotlin/ru/kode/amvi/viewmodel/ViewModel.kt b/amvi-viewmodel/src/commonMain/kotlin/ru/kode/amvi/viewmodel/ViewModel.kt similarity index 92% rename from amvi-viewmodel/src/main/kotlin/ru/kode/amvi/viewmodel/ViewModel.kt rename to amvi-viewmodel/src/commonMain/kotlin/ru/kode/amvi/viewmodel/ViewModel.kt index da7946c..57974b4 100644 --- a/amvi-viewmodel/src/main/kotlin/ru/kode/amvi/viewmodel/ViewModel.kt +++ b/amvi-viewmodel/src/commonMain/kotlin/ru/kode/amvi/viewmodel/ViewModel.kt @@ -16,6 +16,7 @@ import kotlinx.coroutines.flow.filter import kotlinx.coroutines.flow.launchIn import kotlinx.coroutines.flow.onEach import ru.dimsuz.unicorn2.Machine +import kotlin.jvm.JvmName abstract class ViewModel( dispatcher: CoroutineDispatcher = Dispatchers.Default, @@ -113,24 +114,17 @@ abstract class ViewModel( private fun intentInternal(bindOp: (VI) -> UiIntentFactory): Flow { val binder = IntentBinder( bindOp, - MutableSharedFlow() + MutableSharedFlow(), ) intentBinders.add(binder) return binder.relay as Flow } @JvmName("intent1") - fun intent(bindOp: (VI) -> UiIntentFactory1): Flow { - return intentInternal(bindOp) - } + fun intent(bindOp: (VI) -> UiIntentFactory1): Flow = intentInternal(bindOp) @JvmName("intent0") - fun intent(bindOp: (VI) -> UiIntentFactory0): Flow { - return intentInternal(bindOp) - } + fun intent(bindOp: (VI) -> UiIntentFactory0): Flow = intentInternal(bindOp) - private data class IntentBinder( - val intent: (VI) -> UiIntentFactory, - val relay: MutableSharedFlow, - ) + private data class IntentBinder(val intent: (VI) -> UiIntentFactory, val relay: MutableSharedFlow) } diff --git a/amvi-viewmodel/src/commonTest/kotlin/ru/kode/amvi/viewmodel/IntentFactoryTest.kt b/amvi-viewmodel/src/commonTest/kotlin/ru/kode/amvi/viewmodel/IntentFactoryTest.kt new file mode 100644 index 0000000..8b206e1 --- /dev/null +++ b/amvi-viewmodel/src/commonTest/kotlin/ru/kode/amvi/viewmodel/IntentFactoryTest.kt @@ -0,0 +1,81 @@ +package ru.kode.amvi.viewmodel + +import io.kotest.core.spec.style.ShouldSpec +import io.kotest.matchers.collections.shouldHaveSize +import io.kotest.matchers.shouldBe +import io.kotest.matchers.shouldNotBe + +class IntentFactoryTest : + ShouldSpec({ + should("emit intents with name, payload, increasing ids and a shared factory id") { + val emitted = mutableListOf() + val sut = UiIntentFactory1("click", emitted::add) + + sut(10) + sut(20) + sut(30) + + emitted shouldHaveSize 3 + emitted.map { it.id } shouldBe listOf(0L, 1L, 2L) + emitted.map { it.payload } shouldBe listOf(10, 20, 30) + emitted.map { it.name }.toSet() shouldBe setOf("click") + emitted.map { it.factoryId }.toSet() shouldHaveSize 1 + } + + should("emit Unit payload from no-arg factory") { + val emitted = mutableListOf() + val sut = UiIntentFactory0("refresh", emitted::add) + + sut() + sut() + + emitted.map { it.payload } shouldBe listOf(Unit, Unit) + emitted.map { it.id } shouldBe listOf(0L, 1L) + emitted.map { it.name }.toSet() shouldBe setOf("refresh") + } + + should("own only intents it has emitted, even if another factory has the same name") { + val emitted = mutableListOf() + val first = UiIntentFactory1("same", emitted::add) + val second = UiIntentFactory1("same", emitted::add) + val noArg = UiIntentFactory0("same", emitted::add) + + first(1) + second(2) + noArg() + + first.isOwnerOf(emitted[0]) shouldBe true + first.isOwnerOf(emitted[1]) shouldBe false + first.isOwnerOf(emitted[2]) shouldBe false + second.isOwnerOf(emitted[1]) shouldBe true + second.isOwnerOf(emitted[0]) shouldBe false + noArg.isOwnerOf(emitted[2]) shouldBe true + noArg.isOwnerOf(emitted[0]) shouldBe false + } + + should("generate unique factory ids") { + val ids = List(100) { + val emitted = mutableListOf() + UiIntentFactory1("x", emitted::add)(0) + emitted.single().factoryId + } + + ids.toSet() shouldHaveSize 100 + } + + should("be equal only to itself") { + val first = UiIntentFactory1("same") {} + val second = UiIntentFactory1("same") {} + val firstNoArg = UiIntentFactory0("same") {} + val secondNoArg = UiIntentFactory0("same") {} + + first shouldBe first + first shouldNotBe second + first.hashCode() shouldBe first.hashCode() + firstNoArg shouldBe firstNoArg + firstNoArg shouldNotBe secondNoArg + firstNoArg.hashCode() shouldBe firstNoArg.hashCode() + firstNoArg shouldNotBe first + first shouldNotBe null + } + }) diff --git a/amvi-viewmodel/src/commonTest/kotlin/ru/kode/amvi/viewmodel/ViewIntentsTest.kt b/amvi-viewmodel/src/commonTest/kotlin/ru/kode/amvi/viewmodel/ViewIntentsTest.kt new file mode 100644 index 0000000..6a60b59 --- /dev/null +++ b/amvi-viewmodel/src/commonTest/kotlin/ru/kode/amvi/viewmodel/ViewIntentsTest.kt @@ -0,0 +1,52 @@ +package ru.kode.amvi.viewmodel + +import app.cash.turbine.test +import io.kotest.core.spec.style.ShouldSpec +import io.kotest.matchers.shouldBe +import io.kotest.matchers.string.shouldStartWith + +class ViewIntentsTest : + ShouldSpec({ + should("use explicit intent names") { + val sut = NamedIntents() + + sut.noArg.name shouldBe "noArg" + sut.withArg.name shouldBe "withArg" + } + + should("generate default intent names") { + val sut = DefaultNamedIntents() + + sut.noArg.name shouldStartWith "name-" + sut.withArg.name shouldStartWith "name-" + } + + should("publish invoked intents to the stream in order") { + val sut = NamedIntents() + + sut.stream.test { + sut.withArg("a") + sut.noArg() + + val first = awaitItem() + first.name shouldBe "withArg" + first.payload shouldBe "a" + sut.withArg.isOwnerOf(first) shouldBe true + + val second = awaitItem() + second.name shouldBe "noArg" + second.payload shouldBe Unit + sut.noArg.isOwnerOf(second) shouldBe true + } + } + }) + +private class NamedIntents : ViewIntents() { + val noArg = intent(name = "noArg") + val withArg = intent(name = "withArg") +} + +private class DefaultNamedIntents : ViewIntents() { + val noArg = intent() + val withArg = intent() +} diff --git a/amvi-viewmodel/src/commonTest/kotlin/ru/kode/amvi/viewmodel/ViewModelLifecycleTest.kt b/amvi-viewmodel/src/commonTest/kotlin/ru/kode/amvi/viewmodel/ViewModelLifecycleTest.kt new file mode 100644 index 0000000..0a7cb60 --- /dev/null +++ b/amvi-viewmodel/src/commonTest/kotlin/ru/kode/amvi/viewmodel/ViewModelLifecycleTest.kt @@ -0,0 +1,167 @@ +package ru.kode.amvi.viewmodel + +import app.cash.turbine.test +import io.kotest.core.spec.style.ShouldSpec +import io.kotest.matchers.shouldBe +import kotlinx.coroutines.channels.Channel +import kotlinx.coroutines.delay +import kotlinx.coroutines.flow.MutableSharedFlow +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.first +import kotlinx.coroutines.flow.update +import kotlinx.coroutines.withTimeout +import ru.dimsuz.unicorn2.Machine +import ru.dimsuz.unicorn2.machine + +class ViewModelLifecycleTest : + ShouldSpec({ + should("call lifecycle hooks in order") { + val sut = RecordingViewModel() + + sut.attach(LifecycleIntents()) + sut.detach() + sut.destroy() + + sut.calls shouldBe listOf( + "preAttach", + "postAttach", + "preDetach", + "postDetach", + "preDestroy", + "postDestroy", + ) + } + + should("log dispatched intents with the view model name") { + val log = Channel(Channel.UNLIMITED) + val sut = RecordingViewModel(log = { log.trySend(it()) }) + val intents = LifecycleIntents() + sut.attach(intents) + intents.awaitAllBindings() + + intents.add(5) + + withTimeout(3000) { log.receive() } shouldBe "[RecordingViewModel, intent.name=add]" + } + + should("run initial action once across reattach") { + val sut = RecordingViewModel() + + sut.attach(LifecycleIntents()) + sut.detach() + sut.attach(LifecycleIntents()) + + withTimeout(3000) { sut.initialActions.first { it > 0 } } + delay(100) + sut.initialActions.value shouldBe 1 + } + + should("route intents only from the currently attached intents") { + val sut = RecordingViewModel() + val oldIntents = LifecycleIntents() + val newIntents = LifecycleIntents() + + sut.attach(oldIntents) + sut.detach() + sut.attach(newIntents) + newIntents.awaitAllBindings() + + sut.viewStateFlow.test { + awaitItem() shouldBe listOf(0) + oldIntents.add(1) + newIntents.add(2) + awaitItem() shouldBe listOf(0, 2) + newIntents.add(3) + awaitItem() shouldBe listOf(0, 2, 3) + delay(100) + expectNoEvents() + } + } + + should("route each intent only to its own binding") { + val sut = RecordingViewModel() + val intents = LifecycleIntents() + + sut.attach(intents) + intents.awaitAllBindings() + + sut.viewStateFlow.test { + awaitItem() shouldBe listOf(0) + intents.add(7) + awaitItem() shouldBe listOf(0, 7) + intents.clear() + awaitItem() shouldBe emptyList() + delay(100) + expectNoEvents() + } + } + + should("stop reacting to non-intent sources after destroy") { + val sut = RecordingViewModel() + + sut.attach(LifecycleIntents()) + withTimeout(3000) { sut.events.subscriptionCount.first { it > 0 } } + sut.destroy() + + withTimeout(3000) { sut.events.subscriptionCount.first { it == 0 } } + sut.events.tryEmit(42) + delay(100) + sut.viewStateFlow.value shouldBe listOf(0) + } + }) + +// 2 intent bindings + 1 logger subscribe to the intents stream on attach +private suspend fun ViewIntents.awaitAllBindings() { + withTimeout(3000) { (stream as MutableSharedFlow).subscriptionCount.first { it >= 3 } } +} + +private class LifecycleIntents : ViewIntents() { + val add = intent(name = "add") + val clear = intent(name = "clear") +} + +private class RecordingViewModel(log: (() -> String) -> Unit = {}) : ViewModel, LifecycleIntents>(log = log) { + val calls = mutableListOf() + val events = MutableSharedFlow(extraBufferCapacity = 1) + val initialActions = MutableStateFlow(0) + + override fun buildMachine(): Machine> = machine { + initial = listOf(0) to { initialActions.update { it + 1 } } + + onEach(events) { + transitionTo { state, payload -> state + payload } + } + + onEach(intent(LifecycleIntents::add)) { + transitionTo { state, payload -> state + payload } + } + + onEach(intent(LifecycleIntents::clear)) { + transitionTo { _, _ -> emptyList() } + } + } + + override fun preAttach() { + calls += "preAttach" + } + + override fun postAttach() { + calls += "postAttach" + } + + override fun preDetach() { + calls += "preDetach" + } + + override fun postDetach() { + calls += "postDetach" + } + + override fun preDestroy() { + calls += "preDestroy" + } + + override fun postDestroy() { + calls += "postDestroy" + } +} diff --git a/amvi-viewmodel/src/commonTest/kotlin/ru/kode/amvi/viewmodel/ViewModelTest.kt b/amvi-viewmodel/src/commonTest/kotlin/ru/kode/amvi/viewmodel/ViewModelTest.kt new file mode 100644 index 0000000..2436e7a --- /dev/null +++ b/amvi-viewmodel/src/commonTest/kotlin/ru/kode/amvi/viewmodel/ViewModelTest.kt @@ -0,0 +1,147 @@ +package ru.kode.amvi.viewmodel + +import app.cash.turbine.test +import io.kotest.core.spec.style.ShouldSpec +import io.kotest.matchers.shouldBe +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.delay +import kotlinx.coroutines.flow.MutableSharedFlow +import kotlinx.coroutines.flow.first +import kotlinx.coroutines.flow.flowOf +import kotlinx.coroutines.flow.onEach +import ru.dimsuz.unicorn2.machine + +class ViewModelTest : + ShouldSpec({ + should("emit state on start only once") { + val sut = object : ViewModel() { + override fun buildMachine() = machine { + initial = 3 to null + } + } + + sut.viewStateFlow.test { + awaitItem() shouldBe 3 + delay(100) + expectNoEvents() + } + } + + should("execute transitions in response to non-intent sources after attach") { + val sut = object : ViewModel, TestIntents>(dispatcher = Dispatchers.Default) { + override fun buildMachine() = machine> { + initial = listOf(3) to null + + onEach(flowOf(11, 22, 33).onEach { delay(20) }) { + transitionTo { state, payload -> + state + payload + } + } + } + } + + sut.attach(TestIntents()) + + sut.viewStateFlow.test { + awaitItem() shouldBe listOf(3) + awaitItem() shouldBe listOf(3, 11) + awaitItem() shouldBe listOf(3, 11, 22) + awaitItem() shouldBe listOf(3, 11, 22, 33) + delay(100) + expectNoEvents() + } + } + + should("execute transitions in response to intent sources after attach") { + val sut = object : ViewModel, TestIntents>(dispatcher = Dispatchers.Default) { + override fun buildMachine() = machine> { + initial = listOf(3) to null + + onEach(intent(TestIntents::intentNoArg)) { + transitionTo { state, _ -> + state + 11 + } + } + + onEach(intent(TestIntents::intentWithArg)) { + transitionTo { state, payload -> + state + payload + } + } + } + } + + val intents = TestIntents() + sut.attach(intents) + + sut.viewStateFlow.test { + awaitItem() shouldBe listOf(3) + intents.intentWithArg(88) + awaitItem() shouldBe listOf(3, 88) + intents.intentWithArg(77) + awaitItem() shouldBe listOf(3, 88, 77) + intents.intentNoArg() + awaitItem() shouldBe listOf(3, 88, 77, 11) + delay(100) + expectNoEvents() + } + } + + should("not execute transitions in response to intent sources after detach") { + val sut = object : ViewModel, TestIntents>(dispatcher = Dispatchers.Default) { + override fun buildMachine() = machine> { + initial = listOf(3) to null + + onEach(intent(TestIntents::intentNoArg)) { + transitionTo { state, _ -> + state + 11 + } + } + } + } + + val intents = TestIntents() + sut.attach(intents) + + sut.viewStateFlow.test { + awaitItem() shouldBe listOf(3) + sut.detach() + intents.intentNoArg() + delay(100) + expectNoEvents() + } + } + + should("continue to execute transitions in response to non-intent sources after detach") { + val events = MutableSharedFlow(extraBufferCapacity = 3) + val sut = object : ViewModel, TestIntents>(dispatcher = Dispatchers.Default) { + override fun buildMachine() = machine> { + initial = listOf(3) to null + + onEach(events) { + transitionTo { state, payload -> + state + payload + } + } + } + } + + sut.attach(TestIntents()) + + sut.viewStateFlow.test { + awaitItem() shouldBe listOf(3) + sut.detach() + // events has no replay: wait until the machine subscribes, otherwise the value is dropped + events.subscriptionCount.first { it > 0 } + events.emit(12) + awaitItem() shouldBe listOf(3, 12) + delay(100) + expectNoEvents() + } + } + }) + +private class TestIntents : ViewIntents() { + val intentNoArg = intent(name = "intentNoArg") + val intentWithArg = intent(name = "intentWithArg") +} diff --git a/amvi-viewmodel/src/main/kotlin/ru/kode/amvi/viewmodel/IntentFactory.kt b/amvi-viewmodel/src/main/kotlin/ru/kode/amvi/viewmodel/IntentFactory.kt deleted file mode 100644 index ad14cb2..0000000 --- a/amvi-viewmodel/src/main/kotlin/ru/kode/amvi/viewmodel/IntentFactory.kt +++ /dev/null @@ -1,74 +0,0 @@ -package ru.kode.amvi.viewmodel - -import androidx.compose.runtime.Stable -import java.util.UUID - -data class UiIntent internal constructor( - val id: Long, - val factoryId: String, - val name: String, - val payload: Any, -) - -interface UiIntentFactory { - val name: String - fun isOwnerOf(intent: UiIntent): Boolean - - override fun equals(other: Any?): Boolean - override fun hashCode(): Int -} - -@Stable -class UiIntentFactory0 internal constructor( - override val name: String, - emit: (UiIntent) -> Unit, -) : Function0, UiIntentFactory { - private val wrapped = UiIntentFactory1(name, emit) - - override fun invoke() { - wrapped.invoke(Unit) - } - - override fun isOwnerOf(intent: UiIntent): Boolean { - return wrapped.isOwnerOf(intent) - } - - override fun equals(other: Any?): Boolean { - return when { - this === other -> true - other is UiIntentFactory0 -> this.wrapped == other.wrapped - else -> this.wrapped == other - } - } - - override fun hashCode(): Int { - return wrapped.hashCode() - } -} - -@Stable -class UiIntentFactory1 internal constructor( - override val name: String, - private val emit: (UiIntent) -> Unit, -) : Function1, UiIntentFactory { - private val factoryId = UUID.randomUUID().toString() - private var nextId = 0L - - override fun isOwnerOf(intent: UiIntent) = intent.factoryId == factoryId - - override fun invoke(payload: T) { - emit(UiIntent(nextId++, factoryId, name, payload)) - } - - override fun equals(other: Any?): Boolean { - if (this === other) return true - if (other == null || this::class != other::class) return false - other as UiIntentFactory1<*> - if (factoryId != other.factoryId) return false - return true - } - - override fun hashCode(): Int { - return factoryId.hashCode() - } -} diff --git a/amvi-viewmodel/src/main/kotlin/ru/kode/amvi/viewmodel/ViewIntents.kt b/amvi-viewmodel/src/main/kotlin/ru/kode/amvi/viewmodel/ViewIntents.kt deleted file mode 100644 index ba241e2..0000000 --- a/amvi-viewmodel/src/main/kotlin/ru/kode/amvi/viewmodel/ViewIntents.kt +++ /dev/null @@ -1,18 +0,0 @@ -package ru.kode.amvi.viewmodel - -import kotlinx.coroutines.flow.Flow -import kotlinx.coroutines.flow.MutableSharedFlow - -open class ViewIntents { - private val intentRelay = MutableSharedFlow(extraBufferCapacity = 12) - - internal val stream: Flow = intentRelay - - fun intent(name: String = "name-${System.currentTimeMillis()}"): UiIntentFactory0 { - return UiIntentFactory0(name, intentRelay::tryEmit) - } - - fun intent(name: String = "name-${System.currentTimeMillis()}"): UiIntentFactory1 { - return UiIntentFactory1(name, intentRelay::tryEmit) - } -} diff --git a/amvi-viewmodel/src/test/kotlin/ru/kode/amvi/viewmodel/ViewModelTest.kt b/amvi-viewmodel/src/test/kotlin/ru/kode/amvi/viewmodel/ViewModelTest.kt deleted file mode 100644 index 1317bac..0000000 --- a/amvi-viewmodel/src/test/kotlin/ru/kode/amvi/viewmodel/ViewModelTest.kt +++ /dev/null @@ -1,143 +0,0 @@ -package ru.kode.amvi.viewmodel - -import app.cash.turbine.test -import io.kotest.core.spec.style.ShouldSpec -import io.kotest.matchers.shouldBe -import kotlinx.coroutines.Dispatchers -import kotlinx.coroutines.delay -import kotlinx.coroutines.flow.MutableSharedFlow -import kotlinx.coroutines.flow.flowOf -import kotlinx.coroutines.flow.onEach -import ru.dimsuz.unicorn2.machine - -class ViewModelTest : ShouldSpec({ - should("emit state on start only once") { - val sut = object : ViewModel() { - override fun buildMachine() = machine { - initial = 3 to null - } - } - - sut.viewStateFlow.test { - awaitItem() shouldBe 3 - delay(100) - expectNoEvents() - } - } - - should("execute transitions in response to non-intent sources after attach") { - val sut = object : ViewModel, TestIntents>(dispatcher = Dispatchers.Default) { - override fun buildMachine() = machine> { - initial = listOf(3) to null - - onEach(flowOf(11, 22, 33).onEach { delay(20) }) { - transitionTo { state, payload -> - state + payload - } - } - } - } - - sut.attach(TestIntents()) - - sut.viewStateFlow.test { - awaitItem() shouldBe listOf(3) - awaitItem() shouldBe listOf(3, 11) - awaitItem() shouldBe listOf(3, 11, 22) - awaitItem() shouldBe listOf(3, 11, 22, 33) - delay(100) - expectNoEvents() - } - } - - should("execute transitions in response to intent sources after attach") { - val sut = object : ViewModel, TestIntents>(dispatcher = Dispatchers.Default) { - override fun buildMachine() = machine> { - initial = listOf(3) to null - - onEach(intent(TestIntents::intentNoArg)) { - transitionTo { state, _ -> - state + 11 - } - } - - onEach(intent(TestIntents::intentWithArg)) { - transitionTo { state, payload -> - state + payload - } - } - } - } - - val intents = TestIntents() - sut.attach(intents) - - sut.viewStateFlow.test { - awaitItem() shouldBe listOf(3) - intents.intentWithArg(88) - awaitItem() shouldBe listOf(3, 88) - intents.intentWithArg(77) - awaitItem() shouldBe listOf(3, 88, 77) - intents.intentNoArg() - awaitItem() shouldBe listOf(3, 88, 77, 11) - delay(100) - expectNoEvents() - } - } - - should("not execute transitions in response to intent sources after detach") { - val sut = object : ViewModel, TestIntents>(dispatcher = Dispatchers.Default) { - override fun buildMachine() = machine> { - initial = listOf(3) to null - - onEach(intent(TestIntents::intentNoArg)) { - transitionTo { state, _ -> - state + 11 - } - } - } - } - - val intents = TestIntents() - sut.attach(intents) - - sut.viewStateFlow.test { - awaitItem() shouldBe listOf(3) - sut.detach() - intents.intentNoArg() - delay(100) - expectNoEvents() - } - } - - should("continue to execute transitions in response to non-intent sources after detach") { - val events = MutableSharedFlow(extraBufferCapacity = 3) - val sut = object : ViewModel, TestIntents>(dispatcher = Dispatchers.Default) { - override fun buildMachine() = machine> { - initial = listOf(3) to null - - onEach(events) { - transitionTo { state, payload -> - state + payload - } - } - } - } - - sut.attach(TestIntents()) - - sut.viewStateFlow.test { - awaitItem() shouldBe listOf(3) - sut.detach() - events.emit(12) - awaitItem() shouldBe listOf(3, 12) - delay(100) - expectNoEvents() - } - } -}) - -private class TestIntents : ViewIntents() { - val intentNoArg = intent(name = "intentNoArg") - val intentWithArg = intent(name = "intentWithArg") -} diff --git a/build.gradle.kts b/build.gradle.kts index f529771..6617dea 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -1,135 +1,32 @@ -import org.jetbrains.dokka.gradle.DokkaTask -import org.jetbrains.kotlin.gradle.plugin.KotlinPluginWrapper - +@Suppress("DSL_SCOPE_VIOLATION") plugins { - kotlin("jvm") version "1.7.20" apply false - alias(libs.plugins.dokka) apply false alias(libs.plugins.spotless) - alias(libs.plugins.composeDesktop) apply false -} - -allprojects { - buildscript { - repositories { - google() - mavenCentral() - } - } - repositories { - google() - mavenCentral() - mavenLocal() - } -} - -subprojects { - plugins.withType { - apply(plugin = libs.plugins.dokka.get().pluginId) - apply(plugin = "maven-publish") - - val dokkaHtml by tasks.existing(DokkaTask::class) - - val dokkaJar by tasks.creating(org.gradle.jvm.tasks.Jar::class) { - group = JavaBasePlugin.DOCUMENTATION_GROUP - archiveClassifier.set("javadoc") - from(dokkaHtml) - } - - val sourcesJar by tasks.creating(org.gradle.jvm.tasks.Jar::class) { - archiveClassifier.set("sources") - from(project.the()["main"].allSource) - } - - configure { - publications.withType { - artifact(dokkaJar) - artifact(sourcesJar) - } - } - } - - plugins.withType { - apply(plugin = "org.gradle.signing") - - configure { - repositories { - mavenLocal() - maven { - name = "MavenCentral" - val releasesRepoUrl = uri("https://s01.oss.sonatype.org/service/local/staging/deploy/maven2/") - val snapshotsRepoUrl = uri("https://s01.oss.sonatype.org/content/repositories/snapshots/") - val versionName: String by project - url = if (versionName.endsWith("SNAPSHOT")) snapshotsRepoUrl else releasesRepoUrl - credentials { - username = project.findProperty("NEXUS_USERNAME")?.toString() - password = project.findProperty("NEXUS_PASSWORD")?.toString() - } - } - } - - publications.create("maven") { - val versionName: String by project - val pomGroupId: String by project - groupId = pomGroupId - version = versionName - - from(components["java"]) - - pom { - val pomDescription: String by project - val pomUrl: String by project - val pomName: String by project - description.set(pomDescription) - url.set(pomUrl) - name.set(pomName) - scm { - val pomScmUrl: String by project - val pomScmConnection: String by project - val pomScmDevConnection: String by project - url.set(pomScmUrl) - connection.set(pomScmConnection) - developerConnection.set(pomScmDevConnection) - } - licenses { - license { - val pomLicenseName: String by project - val pomLicenseUrl: String by project - val pomLicenseDist: String by project - name.set(pomLicenseName) - url.set(pomLicenseUrl) - distribution.set(pomLicenseDist) - } - } - developers { - developer { - val pomDeveloperId: String by project - val pomDeveloperName: String by project - id.set(pomDeveloperId) - name.set(pomDeveloperName) - } - } - } - } - - configure { - sign(publications) - } - } - } + alias(libs.plugins.kotlinMultiplatform) apply false + alias(libs.plugins.kotlinCompose) apply false + alias(libs.plugins.androidKmpLibrary) apply false + alias(libs.plugins.ksp) apply false + alias(libs.plugins.kotest) apply false + alias(libs.plugins.vanniktech.maven.publish) apply false } spotless { kotlin { target("**/*.kt") - targetExclude("!**/build/**/*.*") - ktlint(libs.versions.ktlint.get()).userData(mapOf("indent_size" to "2", "max_line_length" to "120")) + targetExclude("**/build/**/*.*") + ktlint(libs.versions.ktlint.get()).editorConfigOverride( + mapOf( + "indent_size" to "2", + "max_line_length" to "120", + "ktlint_function_naming_ignore_when_annotated_with" to "Composable", + ), + ) trimTrailingWhitespace() endWithNewline() } kotlinGradle { target("**/*.gradle.kts") - ktlint(libs.versions.ktlint.get()).userData(mapOf("indent_size" to "2", "max_line_length" to "120")) + ktlint(libs.versions.ktlint.get()).editorConfigOverride(mapOf("indent_size" to "2", "max_line_length" to "120")) trimTrailingWhitespace() endWithNewline() } diff --git a/gradle.properties b/gradle.properties index cce8106..8ac47e0 100644 --- a/gradle.properties +++ b/gradle.properties @@ -1,14 +1,20 @@ +org.gradle.jvmargs=-XX:MaxMetaspaceSize=1g + kotlin.code.style=official -versionName=0.9.1 +versionName=0.10.0 pomGroupId=ru.kode pomDescription=KODE Android MVI view models and components pomUrl=https://github.com/appKODE/amvi pomScmUrl=https://github.com/appKODE/amvi -pomScmConnection=scm:git@github.com:appKODE/amvi.git -pomScmDevConnection=scm:git@github.com:appKODE/amvi.git +pomScmConnection=scm:git:https://github.com/appKODE/amvi.git +pomScmDevConnection=scm:git:ssh://github.com/appKODE/amvi.git pomLicenseName=MIT License pomLicenseUrl=https://github.com/appKODE/amvi/blob/master/LICENSE pomLicenseDist=repo pomDeveloperId=dimsuz pomDeveloperName=Dmitry Suzdalev +kotlin.native.ignoreDisabledTargets=true + +android.useAndroidX=true +org.gradle.configuration-cache=true diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml index 831863b..ab48b40 100644 --- a/gradle/libs.versions.toml +++ b/gradle/libs.versions.toml @@ -1,25 +1,43 @@ [versions] -ktlint = "0.43.2" -spotless = "6.11.0" -dokka = "1.5.31" -coroutines = "1.6.4" -unicorn = "2.2.0" -composeDesktop = "1.2.2" -koTest = "5.5.1" -turbine = "0.11.0" +koTest = "6.1.9" +ktlint = "1.8.0" +coroutines = "1.10.2" +# Should be equal to the Gradle embedded Kotlin version to prevent multiple Kotlin Compiler Daemon instances +kotlin = "2.3.20" +spotless = "8.4.0" +turbine = "1.2.1" +compose = "1.10.6" +# Compose Multiplatform for non-Android targets; on Android `compose` above wins +composeMultiplatform = "1.10.3" +agp = "9.0.1" +ksp = "2.3.6" +vanniktechMavenPublish = "0.37.0" +unicorn = "2.3.0" +compileSdk = "36" [libraries] +kotest-junit-runner = { module = "io.kotest:kotest-runner-junit5", version.ref = "koTest" } +kotest-framework-engine = { module = "io.kotest:kotest-framework-engine", version.ref = "koTest" } +kotest-assertions-core = { module = "io.kotest:kotest-assertions-core", version.ref = "koTest" } +kotest-property = { module = "io.kotest:kotest-property", version.ref = "koTest" } ktlint = { module = "com.pinterest:ktlint", version.ref = "ktlint" } -kotlinCoroutinesCore = { module = "org.jetbrains.kotlinx:kotlinx-coroutines-core", version.ref = "coroutines" } -kotlinCoroutinesAndroid = { module = "org.jetbrains.kotlinx:kotlinx-coroutines-android", version.ref = "coroutines" } -unicorn = { module = "ru.dimsuz:unicorn2", version.ref = "unicorn" } -composeRuntimeJvm = { module = "org.jetbrains.compose.runtime:runtime", version.ref = "composeDesktop" } -koTestRunner = { module = "io.kotest:kotest-runner-junit5", version.ref = "koTest"} -koTestAssertions = { module = "io.kotest:kotest-assertions-core", version.ref = "koTest" } -koTestProperty = { module = "io.kotest:kotest-property", version.ref = "koTest" } +coroutines-core = { module = "org.jetbrains.kotlinx:kotlinx-coroutines-core", version.ref = "coroutines" } turbine = { module = "app.cash.turbine:turbine", version.ref = "turbine" } +unicorn = { module = "ru.kode:unicorn2", version.ref = "unicorn" } +composeRuntime = { module = "androidx.compose.runtime:runtime", version.ref = "compose" } +composeRuntimeAnnotation = { module = "androidx.compose.runtime:runtime-annotation", version.ref = "compose" } +cmpRuntime = { module = "org.jetbrains.compose.runtime:runtime", version.ref = "composeMultiplatform" } + +[bundles] +koTestCommon = ["kotest-assertions-core", "kotest-property", "kotest-framework-engine"] +koTestJvm = ["kotest-junit-runner"] +coroutines = ["coroutines-core"] [plugins] +kotlinMultiplatform = { id = "org.jetbrains.kotlin.multiplatform", version.ref = "kotlin" } +kotlinCompose = { id = "org.jetbrains.kotlin.plugin.compose", version.ref = "kotlin" } spotless = { id = "com.diffplug.spotless", version.ref = "spotless" } -dokka = { id = "org.jetbrains.dokka", version.ref = "dokka" } -composeDesktop = { id = "org.jetbrains.compose", version.ref = "composeDesktop" } +androidKmpLibrary = { id = "com.android.kotlin.multiplatform.library", version.ref = "agp" } +ksp = { id = "com.google.devtools.ksp", version.ref = "ksp" } +kotest = { id = "io.kotest", version.ref = "koTest" } +vanniktech-maven-publish = { id = "com.vanniktech.maven.publish", version.ref = "vanniktechMavenPublish" } diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar index 7454180..41d9927 100644 Binary files a/gradle/wrapper/gradle-wrapper.jar and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties index 60c76b3..221c4f9 100644 --- a/gradle/wrapper/gradle-wrapper.properties +++ b/gradle/wrapper/gradle-wrapper.properties @@ -1,5 +1,5 @@ distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-7.4.2-bin.zip +distributionUrl=https\://services.gradle.org/distributions/gradle-9.4.1-bin.zip zipStoreBase=GRADLE_USER_HOME -zipStorePath=wrapper/dists \ No newline at end of file +zipStorePath=wrapper/dists diff --git a/settings.gradle.kts b/settings.gradle.kts index 0ae8a9b..24d227e 100644 --- a/settings.gradle.kts +++ b/settings.gradle.kts @@ -1,14 +1,20 @@ - -rootProject.name = "amvi" - -include("amvi-viewmodel") -include("amvi-component-compose") - pluginManagement { repositories { gradlePluginPortal() google() mavenCentral() - maven("https://maven.pkg.jetbrains.space/public/p/compose/dev") } } + +dependencyResolutionManagement { + repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS) + repositories { + google() + mavenCentral() + } +} + +rootProject.name = "amvi" + +include(":amvi-viewmodel") +include(":amvi-component-compose")