Skip to content
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

Add support to save non-mutable int in StateSnapshot #1508

Merged
merged 3 commits into from
Sep 26, 2023
Merged
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
Expand Up @@ -109,7 +109,7 @@ private class RedwoodZiplineTreehouseUi(
)
}

override fun snapshotState(): StateSnapshot? {
override fun snapshotState(): StateSnapshot {
val savedState = saveableStateRegistry.performSave()
return savedState.toStateSnapshot()
}
Expand Down
7 changes: 7 additions & 0 deletions redwood-treehouse/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,13 @@ kotlin {
api libs.zipline
}
}

commonTest {
dependencies {
implementation libs.kotlin.test
implementation libs.assertk
}
}
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,20 +18,28 @@ package app.cash.redwood.treehouse
import androidx.compose.runtime.MutableState
import androidx.compose.runtime.mutableStateOf
import kotlin.jvm.JvmInline
import kotlinx.serialization.Contextual
import kotlinx.serialization.Serializable
import kotlinx.serialization.json.JsonArray
import kotlinx.serialization.json.JsonElement
import kotlinx.serialization.json.JsonPrimitive
import kotlinx.serialization.json.booleanOrNull
import kotlinx.serialization.json.doubleOrNull
import kotlinx.serialization.json.intOrNull

@Serializable
public class StateSnapshot(
public val content: Map<String, List<JsonElement?>>,
public val content: Map<String, List<@Contextual Saveable>>,
) {
public fun toValuesMap(): Map<String, List<Any?>>? {
public fun toValuesMap(): Map<String, List<Any?>> {
return content.mapValues { entry ->
entry.value.map { mutableStateOf(it.fromJsonElement()) }
entry.value.map {
if (it.isMutableState) {
mutableStateOf(it.value)
} else {
it.value.fromJsonElement()
}
Comment on lines +37 to +41
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We could remove the need for the Saveable wrapper class if we wrote an adapter to convert between MutableState and JsonElement. Perhaps it isn't worth the effort though, considering we'll change up this mechanism in #1384.

}
}
}

Expand All @@ -48,8 +56,8 @@ public fun Map<String, List<Any?>>.toStateSnapshot(): StateSnapshot = StateSnaps
mapValues { entry ->
entry.value.map { element ->
when (element) {
is MutableState<*> -> element.value.toJsonElement()
else -> error("unexpected type: $this")
is MutableState<*> -> Saveable(true, element.value.toJsonElement())
else -> Saveable(false, element.toJsonElement())
}
}
},
Expand All @@ -58,6 +66,7 @@ public fun Map<String, List<Any?>>.toStateSnapshot(): StateSnapshot = StateSnaps
private fun Any?.toJsonElement(): JsonElement {
return when (this) {
is String -> JsonPrimitive(this)
is Int -> JsonPrimitive(this)
is List<*> -> JsonArray(map { it.toJsonElement() })
is JsonElement -> this
else -> error("unexpected type: $this")
Expand All @@ -68,11 +77,9 @@ private fun Any?.toJsonElement(): JsonElement {
private fun JsonElement?.fromJsonElement(): Any {
return when (this) {
is JsonPrimitive -> {
if (this.isString) {
return content
}
return booleanOrNull ?: doubleOrNull ?: error("unexpected type: $this")
// TODO add other primitive types (double, float, long) when needed
if (this.isString) return content
return booleanOrNull ?: doubleOrNull ?: intOrNull ?: error("unexpected type: $this")
// TODO add other primitive types (float, long) when needed
}

is JsonArray -> listOf({ this.forEach { it.toJsonElement() } })
Expand All @@ -81,3 +88,8 @@ private fun JsonElement?.fromJsonElement(): Any {
else -> error("unexpected type: $this")
}
}

public data class Saveable(
val isMutableState: Boolean,
val value: JsonElement,
)
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
/*
* Copyright (C) 2023 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package app.cash.redwood.treehouse

import androidx.compose.runtime.MutableState
import androidx.compose.runtime.mutableStateOf
import assertk.assertThat
import assertk.assertions.containsOnly
import assertk.assertions.isEqualTo
import kotlin.test.Test
import kotlin.test.assertTrue
import kotlinx.serialization.json.JsonPrimitive

class StateSnapshotTest {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Tests! Love it 😄


@Test
fun toValueMapWorksAsExpected() {
val stateSnapshot = stateSnapshot()
val valuesMap = stateSnapshot.toValuesMap()
assertThat(valuesMap.entries.size).isEqualTo(4)
assertTrue(valuesMap["key1"]!![0] is MutableState<*>)
assertThat((valuesMap["key1"]!![0] as MutableState<*>).value).isEqualTo(JsonPrimitive(1))

assertThat(valuesMap["key2"]).isEqualTo(listOf(1.0))

assertThat(valuesMap["key3"]!![0] is MutableState<*>)
assertThat((valuesMap["key3"]!![0] as MutableState<*>).value).isEqualTo(JsonPrimitive("str"))

assertThat(valuesMap["key4"]).isEqualTo(listOf("str"))
Comment on lines +33 to +42
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could these test cases be simplified with the containsOnly function?

    assertThat(valuesMap).containsOnly(
        "key1" to listOf(mutableStateOf(JsonPrimitive(1)),
        …
    )

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

containsOnly errors out:

expected to contain only:<{"key1"=[MutableState(value=1)@916835004], "key2"=[1.0], "key3"=[MutableState(value="str")@2108297149], "key4"=["str"]}> but was:<{"key1"=[MutableState(value=1)@1112737073], "key2"=[1.0], "key3"=[MutableState(value="str")@1513867245], "key4"=["str"]}> elements not found:<{"key1"=[MutableState(value=1)@916835004], "key3"=[MutableState(value="str")@2108297149]}> extra elements found:<{"key1"=[MutableState(value=1)@1112737073], "key3"=[MutableState(value="str")@1513867245]}>

for the MutableState ones, containsOnly doesn't unwrap and compare the values (it compares the instances)

}

@Test
fun toStateSnapshotWorksAsExpected() {
val storedStateSnapshot = storedStateSnapshot()
val stateSnapshot = storedStateSnapshot.toStateSnapshot()
assertThat(stateSnapshot.content).containsOnly(
"key1" to listOf(Saveable(true, JsonPrimitive(1))),
"key2" to listOf(Saveable(false, JsonPrimitive(1))),
"key3" to listOf(Saveable(true, JsonPrimitive("str"))),
"key4" to listOf(Saveable(false, JsonPrimitive("str"))),
)
}

private fun stateSnapshot() = StateSnapshot(
mapOf(
"key1" to listOf(Saveable(true, JsonPrimitive(1))),
"key2" to listOf(Saveable(false, JsonPrimitive(1))),
"key3" to listOf(Saveable(true, JsonPrimitive("str"))),
"key4" to listOf(Saveable(false, JsonPrimitive("str"))),
),
)

private fun storedStateSnapshot() = mapOf(
"key1" to listOf(mutableStateOf(1)),
"key2" to listOf(1),
"key3" to listOf(mutableStateOf("str")),
"key4" to listOf("str"),
)
}