diff --git a/app/src/main/java/kr/co/vividnext/sodalive/mypage/MyPageFragment.kt b/app/src/main/java/kr/co/vividnext/sodalive/mypage/MyPageFragment.kt index 9c4a2566..883871fe 100644 --- a/app/src/main/java/kr/co/vividnext/sodalive/mypage/MyPageFragment.kt +++ b/app/src/main/java/kr/co/vividnext/sodalive/mypage/MyPageFragment.kt @@ -8,6 +8,7 @@ import android.view.View import android.webkit.URLUtil import android.widget.Toast import androidx.core.net.toUri +import androidx.lifecycle.Lifecycle import androidx.media3.common.util.UnstableApi import androidx.recyclerview.widget.GridLayoutManager import androidx.recyclerview.widget.LinearLayoutManager @@ -50,6 +51,7 @@ import kr.co.vividnext.sodalive.v2.creator.channel.CreatorChannelActivity import kr.co.vividnext.sodalive.v2.gift.GiftInboxActivity import kr.co.vividnext.sodalive.v2.gift.GiftInboxEntryPolicy import kr.co.vividnext.sodalive.v2.main.MainV2Activity +import kr.co.vividnext.sodalive.v2.mypage.notice.MyNoticeTicker import org.koin.android.ext.android.inject @UnstableApi @@ -64,6 +66,7 @@ class MyPageFragment : BaseFragment(FragmentMyBinding::inflat private lateinit var loadingDialog: LoadingDialog private val functionButtonAdapter = FunctionButtonAdapter() + private var noticeTicker: MyNoticeTicker? = null override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) @@ -76,28 +79,33 @@ class MyPageFragment : BaseFragment(FragmentMyBinding::inflat } private fun setupLatestNotice() { - // Observe the latest notice LiveData - viewModel.latestNoticeLiveData.observe(viewLifecycleOwner) { noticeItem -> - noticeItem?.let { - // Update the UI with the latest notice title - binding.tvLatestNoticeTitle.text = it.title - - // Set click listener for the latest notice section - binding.llLatestNotice.setOnClickListener { _ -> - startActivity( - Intent( - requireActivity(), - NoticeDetailActivity::class.java - ).apply { - putExtra(Constants.EXTRA_NOTICE, it) - } - ) + noticeTicker = MyNoticeTicker(binding.llLatestNotice, binding.tsLatestNoticeTitle) { notice -> + startActivity( + Intent(requireActivity(), NoticeDetailActivity::class.java).apply { + putExtra(Constants.EXTRA_NOTICE, notice) } - } + ) } + viewModel.latestNoticesLiveData.observe(viewLifecycleOwner) { notices -> + noticeTicker?.submitList(notices) + } + viewModel.getLatestNotices() + } - // Fetch the latest notice using ViewModel - viewModel.getLatestNotice() + override fun onHiddenChanged(hidden: Boolean) { + super.onHiddenChanged(hidden) + noticeTicker?.setActive(!hidden && lifecycle.currentState.isAtLeast(Lifecycle.State.STARTED)) + } + + override fun onStop() { + noticeTicker?.setActive(false) + super.onStop() + } + + override fun onDestroyView() { + noticeTicker?.destroy() + noticeTicker = null + super.onDestroyView() } private fun setupRecentContentSection() { @@ -168,6 +176,7 @@ class MyPageFragment : BaseFragment(FragmentMyBinding::inflat override fun onStart() { super.onStart() + noticeTicker?.setActive(!isHidden) if (SharedPreferenceManager.token.isNotBlank()) { viewModel.getUserInfo() diff --git a/app/src/main/java/kr/co/vividnext/sodalive/v2/mypage/notice/MyNoticeTicker.kt b/app/src/main/java/kr/co/vividnext/sodalive/v2/mypage/notice/MyNoticeTicker.kt new file mode 100644 index 00000000..22975e3a --- /dev/null +++ b/app/src/main/java/kr/co/vividnext/sodalive/v2/mypage/notice/MyNoticeTicker.kt @@ -0,0 +1,94 @@ +package kr.co.vividnext.sodalive.v2.mypage.notice + +import android.os.Handler +import android.os.Looper +import android.view.View +import android.view.animation.Animation +import android.view.animation.TranslateAnimation +import android.widget.TextSwitcher +import kr.co.vividnext.sodalive.settings.notice.NoticeItem + +class MyNoticeTicker( + noticeRow: View, + titleSwitcher: TextSwitcher, + onNoticeClick: (NoticeItem) -> Unit +) { + private var row: View? = noticeRow + private var titles: TextSwitcher? = titleSwitcher + private var onNoticeClick: ((NoticeItem) -> Unit)? = onNoticeClick + private val handler = Handler(Looper.getMainLooper()) + private var notices = emptyList() + private var index = 0 + private var active = false + private val advance = object : Runnable { + override fun run() { + if (!active || notices.size < 2 || titles == null) return + index = (index + 1) % notices.size + titles?.setText(notices[index].title) + schedule() + } + } + + init { + titleSwitcher.inAnimation = verticalAnimation(1f, 0f) + titleSwitcher.outAnimation = verticalAnimation(0f, -1f) + noticeRow.setOnClickListener { + notices.getOrNull(index)?.let { notice -> this.onNoticeClick?.invoke(notice.toNoticeItem()) } + } + submitList(emptyList()) + } + + fun submitList(notices: List) { + if (titles == null) return + handler.removeCallbacks(advance) + clearAnimations() + this.notices = notices + index = 0 + titles?.setCurrentText(notices.firstOrNull()?.title.orEmpty()) + row?.visibility = if (notices.isEmpty()) View.GONE else View.VISIBLE + schedule() + } + + fun setActive(active: Boolean) { + if (titles == null || this.active == active) return + this.active = active + handler.removeCallbacks(advance) + if (active) schedule() else clearAnimations() + } + + fun destroy() { + active = false + handler.removeCallbacks(advance) + clearAnimations() + row?.setOnClickListener(null) + titles?.inAnimation = null + titles?.outAnimation = null + row = null + titles = null + onNoticeClick = null + notices = emptyList() + } + + private fun schedule() { + handler.removeCallbacks(advance) + if (active && notices.size > 1) handler.postDelayed(advance, 5_000L) + } + + private fun clearAnimations() { + titles?.let { switcher -> + switcher.clearAnimation() + repeat(switcher.childCount) { switcher.getChildAt(it).clearAnimation() } + } + } + + private fun verticalAnimation(from: Float, to: Float) = TranslateAnimation( + Animation.RELATIVE_TO_SELF, + 0f, + Animation.RELATIVE_TO_SELF, + 0f, + Animation.RELATIVE_TO_SELF, + from, + Animation.RELATIVE_TO_SELF, + to + ).apply { duration = 250L } +} diff --git a/app/src/main/res/layout/fragment_my.xml b/app/src/main/res/layout/fragment_my.xml index 590b4d15..503892f8 100644 --- a/app/src/main/res/layout/fragment_my.xml +++ b/app/src/main/res/layout/fragment_my.xml @@ -47,31 +47,45 @@ android:id="@+id/ll_latest_notice" android:layout_width="0dp" android:layout_height="wrap_content" - android:background="#000000" + android:background="@color/black" android:gravity="center_vertical" android:orientation="horizontal" - android:paddingHorizontal="24dp" - android:paddingVertical="6dp" + android:paddingHorizontal="@dimen/spacing_24" + android:paddingVertical="@dimen/spacing_6" + android:visibility="gone" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toBottomOf="@id/ll_header"> - + android:layout_weight="1"> + + + + + diff --git a/app/src/test/java/kr/co/vividnext/sodalive/v2/mypage/notice/MyNoticeTickerTest.kt b/app/src/test/java/kr/co/vividnext/sodalive/v2/mypage/notice/MyNoticeTickerTest.kt new file mode 100644 index 00000000..2b11ab88 --- /dev/null +++ b/app/src/test/java/kr/co/vividnext/sodalive/v2/mypage/notice/MyNoticeTickerTest.kt @@ -0,0 +1,424 @@ +package kr.co.vividnext.sodalive.v2.mypage.notice + +import android.app.Application +import android.content.Context +import android.os.Handler +import android.os.Looper +import android.os.SystemClock +import android.view.MotionEvent +import android.view.View +import android.view.ViewGroup +import android.view.animation.Transformation +import android.widget.TextSwitcher +import android.widget.TextView +import android.widget.ViewAnimator +import androidx.core.content.IntentCompat +import androidx.datastore.preferences.core.edit +import androidx.datastore.preferences.core.stringPreferencesKey +import androidx.fragment.app.FragmentActivity +import androidx.lifecycle.Lifecycle +import androidx.lifecycle.MutableLiveData +import androidx.test.core.app.ApplicationProvider +import io.reactivex.rxjava3.android.plugins.RxAndroidPlugins +import io.reactivex.rxjava3.plugins.RxJavaPlugins +import io.reactivex.rxjava3.schedulers.Schedulers +import io.reactivex.rxjava3.subjects.SingleSubject +import kr.co.vividnext.sodalive.R +import kr.co.vividnext.sodalive.common.ApiResponse +import kr.co.vividnext.sodalive.common.AppPreferencesDataStoreProvider +import kr.co.vividnext.sodalive.common.Constants +import kr.co.vividnext.sodalive.common.SharedPreferenceManager +import kr.co.vividnext.sodalive.common.SodaLiveApplicationHolder +import kr.co.vividnext.sodalive.mypage.MyPageFragment +import kr.co.vividnext.sodalive.mypage.MyPageViewModel +import kr.co.vividnext.sodalive.mypage.recent.RecentContentViewModel +import kr.co.vividnext.sodalive.settings.notice.NoticeApi +import kr.co.vividnext.sodalive.settings.notice.NoticeDetailActivity +import kr.co.vividnext.sodalive.settings.notice.NoticeItem +import kr.co.vividnext.sodalive.settings.notice.NoticeRepository +import kotlinx.coroutines.runBlocking +import org.junit.After +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNotNull +import org.junit.Assert.assertNull +import org.junit.Assert.assertSame +import org.junit.Assert.assertTrue +import org.junit.Before +import org.junit.Test +import org.junit.runner.RunWith +import org.koin.core.context.startKoin +import org.koin.core.context.stopKoin +import org.koin.dsl.module +import org.mockito.kotlin.mock +import org.mockito.kotlin.whenever +import org.robolectric.Robolectric +import org.robolectric.RobolectricTestRunner +import org.robolectric.Shadows.shadowOf +import org.robolectric.annotation.Config +import org.robolectric.annotation.LooperMode +import org.robolectric.annotation.Implements +import org.robolectric.shadows.ShadowViewGroup +import org.robolectric.android.controller.ActivityController +import java.time.Duration + +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [28], application = Application::class, shadows = [MyNoticeTickerTest.PlatformViewAnimatorShadow::class]) +@LooperMode(LooperMode.Mode.PAUSED) +class MyNoticeTickerTest { + private val context: Context = ApplicationProvider.getApplicationContext() + private lateinit var row: View + private lateinit var titles: TextSwitcher + private lateinit var ticker: MyNoticeTicker + private val clicks = mutableListOf() + private val notices = listOf( + LatestNoticeResponse(9L, "첫 제목", "

첫 본문 전체 &

", "2026-10-28"), + LatestNoticeResponse(2L, "둘째 제목", "
둘째 본문
", "2026-10-27"), + LatestNoticeResponse(7L, "셋째 제목", "

셋째 본문

", "2026-10-26") + ) + + @Before + fun setUp() { + row = View(context) + titles = TextSwitcher(context).apply { setFactory { TextView(context) } } + ticker = MyNoticeTicker(row, titles) { clicks += it } + } + + @After + fun tearDown() { + ticker.destroy() + } + + @Test + fun `빈 목록은 표시 내용과 클릭 대상을 비우고 예약하지 않는다`() { + ticker.setActive(true) + ticker.submitList(emptyList()) + advance(20_000) + assertEquals("", title()) + row.performClick() + assertTrue(clicks.isEmpty()) + } + + @Test + fun `한 개는 고정 표시하고 상세 payload 원문을 전달한다`() { + ticker.setActive(true) + ticker.submitList(notices.take(1)) + assertCurrent(0) + advance(20_000) + assertCurrent(0) + assertNoAnimations() + } + + @Test + fun `두 개는 4999ms에는 유지하고 5000ms마다 순환한다`() { + ticker.submitList(notices.take(2)) + ticker.setActive(true) + assertCurrent(0) + advance(4_999) + assertEquals("첫 제목", title()) + advance(1) + assertCurrent(1) + advance(5_000) + assertCurrent(0) + } + + @Test + fun `세 개는 정렬 없이 서버 순서대로 마지막에서 처음으로 순환한다`() { + ticker.submitList(notices) + ticker.setActive(true) + assertCurrent(0) + listOf(1, 2, 0, 1).forEach { + advance(5_000) + assertCurrent(it) + } + } + + @Test + fun `반복 활성화는 예약을 중복하거나 기존 5초를 연장하지 않는다`() { + ticker.submitList(notices) + ticker.setActive(true) + advance(2_000) + repeat(3) { ticker.setActive(true) } + advance(3_000) + assertCurrent(1) + advance(5_000) + assertCurrent(2) + } + + @Test + fun `비활성화는 현재 항목을 유지하고 재개 시 새로운 5초를 센다`() { + ticker.submitList(notices) + ticker.setActive(true) + advance(5_000) + ticker.setActive(false) + assertNoAnimations() + advance(60_000) + assertCurrent(1) + ticker.setActive(true) + advance(4_999) + assertEquals("둘째 제목", title()) + advance(1) + assertCurrent(2) + } + + @Test + fun `숨김 중 도착한 목록은 첫 항목을 표시하되 복귀 전에는 예약하지 않는다`() { + ticker.setActive(true) + ticker.setActive(false) + ticker.submitList(notices) + advance(30_000) + assertCurrent(0) + ticker.setActive(true) + advance(4_999) + assertEquals("첫 제목", title()) + advance(1) + assertCurrent(1) + } + + @Test + fun `목록 교체는 애니메이션 없이 첫 항목으로 바꾸고 타이머를 다시 센다`() { + ticker.submitList(notices) + ticker.setActive(true) + advance(5_000) + ticker.submitList(listOf(notices[2], notices[0])) + assertCurrent(2) + assertNoAnimations() + advance(4_999) + assertEquals("셋째 제목", title()) + advance(1) + assertCurrent(0) + } + + @Test + fun `여러 개에서 한 개와 빈 목록으로 교체하면 이전 예약과 클릭 대상이 남지 않는다`() { + ticker.submitList(notices) + ticker.setActive(true) + advance(5_000) + ticker.submitList(listOf(notices[2])) + advance(10_000) + assertCurrent(2) + ticker.submitList(emptyList()) + advance(10_000) + assertEquals("", title()) + val clickCount = clicks.size + row.performClick() + assertEquals(clickCount, clicks.size) + assertNoAnimations() + ticker.submitList(notices.take(2)) + advance(5_000) + assertCurrent(1) + } + + @Test + fun `첫 5초 전환부터 현재 자식에 진입 애니메이션을 시작한다`() { + ticker.submitList(notices.take(2)) + ticker.setActive(true) + assertEquals("첫 제목", title()) + assertNoAnimations() + advance(4_999) + assertEquals("첫 제목", title()) + assertNoAnimations() + Handler(Looper.getMainLooper()).postDelayed({ + assertEquals("둘째 제목", title()) + val animation = titles.currentView.animation + assertNotNull("첫 전환의 현재 자식에 진입 애니메이션이 있어야 한다", animation) + assertSame(titles.inAnimation, animation) + }, 1L) + advance(1) + } + + @Test + fun `초기 목록은 무애니메이션이고 전환은 250ms 아래에서 위로 움직인다`() { + ticker.submitList(notices) + ticker.setActive(true) + assertEquals("첫 제목", title()) + assertNoAnimations() + advance(5_000) + val incoming = titles.inAnimation + val outgoing = titles.outAnimation + assertNotNull(incoming) + assertNotNull(outgoing) + assertEquals(250L, incoming.duration) + assertEquals(250L, outgoing.duration) + incoming.initialize(100, 100, 100, 100) + outgoing.initialize(100, 100, 100, 100) + incoming.startTime = 0 + outgoing.startTime = 0 + val inTransform = Transformation() + val outTransform = Transformation() + incoming.getTransformation(125, inTransform) + outgoing.getTransformation(125, outTransform) + val inValues = FloatArray(9) + val outValues = FloatArray(9) + inTransform.matrix.getValues(inValues) + outTransform.matrix.getValues(outValues) + assertTrue(inValues[android.graphics.Matrix.MTRANS_Y] > 0f) + assertTrue(outValues[android.graphics.Matrix.MTRANS_Y] < 0f) + } + + @Test + fun `파괴는 예약과 애니메이션과 클릭을 해제하고 늦은 응답을 무시한다`() { + ticker.submitList(notices) + ticker.setActive(true) + advance(5_000) + assertCurrent(1) + ticker.destroy() + assertNoAnimations() + assertNull(titles.inAnimation) + assertNull(titles.outAnimation) + assertFalse(row.hasOnClickListeners()) + val clickCount = clicks.size + ticker.setActive(true) + ticker.submitList(listOf(notices[2])) + advance(30_000) + assertEquals("둘째 제목", title()) + row.performClick() + assertEquals(clickCount, clicks.size) + ticker.destroy() + } + + @Test + fun `Fragment 제목과 화살표 클릭은 매번 현재 공지의 상세 Intent를 전달한다`() = withMyPage { controller, fragment, response -> + response.onSuccess(ApiResponse(true, notices)) + advance(0) + val noticeRow = fragment.binding.llLatestNotice + val switcher = fragment.binding.tsLatestNoticeTitle + listOf(0, 1, 2, 0).forEachIndexed { step, index -> + if (step > 0) advance(5_000) + assertEquals(notices[index].title, (switcher.currentView as TextView).text.toString()) + listOf(switcher, noticeRow.getChildAt(noticeRow.childCount - 1)).forEach { target -> + tap(noticeRow, target) + val intent = shadowOf(controller.get()).nextStartedActivity + assertNotNull(intent) + assertEquals(NoticeDetailActivity::class.java.name, intent.component?.className) + val payload = IntentCompat.getParcelableExtra(intent, Constants.EXTRA_NOTICE, NoticeItem::class.java)!! + assertEquals(notices[index].title, payload.title) + assertEquals(notices[index].content, payload.content) + assertEquals(notices[index].date, payload.date) + assertNull(shadowOf(controller.get()).nextStartedActivity) + } + } + } + + @Test + fun `Fragment는 STARTED 상태의 숨김과 지연 응답 배경 복귀 및 View 파괴를 처리한다`() = withMyPage { controller, fragment, response -> + val manager = controller.get().supportFragmentManager + manager.beginTransaction().hide(fragment).commitNow() + assertTrue(fragment.lifecycle.currentState.isAtLeast(Lifecycle.State.STARTED)) + response.onSuccess(ApiResponse(true, notices)) + advance(20_000) + val switcher = fragment.binding.tsLatestNoticeTitle + assertEquals("첫 제목", (switcher.currentView as TextView).text.toString()) + manager.beginTransaction().show(fragment).commitNow() + advance(4_000) + assertEquals("첫 제목", (switcher.currentView as TextView).text.toString()) + advance(1_000) + assertEquals("둘째 제목", (switcher.currentView as TextView).text.toString()) + controller.pause().stop() + advance(20_000) + assertEquals("둘째 제목", (switcher.currentView as TextView).text.toString()) + controller.start().resume() + advance(4_000) + assertEquals("둘째 제목", (switcher.currentView as TextView).text.toString()) + advance(1_000) + assertEquals("셋째 제목", (switcher.currentView as TextView).text.toString()) + val noticeRow = fragment.binding.llLatestNotice + manager.beginTransaction().remove(fragment).commitNow() + advance(20_000) + assertEquals("셋째 제목", (switcher.currentView as TextView).text.toString()) + assertFalse(noticeRow.hasOnClickListeners()) + assertNull(switcher.inAnimation) + assertNull(switcher.outAnimation) + } + + @Test + fun `이전 테스트의 저장된 토큰과 무관하게 공지 fixture는 비로그인으로 시작한다`() { + runBlocking { + AppPreferencesDataStoreProvider.get(context).edit { + it[stringPreferencesKey(Constants.PREF_TOKEN)] = "previous-test-token" + } + } + withMyPage { _, _, _ -> + assertEquals("", SharedPreferenceManager.token) + } + } + + private fun assertCurrent(index: Int) { + val expected = notices[index] + assertEquals(expected.title, title()) + row.performClick() + val payload = clicks.last() + assertEquals(expected.title, payload.title) + assertEquals(expected.content, payload.content) + assertEquals(expected.date, payload.date) + } + + private fun assertNoAnimations() { + assertNull(titles.animation) + repeat(titles.childCount) { assertNull(titles.getChildAt(it).animation) } + } + + private fun title() = (titles.currentView as TextView).text.toString() + + private fun advance(milliseconds: Long) { + shadowOf(Looper.getMainLooper()).idleFor(Duration.ofMillis(milliseconds)) + } + + private fun tap(row: ViewGroup, target: View) { + row.measure(View.MeasureSpec.makeMeasureSpec(1080, View.MeasureSpec.EXACTLY), View.MeasureSpec.UNSPECIFIED) + row.layout(0, 0, row.measuredWidth, row.measuredHeight) + val time = SystemClock.uptimeMillis() + listOf(MotionEvent.ACTION_DOWN, MotionEvent.ACTION_UP).forEach { action -> + val event = MotionEvent.obtain(time, time, action, target.x + target.width / 2f, target.y + target.height / 2f, 0) + row.dispatchTouchEvent(event) + event.recycle() + } + advance(0) + } + + private fun withMyPage( + test: ( + ActivityController, + MyPageFragment, + SingleSubject>> + ) -> Unit + ) { + RxJavaPlugins.setIoSchedulerHandler { Schedulers.trampoline() } + RxAndroidPlugins.setInitMainThreadSchedulerHandler { Schedulers.trampoline() } + RxAndroidPlugins.setMainThreadSchedulerHandler { Schedulers.trampoline() } + SharedPreferenceManager.resetForTest() + runBlocking { + AppPreferencesDataStoreProvider.get(context).edit { + it[stringPreferencesKey(Constants.PREF_TOKEN)] = "" + } + } + SharedPreferenceManager.init(context) + SodaLiveApplicationHolder.init(context.applicationContext as Application) + val api: NoticeApi = mock() + val response = SingleSubject.create>>() + whenever(api.getLatestNotices()).thenReturn(response) + val viewModel = MyPageViewModel(mock(), NoticeRepository(api)) + val recent: RecentContentViewModel = mock() + whenever(recent.getRecentContents(10)).thenReturn(MutableLiveData(emptyList())) + whenever(recent.recentContentsCount).thenReturn(MutableLiveData(0)) + startKoin { modules(module { single { viewModel }; single { recent } }) } + val controller = Robolectric.buildActivity(FragmentActivity::class.java) + controller.get().setTheme(R.style.Theme_SodaLive) + try { + controller.setup() + val fragment = MyPageFragment() + controller.get().supportFragmentManager.beginTransaction() + .add(android.R.id.content, fragment).commitNow() + test(controller, fragment, response) + } finally { + controller.pause().stop().destroy() + stopKoin() + RxJavaPlugins.reset() + RxAndroidPlugins.reset() + SharedPreferenceManager.resetForTest() + } + } + + @Implements(ViewAnimator::class) + class PlatformViewAnimatorShadow : ShadowViewGroup() +}