Skip to content

Introduce renderComposable. #1271

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Draft
wants to merge 1 commit into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
package com.squareup.sample.compose.hellocompose

import com.squareup.sample.compose.hellocompose.HelloComposeWorkflow.State
import com.squareup.sample.compose.hellocompose.HelloComposeWorkflow.State.Goodbye
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import com.squareup.sample.compose.hellocompose.HelloComposeWorkflow.State.Hello
import com.squareup.workflow1.Snapshot
import com.squareup.workflow1.StatefulWorkflow
import com.squareup.workflow1.action
import com.squareup.workflow1.parse
import com.squareup.workflow1.StatelessWorkflow
import com.squareup.workflow1.WorkflowExperimentalApi

object HelloComposeWorkflow : StatefulWorkflow<Unit, State, Nothing, HelloComposeScreen>() {
object HelloComposeWorkflow : StatelessWorkflow<Unit, Nothing, HelloComposeScreen>() {
enum class State {
Hello,
Goodbye;
Expand All @@ -19,24 +19,15 @@ object HelloComposeWorkflow : StatefulWorkflow<Unit, State, Nothing, HelloCompos
}
}

private val helloAction = action("hello") {
state = state.theOtherState()
}

override fun initialState(
props: Unit,
snapshot: Snapshot?
): State = snapshot?.bytes?.parse { source -> if (source.readInt() == 1) Hello else Goodbye }
?: Hello

@OptIn(WorkflowExperimentalApi::class)
override fun render(
renderProps: Unit,
renderState: State,
context: RenderContext
): HelloComposeScreen = HelloComposeScreen(
message = renderState.name,
onClick = { context.actionSink.send(helloAction) }
)

override fun snapshotState(state: State): Snapshot = Snapshot.of(if (state == Hello) 1 else 0)
): HelloComposeScreen = context.renderComposable {
var state by remember { mutableStateOf(Hello) }
HelloComposeScreen(
message = state.name,
onClick = { state = state.theOtherState() }
)
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import androidx.compose.ui.graphics.Color
import androidx.lifecycle.SavedStateHandle
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.squareup.workflow1.SimpleLoggingWorkflowInterceptor
import com.squareup.workflow1.WorkflowExperimentalRuntime
import com.squareup.workflow1.config.AndroidRuntimeConfigTools
import com.squareup.workflow1.mapRendering
Expand Down Expand Up @@ -59,7 +60,8 @@ class NestedRenderingsActivity : AppCompatActivity() {
workflow = RecursiveWorkflow.mapRendering { it.withEnvironment(viewEnvironment) },
scope = viewModelScope,
savedStateHandle = savedState,
runtimeConfig = AndroidRuntimeConfigTools.getAppWorkflowRuntimeConfig()
runtimeConfig = AndroidRuntimeConfigTools.getAppWorkflowRuntimeConfig(),
interceptors = listOf(SimpleLoggingWorkflowInterceptor())
)
}
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,13 +1,15 @@
package com.squareup.sample.compose.nestedrenderings

