diff --git a/.github/ISSUE_TEMPLATE.md b/.github/ISSUE_TEMPLATE.md new file mode 100644 index 0000000..3c52212 --- /dev/null +++ b/.github/ISSUE_TEMPLATE.md @@ -0,0 +1,16 @@ +## Expected Behavior + + +## Actual Behavior + + +## Steps to Reproduce the Problem + +1. +1. +1. + +## Specifications + +- Version: +- Platform: \ No newline at end of file diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md new file mode 100644 index 0000000..0787bd9 --- /dev/null +++ b/.github/PULL_REQUEST_TEMPLATE.md @@ -0,0 +1,6 @@ +Fixes # + +> It's a good idea to open an issue first for discussion. + +- [ ] Tests pass +- [ ] Appropriate changes to README are included in PR \ No newline at end of file diff --git a/.github/workflows/android.yml b/.github/workflows/android.yml new file mode 100644 index 0000000..4d64e1f --- /dev/null +++ b/.github/workflows/android.yml @@ -0,0 +1,21 @@ +name: Android CI + +on: [push] + +jobs: + build: + + runs-on: ubuntu-latest + + steps: + - name: Check out repository + uses: actions/checkout@v3 + with: + submodules: true + - name: Set up JDK 17 + uses: actions/setup-java@v3 + with: + distribution: 'temurin' + java-version: '17' + - name: Build with Gradle + run: ./gradlew assembleDebug lintVitalRelease diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..c8c9acc --- /dev/null +++ b/.gitignore @@ -0,0 +1,7 @@ +/.gradle/ +/.idea/ +/build/ +/captures/ +/local.properties +.DS_Store +*.iml diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..d645695 --- /dev/null +++ b/LICENSE @@ -0,0 +1,202 @@ + + 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. diff --git a/README.md b/README.md new file mode 100644 index 0000000..168424e --- /dev/null +++ b/README.md @@ -0,0 +1,117 @@ +# Compose Preference + +[![Android CI status](https://github.com/zhanghai/ComposePreference/workflows/Android%20CI/badge.svg)](https://github.com/zhanghai/ComposePreference/actions) + +[Preference](https://developer.android.com/develop/ui/views/components/settings) implementation for [Jetpack Compose](https://developer.android.com/jetpack/compose) [Material 3](https://developer.android.com/jetpack/compose/designsystems/material3). + +This is not an officially supported Google product. + +## Preview + +

