feat(dm): 날짜 행과 복귀 스크롤 보존을 연결한다
This commit is contained in:
@@ -15,9 +15,17 @@ import kr.co.vividnext.sodalive.common.LoadingDialog
|
|||||||
import kr.co.vividnext.sodalive.common.SharedPreferenceManager
|
import kr.co.vividnext.sodalive.common.SharedPreferenceManager
|
||||||
import kr.co.vividnext.sodalive.databinding.ActivityDmChatRoomBinding
|
import kr.co.vividnext.sodalive.databinding.ActivityDmChatRoomBinding
|
||||||
import kr.co.vividnext.sodalive.extensions.loadUrl
|
import kr.co.vividnext.sodalive.extensions.loadUrl
|
||||||
|
import kr.co.vividnext.sodalive.settings.language.LanguageManager
|
||||||
import kr.co.vividnext.sodalive.v2.main.chat.dm.model.DmChatRoomUiState
|
import kr.co.vividnext.sodalive.v2.main.chat.dm.model.DmChatRoomUiState
|
||||||
|
import kr.co.vividnext.sodalive.v2.main.chat.dm.model.DmChatScrollState
|
||||||
|
import kr.co.vividnext.sodalive.v2.main.chat.dm.model.firstMessagePosition
|
||||||
|
import kr.co.vividnext.sodalive.v2.main.chat.dm.model.identity
|
||||||
|
import kr.co.vividnext.sodalive.v2.main.chat.dm.model.isDmChatNearBottom
|
||||||
|
import kr.co.vividnext.sodalive.v2.main.chat.dm.model.toTimelineItems
|
||||||
import kr.co.vividnext.sodalive.v2.main.chat.dm.ui.DmChatMessageAdapter
|
import kr.co.vividnext.sodalive.v2.main.chat.dm.ui.DmChatMessageAdapter
|
||||||
import org.koin.androidx.viewmodel.ext.android.viewModel
|
import org.koin.androidx.viewmodel.ext.android.viewModel
|
||||||
|
import java.util.Locale
|
||||||
|
import java.util.TimeZone
|
||||||
|
|
||||||
class DmChatRoomActivity : BaseActivity<ActivityDmChatRoomBinding>(
|
class DmChatRoomActivity : BaseActivity<ActivityDmChatRoomBinding>(
|
||||||
ActivityDmChatRoomBinding::inflate
|
ActivityDmChatRoomBinding::inflate
|
||||||
@@ -30,8 +38,7 @@ class DmChatRoomActivity : BaseActivity<ActivityDmChatRoomBinding>(
|
|||||||
private var roomId: Long = 0L
|
private var roomId: Long = 0L
|
||||||
private var creatorId: Long = 0L
|
private var creatorId: Long = 0L
|
||||||
private var isStarted: Boolean = false
|
private var isStarted: Boolean = false
|
||||||
private var firstVisiblePositionBeforePrepend: Int = RecyclerView.NO_POSITION
|
private val scrollState = DmChatScrollState()
|
||||||
private var firstVisibleTopBeforePrepend: Int = 0
|
|
||||||
|
|
||||||
override fun setupView() {
|
override fun setupView() {
|
||||||
roomId = intent.getLongExtra(EXTRA_ROOM_ID, 0L)
|
roomId = intent.getLongExtra(EXTRA_ROOM_ID, 0L)
|
||||||
@@ -73,10 +80,19 @@ class DmChatRoomActivity : BaseActivity<ActivityDmChatRoomBinding>(
|
|||||||
binding.rvMessages.addOnScrollListener(object : RecyclerView.OnScrollListener() {
|
binding.rvMessages.addOnScrollListener(object : RecyclerView.OnScrollListener() {
|
||||||
override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
|
override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
|
||||||
super.onScrolled(recyclerView, dx, dy)
|
super.onScrolled(recyclerView, dx, dy)
|
||||||
if (layoutManager.findFirstVisibleItemPosition() == 0) {
|
if (recyclerView.scrollState == RecyclerView.SCROLL_STATE_DRAGGING && dy != 0) {
|
||||||
rememberScrollBeforePrepend()
|
scrollState.onUserScroll()
|
||||||
viewModel.loadOlderMessages()
|
|
||||||
}
|
}
|
||||||
|
if (layoutManager.findFirstVisibleItemPosition() == 0) {
|
||||||
|
val state = viewModel.chatRoomStateLiveData.value as? DmChatRoomUiState.Content ?: return
|
||||||
|
if (scrollState.beginPrepend(state, ::rememberScrollBeforePrepend)) {
|
||||||
|
viewModel.loadOlderMessages()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
|
||||||
|
if (newState == RecyclerView.SCROLL_STATE_DRAGGING) scrollState.onUserScroll()
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
@@ -104,6 +120,9 @@ class DmChatRoomActivity : BaseActivity<ActivityDmChatRoomBinding>(
|
|||||||
}
|
}
|
||||||
|
|
||||||
private fun bindViewModel() {
|
private fun bindViewModel() {
|
||||||
|
viewModel.prependedMessageCountLiveData.observe(this) { count ->
|
||||||
|
scrollState.onPrependCount(count)
|
||||||
|
}
|
||||||
viewModel.chatRoomStateLiveData.observe(this) { state ->
|
viewModel.chatRoomStateLiveData.observe(this) { state ->
|
||||||
when (state) {
|
when (state) {
|
||||||
is DmChatRoomUiState.Content -> bindContent(state)
|
is DmChatRoomUiState.Content -> bindContent(state)
|
||||||
@@ -114,9 +133,6 @@ class DmChatRoomActivity : BaseActivity<ActivityDmChatRoomBinding>(
|
|||||||
viewModel.finishEventLiveData.observe(this) {
|
viewModel.finishEventLiveData.observe(this) {
|
||||||
if (it == true) finish()
|
if (it == true) finish()
|
||||||
}
|
}
|
||||||
viewModel.prependedMessageCountLiveData.observe(this) { count ->
|
|
||||||
if (count > 0) restoreScrollAfterPrepend(count)
|
|
||||||
}
|
|
||||||
viewModel.roomOpenedEventLiveData.observe(this) {
|
viewModel.roomOpenedEventLiveData.observe(this) {
|
||||||
if (it.consume() == true) connectRealtimeIfStarted()
|
if (it.consume() == true) connectRealtimeIfStarted()
|
||||||
}
|
}
|
||||||
@@ -137,9 +153,15 @@ class DmChatRoomActivity : BaseActivity<ActivityDmChatRoomBinding>(
|
|||||||
placeholder(R.drawable.ic_placeholder_profile)
|
placeholder(R.drawable.ic_placeholder_profile)
|
||||||
error(R.drawable.ic_placeholder_profile)
|
error(R.drawable.ic_placeholder_profile)
|
||||||
}
|
}
|
||||||
messageAdapter.submitItems(state.messages)
|
messageAdapter.submitItems(
|
||||||
if (shouldScrollToBottom && state.messages.isNotEmpty()) {
|
state.messages.toTimelineItems(Locale(LanguageManager.getEffectiveLanguage(this)), TimeZone.getDefault())
|
||||||
binding.rvMessages.scrollToPosition(state.messages.lastIndex)
|
)
|
||||||
|
when (val update = scrollState.onContentSubmitted(state.isLoadingOlder, shouldScrollToBottom)) {
|
||||||
|
is DmChatScrollState.Update.Restore -> restoreScrollAfterPrepend(update)
|
||||||
|
DmChatScrollState.Update.Bottom -> if (messageAdapter.itemCount > 0) {
|
||||||
|
binding.rvMessages.scrollToPosition(messageAdapter.itemCount - 1)
|
||||||
|
}
|
||||||
|
DmChatScrollState.Update.None -> Unit
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -158,27 +180,24 @@ class DmChatRoomActivity : BaseActivity<ActivityDmChatRoomBinding>(
|
|||||||
binding.ivSend.alpha = if (enabled) 1.0f else 0.4f
|
binding.ivSend.alpha = if (enabled) 1.0f else 0.4f
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun rememberScrollBeforePrepend() {
|
private fun rememberScrollBeforePrepend(): DmChatScrollState.Anchor? {
|
||||||
firstVisiblePositionBeforePrepend = layoutManager.findFirstVisibleItemPosition()
|
val position = messageAdapter.items.firstMessagePosition(
|
||||||
val firstVisibleView = layoutManager.findViewByPosition(firstVisiblePositionBeforePrepend)
|
layoutManager.findFirstVisibleItemPosition(),
|
||||||
firstVisibleTopBeforePrepend = firstVisibleView?.top ?: 0
|
layoutManager.findLastVisibleItemPosition()
|
||||||
|
) ?: return null
|
||||||
|
val view = layoutManager.findViewByPosition(position) ?: return null
|
||||||
|
return DmChatScrollState.Anchor(messageAdapter.items[position].identity(), view.top)
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun restoreScrollAfterPrepend(count: Int) {
|
private fun restoreScrollAfterPrepend(restore: DmChatScrollState.Update.Restore) {
|
||||||
if (firstVisiblePositionBeforePrepend == RecyclerView.NO_POSITION) return
|
binding.rvMessages.post {
|
||||||
layoutManager.scrollToPositionWithOffset(
|
val position = scrollState.resolveRestore(restore, messageAdapter.items) ?: return@post
|
||||||
firstVisiblePositionBeforePrepend + count,
|
layoutManager.scrollToPositionWithOffset(position.position, position.top)
|
||||||
firstVisibleTopBeforePrepend
|
}
|
||||||
)
|
|
||||||
firstVisiblePositionBeforePrepend = RecyclerView.NO_POSITION
|
|
||||||
firstVisibleTopBeforePrepend = 0
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun isNearBottom(): Boolean {
|
private fun isNearBottom(): Boolean {
|
||||||
val itemCount = messageAdapter.itemCount
|
return isDmChatNearBottom(messageAdapter.items, layoutManager.findLastVisibleItemPosition())
|
||||||
if (itemCount == 0) return true
|
|
||||||
val lastVisible = layoutManager.findLastVisibleItemPosition()
|
|
||||||
return lastVisible >= itemCount - NEAR_BOTTOM_THRESHOLD
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun connectRealtimeIfStarted() {
|
private fun connectRealtimeIfStarted() {
|
||||||
@@ -197,7 +216,6 @@ class DmChatRoomActivity : BaseActivity<ActivityDmChatRoomBinding>(
|
|||||||
companion object {
|
companion object {
|
||||||
const val EXTRA_ROOM_ID: String = "extra_room_id"
|
const val EXTRA_ROOM_ID: String = "extra_room_id"
|
||||||
const val EXTRA_CREATOR_ID: String = "extra_creator_id"
|
const val EXTRA_CREATOR_ID: String = "extra_creator_id"
|
||||||
private const val NEAR_BOTTOM_THRESHOLD = 2
|
|
||||||
|
|
||||||
fun newIntentByRoomId(context: Context, roomId: Long): Intent {
|
fun newIntentByRoomId(context: Context, roomId: Long): Intent {
|
||||||
return Intent(context, DmChatRoomActivity::class.java).apply {
|
return Intent(context, DmChatRoomActivity::class.java).apply {
|
||||||
|
|||||||
+30
-31
@@ -14,18 +14,23 @@ import kr.co.vividnext.sodalive.chat.talk.room.formatMessageTime
|
|||||||
import kr.co.vividnext.sodalive.extensions.loadUrl
|
import kr.co.vividnext.sodalive.extensions.loadUrl
|
||||||
import kr.co.vividnext.sodalive.v2.main.chat.dm.model.DmChatMessageStatus
|
import kr.co.vividnext.sodalive.v2.main.chat.dm.model.DmChatMessageStatus
|
||||||
import kr.co.vividnext.sodalive.v2.main.chat.dm.model.DmChatMessageUiItem
|
import kr.co.vividnext.sodalive.v2.main.chat.dm.model.DmChatMessageUiItem
|
||||||
|
import kr.co.vividnext.sodalive.v2.main.chat.dm.model.DmChatTimelineItem
|
||||||
|
import kr.co.vividnext.sodalive.v2.main.chat.dm.model.DmChatTimelineStableIds
|
||||||
|
import kr.co.vividnext.sodalive.v2.main.chat.dm.model.identity
|
||||||
|
|
||||||
class DmChatMessageAdapter(
|
class DmChatMessageAdapter(
|
||||||
private val onRetryClick: (String) -> Unit
|
private val onRetryClick: (String) -> Unit
|
||||||
) : RecyclerView.Adapter<RecyclerView.ViewHolder>() {
|
) : RecyclerView.Adapter<RecyclerView.ViewHolder>() {
|
||||||
|
|
||||||
private var items: List<DmChatMessageUiItem> = emptyList()
|
var items: List<DmChatTimelineItem> = emptyList()
|
||||||
|
private set
|
||||||
|
private val stableIds = DmChatTimelineStableIds()
|
||||||
|
|
||||||
init {
|
init {
|
||||||
setHasStableIds(true)
|
setHasStableIds(true)
|
||||||
}
|
}
|
||||||
|
|
||||||
fun submitItems(newItems: List<DmChatMessageUiItem>) {
|
fun submitItems(newItems: List<DmChatTimelineItem>) {
|
||||||
val diffResult = DiffUtil.calculateDiff(DmChatMessageDiffCallback(items, newItems))
|
val diffResult = DiffUtil.calculateDiff(DmChatMessageDiffCallback(items, newItems))
|
||||||
items = newItems
|
items = newItems
|
||||||
diffResult.dispatchUpdatesTo(this)
|
diffResult.dispatchUpdatesTo(this)
|
||||||
@@ -33,12 +38,11 @@ class DmChatMessageAdapter(
|
|||||||
|
|
||||||
override fun getItemCount(): Int = items.size
|
override fun getItemCount(): Int = items.size
|
||||||
|
|
||||||
override fun getItemId(position: Int): Long = stableId(items[position])
|
override fun getItemId(position: Int): Long = stableIds.idFor(items[position].identity())
|
||||||
|
|
||||||
override fun getItemViewType(position: Int): Int = if (items[position].mine) {
|
override fun getItemViewType(position: Int): Int = when (val item = items[position]) {
|
||||||
VIEW_TYPE_MY_MESSAGE
|
is DmChatTimelineItem.DateHeader -> VIEW_TYPE_DATE_HEADER
|
||||||
} else {
|
is DmChatTimelineItem.Message -> if (item.item.mine) VIEW_TYPE_MY_MESSAGE else VIEW_TYPE_OPPONENT_MESSAGE
|
||||||
VIEW_TYPE_OPPONENT_MESSAGE
|
|
||||||
}
|
}
|
||||||
|
|
||||||
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
|
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
|
||||||
@@ -51,20 +55,24 @@ class DmChatMessageAdapter(
|
|||||||
VIEW_TYPE_OPPONENT_MESSAGE -> OpponentMessageViewHolder(
|
VIEW_TYPE_OPPONENT_MESSAGE -> OpponentMessageViewHolder(
|
||||||
inflater.inflate(R.layout.item_dm_chat_opponent_message, parent, false)
|
inflater.inflate(R.layout.item_dm_chat_opponent_message, parent, false)
|
||||||
)
|
)
|
||||||
|
VIEW_TYPE_DATE_HEADER -> DateHeaderViewHolder(
|
||||||
|
inflater.inflate(R.layout.item_dm_chat_date_header, parent, false)
|
||||||
|
)
|
||||||
else -> throw IllegalArgumentException("Unknown viewType: $viewType")
|
else -> throw IllegalArgumentException("Unknown viewType: $viewType")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
|
override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
|
||||||
when (holder) {
|
when (holder) {
|
||||||
is MyMessageViewHolder -> holder.bind(items[position])
|
is MyMessageViewHolder -> holder.bind((items[position] as DmChatTimelineItem.Message).item)
|
||||||
is OpponentMessageViewHolder -> holder.bind(items[position])
|
is OpponentMessageViewHolder -> holder.bind((items[position] as DmChatTimelineItem.Message).item)
|
||||||
|
is DateHeaderViewHolder -> holder.bind(items[position] as DmChatTimelineItem.DateHeader)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private class DmChatMessageDiffCallback(
|
private class DmChatMessageDiffCallback(
|
||||||
private val oldItems: List<DmChatMessageUiItem>,
|
private val oldItems: List<DmChatTimelineItem>,
|
||||||
private val newItems: List<DmChatMessageUiItem>
|
private val newItems: List<DmChatTimelineItem>
|
||||||
) : DiffUtil.Callback() {
|
) : DiffUtil.Callback() {
|
||||||
override fun getOldListSize(): Int = oldItems.size
|
override fun getOldListSize(): Int = oldItems.size
|
||||||
override fun getNewListSize(): Int = newItems.size
|
override fun getNewListSize(): Int = newItems.size
|
||||||
@@ -79,6 +87,14 @@ class DmChatMessageAdapter(
|
|||||||
oldItems[oldItemPosition] == newItems[newItemPosition]
|
oldItems[oldItemPosition] == newItems[newItemPosition]
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private class DateHeaderViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
|
||||||
|
private val tvDate = itemView.findViewById<TextView>(R.id.tv_date)
|
||||||
|
|
||||||
|
fun bind(item: DmChatTimelineItem.DateHeader) {
|
||||||
|
tvDate.text = item.text
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
private class MyMessageViewHolder(
|
private class MyMessageViewHolder(
|
||||||
itemView: View,
|
itemView: View,
|
||||||
private val onRetryClick: (String) -> Unit
|
private val onRetryClick: (String) -> Unit
|
||||||
@@ -140,27 +156,10 @@ class DmChatMessageAdapter(
|
|||||||
companion object {
|
companion object {
|
||||||
private const val VIEW_TYPE_MY_MESSAGE = 1
|
private const val VIEW_TYPE_MY_MESSAGE = 1
|
||||||
private const val VIEW_TYPE_OPPONENT_MESSAGE = 2
|
private const val VIEW_TYPE_OPPONENT_MESSAGE = 2
|
||||||
|
private const val VIEW_TYPE_DATE_HEADER = 3
|
||||||
private const val MESSAGE_MAX_WIDTH_RATIO = 0.68f
|
private const val MESSAGE_MAX_WIDTH_RATIO = 0.68f
|
||||||
|
|
||||||
private fun stableId(item: DmChatMessageUiItem): Long =
|
private fun sameIdentity(oldItem: DmChatTimelineItem, newItem: DmChatTimelineItem): Boolean =
|
||||||
item.messageId ?: item.localId?.let(::localStableId) ?: localStableId(item.createdAt.toString())
|
oldItem.identity() == newItem.identity()
|
||||||
|
|
||||||
private fun localStableId(localId: String): Long {
|
|
||||||
var hash = 1125899906842597L
|
|
||||||
localId.forEach { char ->
|
|
||||||
hash = 31L * hash + char.code
|
|
||||||
}
|
|
||||||
return -1L - (hash and Long.MAX_VALUE)
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun sameIdentity(oldItem: DmChatMessageUiItem, newItem: DmChatMessageUiItem): Boolean {
|
|
||||||
if (oldItem.messageId != null && newItem.messageId != null) {
|
|
||||||
return oldItem.messageId == newItem.messageId
|
|
||||||
}
|
|
||||||
if (oldItem.localId != null && newItem.localId != null) {
|
|
||||||
return oldItem.localId == newItem.localId
|
|
||||||
}
|
|
||||||
return stableId(oldItem) == stableId(newItem)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,13 @@
|
|||||||
|
<?xml version="1.0" encoding="utf-8"?>
|
||||||
|
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
|
||||||
|
xmlns:tools="http://schemas.android.com/tools"
|
||||||
|
android:id="@+id/tv_date"
|
||||||
|
style="@style/Typography.Caption3"
|
||||||
|
android:layout_width="match_parent"
|
||||||
|
android:layout_height="wrap_content"
|
||||||
|
android:gravity="center"
|
||||||
|
android:includeFontPadding="false"
|
||||||
|
android:paddingHorizontal="@dimen/spacing_12"
|
||||||
|
android:paddingVertical="@dimen/spacing_12"
|
||||||
|
android:textColor="@color/gray_500"
|
||||||
|
tools:text="2026년 10월 16일 금요일" />
|
||||||
+108
@@ -0,0 +1,108 @@
|
|||||||
|
package kr.co.vividnext.sodalive.v2.main.chat.dm
|
||||||
|
|
||||||
|
import android.app.Application
|
||||||
|
import androidx.recyclerview.widget.RecyclerView
|
||||||
|
import kr.co.vividnext.sodalive.v2.main.chat.dm.model.DmChatMessageStatus
|
||||||
|
import kr.co.vividnext.sodalive.v2.main.chat.dm.model.DmChatMessageUiItem
|
||||||
|
import kr.co.vividnext.sodalive.v2.main.chat.dm.model.DmChatTimelineItem
|
||||||
|
import kr.co.vividnext.sodalive.v2.main.chat.dm.ui.DmChatMessageAdapter
|
||||||
|
import org.junit.Assert.assertEquals
|
||||||
|
import org.junit.Assert.assertNotEquals
|
||||||
|
import org.junit.Assert.assertTrue
|
||||||
|
import org.junit.Test
|
||||||
|
import org.junit.runner.RunWith
|
||||||
|
import org.robolectric.RobolectricTestRunner
|
||||||
|
import org.robolectric.annotation.Config
|
||||||
|
|
||||||
|
@RunWith(RobolectricTestRunner::class)
|
||||||
|
@Config(sdk = [28], application = Application::class)
|
||||||
|
class DmChatMessageAdapterTest {
|
||||||
|
private val adapter = DmChatMessageAdapter { }
|
||||||
|
private val header = DmChatTimelineItem.DateHeader("2026-10-16", "2026년 10월 16일 금요일")
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun `날짜와 송수신 메시지는 서로 다른 view type을 선택한다`() {
|
||||||
|
adapter.submitItems(listOf(header, message(1L, mine = true), message(2L)))
|
||||||
|
|
||||||
|
assertEquals(listOf(3, 1, 2), (0 until adapter.itemCount).map(adapter::getItemViewType))
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun `날짜와 서버와 local 메시지 stable ID는 충돌하지 않는다`() {
|
||||||
|
adapter.submitItems(listOf(header, message(0L), message(-1L), message(Long.MAX_VALUE), local("Aa"), local("BB")))
|
||||||
|
val ids = (0 until adapter.itemCount).map(adapter::getItemId)
|
||||||
|
|
||||||
|
assertTrue(adapter.hasStableIds())
|
||||||
|
assertEquals(6, ids.toSet().size)
|
||||||
|
assertTrue(ids.none { it == RecyclerView.NO_ID })
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun `같은 날짜와 메시지는 재제출과 위치 변경 뒤에도 stable ID를 유지한다`() {
|
||||||
|
adapter.submitItems(listOf(header, message(2L)))
|
||||||
|
val headerId = adapter.getItemId(0)
|
||||||
|
val messageId = adapter.getItemId(1)
|
||||||
|
adapter.submitItems(listOf(header.copy(text = "Friday, October 16, 2026"), message(1L), message(2L)))
|
||||||
|
|
||||||
|
assertEquals(headerId, adapter.getItemId(0))
|
||||||
|
assertEquals(messageId, adapter.getItemId(2))
|
||||||
|
assertNotEquals(messageId, adapter.getItemId(1))
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun `pending과 ACK와 재시도 상태는 같은 local identity와 stable ID를 유지한다`() {
|
||||||
|
val pending = local("local-1")
|
||||||
|
adapter.submitItems(listOf(header, pending))
|
||||||
|
val id = adapter.getItemId(1)
|
||||||
|
val changes = Changes()
|
||||||
|
adapter.registerAdapterDataObserver(changes)
|
||||||
|
val ack = pending.copy(item = pending.item.copy(messageId = 42L, status = DmChatMessageStatus.SENT))
|
||||||
|
adapter.submitItems(listOf(header, ack))
|
||||||
|
|
||||||
|
assertEquals(id, adapter.getItemId(1))
|
||||||
|
assertEquals(0, changes.inserted)
|
||||||
|
assertEquals(0, changes.removed)
|
||||||
|
assertEquals(1, changes.changed)
|
||||||
|
adapter.submitItems(listOf(header, pending.copy(item = pending.item.copy(status = DmChatMessageStatus.FAILED))))
|
||||||
|
assertEquals(id, adapter.getItemId(1))
|
||||||
|
assertEquals(2, changes.changed)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun `서버 ID가 같은 숫자여도 local 메시지와 서버 조회 메시지는 다른 identity다`() {
|
||||||
|
val local = local("42").let { it.copy(item = it.item.copy(messageId = 42L)) }
|
||||||
|
adapter.submitItems(listOf(local, message(42L)))
|
||||||
|
|
||||||
|
assertNotEquals(adapter.getItemId(0), adapter.getItemId(1))
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun `날짜 언어와 메시지 본문 변경은 삭제 삽입 없이 내용 변경으로 전달한다`() {
|
||||||
|
adapter.submitItems(listOf(header, message(1L)))
|
||||||
|
val changes = Changes()
|
||||||
|
adapter.registerAdapterDataObserver(changes)
|
||||||
|
adapter.submitItems(listOf(header.copy(text = "2026年10月16日金曜日"), message(1L, text = "수정")))
|
||||||
|
|
||||||
|
assertEquals(0, changes.inserted)
|
||||||
|
assertEquals(0, changes.removed)
|
||||||
|
assertEquals(2, changes.changed)
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun message(id: Long, mine: Boolean = false, text: String = "메시지") = DmChatTimelineItem.Message(
|
||||||
|
DmChatMessageUiItem(id, null, null, mine, text, "상대", "", 1000L, DmChatMessageStatus.SENT)
|
||||||
|
)
|
||||||
|
|
||||||
|
private fun local(id: String) = message(1L, mine = true).let {
|
||||||
|
it.copy(item = it.item.copy(messageId = null, localId = id, status = DmChatMessageStatus.SENDING))
|
||||||
|
}
|
||||||
|
|
||||||
|
private class Changes : RecyclerView.AdapterDataObserver() {
|
||||||
|
var inserted = 0
|
||||||
|
var removed = 0
|
||||||
|
var changed = 0
|
||||||
|
|
||||||
|
override fun onItemRangeInserted(positionStart: Int, itemCount: Int) { inserted += itemCount }
|
||||||
|
override fun onItemRangeRemoved(positionStart: Int, itemCount: Int) { removed += itemCount }
|
||||||
|
override fun onItemRangeChanged(positionStart: Int, itemCount: Int, payload: Any?) { changed += itemCount }
|
||||||
|
}
|
||||||
|
}
|
||||||
+128
@@ -0,0 +1,128 @@
|
|||||||
|
package kr.co.vividnext.sodalive.v2.main.chat.dm
|
||||||
|
|
||||||
|
import android.app.Application
|
||||||
|
import androidx.lifecycle.Lifecycle
|
||||||
|
import androidx.lifecycle.LifecycleOwner
|
||||||
|
import androidx.lifecycle.LifecycleRegistry
|
||||||
|
import androidx.lifecycle.MutableLiveData
|
||||||
|
import kr.co.vividnext.sodalive.v2.main.chat.dm.model.DmChatMessageStatus
|
||||||
|
import kr.co.vividnext.sodalive.v2.main.chat.dm.model.DmChatMessageUiItem
|
||||||
|
import kr.co.vividnext.sodalive.v2.main.chat.dm.model.DmChatRoomUiState
|
||||||
|
import kr.co.vividnext.sodalive.v2.main.chat.dm.model.DmChatScrollState
|
||||||
|
import kr.co.vividnext.sodalive.v2.main.chat.dm.model.DmChatTimelineIdentity
|
||||||
|
import kr.co.vividnext.sodalive.v2.main.chat.dm.model.toTimelineItems
|
||||||
|
import org.junit.Assert.assertEquals
|
||||||
|
import org.junit.Assert.assertTrue
|
||||||
|
import org.junit.Test
|
||||||
|
import org.junit.runner.RunWith
|
||||||
|
import org.robolectric.RobolectricTestRunner
|
||||||
|
import org.robolectric.annotation.Config
|
||||||
|
import java.io.File
|
||||||
|
import java.util.Locale
|
||||||
|
import java.util.TimeZone
|
||||||
|
|
||||||
|
@RunWith(RobolectricTestRunner::class)
|
||||||
|
@Config(sdk = [28], application = Application::class)
|
||||||
|
class DmChatScrollLifecycleTest {
|
||||||
|
private val anchor = DmChatScrollState.Anchor(DmChatTimelineIdentity.ServerMessage(2L), -17)
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun `백그라운드에서 끝난 prepend는 복귀 후 새 목록의 anchor를 한 번 복원한다`() {
|
||||||
|
val harness = Harness()
|
||||||
|
harness.owner.registry.currentState = Lifecycle.State.STARTED
|
||||||
|
harness.content.value = content(2L)
|
||||||
|
assertTrue(harness.scroll.beginPrepend(content(2L)) { anchor })
|
||||||
|
harness.content.value = content(2L).copy(isLoadingOlder = true)
|
||||||
|
harness.owner.registry.currentState = Lifecycle.State.CREATED
|
||||||
|
|
||||||
|
harness.count.value = 1
|
||||||
|
harness.content.value = content(1L, 2L)
|
||||||
|
assertTrue(harness.restores.isEmpty())
|
||||||
|
harness.owner.registry.currentState = Lifecycle.State.STARTED
|
||||||
|
|
||||||
|
assertEquals(listOf(DmChatScrollState.Position(2, -17)), harness.restores)
|
||||||
|
harness.owner.registry.currentState = Lifecycle.State.CREATED
|
||||||
|
harness.owner.registry.currentState = Lifecycle.State.STARTED
|
||||||
|
assertEquals(1, harness.restores.size)
|
||||||
|
harness.owner.registry.currentState = Lifecycle.State.DESTROYED
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun `현재 요청이 없는 재생성에서는 저장된 count를 복원에 사용하지 않는다`() {
|
||||||
|
val harness = Harness()
|
||||||
|
harness.count.value = 9
|
||||||
|
harness.content.value = content(1L, 2L)
|
||||||
|
harness.owner.registry.currentState = Lifecycle.State.STARTED
|
||||||
|
|
||||||
|
assertTrue(harness.restores.isEmpty())
|
||||||
|
assertTrue(harness.scroll.beginPrepend(content(1L, 2L)) { anchor })
|
||||||
|
harness.content.value = content(1L, 2L)
|
||||||
|
assertTrue(harness.restores.isEmpty())
|
||||||
|
harness.owner.registry.currentState = Lifecycle.State.DESTROYED
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun `비활성 중 실패하거나 빈 페이지로 끝나도 다음 요청을 막지 않는다`() {
|
||||||
|
listOf<Int?>(null, 0).forEach { result ->
|
||||||
|
val harness = Harness()
|
||||||
|
harness.owner.registry.currentState = Lifecycle.State.STARTED
|
||||||
|
harness.content.value = content(2L)
|
||||||
|
assertTrue(harness.scroll.beginPrepend(content(2L)) { anchor })
|
||||||
|
harness.content.value = content(2L).copy(isLoadingOlder = true)
|
||||||
|
harness.owner.registry.currentState = Lifecycle.State.CREATED
|
||||||
|
result?.let { harness.count.value = it }
|
||||||
|
harness.content.value = content(2L)
|
||||||
|
harness.owner.registry.currentState = Lifecycle.State.STARTED
|
||||||
|
|
||||||
|
assertTrue(harness.restores.isEmpty())
|
||||||
|
assertTrue(harness.scroll.beginPrepend(content(2L)) { anchor })
|
||||||
|
harness.owner.registry.currentState = Lifecycle.State.DESTROYED
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private class Owner : LifecycleOwner {
|
||||||
|
val registry = LifecycleRegistry(this)
|
||||||
|
override val lifecycle: Lifecycle get() = registry
|
||||||
|
}
|
||||||
|
|
||||||
|
private class Harness {
|
||||||
|
val owner = Owner()
|
||||||
|
val scroll = DmChatScrollState()
|
||||||
|
val count = MutableLiveData(0)
|
||||||
|
val content = MutableLiveData<DmChatRoomUiState.Content>()
|
||||||
|
val restores = mutableListOf<DmChatScrollState.Position>()
|
||||||
|
|
||||||
|
init {
|
||||||
|
val path = "app/src/main/java/kr/co/vividnext/sodalive/v2/main/chat/dm/DmChatRoomActivity.kt"
|
||||||
|
val source = listOf(File(path), File("../$path")).first { it.exists() }.readText()
|
||||||
|
val bindSource = source.substringAfter("private fun bindViewModel()")
|
||||||
|
.substringBefore("private fun bindContent")
|
||||||
|
val countOrder = bindSource.indexOf("viewModel.prependedMessageCountLiveData.observe(this)")
|
||||||
|
val contentOrder = bindSource.indexOf("viewModel.chatRoomStateLiveData.observe(this)")
|
||||||
|
check(countOrder >= 0 && contentOrder >= 0)
|
||||||
|
val bindCount: () -> Unit = { count.observe(owner, scroll::onPrependCount) }
|
||||||
|
val bindContent: () -> Unit = {
|
||||||
|
content.observe(owner) { state ->
|
||||||
|
val submitted = state.messages.toTimelineItems(Locale.KOREAN, TimeZone.getTimeZone("UTC"))
|
||||||
|
val update = scroll.onContentSubmitted(state.isLoadingOlder, false)
|
||||||
|
if (update is DmChatScrollState.Update.Restore) {
|
||||||
|
scroll.resolveRestore(update, submitted)?.let(restores::add)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// Activity의 실제 등록 순서로 LiveData를 연결해 재활성화 전달 순서 회귀를 검증한다.
|
||||||
|
listOf(countOrder to bindCount, contentOrder to bindContent).sortedBy { it.first }.forEach { it.second() }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun content(vararg ids: Long) = DmChatRoomUiState.Content(
|
||||||
|
roomId = 10L,
|
||||||
|
opponentNickname = "상대",
|
||||||
|
opponentProfileImageUrl = "",
|
||||||
|
messages = ids.map { id ->
|
||||||
|
DmChatMessageUiItem(id, null, null, false, "메시지", "상대", "", id * 1000, DmChatMessageStatus.SENT)
|
||||||
|
},
|
||||||
|
hasMore = true,
|
||||||
|
nextCursor = 1L
|
||||||
|
)
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user