import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import com.squareup.sample.compose.databinding.LegacyViewBinding
import com.squareup.sample.compose.nestedrenderings.RecursiveWorkflow.LegacyRendering
import com.squareup.sample.compose.nestedrenderings.RecursiveWorkflow.Rendering
import com.squareup.sample.compose.nestedrenderings.RecursiveWorkflow.State
import com.squareup.workflow1.Snapshot
import com.squareup.workflow1.StatefulWorkflow
import com.squareup.workflow1.action
import com.squareup.workflow1.renderChild
import com.squareup.workflow1.StatelessWorkflow
import com.squareup.workflow1.WorkflowExperimentalApi
import com.squareup.workflow1.ui.AndroidScreen
import com.squareup.workflow1.ui.Screen
import com.squareup.workflow1.ui.ScreenViewFactory
Expand All @@ -22,9 +24,7 @@ import com.squareup.workflow1.ui.WorkflowUiExperimentalApi
* through Composable renderings as well as adapting in both directions.
*/
@OptIn(WorkflowUiExperimentalApi::class)
object RecursiveWorkflow : StatefulWorkflow<Unit, State, Nothing, Screen>() {

data class State(val children: Int = 0)
object RecursiveWorkflow : StatelessWorkflow<Unit, Nothing, Screen>() {

/**
* A rendering from a [RecursiveWorkflow].
Expand All @@ -51,33 +51,29 @@ object RecursiveWorkflow : StatefulWorkflow<Unit, State, Nothing, Screen>() {
)
}

override fun initialState(
props: Unit,
snapshot: Snapshot?
): State = State()

@OptIn(WorkflowExperimentalApi::class)
override fun render(
renderProps: Unit,
renderState: State,
context: RenderContext
): Rendering {
return Rendering(
children = List(renderState.children) { i ->
val child = context.renderChild(RecursiveWorkflow, key = i.toString())
if (i % 2 == 0) child else LegacyRendering(child)
},
onAddChildClicked = { context.actionSink.send(addChild()) },
onResetClicked = { context.actionSink.send(reset()) }
)
): Rendering = context.renderComposable {
produceRendering()
}
}

override fun snapshotState(state: State): Snapshot? = null

private fun addChild() = action("addChild") {
state = state.copy(children = state.children + 1)
}
@OptIn(WorkflowUiExperimentalApi::class)
@Composable
private fun produceRendering(): Rendering {
var children by remember { mutableIntStateOf(0) }

private fun reset() = action("reset") {
state = State()
}
return Rendering(
children = List(children) { i ->
val child = produceRendering()
if ((i % 2) == 0) child else LegacyRendering(child)
},
onAddChildClicked = {
println("OMG onAddChildClicked")
children++
},
onResetClicked = { children = 0 }
)
}
1 change: 1 addition & 0 deletions settings.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ pluginManagement {
google()
// For binary compatibility validator.
maven { url = uri("https://kotlin.bintray.com/kotlinx") }
maven("https://maven.pkg.jetbrains.space/public/p/compose/dev")
}
includeBuild("build-logic")
}
Expand Down
3 changes: 3 additions & 0 deletions workflow-core/build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import com.squareup.workflow1.buildsrc.iosWithSimulatorArm64
plugins {
id("kotlin-multiplatform")
id("published")
id("org.jetbrains.compose") version "1.6.11"
}

kotlin {
Expand All @@ -23,6 +24,8 @@ dependencies {
commonMainApi(libs.kotlinx.coroutines.core)
// For Snapshot.
commonMainApi(libs.squareup.okio)
commonMainApi("org.jetbrains.compose.runtime:runtime:1.7.3")
commonMainApi("org.jetbrains.compose.runtime:runtime-saveable:1.7.3")

commonTestImplementation(libs.kotlinx.atomicfu)
commonTestImplementation(libs.kotlinx.coroutines.test.common)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,9 @@

package com.squareup.workflow1

import androidx.compose.runtime.Composable
import com.squareup.workflow1.WorkflowAction.Companion.noAction
import com.squareup.workflow1.compose.WorkflowComposable
import kotlinx.coroutines.CoroutineScope
import kotlin.jvm.JvmMultifileClass
import kotlin.jvm.JvmName
Expand Down Expand Up @@ -85,6 +87,27 @@ public interface BaseRenderContext<out PropsT, StateT, in OutputT> {
handler: (ChildOutputT) -> WorkflowAction<PropsT, StateT, OutputT>
): ChildRenderingT

/**
* Synchronously composes a [content] function and returns its rendering. Whenever [content] is
* invalidated (i.e. a compose snapshot state object is changed that was previously read by
* [content] or any functions it calls), this workflow will be re-rendered and the relevant
* composables will be recomposed.
*
* The `emitOutput` function passed to [content] should be used to trigger [WorkflowAction]s in
* this workflow via [handler]. Every invocation of `emitOutput` will result [handler]s action
* being sent to this context's [actionSink]. However, it's important for the composable never to
* send to [actionSink] directly because we need to ensure that any state writes the composable
* does invalidate their composables before sending into the [actionSink].
*/
@WorkflowExperimentalApi
public fun <ChildOutputT, ChildRenderingT> renderComposable(
key: String = "",
handler: (ChildOutputT) -> WorkflowAction<PropsT, StateT, OutputT>,
content: @WorkflowComposable @Composable (
emitOutput: (ChildOutputT) -> Unit
) -> ChildRenderingT
): ChildRenderingT

/**
* Ensures [sideEffect] is running with the given [key].
*
Expand Down Expand Up @@ -375,6 +398,20 @@ public fun <PropsT, StateT, OutputT, ChildRenderingT>
key: String = ""
): ChildRenderingT = renderChild(child, Unit, key) { noAction() }

/**
* TODO
*/
@WorkflowExperimentalApi
public fun <PropsT, StateT, OutputT, ChildRenderingT>
BaseRenderContext<PropsT, StateT, OutputT>.renderComposable(
key: String = "",
content: @WorkflowComposable @Composable () -> ChildRenderingT
): ChildRenderingT = renderComposable<Nothing, ChildRenderingT>(
key = key,
handler = { noAction() },
content = { content() }
)

/**
* Ensures a [LifecycleWorker] is running. Since [worker] can't emit anything,
* it can't trigger any [WorkflowAction]s.
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
package com.squareup.workflow1.compose

import androidx.compose.runtime.ComposableTargetMarker
import com.squareup.workflow1.WorkflowExperimentalApi
import kotlin.annotation.AnnotationRetention.BINARY
import kotlin.annotation.AnnotationTarget.FILE
import kotlin.annotation.AnnotationTarget.FUNCTION
import kotlin.annotation.AnnotationTarget.PROPERTY_GETTER
import kotlin.annotation.AnnotationTarget.TYPE
import kotlin.annotation.AnnotationTarget.TYPE_PARAMETER

/**
* An annotation that can be used to mark a composable function as being expected to be use in a
* composable function that is also marked or inferred to be marked as a [WorkflowComposable], i.e.
* that can be called from [BaseRenderContext.renderComposable].
*
* Using this annotation explicitly is rarely necessary as the Compose compiler plugin will infer
* the necessary equivalent annotations automatically. See
* [androidx.compose.runtime.ComposableTarget] for details.
*/
@WorkflowExperimentalApi
@ComposableTargetMarker(description = "Workflow Composable")
@Target(FILE, FUNCTION, PROPERTY_GETTER, TYPE, TYPE_PARAMETER)
@Retention(BINARY)
public annotation class WorkflowComposable
8 changes: 8 additions & 0 deletions workflow-runtime/build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import com.squareup.workflow1.buildsrc.iosWithSimulatorArm64
plugins {
id("kotlin-multiplatform")
id("published")
id("org.jetbrains.compose") version "1.6.11"
}

kotlin {
Expand All @@ -16,6 +17,13 @@ kotlin {
if (targets == "kmp" || targets == "js") {
js(IR) { browser() }
}
sourceSets {
getByName("commonMain") {
dependencies {
implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.8.1")
}
}
}
}

dependencies {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package com.squareup.workflow1

import androidx.compose.runtime.Composable
import com.squareup.workflow1.WorkflowInterceptor.RenderContextInterceptor
import com.squareup.workflow1.WorkflowInterceptor.WorkflowSession
import kotlinx.coroutines.CoroutineScope
Expand Down Expand Up @@ -150,5 +151,15 @@ public open class SimpleLoggingWorkflowInterceptor : WorkflowInterceptor {
}
}
}

override fun <CR> onRenderComposable(
key: String,
content: @Composable () -> CR,
proceed: (key: String, content: @Composable () -> CR) -> CR
): CR = proceed(key) {
logMethod("onRenderComposable", session, "key" to key, "content" to content) {
content()
}
}
}
}
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
package com.squareup.workflow1

