Reorderable icon indicating copy to clipboard operation
Reorderable copied to clipboard

Animation issue when swapping the first item in a lazy layout

Open MiniEmerald opened this issue 2 years ago • 46 comments

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

MiniEmerald avatar Dec 12 '23 23:12 MiniEmerald

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().

https://github.com/Calvin-LL/Reorderable/assets/8357970/2ecf60a8-f9fa-4a92-ba1f-ffe5f7db4cb8

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.

Calvin-LL avatar Dec 13 '23 01:12 Calvin-LL

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")
            }
          }
        }
      }
    }
  }
}

spiral123 avatar Jan 09 '24 15:01 spiral123

@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

dhng22 avatar Jan 12 '24 15:01 dhng22

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

PatricioRios avatar Mar 27 '24 00:03 PatricioRios

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

mak1nt0sh avatar Mar 28 '24 16:03 mak1nt0sh

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 avatar Mar 28 '24 22:03 Calvin-LL

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.

vganin avatar Apr 16 '24 19:04 vganin

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 avatar Apr 21 '24 18:04 Calvin-LL

Is it this problem or not?

https://github.com/Calvin-LL/Reorderable/assets/55230817/22684d9a-228f-4391-9ee7-5e54e10b7bf0

zhelenskiy avatar May 09 '24 23:05 zhelenskiy

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

Calvin-LL avatar May 09 '24 23:05 Calvin-LL

https://github.com/Calvin-LL/Reorderable/assets/55230817/bfe28bd1-6f39-41c8-94e1-fda388d65eea

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

zhelenskiy avatar May 09 '24 23:05 zhelenskiy

https://github.com/Calvin-LL/Reorderable/assets/55230817/166036b1-c91d-4ce3-baf8-0476d0bbd560

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 avatar May 10 '24 00:05 zhelenskiy

It also scrolls in this case for some reason.

https://github.com/Calvin-LL/Reorderable/assets/55230817/223bc73e-93f9-4e3e-8f90-db3437336dcd

zhelenskiy avatar May 10 '24 00:05 zhelenskiy

@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.

Calvin-LL avatar May 10 '24 00:05 Calvin-LL

Still reproducible there

zhelenskiy avatar May 10 '24 00:05 zhelenskiy

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

Calvin-LL avatar May 10 '24 00:05 Calvin-LL

https://github.com/Calvin-LL/Reorderable/assets/55230817/5f4309a2-8ea7-4d03-8660-ed9a89e9dcb9

zhelenskiy avatar May 10 '24 00:05 zhelenskiy

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

zhelenskiy avatar May 10 '24 00:05 zhelenskiy

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

Calvin-LL avatar May 10 '24 00:05 Calvin-LL

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

Calvin-LL avatar May 11 '24 00:05 Calvin-LL

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

https://github.com/Calvin-LL/Reorderable/assets/55230817/b94951e9-77f5-4b01-bb2b-2a7ab07871a2

zhelenskiy avatar May 11 '24 00:05 zhelenskiy

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

Calvin-LL avatar May 11 '24 00:05 Calvin-LL

Both scrolling and jumping? Is there any workaround?

zhelenskiy avatar May 11 '24 01:05 zhelenskiy

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

https://github.com/Calvin-LL/Reorderable/assets/55230817/5bfb3d72-0961-4404-b807-fe882d2d7bfa

zhelenskiy avatar May 11 '24 02:05 zhelenskiy

Both scrolling and jumping? Is there any workaround?

Yeah they jumping will happen whenever the first item moves

Calvin-LL avatar May 11 '24 04:05 Calvin-LL

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 avatar May 11 '24 04:05 Calvin-LL

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 avatar May 11 '24 18:05 Calvin-LL

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

Calvin-LL avatar May 13 '24 03:05 Calvin-LL

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

https://github.com/Calvin-LL/Reorderable/assets/55230817/f4ec840f-6d69-45ba-8251-bd3cc7ed53ec

zhelenskiy avatar May 13 '24 12:05 zhelenskiy

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 https://github.com/Calvin-LL/Reorderable/issues/4#issuecomment-2105485414. 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.

Calvin-LL avatar May 13 '24 22:05 Calvin-LL