diff --git a/.github/workflows/test.yaml b/.github/workflows/test.yaml new file mode 100644 index 0000000..06aba5c --- /dev/null +++ b/.github/workflows/test.yaml @@ -0,0 +1,40 @@ +name: Test the library + +on: + pull_request: + branches: + - main + +jobs: + test: + name: Run tests + runs-on: macos-latest + steps: + - name: Checkout repository + uses: actions/checkout@v4 + + - name: Read cache + uses: actions/cache@v4 + with: + path: | + ~/.gradle/caches + ~/.gradle/wrapper + key: ${{ runner.os }}-gradle-${{ hashFiles('**/*.gradle*', '**/gradle-wrapper.properties') }} + restore-keys: | + ${{ runner.os }}-gradle- + + - name: Setup Java + uses: actions/setup-java@v4 + with: + distribution: 'corretto' + java-version: '21' + + - name: Run tests + run: | + ./gradlew stately:check + + - name: Archive test report + uses: actions/upload-artifact@v4 + with: + name: Test report + path: build/reports/tests/test diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..3c321df --- /dev/null +++ b/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2025 VOIR + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/README.md b/README.md new file mode 100644 index 0000000..12e1372 --- /dev/null +++ b/README.md @@ -0,0 +1,185 @@ +# Stately – Lightweight State Management for Async Operations in Kotlin Multiplatform + +`Stately` is a **lightweight Kotlin Multiplatform library** that simplifies handling async data +flows like fetching and actions across platforms (Android, JVM, iOS). + +Inspired by React hooks like `useSWR`, `useMutation`, `useQuery`, `Stately` aims to provide: + +- **Consistent state management** for async flows (loading, error, data) +- Built-in revalidation (polling) for fetch +- Action management with loading/error callbacks +- Clean UI integration in Jetpack Compose + +--- + +## Not Yet Published + +This library is **not currently published** to any public Maven repository. + +To use it in your own project: + +--- + +#### Step 1: Publish to Maven Local + +Run the following command from the root of the project: + +```bash +./gradlew publishToMavenLocal +``` + +This will install the library to your local Maven cache (`~/.m2`). + +--- + +#### Step 2: Add `mavenLocal()` to your build + +In your `build.gradle.kts` or `build.gradle`: + +```kotlin +repositories { + mavenLocal() + // other repositories like mavenCentral(), google(), etc. +} +``` + +--- + +#### Step 3: Declare the dependency + +In your module's dependencies block: + +```kotlin +dependencies { + implementation("dev.voir:stately:") +} +``` + +> Replace `` with the version from your `build.gradle.kts`. + +--- + +#### Note + +Make sure to rerun `publishToMavenLocal` every time you change the library. + +## Modules + +### `stately` + +Includes: + +- `StatelyFetch`: declarative data fetching with polling and payload support +- `StatelyAction`: single-shot mutation-like execution +- `StatelyFetchResult` and `StatelyActionResult`: unified state containers + +### `sample` + +A sample Jetpack Compose app with: + +- Navigation +- Examples for `StatelyFetch`, `StatelyAction` +- Demo with `StatelyFetchContent`, `StatelyFetchBoundary` +- Dynamic config panel to toggle revalidation, lazy load, errors + +--- + +## Core Concepts + +### StatelyFetch + +```kotlin +val fetch = StatelyFetch( + fetcher = { payload -> api.loadData(payload) }, + revalidateInterval = 5000L, + lazy = false, + initialData = null +) +``` + +- `.state`: exposes loading, error, and data +- `.revalidate(payload?)`: triggers a new fetch +- Revalidates periodically if `revalidateInterval` is set + +### StatelyAction + +```kotlin +val action = StatelyAction( + action = { payload -> api.sendSomething(payload) }, + onSuccess = { result -> println("✅ Success") }, + onError = { error -> println("❌ Failed") } +) + +action.execute(payload) +``` + +--- + +## Testing + +Tests are written using **pure `kotlin.test`**, `kotlinx.coroutines.test` + +### Run all tests + +```bash +./gradlew stately:check +``` + +--- + +## Helper UI Components + +### `StatelyFetchContent` + +Composable for rendering based on `StatelyFetchResult`: + +```kotlin +StatelyFetchContent( + state = state, + loading = { Text("Loading") }, + error = { e -> Text("Error: ${e.message}") }, + content = { data -> Text("Data: $data") } +) +``` + +### `StatelyFetchBoundary` + +A wrapper that handles everything: + +```kotlin +StatelyFetchBoundary( + fetcher = { api.getSomething() }, + content = { data -> Text(data) } +) +``` + +--- + +## Kotlin Multiplatform Targets + +- ✅ Android +- ✅ iOS +- ✅ JVM + +--- + +## Roadmap + +- [ ] Auto cancellation +- [ ] Debouncing + +--- + +## Contributing + +This library is still under active development. PRs and feedback are welcome. + +- File issues +- Suggest features +- Write sample apps for other targets + +--- + +## License + +MIT License – see `LICENSE` for full details. diff --git a/build.gradle.kts b/build.gradle.kts new file mode 100644 index 0000000..3bacfbb --- /dev/null +++ b/build.gradle.kts @@ -0,0 +1,9 @@ +plugins { + // this is necessary to avoid the plugins to be loaded multiple times + // in each subproject's classloader + alias(libs.plugins.androidApplication) apply false + alias(libs.plugins.androidLibrary) apply false + alias(libs.plugins.jetbrainsCompose) apply false + alias(libs.plugins.compose.compiler) apply false + alias(libs.plugins.kotlinMultiplatform) apply false +} diff --git a/gradle.properties b/gradle.properties new file mode 100644 index 0000000..6b6e846 --- /dev/null +++ b/gradle.properties @@ -0,0 +1,8 @@ +kotlin.code.style=official +#Gradle +org.gradle.jvmargs=-Xmx2048M -Dfile.encoding=UTF-8 -Dkotlin.daemon.jvm.options\="-Xmx2048M" +#Android +android.nonTransitiveRClass=true +android.useAndroidX=true +#Kotlin Multiplatform +kotlin.mpp.enableCInteropCommonization=true diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml new file mode 100644 index 0000000..a869df8 --- /dev/null +++ b/gradle/libs.versions.toml @@ -0,0 +1,25 @@ +[versions] +agp = "8.11.0" +android-compileSdk = "36" +android-minSdk = "24" +android-targetSdk = "36" +compose-plugin = "1.8.2" # https://github.com/JetBrains/compose-multiplatform +kotlin = "2.2.0" # https://kotlinlang.org/docs/releases.html +kotlin-coroutines = "1.10.2" # https://github.com/Kotlin/kotlinx.coroutines +androidx-activityCompose = "1.10.1" # https://mvnrepository.com/artifact/androidx.activity/activity-compose +androidx-navigationCompose = "2.9.0-beta03" # https://mvnrepository.com/artifact/org.jetbrains.androidx.navigation/navigation-compose +appcash-turbine = "1.2.1" # https://github.com/cashapp/turbine + +[libraries] +androidx-activity-compose = { module = "androidx.activity:activity-compose", version.ref = "androidx-activityCompose" } +androidx-navigation-compose = { module = "org.jetbrains.androidx.navigation:navigation-compose", version.ref = "androidx-navigationCompose" } +kotlin-coroutines = { module = "org.jetbrains.kotlinx:kotlinx-coroutines-core", version.ref = "kotlin-coroutines" } +kotlinx-coroutines-test = { module = "org.jetbrains.kotlinx:kotlinx-coroutines-test", version.ref = "kotlin-coroutines" } +appcash-turbine = { module = "app.cash.turbine:turbine", version.ref = "appcash-turbine" } + +[plugins] +androidApplication = { id = "com.android.application", version.ref = "agp" } +androidLibrary = { id = "com.android.library", version.ref = "agp" } +jetbrainsCompose = { id = "org.jetbrains.compose", version.ref = "compose-plugin" } +compose-compiler = { id = "org.jetbrains.kotlin.plugin.compose", version.ref = "kotlin" } +kotlinMultiplatform = { id = "org.jetbrains.kotlin.multiplatform", version.ref = "kotlin" } diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..7f93135 Binary files /dev/null and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..37f853b --- /dev/null +++ b/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,7 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-8.13-bin.zip +networkTimeout=10000 +validateDistributionUrl=true +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew new file mode 100755 index 0000000..1aa94a4 --- /dev/null +++ b/gradlew @@ -0,0 +1,249 @@ +#!/bin/sh + +# +# Copyright © 2015-2021 the original authors. +# +# 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 +# +# https://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. +# + +############################################################################## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/HEAD/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +# This is normally unused +# shellcheck disable=SC2034 +APP_BASE_NAME=${0##*/} +# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) +APP_HOME=$( cd "${APP_HOME:-./}" > /dev/null && pwd -P ) || exit + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { + echo "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD=$JAVA_HOME/jre/sh/java + else + JAVACMD=$JAVA_HOME/bin/java + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD=java + if ! command -v java >/dev/null 2>&1 + then + die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Collect all arguments for the java command: +# * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, +# and any embedded shellness will be escaped. +# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be +# treated as '${Hostname}' itself on the command line. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -classpath "$CLASSPATH" \ + org.gradle.wrapper.GradleWrapperMain \ + "$@" + +# Stop when "xargs" is not available. +if ! command -v xargs >/dev/null 2>&1 +then + die "xargs is not available" +fi + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/gradlew.bat b/gradlew.bat new file mode 100644 index 0000000..6689b85 --- /dev/null +++ b/gradlew.bat @@ -0,0 +1,92 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem + +@if "%DEBUG%"=="" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%"=="" set DIRNAME=. +@rem This is normally unused +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if %ERRORLEVEL% equ 0 goto execute + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* + +:end +@rem End local scope for the variables with windows NT shell +if %ERRORLEVEL% equ 0 goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +set EXIT_CODE=%ERRORLEVEL% +if %EXIT_CODE% equ 0 set EXIT_CODE=1 +if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% +exit /b %EXIT_CODE% + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/sample/build.gradle.kts b/sample/build.gradle.kts new file mode 100644 index 0000000..13bf9b3 --- /dev/null +++ b/sample/build.gradle.kts @@ -0,0 +1,79 @@ +import org.jetbrains.kotlin.gradle.ExperimentalKotlinGradlePluginApi +import org.jetbrains.kotlin.gradle.dsl.JvmTarget + +plugins { + alias(libs.plugins.kotlinMultiplatform) + alias(libs.plugins.androidApplication) + alias(libs.plugins.jetbrainsCompose) + alias(libs.plugins.compose.compiler) +} + +kotlin { + androidTarget { + @OptIn(ExperimentalKotlinGradlePluginApi::class) + compilerOptions { + jvmTarget.set(JvmTarget.JVM_21) + } + } + + listOf( + iosX64(), + iosArm64(), + iosSimulatorArm64() + ).forEach { iosTarget -> + iosTarget.binaries.framework { + baseName = "StatelySampleApp" + isStatic = true + } + } + + sourceSets { + androidMain.dependencies { + implementation(compose.preview) + implementation(libs.androidx.activity.compose) + } + commonMain.dependencies { + // Compose + implementation(compose.runtime) + implementation(compose.foundation) + implementation(compose.material3) + implementation(compose.ui) + implementation(libs.androidx.navigation.compose) + + implementation(projects.stately) + } + } +} + +android { + namespace = "dev.voir.stately.sample" + compileSdk = libs.versions.android.compileSdk.get().toInt() + + defaultConfig { + applicationId = "dev.voir.stately.sample" + minSdk = libs.versions.android.minSdk.get().toInt() + targetSdk = libs.versions.android.targetSdk.get().toInt() + versionCode = 1 + versionName = "1.0" + } + packaging { + resources { + excludes += "/META-INF/{AL2.0,LGPL2.1}" + } + } + buildTypes { + getByName("release") { + isMinifyEnabled = false + } + } + compileOptions { + sourceCompatibility = JavaVersion.VERSION_21 + targetCompatibility = JavaVersion.VERSION_21 + } + buildFeatures { + compose = true + } + dependencies { + debugImplementation(compose.uiTooling) + } +} diff --git a/sample/src/androidMain/AndroidManifest.xml b/sample/src/androidMain/AndroidManifest.xml new file mode 100644 index 0000000..f196fee --- /dev/null +++ b/sample/src/androidMain/AndroidManifest.xml @@ -0,0 +1,25 @@ + + + + + + + + + + + + + + + diff --git a/sample/src/androidMain/kotlin/dev/voir/stately/sample/MainActivitiy.kt b/sample/src/androidMain/kotlin/dev/voir/stately/sample/MainActivitiy.kt new file mode 100644 index 0000000..97236f5 --- /dev/null +++ b/sample/src/androidMain/kotlin/dev/voir/stately/sample/MainActivitiy.kt @@ -0,0 +1,15 @@ +package dev.voir.stately.sample + +import android.os.Bundle +import androidx.activity.ComponentActivity +import androidx.activity.compose.setContent + +class MainActivity : ComponentActivity() { + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + + setContent { + App() + } + } +} diff --git a/sample/src/androidMain/res/drawable-v24/ic_launcher_foreground.xml b/sample/src/androidMain/res/drawable-v24/ic_launcher_foreground.xml new file mode 100644 index 0000000..2b068d1 --- /dev/null +++ b/sample/src/androidMain/res/drawable-v24/ic_launcher_foreground.xml @@ -0,0 +1,30 @@ + + + + + + + + + + + \ No newline at end of file diff --git a/sample/src/androidMain/res/drawable/ic_launcher_background.xml b/sample/src/androidMain/res/drawable/ic_launcher_background.xml new file mode 100644 index 0000000..e93e11a --- /dev/null +++ b/sample/src/androidMain/res/drawable/ic_launcher_background.xml @@ -0,0 +1,170 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/sample/src/androidMain/res/mipmap-anydpi-v26/ic_launcher.xml b/sample/src/androidMain/res/mipmap-anydpi-v26/ic_launcher.xml new file mode 100644 index 0000000..eca70cf --- /dev/null +++ b/sample/src/androidMain/res/mipmap-anydpi-v26/ic_launcher.xml @@ -0,0 +1,5 @@ + + + + + \ No newline at end of file diff --git a/sample/src/androidMain/res/mipmap-anydpi-v26/ic_launcher_round.xml b/sample/src/androidMain/res/mipmap-anydpi-v26/ic_launcher_round.xml new file mode 100644 index 0000000..eca70cf --- /dev/null +++ b/sample/src/androidMain/res/mipmap-anydpi-v26/ic_launcher_round.xml @@ -0,0 +1,5 @@ + + + + + \ No newline at end of file diff --git a/sample/src/androidMain/res/mipmap-hdpi/ic_launcher.png b/sample/src/androidMain/res/mipmap-hdpi/ic_launcher.png new file mode 100644 index 0000000..a571e60 Binary files /dev/null and b/sample/src/androidMain/res/mipmap-hdpi/ic_launcher.png differ diff --git a/sample/src/androidMain/res/mipmap-hdpi/ic_launcher_round.png b/sample/src/androidMain/res/mipmap-hdpi/ic_launcher_round.png new file mode 100644 index 0000000..61da551 Binary files /dev/null and b/sample/src/androidMain/res/mipmap-hdpi/ic_launcher_round.png differ diff --git a/sample/src/androidMain/res/mipmap-mdpi/ic_launcher.png b/sample/src/androidMain/res/mipmap-mdpi/ic_launcher.png new file mode 100644 index 0000000..c41dd28 Binary files /dev/null and b/sample/src/androidMain/res/mipmap-mdpi/ic_launcher.png differ diff --git a/sample/src/androidMain/res/mipmap-mdpi/ic_launcher_round.png b/sample/src/androidMain/res/mipmap-mdpi/ic_launcher_round.png new file mode 100644 index 0000000..db5080a Binary files /dev/null and b/sample/src/androidMain/res/mipmap-mdpi/ic_launcher_round.png differ diff --git a/sample/src/androidMain/res/mipmap-xhdpi/ic_launcher.png b/sample/src/androidMain/res/mipmap-xhdpi/ic_launcher.png new file mode 100644 index 0000000..6dba46d Binary files /dev/null and b/sample/src/androidMain/res/mipmap-xhdpi/ic_launcher.png differ diff --git a/sample/src/androidMain/res/mipmap-xhdpi/ic_launcher_round.png b/sample/src/androidMain/res/mipmap-xhdpi/ic_launcher_round.png new file mode 100644 index 0000000..da31a87 Binary files /dev/null and b/sample/src/androidMain/res/mipmap-xhdpi/ic_launcher_round.png differ diff --git a/sample/src/androidMain/res/mipmap-xxhdpi/ic_launcher.png b/sample/src/androidMain/res/mipmap-xxhdpi/ic_launcher.png new file mode 100644 index 0000000..15ac681 Binary files /dev/null and b/sample/src/androidMain/res/mipmap-xxhdpi/ic_launcher.png differ diff --git a/sample/src/androidMain/res/mipmap-xxhdpi/ic_launcher_round.png b/sample/src/androidMain/res/mipmap-xxhdpi/ic_launcher_round.png new file mode 100644 index 0000000..b216f2d Binary files /dev/null and b/sample/src/androidMain/res/mipmap-xxhdpi/ic_launcher_round.png differ diff --git a/sample/src/androidMain/res/mipmap-xxxhdpi/ic_launcher.png b/sample/src/androidMain/res/mipmap-xxxhdpi/ic_launcher.png new file mode 100644 index 0000000..f25a419 Binary files /dev/null and b/sample/src/androidMain/res/mipmap-xxxhdpi/ic_launcher.png differ diff --git a/sample/src/androidMain/res/mipmap-xxxhdpi/ic_launcher_round.png b/sample/src/androidMain/res/mipmap-xxxhdpi/ic_launcher_round.png new file mode 100644 index 0000000..e96783c Binary files /dev/null and b/sample/src/androidMain/res/mipmap-xxxhdpi/ic_launcher_round.png differ diff --git a/sample/src/androidMain/res/values/strings.xml b/sample/src/androidMain/res/values/strings.xml new file mode 100644 index 0000000..c7aec5e --- /dev/null +++ b/sample/src/androidMain/res/values/strings.xml @@ -0,0 +1,3 @@ + + Stately Sample + \ No newline at end of file diff --git a/sample/src/commonMain/kotlin/dev/voir/stately/sample/App.kt b/sample/src/commonMain/kotlin/dev/voir/stately/sample/App.kt new file mode 100644 index 0000000..5841dae --- /dev/null +++ b/sample/src/commonMain/kotlin/dev/voir/stately/sample/App.kt @@ -0,0 +1,91 @@ +package dev.voir.stately.sample + +import StatelyActionExampleScreen +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.padding +import androidx.compose.material3.Button +import androidx.compose.material3.ExperimentalMaterial3Api +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Scaffold +import androidx.compose.material3.Text +import androidx.compose.material3.TopAppBar +import androidx.compose.runtime.Composable +import androidx.compose.ui.Modifier +import androidx.compose.ui.unit.dp +import androidx.navigation.NavController +import androidx.navigation.compose.NavHost +import androidx.navigation.compose.composable +import androidx.navigation.compose.rememberNavController +import dev.voir.stately.sample.examples.StatelyFetchBoundaryExampleScreen +import dev.voir.stately.sample.examples.StatelyFetchContentExampleScreen +import dev.voir.stately.sample.examples.StatelyFetchExampleScreen + +sealed class AppScreen(val route: String) { + object Menu : AppScreen("menu") + object FetchExample : AppScreen("fetch") + object ActionExample : AppScreen("action") + object FetchContentExample : AppScreen("fetch_content") + object FetchBoundaryExample : AppScreen("fetch_boundary") +} + +@Composable +fun App() { + val navController = rememberNavController() + + MaterialTheme { + NavHost(navController = navController, startDestination = AppScreen.Menu.route) { + composable(AppScreen.Menu.route) { + MenuScreen(navController) + } + composable(AppScreen.FetchExample.route) { + StatelyFetchExampleScreen() + } + composable(AppScreen.ActionExample.route) { + StatelyActionExampleScreen() + } + composable(AppScreen.FetchContentExample.route) { + StatelyFetchContentExampleScreen() + } + composable(AppScreen.FetchBoundaryExample.route) { + StatelyFetchBoundaryExampleScreen() + } + } + } +} + + +@OptIn(ExperimentalMaterial3Api::class) +@Composable +private fun MenuScreen(navController: NavController) { + Scaffold( + topBar = { + TopAppBar(title = { Text("Stately Examples") }) + } + ) { padding -> + Column( + modifier = Modifier + .padding(padding) + .padding(24.dp), + verticalArrangement = Arrangement.spacedBy(16.dp) + ) { + Text("Choose an example", style = MaterialTheme.typography.titleLarge) + + Button(onClick = { navController.navigate(AppScreen.FetchExample.route) }) { + Text("Stately Fetch") + } + + Button(onClick = { navController.navigate(AppScreen.ActionExample.route) }) { + Text("Stately Action") + } + + Button(onClick = { navController.navigate(AppScreen.FetchContentExample.route) }) { + Text("Fetch with StatelyFetchContent") + } + + Button(onClick = { navController.navigate(AppScreen.FetchBoundaryExample.route) }) { + Text("Fetch with StatelyFetchBoundary") + } + } + } +} diff --git a/sample/src/commonMain/kotlin/dev/voir/stately/sample/examples/StatelyActionExample.kt b/sample/src/commonMain/kotlin/dev/voir/stately/sample/examples/StatelyActionExample.kt new file mode 100644 index 0000000..0875633 --- /dev/null +++ b/sample/src/commonMain/kotlin/dev/voir/stately/sample/examples/StatelyActionExample.kt @@ -0,0 +1,121 @@ +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.verticalScroll +import androidx.compose.material3.Button +import androidx.compose.material3.Checkbox +import androidx.compose.material3.ExperimentalMaterial3Api +import androidx.compose.material3.HorizontalDivider +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.OutlinedTextField +import androidx.compose.material3.Scaffold +import androidx.compose.material3.Text +import androidx.compose.material3.TopAppBar +import androidx.compose.runtime.Composable +import androidx.compose.runtime.collectAsState +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableIntStateOf +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.rememberCoroutineScope +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.unit.dp +import dev.voir.stately.rememberStatelyAction +import kotlinx.coroutines.delay +import kotlinx.coroutines.launch + +@OptIn(ExperimentalMaterial3Api::class) +@Composable +fun StatelyActionExampleScreen() { + var simulateError by remember { mutableStateOf(false) } + var simulateDelay by remember { mutableStateOf(true) } + var payloadInput by remember { mutableStateOf("") } + var actionVersion by remember { mutableIntStateOf(0) } + + var actionTriggered by remember { mutableStateOf(false) } + + val scope = rememberCoroutineScope() + + val action = rememberStatelyAction( + action = { payload -> + if (simulateDelay) delay(2000) + if (simulateError) throw Exception("Simulated Error") + "Processed: $payload" + }, + scope = scope, + onSuccess = { println("✅ onSuccess: $it") }, + onError = { println("❌ onError: ${it.message}") } + ) + + val state by action.state.collectAsState() + + Scaffold( + topBar = { + TopAppBar(title = { Text("StatelyAction Example") }) + }, + content = { padding -> + Column( + modifier = Modifier + .padding(padding) + .padding(16.dp) + .verticalScroll(rememberScrollState()), + verticalArrangement = Arrangement.spacedBy(12.dp) + ) { + Text("Configuration", style = MaterialTheme.typography.titleMedium) + + Row(verticalAlignment = Alignment.CenterVertically) { + Checkbox(checked = simulateDelay, onCheckedChange = { simulateDelay = it }) + Text("Simulate delay") + } + + Row(verticalAlignment = Alignment.CenterVertically) { + Checkbox(checked = simulateError, onCheckedChange = { simulateError = it }) + Text("Simulate error") + } + + OutlinedTextField( + value = payloadInput, + onValueChange = { payloadInput = it }, + label = { Text("Payload") }, + modifier = Modifier.fillMaxWidth() + ) + + Row(horizontalArrangement = Arrangement.spacedBy(12.dp)) { + Button(onClick = { + if (payloadInput.isNotBlank()) { + scope.launch { + action.execute(payloadInput) + actionTriggered = true + } + } + }) { + Text("Trigger Action") + } + + Button(onClick = { + actionTriggered = false + payloadInput = "" + simulateError = false + simulateDelay = true + actionVersion++ // Recreate action + }) { + Text("Reset") + } + } + + if (actionTriggered) { + HorizontalDivider() + Text("Action State", style = MaterialTheme.typography.titleMedium) + Text("Loading: ${state.loading}") + Text("Response: ${state.response ?: "null"}") + Text("Error: ${state.error?.message ?: "none"}") + } + } + } + ) +} diff --git a/sample/src/commonMain/kotlin/dev/voir/stately/sample/examples/StatelyFetchBoundaryExample.kt b/sample/src/commonMain/kotlin/dev/voir/stately/sample/examples/StatelyFetchBoundaryExample.kt new file mode 100644 index 0000000..f63c56b --- /dev/null +++ b/sample/src/commonMain/kotlin/dev/voir/stately/sample/examples/StatelyFetchBoundaryExample.kt @@ -0,0 +1,39 @@ +package dev.voir.stately.sample.examples + +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.padding +import androidx.compose.material3.ExperimentalMaterial3Api +import androidx.compose.material3.Scaffold +import androidx.compose.material3.Text +import androidx.compose.material3.TopAppBar +import androidx.compose.runtime.Composable +import androidx.compose.ui.Modifier +import androidx.compose.ui.unit.dp +import dev.voir.stately.ui.StatelyFetchBoundary +import kotlinx.coroutines.delay + +@OptIn(ExperimentalMaterial3Api::class) +@Composable +fun StatelyFetchBoundaryExampleScreen() { + Scaffold( + topBar = { + TopAppBar(title = { Text("StatelyFetchBoundary Example") }) + } + ) { padding -> + Column( + modifier = Modifier + .padding(padding) + .padding(16.dp) + ) { + StatelyFetchBoundary( + fetcher = { + delay(1500) + "Data from StatelyFetchBoundary" + }, + loading = { Text("⏳ Loading...") }, + error = { error -> Text("❌ Error: ${error.message}") }, + content = { data -> Text("✅ Success: $data") } + ) + } + } +} diff --git a/sample/src/commonMain/kotlin/dev/voir/stately/sample/examples/StatelyFetchContentExample.kt b/sample/src/commonMain/kotlin/dev/voir/stately/sample/examples/StatelyFetchContentExample.kt new file mode 100644 index 0000000..c746544 --- /dev/null +++ b/sample/src/commonMain/kotlin/dev/voir/stately/sample/examples/StatelyFetchContentExample.kt @@ -0,0 +1,51 @@ +package dev.voir.stately.sample.examples + +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.padding +import androidx.compose.material3.ExperimentalMaterial3Api +import androidx.compose.material3.Scaffold +import androidx.compose.material3.Text +import androidx.compose.material3.TopAppBar +import androidx.compose.runtime.Composable +import androidx.compose.runtime.collectAsState +import androidx.compose.runtime.getValue +import androidx.compose.runtime.rememberCoroutineScope +import androidx.compose.ui.Modifier +import androidx.compose.ui.unit.dp +import dev.voir.stately.rememberStatelyFetch +import dev.voir.stately.ui.StatelyFetchContent +import kotlinx.coroutines.delay + +@OptIn(ExperimentalMaterial3Api::class) +@Composable +fun StatelyFetchContentExampleScreen() { + val scope = rememberCoroutineScope() + val statelyFetch = rememberStatelyFetch( + fetcher = { + delay(2000) + "This is data from StatelyFetchContent" + }, + scope = scope + ) + + val state by statelyFetch.state.collectAsState() + + Scaffold( + topBar = { + TopAppBar(title = { Text("StatelyFetchContent Example") }) + } + ) { padding -> + Column( + modifier = Modifier + .padding(padding) + .padding(16.dp) + ) { + StatelyFetchContent( + state = state, + loading = { Text("Loading...") }, + error = { error -> Text("Error: ${error.message}") }, + content = { data -> Text("✅ Data: $data") } + ) + } + } +} diff --git a/sample/src/commonMain/kotlin/dev/voir/stately/sample/examples/StatelyFetchExample.kt b/sample/src/commonMain/kotlin/dev/voir/stately/sample/examples/StatelyFetchExample.kt new file mode 100644 index 0000000..3320b7b --- /dev/null +++ b/sample/src/commonMain/kotlin/dev/voir/stately/sample/examples/StatelyFetchExample.kt @@ -0,0 +1,160 @@ +package dev.voir.stately.sample.examples + +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.text.KeyboardOptions +import androidx.compose.foundation.verticalScroll +import androidx.compose.material3.Button +import androidx.compose.material3.Checkbox +import androidx.compose.material3.ExperimentalMaterial3Api +import androidx.compose.material3.HorizontalDivider +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.OutlinedTextField +import androidx.compose.material3.Scaffold +import androidx.compose.material3.Text +import androidx.compose.material3.TopAppBar +import androidx.compose.runtime.Composable +import androidx.compose.runtime.collectAsState +import androidx.compose.runtime.getValue +import androidx.compose.runtime.key +import androidx.compose.runtime.mutableIntStateOf +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.rememberCoroutineScope +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.text.input.KeyboardType +import androidx.compose.ui.unit.dp +import dev.voir.stately.rememberStatelyFetch +import kotlinx.coroutines.delay + +@OptIn(ExperimentalMaterial3Api::class) +@Composable +fun StatelyFetchExampleScreen() { + var revalidateIntervalInput by remember { mutableStateOf(null) } + var simulateError by remember { mutableStateOf(false) } + var lazy by remember { mutableStateOf(false) } + var initiallyLoading by remember { mutableStateOf(false) } + var initialData by remember { mutableStateOf(null) } + + var currentConfig by remember { mutableStateOf(null) } + var simulationVersion by remember { mutableIntStateOf(0) } + + Scaffold( + topBar = { + TopAppBar(title = { Text("StatelyFetch Example") }) + }, + content = { padding -> + Column( + modifier = Modifier + .padding(padding) + .padding(16.dp) + .verticalScroll(rememberScrollState()), + verticalArrangement = Arrangement.spacedBy(12.dp) + ) { + Text("Configuration", style = MaterialTheme.typography.titleMedium) + + Row(verticalAlignment = Alignment.CenterVertically) { + Checkbox(checked = lazy, onCheckedChange = { lazy = it }) + Text("Lazy") + } + + Row(verticalAlignment = Alignment.CenterVertically) { + Checkbox( + checked = initiallyLoading, + onCheckedChange = { initiallyLoading = it }) + Text("Initially loading") + } + + Row(verticalAlignment = Alignment.CenterVertically) { + Checkbox(checked = simulateError, onCheckedChange = { simulateError = it }) + Text("Simulate error") + } + + OutlinedTextField( + value = revalidateIntervalInput?.toString() ?: "", + onValueChange = { revalidateIntervalInput = it.toLongOrNull() }, + label = { Text("Revalidate Interval (ms)") }, + keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number), + modifier = Modifier.fillMaxWidth() + ) + + OutlinedTextField( + value = initialData ?: "", + onValueChange = { + initialData = it.ifBlank { null } + }, + label = { Text("Initial data") }, + keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Text), + modifier = Modifier.fillMaxWidth() + ) + + Button(onClick = { + currentConfig = FetchConfig( + simulateError = simulateError, + lazy = lazy, + initiallyLoading = initiallyLoading, + revalidateInterval = revalidateIntervalInput, + initialData = initialData + ) + simulationVersion++ + }) { + Text("Start / Reset Simulation") + } + + HorizontalDivider() + + currentConfig?.let { config -> + key(simulationVersion) { + FetchSimulation(config = config) + } + } + } + } + ) +} + +@Composable +private fun FetchSimulation(config: FetchConfig) { + var counter by remember(config) { mutableIntStateOf(0) } + + val scope = rememberCoroutineScope() + + val statelyFetch = rememberStatelyFetch( + fetcher = { + delay(3000) // simulate network delay + if (config.simulateError) throw Exception("Simulated Error") + "Fetched Data: ${counter++}" + }, + scope = scope, + revalidateInterval = config.revalidateInterval, + initiallyLoading = config.initiallyLoading, + initialData = config.initialData, + lazy = config.lazy + ) + + val state by statelyFetch.state.collectAsState() + + Text("Fetch State", style = MaterialTheme.typography.titleMedium) + Text("Loading: ${state.loading}") + Text("Data: ${state.data ?: "null"}") + Text("Error: ${state.error?.message ?: "none"}") + Button(onClick = { + statelyFetch.revalidate() + }) { + Text("Fetch/revalidate") + } +} + +private data class FetchConfig( + val simulateError: Boolean, + val lazy: Boolean, + val initiallyLoading: Boolean, + val revalidateInterval: Long?, + val initialData: String? +) diff --git a/sample/src/iosMain/kotlin/dev/voir/stately/sample/MainViewController.kt b/sample/src/iosMain/kotlin/dev/voir/stately/sample/MainViewController.kt new file mode 100644 index 0000000..b79128b --- /dev/null +++ b/sample/src/iosMain/kotlin/dev/voir/stately/sample/MainViewController.kt @@ -0,0 +1,5 @@ +package dev.voir.stately.sample + +import androidx.compose.ui.window.ComposeUIViewController + +fun MainViewController() = ComposeUIViewController { App() } diff --git a/settings.gradle.kts b/settings.gradle.kts new file mode 100644 index 0000000..68092d7 --- /dev/null +++ b/settings.gradle.kts @@ -0,0 +1,32 @@ +rootProject.name = "StatelyLibrary" +enableFeaturePreview("TYPESAFE_PROJECT_ACCESSORS") + +pluginManagement { + repositories { + google { + mavenContent { + includeGroupAndSubgroups("androidx") + includeGroupAndSubgroups("com.android") + includeGroupAndSubgroups("com.google") + } + } + mavenCentral() + gradlePluginPortal() + } +} + +dependencyResolutionManagement { + repositories { + google { + mavenContent { + includeGroupAndSubgroups("androidx") + includeGroupAndSubgroups("com.android") + includeGroupAndSubgroups("com.google") + } + } + mavenCentral() + } +} + +include(":stately") +include(":sample") diff --git a/stately/build.gradle.kts b/stately/build.gradle.kts new file mode 100644 index 0000000..c4e098f --- /dev/null +++ b/stately/build.gradle.kts @@ -0,0 +1,70 @@ +plugins { + alias(libs.plugins.kotlinMultiplatform) + alias(libs.plugins.androidLibrary) + alias(libs.plugins.jetbrainsCompose) + alias(libs.plugins.compose.compiler) + id("maven-publish") + id("signing") +} + +group = "dev.voir" +version = "1.0.0-alpha01" + +kotlin { + androidTarget { + publishLibraryVariants("release") + } + + listOf( + iosX64(), + iosArm64(), + iosSimulatorArm64(), + ).forEach { iosTarget -> + iosTarget.binaries.framework { + baseName = "Stately" + isStatic = true + } + } + + sourceSets.all { + languageSettings.optIn("kotlin.experimental.ExperimentalObjCName") + } + + sourceSets { + androidMain.dependencies { + } + + commonMain.dependencies { + implementation(libs.kotlin.coroutines) + + api(compose.runtime) + } + + iosMain.dependencies { + } + + commonTest.dependencies { + implementation(kotlin("test")) + implementation(libs.kotlinx.coroutines.test) + implementation(libs.appcash.turbine) + } + } +} + +android { + namespace = "dev.voir.stately" + compileSdk = libs.versions.android.compileSdk.get().toInt() + + defaultConfig { + minSdk = libs.versions.android.minSdk.get().toInt() + } + + compileOptions { + sourceCompatibility = JavaVersion.VERSION_21 + targetCompatibility = JavaVersion.VERSION_21 + } + + kotlin { + jvmToolchain(21) + } +} diff --git a/stately/src/commonMain/kotlin/dev/voir/stately/StatelyAction.kt b/stately/src/commonMain/kotlin/dev/voir/stately/StatelyAction.kt new file mode 100644 index 0000000..d413954 --- /dev/null +++ b/stately/src/commonMain/kotlin/dev/voir/stately/StatelyAction.kt @@ -0,0 +1,53 @@ +package dev.voir.stately + +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.IO +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.launch + +data class StatelyActionResult( + val response: Response? = null, + val loading: Boolean = false, + val error: Throwable? = null, +) + +class StatelyAction( + private val action: suspend (payload: Payload) -> Response, + private val scope: CoroutineScope = CoroutineScope(Dispatchers.IO), + private val onError: ((error: Throwable) -> Unit)? = null, + private val onSuccess: ((response: Response) -> Unit)? = null +) { + private var sending: Boolean = false + private val _state = MutableStateFlow(StatelyActionResult()) + val state: StateFlow> + get() = _state + + fun execute(payload: Payload) { + if (!sending) { + doExecute(payload = payload) + } + } + + private fun doExecute(payload: Payload) { + sending = true + + scope.launch { + _state.value = state.value.copy(loading = true, error = null) + try { + val response = action(payload) + _state.value = StatelyActionResult(response = response, loading = false) + + onSuccess?.let { it(response) } + } catch (e: Exception) { + e.printStackTrace() + _state.value = StatelyActionResult(error = e, loading = false) + + onError?.let { it(e) } + } finally { + sending = false + } + } + } +} diff --git a/stately/src/commonMain/kotlin/dev/voir/stately/StatelyFetch.kt b/stately/src/commonMain/kotlin/dev/voir/stately/StatelyFetch.kt new file mode 100644 index 0000000..a1fb047 --- /dev/null +++ b/stately/src/commonMain/kotlin/dev/voir/stately/StatelyFetch.kt @@ -0,0 +1,76 @@ +package dev.voir.stately + +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.IO +import kotlinx.coroutines.delay +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.launch + +data class StatelyFetchResult( + val payload: Payload?, + val data: Data?, + val loading: Boolean, + val error: Throwable? = null, +) + +class StatelyFetch( + private val fetcher: suspend (payload: Payload?) -> Data, + private val scope: CoroutineScope = CoroutineScope(Dispatchers.IO), + private val revalidateInterval: Long? = null, + lazy: Boolean = false, + initialData: Data? = null, + initialPayload: Payload? = null, + initiallyLoading: Boolean = true, +) { + private var revalidating: Boolean = false + private val _state = MutableStateFlow( + StatelyFetchResult( + payload = initialPayload, + loading = initiallyLoading, + data = initialData + ) + ) + val state: StateFlow> + get() = _state + + init { + if (!lazy) { + revalidate() + } + + if (revalidateInterval != null) { + scope.launch { + while (true) { + delay(revalidateInterval) + revalidate() + } + } + } + } + + fun revalidate(payload: Payload? = null) { + if (!revalidating) { + doRevalidate(payload) + } + } + + private fun doRevalidate(payload: Payload? = null) { + revalidating = true + + scope.launch { + _state.value = state.value.copy(loading = true, error = null, payload = payload) + try { + val data = fetcher(payload) + _state.value = StatelyFetchResult(payload = payload, data = data, loading = false) + } catch (e: Exception) { + e.printStackTrace() + // Keep previous data and payload on error + _state.value = _state.value.copy(error = e, loading = false) + } finally { + revalidating = false + } + } + } +} diff --git a/stately/src/commonMain/kotlin/dev/voir/stately/rememberStatelyAction.kt b/stately/src/commonMain/kotlin/dev/voir/stately/rememberStatelyAction.kt new file mode 100644 index 0000000..40eac19 --- /dev/null +++ b/stately/src/commonMain/kotlin/dev/voir/stately/rememberStatelyAction.kt @@ -0,0 +1,28 @@ +package dev.voir.stately + +import androidx.compose.runtime.Composable +import androidx.compose.runtime.State +import androidx.compose.runtime.collectAsState +import androidx.compose.runtime.remember +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.IO + +@Composable +fun rememberStatelyAction( + action: suspend (payload: Payload) -> Response, + scope: CoroutineScope = CoroutineScope(Dispatchers.IO), + onError: ((error: Throwable) -> Unit)? = null, + onSuccess: ((response: Response) -> Unit)? = null +) = remember { + StatelyAction( + action = action, + scope = scope, + onError = onError, + onSuccess = onSuccess + ) +} + +@Composable +fun StatelyAction.collectAsState(): State> = + this.state.collectAsState() diff --git a/stately/src/commonMain/kotlin/dev/voir/stately/rememberStatelyFetch.kt b/stately/src/commonMain/kotlin/dev/voir/stately/rememberStatelyFetch.kt new file mode 100644 index 0000000..061875f --- /dev/null +++ b/stately/src/commonMain/kotlin/dev/voir/stately/rememberStatelyFetch.kt @@ -0,0 +1,32 @@ +package dev.voir.stately + +import androidx.compose.runtime.Composable +import androidx.compose.runtime.State +import androidx.compose.runtime.collectAsState +import androidx.compose.runtime.remember +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.IO + +@Composable +fun rememberStatelyFetch( + fetcher: suspend () -> Data, + scope: CoroutineScope = CoroutineScope(Dispatchers.IO), + revalidateInterval: Long? = null, + initiallyLoading: Boolean = true, + lazy: Boolean = false, + initialData: Data? = null, +) = remember { + StatelyFetch( + fetcher = { fetcher() }, + scope = scope, + revalidateInterval = revalidateInterval, + initialData = initialData, + initiallyLoading = initiallyLoading, + lazy = lazy + ) +} + +@Composable +fun StatelyFetch.collectAsState(): State> = + this.state.collectAsState() diff --git a/stately/src/commonMain/kotlin/dev/voir/stately/ui/StatelyFetchBoundary.kt b/stately/src/commonMain/kotlin/dev/voir/stately/ui/StatelyFetchBoundary.kt new file mode 100644 index 0000000..56b16fd --- /dev/null +++ b/stately/src/commonMain/kotlin/dev/voir/stately/ui/StatelyFetchBoundary.kt @@ -0,0 +1,32 @@ +package dev.voir.stately.ui + +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import dev.voir.stately.collectAsState +import dev.voir.stately.rememberStatelyFetch +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.IO + +@Composable +fun StatelyFetchBoundary( + fetcher: suspend () -> Data, + loading: @Composable (() -> Unit)? = null, + error: @Composable ((Throwable) -> Unit)? = null, + scope: CoroutineScope = CoroutineScope(Dispatchers.IO), + revalidateInterval: Long? = null, + content: @Composable (data: Data) -> Unit +) { + val state by rememberStatelyFetch( + fetcher = fetcher, + scope = scope, + revalidateInterval = revalidateInterval, + ).collectAsState() + + StatelyFetchContent( + state = state, + loading = loading, + error = error, + content = content + ) +} diff --git a/stately/src/commonMain/kotlin/dev/voir/stately/ui/StatelyFetchContent.kt b/stately/src/commonMain/kotlin/dev/voir/stately/ui/StatelyFetchContent.kt new file mode 100644 index 0000000..f823d1d --- /dev/null +++ b/stately/src/commonMain/kotlin/dev/voir/stately/ui/StatelyFetchContent.kt @@ -0,0 +1,24 @@ +package dev.voir.stately.ui + +import androidx.compose.runtime.Composable +import dev.voir.stately.StatelyFetchResult + +@Composable +fun StatelyFetchContent( + state: StatelyFetchResult, + loading: @Composable (() -> Unit)? = null, + error: @Composable ((Throwable) -> Unit)? = null, + content: @Composable (data: Data) -> Unit +) { + if (state.loading) { + if (loading != null) { + loading() + } + } else if (state.error != null) { + if (error != null) { + error(state.error) + } + } else if (state.data != null) { + content(state.data) + } +} diff --git a/stately/src/commonTest/kotlin/StatelyActionTest.kt b/stately/src/commonTest/kotlin/StatelyActionTest.kt new file mode 100644 index 0000000..4a1429b --- /dev/null +++ b/stately/src/commonTest/kotlin/StatelyActionTest.kt @@ -0,0 +1,125 @@ +import dev.voir.stately.StatelyAction +import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.cancel +import kotlinx.coroutines.delay +import kotlinx.coroutines.test.StandardTestDispatcher +import kotlinx.coroutines.test.TestScope +import kotlinx.coroutines.test.advanceUntilIdle +import kotlinx.coroutines.test.runTest +import kotlin.test.AfterTest +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFalse +import kotlin.test.assertNull +import kotlin.test.assertTrue + +@OptIn(ExperimentalCoroutinesApi::class) +class StatelyActionTest { + + private val dispatcher = StandardTestDispatcher() + private val scope = TestScope(dispatcher) + + @AfterTest + fun tearDown() { + scope.cancel() + } + + + @Test + fun `executes action and updates state`() = scope.runTest { + val action = StatelyAction( + action = { payload -> "Echo: $payload" }, + scope = this + ) + + action.execute("Test") + advanceUntilIdle() + + val result = action.state.value + assertFalse(result.loading) + assertEquals("Echo: Test", result.response) + assertNull(result.error) + } + + @Test + fun `calls onSuccess callback`() = scope.runTest { + var successCalled = false + var resultFromCallback: String? = null + + val action = StatelyAction( + action = { "OK" }, + scope = this, + onSuccess = { + successCalled = true + resultFromCallback = it + } + ) + + action.execute("payload") + advanceUntilIdle() + + assertTrue(successCalled) + assertEquals("OK", resultFromCallback) + } + + @Test + fun `calls onError callback`() = scope.runTest { + var errorCalled = false + var errorMessage: String? = null + + val action = StatelyAction( + action = { throw RuntimeException("Fail!") }, + scope = this, + onError = { + errorCalled = true + errorMessage = it.message + } + ) + + action.execute("payload") + advanceUntilIdle() + + assertTrue(errorCalled) + assertEquals("Fail!", errorMessage) + } + + @Test + fun `does not execute if already sending`() = scope.runTest { + var count = 0 + + val action = StatelyAction( + action = { + count++ + delay(1000) + "done" + }, + scope = this + ) + + action.execute("1") + action.execute("2") // should be ignored + advanceUntilIdle() + + assertEquals(1, count) + assertEquals("done", action.state.value.response) + } + + @Test + fun `resets loading after completion`() = scope.runTest { + val action = StatelyAction( + action = { + delay(500) + "completed" + }, + scope = this + ) + + action.execute("payload") + + advanceUntilIdle() + + // Check loading = false after + assertFalse(action.state.value.loading) + assertEquals("completed", action.state.value.response) + } +} diff --git a/stately/src/commonTest/kotlin/StatelyFetchTest.kt b/stately/src/commonTest/kotlin/StatelyFetchTest.kt new file mode 100644 index 0000000..e4b14cc --- /dev/null +++ b/stately/src/commonTest/kotlin/StatelyFetchTest.kt @@ -0,0 +1,123 @@ +import dev.voir.stately.StatelyFetch +import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.cancel +import kotlinx.coroutines.test.StandardTestDispatcher +import kotlinx.coroutines.test.TestScope +import kotlinx.coroutines.test.advanceUntilIdle +import kotlinx.coroutines.test.runTest +import kotlin.test.AfterTest +import kotlin.test.BeforeTest +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFalse +import kotlin.test.assertNotNull +import kotlin.test.assertTrue + +@OptIn(ExperimentalCoroutinesApi::class) +class StatelyFetchTest { + + private val dispatcher = StandardTestDispatcher() + private val scope = TestScope(dispatcher) + + @BeforeTest + fun setup() { + // Setup phase + } + + @AfterTest + fun tearDown() { + scope.cancel() + } + + @Test + fun `fetches immediately when not lazy`() = scope.runTest { + var called = false + val fetch = StatelyFetch( + fetcher = { + called = true + "Hello" + }, + scope = this, + lazy = false + ) + + advanceUntilIdle() + + assertTrue(called) + assertEquals("Hello", fetch.state.value.data) + } + + @Test + fun `does not fetch when lazy until revalidate`() = scope.runTest { + var called = false + val fetch = StatelyFetch( + fetcher = { + called = true + "World" + }, + scope = this, + lazy = true + ) + + assertFalse(called) + + fetch.revalidate() + + advanceUntilIdle() + assertTrue(called) + assertEquals("World", fetch.state.value.data) + } + + @Test + fun `sets error on exception`() = scope.runTest { + val fetch = StatelyFetch( + fetcher = { throw Exception("Boom") }, + scope = this, + lazy = false + ) + + advanceUntilIdle() + + assertNotNull(fetch.state.value.error) + assertEquals("Boom", fetch.state.value.error?.message) + } + + @Test + fun `keeps previous data on error`() = scope.runTest { + var shouldFail = false + val fetch = StatelyFetch( + fetcher = { + if (shouldFail) throw Exception("Oops") + "Data" + }, + scope = this, + lazy = true + ) + + fetch.revalidate() + advanceUntilIdle() + assertEquals("Data", fetch.state.value.data) + + shouldFail = true + fetch.revalidate() + advanceUntilIdle() + + assertEquals("Data", fetch.state.value.data) + assertEquals("Oops", fetch.state.value.error?.message) + } + + @Test + fun `uses payload in fetch`() = scope.runTest { + val fetch = StatelyFetch( + fetcher = { payload -> "Got $payload" }, + scope = this, + lazy = true + ) + + fetch.revalidate("ABC") + advanceUntilIdle() + + assertEquals("Got ABC", fetch.state.value.data) + assertEquals("ABC", fetch.state.value.payload) + } +}