這次主要建立 NoteEditViewModel,用來處理新增筆記和載入現有筆記
@Composable
fun AllNotesScreen(
modifier: Modifier = Modifier,
uiState: NoteListUiState,
onNavigateBack: () -> Unit,
onNoteClick: (Long) -> Unit
) {
AllNotesScreenContent(
modifier = modifier,
notes = uiState.notes, // We show all notes, not filtered ones
onNavigateBack = onNavigateBack,
onNoteClick = onNoteClick
)
}
@OptIn(ExperimentalMaterial3Api::class)
@Composable
private fun AllNotesScreenContent(
modifier: Modifier = Modifier,
notes: List<com.example.androidtemplate.domain.model.Note>,
onNavigateBack: () -> Unit,
onNoteClick: (Long) -> Unit
) {
Scaffold(
modifier = modifier.fillMaxSize(),
topBar = {
TopAppBar(
title = { Text("全部筆記") },
navigationIcon = {
IconButton(onClick = onNavigateBack) {
Icon(
imageVector = Icons.Default.ArrowBack,
contentDescription = "返回"
)
}
}
)
}
) { innerPadding ->
SearchResultList(
notes = notes,
onNoteClick = onNoteClick,
modifier = Modifier.padding(innerPadding)
)
}
}
class NoteEditViewModel @Inject constructor(
private val noteUseCases: NoteUseCases,
savedStateHandle: SavedStateHandle
) : ViewModel() {
private val _uiState = MutableStateFlow(NoteEditUiState())
val uiState = _uiState.asStateFlow()
private val noteId: Long = savedStateHandle.get<String>("id")?.toLongOrNull() ?: 0L
init {
if (noteId != 0L) {
loadNote()
} else {
_uiState.value = NoteEditUiState(
note = createNewNote(),
isLoading = false
)
}
}
private fun loadNote() {
viewModelScope.launch {
val note = noteUseCases.getNoteById(noteId) // Need to add this use case
_uiState.value = NoteEditUiState(note = note, isLoading = false)
}
}
fun saveNote(title: String, content: String) {
viewModelScope.launch {
val noteToSave = _uiState.value.note?.copy(
title = title,
content = content
) ?: createNewNote().copy(
title = title,
content = content
)
noteUseCases.saveNote(noteToSave)
_uiState.value = _uiState.value.copy(isNoteSaved = true)
}
}
private fun createNewNote(): Note {
return Note(
id = 0L,
title = "",
content = "",
categoryId = 0L, // Default or "Uncategorized"
tags = emptyList(),
createdAt = System.currentTimeMillis(),
updatedAt = System.currentTimeMillis()
)
}
}
sealed interface NavRoute {
/**
* 首頁路由
*/
@Serializable
data object Home : NavRoute
@Serializable
data object AllNotes : NavRoute
@Serializable
data object AllNotes : NavRoute
/**
* 筆記編輯/新增路由
*
* @param noteId 筆記 ID (0L for new note)
*/
@Serializable
data class NoteEdit(val noteId: String) : NavRoute
/**
* 設定頁面路由
*/
@Serializable
data object Settings : NavRoute
}