Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import android.media.AudioAttributes
import android.media.MediaPlayer
import android.net.Uri
import android.provider.Settings
import androidx.activity.compose.BackHandler
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.foundation.background
Expand Down Expand Up @@ -52,11 +53,13 @@ import androidx.compose.material3.rememberModalBottomSheetState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.derivedStateOf
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberUpdatedState
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.runtime.snapshotFlow
import androidx.compose.runtime.snapshots.SnapshotStateMap
Expand All @@ -67,6 +70,7 @@ import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalFocusManager
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.style.TextAlign
Expand Down Expand Up @@ -150,6 +154,7 @@ fun TimeLetterWriteScreen(
onFreePlanLimitDismiss: () -> Unit = {},
) {
val context = LocalContext.current
val focusManager = LocalFocusManager.current
val snackbarHostState = remember { SnackbarHostState() }
val sheetState = rememberModalBottomSheetState()
var showMediaSheet by remember { mutableStateOf(false) }
Expand Down Expand Up @@ -276,6 +281,30 @@ fun TimeLetterWriteScreen(
return
}

// 작성 도중 이탈 가드 (#576): 진입 시점 스냅샷 대비 변경이 있으면 뒤로가기 시 이탈 확인 팝업을 띄운다.
// 애프터노트 에디터(#503)와 같은 방식이다. '내용 존재'가 아니라 '변경' 기준이라 수정 모드에서 무변경
// 이탈에는 경고하지 않는다. 스냅샷은 수신인 선택 왕복·프로세스 복원에도 유지되도록 saveable 로 둔다.
// 팝업 단계는 [ExitConfirmStep] 참고.
var exitConfirmStep by rememberSaveable { mutableStateOf<ExitConfirmStep?>(null) }
var baselineContentSignature by rememberSaveable { mutableStateOf<String?>(null) }
val hasUnsavedChanges by remember(uiState) {
derivedStateOf {
baselineContentSignature != null &&
writeContentSignature(titleState.text.toString(), collectTextContents(), uiState) !=
baselineContentSignature
}
}
val onBackAttempt: () -> Unit = {
focusManager.clearFocus()
when {
!hasUnsavedChanges -> onBackClick()
uiState.isEditingScheduledLetter -> exitConfirmStep = ExitConfirmStep.DiscardEdit
else -> exitConfirmStep = ExitConfirmStep.SaveDraft
}
}
// 변경이 없을 때는 시스템 기본 뒤로가기를 유지한다 (predictive back 애니메이션 보존).
BackHandler(enabled = hasUnsavedChanges) { onBackAttempt() }

// Apply the loaded title once per editing destination. Keying this to draftTitle would
// overwrite the user's input whenever the draft is synchronized back to the ViewModel.
LaunchedEffect(uiState.editingTimeLetterId) {
Expand All @@ -284,6 +313,57 @@ fun TimeLetterWriteScreen(
replace(0, length, uiState.draftTitle.orEmpty())
}
}
// 수정 모드는 불러온 제목을 채운 뒤에 스냅샷을 잡아야 무변경 이탈이 변경으로 읽히지 않는다.
if (baselineContentSignature == null) {
baselineContentSignature =
writeContentSignature(titleState.text.toString(), collectTextContents(), uiState)
}
}

when (exitConfirmStep) {
ExitConfirmStep.SaveDraft -> {
Popup(
type = PopupType.Variant2,
message = stringResource(R.string.timeletter_write_exit_save_draft_message),
// 하단 «임시저장» 버튼과 같은 경로 — 성공하면 savedAsDraft 로 나가고, 수신인 누락·저장
// 실패면 오류 스낵바를 띄운 채 작성 화면에 남는다.
onConfirm = {
exitConfirmStep = null
onDraftClick(titleState.text.toString(), collectTextContents())
},
onDismiss = { exitConfirmStep = ExitConfirmStep.Discard },
)
}

ExitConfirmStep.Discard -> {
Popup(
type = PopupType.Variant2,
message = stringResource(R.string.timeletter_write_exit_discard_message),
onConfirm = {
exitConfirmStep = null
onBackClick()
},
onDismiss = { exitConfirmStep = null },
dismissText = stringResource(R.string.timeletter_write_exit_cancel),
)
}

ExitConfirmStep.DiscardEdit -> {
Popup(
type = PopupType.Variant2,
message = stringResource(R.string.timeletter_write_exit_discard_edit_message),
onConfirm = {
exitConfirmStep = null
onBackClick()
},
onDismiss = { exitConfirmStep = null },
dismissText = stringResource(R.string.timeletter_write_exit_cancel),
)
}

null -> {
Unit
}
}

