// data/repository/NoteRepositoryImpl.kt
package com.example.noteapp.data.repository
import arrow.core.Either
import com.example.noteapp.data.database.dao.NoteDao
import com.example.noteapp.data.database.dao.TagDao
import com.example.noteapp.data.database.entities.NoteEntity
import com.example.noteapp.data.database.entities.NoteTagCrossRef
import com.example.noteapp.data.database.entities.TagEntity
import com.example.noteapp.domain.model.ChecklistItem
import com.example.noteapp.domain.model.Note
import com.example.noteapp.domain.model.Tag
import com.example.noteapp.domain.repository.NoteRepository
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.map
import kotlinx.datetime.Instant
import kotlinx.serialization.encodeToString
import kotlinx.serialization.json.Json
class NoteRepositoryImpl(
private val noteDao: NoteDao,
private val tagDao: TagDao,
private val json: Json
) : NoteRepository {
override fun getAllNotes(): Flow<List<Note>> {
return noteDao.getAllNotesWithTags().map { notesWithTags ->
notesWithTags.map { noteWithTags ->
noteWithTags.toNote(json)
}
}
}
override suspend fun getNoteById(id: String): Either<Throwable, Note?> {
return Either.catch {
noteDao.getNoteWithTags(id)?.toNote(json)
}
}
override suspend fun saveNote(note: Note): Either<Throwable, Unit> {
return Either.catch {
noteDao.insertNote(note.toEntity(json))
noteDao.deleteNoteTagCrossRefs(note.id)
note.tags.forEach { tag ->
tagDao.insertTag(tag.toEntity())
noteDao.insertNoteTagCrossRef(NoteTagCrossRef(note.id, tag.id))
}
}
}
override suspend fun deleteNote(id: String): Either<Throwable, Unit> {
return Either.catch {
val noteWithTags = noteDao.getNoteWithTags(id)
noteWithTags?.let {
noteDao.deleteNote(it.note)
}
}
}
}
// Extension functions
private fun com.example.noteapp.data.database.entities.NoteWithTags.toNote(json: Json): Note {
return Note(
id = note.id,
title = note.title,
content = note.content,
checklistItems = note.checklistItems?.let {
json.decodeFromString<List<ChecklistItem>>(it)
} ?: emptyList(),
updateDate = note.updateDate,
reminders = note.reminders?.let {
json.decodeFromString<List<Instant>>(it)
} ?: emptyList(),
color = note.color,
isTrashed = note.isTrashed,
isPinned = note.isPinned,
isArchived = note.isArchived,
tags = tags.map { it.toTag() }
)
}
private fun Note.toEntity(json: Json): NoteEntity {
return NoteEntity(
id = id,
title = title,
content = content,
checklistItems = if (checklistItems.isNotEmpty()) {
json.encodeToString(checklistItems)
} else null,
updateDate = updateDate,
reminders = if (reminders.isNotEmpty()) {
json.encodeToString(reminders)
} else null,
color = color,
isTrashed = isTrashed,
isPinned = isPinned,
isArchived = isArchived
)
}
private fun TagEntity.toTag(): Tag = Tag(id = id, name = name, color = color)
private fun Tag.toEntity(): TagEntity = TagEntity(id = id, name = name, color = color)
// presentation/notelist/NoteListViewModel.kt
package com.example.noteapp.presentation.notelist
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.example.noteapp.domain.model.Note
import com.example.noteapp.domain.usecase.DeleteNoteUseCase
import com.example.noteapp.domain.usecase.GetNotesUseCase
import kotlinx.coroutines.flow.*
import kotlinx.coroutines.launch
class NoteListViewModel(
private val getNotesUseCase: GetNotesUseCase,
private val deleteNoteUseCase: DeleteNoteUseCase
) : ViewModel() {
private val _uiState = MutableStateFlow(NoteListUiState())
val uiState: StateFlow<NoteListUiState> = _uiState.asStateFlow()
val notes: StateFlow<List<Note>> = getNotesUseCase()
.stateIn(
scope = viewModelScope,
started = SharingStarted.WhileSubscribed(5000),
initialValue = emptyList()
)
fun deleteNote(note: Note) {
viewModelScope.launch {
deleteNoteUseCase(note.id).fold(
ifLeft = { error ->
_uiState.update { it.copy(error = error.message) }
},
ifRight = {
// Success handled by Flow update
}
)
}
}
}
data class NoteListUiState(
val isLoading: Boolean = false,
val error: String? = null
)
// presentation/notedetail/NoteDetailViewModel.kt
package com.example.noteapp.presentation.notedetail
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.example.noteapp.domain.model.ChecklistItem
import com.example.noteapp.domain.model.Note
import com.example.noteapp.domain.usecase.DeleteNoteUseCase
import com.example.noteapp.domain.usecase.GetNoteByIdUseCase
import com.example.noteapp.domain.usecase.SaveNoteUseCase
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
import kotlinx.datetime.Clock
class NoteDetailViewModel(
private val noteId: String?,
private val getNoteByIdUseCase: GetNoteByIdUseCase,
private val saveNoteUseCase: SaveNoteUseCase,
private val deleteNoteUseCase: DeleteNoteUseCase
) : ViewModel() {
private val _uiState = MutableStateFlow(NoteDetailUiState())
val uiState: StateFlow<NoteDetailUiState> = _uiState.asStateFlow()
init {
if (noteId != null) {
loadNote(noteId)
} else {
_uiState.update { it.copy(note = Note(title = "", content = "")) }
}
}
private fun loadNote(id: String) {
viewModelScope.launch {
getNoteByIdUseCase(id).fold(
ifLeft = { error ->
_uiState.update { it.copy(error = error.message) }
},
ifRight = { note ->
note?.let {
_uiState.update { state -> state.copy(note = it) }
}
}
)
}
}
fun updateTitle(title: String) {
_uiState.update { state ->
state.copy(note = state.note?.copy(title = title))
}
}
fun updateContent(content: String) {
_uiState.update { state ->
state.copy(note = state.note?.copy(content = content))
}
}
fun addChecklistItem(text: String) {
_uiState.update { state ->
state.note?.let { note ->
val newItem = ChecklistItem(
text = text,
order = note.checklistItems.size
)
state.copy(
note = note.copy(
checklistItems = note.checklistItems + newItem
)
)
} ?: state
}
}
fun updateChecklistItem(item: ChecklistItem) {
_uiState.update { state ->
state.note?.let { note ->
state.copy(
note = note.copy(
checklistItems = note.checklistItems.map {
if (it.id == item.id) item else it
}
)
)
} ?: state
}
}
fun reorderChecklistItems(from: Int, to: Int) {
_uiState.update { state ->
state.note?.let { note ->
val items = note.checklistItems.toMutableList()
val item = items.removeAt(from)
items.add(to, item)
state.copy(
note = note.copy(
checklistItems = items.mapIndexed { index, checklistItem ->
checklistItem.copy(order = index)
}
)
)
} ?: state
}
}
fun saveNote() {
viewModelScope.launch {
_uiState.value.note?.let { note ->
val updatedNote = note.copy(updateDate = Clock.System.now())
saveNoteUseCase(updatedNote).fold(
ifLeft = { error ->
_uiState.update { it.copy(error = error.message) }
},
ifRight = {
_uiState.update { it.copy(isSaved = true) }
}
)
}
}
}
fun deleteNote() {
viewModelScope.launch {
noteId?.let {
deleteNoteUseCase(it).fold(
ifLeft = { error ->
_uiState.update { state -> state.copy(error = error.message) }
},
ifRight = {
_uiState.update { it.copy(isDeleted = true) }
}
)
}
}
}
}
data class NoteDetailUiState(
val note: Note? = null,
val isLoading: Boolean = false,
val error: String? = null,
val isSaved: Boolean = false,
val isDeleted: Boolean = false
)
// presentation/notelist/NoteListScreen.kt
package com.example.noteapp.presentation.notelist
import androidx.compose.animation.AnimatedVisibilityScope
import androidx.compose.animation.ExperimentalSharedTransitionApi
import androidx.compose.animation.SharedTransitionScope
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.grid.GridCells
import androidx.compose.foundation.lazy.grid.LazyVerticalGrid
import androidx.compose.foundation.lazy.grid.items
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Add
import androidx.compose.material.icons.filled.PushPin
import androidx.compose.material3.*
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.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import com.example.noteapp.domain.model.Note
import kotlinx.datetime.TimeZone
import kotlinx.datetime.toLocalDateTime
import org.koin.androidx.compose.koinViewModel
@OptIn(ExperimentalSharedTransitionApi::class)
@Composable
fun SharedTransitionScope.NoteListScreen(
animatedVisibilityScope: AnimatedVisibilityScope,
onNavigateToDetail: (String?) -> Unit,
viewModel: NoteListViewModel = koinViewModel()
) {
val notes by viewModel.notes.collectAsState()
val uiState by viewModel.uiState.collectAsState()
Scaffold(
topBar = {
TopAppBar(
title = { Text("Notes") }
)
},
floatingActionButton = {
FloatingActionButton(
onClick = { onNavigateToDetail(null) }
) {
Icon(Icons.Default.Add, contentDescription = "Add Note")
}
}
) { paddingValues ->
LazyVerticalGrid(
columns = GridCells.Fixed(2),
contentPadding = paddingValues,
horizontalArrangement = Arrangement.spacedBy(8.dp),
verticalArrangement = Arrangement.spacedBy(8.dp),
modifier = Modifier
.fillMaxSize()
.padding(horizontal = 8.dp)
) {
items(
items = notes,
key = { it.id }
) { note ->
NoteItem(
note = note,
animatedVisibilityScope = animatedVisibilityScope,
onClick = { onNavigateToDetail(note.id) }
)
}
}
}
uiState.error?.let { error ->
LaunchedEffect(error) {
// Show error snackbar
}
}
}
@OptIn(ExperimentalSharedTransitionApi::class)
@Composable
fun SharedTransitionScope.NoteItem(
note: Note,
animatedVisibilityScope: AnimatedVisibilityScope,
onClick: () -> Unit
) {
Card(
modifier = Modifier
.fillMaxWidth()
.sharedElement(
state = rememberSharedContentState(key = "note-${note.id}"),
animatedVisibilityScope = animatedVisibilityScope
)
.clickable { onClick() },
colors = CardDefaults.cardColors(
containerColor = Color(note.color)
)
) {
Column(
modifier = Modifier
.fillMaxWidth()
.padding(12.dp)
) {
if (note.isPinned) {
Icon(
Icons.Default.PushPin,
contentDescription = "Pinned",
modifier = Modifier.size(16.dp)
)
}
Text(
text = note.title,
style = MaterialTheme.typography.titleMedium,
maxLines = 2,
overflow = TextOverflow.Ellipsis
)
Spacer(modifier = Modifier.height(4.dp))
note.content?.let { content ->
Text(
text = content,
style = MaterialTheme.typography.bodyMedium,
maxLines = 4,
overflow = TextOverflow.Ellipsis
)
}
if (note.checklistItems.isNotEmpty()) {
Column {
note.checklistItems.take(3).forEach { item ->
Row(
modifier = Modifier.padding(vertical = 2.dp),
verticalAlignment = Alignment.CenterVertically
) {
Checkbox(
checked = item.isChecked,
onCheckedChange = null,
modifier = Modifier.size(16.dp)
)
Text(
text = item.text,
style = MaterialTheme.typography.bodySmall,
maxLines = 1,
overflow = TextOverflow.Ellipsis,
modifier = Modifier.padding(start = 4.dp)
)
}
}
}
}
Spacer(modifier = Modifier.height(8.dp))
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.SpaceBetween
) {
Text(
text = note.updateDate.toLocalDateTime(TimeZone.currentSystemDefault())
.date.toString(),
style = MaterialTheme.typography.labelSmall
)
Row {
note.tags.forEach { tag ->
Box(
modifier = Modifier
.padding(horizontal = 2.dp)
.clip(RoundedCornerShape(4.dp))
.background(Color(tag.color))
.padding(horizontal = 4.dp, vertical = 2.dp)
) {
Text(
text = tag.name,
style = MaterialTheme.typography.labelSmall,
color = Color.White
)
}
}
}
}
}
}
}
// presentation/notedetail/NoteDetailScreen.kt
package com.example.noteapp.presentation.notedetail
import androidx.compose.animation.AnimatedVisibilityScope
import androidx.compose.animation.ExperimentalSharedTransitionApi
import androidx.compose.animation.SharedTransitionScope
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.*
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.dp
import com.example.noteapp.domain.model.ChecklistItem
import org.koin.androidx.compose.koinViewModel
import org.koin.core.parameter.parametersOf
@OptIn(ExperimentalSharedTransitionApi::class, ExperimentalMaterial3Api::class)
@Composable
fun SharedTransitionScope.NoteDetailScreen(
noteId: String?,
animatedVisibilityScope: AnimatedVisibilityScope,
onNavigateBack: () -> Unit,
viewModel: NoteDetailViewModel = koinViewModel { parametersOf(noteId) }
) {
val uiState by viewModel.uiState.collectAsState()
LaunchedEffect(uiState.isSaved, uiState.isDeleted) {
if (uiState.isSaved || uiState.isDeleted) {
onNavigateBack()
}
}
Scaffold(
topBar = {
TopAppBar(
title = { },
navigationIcon = {
IconButton(onClick = onNavigateBack) {
Icon(Icons.Default.ArrowBack, contentDescription = "Back")
}
},
actions = {
IconButton(onClick = viewModel::saveNote) {
Icon(Icons.Default.Save, contentDescription = "Save")
}
if (noteId != null) {
IconButton(onClick = viewModel::deleteNote) {
Icon(Icons.Default.Delete, contentDescription = "Delete")
}
}
}
)
},
modifier = Modifier.sharedElement(
state = rememberSharedContentState(key = "note-$noteId"),
animatedVisibilityScope = animatedVisibilityScope
)
) { paddingValues ->
uiState.note?.let { note ->
LazyColumn(
modifier = Modifier
.fillMaxSize()
.padding(paddingValues)
.padding(16.dp),
verticalArrangement = Arrangement.spacedBy(8.dp)
) {
item {
TextField(
value = note.title,
onValueChange = viewModel::updateTitle,
placeholder = { Text("Title") },
colors = TextFieldDefaults.colors(
focusedContainerColor = Color.Transparent,
unfocusedContainerColor = Color.Transparent,
focusedIndicatorColor = Color.Transparent,
unfocusedIndicatorColor = Color.Transparent
),
textStyle = MaterialTheme.typography.headlineMedium,
modifier = Modifier.fillMaxWidth()
)
}
item {
var showChecklistInput by remember { mutableStateOf(false) }
if (note.content != null || note.checklistItems.isEmpty()) {
TextField(
value = note.content ?: "",
onValueChange = viewModel::updateContent,
placeholder = { Text("Note") },
colors = TextFieldDefaults.colors(
focusedContainerColor = Color.Transparent,
unfocusedContainerColor = Color.Transparent,
focusedIndicatorColor = Color.Transparent,
unfocusedIndicatorColor = Color.Transparent
),
modifier = Modifier.fillMaxWidth()
)
}
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.End
) {
TextButton(
onClick = { showChecklistInput = !showChecklistInput }
) {
Icon(
Icons.Default.CheckBox,
contentDescription = "Add Checklist"
)
Text("Add Checklist")
}
}
if (showChecklistInput) {
var newItemText by remember { mutableStateOf("") }
Row(
modifier = Modifier.fillMaxWidth(),
verticalAlignment = Alignment.CenterVertically
) {
TextField(
value = newItemText,
onValueChange = { newItemText = it },
placeholder = { Text("New item") },
modifier = Modifier.weight(1f)
)
IconButton(
onClick = {
if (newItemText.isNotBlank()) {
viewModel.addChecklistItem(newItemText)
newItemText = ""
}
}
) {
Icon(Icons.Default.Add, contentDescription = "Add")
}
}
}
}
items(
items = note.checklistItems,
key = { it.id }
) { item ->
ChecklistItemRow(
item = item,
onCheckedChange = { checked ->
viewModel.updateChecklistItem(item.copy(isChecked = checked))
},
onTextChange = { text ->
viewModel.updateChecklistItem(item.copy(text = text))
}
)
}
}
}
}
}
@Composable
fun ChecklistItemRow(
item: ChecklistItem,
onCheckedChange: (Boolean) -> Unit,
onTextChange: (String) -> Unit
) {
Row(
modifier = Modifier.fillMaxWidth(),
verticalAlignment = Alignment.CenterVertically
) {
Checkbox(
checked = item.isChecked,
onCheckedChange = onCheckedChange
)
TextField(
value = item.text,
onValueChange = onTextChange,
colors = TextFieldDefaults.colors(
focusedContainerColor = Color.Transparent,
unfocusedContainerColor = Color.Transparent,
focusedIndicatorColor = Color.Transparent,
unfocusedIndicatorColor = Color.Transparent
),
modifier = Modifier.weight(1f)
)
}
}