+ +## Integration + +Gradle: + +```gradle +implementation 'me.zhanghai.compose.preference:library:1.0.0' +``` + +## Design + +There is no official and complete Material 3 UX specification for preference yet, so the UX design of this library mainly comes from the following sources: + +- [Material Design 3](https://m3.material.io/) +- [Material Design 2 Android Settings](https://m2.material.io/design/platform-guidance/android-settings.html) +- [Android settings design guidelines](https://source.android.com/docs/core/settings/settings-guidelines) +- [AndroidX Preference](https://developer.android.com/jetpack/androidx/releases/preference) +- [AOSP Settings](https://android.googlesource.com/platform/packages/apps/Settings/+/refs/heads/main/) + +## Usage + +This library is designed with both extensibility and ease-of-use in mind. + +Basic usage of this library involves invoking the `ProvidePreferenceLocals` composable, and then calling the `*Preference` helper functions in a `LazyColumn` composable: + +```kotlin +AppTheme { + ProvidePreferenceLocals { + // Other composables wrapping the LazyColumn ... + LazyColumn(modifier = Modifier.fillMaxSize()) { + switchPreference( + key = "switch_preference", + defaultValue = false, + title = { Text(text = "Switch preference") }, + summary = { Text(text = if (it) "On" else "Off") } + ) + } + } +} +``` + +### Prefences + +Built-in types of preferences include: + +- [`Preference`](library/src/main/java/me/zhanghai/compose/preference/Preference.kt) +- [`PreferenceCategory`](library/src/main/java/me/zhanghai/compose/preference/PreferenceCategory.kt) +- [`CheckboxPreference`](library/src/main/java/me/zhanghai/compose/preference/CheckboxPreference.kt) +- [`FooterPreference`](library/src/main/java/me/zhanghai/compose/preference/FooterPreference.kt) +- [`ListPreference`](library/src/main/java/me/zhanghai/compose/preference/ListPreference.kt) (supports both alert dialog and dropdown menu) +- [`MultiSelectListPreference`](library/src/main/java/me/zhanghai/compose/preference/MultiSelectListPreference.kt) +- [`RadioButtonPreference`](library/src/main/java/me/zhanghai/compose/preference/RadioButtonPreference.kt) +- [`SliderPreference`](library/src/main/java/me/zhanghai/compose/preference/SliderPreference.kt) +- [`SwitchPreference`](library/src/main/java/me/zhanghai/compose/preference/SwitchPreference.kt) +- [`TextFieldPreference`](library/src/main/java/me/zhanghai/compose/preference/TextFieldPreference.kt) +- [`TwoTargetIconButtonPreference`](library/src/main/java/me/zhanghai/compose/preference/TwoTargetIconButtonPreference.kt) +- [`TwoTargetSwitchPreference`](library/src/main/java/me/zhanghai/compose/preference/TwoTargetSwitchPreference.kt) + +Each type of built-in preference includes 3 kinds of APIs: + +1. A `LazyListScope.*Preference` extension function, which is the easiest way to use preferences in this library, and helps developers to avoid boilerplates like having to specify the key twice for the `LazyColumn` and the `Preference`. +2. A `*Preference` composable that takes a `MutableState`, which allows developers to bring in any kind of state they currently have. +3. A `*Preference` composable that takes `value` and `onValueChange`, which allows developers to use the preference without a state and even in non-preference scenarios. + +### Theming + +The visual appearance of the preferences can be customized by providing a custom [`PreferenceTheme`](library/src/main/java/me/zhanghai/compose/preference/PreferenceTheme.kt) with `preferenceTheme` to `ProvidePreferenceLocals` or `ProvidePreferenceTheme`. + +Customizable values in the theme include most dimensions, colors and text styles used by the built-in preferences. + +### Data source + +The data source of the preferences can be customized by providing a custom `MutableStateFlow` to `ProvidePreferenceLocals` or `ProvidePreferenceFlow`. + +The [`Preferences`](library/src/main/java/me/zhanghai/compose/preference/Preferences.kt) interface defined in this library is similar to the AndroidX DataStore [`Preferences`](https://developer.android.com/reference/kotlin/androidx/datastore/preferences/core/Preferences) class, but: + +- It can be implemented by other mechanisms like [`SharedPreferences`](https://developer.android.com/reference/android/content/SharedPreferences), thanks to being a public interface instead of an abstract class with only an internal constructor. +- It doesn't have to be produced and updated via a [`DataStore`](https://developer.android.com/reference/kotlin/androidx/datastore/core/DataStore). +- It doesn't mandate a fixed set of types that an implementation has to support, so that implementations have the flexibility to support much more or less types. The implementations within this library will always support the types supported by `SharedPreferences` (the same as AndroidX DataStore). + +The default data source provided by this library (`defaultPreferenceFlow`) is implemented with `SharedPreferences`, because: + +- `SharedPreferences` is available as part of the Android framework, and doesn't require external dependencies like AndroidX DataStore which [bundles its own copy of `protobuf-lite`](https://cs.android.com/androidx/platform/frameworks/support/+/androidx-main:datastore/datastore-preferences-core/build.gradle;l=108;drc=9fd0cda7bb963d41fd25645b0761776caa830ed7). +- `SharedPreferences` can actually be [10x faster](https://stackoverflow.com/q/71601343) than AndroidX DataStore, likely due to its existing optimizations and simple threading and persistence model (XML is simple enough to be faster than Protobuf). +- `SharedPreferences` has a synchronous API, but it is actually async except for the first (un-cached) read, and allows in-memory value change without waiting for the disk write to complete, which is good for the preference use case. +- Existing users of `SharedPreferences` can use this library directly with the default data source. + +There should only be at most one instance of `defaultPreferenceFlow`, similar to `DataStore` in AndroidX DataStore. It is also only for usage within a single process due to being backed by `SharedPreferences`. + +If AndroidX DataStore is considered more appropriate for your use case, e.g. you are working on a [Compose Multiplatform](https://www.jetbrains.com/lp/compose-multiplatform/) project or you need multi-process support, you can also easily use a AndroidX DataStore backed implementation that provides a `MutableStateFlow`. + +## License + + Copyright 2023 Google LLC + + 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. diff --git a/build.gradle.kts b/build.gradle.kts new file mode 100644 index 0000000..cc06ad1 --- /dev/null +++ b/build.gradle.kts @@ -0,0 +1,24 @@ +/* + * Copyright 2023 Google LLC + * + * 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. + */ + +// Top-level build file where you can add configuration options common to all sub-projects/modules. +plugins { + val androidGradlePluginVersion = "8.2.0" + id("com.android.application") version androidGradlePluginVersion apply false + id("com.android.library") version androidGradlePluginVersion apply false + kotlin("android") version "1.9.20" apply false + id("com.vanniktech.maven.publish") version "0.25.3" apply false +} diff --git a/docs/contributing.md b/docs/contributing.md new file mode 100644 index 0000000..654a071 --- /dev/null +++ b/docs/contributing.md @@ -0,0 +1,28 @@ +# How to Contribute + +We'd love to accept your patches and contributions to this project. There are +just a few small guidelines you need to follow. + +## Contributor License Agreement + +Contributions to this project must be accompanied by a Contributor License +Agreement. You (or your employer) retain the copyright to your contribution; +this simply gives us permission to use and redistribute your contributions as +part of the project. Head over to to see +your current agreements on file or to sign a new one. + +You generally only need to submit a CLA once, so if you've already submitted one +(even if it was for a different project), you probably don't need to do it +again. + +## Code reviews + +All submissions, including submissions by project members, require review. We +use GitHub pull requests for this purpose. Consult +[GitHub Help](https://help.github.com/articles/about-pull-requests/) for more +information on using pull requests. + +## Community Guidelines + +This project follows [Google's Open Source Community +Guidelines](https://opensource.google/conduct/). diff --git a/fastlane/metadata/android/en-US/changelogs/1.txt b/fastlane/metadata/android/en-US/changelogs/1.txt new file mode 100644 index 0000000..0b4c33a --- /dev/null +++ b/fastlane/metadata/android/en-US/changelogs/1.txt @@ -0,0 +1 @@ +- Initial release. diff --git a/fastlane/metadata/android/en-US/images/phoneScreenshots/1.png b/fastlane/metadata/android/en-US/images/phoneScreenshots/1.png new file mode 100644 index 0000000..2a3a0fb Binary files /dev/null and b/fastlane/metadata/android/en-US/images/phoneScreenshots/1.png differ diff --git a/fastlane/metadata/android/en-US/images/phoneScreenshots/2.png b/fastlane/metadata/android/en-US/images/phoneScreenshots/2.png new file mode 100644 index 0000000..1f414f0 Binary files /dev/null and b/fastlane/metadata/android/en-US/images/phoneScreenshots/2.png differ diff --git a/gradle.properties b/gradle.properties new file mode 100644 index 0000000..9126f52 --- /dev/null +++ b/gradle.properties @@ -0,0 +1,45 @@ +# 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 + +SONATYPE_HOST=DEFAULT +RELEASE_SIGNING_ENABLED=true + +GROUP=me.zhanghai.compose.preference +VERSION_NAME=1.0.0 +VERSION_CODE=1 + +POM_DESCRIPTION=Compose Preference library +POM_URL=https://github.com/zhanghai/ComposePreference +POM_INCEPTION_YEAR=2023 +POM_LICENCE_NAME=The Apache Software License, Version 2.0 +POM_LICENCE_URL=http://www.apache.org/licenses/LICENSE-2.0.txt +POM_LICENCE_DIST=repo +POM_DEVELOPER_ID=zhanghai +POM_DEVELOPER_NAME=Hai Zhang +POM_DEVELOPER_URL=https://github.com/zhanghai +POM_SCM_CONNECTION=scm:git@github.com:zhanghai/ComposePreference.git +POM_SCM_DEV_CONNECTION=scm:git@github.com:zhanghai/ComposePreference.git +POM_SCM_URL=https://github.com/zhanghai/ComposePreference diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..e708b1c Binary files /dev/null and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..90b3349 --- /dev/null +++ b/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,6 @@ +#Thu Sep 23 01:27:10 PDT 2021 +distributionBase=GRADLE_USER_HOME +distributionUrl=https\://services.gradle.org/distributions/gradle-8.2-all.zip +distributionPath=wrapper/dists +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew new file mode 100755 index 0000000..4f906e0 --- /dev/null +++ b/gradlew @@ -0,0 +1,185 @@ +#!/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" "$@" diff --git a/gradlew.bat b/gradlew.bat new file mode 100644 index 0000000..ac1b06f --- /dev/null +++ b/gradlew.bat @@ -0,0 +1,89 @@ +@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 diff --git a/library/.gitignore b/library/.gitignore new file mode 100644 index 0000000..dda6bfc --- /dev/null +++ b/library/.gitignore @@ -0,0 +1,3 @@ +/.cxx/ +/build/ +/out/ diff --git a/library/build.gradle.kts b/library/build.gradle.kts new file mode 100644 index 0000000..3d11cab --- /dev/null +++ b/library/build.gradle.kts @@ -0,0 +1,55 @@ +/* + * Copyright 2023 Google LLC + * + * 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. + */ + +plugins { + id("com.android.library") + kotlin("android") + id("com.vanniktech.maven.publish") +} + +android { + namespace = "me.zhanghai.compose.preference" + buildToolsVersion = "34.0.0" + compileSdk = 34 + defaultConfig { + minSdk = 21 + consumerProguardFiles("proguard-rules.pro") + } + compileOptions { + sourceCompatibility = JavaVersion.VERSION_1_8 + targetCompatibility = JavaVersion.VERSION_1_8 + } + kotlinOptions { jvmTarget = JavaVersion.VERSION_1_8.toString() } + buildFeatures { compose = true } + composeOptions { kotlinCompilerExtensionVersion = "1.5.5" } + packaging { resources { excludes += "/META-INF/{AL2.0,LGPL2.1}" } } + buildTypes { + release { + isMinifyEnabled = false + } + } +} + +dependencies { + implementation(platform("androidx.compose:compose-bom:2023.10.01")) + implementation("androidx.compose.material3:material3") + implementation("androidx.compose.ui:ui-tooling-preview") + debugImplementation("androidx.compose.ui:ui-tooling") + debugImplementation("androidx.compose.ui:ui-test-manifest") + + implementation("androidx.core:core-ktx:1.12.0") + implementation("androidx.lifecycle:lifecycle-runtime-compose:2.6.2") +} diff --git a/library/gradle.properties b/library/gradle.properties new file mode 100644 index 0000000..e73eb41 --- /dev/null +++ b/library/gradle.properties @@ -0,0 +1 @@ +POM_NAME=ComposePreference Library diff --git a/library/proguard-rules.pro b/library/proguard-rules.pro new file mode 100644 index 0000000..f1b4245 --- /dev/null +++ b/library/proguard-rules.pro @@ -0,0 +1,21 @@ +# 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 diff --git a/library/src/main/AndroidManifest.xml b/library/src/main/AndroidManifest.xml new file mode 100644 index 0000000..bf52ab1 --- /dev/null +++ b/library/src/main/AndroidManifest.xml @@ -0,0 +1,19 @@ + + + + + diff --git a/library/src/main/java/me/zhanghai/compose/preference/BasicPreference.kt b/library/src/main/java/me/zhanghai/compose/preference/BasicPreference.kt new file mode 100644 index 0000000..9456da7 --- /dev/null +++ b/library/src/main/java/me/zhanghai/compose/preference/BasicPreference.kt @@ -0,0 +1,73 @@ +/* + * Copyright 2023 Google LLC + * + * 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. + */ + +package me.zhanghai.compose.preference + +import androidx.compose.foundation.clickable +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.lazy.LazyListScope +import androidx.compose.runtime.Composable +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier + +fun LazyListScope.basicPreference( + key: String, + textContainer: @Composable () -> Unit, + modifier: Modifier = Modifier.fillMaxWidth(), + enabled: Boolean = true, + iconContainer: @Composable () -> Unit = {}, + widgetContainer: @Composable () -> Unit = {}, + onClick: (() -> Unit)? = null +) { + item(key = key, contentType = "BasicPreference") { + BasicPreference( + textContainer = textContainer, + modifier = modifier, + enabled = enabled, + iconContainer = iconContainer, + widgetContainer = widgetContainer, + onClick = onClick + ) + } +} + +@Composable +fun BasicPreference( + textContainer: @Composable () -> Unit, + modifier: Modifier = Modifier, + enabled: Boolean = true, + iconContainer: @Composable () -> Unit = {}, + widgetContainer: @Composable () -> Unit = {}, + onClick: (() -> Unit)? = null +) { + Row( + modifier = + modifier.then( + if (onClick != null) { + Modifier.clickable(enabled, onClick = onClick) + } else { + Modifier + } + ), + verticalAlignment = Alignment.CenterVertically + ) { + iconContainer() + Box(modifier = Modifier.weight(1f)) { textContainer() } + widgetContainer() + } +} diff --git a/library/src/main/java/me/zhanghai/compose/preference/CheckboxPreference.kt b/library/src/main/java/me/zhanghai/compose/preference/CheckboxPreference.kt new file mode 100644 index 0000000..28b1383 --- /dev/null +++ b/library/src/main/java/me/zhanghai/compose/preference/CheckboxPreference.kt @@ -0,0 +1,125 @@ +/* + * Copyright 2023 Google LLC + * + * 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. + */ + +package me.zhanghai.compose.preference + +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.lazy.LazyListScope +import androidx.compose.foundation.selection.toggleable +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.outlined.Info +import androidx.compose.material3.Checkbox +import androidx.compose.material3.Icon +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.runtime.MutableState +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import androidx.compose.ui.Modifier +import androidx.compose.ui.semantics.Role +import androidx.compose.ui.tooling.preview.Preview + +inline fun LazyListScope.checkboxPreference( + key: String, + defaultValue: Boolean, + crossinline title: @Composable (Boolean) -> Unit, + modifier: Modifier = Modifier.fillMaxWidth(), + crossinline rememberState: @Composable () -> MutableState = { + rememberPreferenceState(key, defaultValue) + }, + crossinline enabled: (Boolean) -> Boolean = { true }, + noinline icon: @Composable ((Boolean) -> Unit)? = null, + noinline summary: @Composable ((Boolean) -> Unit)? = null +) { + item(key = key, contentType = "CheckboxPreference") { + val state = rememberState() + val value by state + CheckboxPreference( + state = state, + title = { title(value) }, + modifier = modifier, + enabled = enabled(value), + icon = icon?.let { { it(value) } }, + summary = summary?.let { { it(value) } } + ) + } +} + +@Composable +fun CheckboxPreference( + state: MutableState, + title: @Composable () -> Unit, + modifier: Modifier = Modifier, + enabled: Boolean = true, + icon: @Composable (() -> Unit)? = null, + summary: @Composable (() -> Unit)? = null +) { + var value by state + CheckboxPreference( + value = value, + onValueChange = { value = it }, + title = title, + modifier = modifier, + enabled = enabled, + icon = icon, + summary = summary + ) +} + +@Composable +fun CheckboxPreference( + value: Boolean, + onValueChange: (Boolean) -> Unit, + title: @Composable () -> Unit, + modifier: Modifier = Modifier, + enabled: Boolean = true, + icon: @Composable (() -> Unit)? = null, + summary: @Composable (() -> Unit)? = null +) { + Preference( + title = title, + modifier = modifier.toggleable(value, enabled, Role.Checkbox, onValueChange), + enabled = enabled, + icon = icon, + summary = summary, + widgetContainer = { + val theme = LocalPreferenceTheme.current + Checkbox( + checked = value, + onCheckedChange = null, + modifier = Modifier.padding(theme.padding.copy(start = theme.horizontalSpacing)), + enabled = enabled + ) + } + ) +} + +@Composable +@Preview(showBackground = true) +private fun CheckboxPreferencePreview() { + ProvidePreferenceTheme { + CheckboxPreference( + state = remember { mutableStateOf(true) }, + title = { Text(text = "Checkbox preference") }, + modifier = Modifier.fillMaxWidth(), + icon = { Icon(imageVector = Icons.Outlined.Info, contentDescription = null) }, + summary = { Text(text = "Summary") } + ) + } +} diff --git a/library/src/main/java/me/zhanghai/compose/preference/FooterPreference.kt b/library/src/main/java/me/zhanghai/compose/preference/FooterPreference.kt new file mode 100644 index 0000000..1d1e185 --- /dev/null +++ b/library/src/main/java/me/zhanghai/compose/preference/FooterPreference.kt @@ -0,0 +1,77 @@ +/* + * Copyright 2023 Google LLC + * + * 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. + */ + +package me.zhanghai.compose.preference + +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.lazy.LazyListScope +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.outlined.Info +import androidx.compose.material3.Icon +import androidx.compose.material3.LocalContentColor +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.runtime.CompositionLocalProvider +import androidx.compose.ui.Modifier +import androidx.compose.ui.tooling.preview.Preview + +fun LazyListScope.footerPreference( + key: String, + summary: @Composable () -> Unit, + modifier: Modifier = Modifier.fillMaxWidth(), + icon: @Composable () -> Unit = FooterPreferenceDefaults.Icon +) { + item(key = key, contentType = "FooterPreference") { + FooterPreference(summary = summary, modifier = modifier, icon = icon) + } +} + +@Composable +fun FooterPreference( + summary: @Composable () -> Unit, + modifier: Modifier = Modifier, + icon: @Composable () -> Unit = FooterPreferenceDefaults.Icon +) { + Preference( + title = { + val theme = LocalPreferenceTheme.current + Box(modifier = Modifier.padding(bottom = theme.verticalSpacing)) { + CompositionLocalProvider(LocalContentColor provides theme.iconColor, content = icon) + } + }, + modifier = modifier, + summary = summary, + ) +} + +private object FooterPreferenceDefaults { + val Icon: @Composable () -> Unit = { + Icon(imageVector = Icons.Outlined.Info, contentDescription = null) + } +} + +@Composable +@Preview(showBackground = true) +private fun FooterPreferencePreview() { + ProvidePreferenceTheme { + FooterPreference( + modifier = Modifier.fillMaxWidth(), + summary = { Text(text = "Footer preference summary") } + ) + } +} diff --git a/library/src/main/java/me/zhanghai/compose/preference/ListPreference.kt b/library/src/main/java/me/zhanghai/compose/preference/ListPreference.kt new file mode 100644 index 0000000..b8cb71b --- /dev/null +++ b/library/src/main/java/me/zhanghai/compose/preference/ListPreference.kt @@ -0,0 +1,281 @@ +/* + * Copyright 2023 Google LLC + * + * 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. + */ + +package me.zhanghai.compose.preference + +import androidx.compose.foundation.background +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.heightIn +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.width +import androidx.compose.foundation.lazy.LazyColumn +import androidx.compose.foundation.lazy.LazyListScope +import androidx.compose.foundation.lazy.items +import androidx.compose.foundation.lazy.rememberLazyListState +import androidx.compose.foundation.selection.selectable +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.outlined.Info +import androidx.compose.material3.DropdownMenu +import androidx.compose.material3.DropdownMenuItem +import androidx.compose.material3.Icon +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.MenuDefaults +import androidx.compose.material3.RadioButton +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton +import androidx.compose.runtime.Composable +import androidx.compose.runtime.MutableState +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.saveable.rememberSaveable +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.semantics.Role +import androidx.compose.ui.text.AnnotatedString +import androidx.compose.ui.tooling.preview.Preview +import androidx.compose.ui.unit.dp + +enum class ListPreferenceType { + ALERT_DIALOG, + DROPDOWN_MENU +} + +inline fun LazyListScope.listPreference( + key: String, + defaultValue: T, + values: List, + crossinline title: @Composable (T) -> Unit, + modifier: Modifier = Modifier.fillMaxWidth(), + crossinline rememberState: @Composable () -> MutableState = { + rememberPreferenceState(key, defaultValue) + }, + crossinline enabled: (T) -> Boolean = { true }, + noinline icon: @Composable ((T) -> Unit)? = null, + noinline summary: @Composable ((T) -> Unit)? = null, + type: ListPreferenceType = ListPreferenceType.ALERT_DIALOG, + noinline valueToText: (T) -> AnnotatedString = { AnnotatedString(it.toString()) }, + noinline item: @Composable (value: T, currentValue: T, onClick: () -> Unit) -> Unit = + ListPreferenceDefaults.item(type, valueToText) +) { + item(key = key, contentType = "ListPreference") { + val state = rememberState() + val value by state + ListPreference( + state = state, + values = values, + title = { title(value) }, + modifier = modifier, + enabled = enabled(value), + icon = icon?.let { { it(value) } }, + summary = summary?.let { { it(value) } }, + type = type, + valueToText = valueToText, + item = item + ) + } +} + +@Composable +fun ListPreference( + state: MutableState, + values: List, + title: @Composable () -> Unit, + modifier: Modifier = Modifier, + enabled: Boolean = true, + icon: @Composable (() -> Unit)? = null, + summary: @Composable (() -> Unit)? = null, + type: ListPreferenceType = ListPreferenceType.ALERT_DIALOG, + valueToText: (T) -> AnnotatedString = { AnnotatedString(it.toString()) }, + item: @Composable (value: T, currentValue: T, onClick: () -> Unit) -> Unit = + ListPreferenceDefaults.item(type, valueToText) +) { + var value by state + ListPreference( + value = value, + onValueChange = { value = it }, + values = values, + title = title, + modifier = modifier, + enabled = enabled, + icon = icon, + summary = summary, + type = type, + valueToText = valueToText, + item = item + ) +} + +@Composable +fun ListPreference( + value: T, + onValueChange: (T) -> Unit, + values: List, + title: @Composable () -> Unit, + modifier: Modifier = Modifier, + enabled: Boolean = true, + icon: @Composable (() -> Unit)? = null, + summary: @Composable (() -> Unit)? = null, + type: ListPreferenceType = ListPreferenceType.ALERT_DIALOG, + valueToText: (T) -> AnnotatedString = { AnnotatedString(it.toString()) }, + item: @Composable (value: T, currentValue: T, onClick: () -> Unit) -> Unit = + ListPreferenceDefaults.item(type, valueToText) +) { + var openSelector by rememberSaveable { mutableStateOf(false) } + // Put DropdownMenu before Preference so that it can anchor to the right position. + if (openSelector) { + when (type) { + ListPreferenceType.ALERT_DIALOG -> { + PreferenceAlertDialog( + onDismissRequest = { openSelector = false }, + title = title, + buttons = { + TextButton(onClick = { openSelector = false }) { + Text(text = stringResource(android.R.string.cancel)) + } + } + ) { + val lazyListState = rememberLazyListState() + LazyColumn( + modifier = Modifier.fillMaxWidth().verticalScrollIndicators(lazyListState), + state = lazyListState + ) { + items(values) { itemValue -> + item(itemValue, value) { + onValueChange(itemValue) + openSelector = false + } + } + } + } + } + ListPreferenceType.DROPDOWN_MENU -> { + val theme = LocalPreferenceTheme.current + Box( + modifier = Modifier.fillMaxWidth().padding(theme.padding.copy(vertical = 0.dp)) + ) { + DropdownMenu( + expanded = openSelector, + onDismissRequest = { openSelector = false } + ) { + for (itemValue in values) { + item(itemValue, value) { + onValueChange(itemValue) + openSelector = false + } + } + } + } + } + } + } + Preference( + title = title, + modifier = modifier, + enabled = enabled, + icon = icon, + summary = summary + ) { + openSelector = true + } +} + +@PublishedApi +internal object ListPreferenceDefaults { + fun item( + type: ListPreferenceType, + valueToText: (T) -> AnnotatedString + ): @Composable (value: T, currentValue: T, onClick: () -> Unit) -> Unit = + when (type) { + ListPreferenceType.ALERT_DIALOG -> { + { value, currentValue, onClick -> + DialogItem(value, currentValue, valueToText, onClick) + } + } + ListPreferenceType.DROPDOWN_MENU -> { + { value, currentValue, onClick -> + DropdownMenuItem(value, currentValue, valueToText, onClick) + } + } + } + + @Composable + private fun DialogItem( + value: T, + currentValue: T, + valueToText: (T) -> AnnotatedString, + onClick: () -> Unit + ) { + val selected = value == currentValue + Row( + modifier = + Modifier.fillMaxWidth() + .heightIn(min = 48.dp) + .selectable(selected, true, Role.RadioButton, onClick) + .padding(horizontal = 24.dp, vertical = 8.dp), + verticalAlignment = Alignment.CenterVertically + ) { + RadioButton(selected = selected, onClick = null) + Spacer(modifier = Modifier.width(24.dp)) + Text( + text = valueToText(value), + color = MaterialTheme.colorScheme.onSurface, + style = MaterialTheme.typography.bodyLarge + ) + } + } + + @Composable + private fun DropdownMenuItem( + value: T, + currentValue: T, + valueToText: (T) -> AnnotatedString, + onClick: () -> Unit + ) { + DropdownMenuItem( + text = { Text(text = valueToText(value)) }, + onClick = onClick, + modifier = + Modifier.background( + if (value == currentValue) MaterialTheme.colorScheme.secondaryContainer + else Color.Transparent + ), + colors = MenuDefaults.itemColors() + ) + } +} + +@Composable +@Preview(showBackground = true) +private fun ListPreferencePreview() { + ProvidePreferenceTheme { + val state = remember { mutableStateOf("Alpha") } + ListPreference( + state = state, + values = listOf("Alpha", "Beta", "Canary"), + title = { Text(text = "List preference") }, + modifier = Modifier.fillMaxWidth(), + icon = { Icon(imageVector = Icons.Outlined.Info, contentDescription = null) }, + summary = { Text(text = state.value) } + ) + } +} diff --git a/library/src/main/java/me/zhanghai/compose/preference/MultiSelectListPreference.kt b/library/src/main/java/me/zhanghai/compose/preference/MultiSelectListPreference.kt new file mode 100644 index 0000000..7086c8b --- /dev/null +++ b/library/src/main/java/me/zhanghai/compose/preference/MultiSelectListPreference.kt @@ -0,0 +1,223 @@ +/* + * Copyright 2023 Google LLC + * + * 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. + */ + +package me.zhanghai.compose.preference + +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.heightIn +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.width +import androidx.compose.foundation.lazy.LazyColumn +import androidx.compose.foundation.lazy.LazyListScope +import androidx.compose.foundation.lazy.items +import androidx.compose.foundation.lazy.rememberLazyListState +import androidx.compose.foundation.selection.toggleable +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.outlined.Info +import androidx.compose.material3.Checkbox +import androidx.compose.material3.Icon +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton +import androidx.compose.runtime.Composable +import androidx.compose.runtime.MutableState +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.saveable.rememberSaveable +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.semantics.Role +import androidx.compose.ui.text.AnnotatedString +import androidx.compose.ui.tooling.preview.Preview +import androidx.compose.ui.unit.dp + +inline fun LazyListScope.multiSelectListPreference( + key: String, + defaultValue: Set, + values: List, + crossinline title: @Composable (Set) -> Unit, + modifier: Modifier = Modifier.fillMaxWidth(), + crossinline rememberState: @Composable () -> MutableState> = { + rememberPreferenceState(key, defaultValue) + }, + crossinline enabled: (Set) -> Boolean = { true }, + noinline icon: @Composable ((Set) -> Unit)? = null, + noinline summary: @Composable ((Set) -> Unit)? = null, + noinline valueToText: (T) -> AnnotatedString = { AnnotatedString(it.toString()) }, + noinline item: + @Composable + (value: T, currentValues: Set, onToggle: (Boolean) -> Unit) -> Unit = + MultiSelectListPreferenceDefaults.item(valueToText) +) { + item(key = key, contentType = "MultiSelectListPreference") { + val state = rememberState() + val value by state + MultiSelectListPreference( + state = state, + values = values, + title = { title(value) }, + modifier = modifier, + enabled = enabled(value), + icon = icon?.let { { it(value) } }, + summary = summary?.let { { it(value) } }, + valueToText = valueToText, + item = item + ) + } +} + +@Composable +fun MultiSelectListPreference( + state: MutableState>, + values: List, + title: @Composable () -> Unit, + modifier: Modifier = Modifier, + enabled: Boolean = true, + icon: @Composable (() -> Unit)? = null, + summary: @Composable (() -> Unit)? = null, + valueToText: (T) -> AnnotatedString = { AnnotatedString(it.toString()) }, + item: @Composable (value: T, currentValues: Set, onToggle: (Boolean) -> Unit) -> Unit = + MultiSelectListPreferenceDefaults.item(valueToText) +) { + var value by state + MultiSelectListPreference( + value = value, + onValueChange = { value = it }, + values = values, + title = title, + modifier = modifier, + enabled = enabled, + icon = icon, + summary = summary, + valueToText = valueToText, + item = item + ) +} + +@Composable +fun MultiSelectListPreference( + value: Set, + onValueChange: (Set) -> Unit, + values: List, + title: @Composable () -> Unit, + modifier: Modifier = Modifier, + enabled: Boolean = true, + icon: @Composable (() -> Unit)? = null, + summary: @Composable (() -> Unit)? = null, + valueToText: (T) -> AnnotatedString = { AnnotatedString(it.toString()) }, + item: @Composable (value: T, currentValues: Set, onToggle: (Boolean) -> Unit) -> Unit = + MultiSelectListPreferenceDefaults.item(valueToText) +) { + var openDialog by rememberSaveable { mutableStateOf(false) } + Preference( + title = title, + modifier = modifier, + enabled = enabled, + icon = icon, + summary = summary + ) { + openDialog = true + } + if (openDialog) { + var dialogValue by rememberSaveable { mutableStateOf(value) } + PreferenceAlertDialog( + onDismissRequest = { openDialog = false }, + title = title, + buttons = { + TextButton(onClick = { openDialog = false }) { + Text(text = stringResource(android.R.string.cancel)) + } + TextButton( + onClick = { + onValueChange(dialogValue) + openDialog = false + } + ) { + Text(text = stringResource(android.R.string.ok)) + } + } + ) { + val lazyListState = rememberLazyListState() + LazyColumn( + modifier = Modifier.fillMaxWidth().verticalScrollIndicators(lazyListState), + state = lazyListState + ) { + items(values) { itemValue -> + item(itemValue, dialogValue) { + dialogValue = if (it) dialogValue + itemValue else dialogValue - itemValue + } + } + } + } + } +} + +@PublishedApi +internal object MultiSelectListPreferenceDefaults { + fun item( + valueToText: (T) -> AnnotatedString + ): @Composable (value: T, currentValues: Set, onToggle: (Boolean) -> Unit) -> Unit = + { value, currentValues, onToggle -> + Item(value, currentValues, valueToText, onToggle) + } + + @Composable + private fun Item( + value: T, + currentValues: Set, + valueToText: (T) -> AnnotatedString, + onToggle: (Boolean) -> Unit + ) { + val checked = value in currentValues + Row( + modifier = + Modifier.fillMaxWidth() + .heightIn(min = 48.dp) + .toggleable(checked, true, Role.Checkbox, onToggle) + .padding(horizontal = 24.dp, vertical = 8.dp), + verticalAlignment = Alignment.CenterVertically + ) { + Checkbox(checked = checked, onCheckedChange = null) + Spacer(modifier = Modifier.width(24.dp)) + Text( + text = valueToText(value), + color = MaterialTheme.colorScheme.onSurface, + style = MaterialTheme.typography.bodyLarge + ) + } + } +} + +@Composable +@Preview(showBackground = true) +private fun MultiSelectListPreferencePreview() { + ProvidePreferenceTheme { + val state = remember { mutableStateOf(setOf("Alpha", "Beta")) } + MultiSelectListPreference( + state = state, + values = listOf("Alpha", "Beta", "Canary"), + title = { Text(text = "Multi-select list preference") }, + modifier = Modifier.fillMaxWidth(), + icon = { Icon(imageVector = Icons.Outlined.Info, contentDescription = null) }, + summary = { Text(text = state.value.joinToString(", ")) } + ) + } +} diff --git a/library/src/main/java/me/zhanghai/compose/preference/PaddingValuesExtensions.kt b/library/src/main/java/me/zhanghai/compose/preference/PaddingValuesExtensions.kt new file mode 100644 index 0000000..f41b206 --- /dev/null +++ b/library/src/main/java/me/zhanghai/compose/preference/PaddingValuesExtensions.kt @@ -0,0 +1,151 @@ +/* + * Copyright 2023 Google LLC + * + * 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. + */ + +package me.zhanghai.compose.preference + +import androidx.compose.foundation.layout.PaddingValues +import androidx.compose.runtime.Composable +import androidx.compose.runtime.Stable +import androidx.compose.ui.unit.Dp +import androidx.compose.ui.unit.LayoutDirection +import androidx.compose.ui.unit.dp + +@Composable +internal fun PaddingValues.copy( + horizontal: Dp = Dp.Unspecified, + vertical: Dp = Dp.Unspecified +): PaddingValues = copy(start = horizontal, top = vertical, end = horizontal, bottom = vertical) + +@Composable +internal fun PaddingValues.copy( + start: Dp = Dp.Unspecified, + top: Dp = Dp.Unspecified, + end: Dp = Dp.Unspecified, + bottom: Dp = Dp.Unspecified +): PaddingValues = CopiedPaddingValues(start, top, end, bottom, this) + +@Stable +private class CopiedPaddingValues( + private val start: Dp, + private val top: Dp, + private val end: Dp, + private val bottom: Dp, + private val paddingValues: PaddingValues +) : PaddingValues { + override fun calculateLeftPadding(layoutDirection: LayoutDirection): Dp = + (if (layoutDirection == LayoutDirection.Ltr) start else end).takeIf { it != Dp.Unspecified } + ?: paddingValues.calculateLeftPadding(layoutDirection) + + override fun calculateTopPadding(): Dp = + top.takeIf { it != Dp.Unspecified } ?: paddingValues.calculateTopPadding() + + override fun calculateRightPadding(layoutDirection: LayoutDirection): Dp = + (if (layoutDirection == LayoutDirection.Ltr) end else start).takeIf { it != Dp.Unspecified } + ?: paddingValues.calculateRightPadding(layoutDirection) + + override fun calculateBottomPadding(): Dp = + bottom.takeIf { it != Dp.Unspecified } ?: paddingValues.calculateBottomPadding() + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + if (other !is CopiedPaddingValues) { + return false + } + return start == other.start && + top == other.top && + end == other.end && + bottom == other.bottom && + paddingValues == other.paddingValues + } + + override fun hashCode(): Int { + var result = start.hashCode() + result = 31 * result + top.hashCode() + result = 31 * result + end.hashCode() + result = 31 * result + bottom.hashCode() + result = 31 * result + paddingValues.hashCode() + return result + } + + override fun toString(): String { + return "Copied($start, $top, $end, $bottom, $paddingValues)" + } +} + +@Composable +internal fun PaddingValues.offset(all: Dp = 0.dp): PaddingValues = offset(all, all, all, all) + +@Composable +internal fun PaddingValues.offset(horizontal: Dp = 0.dp, vertical: Dp = 0.dp): PaddingValues = + offset(horizontal, vertical, horizontal, vertical) + +@Composable +internal fun PaddingValues.offset( + start: Dp = 0.dp, + top: Dp = 0.dp, + end: Dp = 0.dp, + bottom: Dp = 0.dp +): PaddingValues = OffsetPaddingValues(start, top, end, bottom, this) + +@Stable +private class OffsetPaddingValues( + private val start: Dp, + private val top: Dp, + private val end: Dp, + private val bottom: Dp, + private val paddingValues: PaddingValues +) : PaddingValues { + override fun calculateLeftPadding(layoutDirection: LayoutDirection): Dp = + paddingValues.calculateLeftPadding(layoutDirection) + + (if (layoutDirection == LayoutDirection.Ltr) start else end) + + override fun calculateTopPadding(): Dp = paddingValues.calculateTopPadding() + top + + override fun calculateRightPadding(layoutDirection: LayoutDirection): Dp = + paddingValues.calculateRightPadding(layoutDirection) + + (if (layoutDirection == LayoutDirection.Ltr) end else start) + + override fun calculateBottomPadding(): Dp = paddingValues.calculateBottomPadding() + bottom + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + if (other !is OffsetPaddingValues) { + return false + } + return start == other.start && + top == other.top && + end == other.end && + bottom == other.bottom && + paddingValues == other.paddingValues + } + + override fun hashCode(): Int { + var result = start.hashCode() + result = 31 * result + top.hashCode() + result = 31 * result + end.hashCode() + result = 31 * result + bottom.hashCode() + result = 31 * result + paddingValues.hashCode() + return result + } + + override fun toString(): String { + return "Offset($start, $top, $end, $bottom, $paddingValues)" + } +} diff --git a/library/src/main/java/me/zhanghai/compose/preference/Preference.kt b/library/src/main/java/me/zhanghai/compose/preference/Preference.kt new file mode 100644 index 0000000..9519f26 --- /dev/null +++ b/library/src/main/java/me/zhanghai/compose/preference/Preference.kt @@ -0,0 +1,160 @@ +/* + * Copyright 2023 Google LLC + * + * 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. + */ + +package me.zhanghai.compose.preference + +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.widthIn +import androidx.compose.foundation.lazy.LazyListScope +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.outlined.Info +import androidx.compose.material3.Icon +import androidx.compose.material3.LocalContentColor +import androidx.compose.material3.ProvideTextStyle +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.runtime.CompositionLocalProvider +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.tooling.preview.Preview +import androidx.compose.ui.unit.Dp +import androidx.compose.ui.unit.dp + +fun LazyListScope.preference( + key: String, + title: @Composable () -> Unit, + modifier: Modifier = Modifier.fillMaxWidth(), + enabled: Boolean = true, + icon: @Composable (() -> Unit)? = null, + summary: @Composable (() -> Unit)? = null, + widgetContainer: @Composable (() -> Unit)? = null, + onClick: (() -> Unit)? = null +) { + item(key = key, contentType = "Preference") { + Preference( + title = title, + modifier = modifier, + enabled = enabled, + icon = icon, + summary = summary, + widgetContainer = widgetContainer, + onClick = onClick + ) + } +} + +@Composable +fun Preference( + title: @Composable () -> Unit, + modifier: Modifier = Modifier, + enabled: Boolean = true, + icon: @Composable (() -> Unit)? = null, + summary: @Composable (() -> Unit)? = null, + widgetContainer: @Composable (() -> Unit)? = null, + onClick: (() -> Unit)? = null +) { + BasicPreference( + textContainer = { + val theme = LocalPreferenceTheme.current + Column( + modifier = + Modifier.padding( + theme.padding.copy( + start = if (icon != null) 0.dp else Dp.Unspecified, + end = if (widgetContainer != null) 0.dp else Dp.Unspecified, + ) + ) + ) { + PreferenceDefaults.TitleContainer(title = title, enabled = enabled) + PreferenceDefaults.SummaryContainer(summary = summary, enabled = enabled) + } + }, + modifier = modifier, + enabled = enabled, + iconContainer = { PreferenceDefaults.IconContainer(icon = icon, enabled = enabled) }, + widgetContainer = { widgetContainer?.invoke() }, + onClick = onClick + ) +} + +internal object PreferenceDefaults { + @Composable + fun IconContainer( + icon: @Composable (() -> Unit)?, + enabled: Boolean, + excludedEndPadding: Dp = 0.dp + ) { + if (icon != null) { + val theme = LocalPreferenceTheme.current + Box( + modifier = + Modifier.widthIn(min = theme.iconContainerMinWidth - excludedEndPadding) + .padding(theme.padding.copy(end = 0.dp)), + contentAlignment = Alignment.CenterStart + ) { + CompositionLocalProvider( + LocalContentColor provides + theme.iconColor.let { + if (enabled) it else it.copy(alpha = theme.disabledOpacity) + }, + content = icon + ) + } + } + } + + @Composable + fun TitleContainer(title: @Composable () -> Unit, enabled: Boolean) { + val theme = LocalPreferenceTheme.current + CompositionLocalProvider( + LocalContentColor provides + theme.titleColor.let { if (enabled) it else it.copy(alpha = theme.disabledOpacity) } + ) { + ProvideTextStyle(value = theme.titleTextStyle, content = title) + } + } + + @Composable + fun SummaryContainer(summary: (@Composable () -> Unit)?, enabled: Boolean) { + if (summary != null) { + val theme = LocalPreferenceTheme.current + CompositionLocalProvider( + LocalContentColor provides + theme.summaryColor.let { + if (enabled) it else it.copy(alpha = theme.disabledOpacity) + } + ) { + ProvideTextStyle(value = theme.summaryTextStyle, content = summary) + } + } + } +} + +@Composable +@Preview(showBackground = true) +private fun PreferencePreview() { + ProvidePreferenceTheme { + Preference( + title = { Text(text = "Preference") }, + modifier = Modifier.fillMaxWidth(), + icon = { Icon(imageVector = Icons.Outlined.Info, contentDescription = null) }, + summary = { Text(text = "Summary") } + ) + } +} diff --git a/library/src/main/java/me/zhanghai/compose/preference/PreferenceAlertDialog.kt b/library/src/main/java/me/zhanghai/compose/preference/PreferenceAlertDialog.kt new file mode 100644 index 0000000..9e73e25 --- /dev/null +++ b/library/src/main/java/me/zhanghai/compose/preference/PreferenceAlertDialog.kt @@ -0,0 +1,180 @@ +/* + * Copyright 2023 Google LLC + * + * 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. + */ + +package me.zhanghai.compose.preference + +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.padding +import androidx.compose.material3.AlertDialog +import androidx.compose.material3.AlertDialogDefaults +import androidx.compose.material3.ExperimentalMaterial3Api +import androidx.compose.material3.LocalContentColor +import androidx.compose.material3.LocalMinimumInteractiveComponentEnforcement +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.ProvideTextStyle +import androidx.compose.material3.Surface +import androidx.compose.runtime.Composable +import androidx.compose.runtime.CompositionLocalProvider +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.layout.Layout +import androidx.compose.ui.layout.Placeable +import androidx.compose.ui.unit.Dp +import androidx.compose.ui.unit.dp +import kotlin.math.max + +@Composable +@OptIn(ExperimentalMaterial3Api::class) +internal fun PreferenceAlertDialog( + onDismissRequest: () -> Unit, + title: @Composable () -> Unit, + buttons: @Composable () -> Unit, + modifier: Modifier = Modifier, + content: @Composable () -> Unit +) { + AlertDialog(onDismissRequest = onDismissRequest, modifier = modifier) { + Surface( + modifier = Modifier.fillMaxWidth(), + shape = AlertDialogDefaults.shape, + color = AlertDialogDefaults.containerColor, + tonalElevation = AlertDialogDefaults.TonalElevation, + ) { + Column(modifier = Modifier.fillMaxWidth()) { + Box( + modifier = + Modifier.fillMaxWidth() + .padding(start = 24.dp, top = 24.dp, end = 24.dp, bottom = 16.dp) + ) { + CompositionLocalProvider( + LocalContentColor provides AlertDialogDefaults.titleContentColor + ) { + ProvideTextStyle(MaterialTheme.typography.headlineSmall, title) + } + } + Box(modifier = Modifier.fillMaxWidth().weight(1f, fill = false)) { content() } + Box( + modifier = + Modifier.fillMaxWidth() + .padding(start = 24.dp, top = 16.dp, end = 24.dp, bottom = 24.dp), + contentAlignment = Alignment.CenterEnd + ) { + AlertDialogFlowRow(mainAxisSpacing = 8.dp, crossAxisSpacing = 12.dp) { + CompositionLocalProvider( + LocalMinimumInteractiveComponentEnforcement provides false, + content = buttons + ) + } + } + } + } + } +} + +// Copied from androidx.compose.material3.AlertDialogFlowRow . +@Composable +internal fun AlertDialogFlowRow( + mainAxisSpacing: Dp, + crossAxisSpacing: Dp, + content: @Composable () -> Unit +) { + Layout(content) { measurables, constraints -> + val sequences = mutableListOf>() + val crossAxisSizes = mutableListOf() + val crossAxisPositions = mutableListOf() + + var mainAxisSpace = 0 + var crossAxisSpace = 0 + + val currentSequence = mutableListOf() + var currentMainAxisSize = 0 + var currentCrossAxisSize = 0 + + // Return whether the placeable can be added to the current sequence. + fun canAddToCurrentSequence(placeable: Placeable) = + currentSequence.isEmpty() || + currentMainAxisSize + mainAxisSpacing.roundToPx() + placeable.width <= + constraints.maxWidth + + // Store current sequence information and start a new sequence. + fun startNewSequence() { + if (sequences.isNotEmpty()) { + crossAxisSpace += crossAxisSpacing.roundToPx() + } + sequences += currentSequence.toList() + crossAxisSizes += currentCrossAxisSize + crossAxisPositions += crossAxisSpace + + crossAxisSpace += currentCrossAxisSize + mainAxisSpace = max(mainAxisSpace, currentMainAxisSize) + + currentSequence.clear() + currentMainAxisSize = 0 + currentCrossAxisSize = 0 + } + + for (measurable in measurables) { + // Ask the child for its preferred size. + val placeable = measurable.measure(constraints) + + // Start a new sequence if there is not enough space. + if (!canAddToCurrentSequence(placeable)) startNewSequence() + + // Add the child to the current sequence. + if (currentSequence.isNotEmpty()) { + currentMainAxisSize += mainAxisSpacing.roundToPx() + } + currentSequence.add(placeable) + currentMainAxisSize += placeable.width + currentCrossAxisSize = max(currentCrossAxisSize, placeable.height) + } + + if (currentSequence.isNotEmpty()) startNewSequence() + + val mainAxisLayoutSize = max(mainAxisSpace, constraints.minWidth) + + val crossAxisLayoutSize = max(crossAxisSpace, constraints.minHeight) + + val layoutWidth = mainAxisLayoutSize + + val layoutHeight = crossAxisLayoutSize + + layout(layoutWidth, layoutHeight) { + sequences.forEachIndexed { i, placeables -> + val childrenMainAxisSizes = + IntArray(placeables.size) { j -> + placeables[j].width + + if (j < placeables.lastIndex) mainAxisSpacing.roundToPx() else 0 + } + val arrangement = Arrangement.End + val mainAxisPositions = IntArray(childrenMainAxisSizes.size) { 0 } + with(arrangement) { + arrange( + mainAxisLayoutSize, + childrenMainAxisSizes, + layoutDirection, + mainAxisPositions + ) + } + placeables.forEachIndexed { j, placeable -> + placeable.place(x = mainAxisPositions[j], y = crossAxisPositions[i]) + } + } + } + } +} diff --git a/library/src/main/java/me/zhanghai/compose/preference/PreferenceCategory.kt b/library/src/main/java/me/zhanghai/compose/preference/PreferenceCategory.kt new file mode 100644 index 0000000..8f424dd --- /dev/null +++ b/library/src/main/java/me/zhanghai/compose/preference/PreferenceCategory.kt @@ -0,0 +1,69 @@ +/* + * Copyright 2023 Google LLC + * + * 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. + */ + +package me.zhanghai.compose.preference + +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.lazy.LazyListScope +import androidx.compose.material3.LocalContentColor +import androidx.compose.material3.ProvideTextStyle +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.runtime.CompositionLocalProvider +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.tooling.preview.Preview + +fun LazyListScope.preferenceCategory( + key: String, + title: @Composable () -> Unit, + modifier: Modifier = Modifier.fillMaxWidth() +) { + item(key = key, contentType = "PreferenceCategory") { + PreferenceCategory(title = title, modifier = modifier) + } +} + +@Composable +fun PreferenceCategory(title: @Composable () -> Unit, modifier: Modifier = Modifier) { + BasicPreference( + textContainer = { + val theme = LocalPreferenceTheme.current + Box( + modifier = Modifier.padding(theme.categoryPadding), + contentAlignment = Alignment.CenterStart + ) { + CompositionLocalProvider(LocalContentColor provides theme.categoryColor) { + ProvideTextStyle(value = theme.categoryTextStyle, content = title) + } + } + }, + modifier = modifier + ) +} + +@Composable +@Preview(showBackground = true) +private fun PreferenceCategoryPreview() { + ProvidePreferenceTheme { + PreferenceCategory( + title = { Text(text = "Preference category") }, + modifier = Modifier.fillMaxWidth() + ) + } +} diff --git a/library/src/main/java/me/zhanghai/compose/preference/PreferenceFlow.kt b/library/src/main/java/me/zhanghai/compose/preference/PreferenceFlow.kt new file mode 100644 index 0000000..2a6583a --- /dev/null +++ b/library/src/main/java/me/zhanghai/compose/preference/PreferenceFlow.kt @@ -0,0 +1,48 @@ +/* + * Copyright 2023 Google LLC + * + * 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. + */ + +package me.zhanghai.compose.preference + +import android.preference.PreferenceManager +import androidx.compose.runtime.Composable +import androidx.compose.runtime.CompositionLocalProvider +import androidx.compose.runtime.compositionLocalOf +import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.platform.LocalView +import kotlinx.coroutines.flow.MutableStateFlow + +@Composable +fun defaultPreferenceFlow(): MutableStateFlow { + val view = LocalView.current + return if (view.isInEditMode) { + MutableStateFlow(MapPreferences()) + } else { + val context = LocalContext.current + @Suppress("DEPRECATION") + PreferenceManager.getDefaultSharedPreferences(context).getPreferenceFlow() + } +} + +val LocalPreferenceFlow = + compositionLocalOf> { noLocalProvidedFor("LocalPreferenceFlow") } + +@Composable +fun ProvidePreferenceFlow( + flow: MutableStateFlow = defaultPreferenceFlow(), + content: @Composable () -> Unit +) { + CompositionLocalProvider(LocalPreferenceFlow provides flow, content = content) +} diff --git a/library/src/main/java/me/zhanghai/compose/preference/PreferenceLocals.kt b/library/src/main/java/me/zhanghai/compose/preference/PreferenceLocals.kt new file mode 100644 index 0000000..02635cf --- /dev/null +++ b/library/src/main/java/me/zhanghai/compose/preference/PreferenceLocals.kt @@ -0,0 +1,38 @@ +/* + * Copyright 2023 Google LLC + * + * 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. + */ + +package me.zhanghai.compose.preference + +import androidx.compose.runtime.Composable +import androidx.compose.runtime.CompositionLocalProvider +import kotlinx.coroutines.flow.MutableStateFlow + +@Composable +fun ProvidePreferenceLocals( + flow: MutableStateFlow = defaultPreferenceFlow(), + theme: PreferenceTheme = preferenceTheme(), + content: @Composable () -> Unit +) { + CompositionLocalProvider( + LocalPreferenceFlow provides flow, + LocalPreferenceTheme provides theme, + content = content + ) +} + +internal fun noLocalProvidedFor(name: String): Nothing { + error("CompositionLocal $name not present") +} diff --git a/library/src/main/java/me/zhanghai/compose/preference/PreferenceState.kt b/library/src/main/java/me/zhanghai/compose/preference/PreferenceState.kt new file mode 100644 index 0000000..0d3716b --- /dev/null +++ b/library/src/main/java/me/zhanghai/compose/preference/PreferenceState.kt @@ -0,0 +1,56 @@ +/* + * Copyright 2023 Google LLC + * + * 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. + */ + +package me.zhanghai.compose.preference + +import androidx.compose.runtime.Composable +import androidx.compose.runtime.MutableState +import androidx.compose.runtime.Stable +import androidx.compose.runtime.State +import androidx.compose.runtime.remember +import androidx.lifecycle.compose.collectAsStateWithLifecycle +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.map + +@Composable +fun rememberPreferenceState( + key: String, + defaultValue: T, + flow: MutableStateFlow = LocalPreferenceFlow.current +): MutableState { + val valueFlow = remember(key, defaultValue, flow) { flow.map { it[key] ?: defaultValue } } + return valueFlow.collectAsStateWithLifecycle(flow.value[key] ?: defaultValue).asMutable { value + -> + flow.value = flow.value.toMutablePreferences().apply { this[key] = value } + } +} + +private fun State.asMutable(setValue: (T) -> Unit): MutableState = + AsMutableState(this, setValue) + +@Stable +private class AsMutableState(private val state: State, private val setValue: (T) -> Unit) : + MutableState { + override var value: T + get() = state.value + set(value) { + setValue(value) + } + + override fun component1(): T = state.value + + override fun component2(): (T) -> Unit = setValue +} diff --git a/library/src/main/java/me/zhanghai/compose/preference/PreferenceTheme.kt b/library/src/main/java/me/zhanghai/compose/preference/PreferenceTheme.kt new file mode 100644 index 0000000..0fa3799 --- /dev/null +++ b/library/src/main/java/me/zhanghai/compose/preference/PreferenceTheme.kt @@ -0,0 +1,92 @@ +/* + * Copyright 2023 Google LLC + * + * 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. + */ + +package me.zhanghai.compose.preference + +import androidx.compose.foundation.layout.PaddingValues +import androidx.compose.material3.MaterialTheme +import androidx.compose.runtime.Composable +import androidx.compose.runtime.CompositionLocalProvider +import androidx.compose.runtime.Stable +import androidx.compose.runtime.compositionLocalOf +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.text.TextStyle +import androidx.compose.ui.unit.Dp +import androidx.compose.ui.unit.dp + +@Stable +class PreferenceTheme( + val categoryPadding: PaddingValues, + val categoryColor: Color, + val categoryTextStyle: TextStyle, + val padding: PaddingValues, + val horizontalSpacing: Dp, + val verticalSpacing: Dp, + val disabledOpacity: Float, + val iconContainerMinWidth: Dp, + val iconColor: Color, + val titleColor: Color, + val titleTextStyle: TextStyle, + val summaryColor: Color, + val summaryTextStyle: TextStyle, + val dividerHeight: Dp +) + +@Composable +fun preferenceTheme( + categoryPadding: PaddingValues = + PaddingValues(start = 16.dp, top = 24.dp, end = 16.dp, bottom = 8.dp), + categoryColor: Color = MaterialTheme.colorScheme.secondary, + categoryTextStyle: TextStyle = MaterialTheme.typography.labelLarge, + padding: PaddingValues = PaddingValues(16.dp), + horizontalSpacing: Dp = 16.dp, + verticalSpacing: Dp = 16.dp, + disabledOpacity: Float = 0.38f, + iconContainerMinWidth: Dp = 56.dp, + iconColor: Color = MaterialTheme.colorScheme.onSurfaceVariant, + titleColor: Color = MaterialTheme.colorScheme.onSurface, + titleTextStyle: TextStyle = MaterialTheme.typography.bodyLarge, + summaryColor: Color = MaterialTheme.colorScheme.onSurfaceVariant, + summaryTextStyle: TextStyle = MaterialTheme.typography.bodyMedium, + dividerHeight: Dp = 32.dp +) = + PreferenceTheme( + categoryPadding = categoryPadding, + categoryColor = categoryColor, + categoryTextStyle = categoryTextStyle, + padding = padding, + horizontalSpacing = horizontalSpacing, + verticalSpacing = verticalSpacing, + disabledOpacity = disabledOpacity, + iconContainerMinWidth = iconContainerMinWidth, + iconColor = iconColor, + titleColor = titleColor, + titleTextStyle = titleTextStyle, + summaryColor = summaryColor, + summaryTextStyle = summaryTextStyle, + dividerHeight = dividerHeight + ) + +val LocalPreferenceTheme = + compositionLocalOf { noLocalProvidedFor("LocalPreferenceTheme") } + +@Composable +fun ProvidePreferenceTheme( + theme: PreferenceTheme = preferenceTheme(), + content: @Composable () -> Unit +) { + CompositionLocalProvider(LocalPreferenceTheme provides theme, content = content) +} diff --git a/library/src/main/java/me/zhanghai/compose/preference/Preferences.kt b/library/src/main/java/me/zhanghai/compose/preference/Preferences.kt new file mode 100644 index 0000000..e6dcfe8 --- /dev/null +++ b/library/src/main/java/me/zhanghai/compose/preference/Preferences.kt @@ -0,0 +1,72 @@ +/* + * Copyright 2023 Google LLC + * + * 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. + */ + +package me.zhanghai.compose.preference + +interface Preferences { + operator fun get(key: String): T? + + fun asMap(): Map + + fun toPreferences(): Preferences = toMutablePreferences() + + fun toMutablePreferences(): MutablePreferences +} + +internal class MapPreferences(private val map: Map = emptyMap()) : Preferences { + @Suppress("UNCHECKED_CAST") override fun get(key: String): T? = map[key] as T? + + override fun asMap(): Map = map + + override fun toMutablePreferences(): MutablePreferences = + MapMutablePreferences(map.toMutableMap()) +} + +interface MutablePreferences : Preferences { + operator fun set(key: String, value: T?) + + fun remove(key: String) { + set(key, null) + } + + operator fun minusAssign(key: String) { + remove(key) + } + + fun clear() +} + +internal class MapMutablePreferences(private val map: MutableMap = mutableMapOf()) : + MutablePreferences { + @Suppress("UNCHECKED_CAST") override fun get(key: String): T? = map[key] as T? + + override fun asMap(): Map = map + + override fun toMutablePreferences(): MutablePreferences = + MapMutablePreferences(map.toMutableMap()) + + override fun set(key: String, value: T?) { + if (value != null) { + map[key] = value + } else { + map -= key + } + } + + override fun clear() { + map.clear() + } +} diff --git a/library/src/main/java/me/zhanghai/compose/preference/RadioButtonPreference.kt b/library/src/main/java/me/zhanghai/compose/preference/RadioButtonPreference.kt new file mode 100644 index 0000000..1bc9b78 --- /dev/null +++ b/library/src/main/java/me/zhanghai/compose/preference/RadioButtonPreference.kt @@ -0,0 +1,83 @@ +/* + * Copyright 2023 Google LLC + * + * 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. + */ + +package me.zhanghai.compose.preference + +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.lazy.LazyListScope +import androidx.compose.foundation.selection.selectable +import androidx.compose.material3.RadioButton +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.ui.Modifier +import androidx.compose.ui.semantics.Role +import androidx.compose.ui.tooling.preview.Preview + +fun LazyListScope.radioButtonPreference( + key: String, + selected: Boolean, + title: @Composable () -> Unit, + modifier: Modifier = Modifier, + enabled: Boolean = true, + summary: @Composable (() -> Unit)? = null, + widgetContainer: @Composable (() -> Unit)? = null, + onClick: () -> Unit +) { + item(key = key, contentType = "RadioButtonPreference") { + RadioButtonPreference( + selected = selected, + title = title, + modifier = modifier, + enabled = enabled, + summary = summary, + widgetContainer = widgetContainer, + onClick = onClick + ) + } +} + +@Composable +fun RadioButtonPreference( + selected: Boolean, + title: @Composable () -> Unit, + modifier: Modifier = Modifier, + enabled: Boolean = true, + summary: @Composable (() -> Unit)? = null, + widgetContainer: @Composable (() -> Unit)? = null, + onClick: () -> Unit +) { + Preference( + title = title, + modifier = modifier.selectable(selected, enabled, Role.RadioButton, onClick), + enabled = enabled, + icon = { RadioButton(selected = selected, onClick = null, enabled = enabled) }, + summary = summary, + widgetContainer = widgetContainer + ) +} + +@Composable +@Preview(showBackground = true) +private fun RadioButtonPreferencePreview() { + ProvidePreferenceTheme { + RadioButtonPreference( + selected = true, + title = { Text(text = "Radio button preference") }, + modifier = Modifier.fillMaxWidth(), + summary = { Text(text = "Summary") } + ) {} + } +} diff --git a/library/src/main/java/me/zhanghai/compose/preference/ScrollIndicators.kt b/library/src/main/java/me/zhanghai/compose/preference/ScrollIndicators.kt new file mode 100644 index 0000000..2c63f9a --- /dev/null +++ b/library/src/main/java/me/zhanghai/compose/preference/ScrollIndicators.kt @@ -0,0 +1,142 @@ +/* + * Copyright 2023 Google LLC + * + * 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. + */ + +package me.zhanghai.compose.preference + +import androidx.compose.foundation.gestures.Orientation +import androidx.compose.foundation.gestures.ScrollableDefaults +import androidx.compose.foundation.gestures.ScrollableState +import androidx.compose.material3.LocalContentColor +import androidx.compose.ui.Modifier +import androidx.compose.ui.composed +import androidx.compose.ui.draw.drawWithContent +import androidx.compose.ui.geometry.Offset +import androidx.compose.ui.geometry.Size +import androidx.compose.ui.platform.LocalDensity +import androidx.compose.ui.platform.LocalLayoutDirection +import androidx.compose.ui.platform.debugInspectorInfo +import androidx.compose.ui.unit.LayoutDirection +import androidx.compose.ui.unit.dp + +internal fun Modifier.verticalScrollIndicators( + scrollableState: ScrollableState, + reverseScrolling: Boolean = false, + drawTopIndicator: Boolean = true, + drawBottomIndicator: Boolean = true +): Modifier = + scrollIndicators( + scrollableState, + Orientation.Vertical, + reverseScrolling, + drawTopIndicator, + drawBottomIndicator + ) + +internal fun Modifier.horizontalScrollIndicators( + scrollableState: ScrollableState, + reverseScrolling: Boolean = false, + drawStartIndicator: Boolean = true, + drawEndIndicator: Boolean = true +): Modifier = + scrollIndicators( + scrollableState, + Orientation.Horizontal, + reverseScrolling, + drawStartIndicator, + drawEndIndicator + ) + +private fun Modifier.scrollIndicators( + scrollableState: ScrollableState, + orientation: Orientation, + reverseScrolling: Boolean = false, + drawTopStartIndicator: Boolean = true, + drawBottomEndIndicator: Boolean = true +): Modifier = + composed( + debugInspectorInfo { + name = "scrollIndicators" + properties["orientation"] = orientation + properties["reverseScrolling"] = reverseScrolling + properties["scrollableState"] = scrollableState + properties["drawTopStartIndicator"] = drawTopStartIndicator + properties["drawBottomEndIndicator"] = drawBottomEndIndicator + } + ) { + val layoutDirection = LocalLayoutDirection.current + val reverseDirection = + ScrollableDefaults.reverseDirection(layoutDirection, orientation, reverseScrolling) + val drawTopLeftIndicator: Boolean + val drawBottomRightIndicator: Boolean + when (orientation) { + Orientation.Vertical -> { + drawTopLeftIndicator = drawTopStartIndicator + drawBottomRightIndicator = drawBottomEndIndicator + } + Orientation.Horizontal -> { + when (layoutDirection) { + LayoutDirection.Ltr -> { + drawTopLeftIndicator = drawTopStartIndicator + drawBottomRightIndicator = drawBottomEndIndicator + } + LayoutDirection.Rtl -> { + drawTopLeftIndicator = drawBottomEndIndicator + drawBottomRightIndicator = drawTopStartIndicator + } + } + } + } + val color = LocalContentColor.current.copy(alpha = ScrollIndicatorOpacity) + val thickness = with(LocalDensity.current) { ScrollIndicatorThickness.toPx() } + drawWithContent { + drawContent() + val indicatorSize = + when (orientation) { + Orientation.Vertical -> Size(size.width, thickness) + Orientation.Horizontal -> Size(thickness, size.height) + } + if (drawTopLeftIndicator) { + val canScrollUpLeft = + if (reverseDirection) { + scrollableState.canScrollBackward + } else { + scrollableState.canScrollForward + } + if (canScrollUpLeft) { + drawRect(color = color, size = indicatorSize) + } + } + if (drawBottomRightIndicator) { + val canScrollDownRight = + if (reverseDirection) { + scrollableState.canScrollForward + } else { + scrollableState.canScrollBackward + } + val topLeft = + when (orientation) { + Orientation.Vertical -> Offset(0f, size.height - thickness) + Orientation.Horizontal -> Offset(size.width - thickness, 0f) + } + if (canScrollDownRight) { + drawRect(color = color, topLeft = topLeft, size = indicatorSize) + } + } + } + } + +private const val ScrollIndicatorOpacity = 0.12f +private val ScrollIndicatorThickness = 1.dp diff --git a/library/src/main/java/me/zhanghai/compose/preference/SharedPreferencesPreferenceFlow.kt b/library/src/main/java/me/zhanghai/compose/preference/SharedPreferencesPreferenceFlow.kt new file mode 100644 index 0000000..604f277 --- /dev/null +++ b/library/src/main/java/me/zhanghai/compose/preference/SharedPreferencesPreferenceFlow.kt @@ -0,0 +1,50 @@ +/* + * Copyright 2023 Google LLC + * + * 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. + */ + +package me.zhanghai.compose.preference + +import android.content.SharedPreferences +import androidx.core.content.edit +import kotlinx.coroutines.DelicateCoroutinesApi +import kotlinx.coroutines.GlobalScope +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.drop +import kotlinx.coroutines.launch + +@OptIn(DelicateCoroutinesApi::class) +fun SharedPreferences.getPreferenceFlow(): MutableStateFlow = + MutableStateFlow(preferences).also { + GlobalScope.launch { it.drop(1).collect { preferences = it } } + } + +private var SharedPreferences.preferences: Preferences + get() = @Suppress("UNCHECKED_CAST") MapPreferences(all as Map) + set(value) { + edit { + clear() + value.asMap().forEach { (key, value) -> + when (value) { + is Boolean -> putBoolean(key, value) + is Int -> putInt(key, value) + is Long -> putLong(key, value) + is Float -> putFloat(key, value) + is String -> putString(key, value) + is Set<*> -> @Suppress("UNCHECKED_CAST") putStringSet(key, value as Set) + else -> throw IllegalArgumentException("Unsupported type for value $value") + } + } + } + } diff --git a/library/src/main/java/me/zhanghai/compose/preference/SliderPreference.kt b/library/src/main/java/me/zhanghai/compose/preference/SliderPreference.kt new file mode 100644 index 0000000..1c139d0 --- /dev/null +++ b/library/src/main/java/me/zhanghai/compose/preference/SliderPreference.kt @@ -0,0 +1,253 @@ +/* + * Copyright 2023 Google LLC + * + * 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. + */ + +package me.zhanghai.compose.preference + +import android.annotation.SuppressLint +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.lazy.LazyListScope +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.outlined.Info +import androidx.compose.material3.ExperimentalMaterial3Api +import androidx.compose.material3.Icon +import androidx.compose.material3.LocalContentColor +import androidx.compose.material3.LocalMinimumInteractiveComponentEnforcement +import androidx.compose.material3.ProvideTextStyle +import androidx.compose.material3.Slider +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.runtime.CompositionLocalProvider +import androidx.compose.runtime.MutableState +import androidx.compose.runtime.SideEffect +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableFloatStateOf +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.tooling.preview.Preview +import androidx.compose.ui.unit.Dp +import androidx.compose.ui.unit.dp + +inline fun LazyListScope.sliderPreference( + key: String, + defaultValue: Float, + crossinline title: @Composable (Float) -> Unit, + modifier: Modifier = Modifier.fillMaxWidth(), + crossinline rememberState: @Composable () -> MutableState = { + rememberPreferenceState(key, defaultValue) + }, + valueRange: ClosedFloatingPointRange = 0f..1f, + valueSteps: Int = 0, + crossinline rememberSliderState: @Composable (Float) -> MutableState = { + remember { mutableFloatStateOf(it) } + }, + crossinline enabled: (Float) -> Boolean = { true }, + noinline icon: @Composable ((Float) -> Unit)? = null, + noinline summary: @Composable ((Float) -> Unit)? = null, + noinline valueText: @Composable ((Float) -> Unit)? = null +) { + item(key = key, contentType = "SliderPreference") { + val state = rememberState() + val value by state + val sliderState = rememberSliderState(value) + val sliderValue by sliderState + SliderPreference( + state = state, + title = { title(sliderValue) }, + modifier = modifier, + valueRange = valueRange, + valueSteps = valueSteps, + sliderState = sliderState, + enabled = enabled(value), + icon = icon?.let { { it(sliderValue) } }, + summary = summary?.let { { it(sliderValue) } }, + valueText = valueText?.let { { it(sliderValue) } } + ) + } +} + +@Composable +fun SliderPreference( + state: MutableState, + title: @Composable () -> Unit, + modifier: Modifier = Modifier, + valueRange: ClosedFloatingPointRange = 0f..1f, + valueSteps: Int = 0, + sliderState: MutableState = remember { mutableFloatStateOf(state.value) }, + enabled: Boolean = true, + icon: @Composable (() -> Unit)? = null, + summary: @Composable (() -> Unit)? = null, + valueText: @Composable (() -> Unit)? = null +) { + var value by state + var sliderValue by sliderState + SliderPreference( + value = value, + onValueChange = { value = it }, + sliderValue = sliderValue, + onSliderValueChange = { sliderValue = it }, + title = title, + modifier = modifier, + valueRange = valueRange, + valueSteps = valueSteps, + enabled = enabled, + icon = icon, + summary = summary, + valueText = valueText + ) +} + +@Composable +@OptIn(ExperimentalMaterial3Api::class) +fun SliderPreference( + value: Float, + onValueChange: (Float) -> Unit, + sliderValue: Float, + onSliderValueChange: (Float) -> Unit, + title: @Composable () -> Unit, + modifier: Modifier = Modifier, + valueRange: ClosedFloatingPointRange = 0f..1f, + valueSteps: Int = 0, + enabled: Boolean = true, + icon: @Composable (() -> Unit)? = null, + summary: @Composable (() -> Unit)? = null, + valueText: @Composable (() -> Unit)? = null +) { + var lastValue by remember { mutableFloatStateOf(value) } + SideEffect { + if (value != lastValue) { + onSliderValueChange(value) + lastValue = value + } + } + BasicPreference( + textContainer = { + Column { + val theme = LocalPreferenceTheme.current + Column( + modifier = + Modifier.padding( + theme.padding.copy( + start = if (icon != null) 8.dp else Dp.Unspecified, + bottom = 0.dp + ) + ) + ) { + PreferenceDefaults.TitleContainer(title = title, enabled = enabled) + PreferenceDefaults.SummaryContainer(summary = summary, enabled = enabled) + } + Row(verticalAlignment = Alignment.CenterVertically) { + CompositionLocalProvider( + LocalMinimumInteractiveComponentEnforcement provides false + ) { + // onValueChangeFinished() may be invoked before a recomposition has + // happened for onValueChange(), for example in the clicking case, so make + // onValueChange() share the latest value to onValueChangeFinished(). + var latestSliderValue = sliderValue + Slider( + value = sliderValue, + onValueChange = { + onSliderValueChange(it) + latestSliderValue = it + }, + modifier = + Modifier.weight(1f) + .padding( + theme.padding + .copy( + start = + if (icon != null) { + 8.dp + } else { + Dp.Unspecified + }, + top = theme.verticalSpacing, + end = + if (valueText != null) { + theme.horizontalSpacing + } else { + Dp.Unspecified + } + ) + .offset((-8).dp) + ), + enabled = enabled, + valueRange = valueRange, + steps = valueSteps, + onValueChangeFinished = { onValueChange(latestSliderValue) } + ) + } + if (valueText != null) { + Box( + modifier = + Modifier.padding( + theme.padding.copy(start = 0.dp, top = 0.dp, bottom = 0.dp) + ) + ) { + CompositionLocalProvider( + LocalContentColor provides + theme.summaryColor.let { + if (enabled) it else it.copy(alpha = theme.disabledOpacity) + } + ) { + ProvideTextStyle( + value = theme.summaryTextStyle, + content = valueText + ) + } + } + } + } + } + }, + modifier = modifier, + enabled = enabled, + iconContainer = { + PreferenceDefaults.IconContainer( + icon = icon, + enabled = enabled, + excludedEndPadding = 8.dp + ) + } + ) +} + +@Composable +@Preview(showBackground = true) +@SuppressLint("AutoboxingStateCreation") +private fun SliderPreferencePreview() { + ProvidePreferenceTheme { + val state = remember { mutableStateOf(3.5f) } + val sliderState = remember { mutableStateOf(state.value) } + SliderPreference( + state = state, + title = { Text(text = "Slider preference") }, + modifier = Modifier.fillMaxWidth(), + valueRange = 0f..5f, + valueSteps = 9, + sliderState = sliderState, + icon = { Icon(imageVector = Icons.Outlined.Info, contentDescription = null) }, + summary = { Text(text = "Summary") }, + valueText = { Text(text = String.format("%.1f", sliderState.value)) } + ) + } +} diff --git a/library/src/main/java/me/zhanghai/compose/preference/SwitchPreference.kt b/library/src/main/java/me/zhanghai/compose/preference/SwitchPreference.kt new file mode 100644 index 0000000..21d3148 --- /dev/null +++ b/library/src/main/java/me/zhanghai/compose/preference/SwitchPreference.kt @@ -0,0 +1,125 @@ +/* + * Copyright 2023 Google LLC + * + * 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. + */ + +package me.zhanghai.compose.preference + +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.lazy.LazyListScope +import androidx.compose.foundation.selection.toggleable +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.outlined.Info +import androidx.compose.material3.Icon +import androidx.compose.material3.Switch +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.runtime.MutableState +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import androidx.compose.ui.Modifier +import androidx.compose.ui.semantics.Role +import androidx.compose.ui.tooling.preview.Preview + +inline fun LazyListScope.switchPreference( + key: String, + defaultValue: Boolean, + crossinline title: @Composable (Boolean) -> Unit, + modifier: Modifier = Modifier.fillMaxWidth(), + crossinline rememberState: @Composable () -> MutableState = { + rememberPreferenceState(key, defaultValue) + }, + crossinline enabled: (Boolean) -> Boolean = { true }, + noinline icon: @Composable ((Boolean) -> Unit)? = null, + noinline summary: @Composable ((Boolean) -> Unit)? = null +) { + item(key = key, contentType = "SwitchPreference") { + val state = rememberState() + val value by state + SwitchPreference( + state = state, + title = { title(value) }, + modifier = modifier, + enabled = enabled(value), + icon = icon?.let { { it(value) } }, + summary = summary?.let { { it(value) } } + ) + } +} + +@Composable +fun SwitchPreference( + state: MutableState, + title: @Composable () -> Unit, + modifier: Modifier = Modifier, + enabled: Boolean = true, + icon: @Composable (() -> Unit)? = null, + summary: @Composable (() -> Unit)? = null +) { + var value by state + SwitchPreference( + value = value, + onValueChange = { value = it }, + title = title, + modifier = modifier, + enabled = enabled, + icon = icon, + summary = summary + ) +} + +@Composable +fun SwitchPreference( + value: Boolean, + onValueChange: (Boolean) -> Unit, + title: @Composable () -> Unit, + modifier: Modifier = Modifier, + enabled: Boolean = true, + icon: @Composable (() -> Unit)? = null, + summary: @Composable (() -> Unit)? = null +) { + Preference( + title = title, + modifier = modifier.toggleable(value, enabled, Role.Switch, onValueChange), + enabled = enabled, + icon = icon, + summary = summary, + widgetContainer = { + val theme = LocalPreferenceTheme.current + Switch( + checked = value, + onCheckedChange = null, + modifier = Modifier.padding(theme.padding.copy(start = theme.horizontalSpacing)), + enabled = enabled + ) + } + ) +} + +@Composable +@Preview(showBackground = true) +private fun SwitchPreferencePreview() { + ProvidePreferenceTheme { + SwitchPreference( + state = remember { mutableStateOf(true) }, + title = { Text(text = "Switch preference") }, + modifier = Modifier.fillMaxWidth(), + icon = { Icon(imageVector = Icons.Outlined.Info, contentDescription = null) }, + summary = { Text(text = "Summary") } + ) + } +} diff --git a/library/src/main/java/me/zhanghai/compose/preference/TextFieldPreference.kt b/library/src/main/java/me/zhanghai/compose/preference/TextFieldPreference.kt new file mode 100644 index 0000000..ae37430 --- /dev/null +++ b/library/src/main/java/me/zhanghai/compose/preference/TextFieldPreference.kt @@ -0,0 +1,207 @@ +/* + * Copyright 2023 Google LLC + * + * 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. + */ + +package me.zhanghai.compose.preference + +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.lazy.LazyListScope +import androidx.compose.foundation.text.KeyboardActions +import androidx.compose.foundation.text.KeyboardOptions +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.outlined.Info +import androidx.compose.material3.Icon +import androidx.compose.material3.OutlinedTextField +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.MutableState +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.saveable.rememberSaveable +import androidx.compose.runtime.setValue +import androidx.compose.ui.Modifier +import androidx.compose.ui.focus.FocusRequester +import androidx.compose.ui.focus.focusRequester +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.text.TextRange +import androidx.compose.ui.text.input.TextFieldValue +import androidx.compose.ui.tooling.preview.Preview +import androidx.compose.ui.unit.dp + +inline fun LazyListScope.textFieldPreference( + key: String, + defaultValue: T, + crossinline title: @Composable (T) -> Unit, + noinline textToValue: (String) -> T?, + modifier: Modifier = Modifier.fillMaxWidth(), + crossinline rememberState: @Composable () -> MutableState = { + rememberPreferenceState(key, defaultValue) + }, + crossinline enabled: (T) -> Boolean = { true }, + noinline icon: @Composable ((T) -> Unit)? = null, + noinline summary: @Composable ((T) -> Unit)? = null, + noinline valueToText: (T) -> String = { it.toString() }, + noinline textField: + @Composable + (value: TextFieldValue, onValueChange: (TextFieldValue) -> Unit, onOk: () -> Unit) -> Unit = + TextFieldPreferenceDefaults.TextField +) { + item(key = key, contentType = "TextFieldPreference") { + val state = rememberState() + val value by state + TextFieldPreference( + state = state, + title = { title(value) }, + textToValue = textToValue, + modifier = modifier, + enabled = enabled(value), + icon = icon?.let { { it(value) } }, + summary = summary?.let { { it(value) } }, + valueToText = valueToText, + textField = textField + ) + } +} + +@Composable +fun TextFieldPreference( + state: MutableState, + title: @Composable () -> Unit, + textToValue: (String) -> T?, + modifier: Modifier = Modifier, + enabled: Boolean = true, + icon: @Composable (() -> Unit)? = null, + summary: @Composable (() -> Unit)? = null, + valueToText: (T) -> String = { it.toString() }, + textField: + @Composable + (value: TextFieldValue, onValueChange: (TextFieldValue) -> Unit, onOk: () -> Unit) -> Unit = + TextFieldPreferenceDefaults.TextField +) { + var value by state + TextFieldPreference( + value = value, + onValueChange = { value = it }, + title = title, + textToValue = textToValue, + modifier = modifier, + enabled = enabled, + icon = icon, + summary = summary, + valueToText = valueToText, + textField = textField + ) +} + +@Composable +fun TextFieldPreference( + value: T, + onValueChange: (T) -> Unit, + title: @Composable () -> Unit, + textToValue: (String) -> T?, + modifier: Modifier = Modifier, + enabled: Boolean = true, + icon: @Composable (() -> Unit)? = null, + summary: @Composable (() -> Unit)? = null, + valueToText: (T) -> String = { it.toString() }, + textField: + @Composable + (value: TextFieldValue, onValueChange: (TextFieldValue) -> Unit, onOk: () -> Unit) -> Unit = + TextFieldPreferenceDefaults.TextField +) { + var openDialog by rememberSaveable { mutableStateOf(false) } + Preference( + title = title, + modifier = modifier, + enabled = enabled, + icon = icon, + summary = summary + ) { + openDialog = true + } + if (openDialog) { + var dialogText by + rememberSaveable(stateSaver = TextFieldValue.Saver) { + val text = valueToText(value) + mutableStateOf(TextFieldValue(text, TextRange(text.length))) + } + val onOk = { + val dialogValue = textToValue(dialogText.text) + if (dialogValue != null) { + onValueChange(dialogValue) + openDialog = false + } + } + PreferenceAlertDialog( + onDismissRequest = { openDialog = false }, + title = title, + buttons = { + TextButton(onClick = { openDialog = false }) { + Text(text = stringResource(android.R.string.cancel)) + } + TextButton(onClick = onOk) { Text(text = stringResource(android.R.string.ok)) } + } + ) { + val focusRequester = remember { FocusRequester() } + Box( + modifier = + Modifier.fillMaxWidth() + .padding(horizontal = 24.dp) + .focusRequester(focusRequester) + ) { + textField(dialogText, { dialogText = it }, onOk) + } + LaunchedEffect(focusRequester) { focusRequester.requestFocus() } + } + } +} + +@PublishedApi +internal object TextFieldPreferenceDefaults { + val TextField: + @Composable + (value: TextFieldValue, onValueChange: (TextFieldValue) -> Unit, onOk: () -> Unit) -> Unit = + { value, onValueChange, onOk -> + OutlinedTextField( + value = value, + onValueChange = onValueChange, + modifier = Modifier.fillMaxWidth(), + keyboardOptions = KeyboardOptions(autoCorrect = false), + keyboardActions = KeyboardActions { onOk() }, + singleLine = true + ) + } +} + +@Composable +@Preview(showBackground = true) +private fun TextFieldPreferencePreview() { + ProvidePreferenceTheme { + val state = remember { mutableStateOf("Value") } + TextFieldPreference( + state = state, + title = { Text(text = "Text field preference") }, + textToValue = { it }, + modifier = Modifier.fillMaxWidth(), + icon = { Icon(imageVector = Icons.Outlined.Info, contentDescription = null) }, + summary = { Text(text = state.value) } + ) + } +} diff --git a/library/src/main/java/me/zhanghai/compose/preference/TwoTargetIconButtonPreference.kt b/library/src/main/java/me/zhanghai/compose/preference/TwoTargetIconButtonPreference.kt new file mode 100644 index 0000000..a230a42 --- /dev/null +++ b/library/src/main/java/me/zhanghai/compose/preference/TwoTargetIconButtonPreference.kt @@ -0,0 +1,112 @@ +/* + * Copyright 2023 Google LLC + * + * 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. + */ + +package me.zhanghai.compose.preference + +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.lazy.LazyListScope +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.outlined.Info +import androidx.compose.material3.ExperimentalMaterial3Api +import androidx.compose.material3.Icon +import androidx.compose.material3.IconButton +import androidx.compose.material3.IconButtonDefaults +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.ui.Modifier +import androidx.compose.ui.tooling.preview.Preview +import androidx.compose.ui.unit.dp + +fun LazyListScope.twoTargetIconButtonPreference( + key: String, + title: @Composable () -> Unit, + iconButtonIcon: @Composable () -> Unit, + modifier: Modifier = Modifier, + enabled: Boolean = true, + icon: @Composable (() -> Unit)? = null, + summary: @Composable (() -> Unit)? = null, + onClick: (() -> Unit)? = null, + iconButtonEnabled: Boolean = enabled, + onIconButtonClick: () -> Unit +) { + item(key = key, contentType = "TwoTargetIconButtonPreference") { + TwoTargetIconButtonPreference( + title = title, + iconButtonIcon = iconButtonIcon, + modifier = modifier, + enabled = enabled, + icon = icon, + summary = summary, + onClick = onClick, + iconButtonEnabled = iconButtonEnabled, + onIconButtonClick = onIconButtonClick + ) + } +} + +@Composable +@OptIn(ExperimentalMaterial3Api::class) +fun TwoTargetIconButtonPreference( + title: @Composable () -> Unit, + iconButtonIcon: @Composable () -> Unit, + modifier: Modifier = Modifier, + enabled: Boolean = true, + icon: @Composable (() -> Unit)? = null, + summary: @Composable (() -> Unit)? = null, + onClick: (() -> Unit)? = null, + iconButtonEnabled: Boolean = enabled, + onIconButtonClick: () -> Unit +) { + TwoTargetPreference( + title = title, + secondTarget = { + val theme = LocalPreferenceTheme.current + IconButton( + onClick = onIconButtonClick, + modifier = + Modifier.padding( + theme.padding.copy(start = theme.horizontalSpacing).offset((-12).dp) + ), + enabled = iconButtonEnabled, + colors = + IconButtonDefaults.iconButtonColors( + contentColor = theme.iconColor, + disabledContentColor = theme.iconColor.copy(alpha = theme.disabledOpacity) + ), + content = iconButtonIcon + ) + }, + modifier = modifier, + enabled = enabled, + icon = icon, + summary = summary, + onClick = onClick + ) +} + +@Composable +@Preview(showBackground = true) +private fun TwoTargetIconButtonPreferencePreview() { + ProvidePreferenceTheme { + TwoTargetIconButtonPreference( + title = { Text(text = "Two target icon button preference") }, + iconButtonIcon = { Icon(imageVector = Icons.Outlined.Info, contentDescription = null) }, + modifier = Modifier.fillMaxWidth(), + summary = { Text(text = "Summary") } + ) {} + } +} diff --git a/library/src/main/java/me/zhanghai/compose/preference/TwoTargetPreference.kt b/library/src/main/java/me/zhanghai/compose/preference/TwoTargetPreference.kt new file mode 100644 index 0000000..d80a38d --- /dev/null +++ b/library/src/main/java/me/zhanghai/compose/preference/TwoTargetPreference.kt @@ -0,0 +1,90 @@ +/* + * Copyright 2023 Google LLC + * + * 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. + */ + +package me.zhanghai.compose.preference + +import androidx.compose.foundation.background +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.lazy.LazyListScope +import androidx.compose.material3.DividerDefaults +import androidx.compose.runtime.Composable +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier + +fun LazyListScope.twoTargetPreference( + key: String, + title: @Composable () -> Unit, + secondTarget: @Composable () -> Unit, + modifier: Modifier = Modifier.fillMaxWidth(), + enabled: Boolean = true, + icon: @Composable (() -> Unit)? = null, + summary: @Composable (() -> Unit)? = null, + onClick: (() -> Unit)? = null +) { + item(key = key, contentType = "TwoTargetPreference") { + TwoTargetPreference( + title = title, + secondTarget = secondTarget, + modifier = modifier, + enabled = enabled, + icon = icon, + summary = summary, + onClick = onClick + ) + } +} + +@Composable +fun TwoTargetPreference( + title: @Composable () -> Unit, + secondTarget: @Composable () -> Unit, + modifier: Modifier = Modifier, + enabled: Boolean = true, + icon: @Composable (() -> Unit)? = null, + summary: @Composable (() -> Unit)? = null, + onClick: (() -> Unit)? = null +) { + Preference( + title = title, + modifier = modifier, + enabled = enabled, + icon = icon, + summary = summary, + widgetContainer = { + val theme = LocalPreferenceTheme.current + Row( + modifier = Modifier.padding(start = theme.horizontalSpacing), + verticalAlignment = Alignment.CenterVertically + ) { + Box( + modifier = + Modifier.size(DividerDefaults.Thickness, theme.dividerHeight) + .background( + DividerDefaults.color.let { + if (enabled) it else it.copy(alpha = theme.disabledOpacity) + } + ) + ) + secondTarget() + } + }, + onClick = onClick + ) +} diff --git a/library/src/main/java/me/zhanghai/compose/preference/TwoTargetSwitchPreference.kt b/library/src/main/java/me/zhanghai/compose/preference/TwoTargetSwitchPreference.kt new file mode 100644 index 0000000..b95ccd8 --- /dev/null +++ b/library/src/main/java/me/zhanghai/compose/preference/TwoTargetSwitchPreference.kt @@ -0,0 +1,142 @@ +/* + * Copyright 2023 Google LLC + * + * 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. + */ + +package me.zhanghai.compose.preference + +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.lazy.LazyListScope +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.outlined.Info +import androidx.compose.material3.ExperimentalMaterial3Api +import androidx.compose.material3.Icon +import androidx.compose.material3.Switch +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.runtime.MutableState +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import androidx.compose.ui.Modifier +import androidx.compose.ui.tooling.preview.Preview +import androidx.compose.ui.unit.dp + +inline fun LazyListScope.twoTargetSwitchPreference( + key: String, + defaultValue: Boolean, + crossinline title: @Composable (Boolean) -> Unit, + modifier: Modifier = Modifier.fillMaxWidth(), + crossinline rememberState: @Composable () -> MutableState = { + rememberPreferenceState(key, defaultValue) + }, + noinline enabled: (Boolean) -> Boolean = { true }, + noinline icon: @Composable ((Boolean) -> Unit)? = null, + noinline summary: @Composable ((Boolean) -> Unit)? = null, + noinline switchEnabled: (Boolean) -> Boolean = enabled, + noinline onClick: ((Boolean) -> Unit)? = null +) { + item(key = key, contentType = "TwoTargetSwitchPreference") { + val state = rememberState() + val value by state + TwoTargetSwitchPreference( + state = state, + title = { title(value) }, + modifier = modifier, + enabled = enabled(value), + icon = icon?.let { { it(value) } }, + summary = summary?.let { { it(value) } }, + switchEnabled = switchEnabled(value), + onClick = onClick?.let { { it(value) } } + ) + } +} + +@Composable +fun TwoTargetSwitchPreference( + state: MutableState, + title: @Composable () -> Unit, + modifier: Modifier = Modifier, + enabled: Boolean = true, + icon: @Composable (() -> Unit)? = null, + summary: @Composable (() -> Unit)? = null, + switchEnabled: Boolean = enabled, + onClick: (() -> Unit)? = null +) { + var value by state + TwoTargetSwitchPreference( + value = value, + onValueChange = { value = it }, + title = title, + modifier = modifier, + enabled = enabled, + icon = icon, + summary = summary, + switchEnabled = switchEnabled, + onClick = onClick + ) +} + +@Composable +@OptIn(ExperimentalMaterial3Api::class) +fun TwoTargetSwitchPreference( + value: Boolean, + onValueChange: (Boolean) -> Unit, + title: @Composable () -> Unit, + modifier: Modifier = Modifier, + enabled: Boolean = true, + icon: @Composable (() -> Unit)? = null, + summary: @Composable (() -> Unit)? = null, + switchEnabled: Boolean = enabled, + onClick: (() -> Unit)? = null +) { + TwoTargetPreference( + title = title, + secondTarget = { + val theme = LocalPreferenceTheme.current + Switch( + checked = value, + onCheckedChange = onValueChange, + modifier = + Modifier.padding( + theme.padding + .copy(start = theme.horizontalSpacing) + .offset(vertical = (-8).dp) + ), + enabled = switchEnabled + ) + }, + modifier = modifier, + enabled = enabled, + icon = icon, + summary = summary, + onClick = onClick + ) +} + +@Composable +@Preview(showBackground = true) +private fun TwoTargetSwitchPreferencePreview() { + ProvidePreferenceTheme { + TwoTargetSwitchPreference( + state = remember { mutableStateOf(true) }, + title = { Text(text = "Two target switch preference") }, + modifier = Modifier.fillMaxWidth(), + icon = { Icon(imageVector = Icons.Outlined.Info, contentDescription = null) }, + summary = { Text(text = "Summary") } + ) + } +} diff --git a/sample/.gitignore b/sample/.gitignore new file mode 100644 index 0000000..dda6bfc --- /dev/null +++ b/sample/.gitignore @@ -0,0 +1,3 @@ +/.cxx/ +/build/ +/out/ diff --git a/sample/build.gradle.kts b/sample/build.gradle.kts new file mode 100644 index 0000000..25996bc --- /dev/null +++ b/sample/build.gradle.kts @@ -0,0 +1,69 @@ +/* + * Copyright 2023 Google LLC + * + * 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. + */ + +plugins { + id("com.android.application") + kotlin("android") +} + +android { + namespace = "me.zhanghai.compose.preference.sample" + buildToolsVersion = "34.0.0" + compileSdk = 34 + defaultConfig { + applicationId = "me.zhanghai.android.librarytemplate.sample" + minSdk = 21 + targetSdk = 34 + versionCode = (extra["VERSION_CODE"] as String).toInt() + versionName = extra["VERSION_NAME"] as String + } + compileOptions { + sourceCompatibility = JavaVersion.VERSION_1_8 + targetCompatibility = JavaVersion.VERSION_1_8 + } + kotlinOptions { jvmTarget = JavaVersion.VERSION_1_8.toString() } + buildFeatures { compose = true } + composeOptions { kotlinCompilerExtensionVersion = "1.5.5" } + packaging { resources { excludes += "/META-INF/{AL2.0,LGPL2.1}" } } + signingConfigs { + create("release") { + storeFile = File(System.getenv("STORE_FILE") ?: "/dev/null") + storePassword = System.getenv("STORE_PASSWORD") + keyAlias = System.getenv("KEY_ALIAS") + keyPassword = System.getenv("KEY_PASSWORD") + } + } + buildTypes { + release { + isMinifyEnabled = true + isShrinkResources = true + proguardFiles(getDefaultProguardFile("proguard-android-optimize.txt"), "proguard-rules.pro") + signingConfig = signingConfigs.getByName("release") + } + } +} + +dependencies { + implementation(project(":library")) + + implementation(platform("androidx.compose:compose-bom:2023.10.01")) + implementation("androidx.compose.material3:material3") + implementation("androidx.compose.ui:ui-tooling-preview") + debugImplementation("androidx.compose.ui:ui-tooling") + debugImplementation("androidx.compose.ui:ui-test-manifest") + + implementation("androidx.activity:activity-compose:1.8.1") +} diff --git a/sample/proguard-rules.pro b/sample/proguard-rules.pro new file mode 100644 index 0000000..f1b4245 --- /dev/null +++ b/sample/proguard-rules.pro @@ -0,0 +1,21 @@ +# 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 diff --git a/sample/src/main/AndroidManifest.xml b/sample/src/main/AndroidManifest.xml new file mode 100644 index 0000000..6baa697 --- /dev/null +++ b/sample/src/main/AndroidManifest.xml @@ -0,0 +1,43 @@ + + + + + + + + + + + + + + + + diff --git a/sample/src/main/java/me/zhanghai/compose/preference/sample/MainActivity.kt b/sample/src/main/java/me/zhanghai/compose/preference/sample/MainActivity.kt new file mode 100644 index 0000000..5e7f604 --- /dev/null +++ b/sample/src/main/java/me/zhanghai/compose/preference/sample/MainActivity.kt @@ -0,0 +1,29 @@ +/* + * Copyright 2023 Google LLC + * + * 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. + */ + +package me.zhanghai.compose.preference.sample + +import android.os.Bundle +import androidx.activity.ComponentActivity +import androidx.activity.compose.setContent + +class MainActivity : ComponentActivity() { + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + + setContent { SampleApp() } + } +} diff --git a/sample/src/main/java/me/zhanghai/compose/preference/sample/SampleApp.kt b/sample/src/main/java/me/zhanghai/compose/preference/sample/SampleApp.kt new file mode 100644 index 0000000..6dbf80d --- /dev/null +++ b/sample/src/main/java/me/zhanghai/compose/preference/sample/SampleApp.kt @@ -0,0 +1,178 @@ +/* + * Copyright 2023 Google LLC + * + * 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. + */ + +package me.zhanghai.compose.preference.sample + +import androidx.compose.foundation.layout.WindowInsets +import androidx.compose.foundation.layout.WindowInsetsSides +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.only +import androidx.compose.foundation.layout.safeDrawing +import androidx.compose.foundation.lazy.LazyColumn +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.outlined.Settings +import androidx.compose.material3.ExperimentalMaterial3Api +import androidx.compose.material3.Icon +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Scaffold +import androidx.compose.material3.Text +import androidx.compose.material3.TopAppBar +import androidx.compose.material3.TopAppBarDefaults +import androidx.compose.material3.contentColorFor +import androidx.compose.runtime.Composable +import androidx.compose.ui.Modifier +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.input.nestedscroll.nestedScroll +import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.platform.LocalView +import androidx.compose.ui.tooling.preview.Preview +import me.zhanghai.compose.preference.ListPreferenceType +import me.zhanghai.compose.preference.ProvidePreferenceLocals +import me.zhanghai.compose.preference.checkboxPreference +import me.zhanghai.compose.preference.footerPreference +import me.zhanghai.compose.preference.listPreference +import me.zhanghai.compose.preference.multiSelectListPreference +import me.zhanghai.compose.preference.preference +import me.zhanghai.compose.preference.radioButtonPreference +import me.zhanghai.compose.preference.sliderPreference +import me.zhanghai.compose.preference.switchPreference +import me.zhanghai.compose.preference.textFieldPreference +import me.zhanghai.compose.preference.twoTargetIconButtonPreference +import me.zhanghai.compose.preference.twoTargetSwitchPreference + +@Composable +fun SampleApp() { + SampleTheme { ProvidePreferenceLocals { SampleScreen() } } +} + +@Composable +@OptIn(ExperimentalMaterial3Api::class) +fun SampleScreen() { + val windowInsets = WindowInsets.safeDrawing + val scrollBehavior = TopAppBarDefaults.pinnedScrollBehavior() + Scaffold( + modifier = Modifier.fillMaxSize().nestedScroll(scrollBehavior.nestedScrollConnection), + topBar = { + val context = LocalContext.current + val appLabel = + if (LocalView.current.isInEditMode) { + "Sample" + } else { + context.applicationInfo.loadLabel(context.packageManager).toString() + } + TopAppBar( + title = { Text(text = appLabel) }, + modifier = Modifier.fillMaxWidth(), + windowInsets = + windowInsets.only(WindowInsetsSides.Horizontal + WindowInsetsSides.Top), + scrollBehavior = scrollBehavior + ) + }, + containerColor = Color.Transparent, + contentColor = contentColorFor(MaterialTheme.colorScheme.background), + contentWindowInsets = windowInsets + ) { contentPadding -> + LazyColumn(modifier = Modifier.fillMaxSize(), contentPadding = contentPadding) { + preference( + key = "preference", + title = { Text(text = "Preference") }, + summary = { Text(text = "Summary") } + ) {} + checkboxPreference( + key = "checkbox_preference", + defaultValue = false, + title = { Text(text = "Checkbox preference") }, + summary = { Text(text = if (it) "On" else "Off") } + ) + switchPreference( + key = "switch_preference", + defaultValue = false, + title = { Text(text = "Switch preference") }, + summary = { Text(text = if (it) "On" else "Off") } + ) + twoTargetSwitchPreference( + key = "two_target_switch_preference", + defaultValue = false, + title = { Text(text = "Two target switch preference") }, + summary = { Text(text = if (it) "On" else "Off") } + ) {} + twoTargetIconButtonPreference( + key = "two_target_icon_button_preference", + title = { Text(text = "Two target icon button preference") }, + summary = { Text(text = "Summary") }, + onClick = {}, + iconButtonIcon = { + Icon(imageVector = Icons.Outlined.Settings, contentDescription = "Settings") + } + ) {} + sliderPreference( + key = "slider_preference", + defaultValue = 0f, + title = { Text(text = "Slider preference") }, + valueRange = 0f..5f, + valueSteps = 9, + summary = { Text(text = "Summary") }, + valueText = { Text(text = "%.1f".format(it)) } + ) + listPreference( + key = "list_alert_dialog_preference", + defaultValue = "Alpha", + values = listOf("Alpha", "Beta", "Canary"), + title = { Text(text = "List preference (alert dialog)") }, + summary = { Text(text = it) } + ) + listPreference( + key = "list_dropdown_menu_preference", + defaultValue = "Alpha", + values = listOf("Alpha", "Beta", "Canary"), + title = { Text(text = "List preference (dropdown menu)") }, + summary = { Text(text = it) }, + type = ListPreferenceType.DROPDOWN_MENU + ) + multiSelectListPreference( + key = "multi_select_list_preference", + defaultValue = setOf("Alpha", "Beta"), + values = listOf("Alpha", "Beta", "Canary"), + title = { Text(text = "Multi-select list preference") }, + summary = { Text(text = it.sorted().joinToString(", ")) } + ) + textFieldPreference( + key = "text_field_preference", + defaultValue = "Value", + title = { Text(text = "Text field preference") }, + textToValue = { it }, + summary = { Text(text = it) } + ) + radioButtonPreference( + key = "radio_button_preference", + selected = true, + title = { Text(text = "Radio button preference") }, + summary = { Text(text = "Summary") } + ) {} + footerPreference( + key = "footer_preference", + summary = { Text(text = "Footer preference summary") } + ) + } + } +} + +@Composable +@Preview(showBackground = true) +fun SampleAppPreview() { + SampleApp() +} diff --git a/sample/src/main/java/me/zhanghai/compose/preference/sample/SampleTheme.kt b/sample/src/main/java/me/zhanghai/compose/preference/sample/SampleTheme.kt new file mode 100644 index 0000000..26a88fa --- /dev/null +++ b/sample/src/main/java/me/zhanghai/compose/preference/sample/SampleTheme.kt @@ -0,0 +1,72 @@ +/* + * Copyright 2023 Google LLC + * + * 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. + */ + +package me.zhanghai.compose.preference.sample + +import android.app.Activity +import android.graphics.drawable.ColorDrawable +import android.os.Build +import androidx.compose.foundation.isSystemInDarkTheme +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.darkColorScheme +import androidx.compose.material3.dynamicDarkColorScheme +import androidx.compose.material3.dynamicLightColorScheme +import androidx.compose.material3.lightColorScheme +import androidx.compose.runtime.Composable +import androidx.compose.runtime.SideEffect +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.graphics.toArgb +import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.platform.LocalView +import androidx.core.view.WindowCompat + +@Composable +fun SampleTheme( + darkTheme: Boolean = isSystemInDarkTheme(), + dynamicColor: Boolean = true, + content: @Composable () -> Unit +) { + val context = LocalContext.current + val colorScheme = + when { + dynamicColor && Build.VERSION.SDK_INT >= Build.VERSION_CODES.S -> { + if (darkTheme) dynamicDarkColorScheme(context) else dynamicLightColorScheme(context) + } + darkTheme -> darkColorScheme() + else -> lightColorScheme() + } + + val view = LocalView.current + if (!view.isInEditMode) { + SideEffect { + val window = (context as Activity).window + WindowCompat.setDecorFitsSystemWindows(window, false) + val windowBackgroundColor = colorScheme.background.toArgb() + window.setBackgroundDrawable(ColorDrawable(windowBackgroundColor)) + val insetsController = WindowCompat.getInsetsController(window, view) + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { + window.statusBarColor = Color.Transparent.toArgb() + insetsController.isAppearanceLightStatusBars = !darkTheme + } + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O_MR1) { + window.navigationBarColor = Color.Transparent.toArgb() + insetsController.isAppearanceLightNavigationBars = !darkTheme + } + } + } + + MaterialTheme(colorScheme = colorScheme, content = content) +} diff --git a/sample/src/main/res/values-night/themes.xml b/sample/src/main/res/values-night/themes.xml new file mode 100644 index 0000000..e55f84d --- /dev/null +++ b/sample/src/main/res/values-night/themes.xml @@ -0,0 +1,21 @@ + + + + + + + + + +