var showDatePicker by remember { mutableStateOf(false) }
Expand Down Expand Up @@ -472,7 +552,7 @@ fun TimeLetterWriteScreen(
topBar = {
DetailTopBar(
title = "타임레터",
onBackClick = onBackClick,
onBackClick = onBackAttempt,
actions = {
TimeLetterTextButton(
text = if (uiState.editingTimeLetterId == null) "등록" else "수정",
Expand Down Expand Up @@ -583,6 +663,43 @@ fun TimeLetterWriteScreen(
}
}

/**
* 변경이 있는 채로 뒤로가기를 눌렀을 때의 이탈 확인 단계 (#576).
*
* - 새 편지·임시저장 편지: [SaveDraft] 「예」는 임시저장, 「아니요」는 [Discard] 로 넘어가 한 번 더 묻는다.
* - 예약 편지 수정: [DiscardEdit] 하나만 묻는다. 임시저장을 권하면 예약이 DRAFT 로 풀린다.
*/
private enum class ExitConfirmStep {
SaveDraft,
Discard,
DiscardEdit,
}

/**
* 이탈 가드가 비교하는 작성 내용 지문. 화면 정렬처럼 보내지 않는 값은 넣지 않는다.
* 텍스트 블록은 블록 순서대로, 미디어 블록은 가리키는 대상으로 비교한다.
*/
internal fun writeContentSignature(
title: String,
textContents: Map<Long, String>,
uiState: TimeLetterWriteUiState,
): String =
listOf(
title,
uiState.editorBlocks.joinToString("\u0001") { block ->
when (block) {
is EditorBlock.Text -> "T:${textContents[block.id].orEmpty()}"
is EditorBlock.Image -> "I:${block.uri}"
is EditorBlock.Audio -> "A:${block.uri}"
is EditorBlock.File -> "F:${block.uri}"
is EditorBlock.Link -> "L:${block.url}"
}
},
uiState.recipientIds.joinToString(","),
uiState.sendAt.orEmpty(),
uiState.sendTime.orEmpty(),
).joinToString("\u0002")

internal fun collectTextBlockContents(
editorBlocks: List<EditorBlock>,
visibleTextContents: Map<Long, String>,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@ import com.afternote.feature.timeletter.domain.model.RecordedAudio

data class TimeLetterWriteUiState(
val editingTimeLetterId: Long? = null,
/** 예약된 편지를 수정 중인지. 이탈 시 임시저장을 권하면 예약이 DRAFT 로 풀리므로 폐기 확인만 묻는다 (#576). */
val isEditingScheduledLetter: Boolean = false,
val isLoadingEditingLetter: Boolean = false,
val draftTitle: String? = null,
val draftTextContents: Map<Long, String> = emptyMap(),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -530,6 +530,7 @@ class TimeLetterWriteViewModel
_uiState.update {
it.copy(
editingTimeLetterId = letter.id,
isEditingScheduledLetter = letter.status == TimeLetterStatus.SCHEDULED,
isLoadingEditingLetter = false,
draftTitle = letter.title.orEmpty(),
draftTextContents =
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,10 @@
<string name="timeletter_write_load_failed">타임레터를 불러올 수 없습니다.</string>
<string name="timeletter_write_recipient_required">수신자를 선택해주세요.</string>
<string name="timeletter_write_save_failed">저장에 실패했어요. 다시 시도해주세요.</string>
<string name="timeletter_write_exit_save_draft_message">작성 중인 내용을 임시저장할까요?</string>
<string name="timeletter_write_exit_discard_message">작성한 내용을 삭제할까요?</string>
<string name="timeletter_write_exit_discard_edit_message">수정한 내용을 취소할까요?</string>
<string name="timeletter_write_exit_cancel">취소</string>
<string name="timeletter_write_rejected">요청을 처리할 수 없어요. 다시 확인해주세요.</string>
<string name="timeletter_voice_recording_title">음성 메시지 녹음</string>
<string name="timeletter_voice_recording_instruction">녹음 버튼을 눌러 음성 메시지를 남겨주세요.</string>
Expand Down
Original file line number Diff line number Diff line change
@@ -1,11 +1,15 @@
package com.afternote.feature.timeletter.presentation.screen.sender

import androidx.activity.OnBackPressedDispatcher
import androidx.activity.compose.LocalOnBackPressedDispatcherOwner
import androidx.compose.foundation.text.input.TextFieldState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.compose.ui.test.junit4.v2.createComposeRule
import androidx.compose.ui.test.onNodeWithContentDescription
import androidx.compose.ui.test.onNodeWithText
import androidx.compose.ui.test.performClick
import com.afternote.core.ui.theme.AfternoteTheme
import com.afternote.feature.timeletter.presentation.viewmodel.TimeLetterWriteUiState
import org.junit.Assert.assertEquals
Expand Down Expand Up @@ -56,6 +60,168 @@ class TimeLetterWriteScreenTest {
}
}

@Test
fun `변경 없이 뒤로가면 팝업 없이 바로 나간다`() {
var backCount = 0
setWriteScreen(onBackClick = { backCount++ })

composeRule.onNodeWithContentDescription("뒤로가기").performClick()

composeRule.onNodeWithText(SAVE_DRAFT_MESSAGE).assertDoesNotExist()
composeRule.runOnIdle { assertEquals(1, backCount) }
}

@Test
fun `작성 중 뒤로가기에서 임시저장을 고르면 작성 내용으로 임시저장하고 직접 나가지 않는다`() {
var backCount = 0
val draftRequests = mutableListOf<String>()
val titleState = TextFieldState()
val dispatcher =
setWriteScreen(
titleState = titleState,
onBackClick = { backCount++ },
onDraftClick = { title, _ -> draftRequests += title },
)

composeRule.runOnIdle { titleState.edit { append("작성 중") } }
composeRule.runOnIdle { dispatcher.onBackPressed() }
composeRule.onNodeWithText(SAVE_DRAFT_MESSAGE).assertExists()
composeRule.onNodeWithText("예").performClick()

// 이탈은 임시저장 성공(savedAsDraft)이 맡는다 — 수신인 누락·저장 실패면 화면에 남아 오류를 보여야 한다.
composeRule.onNodeWithText(SAVE_DRAFT_MESSAGE).assertDoesNotExist()
composeRule.runOnIdle {
assertEquals(listOf("작성 중"), draftRequests)
assertEquals(0, backCount)
}
}

@Test
fun `임시저장을 거절하고 삭제를 확인하면 저장 없이 나간다`() {
var backCount = 0
var draftCount = 0
var uiState by mutableStateOf(TimeLetterWriteUiState())
setWriteScreen(
uiState = { uiState },
onBackClick = { backCount++ },
onDraftClick = { _, _ -> draftCount++ },
)

composeRule.runOnIdle { uiState = uiState.copy(recipientIds = listOf(1L), sendAt = "2026-12-25") }
composeRule.onNodeWithContentDescription("뒤로가기").performClick()
composeRule.onNodeWithText("아니요").performClick()
composeRule.onNodeWithText(DISCARD_MESSAGE).assertExists()
composeRule.onNodeWithText("예").performClick()

composeRule.runOnIdle {
assertEquals(1, backCount)
assertEquals(0, draftCount)
}
}

@Test
fun `삭제 확인에서 취소하면 작성 화면에 남고 내용을 지킨다`() {
var backCount = 0
val titleState = TextFieldState()
val dispatcher = setWriteScreen(titleState = titleState, onBackClick = { backCount++ })

composeRule.runOnIdle { titleState.edit { append("작성 중") } }
composeRule.runOnIdle { dispatcher.onBackPressed() }
composeRule.onNodeWithText("아니요").performClick()
composeRule.onNodeWithText("취소").performClick()

composeRule.onNodeWithText(DISCARD_MESSAGE).assertDoesNotExist()
composeRule.runOnIdle {
assertEquals(0, backCount)
assertEquals("작성 중", titleState.text.toString())
}
}

@Test
fun `예약 편지 수정 중 뒤로가기는 임시저장을 묻지 않고 수정 취소만 묻는다`() {
var backCount = 0
var draftCount = 0
var uiState by mutableStateOf(TimeLetterWriteUiState(isLoadingEditingLetter = true))
setWriteScreen(
uiState = { uiState },
onBackClick = { backCount++ },
onDraftClick = { _, _ -> draftCount++ },
)
val loaded =
TimeLetterWriteUiState(
editingTimeLetterId = 1L,
isEditingScheduledLetter = true,
draftTitle = "기존 제목",
recipientIds = listOf(1L),
sendAt = "2026-12-25",
)
composeRule.runOnIdle { uiState = loaded }
composeRule.waitForIdle()

composeRule.runOnIdle { uiState = loaded.copy(sendAt = "2026-12-31") }
composeRule.onNodeWithContentDescription("뒤로가기").performClick()

composeRule.onNodeWithText(SAVE_DRAFT_MESSAGE).assertDoesNotExist()
composeRule.onNodeWithText(DISCARD_EDIT_MESSAGE).assertExists()
composeRule.onNodeWithText("예").performClick()

composeRule.runOnIdle {
assertEquals(1, backCount)
assertEquals(0, draftCount)
}
}

@Test
fun `수정 모드에서 불러온 내용을 바꾸지 않고 나가면 팝업을 띄우지 않는다`() {
var backCount = 0
var uiState by mutableStateOf(TimeLetterWriteUiState(isLoadingEditingLetter = true))
setWriteScreen(uiState = { uiState }, onBackClick = { backCount++ })

composeRule.runOnIdle {
uiState =
TimeLetterWriteUiState(
editingTimeLetterId = 1L,
draftTitle = "기존 제목",
draftTextContents = mapOf(0L to "기존 내용"),
recipientIds = listOf(1L),
sendAt = "2026-12-25",
)
}
composeRule.waitForIdle()
composeRule.onNodeWithContentDescription("뒤로가기").performClick()

composeRule.onNodeWithText(SAVE_DRAFT_MESSAGE).assertDoesNotExist()
composeRule.runOnIdle { assertEquals(1, backCount) }
}

private fun setWriteScreen(
uiState: () -> TimeLetterWriteUiState = { TimeLetterWriteUiState() },
titleState: TextFieldState = TextFieldState(),
onBackClick: () -> Unit,
onDraftClick: (String, Map<Long, String>) -> Unit = { _, _ -> },
): OnBackPressedDispatcher {
lateinit var dispatcher: OnBackPressedDispatcher
composeRule.setContent {
dispatcher = checkNotNull(LocalOnBackPressedDispatcherOwner.current).onBackPressedDispatcher
AfternoteTheme {
TimeLetterWriteScreen(
uiState = uiState(),
titleState = titleState,
onBackClick = onBackClick,
onDraftClick = onDraftClick,
)
}
}
composeRule.waitForIdle()
return dispatcher
}

private companion object {
const val SAVE_DRAFT_MESSAGE = "작성 중인 내용을 임시저장할까요?"
const val DISCARD_MESSAGE = "작성한 내용을 삭제할까요?"
const val DISCARD_EDIT_MESSAGE = "수정한 내용을 취소할까요?"
}

@Test
fun `voice recorder keeps audio file picker available`() {
composeRule.setContent {
Expand Down
Loading
Loading