Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Animation issue when swapping the first item in a lazy layout #4

Open
MiniEmerald opened this issue Dec 12, 2023 · 40 comments
Open

Animation issue when swapping the first item in a lazy layout #4

MiniEmerald opened this issue Dec 12, 2023 · 40 comments
Labels
Waiting for Compose Foundation v1.7.0 Waiting for Compose Foundation v1.7.0 to be in Compose Multiplatform

Comments

@MiniEmerald
Copy link

MiniEmerald commented Dec 12, 2023

In the simple lazy column sample, swapping the first item instantly moves most of it outside the screen for a split second.

Tested in the android emulator on Android 14

Screen_recording_20231212_215838.webm
@Calvin-LL
Copy link
Owner

Unfortunately that is one of the drawbacks of using .animateItemPlacement(). This happens whenever the position of the first visible item it changed.

I'll leave this issue open to see if anyone can find a solution.

Details

This video shows what happens when the first and second items are swapped in a LazyColumn where every item that has .animateItemPlacement().

Screen_recording_20231212_164220.mp4

As you can see, the position of Item #0 stays the same while all the other items move around it.

Turns out .animateItemPlacement() will always keep the first visible item in place as an anchor.

But when we are dragging Item #1 and swapping it with Item #0, we don't want Item #1 to disappear above Item #0.

So I decided to do what this Android demo does in here. When an item is dragged to replace the first visible item:

  1. scroll to the item that will replace the first visible item so that it will remain the first visible item after the swap (in the case in your video, that's Item #1)
  2. call the callback that will actually swap the dragging item with the first visible item

And similarly, when the first visible item is dragged to replace another item:

  1. scroll to the target item so that it will remain the first visible item after the swap
  2. call the callback that will actually swap the first visible item with the target item

All this means that whenever the position of the first visible item changes, items will move around in a weird way.

@spiral123
Copy link

Firstly, thanks for the library - it's very useful.

I have a workaround for the visual glitching when moving over the first item.

In my app I'm adding a dummy element as the first item in the reorderable list. When I render the list I ensure that the dummy ReorderableItem has enabled = false and render it as a 1.dp high empty row. The remaining list items are resolved normally.

For example, Items.kt now becomes:

data class Item(val id: UUID = UUID.randomUUID(), val sequence: Int, val size: Int)

val items = (-1..200).map {
    Item(sequence = it, size = if (it % 2 == 0) 50 else 100)
}

and SimpleReorderableLazyColumnScreen.kt would be:

@OptIn(ExperimentalFoundationApi::class)
@Composable
fun SimpleReorderableLazyColumnScreen() {
  val view = LocalView.current

  var list by remember { mutableStateOf(items) }
  val lazyListState = rememberLazyListState()
  val reorderableLazyColumnState = rememberReorderableLazyColumnState(lazyListState) { from, to ->
    list = list.toMutableList().apply {
      add(to.index, removeAt(from.index))
    }

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE) {
      view.performHapticFeedback(HapticFeedbackConstants.SEGMENT_FREQUENT_TICK)
    }
  }

  LazyColumn(
    modifier = Modifier.fillMaxSize(),
    state = lazyListState,
    contentPadding = PaddingValues(8.dp),
    verticalArrangement = Arrangement.spacedBy(8.dp)
  ) {
    items(list, key = { it.id }) {
      ReorderableItem(
        reorderableLazyListState = reorderableLazyColumnState,
        key = it.id,
        enabled = it.sequence > -1,
      ) { isDragging ->
        val elevation by animateDpAsState(if (isDragging) 4.dp else 0.dp)

        if (it.sequence < 0) {
          Row(modifier = Modifier.height(1.dp)) { }
        } else {
          Card(
            modifier = Modifier.height(it.size.dp),
            shadowElevation = elevation,
          ) {
            Text("Item #${it.sequence}", Modifier.padding(horizontal = 8.dp))
            IconButton(
              modifier = Modifier.draggableHandle(
                onDragStarted = {
                  if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE) {
                    view.performHapticFeedback(HapticFeedbackConstants.DRAG_START)
                  }
                },
                onDragStopped = {
                  if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
                    view.performHapticFeedback(HapticFeedbackConstants.GESTURE_END)
                  }
                },
              ),
              onClick = {},
            ) {
              Icon(Icons.Rounded.DragHandle, contentDescription = "Reorder")
            }
          }
        }
      }
    }
  }
}

