├── web ├── .gitignore ├── src │ └── jsMain │ │ ├── resources │ │ ├── styles.css │ │ └── index.html │ │ └── kotlin │ │ ├── BrowserViewportWindow.kt │ │ └── main.js.kt └── build.gradle.kts ├── android ├── .gitignore ├── src │ └── main │ │ ├── res │ │ ├── mipmap-hdpi │ │ │ ├── ic_launcher.webp │ │ │ └── ic_launcher_round.webp │ │ ├── mipmap-mdpi │ │ │ ├── ic_launcher.webp │ │ │ └── ic_launcher_round.webp │ │ ├── mipmap-xhdpi │ │ │ ├── ic_launcher.webp │ │ │ └── ic_launcher_round.webp │ │ ├── mipmap-xxhdpi │ │ │ ├── ic_launcher.webp │ │ │ └── ic_launcher_round.webp │ │ ├── mipmap-xxxhdpi │ │ │ ├── ic_launcher.webp │ │ │ └── ic_launcher_round.webp │ │ ├── values │ │ │ ├── strings.xml │ │ │ └── themes.xml │ │ ├── mipmap-anydpi-v26 │ │ │ ├── ic_launcher.xml │ │ │ └── ic_launcher_round.xml │ │ ├── drawable-v24 │ │ │ └── ic_launcher_foreground.xml │ │ └── drawable │ │ │ └── ic_launcher_background.xml │ │ ├── kotlin │ │ └── org │ │ │ └── burnoutcrew │ │ │ └── android │ │ │ └── ui │ │ │ ├── theme │ │ │ ├── Color.kt │ │ │ ├── Shape.kt │ │ │ ├── Type.kt │ │ │ └── Theme.kt │ │ │ ├── reorderlist │ │ │ ├── ItemData.kt │ │ │ ├── ImageListViewModel.kt │ │ │ ├── ReorderListViewModel.kt │ │ │ ├── ReorderImageList.kt │ │ │ ├── ReorderGrid.kt │ │ │ └── ReorderList.kt │ │ │ ├── MainActivity.kt │ │ │ └── Root.kt │ │ └── AndroidManifest.xml └── build.gradle.kts ├── desktop ├── .gitignore ├── build.gradle.kts └── src │ └── jvmMain │ └── kotlin │ └── Main.kt ├── reorderable ├── .gitignore ├── src │ └── commonMain │ │ └── kotlin │ │ └── org │ │ └── burnoutcrew │ │ └── reorderable │ │ ├── ItemPosition.kt │ │ ├── DragCancelledAnimation.kt │ │ ├── DetectReorder.kt │ │ ├── Reorderable.kt │ │ ├── ReorderableItem.kt │ │ ├── ReorderableLazyGridState.kt │ │ ├── ReorderableLazyListState.kt │ │ ├── DragGesture.kt │ │ └── ReorderableState.kt └── build.gradle.kts ├── readme ├── sample.gif └── desktop.gif ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── .gitignore ├── settings.gradle.kts ├── .github ├── dependabot.yml └── workflows │ └── pull-request.yml ├── gradle.properties ├── gradlew.bat ├── README.md ├── gradlew └── LICENSE /web/.gitignore: -------------------------------------------------------------------------------- 1 | /build -------------------------------------------------------------------------------- /android/.gitignore: -------------------------------------------------------------------------------- 1 | /build -------------------------------------------------------------------------------- /desktop/.gitignore: -------------------------------------------------------------------------------- 1 | /build -------------------------------------------------------------------------------- /reorderable/.gitignore: -------------------------------------------------------------------------------- 1 | /build -------------------------------------------------------------------------------- /readme/sample.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aclassen/ComposeReorderable/HEAD/readme/sample.gif -------------------------------------------------------------------------------- /readme/desktop.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aclassen/ComposeReorderable/HEAD/readme/desktop.gif -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aclassen/ComposeReorderable/HEAD/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /android/src/main/res/mipmap-hdpi/ic_launcher.webp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aclassen/ComposeReorderable/HEAD/android/src/main/res/mipmap-hdpi/ic_launcher.webp -------------------------------------------------------------------------------- /android/src/main/res/mipmap-mdpi/ic_launcher.webp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aclassen/ComposeReorderable/HEAD/android/src/main/res/mipmap-mdpi/ic_launcher.webp -------------------------------------------------------------------------------- /android/src/main/res/mipmap-xhdpi/ic_launcher.webp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aclassen/ComposeReorderable/HEAD/android/src/main/res/mipmap-xhdpi/ic_launcher.webp -------------------------------------------------------------------------------- /android/src/main/res/mipmap-xxhdpi/ic_launcher.webp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aclassen/ComposeReorderable/HEAD/android/src/main/res/mipmap-xxhdpi/ic_launcher.webp -------------------------------------------------------------------------------- /android/src/main/res/mipmap-xxxhdpi/ic_launcher.webp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aclassen/ComposeReorderable/HEAD/android/src/main/res/mipmap-xxxhdpi/ic_launcher.webp -------------------------------------------------------------------------------- /android/src/main/res/mipmap-hdpi/ic_launcher_round.webp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aclassen/ComposeReorderable/HEAD/android/src/main/res/mipmap-hdpi/ic_launcher_round.webp -------------------------------------------------------------------------------- /android/src/main/res/mipmap-mdpi/ic_launcher_round.webp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aclassen/ComposeReorderable/HEAD/android/src/main/res/mipmap-mdpi/ic_launcher_round.webp -------------------------------------------------------------------------------- /android/src/main/res/mipmap-xhdpi/ic_launcher_round.webp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aclassen/ComposeReorderable/HEAD/android/src/main/res/mipmap-xhdpi/ic_launcher_round.webp -------------------------------------------------------------------------------- /android/src/main/res/mipmap-xxhdpi/ic_launcher_round.webp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aclassen/ComposeReorderable/HEAD/android/src/main/res/mipmap-xxhdpi/ic_launcher_round.webp -------------------------------------------------------------------------------- /reorderable/src/commonMain/kotlin/org/burnoutcrew/reorderable/ItemPosition.kt: -------------------------------------------------------------------------------- 1 | package org.burnoutcrew.reorderable 2 | 3 | data class ItemPosition(val index: Int, val key: Any?) -------------------------------------------------------------------------------- /web/src/jsMain/resources/styles.css: -------------------------------------------------------------------------------- 1 | #root { 2 | width: 100%; 3 | height: 100vh; 4 | } 5 | 6 | #root > .compose-web-column > div { 7 | position: relative; 8 | } 9 | -------------------------------------------------------------------------------- /android/src/main/res/mipmap-xxxhdpi/ic_launcher_round.webp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aclassen/ComposeReorderable/HEAD/android/src/main/res/mipmap-xxxhdpi/ic_launcher_round.webp -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | *.iml 2 | .gradle 3 | /local.properties 4 | .idea 5 | .DS_Store 6 | /build 7 | /captures 8 | .externalNativeBuild 9 | .cxx 10 | local.properties 11 | .idea/jarRepositories.xml 12 | -------------------------------------------------------------------------------- /android/src/main/res/values/strings.xml: -------------------------------------------------------------------------------- 1 | 2 | Lazy reorder list 3 | Header 4 | Footer 5 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionBase=GRADLE_USER_HOME 2 | distributionPath=wrapper/dists 3 | distributionUrl=https\://services.gradle.org/distributions/gradle-7.5.1-bin.zip 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | -------------------------------------------------------------------------------- /android/src/main/kotlin/org/burnoutcrew/android/ui/theme/Color.kt: -------------------------------------------------------------------------------- 1 | package org.burnoutcrew.android.ui.theme 2 | 3 | import androidx.compose.ui.graphics.Color 4 | 5 | val Purple200 = Color(0xFFBB86FC) 6 | val Purple500 = Color(0xFF6200EE) 7 | val Purple700 = Color(0xFF3700B3) 8 | val Teal200 = Color(0xFF03DAC5) -------------------------------------------------------------------------------- /android/src/main/res/mipmap-anydpi-v26/ic_launcher.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | -------------------------------------------------------------------------------- /android/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | -------------------------------------------------------------------------------- /android/src/main/res/values/themes.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 7 | -------------------------------------------------------------------------------- /settings.gradle.kts: -------------------------------------------------------------------------------- 1 | pluginManagement { 2 | repositories { 3 | google() 4 | gradlePluginPortal() 5 | mavenCentral() 6 | maven("https://maven.pkg.jetbrains.space/public/p/compose/dev") 7 | } 8 | 9 | } 10 | rootProject.name = "ComposeReorderList" 11 | 12 | 13 | include(":android") 14 | include(":desktop") 15 | include(":reorderable") 16 | include(":web") 17 | 18 | -------------------------------------------------------------------------------- /android/src/main/kotlin/org/burnoutcrew/android/ui/theme/Shape.kt: -------------------------------------------------------------------------------- 1 | package org.burnoutcrew.android.ui.theme 2 | 3 | import androidx.compose.foundation.shape.RoundedCornerShape 4 | import androidx.compose.material.Shapes 5 | import androidx.compose.ui.unit.dp 6 | 7 | val Shapes = Shapes( 8 | small = RoundedCornerShape(4.dp), 9 | medium = RoundedCornerShape(4.dp), 10 | large = RoundedCornerShape(0.dp) 11 | ) -------------------------------------------------------------------------------- /web/src/jsMain/resources/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | ComposeReorderableDemo 6 | 7 | 8 | 9 | 10 |
11 | 12 |
13 | 14 | 15 | 16 | -------------------------------------------------------------------------------- /android/src/main/kotlin/org/burnoutcrew/android/ui/theme/Type.kt: -------------------------------------------------------------------------------- 1 | package org.burnoutcrew.android.ui.theme 2 | 3 | import androidx.compose.material.Typography 4 | import androidx.compose.ui.text.TextStyle 5 | import androidx.compose.ui.text.font.FontFamily 6 | import androidx.compose.ui.text.font.FontWeight 7 | import androidx.compose.ui.unit.sp 8 | 9 | // Set of Material typography styles to start with 10 | val Typography = Typography( 11 | body1 = TextStyle( 12 | fontFamily = FontFamily.Default, 13 | fontWeight = FontWeight.Normal, 14 | fontSize = 16.sp 15 | ) 16 | ) -------------------------------------------------------------------------------- /.github/dependabot.yml: -------------------------------------------------------------------------------- 1 | # To get started with Dependabot version updates, you'll need to specify which 2 | # package ecosystems to update and where the package manifests are located. 3 | # Please see the documentation for all configuration options: 4 | # https://help.github.com/github/administering-a-repository/configuration-options-for-dependency-updates 5 | 6 | version: 2 7 | updates: 8 | - package-ecosystem: "gradle" # See documentation for possible values 9 | directory: "/" # Location of package manifests 10 | schedule: 11 | interval: "daily" 12 | open-pull-requests-limit: 20 13 | - package-ecosystem: "github-actions" # See documentation for possible values 14 | directory: "" # Location of package manifests 15 | schedule: 16 | interval: "daily" 17 | open-pull-requests-limit: 20 18 | -------------------------------------------------------------------------------- /android/src/main/kotlin/org/burnoutcrew/android/ui/reorderlist/ItemData.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2022 André Claßen 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package org.burnoutcrew.android.ui.reorderlist 17 | 18 | data class ItemData(val title: String, val key: String, val isLocked: Boolean = false) -------------------------------------------------------------------------------- /android/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 11 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | -------------------------------------------------------------------------------- /desktop/build.gradle.kts: -------------------------------------------------------------------------------- 1 | import org.jetbrains.compose.compose 2 | import org.jetbrains.compose.desktop.application.dsl.TargetFormat 3 | 4 | plugins { 5 | kotlin("multiplatform") 6 | id("org.jetbrains.compose") 7 | } 8 | 9 | kotlin { 10 | jvm { 11 | compilations.all { 12 | kotlinOptions.jvmTarget = "11" 13 | } 14 | } 15 | sourceSets { 16 | val jvmMain by getting { 17 | dependencies { 18 | implementation(project(":reorderable")) 19 | implementation(compose.desktop.currentOs) 20 | } 21 | } 22 | } 23 | } 24 | 25 | compose.desktop { 26 | application { 27 | mainClass = "MainKt" 28 | nativeDistributions { 29 | targetFormats(TargetFormat.Dmg, TargetFormat.Msi, TargetFormat.Deb) 30 | packageName = "jvm" 31 | packageVersion = "1.0.0" 32 | } 33 | } 34 | } -------------------------------------------------------------------------------- /gradle.properties: -------------------------------------------------------------------------------- 1 | ## For more details on how to configure your build environment visit 2 | # http://www.gradle.org/docs/current/userguide/build_environment.html 3 | # 4 | # Specifies the JVM arguments used for the daemon process. 5 | # The setting is particularly useful for tweaking memory settings. 6 | # Default value: -Xmx1024m -XX:MaxPermSize=256m 7 | # org.gradle.jvmargs=-Xmx2048m -XX:MaxPermSize=512m -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8 8 | # 9 | # When configured, Gradle will run in incubating parallel mode. 10 | # This option should only be used with decoupled projects. More details, visit 11 | # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects 12 | # org.gradle.parallel=true 13 | #Tue May 17 23:35:28 CEST 2022 14 | kotlin.code.style=official 15 | org.gradle.jvmargs=-Xmx2048M -Dkotlin.daemon.jvm.options\="-Xmx2048M" 16 | android.useAndroidX=true 17 | 18 | org.jetbrains.compose.experimental.jscanvas.enabled=true -------------------------------------------------------------------------------- /.github/workflows/pull-request.yml: -------------------------------------------------------------------------------- 1 | name: Pull request workflow 2 | 3 | on: 4 | pull_request: 5 | branches: [ main ] 6 | 7 | jobs: 8 | # This workflow contains a single job called "build" 9 | build: 10 | # The type of runner that the job will run on 11 | runs-on: ubuntu-latest 12 | 13 | # Steps represent a sequence of tasks that will be executed as part of the job 14 | steps: 15 | # Checks-out your repository under $GITHUB_WORKSPACE, so your job can access it 16 | - name: Check out code 17 | uses: actions/checkout@v3.3.0 18 | with: 19 | fetch-depth: '0' 20 | 21 | - name: Check out java 22 | uses: actions/setup-java@v2 23 | with: 24 | distribution: 'adopt' 25 | java-version: 11 26 | 27 | - name: Run Checks 28 | run: ./gradlew check 29 | 30 | - name: Upload reports 31 | uses: actions/upload-artifact@v2 32 | if: failure() 33 | with: 34 | name: Reports 35 | path: '**/build/reports/*' 36 | retention-days: 2 -------------------------------------------------------------------------------- /android/src/main/kotlin/org/burnoutcrew/android/ui/theme/Theme.kt: -------------------------------------------------------------------------------- 1 | package org.burnoutcrew.android.ui.theme 2 | 3 | import androidx.compose.foundation.isSystemInDarkTheme 4 | import androidx.compose.material.MaterialTheme 5 | import androidx.compose.material.darkColors 6 | import androidx.compose.material.lightColors 7 | import androidx.compose.runtime.Composable 8 | 9 | private val DarkColorPalette = darkColors( 10 | primary = Purple200, 11 | primaryVariant = Purple700, 12 | secondary = Teal200 13 | ) 14 | 15 | private val LightColorPalette = lightColors( 16 | primary = Purple500, 17 | primaryVariant = Purple700, 18 | secondary = Teal200 19 | ) 20 | 21 | @Composable 22 | fun ReorderListTheme(darkTheme: Boolean = isSystemInDarkTheme(), content: @Composable () -> Unit) { 23 | val colors = if (darkTheme) { 24 | DarkColorPalette 25 | } else { 26 | LightColorPalette 27 | } 28 | 29 | MaterialTheme( 30 | colors = colors, 31 | typography = Typography, 32 | shapes = Shapes, 33 | content = content 34 | ) 35 | } -------------------------------------------------------------------------------- /android/src/main/kotlin/org/burnoutcrew/android/ui/MainActivity.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2021 André Claßen 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package org.burnoutcrew.android.ui 17 | 18 | import android.os.Bundle 19 | import androidx.activity.ComponentActivity 20 | import androidx.activity.compose.setContent 21 | 22 | class MainActivity : ComponentActivity() { 23 | override fun onCreate(savedInstanceState: Bundle?) { 24 | super.onCreate(savedInstanceState) 25 | setContent { 26 | Root() 27 | } 28 | } 29 | } -------------------------------------------------------------------------------- /android/build.gradle.kts: -------------------------------------------------------------------------------- 1 | plugins { 2 | id("org.jetbrains.compose") 3 | id("com.android.application") 4 | kotlin("android") 5 | } 6 | 7 | dependencies { 8 | implementation(project(":reorderable")) 9 | implementation("androidx.compose.runtime:runtime:1.3.3") 10 | implementation("androidx.compose.material:material:1.3.1") 11 | implementation("androidx.activity:activity-compose:1.6.1") 12 | implementation("com.google.android.material:material:1.8.0") 13 | implementation("androidx.lifecycle:lifecycle-viewmodel-ktx:2.5.1") 14 | implementation("androidx.lifecycle:lifecycle-viewmodel-compose:2.5.1") 15 | implementation("androidx.navigation:navigation-compose:2.5.3") 16 | implementation("io.coil-kt:coil-compose:2.2.2") 17 | } 18 | 19 | android { 20 | 21 | sourceSets { 22 | map { it.java.srcDir("src/${it.name}/kotlin") } 23 | } 24 | val minSdkVersion: Int by rootProject.extra 25 | val targetSdkVersion: Int by rootProject.extra 26 | val compileSdkVersion: Int by rootProject.extra 27 | compileSdk = compileSdkVersion 28 | defaultConfig { 29 | minSdk = minSdkVersion 30 | targetSdk = targetSdkVersion 31 | versionCode = 1 32 | versionName = "1.0" 33 | } 34 | 35 | compileOptions { 36 | sourceCompatibility = JavaVersion.VERSION_11 37 | targetCompatibility = JavaVersion.VERSION_11 38 | } 39 | 40 | kotlinOptions { 41 | jvmTarget = "1.8" 42 | } 43 | namespace = "org.burnoutcrew.android" 44 | } -------------------------------------------------------------------------------- /web/build.gradle.kts: -------------------------------------------------------------------------------- 1 | import org.jetbrains.compose.compose 2 | import org.jetbrains.compose.desktop.application.dsl.TargetFormat 3 | import org.jetbrains.kotlin.gradle.tasks.KotlinCompile 4 | import org.jetbrains.kotlin.gradle.targets.js.nodejs.NodeJsRootExtension 5 | 6 | plugins { 7 | kotlin("multiplatform") 8 | id("org.jetbrains.compose") 9 | } 10 | 11 | repositories { 12 | google() 13 | mavenCentral() 14 | maven("https://maven.pkg.jetbrains.space/public/p/compose/dev") 15 | } 16 | 17 | kotlin { 18 | js(IR) { 19 | browser { 20 | testTask { 21 | testLogging.showStandardStreams = true 22 | useKarma { 23 | useChromeHeadless() 24 | useFirefox() 25 | } 26 | } 27 | } 28 | binaries.executable() 29 | } 30 | sourceSets { 31 | val jsMain by getting { 32 | dependencies { 33 | implementation(compose.web.core) 34 | implementation(compose.runtime) 35 | implementation(compose.material) 36 | implementation(project(":reorderable")) 37 | } 38 | } 39 | val jsTest by getting { 40 | dependencies { 41 | implementation(kotlin("test-js")) 42 | } 43 | } 44 | } 45 | } 46 | 47 | compose.experimental { 48 | web.application {} 49 | } 50 | 51 | afterEvaluate { 52 | rootProject.extensions.configure { 53 | // versions.webpackDevServer.version = "4.0.0" 54 | // versions.webpackCli.version = "4.9.0" 55 | // nodeVersion = "16.0.0" 56 | } 57 | } -------------------------------------------------------------------------------- /android/src/main/kotlin/org/burnoutcrew/android/ui/reorderlist/ImageListViewModel.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2022 André Claßen 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package org.burnoutcrew.android.ui.reorderlist 17 | 18 | import androidx.compose.runtime.getValue 19 | import androidx.compose.runtime.mutableStateOf 20 | import androidx.compose.runtime.setValue 21 | import androidx.lifecycle.ViewModel 22 | import org.burnoutcrew.reorderable.ItemPosition 23 | import kotlin.random.Random 24 | 25 | 26 | class ImageListViewModel : ViewModel() { 27 | val headerImage = "https://picsum.photos/seed/compose${Random.nextInt(Int.MAX_VALUE)}/400/200" 28 | val footerImage = "https://picsum.photos/seed/compose${Random.nextInt(Int.MAX_VALUE)}/400/200" 29 | var images by mutableStateOf(List(20) { "https://picsum.photos/seed/compose$it/200/300" }) 30 | fun onMove(from: ItemPosition, to: ItemPosition) { 31 | images = images.toMutableList().apply { 32 | add(images.indexOfFirst { it == to.key }, removeAt(images.indexOfFirst { it == from.key })) 33 | } 34 | } 35 | 36 | fun canDragOver(draggedOver: ItemPosition, dragging: ItemPosition) = images.any { it == draggedOver.key } 37 | } -------------------------------------------------------------------------------- /android/src/main/kotlin/org/burnoutcrew/android/ui/reorderlist/ReorderListViewModel.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2022 André Claßen 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package org.burnoutcrew.android.ui.reorderlist 17 | 18 | import androidx.compose.runtime.getValue 19 | import androidx.compose.runtime.mutableStateOf 20 | import androidx.compose.runtime.setValue 21 | import androidx.lifecycle.ViewModel 22 | import org.burnoutcrew.reorderable.ItemPosition 23 | 24 | class ReorderListViewModel : ViewModel() { 25 | var cats by mutableStateOf(List(500) { ItemData("Cat $it", "id$it") }) 26 | var dogs by mutableStateOf(List(500) { 27 | if (it.mod(10) == 0) ItemData("Locked", "id$it", true) else ItemData("Dog $it", "id$it") 28 | }) 29 | 30 | fun moveCat(from: ItemPosition, to: ItemPosition) { 31 | cats = cats.toMutableList().apply { 32 | add(to.index, removeAt(from.index)) 33 | } 34 | } 35 | 36 | fun moveDog(from: ItemPosition, to: ItemPosition) { 37 | dogs = dogs.toMutableList().apply { 38 | add(to.index, removeAt(from.index)) 39 | } 40 | } 41 | 42 | fun isDogDragEnabled(draggedOver: ItemPosition, dragging: ItemPosition) = dogs.getOrNull(draggedOver.index)?.isLocked != true 43 | } -------------------------------------------------------------------------------- /android/src/main/res/drawable-v24/ic_launcher_foreground.xml: -------------------------------------------------------------------------------- 1 | 7 | 8 | 9 | 15 | 18 | 21 | 22 | 23 | 24 | 30 | -------------------------------------------------------------------------------- /reorderable/src/commonMain/kotlin/org/burnoutcrew/reorderable/DragCancelledAnimation.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2022 André Claßen 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package org.burnoutcrew.reorderable 17 | 18 | import androidx.compose.animation.core.Animatable 19 | import androidx.compose.animation.core.Spring 20 | import androidx.compose.animation.core.VectorConverter 21 | import androidx.compose.animation.core.VisibilityThreshold 22 | import androidx.compose.animation.core.spring 23 | import androidx.compose.runtime.getValue 24 | import androidx.compose.runtime.mutableStateOf 25 | import androidx.compose.runtime.setValue 26 | import androidx.compose.ui.geometry.Offset 27 | 28 | interface DragCancelledAnimation { 29 | suspend fun dragCancelled(position: ItemPosition, offset: Offset) 30 | val position: ItemPosition? 31 | val offset: Offset 32 | } 33 | 34 | class NoDragCancelledAnimation : DragCancelledAnimation { 35 | override suspend fun dragCancelled(position: ItemPosition, offset: Offset) {} 36 | override val position: ItemPosition? = null 37 | override val offset: Offset = Offset.Zero 38 | } 39 | 40 | class SpringDragCancelledAnimation(private val stiffness: Float = Spring.StiffnessMediumLow) : DragCancelledAnimation { 41 | private val animatable = Animatable(Offset.Zero, Offset.VectorConverter) 42 | override val offset: Offset 43 | get() = animatable.value 44 | 45 | override var position by mutableStateOf(null) 46 | private set 47 | 48 | override suspend fun dragCancelled(position: ItemPosition, offset: Offset) { 49 | this.position = position 50 | animatable.snapTo(offset) 51 | animatable.animateTo( 52 | Offset.Zero, 53 | spring(stiffness = stiffness, visibilityThreshold = Offset.VisibilityThreshold) 54 | ) 55 | this.position = null 56 | } 57 | } -------------------------------------------------------------------------------- /reorderable/src/commonMain/kotlin/org/burnoutcrew/reorderable/DetectReorder.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2022 André Claßen 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package org.burnoutcrew.reorderable 17 | 18 | import androidx.compose.foundation.gestures.awaitFirstDown 19 | import androidx.compose.foundation.gestures.forEachGesture 20 | import androidx.compose.ui.Modifier 21 | import androidx.compose.ui.geometry.Offset 22 | import androidx.compose.ui.input.pointer.PointerInputChange 23 | import androidx.compose.ui.input.pointer.pointerInput 24 | 25 | fun Modifier.detectReorder(state: ReorderableState<*>) = 26 | this.then( 27 | Modifier.pointerInput(Unit) { 28 | forEachGesture { 29 | awaitPointerEventScope { 30 | val down = awaitFirstDown(requireUnconsumed = false) 31 | var drag: PointerInputChange? 32 | var overSlop = Offset.Zero 33 | do { 34 | drag = awaitPointerSlopOrCancellation(down.id, down.type) { change, over -> 35 | change.consume() 36 | overSlop = over 37 | } 38 | } while (drag != null && !drag.isConsumed) 39 | if (drag != null) { 40 | state.interactions.trySend(StartDrag(down.id, overSlop)) 41 | } 42 | } 43 | } 44 | } 45 | ) 46 | 47 | 48 | fun Modifier.detectReorderAfterLongPress(state: ReorderableState<*>) = 49 | this.then( 50 | Modifier.pointerInput(Unit) { 51 | forEachGesture { 52 | val down = awaitPointerEventScope { 53 | awaitFirstDown(requireUnconsumed = false) 54 | } 55 | awaitLongPressOrCancellation(down)?.also { 56 | state.interactions.trySend(StartDrag(down.id)) 57 | } 58 | } 59 | } 60 | ) -------------------------------------------------------------------------------- /web/src/jsMain/kotlin/BrowserViewportWindow.kt: -------------------------------------------------------------------------------- 1 | // From Slack by OliverO 2 | // See: https://kotlinlang.slack.com/archives/C01F2HV7868/p1660083429206369?thread_ts=1660083398.571449&cid=C01F2HV7868 3 | 4 | @file:Suppress( 5 | "INVISIBLE_MEMBER", 6 | "INVISIBLE_REFERENCE", 7 | "EXPOSED_PARAMETER_TYPE" 8 | ) // WORKAROUND: ComposeWindow and ComposeLayer are internal 9 | 10 | import androidx.compose.runtime.Composable 11 | import androidx.compose.ui.window.ComposeWindow 12 | import kotlinx.browser.document 13 | import kotlinx.browser.window 14 | import org.w3c.dom.HTMLCanvasElement 15 | import org.w3c.dom.HTMLStyleElement 16 | import org.w3c.dom.HTMLTitleElement 17 | 18 | private const val CANVAS_ELEMENT_ID = "ComposeTarget" // Hardwired into ComposeWindow 19 | 20 | /** 21 | * A Skiko/Canvas-based top-level window using the browser's entire viewport. Supports resizing. 22 | */ 23 | fun BrowserViewportWindow( 24 | title: String = "Untitled", 25 | content: @Composable ComposeWindow.() -> Unit 26 | ) { 27 | val htmlHeadElement = document.head!! 28 | htmlHeadElement.appendChild( 29 | (document.createElement("style") as HTMLStyleElement).apply { 30 | type = "text/css" 31 | appendChild( 32 | document.createTextNode( 33 | """ 34 | html, body { 35 | overflow: hidden; 36 | margin: 0 !important; 37 | padding: 0 !important; 38 | } 39 | #$CANVAS_ELEMENT_ID { 40 | outline: none; 41 | } 42 | """.trimIndent() 43 | ) 44 | ) 45 | } 46 | ) 47 | 48 | fun HTMLCanvasElement.fillViewportSize() { 49 | setAttribute("width", "${window.innerWidth}") 50 | setAttribute("height", "${window.innerHeight}") 51 | } 52 | 53 | val canvas = (document.getElementById(CANVAS_ELEMENT_ID) as HTMLCanvasElement).apply { 54 | fillViewportSize() 55 | } 56 | 57 | ComposeWindow().apply { 58 | window.addEventListener("resize", { 59 | canvas.fillViewportSize() 60 | layer.layer.attachTo(canvas) 61 | val scale = layer.layer.contentScale 62 | layer.setSize((canvas.width / scale).toInt(), (canvas.height / scale).toInt()) 63 | layer.layer.needRedraw() 64 | }) 65 | 66 | // WORKAROUND: ComposeWindow does not implement `setTitle(title)` 67 | val htmlTitleElement = ( 68 | htmlHeadElement.getElementsByTagName("title").item(0) 69 | ?: document.createElement("title").also { htmlHeadElement.appendChild(it) } 70 | ) as HTMLTitleElement 71 | htmlTitleElement.textContent = title 72 | 73 | setContent { 74 | content(this) 75 | } 76 | } 77 | } -------------------------------------------------------------------------------- /reorderable/build.gradle.kts: -------------------------------------------------------------------------------- 1 | import org.jetbrains.compose.ComposeBuildConfig.composeVersion 2 | 3 | plugins { 4 | kotlin("multiplatform") 5 | id("org.jetbrains.compose") 6 | id("maven-publish") 7 | id("signing") 8 | } 9 | 10 | group = "org.burnoutcrew.composereorderable" 11 | version = "0.9.7" 12 | 13 | kotlin { 14 | jvm() 15 | js(IR) { 16 | browser() 17 | binaries.executable() 18 | } 19 | sourceSets { 20 | val commonMain by getting { 21 | dependencies { 22 | implementation(compose.foundation) 23 | implementation(compose.animation) 24 | implementation("org.jetbrains.compose.ui:ui-util:${composeVersion}") 25 | } 26 | } 27 | } 28 | } 29 | 30 | val javadocJar = tasks.register("javadocJar", Jar::class.java) { 31 | archiveClassifier.set("javadoc") 32 | } 33 | 34 | publishing { 35 | publications { 36 | repositories { 37 | maven { 38 | name="oss" 39 | val releasesRepoUrl = uri("https://s01.oss.sonatype.org/service/local/staging/deploy/maven2/") 40 | val snapshotsRepoUrl = uri("https://s01.oss.sonatype.org/content/repositories/snapshots/") 41 | url = if (version.toString().endsWith("SNAPSHOT")) snapshotsRepoUrl else releasesRepoUrl 42 | credentials { 43 | username = extra.properties.getOrDefault("ossrh.Username", "") as String 44 | password = extra.properties.getOrDefault("ossrh.Password", "") as String 45 | } 46 | } 47 | } 48 | } 49 | publications { 50 | withType { 51 | artifact(javadocJar) 52 | pom { 53 | name.set("ComposeReorderable") 54 | description.set("Reorderable Compose LazyList") 55 | licenses { 56 | license { 57 | name.set("Apache-2.0") 58 | url.set("https://opensource.org/licenses/Apache-2.0") 59 | } 60 | } 61 | url.set("https://github.com/aclassen/ComposeReorderable") 62 | issueManagement { 63 | system.set("Github") 64 | url.set("https://github.com/aclassen/ComposeReorderable/issues") 65 | } 66 | scm { 67 | connection.set("https://github.com/aclassen/ComposeReorderable.git") 68 | url.set("https://github.com/aclassen/ComposeReorderable") 69 | } 70 | developers { 71 | developer { 72 | name.set("Andre Claßen") 73 | email.set("andreclassen1337@gmail.com") 74 | } 75 | } 76 | } 77 | } 78 | } 79 | } 80 | 81 | signing { 82 | sign(publishing.publications) 83 | } 84 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @rem 2 | @rem Copyright 2015 the original author or authors. 3 | @rem 4 | @rem Licensed under the Apache License, Version 2.0 (the "License"); 5 | @rem you may not use this file except in compliance with the License. 6 | @rem You may obtain a copy of the License at 7 | @rem 8 | @rem https://www.apache.org/licenses/LICENSE-2.0 9 | @rem 10 | @rem Unless required by applicable law or agreed to in writing, software 11 | @rem distributed under the License is distributed on an "AS IS" BASIS, 12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | @rem See the License for the specific language governing permissions and 14 | @rem limitations under the License. 15 | @rem 16 | 17 | @if "%DEBUG%" == "" @echo off 18 | @rem ########################################################################## 19 | @rem 20 | @rem Gradle startup script for Windows 21 | @rem 22 | @rem ########################################################################## 23 | 24 | @rem Set local scope for the variables with windows NT shell 25 | if "%OS%"=="Windows_NT" setlocal 26 | 27 | set DIRNAME=%~dp0 28 | if "%DIRNAME%" == "" set DIRNAME=. 29 | set APP_BASE_NAME=%~n0 30 | set APP_HOME=%DIRNAME% 31 | 32 | @rem Resolve any "." and ".." in APP_HOME to make it shorter. 33 | for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi 34 | 35 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 36 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" 37 | 38 | @rem Find java.exe 39 | if defined JAVA_HOME goto findJavaFromJavaHome 40 | 41 | set JAVA_EXE=java.exe 42 | %JAVA_EXE% -version >NUL 2>&1 43 | if "%ERRORLEVEL%" == "0" goto execute 44 | 45 | echo. 46 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 47 | echo. 48 | echo Please set the JAVA_HOME variable in your environment to match the 49 | echo location of your Java installation. 50 | 51 | goto fail 52 | 53 | :findJavaFromJavaHome 54 | set JAVA_HOME=%JAVA_HOME:"=% 55 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 56 | 57 | if exist "%JAVA_EXE%" goto execute 58 | 59 | echo. 60 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 61 | echo. 62 | echo Please set the JAVA_HOME variable in your environment to match the 63 | echo location of your Java installation. 64 | 65 | goto fail 66 | 67 | :execute 68 | @rem Setup the command line 69 | 70 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 71 | 72 | 73 | @rem Execute Gradle 74 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* 75 | 76 | :end 77 | @rem End local scope for the variables with windows NT shell 78 | if "%ERRORLEVEL%"=="0" goto mainEnd 79 | 80 | :fail 81 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 82 | rem the _cmd.exe /c_ return code! 83 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 84 | exit /b 1 85 | 86 | :mainEnd 87 | if "%OS%"=="Windows_NT" endlocal 88 | 89 | :omega 90 | -------------------------------------------------------------------------------- /reorderable/src/commonMain/kotlin/org/burnoutcrew/reorderable/Reorderable.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2022 André Claßen 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package org.burnoutcrew.reorderable 17 | 18 | import androidx.compose.foundation.gestures.drag 19 | import androidx.compose.foundation.gestures.forEachGesture 20 | import androidx.compose.ui.Modifier 21 | import androidx.compose.ui.geometry.Offset 22 | import androidx.compose.ui.input.pointer.PointerId 23 | import androidx.compose.ui.input.pointer.PointerInputChange 24 | import androidx.compose.ui.input.pointer.PointerInputScope 25 | import androidx.compose.ui.input.pointer.changedToUp 26 | import androidx.compose.ui.input.pointer.pointerInput 27 | import androidx.compose.ui.input.pointer.positionChange 28 | import androidx.compose.ui.util.fastFirstOrNull 29 | 30 | fun Modifier.reorderable( 31 | state: ReorderableState<*> 32 | ) = then( 33 | Modifier.pointerInput(Unit) { 34 | forEachGesture { 35 | val dragStart = state.interactions.receive() 36 | val down = awaitPointerEventScope { 37 | currentEvent.changes.fastFirstOrNull { it.id == dragStart.id } 38 | } 39 | if (down != null && state.onDragStart(down.position.x.toInt(), down.position.y.toInt())) { 40 | dragStart.offset?.apply { 41 | state.onDrag(x.toInt(), y.toInt()) 42 | } 43 | detectDrag( 44 | down.id, 45 | onDragEnd = { 46 | state.onDragCanceled() 47 | }, 48 | onDragCancel = { 49 | state.onDragCanceled() 50 | }, 51 | onDrag = { change, dragAmount -> 52 | change.consume() 53 | state.onDrag(dragAmount.x.toInt(), dragAmount.y.toInt()) 54 | }) 55 | } 56 | } 57 | }) 58 | 59 | internal suspend fun PointerInputScope.detectDrag( 60 | down: PointerId, 61 | onDragEnd: () -> Unit = { }, 62 | onDragCancel: () -> Unit = { }, 63 | onDrag: (change: PointerInputChange, dragAmount: Offset) -> Unit, 64 | ) { 65 | awaitPointerEventScope { 66 | if ( 67 | drag(down) { 68 | onDrag(it, it.positionChange()) 69 | it.consume() 70 | } 71 | ) { 72 | // consume up if we quit drag gracefully with the up 73 | currentEvent.changes.forEach { 74 | if (it.changedToUp()) it.consume() 75 | } 76 | onDragEnd() 77 | } else { 78 | onDragCancel() 79 | } 80 | } 81 | } 82 | 83 | internal data class StartDrag(val id: PointerId, val offset: Offset? = null) -------------------------------------------------------------------------------- /web/src/jsMain/kotlin/main.js.kt: -------------------------------------------------------------------------------- 1 | import androidx.compose.animation.core.animateDpAsState 2 | import androidx.compose.foundation.Image 3 | import androidx.compose.foundation.VerticalScrollbar 4 | import androidx.compose.foundation.background 5 | import androidx.compose.foundation.layout.* 6 | import androidx.compose.foundation.lazy.LazyColumn 7 | import androidx.compose.foundation.lazy.items 8 | import androidx.compose.foundation.rememberScrollbarAdapter 9 | import androidx.compose.material.Divider 10 | import androidx.compose.material.MaterialTheme 11 | import androidx.compose.material.Text 12 | import androidx.compose.material.icons.Icons 13 | import androidx.compose.material.icons.filled.Menu 14 | import androidx.compose.runtime.Composable 15 | import androidx.compose.runtime.mutableStateOf 16 | import androidx.compose.runtime.remember 17 | import androidx.compose.ui.Alignment 18 | import androidx.compose.ui.Modifier 19 | import androidx.compose.ui.draw.shadow 20 | import androidx.compose.ui.unit.dp 21 | import org.burnoutcrew.reorderable.ReorderableItem 22 | import org.burnoutcrew.reorderable.detectReorder 23 | import org.burnoutcrew.reorderable.rememberReorderableLazyListState 24 | import org.burnoutcrew.reorderable.reorderable 25 | import org.jetbrains.skiko.wasm.onWasmReady 26 | 27 | fun main() { 28 | onWasmReady { 29 | BrowserViewportWindow("ComposeReorderableDemo") { 30 | MaterialTheme { 31 | Box(modifier = Modifier.fillMaxSize()) { 32 | VerticalReorderList() 33 | } 34 | } 35 | } 36 | } 37 | } 38 | 39 | 40 | @Composable 41 | fun VerticalReorderList() { 42 | val items = remember { mutableStateOf(List(100) { it }) } 43 | val state = rememberReorderableLazyListState(onMove = { from, to -> 44 | items.value = items.value.toMutableList().apply { 45 | add(to.index, removeAt(from.index)) 46 | } 47 | }) 48 | Box { 49 | LazyColumn( 50 | state = state.listState, 51 | modifier = Modifier.reorderable(state) 52 | ) { 53 | items(items.value, { it }) { item -> 54 | ReorderableItem(state, orientationLocked = false, key = item) { isDragging -> 55 | val elevation = animateDpAsState(if (isDragging) 8.dp else 0.dp) 56 | Column( 57 | modifier = Modifier 58 | .shadow(elevation.value) 59 | .background(MaterialTheme.colors.surface) 60 | ) { 61 | Row( 62 | verticalAlignment = Alignment.CenterVertically, 63 | modifier = Modifier.padding(16.dp) 64 | ) { 65 | Image( 66 | imageVector = Icons.Filled.Menu, 67 | contentDescription = "", 68 | modifier = Modifier.detectReorder(state) 69 | ) 70 | Text( 71 | text = item.toString(), 72 | modifier = Modifier.padding(start = 8.dp) 73 | ) 74 | } 75 | Divider() 76 | } 77 | } 78 | } 79 | } 80 | VerticalScrollbar( 81 | modifier = Modifier.align(Alignment.CenterEnd) 82 | .fillMaxHeight(), 83 | adapter = rememberScrollbarAdapter(state.listState) 84 | ) 85 | } 86 | } -------------------------------------------------------------------------------- /reorderable/src/commonMain/kotlin/org/burnoutcrew/reorderable/ReorderableItem.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2022 André Claßen 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package org.burnoutcrew.reorderable 17 | 18 | import androidx.compose.foundation.ExperimentalFoundationApi 19 | import androidx.compose.foundation.layout.Box 20 | import androidx.compose.foundation.layout.BoxScope 21 | import androidx.compose.foundation.lazy.LazyItemScope 22 | import androidx.compose.foundation.lazy.grid.LazyGridItemScope 23 | import androidx.compose.runtime.Composable 24 | import androidx.compose.ui.Modifier 25 | import androidx.compose.ui.graphics.graphicsLayer 26 | import androidx.compose.ui.zIndex 27 | 28 | @OptIn(ExperimentalFoundationApi::class) 29 | @Composable 30 | fun LazyItemScope.ReorderableItem( 31 | reorderableState: ReorderableState<*>, 32 | key: Any?, 33 | modifier: Modifier = Modifier, 34 | index: Int? = null, 35 | orientationLocked: Boolean = true, 36 | content: @Composable BoxScope.(isDragging: Boolean) -> Unit 37 | ) = ReorderableItem(reorderableState, key, modifier, Modifier.animateItemPlacement(), orientationLocked, index, content) 38 | 39 | @OptIn(ExperimentalFoundationApi::class) 40 | @Composable 41 | fun LazyGridItemScope.ReorderableItem( 42 | reorderableState: ReorderableState<*>, 43 | key: Any?, 44 | modifier: Modifier = Modifier, 45 | index: Int? = null, 46 | content: @Composable BoxScope.(isDragging: Boolean) -> Unit 47 | ) = ReorderableItem(reorderableState, key, modifier, Modifier.animateItemPlacement(), false, index, content) 48 | 49 | @Composable 50 | fun ReorderableItem( 51 | state: ReorderableState<*>, 52 | key: Any?, 53 | modifier: Modifier = Modifier, 54 | defaultDraggingModifier: Modifier = Modifier, 55 | orientationLocked: Boolean = true, 56 | index: Int? = null, 57 | content: @Composable BoxScope.(isDragging: Boolean) -> Unit 58 | ) { 59 | val isDragging = if (index != null) { 60 | index == state.draggingItemIndex 61 | } else { 62 | key == state.draggingItemKey 63 | } 64 | val draggingModifier = 65 | if (isDragging) { 66 | Modifier 67 | .zIndex(1f) 68 | .graphicsLayer { 69 | translationX = if (!orientationLocked || !state.isVerticalScroll) state.draggingItemLeft else 0f 70 | translationY = if (!orientationLocked || state.isVerticalScroll) state.draggingItemTop else 0f 71 | } 72 | } else { 73 | val cancel = if (index != null) { 74 | index == state.dragCancelledAnimation.position?.index 75 | } else { 76 | key == state.dragCancelledAnimation.position?.key 77 | } 78 | if (cancel) { 79 | Modifier.zIndex(1f) 80 | .graphicsLayer { 81 | translationX = if (!orientationLocked || !state.isVerticalScroll) state.dragCancelledAnimation.offset.x else 0f 82 | translationY = if (!orientationLocked || state.isVerticalScroll) state.dragCancelledAnimation.offset.y else 0f 83 | } 84 | } else { 85 | defaultDraggingModifier 86 | } 87 | } 88 | Box(modifier = modifier.then(draggingModifier)) { 89 | content(isDragging) 90 | } 91 | } -------------------------------------------------------------------------------- /desktop/src/jvmMain/kotlin/Main.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2021 André Claßen 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | import androidx.compose.animation.core.animateDpAsState 18 | import androidx.compose.foundation.Image 19 | import androidx.compose.foundation.VerticalScrollbar 20 | import androidx.compose.foundation.background 21 | import androidx.compose.foundation.layout.Box 22 | import androidx.compose.foundation.layout.Column 23 | import androidx.compose.foundation.layout.Row 24 | import androidx.compose.foundation.layout.fillMaxHeight 25 | import androidx.compose.foundation.layout.padding 26 | import androidx.compose.foundation.lazy.LazyColumn 27 | import androidx.compose.foundation.lazy.items 28 | import androidx.compose.foundation.rememberScrollbarAdapter 29 | import androidx.compose.material.Divider 30 | import androidx.compose.material.MaterialTheme 31 | import androidx.compose.material.Text 32 | import androidx.compose.material.icons.Icons 33 | import androidx.compose.material.icons.filled.Menu 34 | import androidx.compose.runtime.Composable 35 | import androidx.compose.runtime.mutableStateOf 36 | import androidx.compose.runtime.remember 37 | import androidx.compose.ui.Alignment 38 | import androidx.compose.ui.Modifier 39 | import androidx.compose.ui.draw.shadow 40 | import androidx.compose.ui.unit.dp 41 | import androidx.compose.ui.window.Window 42 | import androidx.compose.ui.window.application 43 | import org.burnoutcrew.reorderable.ReorderableItem 44 | import org.burnoutcrew.reorderable.detectReorder 45 | import org.burnoutcrew.reorderable.rememberReorderableLazyListState 46 | import org.burnoutcrew.reorderable.reorderable 47 | 48 | fun main() = application { 49 | Window( 50 | onCloseRequest = ::exitApplication, 51 | title = "Lazy reorder list" 52 | ) { 53 | VerticalReorderList() 54 | } 55 | } 56 | 57 | @Composable 58 | fun VerticalReorderList() { 59 | val items = remember { mutableStateOf(List(100) { it }) } 60 | val state = rememberReorderableLazyListState(onMove = { from, to -> 61 | items.value = items.value.toMutableList().apply { 62 | add(to.index, removeAt(from.index)) 63 | } 64 | }) 65 | Box { 66 | LazyColumn( 67 | state = state.listState, 68 | modifier = Modifier.reorderable(state) 69 | ) { 70 | items(items.value, { it }) { item -> 71 | ReorderableItem(state, orientationLocked = false, key = item) { isDragging -> 72 | val elevation = animateDpAsState(if (isDragging) 8.dp else 0.dp) 73 | Column( 74 | modifier = Modifier 75 | .shadow(elevation.value) 76 | .background(MaterialTheme.colors.surface) 77 | ) { 78 | Row( 79 | verticalAlignment = Alignment.CenterVertically, 80 | modifier = Modifier.padding(16.dp) 81 | ) { 82 | Image( 83 | imageVector = Icons.Filled.Menu, 84 | contentDescription = "", 85 | modifier = Modifier.detectReorder(state) 86 | ) 87 | Text( 88 | text = item.toString(), 89 | modifier = Modifier.padding(start = 8.dp) 90 | ) 91 | } 92 | Divider() 93 | } 94 | } 95 | } 96 | } 97 | VerticalScrollbar( 98 | modifier = Modifier.align(Alignment.CenterEnd) 99 | .fillMaxHeight(), 100 | adapter = rememberScrollbarAdapter(state.listState) 101 | ) 102 | } 103 | } -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Compose LazyList/Grid reorder 2 | [![Latest release](https://img.shields.io/github/v/release/aclassen/ComposeReorderable?color=brightgreen&label=latest%20release)](https://github.com/aclassen/ComposeReorderable/releases/latest) 3 | 4 | A Jetpack Compose (Android + Desktop) modifier enabling reordering by drag and drop in a LazyList and LazyGrid. 5 | 6 | ![Sample](readme/sample.gif) 7 | 8 | ## Download 9 | 10 | ``` 11 | dependencies { 12 | implementation("org.burnoutcrew.composereorderable:reorderable:") 13 | } 14 | ``` 15 | 16 | ## How to use 17 | 18 | - Create a reorderable state by `rememberReorderableLazyListState` for LazyList or `rememberReorderableLazyGridState` for LazyGrid 19 | - Add the `reorderable(state)` modifier to your list/grid 20 | - Inside the list/grid itemscope create a `ReorderableItem(state, key = )` for a keyed lists or `ReorderableItem(state, index = )` for a indexed only list. (Animated items only work with keyed lists) 21 | - Apply the `detectReorderAfterLongPress(state)` or `detectReorder(state)` modifier to the list. 22 | If only a drag handle is needed apply the detect modifier to any child composable inside the item layout. 23 | 24 | `ReorderableItem` provides the item dragging state, use this to apply elevation , scale etc. 25 | 26 | ```kotlin 27 | @Composable 28 | fun VerticalReorderList() { 29 | val data = remember { mutableStateOf(List(100) { "Item $it" }) } 30 | val state = rememberReorderableLazyListState(onMove = { from, to -> 31 | data.value = data.value.toMutableList().apply { 32 | add(to.index, removeAt(from.index)) 33 | } 34 | }) 35 | LazyColumn( 36 | state = state.listState, 37 | modifier = Modifier 38 | .reorderable(state) 39 | .detectReorderAfterLongPress(state) 40 | ) { 41 | items(data.value, { it }) { item -> 42 | ReorderableItem(state, key = item) { isDragging -> 43 | val elevation = animateDpAsState(if (isDragging) 16.dp else 0.dp) 44 | Column( 45 | modifier = Modifier 46 | .shadow(elevation.value) 47 | .background(MaterialTheme.colors.surface) 48 | ) { 49 | Text(item) 50 | } 51 | } 52 | } 53 | } 54 | } 55 | 56 | ``` 57 | The item placement and drag cancelled animation can be changed or disabled by `dragCancelledAnimation` and `defaultDraggingModifier` 58 | 59 | ```kotlin 60 | @Composable 61 | fun VerticalReorderGrid() { 62 | val data = remember { mutableStateOf(List(100) { "Item $it" }) } 63 | val state = rememberReorderableLazyGridState(dragCancelledAnimation = NoDragCancelledAnimation(), 64 | onMove = { from, to -> 65 | data.value = data.value.toMutableList().apply { 66 | add(to.index, removeAt(from.index)) 67 | } 68 | }) 69 | LazyVerticalGrid( 70 | columns = GridCells.Fixed(4), 71 | state = state.gridState, 72 | modifier = Modifier.reorderable(state) 73 | ) { 74 | items(data.value, { it }) { item -> 75 | ReorderableItem(state, key = item, defaultDraggingModifier = Modifier) { isDragging -> 76 | Box( 77 | modifier = Modifier 78 | .aspectRatio(1f) 79 | .background(MaterialTheme.colors.surface) 80 | ) { 81 | Text(text = item, 82 | modifier = Modifier.detectReorderAfterLongPress(state) 83 | ) 84 | } 85 | } 86 | } 87 | } 88 | } 89 | ``` 90 | 91 | Check out the sample app for different implementation samples. 92 | 93 | ## Notes 94 | 95 | It's a known issue that the first visible item does not animate. 96 | 97 | ## License 98 | 99 | ``` 100 | Copyright 2022 André Claßen 101 | 102 | Licensed under the Apache License, Version 2.0 (the "License"); 103 | you may not use this file except in compliance with the License. 104 | You may obtain a copy of the License at 105 | 106 | https://www.apache.org/licenses/LICENSE-2.0 107 | 108 | Unless required by applicable law or agreed to in writing, software 109 | distributed under the License is distributed on an "AS IS" BASIS, 110 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 111 | See the License for the specific language governing permissions and 112 | limitations under the License. 113 | ``` 114 | -------------------------------------------------------------------------------- /reorderable/src/commonMain/kotlin/org/burnoutcrew/reorderable/ReorderableLazyGridState.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2022 André Claßen 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package org.burnoutcrew.reorderable 17 | 18 | import androidx.compose.foundation.gestures.Orientation 19 | import androidx.compose.foundation.gestures.scrollBy 20 | import androidx.compose.foundation.lazy.grid.LazyGridItemInfo 21 | import androidx.compose.foundation.lazy.grid.LazyGridState 22 | import androidx.compose.foundation.lazy.grid.rememberLazyGridState 23 | import androidx.compose.runtime.Composable 24 | import androidx.compose.runtime.LaunchedEffect 25 | import androidx.compose.runtime.remember 26 | import androidx.compose.runtime.rememberCoroutineScope 27 | import androidx.compose.ui.platform.LocalDensity 28 | import androidx.compose.ui.unit.Dp 29 | import androidx.compose.ui.unit.dp 30 | import kotlinx.coroutines.CoroutineScope 31 | 32 | @Composable 33 | fun rememberReorderableLazyGridState( 34 | onMove: (ItemPosition, ItemPosition) -> Unit, 35 | gridState: LazyGridState = rememberLazyGridState(), 36 | canDragOver: ((draggedOver: ItemPosition, dragging: ItemPosition) -> Boolean)? = null, 37 | onDragEnd: ((startIndex: Int, endIndex: Int) -> (Unit))? = null, 38 | maxScrollPerFrame: Dp = 20.dp, 39 | dragCancelledAnimation: DragCancelledAnimation = SpringDragCancelledAnimation() 40 | ): ReorderableLazyGridState { 41 | val maxScroll = with(LocalDensity.current) { maxScrollPerFrame.toPx() } 42 | val scope = rememberCoroutineScope() 43 | val state = remember(gridState) { 44 | ReorderableLazyGridState(gridState, scope, maxScroll, onMove, canDragOver, onDragEnd, dragCancelledAnimation) 45 | } 46 | LaunchedEffect(state) { 47 | state.visibleItemsChanged() 48 | .collect { state.onDrag(0, 0) } 49 | } 50 | 51 | LaunchedEffect(state) { 52 | while (true) { 53 | val diff = state.scrollChannel.receive() 54 | gridState.scrollBy(diff) 55 | } 56 | } 57 | return state 58 | } 59 | 60 | class ReorderableLazyGridState( 61 | val gridState: LazyGridState, 62 | scope: CoroutineScope, 63 | maxScrollPerFrame: Float, 64 | onMove: (fromIndex: ItemPosition, toIndex: ItemPosition) -> (Unit), 65 | canDragOver: ((draggedOver: ItemPosition, dragging: ItemPosition) -> Boolean)? = null, 66 | onDragEnd: ((startIndex: Int, endIndex: Int) -> (Unit))? = null, 67 | dragCancelledAnimation: DragCancelledAnimation = SpringDragCancelledAnimation() 68 | ) : ReorderableState(scope, maxScrollPerFrame, onMove, canDragOver, onDragEnd, dragCancelledAnimation) { 69 | override val isVerticalScroll: Boolean 70 | get() = gridState.layoutInfo.orientation == Orientation.Vertical 71 | override val LazyGridItemInfo.left: Int 72 | get() = offset.x 73 | override val LazyGridItemInfo.right: Int 74 | get() = offset.x + size.width 75 | override val LazyGridItemInfo.top: Int 76 | get() = offset.y 77 | override val LazyGridItemInfo.bottom: Int 78 | get() = offset.y + size.height 79 | override val LazyGridItemInfo.width: Int 80 | get() = size.width 81 | override val LazyGridItemInfo.height: Int 82 | get() = size.height 83 | override val LazyGridItemInfo.itemIndex: Int 84 | get() = index 85 | override val LazyGridItemInfo.itemKey: Any 86 | get() = key 87 | override val visibleItemsInfo: List 88 | get() = gridState.layoutInfo.visibleItemsInfo 89 | override val viewportStartOffset: Int 90 | get() = gridState.layoutInfo.viewportStartOffset 91 | override val viewportEndOffset: Int 92 | get() = gridState.layoutInfo.viewportEndOffset 93 | override val firstVisibleItemIndex: Int 94 | get() = gridState.firstVisibleItemIndex 95 | override val firstVisibleItemScrollOffset: Int 96 | get() = gridState.firstVisibleItemScrollOffset 97 | 98 | override suspend fun scrollToItem(index: Int, offset: Int) { 99 | gridState.scrollToItem(index, offset) 100 | } 101 | } -------------------------------------------------------------------------------- /android/src/main/kotlin/org/burnoutcrew/android/ui/Root.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2021 André Claßen 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package org.burnoutcrew.android.ui 17 | 18 | import androidx.compose.foundation.layout.padding 19 | import androidx.compose.material.BottomNavigation 20 | import androidx.compose.material.BottomNavigationItem 21 | import androidx.compose.material.Icon 22 | import androidx.compose.material.Scaffold 23 | import androidx.compose.material.Text 24 | import androidx.compose.material.TopAppBar 25 | import androidx.compose.material.icons.Icons 26 | import androidx.compose.material.icons.filled.List 27 | import androidx.compose.material.icons.filled.Settings 28 | import androidx.compose.material.icons.filled.Star 29 | import androidx.compose.runtime.Composable 30 | import androidx.compose.ui.Modifier 31 | import androidx.compose.ui.graphics.Color 32 | import androidx.compose.ui.graphics.vector.ImageVector 33 | import androidx.compose.ui.res.stringResource 34 | import androidx.navigation.NavController 35 | import androidx.navigation.NavHostController 36 | import androidx.navigation.compose.NavHost 37 | import androidx.navigation.compose.composable 38 | import androidx.navigation.compose.currentBackStackEntryAsState 39 | import androidx.navigation.compose.rememberNavController 40 | import org.burnoutcrew.android.R 41 | import org.burnoutcrew.android.ui.reorderlist.ReorderGrid 42 | import org.burnoutcrew.android.ui.reorderlist.ReorderImageList 43 | import org.burnoutcrew.android.ui.reorderlist.ReorderList 44 | import org.burnoutcrew.android.ui.theme.ReorderListTheme 45 | 46 | 47 | @Composable 48 | fun Root() { 49 | ReorderListTheme { 50 | val navController = rememberNavController() 51 | val navigationItems = listOf( 52 | NavigationItem.Lists, 53 | NavigationItem.Grids, 54 | NavigationItem.Fixed, 55 | ) 56 | Scaffold( 57 | topBar = { 58 | TopAppBar(title = { Text(stringResource(R.string.app_name)) }) 59 | }, 60 | bottomBar = { 61 | BottomNavigationBar(navigationItems, navController) 62 | } 63 | ) { 64 | Navigation( 65 | navController, 66 | Modifier.padding(top = it.calculateTopPadding(), bottom = it.calculateBottomPadding()) 67 | ) 68 | } 69 | } 70 | } 71 | 72 | @Composable 73 | private fun Navigation(navController: NavHostController, modifier: Modifier) { 74 | NavHost(navController, startDestination = NavigationItem.Lists.route, modifier = modifier) { 75 | composable(NavigationItem.Lists.route) { 76 | ReorderList() 77 | } 78 | composable(NavigationItem.Grids.route) { 79 | ReorderGrid() 80 | } 81 | composable(NavigationItem.Fixed.route) { 82 | ReorderImageList() 83 | } 84 | } 85 | } 86 | 87 | 88 | @Composable 89 | private fun BottomNavigationBar(items: List, navController: NavController) { 90 | BottomNavigation(contentColor = Color.White) { 91 | val navBackStackEntry = navController.currentBackStackEntryAsState() 92 | val currentRoute = navBackStackEntry.value?.destination?.route 93 | items.forEach { item -> 94 | BottomNavigationItem( 95 | icon = { Icon(item.icon, item.title) }, 96 | label = { Text(text = item.title) }, 97 | selected = currentRoute == item.route, 98 | onClick = { 99 | navController.navigate(item.route) { 100 | navController.graph.startDestinationRoute?.let { route -> 101 | popUpTo(route) { 102 | saveState = true 103 | } 104 | } 105 | launchSingleTop = true 106 | restoreState = true 107 | } 108 | } 109 | ) 110 | } 111 | } 112 | } 113 | 114 | private sealed class NavigationItem(var route: String, var icon: ImageVector, var title: String) { 115 | object Lists : NavigationItem("lists", Icons.Default.List, "Lists") 116 | object Grids : NavigationItem("grids", Icons.Default.Settings, "Grids") 117 | object Fixed : NavigationItem("fixed", Icons.Default.Star, "Fixed") 118 | } 119 | -------------------------------------------------------------------------------- /android/src/main/kotlin/org/burnoutcrew/android/ui/reorderlist/ReorderImageList.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2022 André Claßen 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package org.burnoutcrew.android.ui.reorderlist 17 | 18 | import androidx.compose.animation.core.animateDpAsState 19 | import androidx.compose.foundation.Image 20 | import androidx.compose.foundation.background 21 | import androidx.compose.foundation.layout.Box 22 | import androidx.compose.foundation.layout.Column 23 | import androidx.compose.foundation.layout.Row 24 | import androidx.compose.foundation.layout.fillMaxSize 25 | import androidx.compose.foundation.layout.fillMaxWidth 26 | import androidx.compose.foundation.layout.height 27 | import androidx.compose.foundation.layout.padding 28 | import androidx.compose.foundation.layout.size 29 | import androidx.compose.foundation.lazy.LazyColumn 30 | import androidx.compose.foundation.lazy.items 31 | import androidx.compose.material.Divider 32 | import androidx.compose.material.MaterialTheme 33 | import androidx.compose.material.Text 34 | import androidx.compose.material.icons.Icons 35 | import androidx.compose.material.icons.filled.List 36 | import androidx.compose.runtime.Composable 37 | import androidx.compose.ui.Alignment 38 | import androidx.compose.ui.Modifier 39 | import androidx.compose.ui.draw.shadow 40 | import androidx.compose.ui.graphics.Color 41 | import androidx.compose.ui.graphics.ColorFilter 42 | import androidx.compose.ui.layout.ContentScale 43 | import androidx.compose.ui.res.stringResource 44 | import androidx.compose.ui.unit.dp 45 | import androidx.lifecycle.viewmodel.compose.viewModel 46 | import coil.compose.rememberAsyncImagePainter 47 | import org.burnoutcrew.android.R 48 | import org.burnoutcrew.reorderable.ReorderableItem 49 | import org.burnoutcrew.reorderable.detectReorder 50 | import org.burnoutcrew.reorderable.rememberReorderableLazyListState 51 | import org.burnoutcrew.reorderable.reorderable 52 | 53 | @Composable 54 | fun ReorderImageList( 55 | modifier: Modifier = Modifier, 56 | vm: ImageListViewModel = viewModel(), 57 | ) { 58 | val state = rememberReorderableLazyListState(onMove = vm::onMove, canDragOver = vm::canDragOver) 59 | LazyColumn( 60 | state = state.listState, 61 | modifier = modifier 62 | .then(Modifier.reorderable(state)) 63 | ) { 64 | item { 65 | HeaderFooter(stringResource(R.string.header_title), vm.headerImage) 66 | } 67 | items(vm.images, { it }) { item -> 68 | ReorderableItem(state, item) { isDragging -> 69 | val elevation = animateDpAsState(if (isDragging) 8.dp else 0.dp) 70 | Column( 71 | modifier = Modifier 72 | .shadow(elevation.value) 73 | .fillMaxWidth() 74 | .background(MaterialTheme.colors.surface) 75 | 76 | ) { 77 | Row(verticalAlignment = Alignment.CenterVertically) { 78 | Image( 79 | Icons.Default.List, 80 | "", 81 | colorFilter = ColorFilter.tint(color = MaterialTheme.colors.onBackground), 82 | modifier = Modifier.detectReorder(state) 83 | ) 84 | Image( 85 | painter = rememberAsyncImagePainter(item), 86 | contentDescription = null, 87 | modifier = Modifier.size(128.dp) 88 | ) 89 | Text( 90 | text = item, 91 | modifier = Modifier.padding(16.dp) 92 | ) 93 | } 94 | Divider() 95 | } 96 | } 97 | } 98 | item { 99 | HeaderFooter(stringResource(R.string.footer_title), vm.footerImage) 100 | } 101 | } 102 | } 103 | 104 | @Composable 105 | private fun HeaderFooter(title: String, url: String) { 106 | Box(modifier = Modifier.height(128.dp).fillMaxWidth()) { 107 | Image( 108 | painter = rememberAsyncImagePainter(url), 109 | contentDescription = null, 110 | modifier = Modifier.fillMaxSize(), 111 | contentScale = ContentScale.Crop 112 | ) 113 | Text( 114 | title, 115 | style = MaterialTheme.typography.h2, 116 | color = Color.White, 117 | modifier = Modifier.align(Alignment.Center) 118 | ) 119 | } 120 | } -------------------------------------------------------------------------------- /android/src/main/kotlin/org/burnoutcrew/android/ui/reorderlist/ReorderGrid.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2022 André Claßen 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package org.burnoutcrew.android.ui.reorderlist 17 | 18 | import androidx.compose.animation.core.animateDpAsState 19 | import androidx.compose.foundation.background 20 | import androidx.compose.foundation.layout.Arrangement 21 | import androidx.compose.foundation.layout.Box 22 | import androidx.compose.foundation.layout.Column 23 | import androidx.compose.foundation.layout.PaddingValues 24 | import androidx.compose.foundation.layout.aspectRatio 25 | import androidx.compose.foundation.layout.height 26 | import androidx.compose.foundation.layout.padding 27 | import androidx.compose.foundation.layout.size 28 | import androidx.compose.foundation.lazy.grid.GridCells 29 | import androidx.compose.foundation.lazy.grid.LazyHorizontalGrid 30 | import androidx.compose.foundation.lazy.grid.LazyVerticalGrid 31 | import androidx.compose.foundation.lazy.grid.items 32 | import androidx.compose.material.MaterialTheme 33 | import androidx.compose.material.Text 34 | import androidx.compose.runtime.Composable 35 | import androidx.compose.ui.Alignment 36 | import androidx.compose.ui.Modifier 37 | import androidx.compose.ui.draw.shadow 38 | import androidx.compose.ui.unit.dp 39 | import androidx.lifecycle.viewmodel.compose.viewModel 40 | import org.burnoutcrew.reorderable.ReorderableItem 41 | import org.burnoutcrew.reorderable.detectReorderAfterLongPress 42 | import org.burnoutcrew.reorderable.rememberReorderableLazyGridState 43 | import org.burnoutcrew.reorderable.reorderable 44 | 45 | @Composable 46 | fun ReorderGrid(vm: ReorderListViewModel = viewModel()) { 47 | Column { 48 | HorizontalGrid( 49 | vm = vm, 50 | modifier = Modifier.padding(vertical = 16.dp) 51 | ) 52 | VerticalGrid(vm = vm) 53 | } 54 | } 55 | 56 | @Composable 57 | private fun HorizontalGrid( 58 | vm: ReorderListViewModel, 59 | modifier: Modifier = Modifier, 60 | ) { 61 | val state = rememberReorderableLazyGridState(onMove = vm::moveCat) 62 | LazyHorizontalGrid( 63 | rows = GridCells.Fixed(2), 64 | state = state.gridState, 65 | contentPadding = PaddingValues(horizontal = 8.dp), 66 | verticalArrangement = Arrangement.spacedBy(4.dp), 67 | horizontalArrangement = Arrangement.spacedBy(4.dp), 68 | modifier = modifier 69 | .reorderable(state) 70 | .height(200.dp) 71 | .detectReorderAfterLongPress(state) 72 | ) { 73 | items(vm.cats, { it.key }) { item -> 74 | ReorderableItem(state, item.key) { isDragging -> 75 | val elevation = animateDpAsState(if (isDragging) 16.dp else 0.dp) 76 | Box( 77 | contentAlignment = Alignment.Center, 78 | modifier = Modifier 79 | .shadow(elevation.value) 80 | .aspectRatio(1f) 81 | .background(MaterialTheme.colors.secondary) 82 | ) { 83 | Text(item.title) 84 | } 85 | } 86 | } 87 | } 88 | } 89 | 90 | @Composable 91 | private fun VerticalGrid( 92 | vm: ReorderListViewModel, 93 | modifier: Modifier = Modifier, 94 | ) { 95 | val state = rememberReorderableLazyGridState(onMove = vm::moveDog, canDragOver = vm::isDogDragEnabled) 96 | LazyVerticalGrid( 97 | columns = GridCells.Fixed(4), 98 | state = state.gridState, 99 | contentPadding = PaddingValues(horizontal = 8.dp), 100 | verticalArrangement = Arrangement.spacedBy(4.dp), 101 | horizontalArrangement = Arrangement.spacedBy(4.dp), 102 | modifier = modifier.reorderable(state) 103 | ) { 104 | items(vm.dogs, { it.key }) { item -> 105 | if (item.isLocked) { 106 | Box( 107 | contentAlignment = Alignment.Center, 108 | modifier = Modifier 109 | .size(100.dp) 110 | .background(MaterialTheme.colors.surface) 111 | ) { 112 | Text(item.title) 113 | } 114 | } else { 115 | ReorderableItem(state, item.key) { isDragging -> 116 | val elevation = animateDpAsState(if (isDragging) 8.dp else 0.dp) 117 | Box( 118 | contentAlignment = Alignment.Center, 119 | modifier = Modifier 120 | .detectReorderAfterLongPress(state) 121 | .shadow(elevation.value) 122 | .aspectRatio(1f) 123 | .background(MaterialTheme.colors.primary) 124 | ) { 125 | Text(item.title) 126 | } 127 | } 128 | } 129 | } 130 | } 131 | } 132 | -------------------------------------------------------------------------------- /android/src/main/kotlin/org/burnoutcrew/android/ui/reorderlist/ReorderList.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2022 André Claßen 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package org.burnoutcrew.android.ui.reorderlist 17 | 18 | import androidx.compose.animation.core.animateDpAsState 19 | import androidx.compose.animation.core.animateFloatAsState 20 | import androidx.compose.foundation.background 21 | import androidx.compose.foundation.layout.Arrangement 22 | import androidx.compose.foundation.layout.Box 23 | import androidx.compose.foundation.layout.Column 24 | import androidx.compose.foundation.layout.fillMaxWidth 25 | import androidx.compose.foundation.layout.padding 26 | import androidx.compose.foundation.layout.size 27 | import androidx.compose.foundation.lazy.LazyColumn 28 | import androidx.compose.foundation.lazy.LazyRow 29 | import androidx.compose.foundation.lazy.items 30 | import androidx.compose.foundation.shape.RoundedCornerShape 31 | import androidx.compose.material.Divider 32 | import androidx.compose.material.MaterialTheme 33 | import androidx.compose.material.Text 34 | import androidx.compose.runtime.Composable 35 | import androidx.compose.ui.Alignment 36 | import androidx.compose.ui.Modifier 37 | import androidx.compose.ui.draw.clip 38 | import androidx.compose.ui.draw.scale 39 | import androidx.compose.ui.draw.shadow 40 | import androidx.compose.ui.graphics.Color 41 | import androidx.compose.ui.unit.dp 42 | import androidx.lifecycle.viewmodel.compose.viewModel 43 | import org.burnoutcrew.reorderable.ReorderableItem 44 | import org.burnoutcrew.reorderable.detectReorderAfterLongPress 45 | import org.burnoutcrew.reorderable.rememberReorderableLazyListState 46 | import org.burnoutcrew.reorderable.reorderable 47 | 48 | @Composable 49 | fun ReorderList(vm: ReorderListViewModel = viewModel()) { 50 | Column { 51 | HorizontalReorderList( 52 | vm = vm, 53 | modifier = Modifier.padding(vertical = 16.dp), 54 | ) 55 | VerticalReorderList(vm = vm) 56 | } 57 | } 58 | 59 | @Composable 60 | private fun VerticalReorderList( 61 | modifier: Modifier = Modifier, 62 | vm: ReorderListViewModel, 63 | ) { 64 | val state = rememberReorderableLazyListState(onMove = vm::moveDog, canDragOver = vm::isDogDragEnabled) 65 | LazyColumn( 66 | state = state.listState, 67 | modifier = modifier.reorderable(state) 68 | ) { 69 | items(vm.dogs, { item -> item.key }) { item -> 70 | ReorderableItem(state, item.key) { dragging -> 71 | val elevation = animateDpAsState(if (dragging) 8.dp else 0.dp) 72 | if (item.isLocked) { 73 | Column( 74 | modifier = Modifier 75 | .fillMaxWidth() 76 | .background(Color.LightGray) 77 | ) { 78 | Text( 79 | text = item.title, 80 | modifier = Modifier.padding(24.dp) 81 | ) 82 | } 83 | } else { 84 | Column( 85 | modifier = Modifier 86 | .detectReorderAfterLongPress(state) 87 | .shadow(elevation.value) 88 | .fillMaxWidth() 89 | .background(MaterialTheme.colors.surface) 90 | ) { 91 | Text( 92 | text = item.title, 93 | modifier = Modifier.padding(16.dp) 94 | ) 95 | Divider() 96 | } 97 | } 98 | } 99 | } 100 | } 101 | } 102 | 103 | @Composable 104 | private fun HorizontalReorderList( 105 | vm: ReorderListViewModel, 106 | modifier: Modifier = Modifier, 107 | ) { 108 | val state = rememberReorderableLazyListState(onMove = vm::moveCat) 109 | LazyRow( 110 | state = state.listState, 111 | horizontalArrangement = Arrangement.spacedBy(8.dp), 112 | modifier = modifier 113 | .then(Modifier.reorderable(state)) 114 | .detectReorderAfterLongPress(state), 115 | ) { 116 | items(vm.cats, { item -> item.key }) { item -> 117 | ReorderableItem(state, item.key) { dragging -> 118 | val scale = animateFloatAsState(if (dragging) 1.1f else 1.0f) 119 | val elevation = if (dragging) 8.dp else 0.dp 120 | Box( 121 | contentAlignment = Alignment.Center, 122 | modifier = Modifier 123 | .size(100.dp) 124 | .scale(scale.value) 125 | .shadow(elevation, RoundedCornerShape(24.dp)) 126 | .clip(RoundedCornerShape(24.dp)) 127 | .background(Color.Red) 128 | ) { 129 | Text(item.title) 130 | } 131 | } 132 | } 133 | } 134 | } 135 | -------------------------------------------------------------------------------- /android/src/main/res/drawable/ic_launcher_background.xml: -------------------------------------------------------------------------------- 1 | 2 | 7 | 10 | 15 | 20 | 25 | 30 | 35 | 40 | 45 | 50 | 55 | 60 | 65 | 70 | 75 | 80 | 85 | 90 | 95 | 100 | 105 | 110 | 115 | 120 | 125 | 130 | 135 | 140 | 145 | 150 | 155 | 160 | 165 | 170 | 171 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env sh 2 | 3 | # 4 | # Copyright 2015 the original author or authors. 5 | # 6 | # Licensed under the Apache License, Version 2.0 (the "License"); 7 | # you may not use this file except in compliance with the License. 8 | # You may obtain a copy of the License at 9 | # 10 | # https://www.apache.org/licenses/LICENSE-2.0 11 | # 12 | # Unless required by applicable law or agreed to in writing, software 13 | # distributed under the License is distributed on an "AS IS" BASIS, 14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | # See the License for the specific language governing permissions and 16 | # limitations under the License. 17 | # 18 | 19 | ############################################################################## 20 | ## 21 | ## Gradle start up script for UN*X 22 | ## 23 | ############################################################################## 24 | 25 | # Attempt to set APP_HOME 26 | # Resolve links: $0 may be a link 27 | PRG="$0" 28 | # Need this for relative symlinks. 29 | while [ -h "$PRG" ] ; do 30 | ls=`ls -ld "$PRG"` 31 | link=`expr "$ls" : '.*-> \(.*\)$'` 32 | if expr "$link" : '/.*' > /dev/null; then 33 | PRG="$link" 34 | else 35 | PRG=`dirname "$PRG"`"/$link" 36 | fi 37 | done 38 | SAVED="`pwd`" 39 | cd "`dirname \"$PRG\"`/" >/dev/null 40 | APP_HOME="`pwd -P`" 41 | cd "$SAVED" >/dev/null 42 | 43 | APP_NAME="Gradle" 44 | APP_BASE_NAME=`basename "$0"` 45 | 46 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 47 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' 48 | 49 | # Use the maximum available, or set MAX_FD != -1 to use that value. 50 | MAX_FD="maximum" 51 | 52 | warn () { 53 | echo "$*" 54 | } 55 | 56 | die () { 57 | echo 58 | echo "$*" 59 | echo 60 | exit 1 61 | } 62 | 63 | # OS specific support (must be 'true' or 'false'). 64 | cygwin=false 65 | msys=false 66 | darwin=false 67 | nonstop=false 68 | case "`uname`" in 69 | CYGWIN* ) 70 | cygwin=true 71 | ;; 72 | Darwin* ) 73 | darwin=true 74 | ;; 75 | MINGW* ) 76 | msys=true 77 | ;; 78 | NONSTOP* ) 79 | nonstop=true 80 | ;; 81 | esac 82 | 83 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 84 | 85 | 86 | # Determine the Java command to use to start the JVM. 87 | if [ -n "$JAVA_HOME" ] ; then 88 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 89 | # IBM's JDK on AIX uses strange locations for the executables 90 | JAVACMD="$JAVA_HOME/jre/sh/java" 91 | else 92 | JAVACMD="$JAVA_HOME/bin/java" 93 | fi 94 | if [ ! -x "$JAVACMD" ] ; then 95 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 96 | 97 | Please set the JAVA_HOME variable in your environment to match the 98 | location of your Java installation." 99 | fi 100 | else 101 | JAVACMD="java" 102 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 103 | 104 | Please set the JAVA_HOME variable in your environment to match the 105 | location of your Java installation." 106 | fi 107 | 108 | # Increase the maximum file descriptors if we can. 109 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then 110 | MAX_FD_LIMIT=`ulimit -H -n` 111 | if [ $? -eq 0 ] ; then 112 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then 113 | MAX_FD="$MAX_FD_LIMIT" 114 | fi 115 | ulimit -n $MAX_FD 116 | if [ $? -ne 0 ] ; then 117 | warn "Could not set maximum file descriptor limit: $MAX_FD" 118 | fi 119 | else 120 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" 121 | fi 122 | fi 123 | 124 | # For Darwin, add options to specify how the application appears in the dock 125 | if $darwin; then 126 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" 127 | fi 128 | 129 | # For Cygwin or MSYS, switch paths to Windows format before running java 130 | if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then 131 | APP_HOME=`cygpath --path --mixed "$APP_HOME"` 132 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` 133 | 134 | JAVACMD=`cygpath --unix "$JAVACMD"` 135 | 136 | # We build the pattern for arguments to be converted via cygpath 137 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` 138 | SEP="" 139 | for dir in $ROOTDIRSRAW ; do 140 | ROOTDIRS="$ROOTDIRS$SEP$dir" 141 | SEP="|" 142 | done 143 | OURCYGPATTERN="(^($ROOTDIRS))" 144 | # Add a user-defined pattern to the cygpath arguments 145 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then 146 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" 147 | fi 148 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 149 | i=0 150 | for arg in "$@" ; do 151 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` 152 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option 153 | 154 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition 155 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` 156 | else 157 | eval `echo args$i`="\"$arg\"" 158 | fi 159 | i=`expr $i + 1` 160 | done 161 | case $i in 162 | 0) set -- ;; 163 | 1) set -- "$args0" ;; 164 | 2) set -- "$args0" "$args1" ;; 165 | 3) set -- "$args0" "$args1" "$args2" ;; 166 | 4) set -- "$args0" "$args1" "$args2" "$args3" ;; 167 | 5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; 168 | 6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; 169 | 7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; 170 | 8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; 171 | 9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; 172 | esac 173 | fi 174 | 175 | # Escape application args 176 | save () { 177 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done 178 | echo " " 179 | } 180 | APP_ARGS=`save "$@"` 181 | 182 | # Collect all arguments for the java command, following the shell quoting and substitution rules 183 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" 184 | 185 | exec "$JAVACMD" "$@" 186 | -------------------------------------------------------------------------------- /reorderable/src/commonMain/kotlin/org/burnoutcrew/reorderable/ReorderableLazyListState.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2022 André Claßen 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package org.burnoutcrew.reorderable 17 | 18 | import androidx.compose.foundation.gestures.Orientation 19 | import androidx.compose.foundation.gestures.ScrollableState 20 | import androidx.compose.foundation.gestures.scrollBy 21 | import androidx.compose.foundation.lazy.LazyListItemInfo 22 | import androidx.compose.foundation.lazy.LazyListState 23 | import androidx.compose.foundation.lazy.rememberLazyListState 24 | import androidx.compose.runtime.Composable 25 | import androidx.compose.runtime.LaunchedEffect 26 | import androidx.compose.runtime.remember 27 | import androidx.compose.runtime.rememberCoroutineScope 28 | import androidx.compose.ui.platform.LocalDensity 29 | import androidx.compose.ui.platform.LocalLayoutDirection 30 | import androidx.compose.ui.unit.Dp 31 | import androidx.compose.ui.unit.LayoutDirection 32 | import androidx.compose.ui.unit.dp 33 | import kotlinx.coroutines.CoroutineScope 34 | 35 | 36 | @Composable 37 | fun rememberReorderableLazyListState( 38 | onMove: (ItemPosition, ItemPosition) -> Unit, 39 | listState: LazyListState = rememberLazyListState(), 40 | canDragOver: ((draggedOver: ItemPosition, dragging: ItemPosition) -> Boolean)? = null, 41 | onDragEnd: ((startIndex: Int, endIndex: Int) -> (Unit))? = null, 42 | maxScrollPerFrame: Dp = 20.dp, 43 | dragCancelledAnimation: DragCancelledAnimation = SpringDragCancelledAnimation() 44 | ): ReorderableLazyListState { 45 | val maxScroll = with(LocalDensity.current) { maxScrollPerFrame.toPx() } 46 | val scope = rememberCoroutineScope() 47 | val state = remember(listState) { 48 | ReorderableLazyListState(listState, scope, maxScroll, onMove, canDragOver, onDragEnd, dragCancelledAnimation) 49 | } 50 | val isRtl = LocalLayoutDirection.current == LayoutDirection.Rtl 51 | LaunchedEffect(state) { 52 | state.visibleItemsChanged() 53 | .collect { state.onDrag(0, 0) } 54 | } 55 | 56 | LaunchedEffect(state) { 57 | var reverseDirection = !listState.layoutInfo.reverseLayout 58 | if (isRtl && listState.layoutInfo.orientation != Orientation.Vertical) { 59 | reverseDirection = !reverseDirection 60 | } 61 | val direction = if (reverseDirection) 1f else -1f 62 | while (true) { 63 | val diff = state.scrollChannel.receive() 64 | listState.scrollBy(diff * direction) 65 | } 66 | } 67 | return state 68 | } 69 | 70 | class ReorderableLazyListState( 71 | val listState: LazyListState, 72 | scope: CoroutineScope, 73 | maxScrollPerFrame: Float, 74 | onMove: (fromIndex: ItemPosition, toIndex: ItemPosition) -> (Unit), 75 | canDragOver: ((draggedOver: ItemPosition, dragging: ItemPosition) -> Boolean)? = null, 76 | onDragEnd: ((startIndex: Int, endIndex: Int) -> (Unit))? = null, 77 | dragCancelledAnimation: DragCancelledAnimation = SpringDragCancelledAnimation() 78 | ) : ReorderableState( 79 | scope, 80 | maxScrollPerFrame, 81 | onMove, 82 | canDragOver, 83 | onDragEnd, 84 | dragCancelledAnimation 85 | ) { 86 | override val isVerticalScroll: Boolean 87 | get() = listState.layoutInfo.orientation == Orientation.Vertical 88 | override val LazyListItemInfo.left: Int 89 | get() = when { 90 | isVerticalScroll -> 0 91 | listState.layoutInfo.reverseLayout -> listState.layoutInfo.viewportSize.width - offset - size 92 | else -> offset 93 | } 94 | override val LazyListItemInfo.top: Int 95 | get() = when { 96 | !isVerticalScroll -> 0 97 | listState.layoutInfo.reverseLayout -> listState.layoutInfo.viewportSize.height - offset - size 98 | else -> offset 99 | } 100 | override val LazyListItemInfo.right: Int 101 | get() = when { 102 | isVerticalScroll -> 0 103 | listState.layoutInfo.reverseLayout -> listState.layoutInfo.viewportSize.width - offset 104 | else -> offset + size 105 | } 106 | override val LazyListItemInfo.bottom: Int 107 | get() = when { 108 | !isVerticalScroll -> 0 109 | listState.layoutInfo.reverseLayout -> listState.layoutInfo.viewportSize.height - offset 110 | else -> offset + size 111 | } 112 | override val LazyListItemInfo.width: Int 113 | get() = if (isVerticalScroll) 0 else size 114 | override val LazyListItemInfo.height: Int 115 | get() = if (isVerticalScroll) size else 0 116 | override val LazyListItemInfo.itemIndex: Int 117 | get() = index 118 | override val LazyListItemInfo.itemKey: Any 119 | get() = key 120 | override val visibleItemsInfo: List 121 | get() = listState.layoutInfo.visibleItemsInfo 122 | override val viewportStartOffset: Int 123 | get() = listState.layoutInfo.viewportStartOffset 124 | override val viewportEndOffset: Int 125 | get() = listState.layoutInfo.viewportEndOffset 126 | override val firstVisibleItemIndex: Int 127 | get() = listState.firstVisibleItemIndex 128 | override val firstVisibleItemScrollOffset: Int 129 | get() = listState.firstVisibleItemScrollOffset 130 | 131 | override suspend fun scrollToItem(index: Int, offset: Int) { 132 | listState.scrollToItem(index, offset) 133 | } 134 | 135 | override fun onDragStart(offsetX: Int, offsetY: Int): Boolean = 136 | if (isVerticalScroll) { 137 | super.onDragStart(0, offsetY) 138 | } else { 139 | super.onDragStart(offsetX, 0) 140 | } 141 | 142 | override fun findTargets(x: Int, y: Int, selected: LazyListItemInfo) = 143 | if (isVerticalScroll) { 144 | super.findTargets(0, y, selected) 145 | } else { 146 | super.findTargets(x, 0, selected) 147 | } 148 | 149 | override fun chooseDropItem( 150 | draggedItemInfo: LazyListItemInfo?, 151 | items: List, 152 | curX: Int, 153 | curY: Int 154 | ) = 155 | if (isVerticalScroll) { 156 | super.chooseDropItem(draggedItemInfo, items, 0, curY) 157 | } else { 158 | super.chooseDropItem(draggedItemInfo, items, curX, 0) 159 | } 160 | } -------------------------------------------------------------------------------- /reorderable/src/commonMain/kotlin/org/burnoutcrew/reorderable/DragGesture.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2020 The Android Open Source Project 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package org.burnoutcrew.reorderable 17 | 18 | import androidx.compose.ui.geometry.Offset 19 | import androidx.compose.ui.input.pointer.AwaitPointerEventScope 20 | import androidx.compose.ui.input.pointer.PointerEvent 21 | import androidx.compose.ui.input.pointer.PointerEventPass 22 | import androidx.compose.ui.input.pointer.PointerId 23 | import androidx.compose.ui.input.pointer.PointerInputChange 24 | import androidx.compose.ui.input.pointer.PointerInputScope 25 | import androidx.compose.ui.input.pointer.PointerType 26 | import androidx.compose.ui.input.pointer.changedToUpIgnoreConsumed 27 | import androidx.compose.ui.input.pointer.isOutOfBounds 28 | import androidx.compose.ui.input.pointer.positionChange 29 | import androidx.compose.ui.platform.ViewConfiguration 30 | import androidx.compose.ui.unit.dp 31 | import androidx.compose.ui.util.fastAll 32 | import androidx.compose.ui.util.fastAny 33 | import androidx.compose.ui.util.fastFirstOrNull 34 | import kotlinx.coroutines.TimeoutCancellationException 35 | import kotlinx.coroutines.withTimeout 36 | 37 | // Copied from DragGestureDetector , as long the pointer api isn`t ready. 38 | 39 | internal suspend fun AwaitPointerEventScope.awaitPointerSlopOrCancellation( 40 | pointerId: PointerId, 41 | pointerType: PointerType, 42 | onPointerSlopReached: (change: PointerInputChange, overSlop: Offset) -> Unit 43 | ): PointerInputChange? { 44 | if (currentEvent.isPointerUp(pointerId)) { 45 | return null // The pointer has already been lifted, so the gesture is canceled 46 | } 47 | var offset = Offset.Zero 48 | val touchSlop = viewConfiguration.pointerSlop(pointerType) 49 | 50 | var pointer = pointerId 51 | 52 | while (true) { 53 | val event = awaitPointerEvent() 54 | val dragEvent = event.changes.fastFirstOrNull { it.id == pointer } ?: return null 55 | if (dragEvent.isConsumed) { 56 | return null 57 | } else if (dragEvent.changedToUpIgnoreConsumed()) { 58 | val otherDown = event.changes.fastFirstOrNull { it.pressed } 59 | if (otherDown == null) { 60 | // This is the last "up" 61 | return null 62 | } else { 63 | pointer = otherDown.id 64 | } 65 | } else { 66 | offset += dragEvent.positionChange() 67 | val distance = offset.getDistance() 68 | var acceptedDrag = false 69 | if (distance >= touchSlop) { 70 | val touchSlopOffset = offset / distance * touchSlop 71 | onPointerSlopReached(dragEvent, offset - touchSlopOffset) 72 | if (dragEvent.isConsumed) { 73 | acceptedDrag = true 74 | } else { 75 | offset = Offset.Zero 76 | } 77 | } 78 | 79 | if (acceptedDrag) { 80 | return dragEvent 81 | } else { 82 | awaitPointerEvent(PointerEventPass.Final) 83 | if (dragEvent.isConsumed) { 84 | return null 85 | } 86 | } 87 | } 88 | } 89 | } 90 | 91 | internal suspend fun PointerInputScope.awaitLongPressOrCancellation( 92 | initialDown: PointerInputChange 93 | ): PointerInputChange? { 94 | var longPress: PointerInputChange? = null 95 | var currentDown = initialDown 96 | val longPressTimeout = viewConfiguration.longPressTimeoutMillis 97 | return try { 98 | // wait for first tap up or long press 99 | withTimeout(longPressTimeout) { 100 | awaitPointerEventScope { 101 | var finished = false 102 | while (!finished) { 103 | val event = awaitPointerEvent(PointerEventPass.Main) 104 | if (event.changes.fastAll { it.changedToUpIgnoreConsumed() }) { 105 | // All pointers are up 106 | finished = true 107 | } 108 | 109 | if ( 110 | event.changes.fastAny { 111 | it.isConsumed || it.isOutOfBounds(size, extendedTouchPadding) 112 | } 113 | ) { 114 | finished = true // Canceled 115 | } 116 | 117 | // Check for cancel by position consumption. We can look on the Final pass of 118 | // the existing pointer event because it comes after the Main pass we checked 119 | // above. 120 | val consumeCheck = awaitPointerEvent(PointerEventPass.Final) 121 | if (consumeCheck.changes.fastAny { it.isConsumed }) { 122 | finished = true 123 | } 124 | if (!event.isPointerUp(currentDown.id)) { 125 | longPress = event.changes.fastFirstOrNull { it.id == currentDown.id } 126 | } else { 127 | val newPressed = event.changes.fastFirstOrNull { it.pressed } 128 | if (newPressed != null) { 129 | currentDown = newPressed 130 | longPress = currentDown 131 | } else { 132 | // should technically never happen as we checked it above 133 | finished = true 134 | } 135 | } 136 | } 137 | } 138 | } 139 | null 140 | } catch (_: TimeoutCancellationException) { 141 | longPress ?: initialDown 142 | } 143 | } 144 | 145 | private fun PointerEvent.isPointerUp(pointerId: PointerId): Boolean = 146 | changes.fastFirstOrNull { it.id == pointerId }?.pressed != true 147 | 148 | // This value was determined using experiments and common sense. 149 | // We can't use zero slop, because some hypothetical desktop/mobile devices can send 150 | // pointer events with a very high precision (but I haven't encountered any that send 151 | // events with less than 1px precision) 152 | private val mouseSlop = 0.125.dp 153 | private val defaultTouchSlop = 18.dp // The default touch slop on Android devices 154 | private val mouseToTouchSlopRatio = mouseSlop / defaultTouchSlop 155 | 156 | // TODO(demin): consider this as part of ViewConfiguration class after we make *PointerSlop* 157 | // functions public (see the comment at the top of the file). 158 | // After it will be a public API, we should get rid of `touchSlop / 144` and return absolute 159 | // value 0.125.dp.toPx(). It is not possible right now, because we can't access density. 160 | private fun ViewConfiguration.pointerSlop(pointerType: PointerType): Float { 161 | return when (pointerType) { 162 | PointerType.Mouse -> touchSlop * mouseToTouchSlopRatio 163 | else -> touchSlop 164 | } 165 | } -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /reorderable/src/commonMain/kotlin/org/burnoutcrew/reorderable/ReorderableState.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2022 André Claßen 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package org.burnoutcrew.reorderable 17 | 18 | import androidx.compose.runtime.getValue 19 | import androidx.compose.runtime.mutableStateOf 20 | import androidx.compose.runtime.setValue 21 | import androidx.compose.runtime.snapshotFlow 22 | import androidx.compose.runtime.withFrameMillis 23 | import androidx.compose.ui.geometry.Offset 24 | import androidx.compose.ui.util.fastForEach 25 | import kotlinx.coroutines.CoroutineScope 26 | import kotlinx.coroutines.ExperimentalCoroutinesApi 27 | import kotlinx.coroutines.Job 28 | import kotlinx.coroutines.channels.Channel 29 | import kotlinx.coroutines.flow.distinctUntilChanged 30 | import kotlinx.coroutines.flow.filterNotNull 31 | import kotlinx.coroutines.flow.flatMapLatest 32 | import kotlinx.coroutines.flow.flowOf 33 | import kotlinx.coroutines.launch 34 | import kotlin.math.absoluteValue 35 | import kotlin.math.min 36 | import kotlin.math.sign 37 | 38 | 39 | abstract class ReorderableState( 40 | private val scope: CoroutineScope, 41 | private val maxScrollPerFrame: Float, 42 | private val onMove: (fromIndex: ItemPosition, toIndex: ItemPosition) -> (Unit), 43 | private val canDragOver: ((draggedOver: ItemPosition, dragging: ItemPosition) -> Boolean)?, 44 | private val onDragEnd: ((startIndex: Int, endIndex: Int) -> (Unit))?, 45 | val dragCancelledAnimation: DragCancelledAnimation 46 | ) { 47 | var draggingItemIndex by mutableStateOf(null) 48 | private set 49 | val draggingItemKey: Any? 50 | get() = selected?.itemKey 51 | protected abstract val T.left: Int 52 | protected abstract val T.top: Int 53 | protected abstract val T.right: Int 54 | protected abstract val T.bottom: Int 55 | protected abstract val T.width: Int 56 | protected abstract val T.height: Int 57 | protected abstract val T.itemIndex: Int 58 | protected abstract val T.itemKey: Any 59 | protected abstract val visibleItemsInfo: List 60 | protected abstract val firstVisibleItemIndex: Int 61 | protected abstract val firstVisibleItemScrollOffset: Int 62 | protected abstract val viewportStartOffset: Int 63 | protected abstract val viewportEndOffset: Int 64 | internal val interactions = Channel() 65 | internal val scrollChannel = Channel() 66 | val draggingItemLeft: Float 67 | get() = draggingLayoutInfo?.let { item -> 68 | (selected?.left ?: 0) + draggingDelta.x - item.left 69 | } ?: 0f 70 | val draggingItemTop: Float 71 | get() = draggingLayoutInfo?.let { item -> 72 | (selected?.top ?: 0) + draggingDelta.y - item.top 73 | } ?: 0f 74 | abstract val isVerticalScroll: Boolean 75 | private val draggingLayoutInfo: T? 76 | get() = visibleItemsInfo 77 | .firstOrNull { it.itemIndex == draggingItemIndex } 78 | private var draggingDelta by mutableStateOf(Offset.Zero) 79 | private var selected by mutableStateOf(null) 80 | private var autoscroller: Job? = null 81 | private val targets = mutableListOf() 82 | private val distances = mutableListOf() 83 | 84 | protected abstract suspend fun scrollToItem(index: Int, offset: Int) 85 | 86 | @OptIn(ExperimentalCoroutinesApi::class) 87 | internal fun visibleItemsChanged() = 88 | snapshotFlow { draggingItemIndex != null } 89 | .flatMapLatest { if (it) snapshotFlow { visibleItemsInfo } else flowOf(null) } 90 | .filterNotNull() 91 | .distinctUntilChanged { old, new -> old.firstOrNull()?.itemIndex == new.firstOrNull()?.itemIndex && old.count() == new.count() } 92 | 93 | internal open fun onDragStart(offsetX: Int, offsetY: Int): Boolean { 94 | val x: Int 95 | val y: Int 96 | if (isVerticalScroll) { 97 | x = offsetX 98 | y = offsetY + viewportStartOffset 99 | } else { 100 | x = offsetX + viewportStartOffset 101 | y = offsetY 102 | } 103 | return visibleItemsInfo 104 | .firstOrNull { x in it.left..it.right && y in it.top..it.bottom } 105 | ?.also { 106 | selected = it 107 | draggingItemIndex = it.itemIndex 108 | } != null 109 | } 110 | 111 | internal fun onDragCanceled() { 112 | val dragIdx = draggingItemIndex 113 | if (dragIdx != null) { 114 | val position = ItemPosition(dragIdx, selected?.itemKey) 115 | val offset = Offset(draggingItemLeft, draggingItemTop) 116 | scope.launch { 117 | dragCancelledAnimation.dragCancelled(position, offset) 118 | } 119 | } 120 | val startIndex = selected?.itemIndex 121 | val endIndex = draggingItemIndex 122 | selected = null 123 | draggingDelta = Offset.Zero 124 | draggingItemIndex = null 125 | cancelAutoScroll() 126 | onDragEnd?.apply { 127 | if (startIndex != null && endIndex != null) { 128 | invoke(startIndex, endIndex) 129 | } 130 | } 131 | } 132 | 133 | internal fun onDrag(offsetX: Int, offsetY: Int) { 134 | val selected = selected ?: return 135 | draggingDelta = Offset(draggingDelta.x + offsetX, draggingDelta.y + offsetY) 136 | val draggingItem = draggingLayoutInfo ?: return 137 | val startOffset = draggingItem.top + draggingItemTop 138 | val startOffsetX = draggingItem.left + draggingItemLeft 139 | chooseDropItem( 140 | draggingItem, 141 | findTargets(draggingDelta.x.toInt(), draggingDelta.y.toInt(), selected), 142 | startOffsetX.toInt(), 143 | startOffset.toInt() 144 | )?.also { targetItem -> 145 | if (targetItem.itemIndex == firstVisibleItemIndex || draggingItem.itemIndex == firstVisibleItemIndex) { 146 | scope.launch { 147 | onMove.invoke( 148 | ItemPosition(draggingItem.itemIndex, draggingItem.itemKey), 149 | ItemPosition(targetItem.itemIndex, targetItem.itemKey) 150 | ) 151 | scrollToItem(firstVisibleItemIndex, firstVisibleItemScrollOffset) 152 | } 153 | } else { 154 | onMove.invoke( 155 | ItemPosition(draggingItem.itemIndex, draggingItem.itemKey), 156 | ItemPosition(targetItem.itemIndex, targetItem.itemKey) 157 | ) 158 | } 159 | draggingItemIndex = targetItem.itemIndex 160 | } 161 | 162 | with(calcAutoScrollOffset(0, maxScrollPerFrame)) { 163 | if (this != 0f) autoscroll(this) 164 | } 165 | } 166 | 167 | private fun autoscroll(scrollOffset: Float) { 168 | if (scrollOffset != 0f) { 169 | if (autoscroller?.isActive == true) { 170 | return 171 | } 172 | autoscroller = scope.launch { 173 | var scroll = scrollOffset 174 | var start = 0L 175 | while (scroll != 0f && autoscroller?.isActive == true) { 176 | withFrameMillis { 177 | if (start == 0L) { 178 | start = it 179 | } else { 180 | scroll = calcAutoScrollOffset(it - start, maxScrollPerFrame) 181 | } 182 | } 183 | scrollChannel.trySend(scroll) 184 | } 185 | } 186 | } else { 187 | cancelAutoScroll() 188 | } 189 | } 190 | 191 | private fun cancelAutoScroll() { 192 | autoscroller?.cancel() 193 | autoscroller = null 194 | } 195 | 196 | protected open fun findTargets(x: Int, y: Int, selected: T): List { 197 | targets.clear() 198 | distances.clear() 199 | val left = x + selected.left 200 | val right = x + selected.right 201 | val top = y + selected.top 202 | val bottom = y + selected.bottom 203 | val centerX = (left + right) / 2 204 | val centerY = (top + bottom) / 2 205 | visibleItemsInfo.fastForEach { item -> 206 | if ( 207 | item.itemIndex == draggingItemIndex 208 | || item.bottom < top 209 | || item.top > bottom 210 | || item.right < left 211 | || item.left > right 212 | ) { 213 | return@fastForEach 214 | } 215 | if (canDragOver?.invoke( 216 | ItemPosition(item.itemIndex, item.itemKey), 217 | ItemPosition(selected.itemIndex, selected.itemKey) 218 | ) != false 219 | ) { 220 | val dx = (centerX - (item.left + item.right) / 2).absoluteValue 221 | val dy = (centerY - (item.top + item.bottom) / 2).absoluteValue 222 | val dist = dx * dx + dy * dy 223 | var pos = 0 224 | for (j in targets.indices) { 225 | if (dist > distances[j]) { 226 | pos++ 227 | } else { 228 | break 229 | } 230 | } 231 | targets.add(pos, item) 232 | distances.add(pos, dist) 233 | } 234 | } 235 | return targets 236 | } 237 | 238 | protected open fun chooseDropItem(draggedItemInfo: T?, items: List, curX: Int, curY: Int): T? { 239 | if (draggedItemInfo == null) { 240 | return if (draggingItemIndex != null) items.lastOrNull() else null 241 | } 242 | var target: T? = null 243 | var highScore = -1 244 | val right = curX + draggedItemInfo.width 245 | val bottom = curY + draggedItemInfo.height 246 | val dx = curX - draggedItemInfo.left 247 | val dy = curY - draggedItemInfo.top 248 | 249 | items.fastForEach { item -> 250 | if (dx > 0) { 251 | val diff = item.right - right 252 | if (diff < 0 && item.right > draggedItemInfo.right) { 253 | val score = diff.absoluteValue 254 | if (score > highScore) { 255 | highScore = score 256 | target = item 257 | } 258 | } 259 | } 260 | if (dx < 0) { 261 | val diff = item.left - curX 262 | if (diff > 0 && item.left < draggedItemInfo.left) { 263 | val score = diff.absoluteValue 264 | if (score > highScore) { 265 | highScore = score 266 | target = item 267 | } 268 | } 269 | } 270 | if (dy < 0) { 271 | val diff = item.top - curY 272 | if (diff > 0 && item.top < draggedItemInfo.top) { 273 | val score = diff.absoluteValue 274 | if (score > highScore) { 275 | highScore = score 276 | target = item 277 | } 278 | } 279 | } 280 | if (dy > 0) { 281 | val diff = item.bottom - bottom 282 | if (diff < 0 && item.bottom > draggedItemInfo.bottom) { 283 | val score = diff.absoluteValue 284 | if (score > highScore) { 285 | highScore = score 286 | target = item 287 | } 288 | } 289 | } 290 | } 291 | return target 292 | } 293 | 294 | private fun calcAutoScrollOffset(time: Long, maxScroll: Float): Float { 295 | val draggingItem = draggingLayoutInfo ?: return 0f 296 | val startOffset: Float 297 | val endOffset: Float 298 | val delta: Float 299 | if (isVerticalScroll) { 300 | startOffset = draggingItem.top + draggingItemTop 301 | endOffset = startOffset + draggingItem.height 302 | delta = draggingDelta.y 303 | } else { 304 | startOffset = draggingItem.left + draggingItemLeft 305 | endOffset = startOffset + draggingItem.width 306 | delta = draggingDelta.x 307 | } 308 | return when { 309 | delta > 0 -> 310 | (endOffset - viewportEndOffset).coerceAtLeast(0f) 311 | delta < 0 -> 312 | (startOffset - viewportStartOffset).coerceAtMost(0f) 313 | else -> 0f 314 | } 315 | .let { interpolateOutOfBoundsScroll((endOffset - startOffset).toInt(), it, time, maxScroll) } 316 | } 317 | 318 | 319 | companion object { 320 | private const val ACCELERATION_LIMIT_TIME_MS: Long = 1500 321 | private val EaseOutQuadInterpolator: (Float) -> (Float) = { 322 | val t = 1 - it 323 | 1 - t * t * t * t 324 | } 325 | private val EaseInQuintInterpolator: (Float) -> (Float) = { 326 | it * it * it * it * it 327 | } 328 | 329 | private fun interpolateOutOfBoundsScroll( 330 | viewSize: Int, 331 | viewSizeOutOfBounds: Float, 332 | time: Long, 333 | maxScroll: Float, 334 | ): Float { 335 | if (viewSizeOutOfBounds == 0f) return 0f 336 | val outOfBoundsRatio = min(1f, 1f * viewSizeOutOfBounds.absoluteValue / viewSize) 337 | val cappedScroll = sign(viewSizeOutOfBounds) * maxScroll * EaseOutQuadInterpolator(outOfBoundsRatio) 338 | val timeRatio = if (time > ACCELERATION_LIMIT_TIME_MS) 1f else time.toFloat() / ACCELERATION_LIMIT_TIME_MS 339 | return (cappedScroll * EaseInQuintInterpolator(timeRatio)).let { 340 | if (it == 0f) { 341 | if (viewSizeOutOfBounds > 0) 1f else -1f 342 | } else { 343 | it 344 | } 345 | } 346 | } 347 | } 348 | } 349 | --------------------------------------------------------------------------------