import androidx.compose.runtime.Composable
import com.squareup.workflow1.WorkflowInterceptor.RenderContextInterceptor
import com.squareup.workflow1.WorkflowInterceptor.WorkflowSession
import com.squareup.workflow1.compose.WorkflowComposable
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Job
import kotlin.coroutines.CoroutineContext
Expand Down Expand Up @@ -259,6 +261,15 @@ public interface WorkflowInterceptor {
handler: (CO) -> WorkflowAction<P, S, O>
) -> CR
): CR = proceed(child, childProps, key, handler)

public fun <CO, CR> onRenderComposable(
key: String,
content: @Composable (CO) -> CR,
proceed: (
key: String,
content: @Composable (CO) -> CR
) -> CR
): CR = proceed(key, content)
}
}

Expand Down Expand Up @@ -384,6 +395,23 @@ private class InterceptedRenderContext<P, S, O>(
}
}

@OptIn(WorkflowExperimentalApi::class)
override fun <ChildOutputT, ChildRenderingT> renderComposable(
key: String,
handler: (ChildOutputT) -> WorkflowAction<P, S, O>,
content: @WorkflowComposable @Composable (emitOutput: (ChildOutputT) -> Unit) -> ChildRenderingT
): ChildRenderingT = interceptor.onRenderComposable(
key = key,
content = content,
proceed = { iKey, iContent ->
baseRenderContext.renderComposable(
key = iKey,
handler = handler,
content = iContent
)
}
)

/**
* In a block with a CoroutineScope receiver, calls to `coroutineContext` bind
* to `CoroutineScope.coroutineContext` instead of `suspend val coroutineContext`.
Expand Down
Loading