@dhng22
Copy link

dhng22 commented Jan 12, 2024

@spiral123 's workaround was right, i made a shorter solution for the LazyList:

val reorderableLazyListState = rememberReorderableLazyColumnState { from, to ->
        currentList.swapPosition(from.index - 1, to.index - 1)
        ...
}
LazyColumn(modifier = modifier,
           state = reorderableLazyListState.state) {
    item {
        ReorderableItem(reorderableLazyListState,
                        "dummy",
                        enabled = false,
                        modifier = Modifier.fillMaxWidth().height(Dp.Hairline)) {}
    }
    items(currentList, key = { it.id }) { item ->
        ReorderableItem(reorderableLazyListState, item.id) {
            Item(item) { 
                  ...
            }
        }
    }
 }

Make a dummy item with enable = false then minus from and to index by 1 and you're good to go

@PatricioRios
Copy link

PatricioRios commented Mar 27, 2024

Can't you make the first element (partially not visible), non-draggable?,
I have used the dhng22 solution, but even so when I move the lazy a little the problem still appears

@mak1nt0sh
Copy link

Is this the issue? It just got marked as fixed, so maybe the patch will be live soon
https://issuetracker.google.com/issues/209652366

@Calvin-LL
Copy link
Owner

Is this the issue? It just got marked as fixed, so maybe the patch will be live soon
https://issuetracker.google.com/issues/209652366

Thank you for sharing this. I think this is the issue. I will update the library when this comes out. (the issue you mentioned took more than 2 years to get a fix ☠️)

Calvin-LL added a commit that referenced this issue Apr 3, 2024
@Calvin-LL Calvin-LL reopened this Apr 3, 2024
@vganin
Copy link

vganin commented Apr 16, 2024

Can't you make the first element (partially not visible), non-draggable?,
I have used the dhng22 solution, but even so when I move the lazy a little the problem still appears

Dp.Hairline isn't working for me either, but 1.dp does. Probably Compose at that time wasn't optimising empty layout nodes out, but now it does. Also, we don't need extra disabled ReorderableItem, dummy view is enough. So, simplifying it even further, this worked for me:

item {
    Spacer(Modifier.height(1.dp))
}

And the rest is the same.

@Calvin-LL
Copy link
Owner

Is this the issue? It just got marked as fixed, so maybe the patch will be live soon
https://issuetracker.google.com/issues/209652366

Thank you for sharing this. I think this is the issue. I will update the library when this comes out. (the issue you mentioned took more than 2 years to get a fix ☠️)

Looks like this will be released in Compose Foundation v1.7.0 which is currently in alpha. https://developer.android.com/jetpack/androidx/releases/compose-foundation#1.7.0-alpha07

I'll update this library once v1.7.0 make it to compose multiplatform.

@Calvin-LL Calvin-LL added the Waiting for Compose Foundation v1.7.0 Waiting for Compose Foundation v1.7.0 to be in Compose Multiplatform label May 9, 2024
@zhelenskiy
Copy link

Is it this problem or not?

Screen.Recording.2024-05-10.at.01.23.09.mov

@Calvin-LL
Copy link
Owner

That doesn't look right. Can you share a minimal reproducible example?

@zhelenskiy
Copy link

zhelenskiy commented May 9, 2024

Screen.Recording.2024-05-10.at.01.55.33.mov

It can be partially reproduced with my previous example if you decrease the size of the window.

@zhelenskiy
Copy link

Screen.Recording.2024-05-10.at.02.01.41.mov

Or you can just make the tabs wider:

import androidx.compose.animation.*
import androidx.compose.animation.core.animateDpAsState
import androidx.compose.desktop.ui.tooling.preview.Preview
import androidx.compose.foundation.*
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyRow
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.lazy.itemsIndexed
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.*
import androidx.compose.material.MaterialTheme.colors
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Add
import androidx.compose.material.icons.filled.Close
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.input.TextFieldValue
import androidx.compose.ui.text.rememberTextMeasurer
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.compose.ui.window.Window
import androidx.compose.ui.window.application
import kotlinx.coroutines.launch
import sh.calvin.reorderable.ReorderableItem
import sh.calvin.reorderable.rememberReorderableLazyListState

