diff --git a/app/src/main/java/com/philkes/notallyx/presentation/activity/ConfigureWidgetActivity.kt b/app/src/main/java/com/philkes/notallyx/presentation/activity/ConfigureWidgetActivity.kt index be19a89..093e760 100644 --- a/app/src/main/java/com/philkes/notallyx/presentation/activity/ConfigureWidgetActivity.kt +++ b/app/src/main/java/com/philkes/notallyx/presentation/activity/ConfigureWidgetActivity.kt @@ -25,19 +25,16 @@ class ConfigureWidgetActivity : PickNoteActivity() { setResult(RESULT_CANCELED, result) } - override fun onClick(position: Int) { - if (position != -1) { - val preferences = NotallyXPreferences.getInstance(application) - val baseNote = adapter.getItem(position) as BaseNote - preferences.updateWidget(id, baseNote.id, baseNote.type) - - val manager = AppWidgetManager.getInstance(this) - WidgetProvider.updateWidget(application, manager, id, baseNote.id, baseNote.type) - - val success = Intent() - success.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, id) - setResult(RESULT_OK, success) - finish() - } + override fun onNotePicked(note: BaseNote) { + val preferences = NotallyXPreferences.getInstance(application) + preferences.updateWidget(id, note.id, note.type) + + val manager = AppWidgetManager.getInstance(this) + WidgetProvider.updateWidget(application, manager, id, note.id, note.type) + + val success = Intent() + success.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, id) + setResult(RESULT_OK, success) + finish() } } diff --git a/app/src/main/java/com/philkes/notallyx/presentation/activity/main/MainActivity.kt b/app/src/main/java/com/philkes/notallyx/presentation/activity/main/MainActivity.kt index 7d30533..dd7cf7e 100644 --- a/app/src/main/java/com/philkes/notallyx/presentation/activity/main/MainActivity.kt +++ b/app/src/main/java/com/philkes/notallyx/presentation/activity/main/MainActivity.kt @@ -5,6 +5,11 @@ import android.content.pm.PackageManager import android.os.Bundle import android.transition.TransitionManager import android.view.Menu +import androidx.compose.runtime.getValue +import androidx.compose.runtime.livedata.observeAsState +import androidx.compose.ui.platform.ViewCompositionStrategy +import com.philkes.notallyx.presentation.view.main.NotallyTheme +import com.philkes.notallyx.presentation.view.main.SelectionBar import android.view.Menu.CATEGORY_CONTAINER import android.view.Menu.CATEGORY_SYSTEM import android.view.MenuItem @@ -402,8 +407,6 @@ class MainActivity : LockedActivity() { } private fun setupActionMode() { - binding.ActionMode.setNavigationOnClickListener { baseModel.actionMode.close(true) } - val transition = MaterialFade().apply { secondaryAnimatorProvider = null @@ -428,10 +431,22 @@ class MainActivity : LockedActivity() { actionModeCancelCallback.isEnabled = enabled } - val menu = binding.ActionMode.menu - baseModel.folder.observe(this@MainActivity, ModelFolderObserver(this, menu, baseModel)) - baseModel.actionMode.loading.observe(this@MainActivity) { loading -> - menu.setGroupEnabled(Menu.NONE, !loading) + val selectionActions = SelectionActions(this, baseModel) + binding.ActionMode.apply { + setViewCompositionStrategy(ViewCompositionStrategy.DisposeOnViewTreeLifecycleDestroyed) + setContent { + NotallyTheme { + val folder by baseModel.folder.observeAsState(baseModel.folder.value) + val selection by baseModel.actionMode.selection.observeAsState(emptyList()) + val loading by baseModel.actionMode.loading.observeAsState(false) + SelectionBar( + count = selection.size, + actions = selectionActions.forFolder(folder, selection), + enabled = !loading, + onClose = { baseModel.actionMode.close(true) }, + ) + } + } } } diff --git a/app/src/main/java/com/philkes/notallyx/presentation/activity/main/ModelFolderObserver.kt b/app/src/main/java/com/philkes/notallyx/presentation/activity/main/ModelFolderObserver.kt deleted file mode 100644 index 356c00b..0000000 --- a/app/src/main/java/com/philkes/notallyx/presentation/activity/main/ModelFolderObserver.kt +++ /dev/null @@ -1,367 +0,0 @@ -package com.philkes.notallyx.presentation.activity.main - -import android.view.Menu -import android.view.MenuItem -import androidx.lifecycle.LifecycleOwner -import androidx.lifecycle.Observer -import androidx.lifecycle.lifecycleScope -import com.google.android.material.dialog.MaterialAlertDialogBuilder -import com.google.android.material.snackbar.Snackbar -import com.philkes.notallyx.R -import com.philkes.notallyx.data.NotallyDatabase -import com.philkes.notallyx.data.model.BaseNote -import com.philkes.notallyx.data.model.Folder -import com.philkes.notallyx.presentation.activity.note.NoteActionHandler -import com.philkes.notallyx.presentation.add -import com.philkes.notallyx.presentation.checkNotificationPermission -import com.philkes.notallyx.presentation.getQuantityString -import com.philkes.notallyx.presentation.movedToResId -import com.philkes.notallyx.presentation.setCancelButton -import com.philkes.notallyx.presentation.view.misc.NotNullLiveData -import com.philkes.notallyx.presentation.view.misc.tristatecheckbox.TriStateCheckBox -import com.philkes.notallyx.presentation.view.misc.tristatecheckbox.setMultiChoiceTriStateItems -import com.philkes.notallyx.presentation.viewmodel.BaseNoteModel -import com.philkes.notallyx.presentation.viewmodel.ExportMimeType -import com.philkes.notallyx.utils.deleteAttachments -import com.philkes.notallyx.utils.shareNote -import com.philkes.notallyx.utils.showColorSelectDialog -import kotlinx.coroutines.Dispatchers -import kotlinx.coroutines.launch -import kotlinx.coroutines.withContext - -class ModelFolderObserver( - private val activity: MainActivity, - private val menu: Menu, - private val model: BaseNoteModel, -) : Observer { - - private val baseModel - get() = activity.baseModel - - override fun onChanged(value: Folder) { - menu.clear() - model.actionMode.count.removeObservers(activity) - - menu.add( - R.string.select_all, - R.drawable.select_all, - showAsAction = MenuItem.SHOW_AS_ACTION_ALWAYS, - ) { - activity.getCurrentFragmentNotes?.invoke()?.let { model.actionMode.add(it) } - } - when (value) { - Folder.NOTES -> initNotesFolderMenu() - Folder.ARCHIVED -> initArchivedFolderMenu() - Folder.DELETED -> initDeletedFolderMenu() - } - } - - private fun initNotesFolderMenu() { - val pinned = menu.addPinned(MenuItem.SHOW_AS_ACTION_ALWAYS) - menu.addLabels(MenuItem.SHOW_AS_ACTION_ALWAYS) - menu.addDelete(MenuItem.SHOW_AS_ACTION_ALWAYS) - menu.add(R.string.duplicate, R.drawable.content_copy) { - baseModel.duplicateSelectedBaseNotes() - } - menu.add(R.string.archive, R.drawable.archive) { moveNotes(Folder.ARCHIVED) } - menu.addChangeColor() - val pinnedToStatus = menu.addPinnedToStatus() - val share = menu.addShare() - menu.addExportMenu() - model.actionMode.count.observeCountAndPinned(activity, share, pinned, pinnedToStatus) - } - - private fun initArchivedFolderMenu() { - menu.add(R.string.unarchive, R.drawable.unarchive, MenuItem.SHOW_AS_ACTION_ALWAYS) { - moveNotes(Folder.NOTES) - } - menu.addDelete(MenuItem.SHOW_AS_ACTION_ALWAYS) - menu.add(R.string.duplicate, R.drawable.content_copy) { - baseModel.duplicateSelectedBaseNotes() - } - menu.addExportMenu(MenuItem.SHOW_AS_ACTION_ALWAYS) - val pinned = menu.addPinned() - menu.addLabels() - menu.addChangeColor() - val share = menu.addShare() - model.actionMode.count.observeCountAndPinned(activity, share, pinned, null) - } - - private fun initDeletedFolderMenu() { - menu.add(R.string.restore, R.drawable.restore, MenuItem.SHOW_AS_ACTION_ALWAYS) { - moveNotes(Folder.NOTES) - } - menu.add(R.string.delete_forever, R.drawable.delete, MenuItem.SHOW_AS_ACTION_ALWAYS) { - deleteForever() - } - menu.addExportMenu() - menu.addChangeColor() - val share = menu.add(R.string.share, R.drawable.share) { share() } - model.actionMode.count.observeCount(activity, share) - } - - private fun Menu.addPinned(showAsAction: Int = MenuItem.SHOW_AS_ACTION_IF_ROOM): MenuItem { - return add(R.string.pin, R.drawable.pin, showAsAction) {} - } - - private fun Menu.addPinnedToStatus( - showAsAction: Int = MenuItem.SHOW_AS_ACTION_IF_ROOM - ): MenuItem { - return add(R.string.pin_to_status_bar, R.drawable.pinboard, showAsAction) {} - } - - private fun Menu.addLabels(showAsAction: Int = MenuItem.SHOW_AS_ACTION_IF_ROOM): MenuItem { - return add(R.string.labels, R.drawable.label, showAsAction) { label() } - } - - private fun Menu.addChangeColor(showAsAction: Int = MenuItem.SHOW_AS_ACTION_IF_ROOM): MenuItem { - return add(R.string.change_color, R.drawable.change_color, showAsAction) { - activity.lifecycleScope.launch { - val database = - withContext(Dispatchers.Main.immediate) { - NotallyDatabase.getDatabase(activity) - } - if (database.value == null) { - return@launch - } - val colors = - withContext(Dispatchers.IO) { - database.value!!.getBaseNoteDao().getAllColors().toSet() - } - // Show color as selected only if all selected notes have the same color - val currentColor = - model.actionMode.selectedNotes.values - .map { it.color } - .distinct() - .takeIf { it.size == 1 } - ?.firstOrNull() - activity.showColorSelectDialog( - colors, - currentColor, - null, - { selectedColor, oldColor -> - if (oldColor != null) { - model.changeColor(oldColor, selectedColor) - } - model.colorBaseNote(selectedColor) - }, - ) { colorToDelete, newColor -> - model.changeColor(colorToDelete, newColor) - } - } - } - } - - private fun Menu.addDelete(showAsAction: Int = MenuItem.SHOW_AS_ACTION_IF_ROOM): MenuItem { - return add(R.string.delete, R.drawable.delete, showAsAction) { moveNotes(Folder.DELETED) } - } - - private fun Menu.addShare(showAsAction: Int = MenuItem.SHOW_AS_ACTION_IF_ROOM): MenuItem { - return add(R.string.share, R.drawable.share, showAsAction) { share() } - } - - private fun Menu.addExportMenu(showAsAction: Int = MenuItem.SHOW_AS_ACTION_IF_ROOM): MenuItem { - return addSubMenu(R.string.export) - .apply { - setIcon(R.drawable.export) - item.setShowAsAction(showAsAction) - ExportMimeType.entries.forEach { - add(it.name).onClick { activity.exportSelectedNotes(it) } - } - } - .item - } - - fun MenuItem.onClick(function: () -> Unit) { - setOnMenuItemClickListener { - function() - return@setOnMenuItemClickListener false - } - } - - private fun NotNullLiveData.observeCount( - lifecycleOwner: LifecycleOwner, - share: MenuItem, - onCountChange: ((Int) -> Unit)? = null, - ) { - observe(lifecycleOwner) { count -> - activity.binding.ActionMode.title = count.toString() - onCountChange?.invoke(count) - share.setVisible(count == 1) - } - } - - private fun NotNullLiveData.observeCountAndPinned( - lifecycleOwner: LifecycleOwner, - share: MenuItem, - pinned: MenuItem, - pinnedToStatus: MenuItem?, - ) { - observeCount(lifecycleOwner, share) { - val baseNotes = model.actionMode.selectedNotes.values - if (baseNotes.any { !it.pinned }) { - pinned.setTitle(R.string.pin).setIcon(R.drawable.pin).onClick { - model.pinBaseNotes(true) - } - } else { - pinned.setTitle(R.string.unpin).setIcon(R.drawable.unpin).onClick { - model.pinBaseNotes(false) - } - } - pinnedToStatus?.let { - if (baseNotes.any { !it.isPinnedToStatus }) { - pinnedToStatus - .setTitle(R.string.pin_to_status_bar) - .setIcon(R.drawable.pinboard) - .onClick { - activity.checkNotificationPermission( - NoteActionHandler.REQUEST_NOTIFICATION_PERMISSION_PIN_TO_STATUS, - alsoCheckAlarmPermission = false, - ) { - model.pinBaseNotesToStatusBar(activity, true) - } - } - } else { - pinnedToStatus - .setTitle(R.string.unpin_from_status_bar) - .setIcon(R.drawable.pinboard_filled) - .onClick { model.pinBaseNotesToStatusBar(activity, false) } - } - } - } - } - - internal fun moveNotes(folderTo: Folder) { - if (baseModel.actionMode.loading.value || baseModel.actionMode.isEmpty()) { - return - } - try { - baseModel.actionMode.loading.value = true - val folderFrom = baseModel.actionMode.getFirstNote().folder - val ids = - baseModel.moveBaseNotes(folderTo) { baseModel.actionMode.loading.postValue(false) } - Snackbar.make( - activity.findViewById(R.id.DrawerLayout), - activity.getQuantityString(folderTo.movedToResId(), ids.size), - Snackbar.LENGTH_SHORT, - ) - .apply { setAction(R.string.undo) { baseModel.moveBaseNotes(ids, folderFrom) } } - .show() - } catch (_: Exception) { - baseModel.actionMode.loading.postValue(false) - } - } - - internal fun share() { - val baseNote = baseModel.actionMode.getFirstNote() - activity.shareNote(baseNote) - } - - internal fun deleteForever() { - MaterialAlertDialogBuilder(activity) - .setMessage(R.string.delete_selected_notes) - .setPositiveButton(R.string.delete) { _, _ -> - val removedNotes = baseModel.actionMode.selectedNotes.values.toList() - activity.lifecycleScope.launch { - val deletedNotes = baseModel.deleteSelectedBaseNotes() - Snackbar.make( - activity.findViewById(R.id.DrawerLayout), - activity.getQuantityString( - R.plurals.deleted_selected_notes, - removedNotes.size, - ), - Snackbar.LENGTH_SHORT, - ) - .apply { - setAction(R.string.undo) { baseModel.saveNotes(removedNotes) } - addCallback( - object : Snackbar.Callback() { - override fun onDismissed( - transientBottomBar: Snackbar?, - event: Int, - ) { - if (event != DISMISS_EVENT_ACTION) { - activity.deleteAttachments( - deletedNotes, - baseModel.progress, - ) - } - } - } - ) - } - .show() - } - } - .setCancelButton() - .show() - } - - internal fun label() { - val baseNotes = baseModel.actionMode.selectedNotes.values - activity.lifecycleScope.launch { - val labels = baseModel.getAllLabels() - if (labels.isNotEmpty()) { - displaySelectLabelsDialog(labels, baseNotes) - } else { - baseModel.actionMode.close(true) - activity.navigateWithAnimation(R.id.Labels) - } - } - } - - private fun displaySelectLabelsDialog(labels: Array, baseNotes: Collection) { - val checkedPositions = - labels - .map { label -> - if (baseNotes.all { it.labels.contains(label) }) { - TriStateCheckBox.State.CHECKED - } else if (baseNotes.any { it.labels.contains(label) }) { - TriStateCheckBox.State.PARTIALLY_CHECKED - } else { - TriStateCheckBox.State.UNCHECKED - } - } - .toTypedArray() - - MaterialAlertDialogBuilder(activity) - .setTitle(R.string.labels) - .setCancelButton() - .setMultiChoiceTriStateItems(activity, labels, checkedPositions) { idx, state -> - checkedPositions[idx] = state - } - .setPositiveButton(R.string.save) { _, _ -> - val checkedLabels = - checkedPositions.mapIndexedNotNull { index, checked -> - if (checked == TriStateCheckBox.State.CHECKED) { - labels[index] - } else null - } - val uncheckedLabels = - checkedPositions.mapIndexedNotNull { index, checked -> - if (checked == TriStateCheckBox.State.UNCHECKED) { - labels[index] - } else null - } - val updatedBaseNotesLabels = - baseNotes.map { baseNote -> - val noteLabels = baseNote.labels.toMutableList() - checkedLabels.forEach { checkedLabel -> - if (!noteLabels.contains(checkedLabel)) { - noteLabels.add(checkedLabel) - } - } - uncheckedLabels.forEach { uncheckedLabel -> - if (noteLabels.contains(uncheckedLabel)) { - noteLabels.remove(uncheckedLabel) - } - } - noteLabels - } - baseNotes.zip(updatedBaseNotesLabels).forEach { (baseNote, updatedLabels) -> - baseModel.updateBaseNoteLabels(updatedLabels, baseNote.id) - } - } - .show() - } -} diff --git a/app/src/main/java/com/philkes/notallyx/presentation/activity/main/SelectionActions.kt b/app/src/main/java/com/philkes/notallyx/presentation/activity/main/SelectionActions.kt new file mode 100644 index 0000000..d751eb6 --- /dev/null +++ b/app/src/main/java/com/philkes/notallyx/presentation/activity/main/SelectionActions.kt @@ -0,0 +1,274 @@ +package com.philkes.notallyx.presentation.activity.main + +import androidx.lifecycle.lifecycleScope +import com.google.android.material.dialog.MaterialAlertDialogBuilder +import com.google.android.material.snackbar.Snackbar +import com.philkes.notallyx.R +import com.philkes.notallyx.data.NotallyDatabase +import com.philkes.notallyx.data.model.BaseNote +import com.philkes.notallyx.data.model.Folder +import com.philkes.notallyx.presentation.activity.note.NoteActionHandler +import com.philkes.notallyx.presentation.checkNotificationPermission +import com.philkes.notallyx.presentation.getQuantityString +import com.philkes.notallyx.presentation.movedToResId +import com.philkes.notallyx.presentation.setCancelButton +import com.philkes.notallyx.presentation.view.main.SelectionAction +import com.philkes.notallyx.presentation.view.misc.tristatecheckbox.TriStateCheckBox +import com.philkes.notallyx.presentation.view.misc.tristatecheckbox.setMultiChoiceTriStateItems +import com.philkes.notallyx.presentation.viewmodel.BaseNoteModel +import com.philkes.notallyx.presentation.viewmodel.ExportMimeType +import com.philkes.notallyx.utils.deleteAttachments +import com.philkes.notallyx.utils.shareNote +import com.philkes.notallyx.utils.showColorSelectDialog +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.launch +import kotlinx.coroutines.withContext + +/** What the selection bar offers for the selected notes, per folder, and what each action does. */ +class SelectionActions(private val activity: MainActivity, private val model: BaseNoteModel) { + + fun forFolder(folder: Folder, selected: Collection): List { + val single = selected.size == 1 + val actions = + when (folder) { + Folder.NOTES -> + listOf( + selectAll(), + pin(selected, showAsIcon = true), + action(R.string.labels, R.drawable.label, true) { label() }, + action(R.string.delete, R.drawable.delete, true) { moveNotes(Folder.DELETED) }, + action(R.string.duplicate, R.drawable.content_copy) { + model.duplicateSelectedBaseNotes() + }, + action(R.string.archive, R.drawable.archive) { moveNotes(Folder.ARCHIVED) }, + changeColor(), + pinToStatusBar(selected), + share().takeIf { single }, + export(showAsIcon = false), + ) + Folder.ARCHIVED -> + listOf( + selectAll(), + action(R.string.unarchive, R.drawable.unarchive, true) { + moveNotes(Folder.NOTES) + }, + action(R.string.delete, R.drawable.delete, true) { moveNotes(Folder.DELETED) }, + action(R.string.duplicate, R.drawable.content_copy) { + model.duplicateSelectedBaseNotes() + }, + export(showAsIcon = true), + pin(selected, showAsIcon = false), + action(R.string.labels, R.drawable.label) { label() }, + changeColor(), + share().takeIf { single }, + ) + Folder.DELETED -> + listOf( + selectAll(), + action(R.string.restore, R.drawable.restore, true) { moveNotes(Folder.NOTES) }, + action(R.string.delete_forever, R.drawable.delete, true) { deleteForever() }, + export(showAsIcon = false), + changeColor(), + share().takeIf { single }, + ) + } + return actions.filterNotNull() + } + + private fun action( + title: Int, + icon: Int, + showAsIcon: Boolean = false, + onClick: () -> Unit, + ) = SelectionAction(activity.getString(title), icon, showAsIcon, onClick = onClick) + + private fun selectAll() = + action(R.string.select_all, R.drawable.select_all, true) { + activity.getCurrentFragmentNotes?.invoke()?.let { model.actionMode.add(it) } + } + + private fun pin(selected: Collection, showAsIcon: Boolean) = + if (selected.any { !it.pinned }) { + action(R.string.pin, R.drawable.pin, showAsIcon) { model.pinBaseNotes(true) } + } else { + action(R.string.unpin, R.drawable.unpin, showAsIcon) { model.pinBaseNotes(false) } + } + + private fun pinToStatusBar(selected: Collection) = + if (selected.any { !it.isPinnedToStatus }) { + action(R.string.pin_to_status_bar, R.drawable.pinboard) { + activity.checkNotificationPermission( + NoteActionHandler.REQUEST_NOTIFICATION_PERMISSION_PIN_TO_STATUS, + alsoCheckAlarmPermission = false, + ) { + model.pinBaseNotesToStatusBar(activity, true) + } + } + } else { + action(R.string.unpin_from_status_bar, R.drawable.pinboard_filled) { + model.pinBaseNotesToStatusBar(activity, false) + } + } + + private fun share() = + action(R.string.share, R.drawable.share) { + activity.shareNote(model.actionMode.getFirstNote()) + } + + private fun export(showAsIcon: Boolean) = + SelectionAction( + activity.getString(R.string.export), + R.drawable.export, + showAsIcon, + options = + ExportMimeType.entries.map { mimeType -> + mimeType.name to { activity.exportSelectedNotes(mimeType) } + }, + ) + + private fun changeColor() = + action(R.string.change_color, R.drawable.change_color) { + activity.lifecycleScope.launch { + val database = + withContext(Dispatchers.Main.immediate) { + NotallyDatabase.getDatabase(activity) + } + if (database.value == null) { + return@launch + } + val colors = + withContext(Dispatchers.IO) { + database.value!!.getBaseNoteDao().getAllColors().toSet() + } + // Show color as selected only if all selected notes have the same color + val currentColor = + model.actionMode.selectedNotes.values + .map { it.color } + .distinct() + .takeIf { it.size == 1 } + ?.firstOrNull() + activity.showColorSelectDialog( + colors, + currentColor, + null, + { selectedColor, oldColor -> + if (oldColor != null) { + model.changeColor(oldColor, selectedColor) + } + model.colorBaseNote(selectedColor) + }, + ) { colorToDelete, newColor -> + model.changeColor(colorToDelete, newColor) + } + } + } + + private fun moveNotes(folderTo: Folder) { + if (model.actionMode.loading.value || model.actionMode.isEmpty()) { + return + } + try { + model.actionMode.loading.value = true + val folderFrom = model.actionMode.getFirstNote().folder + val ids = model.moveBaseNotes(folderTo) { model.actionMode.loading.postValue(false) } + Snackbar.make( + activity.findViewById(R.id.DrawerLayout), + activity.getQuantityString(folderTo.movedToResId(), ids.size), + Snackbar.LENGTH_SHORT, + ) + .apply { setAction(R.string.undo) { model.moveBaseNotes(ids, folderFrom) } } + .show() + } catch (_: Exception) { + model.actionMode.loading.postValue(false) + } + } + + private fun deleteForever() { + MaterialAlertDialogBuilder(activity) + .setMessage(R.string.delete_selected_notes) + .setPositiveButton(R.string.delete) { _, _ -> + val removedNotes = model.actionMode.selectedNotes.values.toList() + activity.lifecycleScope.launch { + val deletedNotes = model.deleteSelectedBaseNotes() + Snackbar.make( + activity.findViewById(R.id.DrawerLayout), + activity.getQuantityString( + R.plurals.deleted_selected_notes, + removedNotes.size, + ), + Snackbar.LENGTH_SHORT, + ) + .apply { + setAction(R.string.undo) { model.saveNotes(removedNotes) } + addCallback( + object : Snackbar.Callback() { + override fun onDismissed( + transientBottomBar: Snackbar?, + event: Int, + ) { + if (event != DISMISS_EVENT_ACTION) { + activity.deleteAttachments(deletedNotes, model.progress) + } + } + } + ) + } + .show() + } + } + .setCancelButton() + .show() + } + + private fun label() { + val baseNotes = model.actionMode.selectedNotes.values.toList() + activity.lifecycleScope.launch { + val labels = model.getAllLabels() + if (labels.isNotEmpty()) { + displaySelectLabelsDialog(labels, baseNotes) + } else { + model.actionMode.close(true) + activity.navigateWithAnimation(R.id.Labels) + } + } + } + + private fun displaySelectLabelsDialog(labels: Array, baseNotes: Collection) { + val checkedPositions = + labels + .map { label -> + if (baseNotes.all { it.labels.contains(label) }) { + TriStateCheckBox.State.CHECKED + } else if (baseNotes.any { it.labels.contains(label) }) { + TriStateCheckBox.State.PARTIALLY_CHECKED + } else { + TriStateCheckBox.State.UNCHECKED + } + } + .toTypedArray() + + MaterialAlertDialogBuilder(activity) + .setTitle(R.string.labels) + .setCancelButton() + .setMultiChoiceTriStateItems(activity, labels, checkedPositions) { idx, state -> + checkedPositions[idx] = state + } + .setPositiveButton(R.string.save) { _, _ -> + val checkedLabels = + checkedPositions.mapIndexedNotNull { index, checked -> + if (checked == TriStateCheckBox.State.CHECKED) labels[index] else null + } + val uncheckedLabels = + checkedPositions.mapIndexedNotNull { index, checked -> + if (checked == TriStateCheckBox.State.UNCHECKED) labels[index] else null + } + baseNotes.forEach { baseNote -> + val noteLabels = baseNote.labels.toMutableList() + checkedLabels.forEach { if (!noteLabels.contains(it)) noteLabels.add(it) } + uncheckedLabels.forEach { noteLabels.remove(it) } + model.updateBaseNoteLabels(noteLabels, baseNote.id) + } + } + .show() + } +} diff --git a/app/src/main/java/com/philkes/notallyx/presentation/activity/main/fragment/NotallyFragment.kt b/app/src/main/java/com/philkes/notallyx/presentation/activity/main/fragment/NotallyFragment.kt index 724cb81..b05a1f8 100644 --- a/app/src/main/java/com/philkes/notallyx/presentation/activity/main/fragment/NotallyFragment.kt +++ b/app/src/main/java/com/philkes/notallyx/presentation/activity/main/fragment/NotallyFragment.kt @@ -8,23 +8,46 @@ import android.view.View import android.view.ViewGroup import androidx.activity.result.ActivityResultLauncher import androidx.activity.result.contract.ActivityResultContracts -import androidx.core.view.isVisible -import androidx.core.widget.doAfterTextChanged +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Text +import androidx.compose.material3.TextField +import androidx.compose.material3.TextFieldDefaults +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.SideEffect +import androidx.compose.runtime.MutableState +import androidx.compose.runtime.getValue +import androidx.compose.runtime.livedata.observeAsState +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.rememberCoroutineScope +import androidx.compose.ui.ExperimentalComposeUiApi +import androidx.compose.ui.Modifier +import androidx.compose.ui.focus.FocusRequester +import androidx.compose.ui.focus.focusRequester +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.platform.ComposeView +import androidx.compose.ui.platform.LocalFocusManager +import androidx.compose.ui.platform.LocalSoftwareKeyboardController +import androidx.compose.ui.platform.ViewCompositionStrategy +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.unit.dp import androidx.fragment.app.Fragment import androidx.fragment.app.activityViewModels import androidx.lifecycle.LiveData -import androidx.navigation.findNavController -import androidx.recyclerview.widget.LinearLayoutManager -import androidx.recyclerview.widget.RecyclerView -import androidx.recyclerview.widget.SortedListAdapterCallback -import androidx.recyclerview.widget.StaggeredGridLayoutManager +import androidx.navigation.fragment.findNavController import com.google.android.material.snackbar.Snackbar import com.philkes.notallyx.R import com.philkes.notallyx.data.model.BaseNote import com.philkes.notallyx.data.model.Folder import com.philkes.notallyx.data.model.Item import com.philkes.notallyx.data.model.Type -import com.philkes.notallyx.databinding.FragmentNotesBinding import com.philkes.notallyx.presentation.activity.main.MainActivity import com.philkes.notallyx.presentation.activity.main.fragment.SearchFragment.Companion.EXTRA_INITIAL_FOLDER import com.philkes.notallyx.presentation.activity.main.fragment.SearchFragment.Companion.EXTRA_INITIAL_LABEL @@ -37,69 +60,38 @@ import com.philkes.notallyx.presentation.activity.note.EditListActivity import com.philkes.notallyx.presentation.activity.note.EditNoteActivity import com.philkes.notallyx.presentation.activity.note.reminders.RemindersActivity import com.philkes.notallyx.presentation.getQuantityString -import com.philkes.notallyx.presentation.hideKeyboard import com.philkes.notallyx.presentation.movedToResId -import com.philkes.notallyx.presentation.showKeyboard -import com.philkes.notallyx.presentation.view.main.BaseNoteAdapter -import com.philkes.notallyx.presentation.view.main.BaseNoteVHPreferences -import com.philkes.notallyx.presentation.view.main.createCallback -import com.philkes.notallyx.presentation.view.misc.ItemListener +import com.philkes.notallyx.presentation.view.main.CardSettings +import com.philkes.notallyx.presentation.view.main.NotallyTheme +import com.philkes.notallyx.presentation.view.main.NotesList +import com.philkes.notallyx.presentation.view.main.NotesListState +import com.philkes.notallyx.presentation.view.main.SectionLabels +import com.philkes.notallyx.presentation.view.main.comparator +import com.philkes.notallyx.presentation.view.main.rememberNotesListState +import com.philkes.notallyx.presentation.view.main.sectioned import com.philkes.notallyx.presentation.viewmodel.BaseNoteModel +import com.philkes.notallyx.presentation.viewmodel.preference.NotesSort import com.philkes.notallyx.presentation.viewmodel.preference.NotesView +import kotlinx.coroutines.launch -abstract class NotallyFragment : Fragment(), ItemListener { - - protected var notesAdapter: BaseNoteAdapter? = null - private lateinit var openNoteActivityResultLauncher: ActivityResultLauncher - private var lastSelectedNotePosition = -1 - - internal var binding: FragmentNotesBinding? = null +/** + * A destination of the notes overview (Notes, a label, Unlabeled, Archived, Deleted, Reminders, + * Search): the listed notes in Compose, with selection, search field and filters. + */ +abstract class NotallyFragment : Fragment() { internal val model: BaseNoteModel by activityViewModels() - override fun onDestroyView() { - super.onDestroyView() - binding = null - notesAdapter = null - } - - override fun onSaveInstanceState(outState: Bundle) { - super.onSaveInstanceState(outState) - val layoutManager = binding?.MainListView?.layoutManager as? LinearLayoutManager - if (layoutManager != null) { - val firstVisiblePosition = layoutManager.findFirstVisibleItemPosition() - if (firstVisiblePosition != RecyclerView.NO_POSITION) { - val firstVisibleView = layoutManager.findViewByPosition(firstVisiblePosition) - val offset = firstVisibleView?.top ?: 0 - outState.putInt(EXTRA_SCROLL_POS, firstVisiblePosition) - outState.putInt(EXTRA_SCROLL_OFFSET, offset) - } - } - } - - override fun onViewCreated(view: View, savedInstanceState: Bundle?) { - binding?.ImageView?.setImageResource(getBackground()) + private lateinit var openNoteActivityResultLauncher: ActivityResultLauncher - setupAdapter() - setupRecyclerView() - setupObserver() - setupSearch() + /** Notes as they are currently listed, in order. */ + protected var listedNotes: List = emptyList() + private set - setupActivityResultLaunchers() + private val searchText = mutableStateOf("") - savedInstanceState?.let { bundle -> - val scrollPosition = bundle.getInt(EXTRA_SCROLL_POS, -1) - val scrollOffset = bundle.getInt(EXTRA_SCROLL_OFFSET, 0) - if (scrollPosition > -1) { - binding?.MainListView?.post { - val layoutManager = binding?.MainListView?.layoutManager as? LinearLayoutManager - layoutManager?.scrollToPositionWithOffset(scrollPosition, scrollOffset) - } - } - } - } - - private fun setupActivityResultLaunchers() { + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) openNoteActivityResultLauncher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result -> if (result.resultCode == RESULT_OK) { @@ -111,7 +103,7 @@ abstract class NotallyFragment : Fragment(), ItemListener { val folderFrom = Folder.valueOf(data.getStringExtra(EXTRA_FOLDER_FROM)!!) val folderTo = Folder.valueOf(data.getStringExtra(EXTRA_FOLDER_TO)!!) Snackbar.make( - binding!!.root, + requireView(), requireContext().getQuantityString(folderTo.movedToResId(), 1), Snackbar.LENGTH_SHORT, ) @@ -130,216 +122,209 @@ abstract class NotallyFragment : Fragment(), ItemListener { inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?, - ): View? { + ): View { setHasOptionsMenu(true) - binding = FragmentNotesBinding.inflate(inflater) - return binding?.root - } - - // See [RecyclerView.ViewHolder.getAdapterPosition] - override fun onClick(position: Int) { - if (position != -1) { - notesAdapter?.getItem(position)?.let { item -> - if (item is BaseNote) { - if (model.actionMode.isEnabled()) { - handleNoteSelection(item.id, position, item) - } else { - when (item.type) { - Type.NOTE -> goToActivity(EditNoteActivity::class.java, item) - Type.LIST -> goToActivity(EditListActivity::class.java, item) - } - } - } - } + return ComposeView(requireContext()).apply { + // A stable id lets Compose keep scroll positions and filters in the saved state + id = R.id.NotesOverview + setViewCompositionStrategy(ViewCompositionStrategy.DisposeOnViewTreeLifecycleDestroyed) + setContent { NotallyTheme { Overview() } } } } - override fun onReminderClick(position: Int) { - if (model.actionMode.isEnabled()) { - onClick(position) - return - } - if (position != -1) { - notesAdapter?.getItem(position)?.let { item -> - if (item is BaseNote) { - val intent = - Intent(requireContext(), RemindersActivity::class.java).apply { - putExtra(RemindersActivity.NOTE_ID, item.id) - } - startActivity(intent) - } - } - } + override fun onViewCreated(view: View, savedInstanceState: Bundle?) { + super.onViewCreated(view, savedInstanceState) + (activity as? MainActivity)?.getCurrentFragmentNotes = { listedNotes } } - override fun onLongClick(position: Int) { - if (position != -1) { - if (model.actionMode.selectedNotes.isNotEmpty()) { - if (lastSelectedNotePosition > position) { - position..lastSelectedNotePosition - } else { - lastSelectedNotePosition..position - } - .forEach { pos -> - notesAdapter!!.getItem(pos)?.let { item -> - if (item is BaseNote) { - if (!model.actionMode.selectedNotes.contains(item.id)) { - handleNoteSelection(item.id, pos, item) - } - } - } - } - } else { - notesAdapter?.getItem(position)?.let { item -> - if (item is BaseNote) { - handleNoteSelection(item.id, position, item) + @Composable + private fun Overview() { + val observable = remember { getObservable() } + val items by observable.observeAsState() + val sort by model.preferences.notesSorting.getData().observeAsState() + val selection by model.actionMode.selection.observeAsState(emptyList()) + val notesSort = sort ?: model.preferences.notesSorting.value + val settings = + remember(notesSort) { CardSettings.from(model.preferences, model.imageRoot) } + val grid = remember { model.preferences.notesView.value == NotesView.GRID } + val listState = rememberNotesListState() + val scope = rememberCoroutineScope() + val labels = + SectionLabels( + stringResource(R.string.pinned), + stringResource(R.string.others), + stringResource(R.string.archived), + ) + Column(modifier = Modifier.fillMaxSize()) { + if (isSearch() || model.preferences.alwaysShowSearchBar.value) { + SearchField(searchText) { + scope.launch { + if (grid) listState.grid.scrollToItem(0) else listState.list.scrollToItem(0) } } } - } - } - - private fun setupSearch() { - binding?.EnterSearchKeyword?.apply { - setText(model.keyword) - val navController = findNavController() - navController.addOnDestinationChangedListener { controller, destination, arguments -> - if (destination.id == R.id.Search) { - // Always show search bar in Search fragment - binding?.EnterSearchKeywordLayout?.visibility = View.VISIBLE - requestFocus() - activity?.showKeyboard(this) - notesAdapter?.setSearchKeyword(model.keyword) - } else { - // In other fragments, respect the preference - val alwaysShowSearchBar = model.preferences.alwaysShowSearchBar.value - binding?.EnterSearchKeywordLayout?.visibility = - if (alwaysShowSearchBar) View.VISIBLE else View.GONE - setText("") - clearFocus() - activity?.hideKeyboard(this) - notesAdapter?.setSearchKeyword("") - } - } - doAfterTextChanged { text -> - val isSearchFragment = navController.currentDestination?.id == R.id.Search - if (isSearchFragment) { - val newKeyword = text?.toString().orEmpty() - if (model.keyword != newKeyword) { - model.keyword = newKeyword - } - } - if (text?.isNotEmpty() == true && !isSearchFragment) { - setText("") - model.keyword = text.toString() - navController.navigate( - R.id.Search, - Bundle().apply { - putSerializable(EXTRA_INITIAL_FOLDER, model.folder.value) - putSerializable(EXTRA_INITIAL_LABEL, model.currentLabel) - }, + Filters() + Box(modifier = Modifier.fillMaxWidth().weight(1f)) { + val loaded = items + if (loaded != null) { + val arranged = arrange(loaded, notesSort, labels) + val notes = arranged.filterIsInstance() + SideEffect { listedNotes = notes } + LaunchedEffect(notes) { onListed(notes) } + NotesList( + items = arranged, + settings = settings, + grid = grid, + state = listState, + selectedIds = selection.mapTo(HashSet()) { it.id }, + keyword = if (isSearch()) searchText.value else "", + emptyIcon = if (emptyStateVisible()) getBackground() else null, + onClick = ::onNoteClick, + onLongClick = ::onNoteLongClick, + onReminderClick = ::onReminderClick, ) } - this@NotallyFragment.binding?.MainListView?.apply { - postOnAnimationDelayed({ scrollToPosition(0) }, 10) - } + Loading() } } } - private fun handleNoteSelection(id: Long, position: Int, baseNote: BaseNote) { - if (model.actionMode.selectedNotes.contains(id)) { - model.actionMode.remove(id) - } else { - model.actionMode.add(id, baseNote) - lastSelectedNotePosition = position - } - notesAdapter?.notifyItemChanged(position, 0) - } - - private fun setupAdapter() { - notesAdapter = - with(model.preferences) { - BaseNoteAdapter( - model.actionMode.selectedIds, - dateFormatOverview.value, - timeFormatOverview.value, - notesAdapterSortCallback(), - BaseNoteVHPreferences( - textSizeOverview.value, - maxItems.value, - maxLines.value, - maxTitle.value, - labelTagsHiddenInOverview.value, - imagesHiddenInOverview.value, - notesSorting.value.sortedBy, - ), - model.imageRoot, - this@NotallyFragment, - ) + @OptIn(ExperimentalComposeUiApi::class) + @Composable + private fun SearchField(text: MutableState, onKeywordChanged: () -> Unit) { + val inSearch = isSearch() + val focusRequester = remember { FocusRequester() } + val keyboard = LocalSoftwareKeyboardController.current + val focusManager = LocalFocusManager.current + LaunchedEffect(inSearch) { + text.value = if (inSearch) model.keyword else "" + if (inSearch) { + focusRequester.requestFocus() + keyboard?.show() + } else { + focusManager.clearFocus() + keyboard?.hide() } - - notesAdapter?.registerAdapterDataObserver( - object : RecyclerView.AdapterDataObserver() { - override fun onItemRangeInserted(positionStart: Int, itemCount: Int) { - if (itemCount > 0) { - binding?.MainListView?.scrollToPosition(positionStart) + } + val colors = MaterialTheme.colorScheme + TextField( + value = text.value, + onValueChange = { newText -> + if (inSearch) { + text.value = newText + if (model.keyword != newText) { + model.keyword = newText } + onKeywordChanged() + } else if (newText.isNotEmpty()) { + model.keyword = newText + findNavController() + .navigate( + R.id.Search, + Bundle().apply { + putSerializable(EXTRA_INITIAL_FOLDER, model.folder.value) + putSerializable(EXTRA_INITIAL_LABEL, model.currentLabel) + }, + ) } - } + }, + placeholder = { Text(stringResource(R.string.search)) }, + singleLine = true, + textStyle = MaterialTheme.typography.bodyLarge, + shape = RoundedCornerShape(50), + colors = + TextFieldDefaults.colors( + focusedContainerColor = colors.secondaryContainer, + unfocusedContainerColor = colors.secondaryContainer, + focusedIndicatorColor = Color.Transparent, + unfocusedIndicatorColor = Color.Transparent, + cursorColor = colors.onSurface, + ), + modifier = + Modifier.fillMaxWidth() + .padding(horizontal = 8.dp, vertical = 4.dp) + .focusRequester(focusRequester), ) - binding?.MainListView?.apply { - adapter = notesAdapter - setHasFixedSize(false) - } - model.actionMode.addListener = { notesAdapter?.notifyDataSetChanged() } - if (activity is MainActivity) { - (activity as MainActivity).getCurrentFragmentNotes = { - notesAdapter?.currentList?.filterIsInstance() - } - } } - protected open fun notesAdapterSortCallback(): - (BaseNoteAdapter) -> SortedListAdapterCallback = { adapter -> - model.preferences.notesSorting.value.createCallback(adapter) + /** Notes of this destination with their section headers, in display order. */ + protected open fun arrange( + items: List, + sort: NotesSort, + labels: SectionLabels, + ): List = sectioned(items.filterIsInstance(), sort.comparator, labels) + + /** Filter chips shown above the notes. */ + @Composable protected open fun Filters() {} + + /** Shown on top of the notes, e.g. while searching. */ + @Composable protected open fun Loading() {} + + @Composable protected open fun emptyStateVisible(): Boolean = true + + protected open fun onListed(notes: List) { + model.restoreSelection(notes) } - private fun setupObserver() { - getObservable().observe(viewLifecycleOwner) { list -> - notesAdapter?.submitList(list) - binding?.ImageView?.isVisible = list.isEmpty() - } + private fun isSearch() = this is SearchFragment - model.preferences.notesSorting.observe(viewLifecycleOwner) { notesSort -> - notesAdapter?.setNotesSort(notesSort) + private fun onNoteClick(baseNote: BaseNote) { + if (model.actionMode.isEnabled()) { + toggleSelection(baseNote) + } else { + when (baseNote.type) { + Type.NOTE -> goToActivity(EditNoteActivity::class.java, baseNote) + Type.LIST -> goToActivity(EditListActivity::class.java, baseNote) + } } + } - model.actionMode.closeListener.observe(viewLifecycleOwner) { event -> - event.handle { ids -> - notesAdapter?.currentList?.forEachIndexed { index, item -> - if (item is BaseNote && ids.contains(item.id)) { - notesAdapter?.notifyItemChanged(index, 0) - } - } + private fun onReminderClick(baseNote: BaseNote) { + if (model.actionMode.isEnabled()) { + toggleSelection(baseNote) + return + } + val intent = + Intent(requireContext(), RemindersActivity::class.java).apply { + putExtra(RemindersActivity.NOTE_ID, baseNote.id) } + startActivity(intent) + } + + /** + * Starts the selection, or while notes are selected selects every listed note between the last + * selected one and [baseNote]. + */ + private fun onNoteLongClick(baseNote: BaseNote) { + val actionMode = model.actionMode + if (actionMode.selectedNotes.isEmpty()) { + actionMode.add(baseNote.id, baseNote) + return } + val index = listedNotes.indexOfFirst { it.id == baseNote.id } + val anchorIndex = listedNotes.indexOfFirst { it.id == actionMode.anchorId } + val range = + if (index == -1 || anchorIndex == -1) listOf(baseNote) + else listedNotes.subList(minOf(index, anchorIndex), maxOf(index, anchorIndex) + 1) + range + .filterNot { actionMode.selectedIds.contains(it.id) } + .forEach { actionMode.add(it.id, it) } } - private fun setupRecyclerView() { - binding?.MainListView?.layoutManager = - if (model.preferences.notesView.value == NotesView.GRID) { - StaggeredGridLayoutManager(2, RecyclerView.VERTICAL) - } else LinearLayoutManager(requireContext()) + private fun toggleSelection(baseNote: BaseNote) { + if (model.actionMode.selectedIds.contains(baseNote.id)) { + model.actionMode.remove(baseNote.id) + } else { + model.actionMode.add(baseNote.id, baseNote) + } } private fun goToActivity(activity: Class<*>, baseNote: BaseNote) { val intent = Intent(requireContext(), activity) intent.putExtra(EXTRA_SELECTED_BASE_NOTE, baseNote.id) - // If launched from Search fragment with a non-empty keyword, pass it to the editor to + // If launched from Search with a non-empty keyword, pass it to the editor to // auto-highlight - val isInSearch = view?.findNavController()?.currentDestination?.id == R.id.Search - if (isInSearch && model.keyword.isNotBlank()) { + if (isSearch() && model.keyword.isNotBlank()) { intent.putExtra(EditActivity.EXTRA_INITIAL_SEARCH_QUERY, model.keyword) } openNoteActivityResultLauncher.launch(intent) @@ -352,9 +337,4 @@ abstract class NotallyFragment : Fragment(), ItemListener { open fun prepareNewNoteIntent(intent: Intent): Intent { return intent } - - companion object { - private const val EXTRA_SCROLL_POS = "notallyx.intent.extra.SCROLL_POS" - private const val EXTRA_SCROLL_OFFSET = "notallyx.intent.extra.SCROLL_OFFSET" - } } diff --git a/app/src/main/java/com/philkes/notallyx/presentation/activity/main/fragment/RemindersFragment.kt b/app/src/main/java/com/philkes/notallyx/presentation/activity/main/fragment/RemindersFragment.kt index 6f6d103..5e7cbbc 100644 --- a/app/src/main/java/com/philkes/notallyx/presentation/activity/main/fragment/RemindersFragment.kt +++ b/app/src/main/java/com/philkes/notallyx/presentation/activity/main/fragment/RemindersFragment.kt @@ -1,79 +1,64 @@ package com.philkes.notallyx.presentation.activity.main.fragment import android.os.Bundle -import android.view.View +import androidx.compose.runtime.Composable +import androidx.compose.runtime.mutableStateOf +import androidx.compose.ui.res.stringResource +import androidx.core.os.BundleCompat import androidx.lifecycle.LiveData -import androidx.lifecycle.MutableLiveData -import androidx.recyclerview.widget.SortedListAdapterCallback import com.philkes.notallyx.R import com.philkes.notallyx.data.model.BaseNote import com.philkes.notallyx.data.model.Item -import com.philkes.notallyx.data.model.hasAnyUpcomingNotifications -import com.philkes.notallyx.presentation.view.main.BaseNoteAdapter -import com.philkes.notallyx.presentation.view.main.sorting.BaseNoteLastNotificationSort -import com.philkes.notallyx.presentation.view.main.sorting.BaseNoteMostRecentNotificationSort -import com.philkes.notallyx.presentation.view.main.sorting.BaseNoteNextNotificationSort -import com.philkes.notallyx.presentation.viewmodel.preference.SortDirection +import com.philkes.notallyx.presentation.view.main.FilterChips +import com.philkes.notallyx.presentation.view.main.ReminderFilter +import com.philkes.notallyx.presentation.view.main.SectionLabels +import com.philkes.notallyx.presentation.viewmodel.preference.NotesSort class RemindersFragment : NotallyFragment() { - private val currentReminderNotes = MutableLiveData>() - private val allReminderNotes: LiveData> by lazy { model.reminderNotes!! } - private var filterMode = FilterOptions.UPCOMING - override fun onViewCreated(view: View, savedInstanceState: Bundle?) { - super.onViewCreated(view, savedInstanceState) - currentReminderNotes.value = allReminderNotes.value - binding?.ReminderFilter?.visibility = View.VISIBLE - allReminderNotes.observe(viewLifecycleOwner) { _ -> applyFilter(filterMode) } - binding?.ReminderFilter?.setOnCheckedStateChangeListener { _, checkedIds -> - if (checkedIds.isEmpty()) { - binding?.ReminderFilter?.check(R.id.upcoming) - return@setOnCheckedStateChangeListener - } - filterMode = - when (checkedIds.first()) { - R.id.elapsed -> FilterOptions.ELAPSED - R.id.upcoming -> FilterOptions.UPCOMING - else -> FilterOptions.ALL - } - applyFilter(filterMode) - } - } + private val filter = mutableStateOf(ReminderFilter.UPCOMING) - override fun getBackground(): Int = R.drawable.notifications + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + savedInstanceState + ?.let { BundleCompat.getSerializable(it, EXTRA_FILTER, ReminderFilter::class.java) } + ?.let { filter.value = it } + } - override fun getObservable(): LiveData> = currentReminderNotes + override fun onSaveInstanceState(outState: Bundle) { + super.onSaveInstanceState(outState) + outState.putSerializable(EXTRA_FILTER, filter.value) + } - override fun notesAdapterSortCallback(): (BaseNoteAdapter) -> SortedListAdapterCallback = - { adapter -> - when (filterMode) { - FilterOptions.UPCOMING -> BaseNoteNextNotificationSort(adapter, SortDirection.ASC) - FilterOptions.ELAPSED -> BaseNoteLastNotificationSort(adapter, SortDirection.DESC) - FilterOptions.ALL -> BaseNoteMostRecentNotificationSort(adapter, SortDirection.DESC) - } - } + @Composable + override fun Filters() { + FilterChips( + options = + listOf( + ReminderFilter.UPCOMING to stringResource(R.string.upcoming), + ReminderFilter.ELAPSED to stringResource(R.string.elapsed), + ReminderFilter.ALL to stringResource(R.string.all), + ), + selected = filter.value, + onSelect = { filter.value = it }, + horizontalPadding = 4, + ) + } - fun applyFilter(filterOptions: FilterOptions) { - val items: List = allReminderNotes.value ?: return - val filteredList: List = - when (filterOptions) { - FilterOptions.ALL -> { - items - } - FilterOptions.UPCOMING -> { - items.filter { it is BaseNote && it.reminders.hasAnyUpcomingNotifications() } - } - FilterOptions.ELAPSED -> { - items.filter { it is BaseNote && !it.reminders.hasAnyUpcomingNotifications() } - } - } - currentReminderNotes.value = filteredList - notesAdapter?.setNotesSortCallback(notesAdapterSortCallback()) + /** Only the notes matching the filter, in the filter's own order and without headers. */ + override fun arrange(items: List, sort: NotesSort, labels: SectionLabels): List { + val current = filter.value + return items + .filterIsInstance() + .filter { current.matches(it) } + .sortedWith(current.comparator) } -} -enum class FilterOptions { - UPCOMING, - ELAPSED, - ALL, + override fun getBackground(): Int = R.drawable.notifications + + override fun getObservable(): LiveData> = model.reminderNotes!! + + companion object { + private const val EXTRA_FILTER = "notallyx.intent.extra.REMINDER_FILTER" + } } diff --git a/app/src/main/java/com/philkes/notallyx/presentation/activity/main/fragment/SearchFragment.kt b/app/src/main/java/com/philkes/notallyx/presentation/activity/main/fragment/SearchFragment.kt index db5c7f7..7b4057e 100644 --- a/app/src/main/java/com/philkes/notallyx/presentation/activity/main/fragment/SearchFragment.kt +++ b/app/src/main/java/com/philkes/notallyx/presentation/activity/main/fragment/SearchFragment.kt @@ -1,61 +1,94 @@ package com.philkes.notallyx.presentation.activity.main.fragment -import android.os.Build import android.os.Bundle import android.view.View +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.wrapContentSize +import androidx.compose.material3.CircularProgressIndicator +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.livedata.observeAsState +import androidx.compose.runtime.mutableStateOf +import androidx.compose.ui.Modifier +import androidx.compose.ui.res.stringResource import androidx.core.os.BundleCompat -import androidx.core.view.isVisible import com.philkes.notallyx.R import com.philkes.notallyx.data.model.BaseNote import com.philkes.notallyx.data.model.Folder -import com.philkes.notallyx.data.model.isEmpty +import com.philkes.notallyx.presentation.view.main.FilterChips class SearchFragment : NotallyFragment() { + /** Folder searched in, chosen with the folder chips. */ + private val folder = mutableStateOf(Folder.NOTES) + private val showFolderChips = mutableStateOf(false) + override fun onViewCreated(view: View, savedInstanceState: Bundle?) { - // TODO: autofocus and show keyboard + val arguments = arguments val initialFolder = arguments?.let { BundleCompat.getSerializable(it, EXTRA_INITIAL_FOLDER, Folder::class.java) } - binding?.ChipGroup?.visibility = View.VISIBLE - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { - binding?.MainListView?.scrollIndicators = View.SCROLL_INDICATOR_TOP - } - super.onViewCreated(view, savedInstanceState) - val initialLabel = arguments?.getString(EXTRA_INITIAL_LABEL) + super.onViewCreated(view, savedInstanceState) model.currentLabel = initialLabel - if (initialLabel?.isEmpty() == true) { - val checked = - when (initialFolder ?: model.folder.value) { - Folder.NOTES -> R.id.Notes - Folder.DELETED -> R.id.Deleted - Folder.ARCHIVED -> R.id.Archived - } + // Folder chips only when searching all notes, not inside a label or Unlabeled + showFolderChips.value = initialLabel?.isEmpty() == true + if (showFolderChips.value) { + folder.value = + savedInstanceState?.let { + BundleCompat.getSerializable(it, EXTRA_SEARCH_FOLDER, Folder::class.java) + } ?: initialFolder ?: model.folder.value + model.folder.value = folder.value + } + model.refreshSearch() + } - binding?.ChipGroup?.apply { - setOnCheckedStateChangeListener { _, checkedId -> - when (checkedId.first()) { - R.id.Notes -> model.folder.value = Folder.NOTES - R.id.Deleted -> model.folder.value = Folder.DELETED - R.id.Archived -> model.folder.value = Folder.ARCHIVED - } - } - check(checked) - isVisible = true - } - } else binding?.ChipGroup?.isVisible = false - getObservable().observe(viewLifecycleOwner) { items -> - model.actionMode.updateSelected(items?.filterIsInstance()?.map { it.id }) - notesAdapter?.setSearchKeyword(model.keyword) + override fun onSaveInstanceState(outState: Bundle) { + super.onSaveInstanceState(outState) + outState.putSerializable(EXTRA_SEARCH_FOLDER, folder.value) + } + + @Composable + override fun Filters() { + if (!showFolderChips.value) { + return } - model.searchResults?.isLoading?.observe(viewLifecycleOwner) { isLoading -> - binding?.ImageView?.isVisible = !isLoading && model.searchResults.isEmpty - binding?.LoadingProgress?.isVisible = isLoading + FilterChips( + options = + listOf( + Folder.NOTES to stringResource(R.string.notes), + Folder.DELETED to stringResource(R.string.deleted), + Folder.ARCHIVED to stringResource(R.string.archived), + ), + selected = folder.value, + onSelect = { + folder.value = it + model.folder.value = it + }, + ) + } + + @Composable + override fun Loading() { + val loading by model.searchResults!!.isLoading.observeAsState(false) + if (loading) { + Box(modifier = Modifier.fillMaxSize().wrapContentSize()) { CircularProgressIndicator() } } } + @Composable + override fun emptyStateVisible(): Boolean { + val loading by model.searchResults!!.isLoading.observeAsState(false) + return !loading + } + + override fun onListed(notes: List) { + super.onListed(notes) + model.actionMode.updateSelected(notes.map { it.id }) + } + override fun getBackground() = R.drawable.search override fun getObservable() = model.searchResults!!.results @@ -63,5 +96,6 @@ class SearchFragment : NotallyFragment() { companion object { const val EXTRA_INITIAL_FOLDER = "notallyx.intent.extra.INITIAL_FOLDER" const val EXTRA_INITIAL_LABEL = "notallyx.intent.extra.INITIAL_LABEL" + private const val EXTRA_SEARCH_FOLDER = "notallyx.intent.extra.SEARCH_FOLDER" } } diff --git a/app/src/main/java/com/philkes/notallyx/presentation/activity/note/PickNoteActivity.kt b/app/src/main/java/com/philkes/notallyx/presentation/activity/note/PickNoteActivity.kt index a6250df..58d8d42 100644 --- a/app/src/main/java/com/philkes/notallyx/presentation/activity/note/PickNoteActivity.kt +++ b/app/src/main/java/com/philkes/notallyx/presentation/activity/note/PickNoteActivity.kt @@ -3,38 +3,38 @@ package com.philkes.notallyx.presentation.activity.note import android.content.Intent import android.os.Bundle import android.view.ViewGroup +import androidx.compose.runtime.mutableStateOf +import androidx.compose.ui.platform.ViewCompositionStrategy import androidx.core.view.ViewCompat import androidx.core.view.WindowCompat import androidx.core.view.WindowInsetsCompat import androidx.lifecycle.lifecycleScope -import androidx.recyclerview.widget.LinearLayoutManager -import androidx.recyclerview.widget.RecyclerView -import androidx.recyclerview.widget.StaggeredGridLayoutManager import com.philkes.notallyx.R import com.philkes.notallyx.data.NotallyDatabase import com.philkes.notallyx.data.model.BaseNote -import com.philkes.notallyx.data.model.Header +import com.philkes.notallyx.data.model.Item import com.philkes.notallyx.databinding.ActivityPickNoteBinding import com.philkes.notallyx.presentation.activity.LockedActivity -import com.philkes.notallyx.presentation.view.main.BaseNoteAdapter -import com.philkes.notallyx.presentation.view.main.BaseNoteVHPreferences -import com.philkes.notallyx.presentation.view.main.createCallback -import com.philkes.notallyx.presentation.view.misc.ItemListener -import com.philkes.notallyx.presentation.viewmodel.BaseNoteModel +import com.philkes.notallyx.presentation.view.main.CardSettings +import com.philkes.notallyx.presentation.view.main.NotallyTheme +import com.philkes.notallyx.presentation.view.main.NotesList +import com.philkes.notallyx.presentation.view.main.SectionLabels +import com.philkes.notallyx.presentation.view.main.comparator +import com.philkes.notallyx.presentation.view.main.rememberNotesListState +import com.philkes.notallyx.presentation.view.main.sectioned import com.philkes.notallyx.presentation.viewmodel.preference.NotallyXPreferences import com.philkes.notallyx.presentation.viewmodel.preference.NotesView import com.philkes.notallyx.utils.getCurrentImagesDirectory -import java.util.Collections import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import kotlinx.coroutines.withContext -open class PickNoteActivity : LockedActivity(), ItemListener { - - protected lateinit var adapter: BaseNoteAdapter +open class PickNoteActivity : LockedActivity() { private val excludedNoteId by lazy { intent.getLongExtra(EXTRA_EXCLUDE_NOTE_ID, -1L) } + private val notes = mutableStateOf?>(null) + override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityPickNoteBinding.inflate(layoutInflater) @@ -45,54 +45,43 @@ open class PickNoteActivity : LockedActivity(), ItemLis setResult(RESULT_CANCELED, result) val preferences = NotallyXPreferences.getInstance(application) - - adapter = - with(preferences) { - BaseNoteAdapter( - Collections.emptySet(), - dateFormatOverview.value, - timeFormatOverview.value, - { adapter -> notesSorting.value.createCallback(adapter) }, - BaseNoteVHPreferences( - textSizeOverview.value, - maxItems.value, - maxLines.value, - maxTitle.value, - labelTagsHiddenInOverview.value, - imagesHiddenInOverview.value, - notesSorting.value.sortedBy, - ), - application.getCurrentImagesDirectory(), - this@PickNoteActivity, - ) - } - + val settings = CardSettings.from(preferences, application.getCurrentImagesDirectory()) + val grid = preferences.notesView.value == NotesView.GRID + val emptyText = getString(R.string.empty_list) binding.MainListView.apply { - adapter = this@PickNoteActivity.adapter - setHasFixedSize(true) - layoutManager = - if (preferences.notesView.value == NotesView.GRID) { - StaggeredGridLayoutManager(2, RecyclerView.VERTICAL) - } else LinearLayoutManager(this@PickNoteActivity) + setViewCompositionStrategy(ViewCompositionStrategy.DisposeOnViewTreeLifecycleDestroyed) + setContent { + NotallyTheme { + val items = notes.value + if (items != null) { + NotesList( + items = items, + settings = settings, + grid = grid, + state = rememberNotesListState(), + emptyText = emptyText, + onClick = ::onNotePicked, + ) + } + } + } } - val pinned = Header(getString(R.string.pinned)) - val others = Header(getString(R.string.others)) - val archived = Header(getString(R.string.archived)) - + val labels = + SectionLabels( + getString(R.string.pinned), + getString(R.string.others), + getString(R.string.archived), + ) NotallyDatabase.getDatabase(this.application).observe(this) { database -> lifecycleScope.launch { - val notes = + val raw = database?.let { db -> withContext(Dispatchers.IO) { - val raw = - db.getBaseNoteDao().getAllNotes().filter { it.id != excludedNoteId } - BaseNoteModel.transform(raw, pinned, others, archived) + db.getBaseNoteDao().getAllNotes().filter { it.id != excludedNoteId } } } ?: return@launch - adapter.submitList(notes) - binding.EmptyView.visibility = - if (notes.isEmpty()) android.view.View.VISIBLE else android.view.View.GONE + notes.value = sectioned(raw, preferences.notesSorting.value.comparator, labels) } } } @@ -101,9 +90,8 @@ open class PickNoteActivity : LockedActivity(), ItemLis // 1. Enable edge-to-edge display for the activity window. WindowCompat.setDecorFitsSystemWindows(window, false) - // 3. Apply window insets to specific views to prevent content from being obscured. - // Set an OnApplyWindowInsetsListener on the root layout. - ViewCompat.setOnApplyWindowInsetsListener(binding.root) { view, insets -> + // Apply window insets to specific views to prevent content from being obscured. + ViewCompat.setOnApplyWindowInsetsListener(binding.root) { _, insets -> val systemBarsInsets = insets.getInsets(WindowInsetsCompat.Type.systemBars()) val imeInsets = insets.getInsets(WindowInsetsCompat.Type.ime()) @@ -113,9 +101,7 @@ open class PickNoteActivity : LockedActivity(), ItemLis requestLayout() } - // Apply padding to the RecyclerView and EmptyView to account for the navigation bar and - // keyboard. - // Preserve existing horizontal padding. + // Keep the notes above the navigation bar and keyboard. binding.MainListView.apply { setPadding( paddingLeft, @@ -124,35 +110,22 @@ open class PickNoteActivity : LockedActivity(), ItemLis systemBarsInsets.bottom + imeInsets.bottom, ) } - binding.EmptyView.apply { - setPadding( - paddingLeft, - paddingTop, - paddingRight, - systemBarsInsets.bottom + imeInsets.bottom, - ) - } insets } } - override fun onClick(position: Int) { - if (position != -1) { - val note = (adapter.getItem(position) as BaseNote) - val success = Intent() - success.putExtra(EXTRA_PICKED_NOTE_ID, note.id) - success.putExtra(EXTRA_PICKED_NOTE_TITLE, note.title) - success.putExtra(EXTRA_PICKED_NOTE_TYPE, note.type.name) - setResult(RESULT_OK, success) - finish() - } + /** Returns the picked note to the caller. */ + protected open fun onNotePicked(note: BaseNote) { + val success = Intent() + success.putExtra(EXTRA_PICKED_NOTE_ID, note.id) + success.putExtra(EXTRA_PICKED_NOTE_TITLE, note.title) + success.putExtra(EXTRA_PICKED_NOTE_TYPE, note.type.name) + setResult(RESULT_OK, success) + finish() } - override fun onLongClick(position: Int) {} - companion object { const val EXTRA_EXCLUDE_NOTE_ID = "notallyx.intent.extra.EXCLUDE_NOTE_ID" - const val EXTRA_PICKED_NOTE_ID = "notallyx.intent.extra.PICKED_NOTE_ID" const val EXTRA_PICKED_NOTE_TITLE = "notallyx.intent.extra.PICKED_NOTE_TITLE" const val EXTRA_PICKED_NOTE_TYPE = "notallyx.intent.extra.PICKED_NOTE_TYPE" diff --git a/app/src/main/java/com/philkes/notallyx/presentation/view/main/BaseNoteAdapter.kt b/app/src/main/java/com/philkes/notallyx/presentation/view/main/BaseNoteAdapter.kt deleted file mode 100644 index ab9aee1..0000000 --- a/app/src/main/java/com/philkes/notallyx/presentation/view/main/BaseNoteAdapter.kt +++ /dev/null @@ -1,175 +0,0 @@ -package com.philkes.notallyx.presentation.view.main - -import android.view.LayoutInflater -import android.view.ViewGroup -import androidx.recyclerview.widget.RecyclerView -import androidx.recyclerview.widget.SortedList -import androidx.recyclerview.widget.SortedListAdapterCallback -import com.philkes.notallyx.data.model.BaseNote -import com.philkes.notallyx.data.model.Header -import com.philkes.notallyx.data.model.Item -import com.philkes.notallyx.databinding.RecyclerBaseNoteBinding -import com.philkes.notallyx.databinding.RecyclerHeaderBinding -import com.philkes.notallyx.presentation.view.main.sorting.BaseNoteColorSort -import com.philkes.notallyx.presentation.view.main.sorting.BaseNoteCreationDateSort -import com.philkes.notallyx.presentation.view.main.sorting.BaseNoteModifiedDateSort -import com.philkes.notallyx.presentation.view.main.sorting.BaseNoteTitleSort -import com.philkes.notallyx.presentation.view.misc.ItemListener -import com.philkes.notallyx.presentation.viewmodel.preference.DateFormat -import com.philkes.notallyx.presentation.viewmodel.preference.NotesSort -import com.philkes.notallyx.presentation.viewmodel.preference.NotesSortBy -import com.philkes.notallyx.presentation.viewmodel.preference.TimeFormat -import java.io.File - -class BaseNoteAdapter( - private val selectedIds: Set, - private val dateFormat: DateFormat, - private val timeFormat: TimeFormat, - private var notesSortCallback: (adapter: BaseNoteAdapter) -> SortedListAdapterCallback, - private val preferences: BaseNoteVHPreferences, - private val imageRoot: File?, - private val listener: ItemListener, -) : RecyclerView.Adapter() { - - private var searchKeyword: String = "" - - private var list = SortedList(Item::class.java, notesSortCallback(this)) - - override fun getItemViewType(position: Int): Int { - return when (list[position]) { - is Header -> 0 - is BaseNote -> 1 - } - } - - override fun getItemCount(): Int { - return list.size() - } - - override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) { - when (val item = list[position]) { - is Header -> (holder as HeaderVH).bind(item) - is BaseNote -> { - (holder as BaseNoteVH).apply { - setSearchKeyword(searchKeyword) - bind(item, imageRoot, selectedIds.contains(item.id), preferences.sortedBy) - } - } - } - } - - fun setSearchKeyword(keyword: String) { - if (searchKeyword != keyword) { - val oldKeyword = searchKeyword - searchKeyword = keyword - for (i in 0 until list.size()) { - val item = list[i] - if (item is BaseNote) { - if (matchesKeyword(item, oldKeyword) || matchesKeyword(item, keyword)) { - notifyItemChanged(i) - } - } - } - } - } - - private fun matchesKeyword(baseNote: BaseNote, keyword: String): Boolean { - if (keyword.isBlank()) { - return false - } - if (baseNote.title.contains(keyword, true)) { - return true - } - if (baseNote.body.contains(keyword, true)) { - return true - } - for (label in baseNote.labels) { - if (label.contains(keyword, true)) { - return true - } - } - for (item in baseNote.items) { - if (item.body.contains(keyword, true)) { - return true - } - } - return false - } - - override fun onBindViewHolder( - holder: RecyclerView.ViewHolder, - position: Int, - payloads: MutableList, - ) { - if (payloads.isEmpty()) { - onBindViewHolder(holder, position) - } else handleCheck(holder, position) - } - - override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder { - val inflater = LayoutInflater.from(parent.context) - return when (viewType) { - 0 -> { - val binding = RecyclerHeaderBinding.inflate(inflater, parent, false) - HeaderVH(binding) - } - else -> { - val binding = RecyclerBaseNoteBinding.inflate(inflater, parent, false) - BaseNoteVH(binding, dateFormat, timeFormat, preferences, listener) - } - } - } - - fun setNotesSort(notesSort: NotesSort) { - setNotesSortCallback { adapter -> notesSort.createCallback(adapter) } - } - - fun setNotesSortCallback( - notesSortCallback: (adapter: BaseNoteAdapter) -> SortedListAdapterCallback - ) { - this.notesSortCallback = notesSortCallback - replaceSortCallback(this.notesSortCallback(this)) - } - - fun getItem(position: Int): Item? { - return list[position] - } - - val currentList: List - get() = list.toList() - - fun submitList(items: List) { - list.replaceAll(items) - } - - private fun replaceSortCallback(sortCallback: SortedListAdapterCallback) { - val mutableList = mutableListOf() - for (i in 0 until list.size()) { - mutableList.add(list[i]) - } - list.clear() - list = SortedList(Item::class.java, sortCallback) - list.addAll(mutableList) - } - - private fun handleCheck(holder: RecyclerView.ViewHolder, position: Int) { - val baseNote = list[position] as BaseNote - (holder as BaseNoteVH).updateCheck(selectedIds.contains(baseNote.id), baseNote.color) - } - - private fun SortedList.toList(): List { - val mutableList = mutableListOf() - for (i in 0 until this.size()) { - mutableList.add(this[i]) - } - return mutableList.toList() - } -} - -fun NotesSort.createCallback(adapter: RecyclerView.Adapter<*>?) = - when (sortedBy) { - NotesSortBy.TITLE -> BaseNoteTitleSort(adapter, sortDirection) - NotesSortBy.MODIFIED_DATE -> BaseNoteModifiedDateSort(adapter, sortDirection) - NotesSortBy.CREATION_DATE -> BaseNoteCreationDateSort(adapter, sortDirection) - NotesSortBy.COLOR -> BaseNoteColorSort(adapter, sortDirection) - } diff --git a/app/src/main/java/com/philkes/notallyx/presentation/view/main/BaseNoteVH.kt b/app/src/main/java/com/philkes/notallyx/presentation/view/main/BaseNoteVH.kt deleted file mode 100644 index bf96aad..0000000 --- a/app/src/main/java/com/philkes/notallyx/presentation/view/main/BaseNoteVH.kt +++ /dev/null @@ -1,422 +0,0 @@ -package com.philkes.notallyx.presentation.view.main - -import android.graphics.drawable.Drawable -import android.view.View.GONE -import android.view.View.VISIBLE -import android.widget.LinearLayout -import android.widget.TextView -import androidx.core.view.children -import androidx.core.view.isVisible -import androidx.core.view.updateLayoutParams -import androidx.core.view.updatePadding -import androidx.recyclerview.widget.RecyclerView -import com.bumptech.glide.Glide -import com.bumptech.glide.load.DataSource -import com.bumptech.glide.load.engine.DiskCacheStrategy -import com.bumptech.glide.load.engine.GlideException -import com.bumptech.glide.load.resource.drawable.DrawableTransitionOptions -import com.bumptech.glide.request.RequestListener -import com.bumptech.glide.request.target.Target -import com.philkes.notallyx.R -import com.philkes.notallyx.data.model.BaseNote -import com.philkes.notallyx.data.model.FileAttachment -import com.philkes.notallyx.data.model.ListItem -import com.philkes.notallyx.data.model.SpanRepresentation -import com.philkes.notallyx.data.model.Type -import com.philkes.notallyx.databinding.RecyclerBaseNoteBinding -import com.philkes.notallyx.presentation.applySpans -import com.philkes.notallyx.presentation.bindLabels -import com.philkes.notallyx.presentation.displayFormattedTimestamp -import com.philkes.notallyx.presentation.dp -import com.philkes.notallyx.presentation.extractColor -import com.philkes.notallyx.presentation.getQuantityString -import com.philkes.notallyx.presentation.setControlsContrastColorForAllViews -import com.philkes.notallyx.presentation.setTextSizeSp -import com.philkes.notallyx.presentation.setupReminderChip -import com.philkes.notallyx.presentation.view.misc.ItemListener -import com.philkes.notallyx.presentation.view.misc.highlightableview.HighlightableTextView -import com.philkes.notallyx.presentation.view.misc.highlightableview.SEARCH_SNIPPET_ITEM_LINES -import com.philkes.notallyx.presentation.view.note.listitem.init -import com.philkes.notallyx.presentation.viewmodel.preference.DateFormat -import com.philkes.notallyx.presentation.viewmodel.preference.NotesSortBy -import com.philkes.notallyx.presentation.viewmodel.preference.TimeFormat -import com.philkes.notallyx.presentation.viewmodel.preference.displayBodySize -import com.philkes.notallyx.presentation.viewmodel.preference.displaySmallerSize -import com.philkes.notallyx.presentation.viewmodel.preference.displayTitleSize -import java.io.File - -data class BaseNoteVHPreferences( - val textSize: Float, - val maxItems: Int, - val maxLines: Int, - val maxTitleLines: Int, - val hideLabels: Boolean, - val hideImages: Boolean, - val sortedBy: NotesSortBy, -) - -class BaseNoteVH( - private val binding: RecyclerBaseNoteBinding, - private val dateFormat: DateFormat, - private val timeFormat: TimeFormat, - private val preferences: BaseNoteVHPreferences, - listener: ItemListener, -) : RecyclerView.ViewHolder(binding.root) { - - private var searchKeyword: String = "" - - fun setSearchKeyword(keyword: String) { - this.searchKeyword = keyword - } - - init { - - binding.apply { - val titleTextSize = preferences.textSize.displayTitleSize - val bodyTextSize = preferences.textSize.displayBodySize - Title.setTextSizeSp(titleTextSize) - Date.setTextSizeSp(bodyTextSize) - Note.setTextSizeSp(bodyTextSize) - - Title.maxLines = preferences.maxTitleLines - Note.maxLines = preferences.maxLines - - root.setOnClickListener { listener.onClick(absoluteAdapterPosition) } - - root.setOnLongClickListener { - listener.onLongClick(absoluteAdapterPosition) - return@setOnLongClickListener true - } - - ReminderChip.setOnClickListener { listener.onReminderClick(absoluteAdapterPosition) } - ReminderChip.setOnLongClickListener { - listener.onLongClick(absoluteAdapterPosition) - return@setOnLongClickListener true - } - } - } - - fun updateCheck(checked: Boolean, color: String) { - if (checked) { - binding.root.strokeWidth = 3.dp - } else { - binding.root.strokeWidth = if (color == BaseNote.COLOR_DEFAULT) 1.dp else 0 - } - binding.root.isChecked = checked - } - - fun bind(baseNote: BaseNote, imageRoot: File?, checked: Boolean, sortBy: NotesSortBy) { - updateCheck(checked, baseNote.color) - - when (baseNote.type) { - Type.NOTE -> bindNote(baseNote, searchKeyword) - Type.LIST -> bindList(baseNote, searchKeyword) - } - val (date, datePrefixResId) = - when (sortBy) { - NotesSortBy.CREATION_DATE -> Pair(baseNote.timestamp, R.string.creation_date) - NotesSortBy.MODIFIED_DATE -> - Pair(baseNote.modifiedTimestamp, R.string.modified_date) - else -> Pair(null, null) - } - binding.Date.apply { - displayFormattedTimestamp(date, dateFormat, timeFormat, datePrefixResId) - setTextSizeSp(preferences.textSize.displaySmallerSize) - } - - setImages(baseNote.images, imageRoot) - setFiles(baseNote.files) - - binding.Title.apply { - isVisible = baseNote.title.isNotEmpty() - updatePadding( - bottom = - if (baseNote.hasNoContents() || shouldOnlyDisplayTitle(baseNote)) 0 else 8.dp - ) - if (searchKeyword.isNotBlank()) { - val snippet = extractSearchSnippet(baseNote.title, searchKeyword) - if (snippet != null) { - showSearchSnippet(snippet) - } else text = baseNote.title - } else text = baseNote.title - - setCompoundDrawablesWithIntrinsicBounds( - if (baseNote.type == Type.LIST && preferences.maxItems < 1) - R.drawable.checkbox_small - else 0, - 0, - 0, - 0, - ) - } - - if (preferences.hideLabels) { - binding.LabelGroup.visibility = GONE - } else { - binding.LabelGroup.bindLabels( - baseNote.labels, - preferences.textSize, - binding.Note.isVisible || binding.Title.isVisible, - ) - } - - if (baseNote.isEmpty()) { - binding.Title.apply { - setText(baseNote.getEmptyMessage()) - isVisible = true - } - } - binding.ReminderChip.setupReminderChip( - baseNote, - dateFormat, - timeFormat, - preferences.textSize.displaySmallerSize, - ) - setColor(baseNote.color) - } - - private fun bindNote(baseNote: BaseNote, keyword: String) { - binding.LinearLayout.visibility = GONE - if (keyword.isBlank()) { - bindNote(baseNote.body, baseNote.spans, baseNote.title.isEmpty()) - return - } - binding.Note.apply { - val snippet = extractSearchSnippet(baseNote.body, keyword) - if (snippet == null) { - bindNote(baseNote.body, baseNote.spans, baseNote.title.isEmpty()) - } else { - showSearchSnippet(snippet) - } - } - } - - private fun bindNote(body: String, spans: List, isTitleEmpty: Boolean) { - binding.Note.apply { - text = body.applySpans(spans) - if (preferences.maxLines < 1) { - isVisible = isTitleEmpty - maxLines = if (isTitleEmpty) 1 else preferences.maxLines - } else { - isVisible = body.isNotEmpty() - } - } - } - - /** Shows a snippet of ListItems around the ListItem that contains keyword */ - private fun LinearLayout.bindListSearch( - initializedItems: List, - keyword: String, - isTitleEmpty: Boolean, - ) { - binding.LinearLayout.visibility = VISIBLE - val keywordItemIdx = - initializedItems.indexOfFirst { it.body.contains(keyword, ignoreCase = true) } - if (keywordItemIdx == -1) { - return bindList(initializedItems, isTitleEmpty, preferences.textSize.displayBodySize) - } - val listItemViews = children.filterIsInstance(HighlightableTextView::class.java).toList() - listItemViews.forEach { it.visibility = GONE } - val startItemIdx = (keywordItemIdx - SEARCH_SNIPPET_ITEM_LINES).coerceAtLeast(0) - val endItemIdx = - (keywordItemIdx + SEARCH_SNIPPET_ITEM_LINES).coerceAtMost(initializedItems.lastIndex) - (startItemIdx..endItemIdx).forEachIndexed { viewIdx, itemIdx -> - listItemViews[viewIdx].apply { - val item = initializedItems[itemIdx] - text = item.body - if (itemIdx == keywordItemIdx) { - highlight(keyword) - } - handleChecked(this, item.checked) - visibility = VISIBLE - updateLayoutParams { - marginStart = if (item.isChild) 20.dp else 0 - } - } - } - bindItemsRemaining(initializedItems.size, endItemIdx - startItemIdx + 1) - } - - private fun bindList(baseNote: BaseNote, keyword: String) { - binding.Note.visibility = GONE - val initializedItems = baseNote.items.init() - if (baseNote.items.isEmpty()) { - binding.LinearLayout.visibility = GONE - return - } - if (keyword.isBlank()) { - bindList( - initializedItems, - baseNote.title.isEmpty(), - preferences.textSize.displayBodySize, - ) - return - } - binding.LinearLayout.bindListSearch(initializedItems, keyword, baseNote.title.isEmpty()) - } - - private fun bindItemsRemaining(totalItems: Int, displayedItems: Int) { - if (displayedItems > 0 && totalItems > displayedItems) { - binding.ItemsRemaining.apply { - visibility = VISIBLE - text = (totalItems - displayedItems).toString() - } - } else binding.ItemsRemaining.visibility = GONE - } - - private fun bindList(initializedItems: List, isTitleEmpty: Boolean, textSize: Float) { - binding.apply { - bindItemsRemaining(initializedItems.size, preferences.maxItems) - if (initializedItems.isEmpty()) { - LinearLayout.visibility = GONE - } else { - LinearLayout.visibility = VISIBLE - val forceShowFirstItem = preferences.maxItems < 1 && isTitleEmpty - val filteredList = - initializedItems.take(if (forceShowFirstItem) 1 else preferences.maxItems) - LinearLayout.children - .filterIsInstance(HighlightableTextView::class.java) - .forEachIndexed { index, view -> - if (index < filteredList.size) { - val item = filteredList[index] - view.apply { - text = item.body - handleChecked(this, item.checked) - visibility = VISIBLE - updateLayoutParams { - marginStart = if (item.isChild) 20.dp else 0 - } - if (index == filteredList.lastIndex) { - updatePadding(bottom = 0) - } - setTextSizeSp(textSize) - } - } else view.visibility = GONE - } - } - } - } - - private fun setColor(color: String) { - binding.root.apply { - val colorInt = context.extractColor(color) - setCardBackgroundColor(colorInt) - setControlsContrastColorForAllViews(colorInt) - } - } - - private fun setImages(images: List, mediaRoot: File?) { - binding.apply { - if (images.isNotEmpty() && !preferences.hideImages) { - ImageLayout.visibility = VISIBLE - val image = images[0] - val file = if (mediaRoot != null) File(mediaRoot, image.localName) else null - if (file?.exists() == true) { - ImageView.visibility = VISIBLE - Message.visibility = GONE - Glide.with(ImageView.context) - .load(file) - .centerCrop() - .transition(DrawableTransitionOptions.withCrossFade()) - .diskCacheStrategy(DiskCacheStrategy.NONE) - .listener( - object : RequestListener { - - override fun onLoadFailed( - e: GlideException?, - model: Any?, - target: Target?, - isFirstResource: Boolean, - ): Boolean { - Message.visibility = VISIBLE - ImageView.visibility = GONE - return false - } - - override fun onResourceReady( - resource: Drawable?, - model: Any?, - target: Target?, - dataSource: DataSource?, - isFirstResource: Boolean, - ): Boolean { - return false - } - } - ) - .into(ImageView) - } else { - Glide.with(ImageView.context).clear(ImageView) - ImageView.visibility = GONE - Message.visibility = VISIBLE - } - if (images.size > 1) { - ImageViewMore.apply { - text = images.size.toString() - visibility = VISIBLE - } - } else { - ImageViewMore.visibility = GONE - } - } else { - ImageLayout.visibility = GONE - Message.visibility = GONE - ImageViewMore.visibility = GONE - ImageView.visibility = GONE - Glide.with(ImageView.context).clear(ImageView) - } - } - } - - private fun setFiles(files: List) { - binding.apply { - if (files.isNotEmpty()) { - FileViewLayout.visibility = VISIBLE - FileView.text = files[0].originalName - if (files.size > 1) { - FileViewMore.apply { - text = getQuantityString(R.plurals.more_files, files.size - 1) - visibility = VISIBLE - } - } else { - FileViewMore.visibility = GONE - } - } else { - FileViewLayout.visibility = GONE - } - } - } - - private fun shouldOnlyDisplayTitle(baseNote: BaseNote) = - when (baseNote.type) { - Type.NOTE -> preferences.maxLines < 1 - Type.LIST -> preferences.maxItems < 1 - } - - private fun BaseNote.isEmpty() = title.isBlank() && hasNoContents() && images.isEmpty() - - private fun BaseNote.hasNoContents() = body.isEmpty() && items.isEmpty() - - private fun BaseNote.getEmptyMessage() = - when (type) { - Type.NOTE -> R.string.empty_note - Type.LIST -> R.string.empty_list - } - - private fun handleChecked(textView: TextView, checked: Boolean) { - if (checked) { - textView.setCompoundDrawablesRelativeWithIntrinsicBounds( - R.drawable.checkbox_16, - 0, - 0, - 0, - ) - } else - textView.setCompoundDrawablesRelativeWithIntrinsicBounds( - R.drawable.checkbox_outline_16, - 0, - 0, - 0, - ) - } -} diff --git a/app/src/main/java/com/philkes/notallyx/presentation/view/main/FilterChips.kt b/app/src/main/java/com/philkes/notallyx/presentation/view/main/FilterChips.kt new file mode 100644 index 0000000..be6bc1b --- /dev/null +++ b/app/src/main/java/com/philkes/notallyx/presentation/view/main/FilterChips.kt @@ -0,0 +1,43 @@ +package com.philkes.notallyx.presentation.view.main + +import androidx.compose.foundation.background +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.ExperimentalLayoutApi +import androidx.compose.foundation.layout.FlowRow +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.padding +import androidx.compose.material3.ExperimentalMaterial3Api +import androidx.compose.material3.FilterChip +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.ui.Modifier +import androidx.compose.ui.unit.dp + +/** A row of chips of which exactly one is selected. */ +@OptIn(ExperimentalMaterial3Api::class, ExperimentalLayoutApi::class) +@Composable +fun FilterChips( + options: List>, + selected: T, + onSelect: (T) -> Unit, + modifier: Modifier = Modifier, + horizontalPadding: Int = 12, +) { + FlowRow( + horizontalArrangement = Arrangement.spacedBy(8.dp), + modifier = + modifier + .fillMaxWidth() + .background(MaterialTheme.colorScheme.surface) + .padding(horizontal = horizontalPadding.dp), + ) { + options.forEach { (value, title) -> + FilterChip( + selected = value == selected, + onClick = { onSelect(value) }, + label = { Text(title) }, + ) + } + } +} diff --git a/app/src/main/java/com/philkes/notallyx/presentation/view/main/HeaderVH.kt b/app/src/main/java/com/philkes/notallyx/presentation/view/main/HeaderVH.kt deleted file mode 100644 index 7056727..0000000 --- a/app/src/main/java/com/philkes/notallyx/presentation/view/main/HeaderVH.kt +++ /dev/null @@ -1,20 +0,0 @@ -package com.philkes.notallyx.presentation.view.main - -import androidx.recyclerview.widget.RecyclerView -import androidx.recyclerview.widget.StaggeredGridLayoutManager -import com.philkes.notallyx.data.model.Header -import com.philkes.notallyx.databinding.RecyclerHeaderBinding - -class HeaderVH(private val binding: RecyclerHeaderBinding) : RecyclerView.ViewHolder(binding.root) { - - init { - val params = binding.root.layoutParams - if (params is StaggeredGridLayoutManager.LayoutParams) { - params.isFullSpan = true - } - } - - fun bind(header: Header) { - binding.root.text = header.label - } -} diff --git a/app/src/main/java/com/philkes/notallyx/presentation/view/main/NotallyTheme.kt b/app/src/main/java/com/philkes/notallyx/presentation/view/main/NotallyTheme.kt new file mode 100644 index 0000000..8fec6bb --- /dev/null +++ b/app/src/main/java/com/philkes/notallyx/presentation/view/main/NotallyTheme.kt @@ -0,0 +1,60 @@ +package com.philkes.notallyx.presentation.view.main + +import android.content.Context +import androidx.annotation.AttrRes +import androidx.compose.material3.ColorScheme +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.darkColorScheme +import androidx.compose.material3.lightColorScheme +import androidx.compose.runtime.Composable +import androidx.compose.runtime.remember +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.graphics.toArgb +import androidx.compose.ui.platform.LocalContext +import com.google.android.material.R as MaterialR +import com.google.android.material.color.MaterialColors +import com.philkes.notallyx.presentation.isLightColor + +/** + * Material theme for the Compose parts of the app, taken from the current Android theme so that + * light, dark, super dark and dynamic colors stay the same as on the View based screens. + */ +@Composable +fun NotallyTheme(content: @Composable () -> Unit) { + val context = LocalContext.current + val colorScheme = remember(context) { context.themeColorScheme() } + MaterialTheme(colorScheme = colorScheme, content = content) +} + +private fun Context.themeColorScheme(): ColorScheme { + fun color(@AttrRes attr: Int, fallback: Color) = + Color(MaterialColors.getColor(this, attr, fallback.toArgb())) + + val surfaceArgb = MaterialColors.getColor(this, MaterialR.attr.colorSurface, 0xFFFFFFFF.toInt()) + val base = if (surfaceArgb.isLightColor()) lightColorScheme() else darkColorScheme() + return base.copy( + primary = color(MaterialR.attr.colorPrimary, base.primary), + onPrimary = color(MaterialR.attr.colorOnPrimary, base.onPrimary), + primaryContainer = color(MaterialR.attr.colorPrimaryContainer, base.primaryContainer), + onPrimaryContainer = color(MaterialR.attr.colorOnPrimaryContainer, base.onPrimaryContainer), + secondary = color(MaterialR.attr.colorSecondary, base.secondary), + onSecondary = color(MaterialR.attr.colorOnSecondary, base.onSecondary), + secondaryContainer = color(MaterialR.attr.colorSecondaryContainer, base.secondaryContainer), + onSecondaryContainer = + color(MaterialR.attr.colorOnSecondaryContainer, base.onSecondaryContainer), + tertiary = color(MaterialR.attr.colorTertiary, base.tertiary), + onTertiary = color(MaterialR.attr.colorOnTertiary, base.onTertiary), + background = color(android.R.attr.colorBackground, base.background), + surface = Color(surfaceArgb), + onSurface = color(MaterialR.attr.colorOnSurface, base.onSurface), + surfaceVariant = color(MaterialR.attr.colorSurfaceVariant, base.surfaceVariant), + onSurfaceVariant = color(MaterialR.attr.colorOnSurfaceVariant, base.onSurfaceVariant), + outline = color(MaterialR.attr.colorOutline, base.outline), + outlineVariant = color(MaterialR.attr.colorOutlineVariant, base.outlineVariant), + surfaceContainer = color(MaterialR.attr.colorSurfaceContainer, base.surfaceContainer), + surfaceContainerLow = + color(MaterialR.attr.colorSurfaceContainerLow, base.surfaceContainerLow), + surfaceContainerHigh = + color(MaterialR.attr.colorSurfaceContainerHigh, base.surfaceContainerHigh), + ) +} diff --git a/app/src/main/java/com/philkes/notallyx/presentation/view/main/NoteCard.kt b/app/src/main/java/com/philkes/notallyx/presentation/view/main/NoteCard.kt new file mode 100644 index 0000000..f014183 --- /dev/null +++ b/app/src/main/java/com/philkes/notallyx/presentation/view/main/NoteCard.kt @@ -0,0 +1,679 @@ +package com.philkes.notallyx.presentation.view.main + +import android.graphics.BitmapFactory +import androidx.compose.foundation.ExperimentalFoundationApi +import androidx.compose.foundation.Image +import androidx.compose.foundation.background +import androidx.compose.foundation.border +import androidx.compose.foundation.combinedClickable +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.ExperimentalLayoutApi +import androidx.compose.foundation.layout.FlowRow +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.aspectRatio +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.layout.width +import androidx.compose.foundation.layout.widthIn +import androidx.compose.foundation.shape.CircleShape +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.filled.CheckCircle +import androidx.compose.material3.Icon +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.runtime.Immutable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.produceState +import androidx.compose.runtime.remember +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.alpha +import androidx.compose.ui.draw.clip +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.graphics.ImageBitmap +import androidx.compose.ui.graphics.asImageBitmap +import androidx.compose.ui.layout.ContentScale +import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.platform.LocalDensity +import androidx.compose.ui.res.painterResource +import androidx.compose.ui.res.pluralStringResource +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.semantics.selected +import androidx.compose.ui.semantics.semantics +import androidx.compose.ui.text.AnnotatedString +import androidx.compose.ui.text.SpanStyle +import androidx.compose.ui.text.buildAnnotatedString +import androidx.compose.ui.text.font.FontFamily +import androidx.compose.ui.text.font.FontStyle +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.text.style.TextAlign +import androidx.compose.ui.text.style.TextDecoration +import androidx.compose.ui.text.style.TextOverflow +import androidx.compose.ui.unit.dp +import androidx.compose.ui.unit.em +import androidx.compose.ui.unit.sp +import com.philkes.notallyx.R +import com.philkes.notallyx.data.model.BaseNote +import com.philkes.notallyx.data.model.FileAttachment +import com.philkes.notallyx.data.model.ListItem +import com.philkes.notallyx.data.model.SpanRepresentation +import com.philkes.notallyx.data.model.Type +import com.philkes.notallyx.data.model.findNextNotificationDate +import com.philkes.notallyx.data.model.haveAnyRepetition +import com.philkes.notallyx.presentation.format +import com.philkes.notallyx.presentation.view.misc.highlightableview.SEARCH_SNIPPET_ITEM_LINES +import com.philkes.notallyx.presentation.view.misc.highlightableview.displayText +import com.philkes.notallyx.presentation.view.misc.highlightableview.searchSnippet +import com.philkes.notallyx.presentation.view.note.listitem.init +import com.philkes.notallyx.presentation.viewmodel.preference.DateFormat +import com.philkes.notallyx.presentation.viewmodel.preference.NotallyXPreferences +import com.philkes.notallyx.presentation.viewmodel.preference.NotesSortBy +import com.philkes.notallyx.presentation.viewmodel.preference.TimeFormat +import com.philkes.notallyx.presentation.viewmodel.preference.displayBodySize +import com.philkes.notallyx.presentation.viewmodel.preference.displaySmallerSize +import com.philkes.notallyx.presentation.viewmodel.preference.displayTitleSize +import java.io.File +import java.util.Date +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.withContext + +/** The overview settings that decide what a note card shows. */ +@Immutable +data class CardSettings( + val textSize: Float, + val maxItems: Int, + val maxLines: Int, + val maxTitleLines: Int, + val hideLabels: Boolean, + val hideImages: Boolean, + val sortedBy: NotesSortBy, + val dateFormat: DateFormat, + val timeFormat: TimeFormat, + val imageRoot: File?, +) { + companion object { + fun from(preferences: NotallyXPreferences, imageRoot: File?) = + with(preferences) { + CardSettings( + textSize = textSizeOverview.value, + maxItems = maxItems.value, + maxLines = maxLines.value, + maxTitleLines = maxTitle.value, + hideLabels = labelTagsHiddenInOverview.value, + hideImages = imagesHiddenInOverview.value, + sortedBy = notesSorting.value.sortedBy, + dateFormat = dateFormatOverview.value, + timeFormat = timeFormatOverview.value, + imageRoot = imageRoot, + ) + } + } +} + +/** At most this many list items fit on a card. */ +private const val MAX_CARD_ITEMS = 10 + +/** + * A note as shown in the overview, the search results and the note picker. + * + * @param keyword search text to highlight; blank outside of Search. + */ +@OptIn(ExperimentalFoundationApi::class, ExperimentalLayoutApi::class) +@Composable +fun NoteCard( + baseNote: BaseNote, + settings: CardSettings, + modifier: Modifier = Modifier, + selected: Boolean = false, + keyword: String = "", + onClick: () -> Unit = {}, + onLongClick: (() -> Unit)? = null, + onReminderClick: (() -> Unit)? = null, +) { + val colors = MaterialTheme.colorScheme + val isSelected = selected + val background = + if (baseNote.color == BaseNote.COLOR_DEFAULT) colors.surface + else Color(android.graphics.Color.parseColor(baseNote.color)) + val shape = RoundedCornerShape(12.dp) + val strokeWidth = + when { + selected -> 3.dp + baseNote.color == BaseNote.COLOR_DEFAULT -> 1.dp + else -> 0.dp + } + Box( + modifier = + modifier + .padding(start = 4.dp, end = 4.dp, bottom = 8.dp) + .fillMaxWidth() + .clip(shape) + .background(background) + .then( + if (selected) Modifier.background(colors.secondary.copy(alpha = 0.12f)) + else Modifier + ) + .then( + if (strokeWidth > 0.dp) + Modifier.border( + strokeWidth, + if (selected) colors.onSurface else colors.outlineVariant, + shape, + ) + else Modifier + ) + .combinedClickable(onClick = onClick, onLongClick = onLongClick) + .semantics { this.selected = isSelected } + ) { + Column(modifier = Modifier.fillMaxWidth().padding(bottom = 16.dp)) { + if (baseNote.images.isNotEmpty() && !settings.hideImages) { + CardImages(baseNote.images, settings.imageRoot) + } + Spacer(Modifier.height(14.dp)) + CardContent(baseNote, settings, keyword, onReminderClick, onLongClick) + } + if (selected) { + Icon( + Icons.Filled.CheckCircle, + contentDescription = null, + tint = colors.onSurface, + modifier = + Modifier.align(Alignment.TopEnd) + .padding(8.dp) + .size(24.dp) + .background(colors.surface, CircleShape), + ) + } + } +} + +@OptIn(ExperimentalLayoutApi::class) +@Composable +private fun CardContent( + baseNote: BaseNote, + settings: CardSettings, + keyword: String, + onReminderClick: (() -> Unit)?, + onLongClick: (() -> Unit)?, +) { + val colors = MaterialTheme.colorScheme + val searching = keyword.isNotBlank() + val hasNoContents = baseNote.body.isEmpty() && baseNote.items.isEmpty() + val isEmpty = baseNote.title.isBlank() && hasNoContents && baseNote.images.isEmpty() + val onlyTitle = + when (baseNote.type) { + Type.NOTE -> settings.maxLines < 1 + Type.LIST -> settings.maxItems < 1 + } + val highlight = searchHighlightColor() + + // Title + val titleVisible = baseNote.title.isNotEmpty() || isEmpty + if (titleVisible) { + val titleSnippet = if (searching) searchSnippet(baseNote.title, keyword) else null + val titleText = + when { + isEmpty -> + AnnotatedString( + stringResource( + if (baseNote.type == Type.NOTE) R.string.empty_note + else R.string.empty_list + ) + ) + titleSnippet != null -> titleSnippet.highlighted(highlight) + else -> AnnotatedString(baseNote.title) + } + Row( + verticalAlignment = Alignment.CenterVertically, + modifier = + Modifier.fillMaxWidth() + .padding(horizontal = 16.dp) + .padding(bottom = if (hasNoContents || onlyTitle) 0.dp else 8.dp), + ) { + if (baseNote.type == Type.LIST && settings.maxItems < 1) { + Icon( + painterResource(R.drawable.checkbox), + contentDescription = null, + tint = colors.onSurfaceVariant, + modifier = Modifier.size(19.dp), + ) + } + Text( + text = titleText, + color = colors.onSurface, + fontWeight = FontWeight.Medium, + fontSize = settings.textSize.displayTitleSize.sp, + lineHeight = 1.25.em, + maxLines = if (titleSnippet != null) Int.MAX_VALUE else settings.maxTitleLines, + overflow = TextOverflow.Ellipsis, + ) + } + } + + // Date and reminder + val dateText = cardDate(baseNote, settings) + val reminderDate = + baseNote.reminders.findNextNotificationDate() + ?: baseNote.reminders.maxOfOrNull { it.dateTime } + FlowRow( + horizontalArrangement = Arrangement.SpaceBetween, + verticalArrangement = Arrangement.spacedBy(4.dp), + modifier = Modifier.fillMaxWidth().padding(start = 16.dp, end = 16.dp, bottom = 6.dp), + ) { + if (dateText != null) { + Text( + text = dateText, + color = colors.onSurface, + fontSize = settings.textSize.displaySmallerSize.sp, + lineHeight = 1.2.em, + maxLines = 1, + modifier = Modifier.alpha(0.65f).padding(end = 12.dp).align(Alignment.CenterVertically), + ) + } + if (reminderDate != null) { + ReminderChip( + text = reminderDate.format(settings.dateFormat, settings.timeFormat, true), + elapsed = reminderDate < Date(), + repeating = baseNote.reminders.haveAnyRepetition(), + textSize = settings.textSize.displaySmallerSize, + onClick = onReminderClick, + onLongClick = onLongClick, + ) + } + } + + // Files + if (baseNote.files.isNotEmpty()) { + Row( + horizontalArrangement = Arrangement.spacedBy(6.dp), + modifier = Modifier.fillMaxWidth().padding(start = 16.dp, end = 16.dp, bottom = 4.dp), + ) { + FileChip(baseNote.files[0].originalName, R.drawable.text_file, Modifier.weight(1f, false)) + if (baseNote.files.size > 1) { + FileChip( + pluralStringResource( + R.plurals.more_files, + baseNote.files.size - 1, + baseNote.files.size - 1, + ), + null, + ) + } + } + } + + when (baseNote.type) { + Type.NOTE -> NoteBody(baseNote, settings, keyword) + Type.LIST -> ListItems(baseNote, settings, keyword) + } + + if (!settings.hideLabels && baseNote.labels.isNotEmpty()) { + val bodyVisible = + when (baseNote.type) { + Type.NOTE -> noteBodyVisible(baseNote, settings, keyword) + Type.LIST -> false + } + FlowRow( + horizontalArrangement = Arrangement.spacedBy(8.dp), + verticalArrangement = Arrangement.spacedBy(4.dp), + modifier = + Modifier.fillMaxWidth() + .padding(horizontal = 16.dp) + .padding(top = if (bodyVisible || titleVisible) 8.dp else 0.dp), + ) { + baseNote.labels.forEach { label -> LabelChip(label, settings.textSize.displayBodySize) } + } + } +} + +private fun noteBodyVisible(baseNote: BaseNote, settings: CardSettings, keyword: String): Boolean { + if (keyword.isNotBlank() && searchSnippet(baseNote.body, keyword) != null) { + return true + } + return if (settings.maxLines < 1) baseNote.title.isEmpty() else baseNote.body.isNotEmpty() +} + +@Composable +private fun NoteBody(baseNote: BaseNote, settings: CardSettings, keyword: String) { + if (!noteBodyVisible(baseNote, settings, keyword)) { + return + } + val colors = MaterialTheme.colorScheme + val snippet = if (keyword.isNotBlank()) searchSnippet(baseNote.body, keyword) else null + val text = + snippet?.highlighted(searchHighlightColor()) + ?: baseNote.body.withSpans(baseNote.spans, colors.onSurface) + val maxLines = + when { + snippet != null -> Int.MAX_VALUE + settings.maxLines < 1 -> 1 + else -> settings.maxLines + } + Text( + text = text, + color = colors.onSurface, + fontSize = settings.textSize.displayBodySize.sp, + lineHeight = 1.3.em, + maxLines = maxLines, + overflow = TextOverflow.Ellipsis, + modifier = Modifier.fillMaxWidth().padding(horizontal = 16.dp), + ) +} + +@Composable +private fun ListItems(baseNote: BaseNote, settings: CardSettings, keyword: String) { + if (baseNote.items.isEmpty()) { + return + } + val items = remember(baseNote.items) { baseNote.items.init() } + val keywordIndex = + if (keyword.isNotBlank()) items.indexOfFirst { it.body.contains(keyword, true) } else -1 + val shown: List> + val remaining: Int + if (keywordIndex != -1) { + val first = (keywordIndex - SEARCH_SNIPPET_ITEM_LINES).coerceAtLeast(0) + val last = (keywordIndex + SEARCH_SNIPPET_ITEM_LINES).coerceAtMost(items.lastIndex) + shown = (first..last).map { index -> items[index] to (index == keywordIndex) } + remaining = items.size - shown.size + } else { + val forceFirst = settings.maxItems < 1 && baseNote.title.isEmpty() + shown = + items.take(if (forceFirst) 1 else settings.maxItems.coerceAtMost(MAX_CARD_ITEMS)).map { + it to false + } + remaining = if (settings.maxItems > 0 && items.size > settings.maxItems) { + items.size - settings.maxItems + } else 0 + } + if (shown.isEmpty() && remaining == 0) { + return + } + val colors = MaterialTheme.colorScheme + val highlight = searchHighlightColor() + val textSize = settings.textSize.displayBodySize + Column(modifier = Modifier.fillMaxWidth().padding(horizontal = 16.dp)) { + shown.forEachIndexed { index, (item, isMatch) -> + val text = + if (isMatch) { + val start = item.body.indexOf(keyword, ignoreCase = true) + item.body.highlighted(start, start + keyword.length, highlight) + } else AnnotatedString(item.body) + ListItemRow( + text = text, + icon = if (item.checked) R.drawable.checkbox_16 else R.drawable.checkbox_outline_16, + iconTint = if (item.checked) colors.secondary else colors.onSurfaceVariant, + textSize = textSize, + modifier = + Modifier.padding( + start = if (item.isChild) 20.dp else 0.dp, + bottom = if (index == shown.lastIndex && remaining == 0) 0.dp else 4.dp, + ), + ) + } + if (remaining > 0) { + ListItemRow( + text = AnnotatedString(remaining.toString()), + icon = R.drawable.add_16, + iconTint = colors.onSurfaceVariant, + textSize = textSize, + ) + } + } +} + +@Composable +private fun ListItemRow( + text: AnnotatedString, + icon: Int, + iconTint: Color, + textSize: Float, + modifier: Modifier = Modifier, +) { + Row(verticalAlignment = Alignment.CenterVertically, modifier = modifier.fillMaxWidth()) { + Icon( + painterResource(icon), + contentDescription = null, + tint = iconTint, + modifier = Modifier.size(16.dp), + ) + Spacer(Modifier.width(8.dp)) + Text( + text = text, + color = MaterialTheme.colorScheme.onSurface, + fontSize = textSize.sp, + lineHeight = 1.2.em, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + ) + } +} + +@OptIn(ExperimentalFoundationApi::class) +@Composable +private fun ReminderChip( + text: String, + elapsed: Boolean, + repeating: Boolean, + textSize: Float, + onClick: (() -> Unit)?, + onLongClick: (() -> Unit)?, +) { + val colors = MaterialTheme.colorScheme + val iconSize = with(LocalDensity.current) { (textSize + 4).sp.toDp() } + Row( + verticalAlignment = Alignment.CenterVertically, + modifier = + Modifier.alpha(if (elapsed) 0.5f else 1f) + .clip(RoundedCornerShape(50)) + .background(colors.onSurface.copy(alpha = 0.10f)) + .then( + if (onClick != null) + Modifier.combinedClickable(onClick = onClick, onLongClick = onLongClick) + else Modifier + ) + .padding(start = 4.dp, end = 6.dp, top = 4.dp, bottom = 4.dp), + ) { + Icon( + painterResource(R.drawable.notifications), + contentDescription = null, + tint = colors.onSurfaceVariant, + modifier = Modifier.size(iconSize), + ) + Text( + text = text, + color = colors.onSurface.copy(alpha = 0.87f), + fontSize = textSize.sp, + lineHeight = 1.2.em, + textDecoration = if (elapsed) TextDecoration.LineThrough else null, + maxLines = 1, + modifier = Modifier.padding(horizontal = 4.dp), + ) + if (repeating) { + Icon( + painterResource(R.drawable.repetition), + contentDescription = null, + tint = colors.onSurfaceVariant, + modifier = Modifier.size(16.dp), + ) + } + } +} + +@Composable +private fun FileChip(text: String, icon: Int?, modifier: Modifier = Modifier) { + val colors = MaterialTheme.colorScheme + Row( + verticalAlignment = Alignment.CenterVertically, + modifier = + modifier + .height(32.dp) + .border(1.dp, colors.onSurface, RoundedCornerShape(8.dp)) + .padding(start = if (icon != null) 4.dp else 8.dp, end = 8.dp), + ) { + if (icon != null) { + Icon( + painterResource(icon), + contentDescription = null, + tint = colors.onSurface, + modifier = Modifier.size(18.dp), + ) + Spacer(Modifier.width(2.dp)) + } + Text( + text = text, + color = colors.onSurface, + style = MaterialTheme.typography.bodySmall, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + ) + } +} + +@Composable +private fun LabelChip(label: String, textSize: Float) { + val colors = MaterialTheme.colorScheme + Text( + text = label, + color = colors.onSurfaceVariant, + fontSize = textSize.sp, + lineHeight = 1.2.em, + maxLines = 1, + modifier = + Modifier.border(1.dp, colors.onSurface.copy(alpha = 0.2f), RoundedCornerShape(50)) + .padding(horizontal = 12.dp, vertical = 6.dp), + ) +} + +@Composable +private fun CardImages(images: List, imageRoot: File?) { + val file = imageRoot?.let { File(it, images[0].localName) } + val bitmap by + produceState(initialValue = null, file) { + value = withContext(Dispatchers.IO) { file?.takeIf { it.exists() }?.decodeScaled() } + } + val loaded = bitmap + if (file?.exists() == true) { + Box(modifier = Modifier.fillMaxWidth().aspectRatio(4f / 3f)) { + if (loaded != null) { + Image( + bitmap = loaded, + contentDescription = null, + contentScale = ContentScale.Crop, + modifier = Modifier.fillMaxWidth().aspectRatio(4f / 3f), + ) + } + if (images.size > 1) { + Row( + verticalAlignment = Alignment.CenterVertically, + modifier = + Modifier.align(Alignment.TopEnd) + .padding(top = 8.dp, end = 8.dp) + .clip(RoundedCornerShape(8.dp)) + .background(MaterialTheme.colorScheme.surface) + .border(1.dp, MaterialTheme.colorScheme.onSurface, RoundedCornerShape(8.dp)) + .padding(horizontal = 8.dp, vertical = 4.dp), + ) { + Icon( + painterResource(R.drawable.add_images), + contentDescription = null, + tint = MaterialTheme.colorScheme.onSurface, + modifier = Modifier.size(18.dp), + ) + Spacer(Modifier.width(2.dp)) + Text( + images.size.toString(), + color = MaterialTheme.colorScheme.onSurface, + style = MaterialTheme.typography.bodySmall, + ) + } + } + } + } else { + Text( + text = stringResource(R.string.cant_load_image), + color = MaterialTheme.colorScheme.onSurface, + style = MaterialTheme.typography.bodyMedium, + textAlign = TextAlign.Center, + modifier = Modifier.fillMaxWidth().widthIn(min = 0.dp).padding(16.dp), + ) + } +} + +private fun File.decodeScaled(targetWidth: Int = 1080): ImageBitmap? { + val bounds = BitmapFactory.Options().apply { inJustDecodeBounds = true } + BitmapFactory.decodeFile(path, bounds) + var sample = 1 + while (bounds.outWidth / (sample * 2) >= targetWidth) { + sample *= 2 + } + val options = BitmapFactory.Options().apply { inSampleSize = sample } + return BitmapFactory.decodeFile(path, options)?.asImageBitmap() +} + +/** Background of search matches: the highlight color text views use in this theme. */ +@Composable +private fun searchHighlightColor(): Color { + val context = LocalContext.current + return remember(context) { Color(android.widget.TextView(context).highlightColor) } +} + +@Composable +private fun cardDate(baseNote: BaseNote, settings: CardSettings): String? { + val (timestamp, prefix) = + when (settings.sortedBy) { + NotesSortBy.CREATION_DATE -> baseNote.timestamp to R.string.creation_date + NotesSortBy.MODIFIED_DATE -> baseNote.modifiedTimestamp to R.string.modified_date + else -> return null + } + if (settings.dateFormat == DateFormat.NONE && settings.timeFormat == TimeFormat.NONE) { + return null + } + val prefixText = stringResource(prefix) + return "$prefixText ${Date(timestamp).format(settings.dateFormat, settings.timeFormat)}".trim() +} + +private fun com.philkes.notallyx.presentation.view.misc.highlightableview.Snippet.highlighted( + color: Color +): AnnotatedString { + val (text, start) = displayText + return text.highlighted(start, start + keyword.length, color) +} + +private fun String.highlighted(start: Int, end: Int, color: Color): AnnotatedString = + buildAnnotatedString { + append(this@highlighted) + if (start in 0..length && end in start..length) { + addStyle(SpanStyle(background = color), start, end) + } + } + +/** The note's formatting (bold, italic, links, monospace, strikethrough) as text styles. */ +private fun String.withSpans(spans: List, linkColor: Color): AnnotatedString = + buildAnnotatedString { + append(this@withSpans) + spans.forEach { span -> + val start = span.start.coerceIn(0, length) + val end = span.end.coerceIn(start, length) + if (start == end) return@forEach + if (span.bold) addStyle(SpanStyle(fontWeight = FontWeight.Bold), start, end) + if (span.italic) addStyle(SpanStyle(fontStyle = FontStyle.Italic), start, end) + if (span.monospace) addStyle(SpanStyle(fontFamily = FontFamily.Monospace), start, end) + if (span.strikethrough) { + addStyle(SpanStyle(textDecoration = TextDecoration.LineThrough), start, end) + } + if (span.link) { + addStyle( + SpanStyle(color = linkColor, textDecoration = TextDecoration.Underline), + start, + end, + ) + } + } + } diff --git a/app/src/main/java/com/philkes/notallyx/presentation/view/main/NoteOrdering.kt b/app/src/main/java/com/philkes/notallyx/presentation/view/main/NoteOrdering.kt new file mode 100644 index 0000000..db4e6f0 --- /dev/null +++ b/app/src/main/java/com/philkes/notallyx/presentation/view/main/NoteOrdering.kt @@ -0,0 +1,127 @@ +package com.philkes.notallyx.presentation.view.main + +import com.philkes.notallyx.data.model.BaseNote +import com.philkes.notallyx.data.model.Folder +import com.philkes.notallyx.data.model.Header +import com.philkes.notallyx.data.model.Item +import com.philkes.notallyx.data.model.findLastNotificationDate +import com.philkes.notallyx.data.model.findNextNotificationDate +import com.philkes.notallyx.data.model.hasAnyUpcomingNotifications +import com.philkes.notallyx.presentation.viewmodel.preference.NotesSort +import com.philkes.notallyx.presentation.viewmodel.preference.NotesSortBy +import com.philkes.notallyx.presentation.viewmodel.preference.SortDirection + +/** Labels of the section headers shown between groups of notes. */ +data class SectionLabels(val pinned: String, val others: String, val archived: String) + +/** Which reminders the Reminders overview shows, each with its own order. */ +enum class ReminderFilter { + UPCOMING, + ELAPSED, + ALL; + + fun matches(baseNote: BaseNote): Boolean = + when (this) { + ALL -> true + UPCOMING -> baseNote.reminders.hasAnyUpcomingNotifications() + ELAPSED -> !baseNote.reminders.hasAnyUpcomingNotifications() + } + + val comparator: Comparator + get() = + when (this) { + UPCOMING -> directed(SortDirection.ASC) { a, b -> a.compareNextNotification(b) } + ELAPSED -> directed(SortDirection.DESC) { a, b -> a.compareLastNotification(b) } + ALL -> + directed(SortDirection.DESC) { a, b -> + a.compareNextNotification(b).takeIf { it != 0 } + ?: a.compareLastNotification(b) + } + }.pinnedFirst() +} + +/** Order of the overview for the user's sort preference: pinned notes always come first. */ +val NotesSort.comparator: Comparator + get() = + when (sortedBy) { + NotesSortBy.TITLE -> directed(sortDirection) { a, b -> a.title.compareTo(b.title) } + NotesSortBy.CREATION_DATE -> + directed(sortDirection) { a, b -> a.timestamp.compareTo(b.timestamp) } + NotesSortBy.MODIFIED_DATE -> + directed(sortDirection) { a, b -> a.compareModified(b) } + NotesSortBy.COLOR -> + directed(sortDirection) { a, b -> + // Notes of the same color: most recently modified first + a.color.compareTo(b.color).takeIf { it != 0 } ?: -a.compareModified(b) + } + }.pinnedFirst() + +/** + * Sorts [notes] and puts the section headers in front of their groups: "Pinned" and "Others" when + * some (non archived) notes are pinned, "Archived" in front of archived notes that are listed + * together with others (labels, search). + */ +fun sectioned( + notes: Collection, + comparator: Comparator, + labels: SectionLabels, +): List { + val (archived, active) = notes.partition { it.folder == Folder.ARCHIVED } + val (pinned, others) = active.sortedWith(comparator).partition { it.pinned } + val items = ArrayList(notes.size + 3) + if (pinned.isNotEmpty()) { + items.add(Header(labels.pinned)) + items.addAll(pinned) + if (others.isNotEmpty()) { + items.add(Header(labels.others)) + } + } + items.addAll(others) + if (archived.isNotEmpty()) { + items.add(Header(labels.archived)) + items.addAll(archived.sortedWith(comparator)) + } + return items +} + +private fun directed( + direction: SortDirection, + compare: (BaseNote, BaseNote) -> Int, +): Comparator = Comparator { a, b -> + val result = compare(a, b) + if (direction == SortDirection.ASC) result else -result +} + +private fun Comparator.pinnedFirst(): Comparator = + compareByDescending { it.pinned }.then(this) + +private fun BaseNote.compareModified(other: BaseNote) = + modifiedTimestamp.compareTo(other.modifiedTimestamp) + +private fun BaseNote.compareNextNotification(other: BaseNote): Int { + if (reminders.isEmpty() || other.reminders.isEmpty()) { + return reminders.isNotEmpty().compareTo(other.reminders.isNotEmpty()) + } + return compareNullsFirst( + reminders.findNextNotificationDate(), + other.reminders.findNextNotificationDate(), + ) +} + +private fun BaseNote.compareLastNotification(other: BaseNote): Int { + if (reminders.isEmpty() || other.reminders.isEmpty()) { + return reminders.isNotEmpty().compareTo(other.reminders.isNotEmpty()) + } + return compareNullsFirst( + reminders.findLastNotificationDate(), + other.reminders.findLastNotificationDate(), + ) +} + +private fun > compareNullsFirst(a: T?, b: T?): Int = + when { + a == null && b == null -> 0 + a == null -> -1 + b == null -> 1 + else -> a.compareTo(b) + } diff --git a/app/src/main/java/com/philkes/notallyx/presentation/view/main/NotesList.kt b/app/src/main/java/com/philkes/notallyx/presentation/view/main/NotesList.kt new file mode 100644 index 0000000..931ae93 --- /dev/null +++ b/app/src/main/java/com/philkes/notallyx/presentation/view/main/NotesList.kt @@ -0,0 +1,192 @@ +package com.philkes.notallyx.presentation.view.main + +import androidx.compose.foundation.ExperimentalFoundationApi +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.PaddingValues +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.lazy.LazyColumn +import androidx.compose.foundation.lazy.LazyListState +import androidx.compose.foundation.lazy.itemsIndexed +import androidx.compose.foundation.lazy.rememberLazyListState +import androidx.compose.foundation.lazy.staggeredgrid.LazyStaggeredGridState +import androidx.compose.foundation.lazy.staggeredgrid.LazyVerticalStaggeredGrid +import androidx.compose.foundation.lazy.staggeredgrid.StaggeredGridCells +import androidx.compose.foundation.lazy.staggeredgrid.StaggeredGridItemSpan +import androidx.compose.foundation.lazy.staggeredgrid.itemsIndexed +import androidx.compose.foundation.lazy.staggeredgrid.rememberLazyStaggeredGridState +import androidx.compose.material3.Icon +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.remember +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.res.painterResource +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.unit.dp +import androidx.compose.ui.unit.sp +import com.philkes.notallyx.data.model.BaseNote +import com.philkes.notallyx.data.model.Header +import com.philkes.notallyx.data.model.Item + +/** Scroll state of an overview list, kept per destination across recreation and process death. */ +class NotesListState(val list: LazyListState, val grid: LazyStaggeredGridState) + +@Composable +fun rememberNotesListState() = + NotesListState(rememberLazyListState(), rememberLazyStaggeredGridState()) + +/** + * Notes (with their section headers) in a list or a two column staggered grid. Shows [emptyIcon] + * when there is nothing to show. + */ +@OptIn(ExperimentalFoundationApi::class) +@Composable +fun NotesList( + items: List, + settings: CardSettings, + grid: Boolean, + state: NotesListState, + modifier: Modifier = Modifier, + selectedIds: Set = emptySet(), + keyword: String = "", + emptyIcon: Int? = null, + emptyText: String? = null, + onClick: (BaseNote) -> Unit, + onLongClick: ((BaseNote) -> Unit)? = null, + onReminderClick: ((BaseNote) -> Unit)? = null, +) { + ScrollToInsertedNote(items, grid, state) + Box(modifier = modifier.fillMaxSize()) { + val contentPadding = PaddingValues(start = 4.dp, end = 4.dp, top = 8.dp) + if (grid) { + LazyVerticalStaggeredGrid( + columns = StaggeredGridCells.Fixed(2), + state = state.grid, + contentPadding = contentPadding, + modifier = Modifier.fillMaxSize(), + ) { + itemsIndexed( + items, + key = { _, item -> item.key }, + span = { _, item -> + if (item is Header) StaggeredGridItemSpan.FullLine + else StaggeredGridItemSpan.SingleLane + }, + ) { _, item -> + NotesListItem( + item, + settings, + selectedIds, + keyword, + onClick, + onLongClick, + onReminderClick, + ) + } + } + } else { + LazyColumn( + state = state.list, + contentPadding = contentPadding, + modifier = Modifier.fillMaxSize(), + ) { + itemsIndexed(items, key = { _, item -> item.key }) { _, item -> + NotesListItem( + item, + settings, + selectedIds, + keyword, + onClick, + onLongClick, + onReminderClick, + ) + } + } + } + if (items.isEmpty()) { + when { + emptyIcon != null -> + Icon( + painterResource(emptyIcon), + contentDescription = null, + tint = MaterialTheme.colorScheme.primary, + modifier = Modifier.size(96.dp).align(Alignment.Center), + ) + emptyText != null -> + Text( + emptyText, + color = MaterialTheme.colorScheme.onSurface, + modifier = Modifier.align(Alignment.Center), + ) + } + } + } +} + +@Composable +private fun NotesListItem( + item: Item, + settings: CardSettings, + selectedIds: Set, + keyword: String, + onClick: (BaseNote) -> Unit, + onLongClick: ((BaseNote) -> Unit)?, + onReminderClick: ((BaseNote) -> Unit)?, +) { + when (item) { + is Header -> SectionHeader(item.label) + is BaseNote -> + NoteCard( + baseNote = item, + settings = settings, + selected = selectedIds.contains(item.id), + keyword = keyword, + onClick = { onClick(item) }, + onLongClick = onLongClick?.let { { it(item) } }, + onReminderClick = onReminderClick?.let { { it(item) } }, + ) + } +} + +@Composable +fun SectionHeader(label: String) { + Text( + text = label, + color = MaterialTheme.colorScheme.onSurface, + fontSize = 14.sp, + fontWeight = FontWeight.Medium, + modifier = Modifier.fillMaxWidth().padding(horizontal = 20.dp, vertical = 8.dp), + ) +} + +private val Item.key: Any + get() = + when (this) { + is BaseNote -> id + is Header -> "header:$label" + } + +/** Brings a note that was just added (e.g. created or restored) into view, like before. */ +@Composable +private fun ScrollToInsertedNote(items: List, grid: Boolean, state: NotesListState) { + val known = remember { HashSet() } + val initialized = remember { booleanArrayOf(false) } + LaunchedEffect(items) { + val ids = items.filterIsInstance().map { it.id } + val insertedIndex = + if (initialized[0] && known.isNotEmpty()) { + items.indexOfFirst { it is BaseNote && it.id !in known } + } else -1 + known.clear() + known.addAll(ids) + initialized[0] = true + if (insertedIndex >= 0) { + if (grid) state.grid.scrollToItem(insertedIndex) else state.list.scrollToItem(insertedIndex) + } + } +} diff --git a/app/src/main/java/com/philkes/notallyx/presentation/view/main/SelectionBar.kt b/app/src/main/java/com/philkes/notallyx/presentation/view/main/SelectionBar.kt new file mode 100644 index 0000000..cf6455d --- /dev/null +++ b/app/src/main/java/com/philkes/notallyx/presentation/view/main/SelectionBar.kt @@ -0,0 +1,162 @@ +package com.philkes.notallyx.presentation.view.main + +import androidx.compose.foundation.background +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.width +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.filled.MoreVert +import androidx.compose.material3.DropdownMenu +import androidx.compose.material3.DropdownMenuItem +import androidx.compose.material3.Icon +import androidx.compose.material3.IconButton +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.res.painterResource +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.unit.dp +import com.philkes.notallyx.R + +/** + * An action of the selection bar. [showAsIcon] actions are icon buttons labelled with their + * [title]; the others are in the overflow menu. Actions with [options] open a sub menu. + */ +class SelectionAction( + val title: String, + val icon: Int, + val showAsIcon: Boolean, + val options: List Unit>>? = null, + val onClick: () -> Unit = {}, +) + +/** Replaces the top bar while notes are selected: close, number of selected notes, actions. */ +@Composable +fun SelectionBar( + count: Int, + actions: List, + enabled: Boolean, + onClose: () -> Unit, + modifier: Modifier = Modifier, +) { + val colors = MaterialTheme.colorScheme + Row( + verticalAlignment = Alignment.CenterVertically, + modifier = modifier.fillMaxWidth().height(64.dp).background(colors.surface), + ) { + Spacer(Modifier.width(4.dp)) + IconButton(onClick = onClose) { + Icon( + painterResource(R.drawable.close), + contentDescription = stringResource(R.string.close), + tint = colors.onSurface, + ) + } + Text( + text = count.toString(), + style = MaterialTheme.typography.titleLarge, + color = colors.onSurface, + modifier = Modifier.padding(start = 12.dp).weight(1f), + ) + actions + .filter { it.showAsIcon } + .forEach { action -> ActionIconButton(action, enabled) } + val overflow = actions.filterNot { it.showAsIcon } + if (overflow.isNotEmpty()) { + OverflowMenu(overflow, enabled) + } + Spacer(Modifier.width(4.dp)) + } +} + +@Composable +private fun ActionIconButton(action: SelectionAction, enabled: Boolean) { + var expanded by remember { mutableStateOf(false) } + Box { + IconButton( + enabled = enabled, + onClick = { if (action.options != null) expanded = true else action.onClick() }, + ) { + Icon( + painterResource(action.icon), + contentDescription = action.title, + tint = MaterialTheme.colorScheme.onSurfaceVariant, + ) + } + val options = action.options + if (options != null) { + DropdownMenu(expanded = expanded, onDismissRequest = { expanded = false }) { + options.forEach { (title, onClick) -> + DropdownMenuItem( + text = { Text(title) }, + onClick = { + expanded = false + onClick() + }, + ) + } + } + } + } +} + +@Composable +private fun OverflowMenu(actions: List, enabled: Boolean) { + var expanded by remember { mutableStateOf(false) } + var subMenu by remember { mutableStateOf(null) } + Box { + IconButton(onClick = { expanded = true }) { + Icon( + Icons.Filled.MoreVert, + contentDescription = stringResource(R.string.more_options), + tint = MaterialTheme.colorScheme.onSurfaceVariant, + ) + } + DropdownMenu( + expanded = expanded, + onDismissRequest = { + expanded = false + subMenu = null + }, + ) { + val open = subMenu + if (open?.options != null) { + open.options.forEach { (title, onClick) -> + DropdownMenuItem( + text = { Text(title) }, + onClick = { + expanded = false + subMenu = null + onClick() + }, + ) + } + } else { + actions.forEach { action -> + DropdownMenuItem( + text = { Text(action.title) }, + enabled = enabled, + onClick = { + if (action.options != null) { + subMenu = action + } else { + expanded = false + action.onClick() + } + }, + ) + } + } + } + } +} diff --git a/app/src/main/java/com/philkes/notallyx/presentation/view/main/sorting/BaseNoteColorSort.kt b/app/src/main/java/com/philkes/notallyx/presentation/view/main/sorting/BaseNoteColorSort.kt deleted file mode 100644 index e52c344..0000000 --- a/app/src/main/java/com/philkes/notallyx/presentation/view/main/sorting/BaseNoteColorSort.kt +++ /dev/null @@ -1,17 +0,0 @@ -package com.philkes.notallyx.presentation.view.main.sorting - -import androidx.recyclerview.widget.RecyclerView -import com.philkes.notallyx.data.model.BaseNote -import com.philkes.notallyx.presentation.viewmodel.preference.SortDirection - -class BaseNoteColorSort(adapter: RecyclerView.Adapter<*>?, sortDirection: SortDirection) : - ItemSort(adapter, sortDirection) { - - override fun compare(note1: BaseNote, note2: BaseNote, sortDirection: SortDirection): Int { - val sort = - note1.compareColor(note2).takeIf { it != 0 } ?: return -note1.compareModified(note2) - return if (sortDirection == SortDirection.ASC) sort else -1 * sort - } -} - -fun BaseNote.compareColor(other: BaseNote) = color.compareTo(other.color) diff --git a/app/src/main/java/com/philkes/notallyx/presentation/view/main/sorting/BaseNoteCreationDateSort.kt b/app/src/main/java/com/philkes/notallyx/presentation/view/main/sorting/BaseNoteCreationDateSort.kt deleted file mode 100644 index 37ab71f..0000000 --- a/app/src/main/java/com/philkes/notallyx/presentation/view/main/sorting/BaseNoteCreationDateSort.kt +++ /dev/null @@ -1,16 +0,0 @@ -package com.philkes.notallyx.presentation.view.main.sorting - -import androidx.recyclerview.widget.RecyclerView -import com.philkes.notallyx.data.model.BaseNote -import com.philkes.notallyx.presentation.viewmodel.preference.SortDirection - -class BaseNoteCreationDateSort(adapter: RecyclerView.Adapter<*>?, sortDirection: SortDirection) : - ItemSort(adapter, sortDirection) { - - override fun compare(note1: BaseNote, note2: BaseNote, sortDirection: SortDirection): Int { - val sort = note1.compareCreated(note2) - return if (sortDirection == SortDirection.ASC) sort else -1 * sort - } -} - -fun BaseNote.compareCreated(other: BaseNote) = timestamp.compareTo(other.timestamp) diff --git a/app/src/main/java/com/philkes/notallyx/presentation/view/main/sorting/BaseNoteLastNotificationSort.kt b/app/src/main/java/com/philkes/notallyx/presentation/view/main/sorting/BaseNoteLastNotificationSort.kt deleted file mode 100644 index 34af99a..0000000 --- a/app/src/main/java/com/philkes/notallyx/presentation/view/main/sorting/BaseNoteLastNotificationSort.kt +++ /dev/null @@ -1,41 +0,0 @@ -package com.philkes.notallyx.presentation.view.main.sorting - -import androidx.recyclerview.widget.RecyclerView -import com.philkes.notallyx.data.model.BaseNote -import com.philkes.notallyx.data.model.findLastNotificationDate -import com.philkes.notallyx.presentation.viewmodel.preference.SortDirection - -class BaseNoteLastNotificationSort( - adapter: RecyclerView.Adapter<*>?, - sortDirection: SortDirection, -) : ItemSort(adapter, sortDirection) { - - override fun compare(note1: BaseNote, note2: BaseNote, sortDirection: SortDirection): Int { - val sort = note1.compareLastNotification(note2) - return if (sortDirection == SortDirection.ASC) sort else -1 * sort - } -} - -fun BaseNote.compareLastNotification(other: BaseNote): Int { - if (other.reminders.isEmpty() && reminders.isNotEmpty()) { - return 1 - } - if (other.reminders.isNotEmpty() && reminders.isEmpty()) { - return -1 - } - if (other.reminders.isEmpty() && reminders.isEmpty()) { - return 0 - } - val lastNotification = reminders.findLastNotificationDate() - val otherLastNotification = other.reminders.findLastNotificationDate() - if (lastNotification == null && otherLastNotification != null) { - return -1 - } - if (lastNotification != null && otherLastNotification == null) { - return 1 - } - if (lastNotification == null && otherLastNotification == null) { - return 0 - } - return lastNotification!!.compareTo(otherLastNotification!!) -} diff --git a/app/src/main/java/com/philkes/notallyx/presentation/view/main/sorting/BaseNoteModifiedDateSort.kt b/app/src/main/java/com/philkes/notallyx/presentation/view/main/sorting/BaseNoteModifiedDateSort.kt deleted file mode 100644 index ac12fc7..0000000 --- a/app/src/main/java/com/philkes/notallyx/presentation/view/main/sorting/BaseNoteModifiedDateSort.kt +++ /dev/null @@ -1,16 +0,0 @@ -package com.philkes.notallyx.presentation.view.main.sorting - -import androidx.recyclerview.widget.RecyclerView -import com.philkes.notallyx.data.model.BaseNote -import com.philkes.notallyx.presentation.viewmodel.preference.SortDirection - -class BaseNoteModifiedDateSort(adapter: RecyclerView.Adapter<*>?, sortDirection: SortDirection) : - ItemSort(adapter, sortDirection) { - - override fun compare(note1: BaseNote, note2: BaseNote, sortDirection: SortDirection): Int { - val sort = note1.compareModified(note2) - return if (sortDirection == SortDirection.ASC) sort else -1 * sort - } -} - -fun BaseNote.compareModified(other: BaseNote) = modifiedTimestamp.compareTo(other.modifiedTimestamp) diff --git a/app/src/main/java/com/philkes/notallyx/presentation/view/main/sorting/BaseNoteMostRecentNotificationSort.kt b/app/src/main/java/com/philkes/notallyx/presentation/view/main/sorting/BaseNoteMostRecentNotificationSort.kt deleted file mode 100644 index 461e6a0..0000000 --- a/app/src/main/java/com/philkes/notallyx/presentation/view/main/sorting/BaseNoteMostRecentNotificationSort.kt +++ /dev/null @@ -1,18 +0,0 @@ -package com.philkes.notallyx.presentation.view.main.sorting - -import androidx.recyclerview.widget.RecyclerView -import com.philkes.notallyx.data.model.BaseNote -import com.philkes.notallyx.presentation.viewmodel.preference.SortDirection - -class BaseNoteMostRecentNotificationSort( - adapter: RecyclerView.Adapter<*>?, - sortDirection: SortDirection, -) : ItemSort(adapter, sortDirection) { - - override fun compare(note1: BaseNote, note2: BaseNote, sortDirection: SortDirection): Int { - val sort = - note1.compareNextNotification(note2).takeIf { it != 0 } - ?: note1.compareLastNotification(note2) - return if (sortDirection == SortDirection.ASC) sort else -1 * sort - } -} diff --git a/app/src/main/java/com/philkes/notallyx/presentation/view/main/sorting/BaseNoteNextNotificationSort.kt b/app/src/main/java/com/philkes/notallyx/presentation/view/main/sorting/BaseNoteNextNotificationSort.kt deleted file mode 100644 index dd931e5..0000000 --- a/app/src/main/java/com/philkes/notallyx/presentation/view/main/sorting/BaseNoteNextNotificationSort.kt +++ /dev/null @@ -1,41 +0,0 @@ -package com.philkes.notallyx.presentation.view.main.sorting - -import androidx.recyclerview.widget.RecyclerView -import com.philkes.notallyx.data.model.BaseNote -import com.philkes.notallyx.data.model.findNextNotificationDate -import com.philkes.notallyx.presentation.viewmodel.preference.SortDirection - -class BaseNoteNextNotificationSort( - adapter: RecyclerView.Adapter<*>?, - sortDirection: SortDirection, -) : ItemSort(adapter, sortDirection) { - - override fun compare(note1: BaseNote, note2: BaseNote, sortDirection: SortDirection): Int { - val sort = note1.compareNextNotification(note2) - return if (sortDirection == SortDirection.ASC) sort else -1 * sort - } -} - -fun BaseNote.compareNextNotification(other: BaseNote): Int { - if (other.reminders.isEmpty() && reminders.isNotEmpty()) { - return 1 - } - if (other.reminders.isNotEmpty() && reminders.isEmpty()) { - return -1 - } - if (other.reminders.isEmpty() && reminders.isEmpty()) { - return 0 - } - val nextNotification = reminders.findNextNotificationDate() - val otherNextNotification = other.reminders.findNextNotificationDate() - if (nextNotification == null && otherNextNotification != null) { - return -1 - } - if (nextNotification != null && otherNextNotification == null) { - return 1 - } - if (nextNotification == null && otherNextNotification == null) { - return 0 - } - return nextNotification!!.compareTo(otherNextNotification!!) -} diff --git a/app/src/main/java/com/philkes/notallyx/presentation/view/main/sorting/BaseNoteTitleSort.kt b/app/src/main/java/com/philkes/notallyx/presentation/view/main/sorting/BaseNoteTitleSort.kt deleted file mode 100644 index b42b905..0000000 --- a/app/src/main/java/com/philkes/notallyx/presentation/view/main/sorting/BaseNoteTitleSort.kt +++ /dev/null @@ -1,16 +0,0 @@ -package com.philkes.notallyx.presentation.view.main.sorting - -import androidx.recyclerview.widget.RecyclerView -import com.philkes.notallyx.data.model.BaseNote -import com.philkes.notallyx.presentation.viewmodel.preference.SortDirection - -class BaseNoteTitleSort(adapter: RecyclerView.Adapter<*>?, sortDirection: SortDirection) : - ItemSort(adapter, sortDirection) { - - override fun compare(note1: BaseNote, note2: BaseNote, sortDirection: SortDirection): Int { - val sort = note1.compareTitle(note2) - return if (sortDirection == SortDirection.ASC) sort else -1 * sort - } -} - -fun BaseNote.compareTitle(other: BaseNote) = title.compareTo(other.title) diff --git a/app/src/main/java/com/philkes/notallyx/presentation/view/main/sorting/ItemSort.kt b/app/src/main/java/com/philkes/notallyx/presentation/view/main/sorting/ItemSort.kt deleted file mode 100644 index f5d5682..0000000 --- a/app/src/main/java/com/philkes/notallyx/presentation/view/main/sorting/ItemSort.kt +++ /dev/null @@ -1,43 +0,0 @@ -package com.philkes.notallyx.presentation.view.main.sorting - -import androidx.recyclerview.widget.RecyclerView -import androidx.recyclerview.widget.SortedListAdapterCallback -import com.philkes.notallyx.data.model.BaseNote -import com.philkes.notallyx.data.model.Header -import com.philkes.notallyx.data.model.Item -import com.philkes.notallyx.presentation.viewmodel.preference.SortDirection - -abstract class ItemSort( - adapter: RecyclerView.Adapter<*>?, - private val sortDirection: SortDirection, -) : SortedListAdapterCallback(adapter) { - - abstract fun compare(note1: BaseNote, note2: BaseNote, sortDirection: SortDirection): Int - - override fun compare(item1: Item?, item2: Item?): Int { - return when { - item1 == null && item2 == null -> 0 - item1 == null && item2 != null -> -1 - item1 != null && item2 == null -> 1 - item1 is BaseNote && item2 is BaseNote -> { - val pinnedCompare = item1.pinned.compareTo(item2.pinned) * -1 - return if (pinnedCompare != 0) pinnedCompare - else compare(item1, item2, sortDirection) - } - item1 is Header && item2 is Header -> 0 - else -> 0 - } - } - - override fun areContentsTheSame(oldItem: Item?, newItem: Item?): Boolean { - return oldItem == newItem - } - - override fun areItemsTheSame(item1: Item?, item2: Item?): Boolean { - return when { - item1 is BaseNote && item2 is BaseNote -> item1.id == item2.id - item1 is Header && item2 is Header -> item1 == item2 - else -> false - } - } -} diff --git a/app/src/main/java/com/philkes/notallyx/presentation/view/misc/highlightableview/HighlightableTextView.kt b/app/src/main/java/com/philkes/notallyx/presentation/view/misc/highlightableview/HighlightableTextView.kt index 097623c..701e004 100644 --- a/app/src/main/java/com/philkes/notallyx/presentation/view/misc/highlightableview/HighlightableTextView.kt +++ b/app/src/main/java/com/philkes/notallyx/presentation/view/misc/highlightableview/HighlightableTextView.kt @@ -55,26 +55,8 @@ class HighlightableTextView(context: Context, attrs: AttributeSet?) : maxLines = Int.MAX_VALUE } - /** - * Extract a snippet around given keyword that has given lines around the keyword. - * - * @return Snippet's text, keyword idx in the Snippet, whether or not the snippet includes the - * first line of the text. - */ - fun extractSearchSnippet(text: String, keyword: String): Snippet? { - val keywordIndex = text.indexOf(keyword, ignoreCase = true) - if (keywordIndex == -1) { - return null - } - if (text.length <= (2 * SEARCH_SNIPPET_SIZE) + keyword.length) { - return Snippet(text, keyword, text.indexOf(keyword, ignoreCase = true), true, true) - } - val start = (keywordIndex - SEARCH_SNIPPET_SIZE).coerceAtLeast(0) - val end = (keywordIndex + keyword.length + SEARCH_SNIPPET_SIZE).coerceAtMost(text.lastIndex) - val snippetText = text.substring(start, end + 1) - val keywordIdxInSnippet = snippetText.indexOf(keyword, ignoreCase = true) - return Snippet(snippetText, keyword, keywordIdxInSnippet, start == 0, end == text.lastIndex) - } + /** See [searchSnippet]. */ + fun extractSearchSnippet(text: String, keyword: String): Snippet? = searchSnippet(text, keyword) fun TextView.ellipsizeMultilineTextToFit(text: String): String { val paint = paint @@ -99,3 +81,37 @@ data class Snippet( val includesFirstLine: Boolean, val includesLastLine: Boolean, ) + +/** + * Extract a snippet around given keyword that has given lines around the keyword. + * + * @return Snippet's text, keyword idx in the Snippet, whether or not the snippet includes the first + * line of the text. + */ +fun searchSnippet(text: String, keyword: String): Snippet? { + val keywordIndex = text.indexOf(keyword, ignoreCase = true) + if (keywordIndex == -1) { + return null + } + if (text.length <= (2 * SEARCH_SNIPPET_SIZE) + keyword.length) { + return Snippet(text, keyword, text.indexOf(keyword, ignoreCase = true), true, true) + } + val start = (keywordIndex - SEARCH_SNIPPET_SIZE).coerceAtLeast(0) + val end = (keywordIndex + keyword.length + SEARCH_SNIPPET_SIZE).coerceAtMost(text.lastIndex) + val snippetText = text.substring(start, end + 1) + val keywordIdxInSnippet = snippetText.indexOf(keyword, ignoreCase = true) + return Snippet(snippetText, keyword, keywordIdxInSnippet, start == 0, end == text.lastIndex) +} + +/** Text shown for a [Snippet]: ellipses where text was cut off, and where the keyword starts. */ +val Snippet.displayText: Pair + get() { + val displayedText = buildString { + if (!includesFirstLine) append(ELLIPSED_TEXT) + append(text) + if (!includesLastLine) append(ELLIPSED_TEXT) + } + val displayKeywordIdx = + if (!includesFirstLine) keywordIdx + ELLIPSED_TEXT.length else keywordIdx + return Pair(displayedText, displayKeywordIdx) + } diff --git a/app/src/main/java/com/philkes/notallyx/presentation/viewmodel/BaseNoteModel.kt b/app/src/main/java/com/philkes/notallyx/presentation/viewmodel/BaseNoteModel.kt index c987f1a..7057164 100644 --- a/app/src/main/java/com/philkes/notallyx/presentation/viewmodel/BaseNoteModel.kt +++ b/app/src/main/java/com/philkes/notallyx/presentation/viewmodel/BaseNoteModel.kt @@ -14,6 +14,7 @@ import androidx.lifecycle.AndroidViewModel import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.Observer +import androidx.lifecycle.SavedStateHandle import androidx.lifecycle.map import androidx.lifecycle.viewModelScope import com.google.android.material.dialog.MaterialAlertDialogBuilder @@ -82,7 +83,8 @@ import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import kotlinx.coroutines.withContext -class BaseNoteModel(private val app: Application) : AndroidViewModel(app) { +class BaseNoteModel(private val app: Application, private val savedState: SavedStateHandle) : + AndroidViewModel(app) { private lateinit var database: NotallyDatabase private lateinit var labelDao: LabelDao @@ -105,11 +107,12 @@ class BaseNoteModel(private val app: Application) : AndroidViewModel(app) { var currentLabel: String? = CURRENT_LABEL_EMPTY - var keyword = String() + var keyword: String = savedState[KEY_KEYWORD] ?: "" set(value) { if (field != value || searchResults?.value?.isEmpty() == true) { field = value - searchResults!!.fetch(keyword, folder.value, currentLabel) + savedState[KEY_KEYWORD] = value + searchResults?.fetch(keyword, folder.value, currentLabel) } } @@ -127,7 +130,14 @@ class BaseNoteModel(private val app: Application) : AndroidViewModel(app) { val importProgress = MutableLiveData() val progress = MutableLiveData() - val actionMode = ActionMode() + val actionMode = + ActionMode().apply { + onSelectionChanged = { ids -> savedState[KEY_SELECTED_IDS] = ids.toLongArray() } + } + + /** Notes that were selected when Android stopped the app, selected again once listed. */ + private var selectionToRestore: Set? = + savedState.get(KEY_SELECTED_IDS)?.toSet()?.takeIf { it.isNotEmpty() } internal var showRefreshBackupsFolderAfterThemeChange = false private var labelsHiddenObserver: Observer>? = null @@ -135,7 +145,28 @@ class BaseNoteModel(private val app: Application) : AndroidViewModel(app) { fun startObserving() { NotallyDatabase.getDatabase(app).observeForever(::init) folder.observeForever { newFolder -> - searchResults!!.fetch(keyword, newFolder, currentLabel) + searchResults?.fetch(keyword, newFolder, currentLabel) + } + } + + /** Fetches the search results again for the current keyword, folder and label. */ + fun refreshSearch() { + searchResults?.fetch(keyword, folder.value, currentLabel) + } + + /** + * Restores the selection that was saved before the app was stopped, once the notes it refers to + * are listed. + */ + fun restoreSelection(listedNotes: Collection) { + val ids = selectionToRestore ?: return + if (listedNotes.isEmpty()) { + return + } + selectionToRestore = null + val notes = listedNotes.filter { ids.contains(it.id) } + if (notes.isNotEmpty() && actionMode.isEmpty()) { + actionMode.add(notes) } } @@ -798,6 +829,8 @@ class BaseNoteModel(private val app: Application) : AndroidViewModel(app) { private const val TAG = "BaseNoteModel" const val CURRENT_LABEL_EMPTY = "" + private const val KEY_KEYWORD = "notallyx.overview.KEYWORD" + private const val KEY_SELECTED_IDS = "notallyx.overview.SELECTED_IDS" val CURRENT_LABEL_NONE: String? = null fun transform( diff --git a/app/src/main/java/com/philkes/notallyx/utils/ActionMode.kt b/app/src/main/java/com/philkes/notallyx/utils/ActionMode.kt index d8d8714..c075981 100644 --- a/app/src/main/java/com/philkes/notallyx/utils/ActionMode.kt +++ b/app/src/main/java/com/philkes/notallyx/utils/ActionMode.kt @@ -9,25 +9,35 @@ class ActionMode { val enabled = NotNullLiveData(false) val loading = NotNullLiveData(false) val count = NotNullLiveData(0) - val selectedNotes = HashMap() + val selectedNotes = LinkedHashMap() val selectedIds = selectedNotes.keys + /** The selected notes, updated whenever the selection changes. */ + val selection = NotNullLiveData>(emptyList()) val closeListener = MutableLiveData>>() - var addListener: (() -> Unit)? = null + + /** Last note added to the selection, where a range selection starts. */ + var anchorId: Long? = null + private set + + /** Called with the selected ids after every change, e.g. to keep them in saved state. */ + var onSelectionChanged: ((Set) -> Unit)? = null private fun refresh() { count.value = selectedNotes.size enabled.value = selectedNotes.size != 0 + selection.value = selectedNotes.values.toList() + onSelectionChanged?.invoke(HashSet(selectedIds)) } fun add(id: Long, baseNote: BaseNote) { selectedNotes[id] = baseNote + anchorId = id refresh() } fun add(baseNotes: Collection) { baseNotes.forEach { selectedNotes[it.id] = it } refresh() - addListener?.invoke() } fun remove(id: Long) { diff --git a/app/src/main/res/layout/activity_main.xml b/app/src/main/res/layout/activity_main.xml index df8aaed..05edec5 100644 --- a/app/src/main/res/layout/activity_main.xml +++ b/app/src/main/res/layout/activity_main.xml @@ -22,14 +22,12 @@ - + android:visibility="gone" /> - - - + android:layout_below="@id/Toolbar" /> \ No newline at end of file diff --git a/app/src/main/res/layout/recycler_base_note.xml b/app/src/main/res/layout/recycler_base_note.xml deleted file mode 100644 index 01a9ea1..0000000 --- a/app/src/main/res/layout/recycler_base_note.xml +++ /dev/null @@ -1,272 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/app/src/main/res/layout/recycler_header.xml b/app/src/main/res/layout/recycler_header.xml deleted file mode 100644 index da68d66..0000000 --- a/app/src/main/res/layout/recycler_header.xml +++ /dev/null @@ -1,9 +0,0 @@ - - \ No newline at end of file diff --git a/app/src/main/res/values/ids.xml b/app/src/main/res/values/ids.xml new file mode 100644 index 0000000..045e86c --- /dev/null +++ b/app/src/main/res/values/ids.xml @@ -0,0 +1,4 @@ + + + + diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index 8d8d258..3d4ff56 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -92,6 +92,7 @@ All Notes, Images, Files, Audios will be permanently deleted Clear formatting All Data has been cleared + Close Color This color already exists! Content density @@ -275,6 +276,7 @@ Monthly Months %1$d more + More options …%1$d more file …%1$d more files