Repository: zach-klippenstein/compose-undo Branch: main Commit: 274fe613693b Files: 40 Total size: 79.6 KB Directory structure: gitextract_r4b_iw8e/ ├── .gitignore ├── LICENSE ├── README.md ├── build.gradle ├── demo/ │ ├── .gitignore │ ├── build.gradle │ ├── proguard-rules.pro │ └── src/ │ ├── androidTest/ │ │ └── java/ │ │ └── com/ │ │ └── zachklipp/ │ │ └── statehistory/ │ │ └── demo/ │ │ └── DemoTest.kt │ └── main/ │ ├── AndroidManifest.xml │ ├── java/ │ │ └── com/ │ │ └── zachklipp/ │ │ └── statehistory/ │ │ └── demo/ │ │ ├── App.kt │ │ ├── AppWithInspector.kt │ │ ├── MainActivity.kt │ │ ├── StateHistoryInspector.kt │ │ └── ui/ │ │ └── theme/ │ │ ├── Color.kt │ │ ├── Shape.kt │ │ ├── Theme.kt │ │ └── Type.kt │ └── res/ │ ├── drawable/ │ │ └── ic_launcher_background.xml │ ├── drawable-v24/ │ │ └── ic_launcher_foreground.xml │ ├── mipmap-anydpi-v26/ │ │ ├── ic_launcher.xml │ │ └── ic_launcher_round.xml │ ├── values/ │ │ ├── colors.xml │ │ ├── strings.xml │ │ └── themes.xml │ └── xml/ │ ├── backup_rules.xml │ └── data_extraction_rules.xml ├── gradle/ │ └── wrapper/ │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradle.properties ├── gradlew ├── gradlew.bat ├── settings.gradle └── statehistory/ ├── .gitignore ├── build.gradle ├── gradle.properties ├── proguard-rules.pro └── src/ ├── androidTest/ │ └── java/ │ └── com/ │ └── zachklipp/ │ └── statehistory/ │ └── demo/ │ └── StateHistoryTest.kt ├── main/ │ ├── AndroidManifest.xml │ └── java/ │ └── com/ │ └── zachklipp/ │ └── statehistory/ │ └── StateHistory.kt └── test/ └── java/ └── com/ └── zachklipp/ └── statehistory/ └── demo/ └── StateHistoryTest.kt ================================================ FILE CONTENTS ================================================ ================================================ FILE: .gitignore ================================================ # Built application files *.apk *.aar *.ap_ *.aab # Files for the ART/Dalvik VM *.dex # Java class files *.class # Generated files bin/ gen/ out/ # Uncomment the following line in case you need and you don't have the release build type files in your app # release/ # Gradle files .gradle/ build/ # Local configuration file (sdk path, etc) local.properties # Proguard folder generated by Eclipse proguard/ # Log Files *.log # Android Studio Navigation editor temp files .navigation/ # Android Studio captures folder captures/ # IntelliJ *.iml .idea/workspace.xml .idea/tasks.xml .idea/gradle.xml .idea/assetWizardSettings.xml .idea/dictionaries .idea/libraries # Android Studio 3 in .gitignore file. .idea/caches .idea/modules.xml # Comment next line if keeping position of elements in Navigation Editor is relevant for you .idea/navEditor.xml # Keystore files # Uncomment the following lines if you do not want to check your keystore files in. #*.jks #*.keystore # External native build folder generated in Android Studio 2.2 and later .externalNativeBuild .cxx/ # Google Services (e.g. APIs or Firebase) # google-services.json # Freeline freeline.py freeline/ freeline_project_description.json # fastlane fastlane/report.xml fastlane/Preview.html fastlane/screenshots fastlane/test_output fastlane/readme.md # Version control vcs.xml # lint lint/intermediates/ lint/generated/ lint/outputs/ lint/tmp/ # lint/reports/ # From android studio *.iml .gradle /local.properties /.idea/caches /.idea/libraries /.idea/modules.xml /.idea/workspace.xml /.idea/navEditor.xml /.idea/assetWizardSettings.xml .DS_Store /build /captures .externalNativeBuild .cxx local.properties .idea/* ================================================ FILE: LICENSE ================================================ Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] 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. ================================================ FILE: README.md ================================================ # compose-undo ![Maven Central](https://img.shields.io/maven-central/v/com.zachklipp.compose-undo/statehistory) Track changes to any snapshot state object and restore state from any point in the past. ## Usage ```groovy implementation 'com.zachklipp.compose-undo:statehistory:{version}' ``` The simplest way to get started is to use the `WithStateHistory` composable: ```kotlin @Composable fun App() { WithStateHistory { history -> var text by remember { mutableStateOf(TextFieldValue("")) }.trackStateChanges() TextField(text, onValueChange = { text = it }) Button(onClick { history.undo() }) { Text("Undo") } } } ``` The key is to call `trackStateChanges` on every snapshot state object you want to track. If you're creating state objects outside a composition, call `StateHistory.startTrackingState` yourself. ## Advanced usage The main API is the `StateHistory` class. See [its kdoc](/statehistory/src/main/java/com/zachklipp/statehistory/StateHistory.kt) for more detailed information. ## Demo This repo includes a demo app you can run and tinker with if you fork the repo. Here's a little preview: https://user-images.githubusercontent.com/101754/190877868-160456a2-5bd1-498d-9c76-147fb04958e6.mp4 ## How it works `StateHistory` keeps a set of all the state objects that were registered on it. It registers an apply listener to the snapshot system, and any time a snapshot is applied to the global snapshot it checks if any of the objects changed by that snapshot are being tracked. For every tracked changed object, it makes a copy of its latest state record. It collects all changes to tracked objects in a map (called a "frame"), then when `saveFrame` is called, it pushes that map onto the list of frames that represents the history. When asked to restore states to a particular frame, it goes through every tracked state object and searches the frame list from the requested frame to find the latest frame that captured a change to that object. It then asks the snapshot system for a writable record for that object and copies the saved record back into the writable record, effectively setting the state object's value. This is a very unconventional and probably unsupported use case of the [`StateObject`](https://developer.android.com/reference/kotlin/androidx/compose/runtime/snapshots/StateObject) and [`StateRecord`](https://developer.android.com/reference/kotlin/androidx/compose/runtime/snapshots/StateRecord) APIs, but it allows the library to support any type of state object, even custom third-party ones. The actual implementation for saving and restoring state values looks something like this (`stateObject` is a `StateObject`): ```kotlin // Save a state object's current value val savedRecord = stateObject.firstStateRecord.create() stateObject.firstStateRecord.withCurrent { currentRecord -> savedRecord.assign(currentRecord) } // Restore the value stateObject.firstStateRecord.writable(stateObject) { assign(savedRecord) } ``` ================================================ FILE: build.gradle ================================================ buildscript { ext { compose_ui_version = '1.3.0-beta02' } }// Top-level build file where you can add configuration options common to all sub-projects/modules. plugins { id 'com.android.application' version '7.4.0-alpha10' apply false id 'com.android.library' version '7.4.0-alpha10' apply false id 'org.jetbrains.kotlin.android' version '1.7.10' apply false id 'com.vanniktech.maven.publish' version '0.22.0' apply false } ================================================ FILE: demo/.gitignore ================================================ /build ================================================ FILE: demo/build.gradle ================================================ plugins { id 'com.android.application' id 'org.jetbrains.kotlin.android' } android { namespace 'com.zachklipp.statehistory.demo' compileSdk 33 defaultConfig { applicationId "com.zachklipp.statehistory.demo" minSdk 21 targetSdk 33 versionCode 1 versionName "1.0" testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" vectorDrawables { useSupportLibrary true } } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro' } } compileOptions { sourceCompatibility JavaVersion.VERSION_1_8 targetCompatibility JavaVersion.VERSION_1_8 } kotlinOptions { jvmTarget = '1.8' } buildFeatures { compose true } composeOptions { kotlinCompilerExtensionVersion '1.3.1' } packagingOptions { resources { excludes += '/META-INF/{AL2.0,LGPL2.1}' } } } dependencies { implementation project(':statehistory') implementation 'androidx.core:core-ktx:1.9.0' implementation 'androidx.lifecycle:lifecycle-runtime-ktx:2.5.1' implementation 'androidx.lifecycle:lifecycle-viewmodel-compose:2.5.1' implementation 'androidx.activity:activity-compose:1.5.1' implementation "androidx.compose.ui:ui:$compose_ui_version" implementation "androidx.compose.ui:ui-tooling-preview:$compose_ui_version" implementation 'androidx.compose.material:material:1.2.1' testImplementation 'junit:junit:4.13.2' androidTestImplementation 'androidx.test.ext:junit:1.1.3' androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0' androidTestImplementation "androidx.compose.ui:ui-test-junit4:$compose_ui_version" androidTestImplementation 'com.google.truth:truth:1.1.3' debugImplementation "androidx.compose.ui:ui-tooling:$compose_ui_version" debugImplementation "androidx.compose.ui:ui-test-manifest:$compose_ui_version" } ================================================ FILE: demo/proguard-rules.pro ================================================ # Add project specific ProGuard rules here. # You can control the set of applied configuration files using the # proguardFiles setting in build.gradle. # # For more details, see # http://developer.android.com/guide/developing/tools/proguard.html # If your project uses WebView with JS, uncomment the following # and specify the fully qualified class name to the JavaScript interface # class: #-keepclassmembers class fqcn.of.javascript.interface.for.webview { # public *; #} # Uncomment this to preserve the line number information for # debugging stack traces. #-keepattributes SourceFile,LineNumberTable # If you keep the line number information, uncomment this to # hide the original source file name. #-renamesourcefileattribute SourceFile ================================================ FILE: demo/src/androidTest/java/com/zachklipp/statehistory/demo/DemoTest.kt ================================================ package com.zachklipp.statehistory.demo import androidx.compose.ui.semantics.SemanticsActions import androidx.compose.ui.semantics.SemanticsProperties import androidx.compose.ui.semantics.progressBarRangeInfo import androidx.compose.ui.test.* import androidx.compose.ui.test.junit4.createComposeRule import androidx.test.ext.junit.runners.AndroidJUnit4 import com.google.common.truth.Truth.assertThat import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith @RunWith(AndroidJUnit4::class) class DemoTest { @get:Rule val rule = createComposeRule() @Test fun typingUpdatesFrameCount() { rule.setContent { AppWithInspector() } rule.onNode(hasSetTextAction()).performTextInput("a") rule.onNodeWithText("Frame 1 of 1").assertIsDisplayed() rule.onNode(hasSetTextAction()).performTextInput("b") rule.onNodeWithText("Frame 2 of 2").assertIsDisplayed() } @Test fun addingToListUpdatesFrameCount() { rule.setContent { AppWithInspector() } rule.onNode(hasSetTextAction()).performTextInput("a") rule.onNodeWithText("Add to list").performClick() rule.onNodeWithText("Frame 2 of 2").assertIsDisplayed() } @Test fun sliderScrubsHistory() { rule.setContent { AppWithInspector() } rule.onNode(hasSetTextAction()).performTextInput("a") rule.onNode(hasSetTextAction()).performTextInput("b") rule.onNode(hasSetTextAction()).assertTextEquals("ab") rule.onNode(hasSetProgressAction()).assertProgressValue(2f) rule.onNode(hasSetProgressAction()).performSetProgress(1f) rule.onNode(hasSetTextAction()).assertTextEquals("a") rule.onNodeWithText("Frame 1 of 2").assertIsDisplayed() } private fun hasSetProgressAction() = SemanticsMatcher("has setProgress action") { it.config.contains(SemanticsActions.SetProgress) } private fun SemanticsNodeInteraction.assertProgressValue(value: Float) { assertThat( fetchSemanticsNode().config[SemanticsProperties.ProgressBarRangeInfo].current ).isEqualTo(value) } private fun SemanticsNodeInteraction.performSetProgress(value: Float) { fetchSemanticsNode().config[SemanticsActions.SetProgress].action!!.invoke(value) } } ================================================ FILE: demo/src/main/AndroidManifest.xml ================================================ ================================================ FILE: demo/src/main/java/com/zachklipp/statehistory/demo/App.kt ================================================ package com.zachklipp.statehistory.demo import androidx.compose.foundation.border import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.items import androidx.compose.foundation.text.KeyboardActions import androidx.compose.foundation.text.KeyboardOptions import androidx.compose.material.Button import androidx.compose.material.Text import androidx.compose.material.TextField import androidx.compose.runtime.* import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.text.input.ImeAction import androidx.compose.ui.text.input.TextFieldValue import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import com.zachklipp.statehistory.trackStateHistory @Preview(showBackground = true, showSystemUi = true) @Composable fun AppPreview() { App() } @Composable fun App() { var textValue by remember { mutableStateOf(TextFieldValue("")) }.trackStateHistory() val valueList = remember { mutableStateListOf() }.trackStateHistory() fun addValueToList() { valueList += textValue.text textValue = TextFieldValue("") } Column(Modifier.padding(8.dp)) { TextField( modifier = Modifier.fillMaxWidth(), value = textValue, onValueChange = { textValue = it }, keyboardOptions = KeyboardOptions(imeAction = ImeAction.Send), keyboardActions = KeyboardActions { addValueToList() } ) Button( modifier = Modifier.fillMaxWidth(), onClick = { addValueToList() } ) { Text("Add to list") } LazyColumn( reverseLayout = true, modifier = Modifier .border(1.dp, Color.Black) .fillMaxWidth() ) { items(valueList) { Text(it, modifier = Modifier.padding(16.dp)) } } } } ================================================ FILE: demo/src/main/java/com/zachklipp/statehistory/demo/AppWithInspector.kt ================================================ package com.zachklipp.statehistory.demo import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.material.MaterialTheme import androidx.compose.material.Surface import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.lifecycle.ViewModel import androidx.lifecycle.viewmodel.compose.viewModel import com.zachklipp.statehistory.StateHistory import com.zachklipp.statehistory.demo.ui.theme.StateHistoryDemoTheme @Composable fun AppWithInspector() { val stateHistory = viewModel().stateHistory StateHistoryDemoTheme { // A surface container using the 'background' color from the theme Surface( modifier = Modifier.fillMaxSize(), color = MaterialTheme.colors.background ) { StateHistoryInspector(stateHistory) { App() } } } } class StateHistoryViewModel : ViewModel() { val stateHistory = StateHistory() } ================================================ FILE: demo/src/main/java/com/zachklipp/statehistory/demo/MainActivity.kt ================================================ package com.zachklipp.statehistory.demo import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.material.MaterialTheme import androidx.compose.material.Surface import androidx.compose.ui.Modifier import androidx.lifecycle.ViewModel import androidx.lifecycle.viewmodel.compose.viewModel import com.zachklipp.statehistory.StateHistory import com.zachklipp.statehistory.demo.ui.theme.StateHistoryDemoTheme class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { AppWithInspector() } } } ================================================ FILE: demo/src/main/java/com/zachklipp/statehistory/demo/StateHistoryInspector.kt ================================================ package com.zachklipp.statehistory.demo import androidx.compose.foundation.layout.* import androidx.compose.material.* import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.ArrowBack import androidx.compose.material.icons.filled.ArrowForward import androidx.compose.runtime.* import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.unit.dp import com.zachklipp.statehistory.* import kotlin.math.roundToInt @Composable fun StateHistoryInspector( stateHistory: StateHistory, modifier: Modifier = Modifier, content: @Composable () -> Unit ) { Column(modifier) { Box(propagateMinConstraints = true, modifier = Modifier.weight(1f)) { CompositionLocalProvider(LocalStateHistory provides stateHistory, content = content) } HistoryScrubber(stateHistory) } } @Composable private fun HistoryScrubber(stateHistory: StateHistory, modifier: Modifier = Modifier) { var recording by remember { mutableStateOf(true) } if (recording) { LaunchedEffect(stateHistory) { stateHistory.recordChanges { // Save a new frame every time something changes. This could also be done on a // timer, or only after significant actions. stateHistory.saveFrame() } } } Column(modifier.padding(8.dp)) { if (stateHistory.frameCount > 1) { Text( "Frame ${stateHistory.currentFrame} of ${stateHistory.frameCount - 1}", modifier = Modifier.align(Alignment.CenterHorizontally), style = MaterialTheme.typography.caption, ) Row( modifier = Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically, ) { Slider( value = stateHistory.currentFrame.toFloat(), valueRange = 0f..(stateHistory.frameCount - 1).toFloat(), steps = stateHistory.frameCount - 2, onValueChange = { stateHistory.setCurrentFrameGlobally(it.roundToInt()) }, modifier = Modifier .weight(1f) .padding(horizontal = 16.dp) ) } Row(modifier = Modifier.fillMaxWidth()) { IconButton( onClick = { stateHistory.undo() }, enabled = stateHistory.canUndo, modifier = Modifier.weight(1f) ) { Icon(Icons.Default.ArrowBack, contentDescription = "undo") } Button(onClick = { recording = !recording }) { Text(if (recording) "Stop recording" else "Start recording") } IconButton( onClick = { stateHistory.redo() }, enabled = stateHistory.canRedo, modifier = Modifier.weight(1f) ) { Icon(Icons.Default.ArrowForward, contentDescription = "redo") } } } } } ================================================ FILE: demo/src/main/java/com/zachklipp/statehistory/demo/ui/theme/Color.kt ================================================ package com.zachklipp.statehistory.demo.ui.theme import androidx.compose.ui.graphics.Color val Purple200 = Color(0xFFBB86FC) val Purple500 = Color(0xFF6200EE) val Purple700 = Color(0xFF3700B3) val Teal200 = Color(0xFF03DAC5) ================================================ FILE: demo/src/main/java/com/zachklipp/statehistory/demo/ui/theme/Shape.kt ================================================ package com.zachklipp.statehistory.demo.ui.theme import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material.Shapes import androidx.compose.ui.unit.dp val Shapes = Shapes( small = RoundedCornerShape(4.dp), medium = RoundedCornerShape(4.dp), large = RoundedCornerShape(0.dp) ) ================================================ FILE: demo/src/main/java/com/zachklipp/statehistory/demo/ui/theme/Theme.kt ================================================ package com.zachklipp.statehistory.demo.ui.theme import androidx.compose.foundation.isSystemInDarkTheme import androidx.compose.material.MaterialTheme import androidx.compose.material.darkColors import androidx.compose.material.lightColors import androidx.compose.runtime.Composable private val DarkColorPalette = darkColors( primary = Purple200, primaryVariant = Purple700, secondary = Teal200 ) private val LightColorPalette = lightColors( primary = Purple500, primaryVariant = Purple700, secondary = Teal200 /* Other default colors to override background = Color.White, surface = Color.White, onPrimary = Color.White, onSecondary = Color.Black, onBackground = Color.Black, onSurface = Color.Black, */ ) @Composable fun StateHistoryDemoTheme( darkTheme: Boolean = isSystemInDarkTheme(), content: @Composable () -> Unit ) { val colors = if (darkTheme) { DarkColorPalette } else { LightColorPalette } MaterialTheme( colors = colors, typography = Typography, shapes = Shapes, content = content ) } ================================================ FILE: demo/src/main/java/com/zachklipp/statehistory/demo/ui/theme/Type.kt ================================================ package com.zachklipp.statehistory.demo.ui.theme import androidx.compose.material.Typography import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.font.FontFamily import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.sp // Set of Material typography styles to start with val Typography = Typography( body1 = TextStyle( fontFamily = FontFamily.Default, fontWeight = FontWeight.Normal, fontSize = 16.sp ) /* Other default text styles to override button = TextStyle( fontFamily = FontFamily.Default, fontWeight = FontWeight.W500, fontSize = 14.sp ), caption = TextStyle( fontFamily = FontFamily.Default, fontWeight = FontWeight.Normal, fontSize = 12.sp ) */ ) ================================================ FILE: demo/src/main/res/drawable/ic_launcher_background.xml ================================================ ================================================ FILE: demo/src/main/res/drawable-v24/ic_launcher_foreground.xml ================================================ ================================================ FILE: demo/src/main/res/mipmap-anydpi-v26/ic_launcher.xml ================================================ ================================================ FILE: demo/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml ================================================ ================================================ FILE: demo/src/main/res/values/colors.xml ================================================ #FFBB86FC #FF6200EE #FF3700B3 #FF03DAC5 #FF018786 #FF000000 #FFFFFFFF ================================================ FILE: demo/src/main/res/values/strings.xml ================================================ State History Demo ================================================ FILE: demo/src/main/res/values/themes.xml ================================================ ================================================ FILE: demo/src/main/res/xml/backup_rules.xml ================================================ ================================================ FILE: demo/src/main/res/xml/data_extraction_rules.xml ================================================ ================================================ FILE: gradle/wrapper/gradle-wrapper.properties ================================================ #Fri Sep 16 16:06:11 PDT 2022 distributionBase=GRADLE_USER_HOME distributionUrl=https\://services.gradle.org/distributions/gradle-7.5-bin.zip distributionPath=wrapper/dists zipStorePath=wrapper/dists zipStoreBase=GRADLE_USER_HOME ================================================ FILE: gradle.properties ================================================ # Project-wide Gradle settings. # IDE (e.g. Android Studio) users: # Gradle settings configured through the IDE *will override* # any settings specified in this file. # For more details on how to configure your build environment visit # http://www.gradle.org/docs/current/userguide/build_environment.html # Specifies the JVM arguments used for the daemon process. # The setting is particularly useful for tweaking memory settings. org.gradle.jvmargs=-Xmx2048m -Dfile.encoding=UTF-8 # When configured, Gradle will run in incubating parallel mode. # This option should only be used with decoupled projects. More details, visit # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects # org.gradle.parallel=true # AndroidX package structure to make it clearer which packages are bundled with the # Android operating system, and which are packaged with your app's APK # https://developer.android.com/topic/libraries/support-library/androidx-rn android.useAndroidX=true # Kotlin code style for this project: "official" or "obsolete": kotlin.code.style=official # Enables namespacing of each library's R class so that its R class includes only the # resources declared in the library itself and none from the library's dependencies, # thereby reducing the size of the R class for that library android.nonTransitiveRClass=true ================================================ FILE: gradlew ================================================ #!/usr/bin/env sh # # Copyright 2015 the original author or 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 UN*X ## ############################################################################## # Attempt to set APP_HOME # Resolve links: $0 may be a link PRG="$0" # Need this for relative symlinks. while [ -h "$PRG" ] ; do ls=`ls -ld "$PRG"` link=`expr "$ls" : '.*-> \(.*\)$'` if expr "$link" : '/.*' > /dev/null; then PRG="$link" else PRG=`dirname "$PRG"`"/$link" fi done SAVED="`pwd`" cd "`dirname \"$PRG\"`/" >/dev/null APP_HOME="`pwd -P`" cd "$SAVED" >/dev/null APP_NAME="Gradle" APP_BASE_NAME=`basename "$0"` # 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"' # Use the maximum available, or set MAX_FD != -1 to use that value. MAX_FD="maximum" warn () { echo "$*" } die () { echo echo "$*" echo exit 1 } # 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 ;; 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" which java >/dev/null 2>&1 || 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 # Increase the maximum file descriptors if we can. if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then MAX_FD_LIMIT=`ulimit -H -n` if [ $? -eq 0 ] ; then if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then MAX_FD="$MAX_FD_LIMIT" fi ulimit -n $MAX_FD if [ $? -ne 0 ] ; then warn "Could not set maximum file descriptor limit: $MAX_FD" fi else warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" fi fi # For Darwin, add options to specify how the application appears in the dock if $darwin; then GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" fi # For Cygwin or MSYS, switch paths to Windows format before running java if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then APP_HOME=`cygpath --path --mixed "$APP_HOME"` CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` JAVACMD=`cygpath --unix "$JAVACMD"` # We build the pattern for arguments to be converted via cygpath ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` SEP="" for dir in $ROOTDIRSRAW ; do ROOTDIRS="$ROOTDIRS$SEP$dir" SEP="|" done OURCYGPATTERN="(^($ROOTDIRS))" # Add a user-defined pattern to the cygpath arguments if [ "$GRADLE_CYGPATTERN" != "" ] ; then OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" fi # Now convert the arguments - kludge to limit ourselves to /bin/sh i=0 for arg in "$@" ; do CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` else eval `echo args$i`="\"$arg\"" fi i=`expr $i + 1` done case $i in 0) set -- ;; 1) set -- "$args0" ;; 2) set -- "$args0" "$args1" ;; 3) set -- "$args0" "$args1" "$args2" ;; 4) set -- "$args0" "$args1" "$args2" "$args3" ;; 5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; 6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; 7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; 8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; 9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; esac fi # Escape application args save () { for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done echo " " } APP_ARGS=`save "$@"` # Collect all arguments for the java command, following the shell quoting and substitution rules eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" exec "$JAVACMD" "$@" ================================================ FILE: gradlew.bat ================================================ @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=. 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%" == "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%"=="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! if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 exit /b 1 :mainEnd if "%OS%"=="Windows_NT" endlocal :omega ================================================ FILE: settings.gradle ================================================ pluginManagement { repositories { google() mavenCentral() gradlePluginPortal() } } dependencyResolutionManagement { repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS) repositories { google() mavenCentral() } } rootProject.name = "State History" include ':demo' include ':statehistory' ================================================ FILE: statehistory/.gitignore ================================================ /build ================================================ FILE: statehistory/build.gradle ================================================ plugins { id 'com.android.library' id 'org.jetbrains.kotlin.android' id 'com.vanniktech.maven.publish' } android { namespace 'com.zachklipp.statehistory' compileSdk 33 defaultConfig { minSdk 21 targetSdk 33 versionCode 1 versionName "1.0" testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro' } } compileOptions { sourceCompatibility JavaVersion.VERSION_1_8 targetCompatibility JavaVersion.VERSION_1_8 } kotlinOptions { jvmTarget = '1.8' } buildFeatures { compose true } composeOptions { kotlinCompilerExtensionVersion '1.3.1' } packagingOptions { resources { excludes += '/META-INF/{AL2.0,LGPL2.1}' } } } dependencies { api "androidx.compose.runtime:runtime:$compose_ui_version" testImplementation 'junit:junit:4.13.2' testImplementation 'com.google.truth:truth:1.1.3' androidTestImplementation 'androidx.test.ext:junit:1.1.3' androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0' androidTestImplementation "androidx.compose.ui:ui-test-junit4:$compose_ui_version" androidTestImplementation 'com.google.truth:truth:1.1.3' debugImplementation "androidx.compose.ui:ui-tooling:$compose_ui_version" debugImplementation "androidx.compose.ui:ui-test-manifest:$compose_ui_version" } ================================================ FILE: statehistory/gradle.properties ================================================ SONATYPE_HOST=DEFAULT RELEASE_SIGNING_ENABLED=true GROUP=com.zachklipp.compose-undo POM_ARTIFACT_ID=statehistory VERSION_NAME=0.2.0 POM_NAME=Compose Undo State History POM_DESCRIPTION=Undo snapshot state changes in Compose. POM_INCEPTION_YEAR=2022 POM_URL=https://github.com/zach-klippenstein/compose-undo/ POM_LICENSE_NAME=The Apache Software License, Version 2.0 POM_LICENSE_URL=https://www.apache.org/licenses/LICENSE-2.0.txt POM_LICENSE_DIST=repo POM_SCM_URL=https://github.com/zach-klippenstein/compose-undo/ POM_SCM_CONNECTION=scm:git:git://github.com/zach-klippenstein/compose-undo.git POM_SCM_DEV_CONNECTION=scm:git:ssh://git@github.com/zach-klippenstein/compose-undo.git POM_DEVELOPER_ID=zachklipp POM_DEVELOPER_NAME=Zach Klippenstein POM_DEVELOPER_URL=https://github.com/zach-klippenstein/ ================================================ FILE: statehistory/proguard-rules.pro ================================================ # Add project specific ProGuard rules here. # You can control the set of applied configuration files using the # proguardFiles setting in build.gradle. # # For more details, see # http://developer.android.com/guide/developing/tools/proguard.html # If your project uses WebView with JS, uncomment the following # and specify the fully qualified class name to the JavaScript interface # class: #-keepclassmembers class fqcn.of.javascript.interface.for.webview { # public *; #} # Uncomment this to preserve the line number information for # debugging stack traces. #-keepattributes SourceFile,LineNumberTable # If you keep the line number information, uncomment this to # hide the original source file name. #-renamesourcefileattribute SourceFile ================================================ FILE: statehistory/src/androidTest/java/com/zachklipp/statehistory/demo/StateHistoryTest.kt ================================================ package com.zachklipp.statehistory.demo import androidx.compose.runtime.mutableStateOf import androidx.compose.ui.test.junit4.createComposeRule import androidx.test.ext.junit.runners.AndroidJUnit4 import com.google.common.truth.Truth.assertThat import com.zachklipp.statehistory.StateHistory import com.zachklipp.statehistory.WithStateHistory import com.zachklipp.statehistory.trackStateHistory import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith @RunWith(AndroidJUnit4::class) class StateHistoryTest { @get:Rule val rule = createComposeRule() @Test fun withStateHistory_recordsChanges() { val state = mutableStateOf(0) lateinit var stateHistory: StateHistory rule.setContent { WithStateHistory { stateHistory = it state.trackStateHistory() } } rule.runOnIdle { assertThat(stateHistory.frameCount).isEqualTo(0) state.value = 1 } rule.runOnIdle { assertThat(stateHistory.frameCount).isEqualTo(1) } } } ================================================ FILE: statehistory/src/main/AndroidManifest.xml ================================================ ================================================ FILE: statehistory/src/main/java/com/zachklipp/statehistory/StateHistory.kt ================================================ package com.zachklipp.statehistory import androidx.compose.runtime.* import androidx.compose.runtime.collection.mutableVectorOf import androidx.compose.runtime.snapshots.* import kotlinx.coroutines.awaitCancellation import java.util.* import kotlin.contracts.ExperimentalContracts import kotlin.contracts.contract private const val DEBUG = true private const val TAG = "StateHistory" val LocalStateHistory: ProvidableCompositionLocal = staticCompositionLocalOf { null } /** * Convenience function for simple usage of [StateHistory]. * * Inside [content], call [MutableState.trackStateHistory], [SnapshotStateList.trackStateHistory], * and [SnapshotStateMap.trackStateHistory] to register state objects for change tracking, or pass * them to [StateHistory.startTrackingState]. Then use the [StateHistory.undo], [StateHistory.redo], * and [StateHistory.setCurrentFrameGlobally] methods to restore state. */ @Composable fun WithStateHistory(content: @Composable (StateHistory) -> Unit) { val stateHistory = remember { StateHistory() } LaunchedEffect(stateHistory) { stateHistory.recordChanges { stateHistory.saveFrame() } } CompositionLocalProvider(LocalStateHistory provides stateHistory) { content(stateHistory) } } /** * Records changes to state objects that are registered via [startTrackingState] (or * [trackStateHistory]) and allows restoring state to previous values. * * ## Usage * * ### Simple * * 1. Wrap your composition in [WithStateHistory]. * 2. Call [MutableState.trackStateHistory] on the states you want to track. (See also * [SnapshotStateList.trackStateHistory], [SnapshotStateMap.trackStateHistory].) * 3. Call [StateHistory.undo] to undo changes. * * ### Advanced * * 1. Create an instance of this that will live across recompositions (e.g. use remember or store * near the top of your DI object graph). * 1. Provide the instance to your composition through the [LocalStateHistory] composition local. * 1. Call [recordChanges] from a coroutine to start recording changes. To save a new history frame * every time some state changes are applied, pass a callback that calls [saveFrame]. * 1. Register states you want to track with [startTrackingState]. Make sure to call * [stopTrackingState] when finished with the state object to allow it to be garbage-collected. * If creating the state directly in a composition (e.g. with [remember]), you can also pass the * state object to [trackStateHistory] to automatically stop tracking it when it leaves the * composition. * 1. Call [setCurrentFrameGlobally] to restore the state of all tracked objects to the states they * had at the given frame, or call the convenience methods [undo]/[redo] to move the frame by one. * * ## Defining save points * * History frames will only be pushed onto the stack when [safeFrame] is called. You can call this * method whenever you want, so the granularity of the history is up to you. To get the most detail, * call it from the [recordChanges] callback, which will be invoked every time a snapshot is applied * to the global snapshot that changes one or more tracked state objects. If that's too much detail * for your use case, you can pass a null callback to [recordChanges] and call [saveFrame] only * whenever something significant happens in your app, at regular intervals with a timer, etc. * * **Key point: State changes from a single snapshot will always be saved to the same frame.** * * @sample WithStateHistory */ @Stable class StateHistory { /** * Used to guard access to [frames], [trackedStates], and [nextFrame]. */ private val lock = Any() /** * The set of all state objects we're currently tracking via [startTrackingState]. */ private val trackedStates = WeakHashMap() private var handle: ObserverHandle? = null /** * By storing and restoring [StateRecord]s directly, we don't have to care what types the state * objects are or even what data they hold. The records already implement all the operations * we need. */ private val frames = mutableVectorOf>() /** * We "start" recording the next frame as soon as the previous one is committed to the [frames] * list. This way we can eagerly record the initial value of newly-tracked objects from * [startTrackingState] so that their initial values will be saved on the next frame, even if * they're not recorded as changed. Maybe unnecessary? */ private var nextFrame = WeakHashMap() private var onTrackStateApplied: (() -> Unit)? = null /** * The total number of history frames that have been recorded. */ var frameCount: Int by mutableStateOf(0) private set /** * The index of frame that represents the current state. When the global snapshot is advanced * with changes to tracked state, this value will be incremented. It can also be set to a lower * value by calling [setCurrentFrameGlobally]. */ var currentFrame: Int by mutableStateOf(NoFrame) private set /** * Starts recording changes and suspends until cancelled. * * @param onTrackStateApplied Called every time a snapshot is applied to the global snapshot * that changes any of the state objects tracked via [startTrackingState]. Call [saveFrame] from * this callback to save every change to the history. */ suspend fun recordChanges(onTrackStateApplied: (() -> Unit)? = null) { if (!startRecording(onTrackStateApplied)) return try { awaitCancellation() } finally { stopRecording(clearOnTrackStateApplied = true) } } /** * Saves any changes to tracked state objects since the last call to this method to the history. * * If [currentFrame] is not the last frame, any frames after it will be removed. */ fun saveFrame() { // Take the lock outside the snapshot so // This won't conflict with the lock in the apply observer when the snapshot is applied // because the none of the states changed in this snapshot are tracked. synchronized(lock) { withGlobalMutableSnapshot { if (DEBUG) println("[$TAG] Recording frame ${currentFrame + 1}: $nextFrame") // If committing a new frame while peeking into the history, clear the // frames after this point and start recording fresh. if (frames.lastIndex > currentFrame) { frames.removeRange(currentFrame + 1, frames.size) } frames += nextFrame nextFrame = WeakHashMap() frameCount = frames.size currentFrame = frames.lastIndex } } } /** * Starts tracking changes [stateObject]. The current value of the object will be recorded in * the next frame, i.e. the next time the global snapshot is applied while * [recording][startRecording]. * * Calling [stopTrackingState] after this method is optional. If it's not called, the history * for the state object will be cleaned up when it's garbage collected. * * @param stateObject Must be a snapshot state object, such as a [MutableState], * [SnapshotStateList], etc. The concrete object must implement [StateObject]. */ fun startTrackingState(stateObject: S) { ensureValidStateObject(stateObject) if (stateObject in trackedStates) return // Record the initial state of the object in the next frame to be committed. val initialRecord = stateObject.copyCurrentRecord() synchronized(lock) { trackedStates[stateObject] = Unit nextFrame[stateObject] = initialRecord } if (DEBUG) println( "[$TAG] Starting to track object $stateObject with initial record $initialRecord" ) } /** * Stops tracking changes to [stateObject]. * * Calling this method after [startTrackingState] is optional. If it's not called, the history * for the state object will be cleaned up when it's garbage collected. */ fun stopTrackingState(stateObject: Any) { stateObject as StateObject if (DEBUG) println("[$TAG] Stopping tracking object $stateObject") synchronized(lock) { trackedStates -= stateObject nextFrame -= stateObject // Remove all references to the state object from the history so it can be GC'd. // TODO Figure out a way to do this without iterating through the entire history. // WeakRefs? frames.forEach { it -= stateObject } } } /** * Restores the values of all tracked state objects to the values they had at the frame at * [frameIndex]. Calling this method will not change [frameCount] immediately, although the next * time a tracked state is changed and applied to the global snapshot, all frames between * [currentFrame] and [frameCount] will be removed and replaced with a new frame. * * The [frameIndex] will be coerced into the valid frame range, and this function will do * nothing if equal to [currentFrame]. */ fun setCurrentFrameGlobally(frameIndex: Int) { if (frameIndex == currentFrame) return // Stop recording so we don't record the application of the mutable snapshot below as a // new frame. Use the return value instead of isRecording to avoid a race. // Don't clear the callback so we can re-use it after. val wasRecording = stopRecording(clearOnTrackStateApplied = false) if (DEBUG) println( "[$TAG] Pausing recording to set current frame (wasRecording=$wasRecording)" ) // Peeking in non-global snapshots is not currently supported. synchronized(lock) { withGlobalMutableSnapshot { @Suppress("NAME_SHADOWING") val frameIndex = frameIndex.coerceIn(0, frames.lastIndex) if (DEBUG) println("[$TAG] Setting current frame to $frameIndex") // Check again after coercing. if (frameIndex == currentFrame) return currentFrame = frameIndex trackedStates.forEach { (stateObject, _) -> // Find the latest frame containing the state object, if any. var readFrameIndex = frameIndex while (readFrameIndex >= 0 && stateObject !in frames[readFrameIndex]) { readFrameIndex-- } if (readFrameIndex >= 0) { val frame = frames[readFrameIndex] val record = frame.getValue(stateObject) if (DEBUG) println("[$TAG] Restoring $stateObject to $record") stateObject.restoreFrom(record) } else if (DEBUG) { println("[$TAG] Couldn't find value for $stateObject in history") } } // When the mutableSnapshot is applied, we'll synchronously get an apply // observer callback - or we would, if we hadn't stopped recording. After that, // it's safe to stop recording again. } } if (wasRecording) { if (DEBUG) println("[$TAG] Resuming recording after setting current frame") // Keep using the old callback. startRecording(onTrackStateApplied) } } /** * Starts recording state changes. This is a no-op if recording has already been started. * * @return True if recording was successfully started, false if already recording. */ private fun startRecording(onTrackStateApplied: (() -> Unit)?): Boolean { if (handle != null) { if (DEBUG) println("[$TAG] Recording already started, ignoring start request") return false } if (DEBUG) println("[$TAG] Starting recording") synchronized(lock) { if (handle != null) return false this.onTrackStateApplied = onTrackStateApplied handle = Snapshot.registerApplyObserver(this::onApply) return true } } /** * Stops recording state changes. * * @return True if recording was stopped, false if it was not started. */ private fun stopRecording(clearOnTrackStateApplied: Boolean): Boolean { if (DEBUG) println("[$TAG] Stopping recording") if (handle == null) return false synchronized(lock) { if (handle == null) return false handle!!.dispose() handle = null if (clearOnTrackStateApplied) { onTrackStateApplied = null } return true } } private fun onApply(changedStates: Set, snapshot: Snapshot) { var atLeastOneTrackedStateChanged = false // Read values inside the snapshot to avoid race conditions. snapshot.withNestedSnapshot { synchronized(lock) { changedStates.forEach { stateObject -> stateObject as StateObject if (stateObject in trackedStates) { atLeastOneTrackedStateChanged = true nextFrame[stateObject] = stateObject.copyCurrentRecord() } } } } if (atLeastOneTrackedStateChanged) { if (DEBUG) println("[$TAG] Tracked state changes were applied, invoking callback") onTrackStateApplied?.invoke() } } private inline fun withGlobalMutableSnapshot(block: () -> Unit) { Snapshot.global { Snapshot.withMutableSnapshot(block) } } private inline fun Snapshot.withNestedSnapshot(block: () -> Unit) { takeNestedSnapshot().run { try { enter(block) } finally { dispose() } } } /** * Returns a copy of this object's current readable record, without recording a read. The record * is a copy since the original record could be reused at any point in the future. */ private fun StateObject.copyCurrentRecord(): StateRecord { val newRecord = firstStateRecord.create() firstStateRecord.withCurrent { current -> newRecord.assign(current) } return newRecord } /** * Copies [record] into the write record for this state object in the current snapshot. */ private fun StateObject.restoreFrom(record: StateRecord) { firstStateRecord.writable(this) { assign(record) } } companion object { const val NoFrame: Int = -1 } } @Composable fun trackStateHistory(stateObject: S): S { ensureValidStateObject(stateObject) val stateHistory = LocalStateHistory.current ?: return stateObject DisposableEffect(stateHistory, stateObject) { stateHistory.startTrackingState(stateObject) onDispose { stateHistory.stopTrackingState(stateObject) } } return stateObject } val StateHistory.canUndo: Boolean get() = currentFrame > 0 val StateHistory.canRedo: Boolean get() = currentFrame < frameCount - 1 /** * Sets the current frame to the previous frame. */ fun StateHistory.undo() { setCurrentFrameGlobally(currentFrame - 1) } /** * Sets the current frame to the next frame. */ fun StateHistory.redo() { setCurrentFrameGlobally(currentFrame + 1) } @Suppress("NOTHING_TO_INLINE") @Composable inline fun MutableState.trackStateHistory(): MutableState = trackStateHistory(this) @Suppress("NOTHING_TO_INLINE") @Composable inline fun SnapshotStateList.trackStateHistory(): SnapshotStateList = trackStateHistory(this) @Suppress("NOTHING_TO_INLINE") @Composable inline fun SnapshotStateMap.trackStateHistory(): SnapshotStateMap = trackStateHistory(this) @OptIn(ExperimentalContracts::class) private fun ensureValidStateObject(stateObject: Any) { contract { returns() implies (stateObject is StateObject) } require(stateObject is StateObject) { "Can only track objects that are instance of StateObject, which this is not: $stateObject" } } ================================================ FILE: statehistory/src/test/java/com/zachklipp/statehistory/demo/StateHistoryTest.kt ================================================ package com.zachklipp.statehistory.demo import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.snapshots.Snapshot import com.google.common.truth.Truth.assertThat import com.zachklipp.statehistory.StateHistory import com.zachklipp.statehistory.redo import com.zachklipp.statehistory.undo import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.cancel import kotlinx.coroutines.launch import org.junit.After import org.junit.Test class StateHistoryTest { private val stateHistory = StateHistory() private val scope = CoroutineScope(Dispatchers.Unconfined) @After fun tearDown() { scope.cancel() } @Test fun initialFrameCount() { assertThat(stateHistory.frameCount).isEqualTo(0) } @Test fun initialCurrentFrame() { assertThat(stateHistory.currentFrame).isEqualTo(StateHistory.NoFrame) } @Test fun recordsChanges_whenStartTrackingAfterRecording() { scope.launch { stateHistory.recordChanges { stateHistory.saveFrame() } } val state = mutableStateOf(0) stateHistory.startTrackingState(state) assertThat(stateHistory.frameCount).isEqualTo(0) Snapshot.sendApplyNotifications() assertThat(stateHistory.frameCount).isEqualTo(0) Snapshot.withMutableSnapshot { state.value = 1 } assertThat(stateHistory.frameCount).isEqualTo(1) assertThat(stateHistory.currentFrame).isEqualTo(0) } @Test fun recordsChanges_whenStartRecordingAfterTracking() { val state = mutableStateOf(0) stateHistory.startTrackingState(state) assertThat(stateHistory.frameCount).isEqualTo(0) Snapshot.sendApplyNotifications() assertThat(stateHistory.frameCount).isEqualTo(0) scope.launch { stateHistory.recordChanges { stateHistory.saveFrame() } } Snapshot.withMutableSnapshot { state.value = 1 } assertThat(stateHistory.frameCount).isEqualTo(1) assertThat(stateHistory.currentFrame).isEqualTo(0) } @Test fun noops_whenChangeCallbackIsNull() { scope.launch { stateHistory.recordChanges() } val state = mutableStateOf(0) stateHistory.startTrackingState(state) Snapshot.withMutableSnapshot { state.value = 1 } assertThat(stateHistory.frameCount).isEqualTo(0) assertThat(stateHistory.currentFrame).isEqualTo(StateHistory.NoFrame) } @Test fun setCurrentFrameGlobally_restoresState() { scope.launch { stateHistory.recordChanges { stateHistory.saveFrame() } } val state = mutableStateOf(0) stateHistory.startTrackingState(state) Snapshot.withMutableSnapshot { state.value = 1 } Snapshot.withMutableSnapshot { state.value = 2 } assertThat(stateHistory.frameCount).isEqualTo(2) assertThat(stateHistory.currentFrame).isEqualTo(1) assertThat(state.value).isEqualTo(2) stateHistory.setCurrentFrameGlobally(0) assertThat(stateHistory.frameCount).isEqualTo(2) assertThat(stateHistory.currentFrame).isEqualTo(0) assertThat(state.value).isEqualTo(1) } @Test fun settingState_afterUndo_clearsPreviousFutureState() { scope.launch { stateHistory.recordChanges { stateHistory.saveFrame() } } val state = mutableStateOf(0) stateHistory.startTrackingState(state) Snapshot.withMutableSnapshot { state.value = 1 } Snapshot.withMutableSnapshot { state.value = 2 } assertThat(stateHistory.frameCount).isEqualTo(2) assertThat(stateHistory.currentFrame).isEqualTo(1) assertThat(state.value).isEqualTo(2) // Undo one and change the value. stateHistory.setCurrentFrameGlobally(0) Snapshot.withMutableSnapshot { state.value = 3 } // That should have overwritten the previous frame in which state was 2. assertThat(stateHistory.frameCount).isEqualTo(2) assertThat(stateHistory.currentFrame).isEqualTo(1) assertThat(state.value).isEqualTo(3) // But preserve the frame where state is 1. stateHistory.setCurrentFrameGlobally(0) assertThat(stateHistory.frameCount).isEqualTo(2) assertThat(stateHistory.currentFrame).isEqualTo(0) assertThat(state.value).isEqualTo(1) } @Test fun tracksMultipleStateChanges() { scope.launch { stateHistory.recordChanges { stateHistory.saveFrame() } } val state1 = mutableStateOf(0) stateHistory.startTrackingState(state1) Snapshot.withMutableSnapshot { state1.value = 1 } assertThat(stateHistory.frameCount).isEqualTo(1) val state2 = mutableStateOf(10) stateHistory.startTrackingState(state2) Snapshot.withMutableSnapshot { state2.value = 20 } assertThat(stateHistory.frameCount).isEqualTo(2) } @Test fun restoresMultipleStateChanges() { scope.launch { stateHistory.recordChanges { stateHistory.saveFrame() } } val state1 = mutableStateOf(0) stateHistory.startTrackingState(state1) Snapshot.withMutableSnapshot { state1.value = 1 } val state2 = mutableStateOf(0) stateHistory.startTrackingState(state2) Snapshot.withMutableSnapshot { state2.value = 10 } Snapshot.withMutableSnapshot { state2.value = 20 } // Add a frame where both are set at once. Snapshot.withMutableSnapshot { state1.value = 2 state2.value = 30 } stateHistory.undo() assertThat(state1.value).isEqualTo(1) assertThat(state2.value).isEqualTo(20) stateHistory.undo() assertThat(state1.value).isEqualTo(1) assertThat(state2.value).isEqualTo(10) stateHistory.redo() assertThat(state1.value).isEqualTo(1) assertThat(state2.value).isEqualTo(20) } @Test fun stopTracking_whenStateObjectUnregistered() { scope.launch { stateHistory.recordChanges { stateHistory.saveFrame() } } val state = mutableStateOf(0) stateHistory.startTrackingState(state) Snapshot.withMutableSnapshot { state.value = 1 } assertThat(stateHistory.frameCount).isEqualTo(1) assertThat(stateHistory.currentFrame).isEqualTo(0) stateHistory.stopTrackingState(state) Snapshot.withMutableSnapshot { state.value = 2 } assertThat(stateHistory.frameCount).isEqualTo(1) assertThat(stateHistory.currentFrame).isEqualTo(0) } @Test fun stopTracking_whenRecordingStopped() { val job = scope.launch { stateHistory.recordChanges { stateHistory.saveFrame() } } val state = mutableStateOf(0) stateHistory.startTrackingState(state) Snapshot.withMutableSnapshot { state.value = 1 } assertThat(stateHistory.frameCount).isEqualTo(1) assertThat(stateHistory.currentFrame).isEqualTo(0) job.cancel() Snapshot.withMutableSnapshot { state.value = 2 } assertThat(stateHistory.frameCount).isEqualTo(1) assertThat(stateHistory.currentFrame).isEqualTo(0) } }