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