@Composable
@Preview
fun App() {
    MaterialTheme {
        TabRow()
    }
}

fun main() = application {
    Window(onCloseRequest = ::exitApplication) {
        App()
    }
}

typealias Id = Long

data class Tab(val id: Id)

@OptIn(ExperimentalFoundationApi::class)
@Composable
private fun TabRow() {
    var tabModels: List<Tab> by remember { mutableStateOf(listOf(Tab(-1))) }
    val coroutineScope = rememberCoroutineScope()
    val tabRowScrollState = rememberLazyListState()
    val reorderableLazyColumnState =
        rememberReorderableLazyListState(tabRowScrollState) { from, to ->
            coroutineScope.launch {
                tabModels = tabModels.toMutableList().apply {
                    add(to.index, removeAt(from.index))
                }
            }
        }
    var chosenId by remember { mutableStateOf(tabModels.first().id) }
    BoxWithConstraints {
        AnimatedVisibility(
            visible = maxHeight > 300.dp,
            enter = expandVertically(),
            exit = shrinkVertically(),
        ) {
            LazyRow(
                state = tabRowScrollState,
                verticalAlignment = Alignment.CenterVertically,
                modifier = Modifier.fillMaxWidth(),
                contentPadding = PaddingValues(horizontal = 1.dp),
            ) {
                items(tabModels, key = { model -> model.id }) { tabModel ->
                    ReorderableItem(
                        reorderableLazyColumnState,
                        key = tabModel.id
                    ) { _ ->
                        val isSelected = tabModel.id == chosenId
                        val chooseThis = { coroutineScope.launch { chosenId = tabModel.id } }
                        Row(
                            Modifier
                                .height(IntrinsicSize.Min).draggableHandle()
                        ) {
                            Tab(
                                selected = isSelected,
                                enabled = !isSelected,
                                modifier = Modifier
                                    .padding(horizontal = 2.dp)
                                    .clip(RoundedCornerShape(topEnd = 4.dp, topStart = 4.dp))
                                    .width(200.dp),
                                onClick = { chooseThis() },
                            ) {
                                Box(Modifier.width(IntrinsicSize.Min)) {
                                    val textColor = if (isSelected) Color.Black else Color.Blue
                                    val maxTabWidth = 300.dp
                                    Row(
                                        verticalAlignment = Alignment.CenterVertically,
                                        modifier = Modifier.widthIn(max = maxTabWidth)
                                            .padding(vertical = 4.dp)
                                            .padding(start = 12.dp),
                                    ) {
                                        Spacer(Modifier.width(6.dp))
                                        val textStyle =
                                            TextStyle(color = textColor, fontSize = 18.sp)
                                        Box(Modifier.weight(1f)) {
                                            Text(
                                                text = tabModel.id.toString(),
                                                style = textStyle,
                                                maxLines = 1,
                                                softWrap = false,
                                                modifier = Modifier
                                                    .horizontalScroll(rememberScrollState())
                                            )
                                        }
                                        val expectedCloseSize by animateDpAsState(if (tabModels.size > 1) 48.dp else 8.dp)
                                        Box(Modifier.width(expectedCloseSize)) {
                                            androidx.compose.animation.AnimatedVisibility(
                                                tabModels.size > 1,
                                                enter = scaleIn() + fadeIn(),
                                                exit = scaleOut() + fadeOut(),
                                            ) {
                                                IconButton(
                                                    onClick = {
                                                    },
                                                    enabled = tabModels.size > 1,
                                                ) {
                                                    Icon(
                                                        imageVector = Icons.Default.Close,
                                                        tint = textColor,
                                                        contentDescription = "Close tab"
                                                    )
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                item {
                    IconButton(
                        onClick = {
                            coroutineScope.launch {
                                tabModels += Tab(tabModels.size.toLong())
                            }
                        }
                    ) {
                        Icon(
                            Icons.Default.Add,
                            contentDescription = "Add tab",
                        )
                    }
                }
            }
        }
    }
}

@zhelenskiy
Copy link

It also scrolls in this case for some reason.

Screen.Recording.2024-05-10.at.02.12.13.mov

@Calvin-LL
Copy link
Owner

Calvin-LL commented May 10, 2024

@zhelenskiy try 2.1.1-dev. I think this should be fixed there. Just published it so it might take a few minutes to be available.

@zhelenskiy
Copy link

Still reproducible there

@Calvin-LL
Copy link
Owner

Just the flashing or still can't move the second item to the first position?

@zhelenskiy
Copy link

Screen.Recording.2024-05-10.at.02.47.14.mov

@zhelenskiy
Copy link

By the way, the version is not available on GitHub.

@Calvin-LL
Copy link
Owner

Hmm I will investigate further tomorrow. It's not on GitHub because I made it just for you ❤️.

@Calvin-LL
Copy link
Owner

@zhelenskiy give 2.1.1-dev2 a try. You should be able to drag the second item to the first position now.

@zhelenskiy
Copy link

I can. But it is still jumping and scrolling right.

Screen.Recording.2024-05-11.at.02.50.05.mov

@Calvin-LL
Copy link
Owner

Yeah I think that's the expected behavior right now. Will be fixed when Foundation v1.7.0

@zhelenskiy
Copy link

zhelenskiy commented May 11, 2024

Both scrolling and jumping? Is there any workaround?

@zhelenskiy
Copy link

When you have a little of space, it is still almost impossible to move the tab. It starts scrolling too fast, may drop dragging.

Screen.Recording.2024-05-11.at.04.21.33.mp4

@Calvin-LL
Copy link
Owner

Both scrolling and jumping? Is there any workaround?

Yeah they jumping will happen whenever the first item moves

@Calvin-LL
Copy link
Owner

When you have a little of space, it is still almost impossible to move the tab. It starts scrolling too fast, may drop dragging.

Oh hmm I will need to think about this one. I think I can make the drag speed depend on the item size.

@Calvin-LL
Copy link
Owner

When you have a little of space, it is still almost impossible to move the tab. It starts scrolling too fast, may drop dragging.

I'll get back to you by the end of the upcoming Friday.

@Calvin-LL
Copy link
Owner

@zhelenskiy should be fixed in 2.1.1. Thanks again for finding these bugs ❤️ .

@zhelenskiy
Copy link

It is much better! But it still drops drag when I try to move the first item.

Screen.Recording.2024-05-13.at.14.09.40.mov

@Calvin-LL
Copy link
Owner

It is much better! But it still drops drag when I try to move the first item.

Yeah so the problem is it's either this or scrolling too fast as in #4 (comment). It's caused by the fact that moving the first visible item causes strange things to happen. This too will be solved in Foundation 1.7.0.

@zhelenskiy
Copy link

Ok, thanks! Let's wait then.

@zhelenskiy
Copy link

Moving the first item does not work on Android.

Screen.Recording.2024-05-14.at.23.25.26.mov

@Calvin-LL
Copy link
Owner

Calvin-LL commented May 14, 2024

Is onMoved called at all? Is there a chance the wrong item is being moved in onMove? Looks like the "Foxing" tab is being moved instead.

@zhelenskiy
Copy link

Yes, it seems to be what happened.

@zhelenskiy
Copy link

I logged move indexes during this strange movement:
0 -> 1
0 -> 2

@Calvin-LL
Copy link
Owner

Is there a coroutine launch in onMove? Try if removing that helps.

@zhelenskiy
Copy link

What do you expect me to write then?

rememberReorderableLazyListState(tabRowScrollState) { from, to ->
    println(from.index to to.index)
    coroutineScope.launch {
        viewModel.move(from.index, to.index)
    }
}

@Calvin-LL
Copy link
Owner

Calvin-LL commented May 14, 2024

Try

rememberReorderableLazyListState(tabRowScrollState) { from, to ->
    println(from.index to to.index)
    viewModel.move(from.index, to.index)
}

@zhelenskiy
Copy link

Oh, it is already suspend.

@zhelenskiy
Copy link

Now that works fine! Thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Waiting for Compose Foundation v1.7.0 Waiting for Compose Foundation v1.7.0 to be in Compose Multiplatform
Projects
None yet
Development

No branches or pull requests

8 participants